test_ita_shared_lifecycle.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. """W1: exercise the shared implementations, mocking only external boundaries."""
  2. from contextlib import ExitStack
  3. from datetime import date
  4. from pathlib import Path
  5. from tempfile import TemporaryDirectory
  6. from types import SimpleNamespace
  7. import unittest
  8. from unittest.mock import Mock, patch
  9. from plugins import ita_plugin as ita
  10. from test.ita.ita_test_fakes import FakeChromiumOptions, FakeKeyboard, FakeMouse, FakePage
  11. from utils import plugin_utils as shared
  12. from vs_types import VSAccount, VSPlgConfig
  13. class SharedInitializationTests(unittest.TestCase):
  14. def test_real_shared_options_cover_direct_and_authenticated_proxy(self):
  15. for proxy in (None, SimpleNamespace(ip="proxy.test", port=8080, proto="http", username="", password=""),
  16. SimpleNamespace(ip="proxy.test", port=8080, proto="http", username="fixture", password="synthetic")):
  17. with self.subTest(authenticated=bool(proxy and proxy.username)), ExitStack() as stack:
  18. options, tunnel = Mock(), Mock()
  19. tunnel.start.return_value = "http://127.0.0.1:9901"
  20. stack.enter_context(patch.object(shared, "ChromiumOptions", return_value=options))
  21. stack.enter_context(patch.object(shared, "get_free_port", return_value=9900))
  22. factory = stack.enter_context(patch.object(shared, "MihomoTunnel", return_value=tunnel))
  23. fp = stack.enter_context(patch.object(shared, "FingerprintGenerator"))
  24. fp.return_value.generate.return_value = {"seed": 9, "platform": "macos", "brand": "Chrome"}
  25. stack.enter_context(patch.object(shared.configure, "CHROME_PATH", "/fixture/chrome"))
  26. stack.enter_context(patch.object(shared.configure, "MIHOMO_BIN_PATH", "/fixture/mihomo"))
  27. stack.enter_context(patch.object(shared.configure, "MIHOMO_RELAY_NODES", None))
  28. stack.enter_context(patch.object(shared.os.path, "exists", return_value=True))
  29. actual_options, actual_tunnel = shared.init_chromium_options(
  30. "/fixture/profile", username_seed="fixture@example.test", proxy=proxy)
  31. self.assertIs(actual_options, options)
  32. options.set_local_port.assert_called_once_with(9900)
  33. options.set_user_data_path.assert_called_once_with("/fixture/profile")
  34. options.set_paths.assert_called_once_with(browser_path="/fixture/chrome")
  35. options.headless.assert_called_once_with(False)
  36. options.set_argument.assert_any_call("--window-size=1920,1080")
  37. fp.return_value.generate.assert_called_once_with("fixture@example.test")
  38. if proxy and proxy.username:
  39. self.assertIs(actual_tunnel, tunnel)
  40. factory.assert_called_once()
  41. options.set_argument.assert_any_call("--proxy-server=http://127.0.0.1:9901")
  42. else:
  43. self.assertIsNone(actual_tunnel)
  44. factory.assert_not_called()
  45. if proxy:
  46. options.set_argument.assert_any_call("--proxy-server=http://proxy.test:8080")
  47. def test_italy_calls_real_shared_initializer_and_creates_only_one_page(self):
  48. page = FakePage()
  49. with TemporaryDirectory() as workspace, ExitStack() as stack:
  50. stack.enter_context(patch.object(ita.os.path, "abspath", return_value=workspace))
  51. plugin = ita.ItaPlugin("offline-shared-init")
  52. plugin.set_log(Mock())
  53. plugin.set_config(VSPlgConfig(account=VSAccount(username="fixture@example.test", password="synthetic")))
  54. stack.enter_context(patch.object(shared, "ChromiumOptions", FakeChromiumOptions))
  55. stack.enter_context(patch.object(shared, "get_free_port", return_value=9900))
  56. initialize = stack.enter_context(patch.object(ita, "init_chromium_options", wraps=shared.init_chromium_options))
  57. create = stack.enter_context(patch.object(ita, "ChromiumPage", return_value=page))
  58. stack.enter_context(patch.object(ita, "HumanMouse", FakeMouse))
  59. stack.enter_context(patch.object(ita, "HumanKeyboard", FakeKeyboard))
  60. stack.enter_context(patch.object(ita.time, "sleep"))
  61. try:
  62. plugin.create_session()
  63. self.assertTrue(plugin.is_healthy)
  64. initialize.assert_called_once_with(
  65. user_data_path=plugin.user_data_path, username_seed=plugin.config.account.username,
  66. proxy=plugin.config.proxy, headless=False, window_size="1920,1080", logger=plugin._log)
  67. create.assert_called_once()
  68. self.assertEqual(page.clicked.count("submit"), 1)
  69. finally:
  70. plugin.cleanup()
  71. class SharedCleanupTests(unittest.TestCase):
  72. def test_legacy_positional_call_still_swallows_failures_and_cleans_other_resources(self):
  73. # Exact positional signature used by VFS/TLS; no opt-in behavior change.
  74. with TemporaryDirectory() as parent:
  75. root = Path(parent) / "workspace"
  76. root.mkdir()
  77. page, tunnel = Mock(), Mock()
  78. page.quit.side_effect = RuntimeError("synthetic")
  79. tunnel.stop.side_effect = RuntimeError("synthetic")
  80. with patch.object(shared.time, "sleep"):
  81. self.assertIsNone(shared.cleanup_browser_workspace(page, str(root), tunnel, Mock()))
  82. page.quit.assert_called_once_with(force=True)
  83. tunnel.stop.assert_called_once()
  84. self.assertFalse(root.exists())
  85. def test_italy_cleanup_uses_the_unchanged_shared_contract(self):
  86. with TemporaryDirectory() as parent, ExitStack() as stack:
  87. root = Path(parent) / "workspace"
  88. root.mkdir()
  89. plugin = ita.ItaPlugin.__new__(ita.ItaPlugin)
  90. plugin.page, plugin.tunnel = Mock(), Mock()
  91. page, tunnel = plugin.page, plugin.tunnel
  92. plugin.root_workspace = str(root)
  93. plugin.is_healthy = True
  94. plugin._prepared_calendar = object()
  95. plugin._log = Mock()
  96. cleanup = stack.enter_context(patch.object(
  97. ita, "cleanup_browser_workspace", wraps=shared.cleanup_browser_workspace,
  98. ))
  99. stack.enter_context(patch.object(shared.time, "sleep"))
  100. plugin.cleanup()
  101. cleanup.assert_called_once_with(page, str(root), tunnel, plugin._log)
  102. self.assertFalse(root.exists())
  103. self.assertFalse(plugin.is_healthy)
  104. class SharedDateTests(unittest.TestCase):
  105. def test_positive_days_use_shared_filter_without_shuffle_or_missing_bound(self):
  106. days = tuple(ita.CalendarDay(date(2026, 10, n), 1, 0) for n in (20, 13, 9))
  107. for bounds, expected in (({}, (9, 13, 20)), ({"start_day": date(2026, 10, 13)}, (13, 20)),
  108. ({"end_day": date(2026, 10, 13)}, (9, 13))):
  109. with self.subTest(bounds=bounds), patch.object(ita, "filter_dates_in_range", wraps=shared.filter_dates_in_range) as select:
  110. actual = ita.available_calendar_days(days, **bounds)
  111. self.assertEqual(tuple(d.day.day for d in actual), expected)
  112. select.assert_called_once()
  113. self.assertIs(select.call_args.kwargs["shuffle"], False)
  114. self.assertTrue(select.call_args.args[1])
  115. self.assertTrue(select.call_args.args[2])
  116. if __name__ == "__main__":
  117. unittest.main()