| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255 |
- """Offline checks for the Italy profile consumed by the existing public tester."""
- import copy
- from contextlib import redirect_stdout
- import io
- import json
- import logging
- from pathlib import Path
- import shlex
- from types import SimpleNamespace
- import unittest
- from unittest.mock import Mock, patch
- from plugins.ita_protocol import ItaCapability, resolve_route_config
- from sentinel import SentinelGCO
- from tools.plugin_tester import PluginTester
- from vs_types import GroupConfig
- def hong_kong_group():
- groups = json.loads((Path(__file__).resolve().parents[1] / "config/config_sentinel.json").read_text())
- matches = [group for group in groups if group["identifier"] == "ita.hong_kong"]
- if len(matches) != 1:
- raise AssertionError("Expected exactly one Hong Kong Sentinel profile")
- return GroupConfig.from_json(matches[0])
- class ItalyPublicTesterConfigTests(unittest.TestCase):
- def setUp(self):
- # Exercise the actual JSON loader and registration, never create a plugin,
- # open a browser, or use the configured credentials in an assertion.
- with patch("vs_plg_factory.VSC_INFO"), patch(
- "tools.plugin_tester.VSPlgFactory.create",
- side_effect=AssertionError("Offline configuration check must not create a plugin"),
- ):
- self.tester = PluginTester.from_json_config(
- "ita_plugin",
- str(Path(__file__).resolve().parents[1] / "config/test_conf.json"),
- user_override="query@example.test",
- password_override="synthetic-not-a-secret",
- proxy_override="http://127.0.0.1:9999",
- )
- def test_existing_loader_resolves_one_hong_kong_appointment(self):
- self.assertIsNone(self.tester.plugin)
- self.assertEqual(self.tester.group_id, "ita.hong_kong")
- self.assertEqual(len(self.tester.appointment_types), 1)
- appointment = self.tester.appointment_types[0]
- self.assertEqual(appointment.routing_key, "slot.hkg.it.tourist")
- self.assertEqual(appointment.city, "Hong Kong")
- self.assertEqual(appointment.country, "Italy")
- self.assertEqual(appointment.visa_type, "Tourist")
- def test_query_profile_uses_cloud_preparation_and_disables_final_submission(self):
- config = self.tester.config
- self.assertIs(config.debug, False)
- self.assertEqual(config.free_config["query_mode"], "calendar")
- self.assertEqual(config.free_config["otp_mode"], "cloud")
- self.assertIs(config.free_config["final_submit_enabled"], False)
- def test_existing_protocol_parser_accepts_evidenced_form_and_scan_settings(self):
- route = resolve_route_config(
- self.tester.config.free_config["apt_configs"],
- self.tester.appointment_types[0].routing_key,
- )
- self.assertEqual(route.service_id, 4937)
- self.assertIs(route.capability, ItaCapability.SINGLE_SCHENGEN_TOURISM)
- self.assertEqual(route.calendar_scan.lookahead_months, 12)
- self.assertEqual(route.booking_type.control_id, "typeofbookingddl")
- self.assertEqual(route.booking_type.value, "1")
- self.assertEqual(route.booking_type.labels, ("Prenotazione Singola", "Single booking"))
- self.assertEqual(route.purpose.control_id, "ddls_0")
- self.assertEqual(route.purpose.value, "42")
- self.assertEqual(route.purpose.labels, ("Turismo", "Tourism"))
- self.assertIsNotNone(route.mail)
- self.assertEqual(route.mail.authorization_source, "account")
- self.assertIsNone(route.mail.authorization_email)
- self.assertEqual(route.mail.mailbox_for("query@example.test"), "query@example.test")
- def test_public_tester_and_sentinel_share_route_and_otp_contract(self):
- group = hong_kong_group()
- config = self.tester.config.free_config
- self.assertEqual(group.appointment_types, self.tester.appointment_types)
- for key in ("website", "query_mode", "otp_mode", "final_submit_enabled", "apt_configs"):
- self.assertEqual(group.free_config[key], config[key])
- class ItalySingleAccountPoolConfigTests(unittest.TestCase):
- def setUp(self):
- self.group = hong_kong_group()
- # Do not create browsers, read account secrets or call a live backend.
- for target in ("socket.socket.connect", "socket.socket.connect_ex", "socket.create_connection",
- "requests.sessions.Session.request", "subprocess.Popen"):
- self.enterContext(patch(target, side_effect=AssertionError("Offline test attempted external I/O")))
- self.cloud = Mock()
- self.cloud.get_next_account.return_value = {
- "id": 71, "pool_name": "hkg.it.sentinel", "username": "pooled@example.test",
- "password": "synthetic-pool-password", "status": "active",
- }
- self.cloud.get_next_proxy.return_value = {"id": 72, "ip": "127.0.0.1", "port": 9999}
- self.redis = Mock()
- self.enterContext(patch.dict(SentinelGCO.__init__.__globals__, {
- "SafeRedisClient": Mock(return_value=self.redis),
- "VSCloudApi": SimpleNamespace(Instance=lambda: self.cloud),
- }))
- self.sentinel = SentinelGCO(self.group, {}, Mock())
- self.plugin = Mock()
- self.sentinel.m_factory.create = Mock(return_value=self.plugin)
- self.addCleanup(self.sentinel.stop)
- def test_profile_is_disabled_single_instance_cloud_query_without_local_credentials(self):
- group = self.group
- self.assertFalse(group.enable)
- self.assertFalse(group.debug)
- self.assertTrue(group.need_account)
- self.assertEqual(group.sentinel.account_source, "built-in")
- self.assertEqual(group.sentinel.account_pool_id, "hkg.it.sentinel")
- self.assertEqual(group.sentinel.target_instances, 1)
- self.assertEqual(group.sentinel.account_cd, group.session_max_life)
- self.assertEqual(group.sentinel.account_cd, 1800)
- self.assertEqual(group.free_config["otp_mode"], "cloud")
- self.assertIs(group.free_config["final_submit_enabled"], False)
- for key in ("account", "password", "local_account_file", "authorization_code"):
- self.assertNotIn(key, group.free_config)
- self.sentinel.start()
- self.sentinel.m_factory.create.assert_not_called()
- self.cloud.get_next_account.assert_not_called()
- def test_existing_sentinel_spawner_binds_pool_account_and_mail_configuration(self):
- before = copy.deepcopy(self.group)
- self.sentinel._spawn_sentinel_worker()
- self.cloud.get_next_account.assert_called_once_with("hkg.it.sentinel", 1800)
- self.cloud.get_next_proxy.assert_called_once_with(self.group.proxy_pool, self.group.proxy_cd)
- self.plugin.set_config.assert_called_once()
- config = self.plugin.set_config.call_args.args[0]
- self.assertEqual(config.account.id, 71)
- self.assertEqual(config.account.username, "pooled@example.test")
- self.assertEqual(config.account.password, "synthetic-pool-password")
- self.assertEqual(config.free_config, self.group.free_config)
- self.assertEqual(self.group, before)
- self.plugin.create_session.assert_called_once()
- self.assertEqual(len(self.sentinel.m_tasks), 1)
- self.assertFalse(self.sentinel.m_tasks[0].book_allowed)
- self.plugin.book.assert_not_called()
- self.redis.setex.assert_not_called()
- def test_empty_or_cooling_pool_does_not_fall_back_to_a_local_account(self):
- self.cloud.get_next_account.side_effect = RuntimeError("synthetic unavailable pool")
- self.sentinel._spawn_sentinel_worker()
- self.cloud.get_next_account.assert_called_once_with("hkg.it.sentinel", 1800)
- self.sentinel.m_factory.create.assert_not_called()
- self.plugin.create_session.assert_not_called()
- self.assertEqual(self.sentinel.m_tasks, [])
- class ItalyDocumentedPoolCommandTests(unittest.TestCase):
- def setUp(self):
- for target in ("socket.socket.connect", "socket.socket.connect_ex", "socket.create_connection",
- "requests.sessions.Session.request", "subprocess.Popen"):
- self.enterContext(patch(target, side_effect=AssertionError("Offline test attempted external I/O")))
- logger = logging.Logger("ita-pool-command-offline", level=logging.INFO)
- self.enterContext(patch("vs_log_macros._active_logger", logger))
- self.enterContext(patch("configure.TEST_ACCOUNT", None))
- self.cloud = Mock()
- self.cloud.get_next_account.return_value = {
- "id": 71, "username": "first-pool-account@example.test",
- "password": "synthetic-command-password", "pool_name": "hkg.it.sentinel", "status": "active",
- }
- self.enterContext(patch("toolkit.vs_cloud_api.VSCloudApi.Instance", return_value=self.cloud))
- self.pipeline = self.enterContext(patch.object(PluginTester, "run_pipeline", autospec=True, return_value=True))
- self.enterContext(patch("utils.local_account.load_local_account",
- side_effect=AssertionError("Pool test must not load a local account")))
- def run_documented_command(self):
- path = Path(__file__).resolve().parents[1] / "docs/ita_query_book_acceptance.md"
- section = path.read_text().split("<!-- ITA_POOL_QUERY_COMMAND -->", 1)[1].split("<!-- /ITA_POOL_QUERY_COMMAND -->", 1)[0]
- shell = section.split("```bash", 1)[1].split("```", 1)[0]
- tokens = shlex.split(shell)
- code = tokens[tokens.index("-c") + 1]
- output = io.StringIO()
- with redirect_stdout(output), self.assertRaises(SystemExit) as result:
- exec(compile(code, str(path) + ":pool-query-command", "exec"), {"__name__": "__main__"})
- return result.exception.code, output.getvalue()
- def test_exact_documented_command_uses_existing_sdk_and_public_tester_query_only(self):
- code, output = self.run_documented_command()
- self.assertEqual(code, 0)
- self.cloud.get_next_account.assert_called_once_with("hkg.it.sentinel", 1800)
- self.pipeline.assert_called_once()
- self.assertEqual(self.pipeline.call_args.kwargs, {"test_book": False})
- tester = self.pipeline.call_args.args[0]
- self.assertEqual(tester.config.account.id, 71)
- self.assertEqual(tester.config.account.password, "synthetic-command-password")
- self.assertEqual(tester.config.free_config, hong_kong_group().free_config)
- self.assertEqual(tester.config.proxy.port, 6268)
- self.assertIsNone(tester.plugin)
- self.assertIn("ITA_POOL_QUERY_SOURCE=cloud_pool pool=hkg.it.sentinel book=false", output)
- self.assertNotIn("synthetic-command-password", output)
- self.assertIn("ITA_POOL_QUERY_CONTRACT=account-mailbox-v2", output)
- def test_second_pool_account_is_accepted_and_resolves_its_own_mailbox(self):
- for address in ("first-pool-account@example.test", "second-pool-account@example.test"):
- with self.subTest(address=address):
- self.pipeline.reset_mock()
- self.cloud.get_next_account.return_value["username"] = address
- code, _ = self.run_documented_command()
- self.assertEqual(code, 0)
- tester = self.pipeline.call_args.args[0]
- route = resolve_route_config(tester.config.free_config["apt_configs"],
- tester.appointment_types[0].routing_key)
- self.assertEqual(route.mail.mailbox_for(tester.config.account.username), address)
- self.assertIsNone(route.mail.authorization_email)
- def test_debug_payload_logging_stops_before_account_allocation(self):
- with patch("vs_log_macros._active_logger", logging.Logger("unsafe-fixture", level=logging.DEBUG)):
- with self.assertRaisesRegex(Exception, "DEBUG"):
- self.run_documented_command()
- self.cloud.get_next_account.assert_not_called()
- self.pipeline.assert_not_called()
- def test_test_account_override_stops_before_pool_allocation(self):
- with patch("configure.TEST_ACCOUNT", {"username": "fixture@example.test"}):
- code, _ = self.run_documented_command()
- self.assertIn("TEST_ACCOUNT", code)
- self.cloud.get_next_account.assert_not_called()
- self.pipeline.assert_not_called()
- def test_pool_failure_does_not_fall_back_or_print_backend_error_body(self):
- self.cloud.get_next_account.side_effect = RuntimeError("synthetic-sensitive-response")
- code, output = self.run_documented_command()
- self.assertEqual(code, 1)
- self.assertIn("ITA_POOL_QUERY_ACCOUNT_FAILED type=RuntimeError", output)
- self.assertNotIn("synthetic-sensitive-response", output)
- self.pipeline.assert_not_called()
- def test_wrong_pool_empty_password_or_disabled_account_stops_before_browser(self):
- original = self.cloud.get_next_account.return_value.copy()
- for field, value in (("pool_name", "other.pool"), ("password", ""), ("status", "disable")):
- with self.subTest(field=field):
- self.cloud.get_next_account.return_value = {**original, field: value}
- code, _ = self.run_documented_command()
- self.assertIsInstance(code, str)
- self.assertIn("Stop:", code)
- self.pipeline.assert_not_called()
- def test_invalid_account_email_stops_before_browser(self):
- self.cloud.get_next_account.return_value["username"] = "not-an-email"
- code, output = self.run_documented_command()
- self.assertEqual(code, 1)
- self.assertIn("ITA_POOL_QUERY_MAIL_CONFIG_FAILED", output)
- self.pipeline.assert_not_called()
- if __name__ == "__main__":
- unittest.main()
|