test_desktop.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. from pathlib import Path
  2. from types import SimpleNamespace
  3. from unittest.mock import Mock
  4. import pytest
  5. from module.device.method import desktop_impl as desktop
  6. from module.device.desktop_device import DesktopDevice
  7. from module.device.device import Device
  8. from module.device.platform2 import Platform
  9. from module.atom import image
  10. from module.exception import GameNotRunningError, RequestHumanTakeover
  11. from tasks.Restart.script_task import ScriptTask
  12. from tasks.Script.config import Script
  13. def test_existing_configs_default_to_emulator():
  14. assert Script.model_validate({'device': {'serial': '127.0.0.1:16384'}}).desktop.enable is False
  15. def test_rebuilt_window_refreshes_screenshot_and_input_caches(monkeypatch):
  16. window = desktop.DesktopWindow()
  17. window.root_handle = '123'
  18. window.root_handle_num = 11
  19. window.screenshot_handle_num = 11
  20. window.screenshot_size = (1280, 720)
  21. window.control_handle_list = [11]
  22. monkeypatch.setattr(desktop, 'find_desktop_window_by_pid', lambda *args: 22)
  23. assert window.desktop_window_exists()
  24. assert window.root_handle_num == 22
  25. assert 'screenshot_handle_num' not in window.__dict__
  26. assert 'control_handle_list' not in window.__dict__
  27. def test_missing_main_process_does_not_hide_failed_launcher_cleanup(monkeypatch):
  28. window = desktop.DesktopWindow()
  29. window.root_handle = '123'
  30. window.root_handle_num = 0
  31. window.desktop_profile_dir = lambda: None
  32. window._desktop_kill_spawned_leftovers = Mock(return_value=False)
  33. monkeypatch.setattr(desktop, 'desktop_pid_alive', lambda pid: False)
  34. monkeypatch.setattr(desktop, 'desktop_keep_screen_on', lambda enable: None)
  35. assert window.desktop_stop_client() is False
  36. @pytest.mark.parametrize('job', [0, 99])
  37. def test_isolated_spawn_never_claims_an_unrelated_new_window(monkeypatch, tmp_path, job):
  38. now = [100.0]
  39. monkeypatch.setattr(desktop, 'time', SimpleNamespace(
  40. time=lambda: now[0], sleep=lambda seconds: now.__setitem__(0, now[0] + seconds)))
  41. other = dict(pid=456, hwnd=33)
  42. monkeypatch.setattr(desktop, 'list_desktop_windows',
  43. lambda: [] if now[0] == 100 else [other])
  44. monkeypatch.setattr(desktop.subprocess, 'Popen', lambda *a, **kw: SimpleNamespace(pid=123))
  45. monkeypatch.setattr(desktop, '_desktop_attach_job', lambda pid: job)
  46. monkeypatch.setattr(desktop, '_desktop_job_member_pids', lambda handle: set())
  47. monkeypatch.setattr(desktop, '_desktop_pid_under_root', lambda *args: True)
  48. monkeypatch.setattr(desktop, '_desktop_best_window', lambda pid, hwnd: hwnd)
  49. monkeypatch.setattr(desktop.ctypes, 'windll', SimpleNamespace(kernel32=SimpleNamespace(CloseHandle=lambda handle: None)))
  50. bound = Mock()
  51. pid, spawned = desktop.desktop_spawn_client('game.exe', str(tmp_path), tmp_path / 'account', timeout=4, on_bound=bound)
  52. assert pid == 0
  53. assert spawned == {123}
  54. bound.assert_not_called()
  55. @pytest.mark.parametrize('cleanup_succeeds', [True, False])
  56. def test_failed_launch_cleans_each_attempt_before_retry(monkeypatch, cleanup_succeeds):
  57. window = desktop.DesktopWindow()
  58. window.desktop_resolve_install_root = lambda: 'game'
  59. window.desktop_profile_dir = lambda: None
  60. calls, killed, alive = [], [], set()
  61. monkeypatch.setattr(desktop, 'desktop_game_exe', lambda root: 'game.exe')
  62. def spawn(*args, **kwargs):
  63. pid = 100 + len(calls)
  64. calls.append(pid)
  65. alive.add(pid)
  66. return 0, {pid}
  67. def cleanup(pids):
  68. killed.append(set(pids))
  69. if cleanup_succeeds:
  70. alive.difference_update(pids)
  71. monkeypatch.setattr(desktop, 'desktop_spawn_client', spawn)
  72. monkeypatch.setattr(desktop, 'desktop_pid_alive', lambda pid: pid in alive)
  73. window._desktop_kill_pids = cleanup
  74. assert window.launch_desktop_client(timeout=1) is False
  75. assert len(calls) == (2 if cleanup_succeeds else 1)
  76. assert killed == [{pid} for pid in calls]
  77. def test_emulator_initialization_resets_desktop_matching_padding(monkeypatch):
  78. task = object.__new__(Device)
  79. task.is_desktop = False
  80. task.config = SimpleNamespace(script=SimpleNamespace(device=SimpleNamespace(
  81. emulatorinfo_type='MuMuPlayer', screenshot_method='adb')))
  82. task.screenshot_interval_set = lambda: None
  83. monkeypatch.setattr(Platform, '__init__', lambda *args, **kwargs: None)
  84. monkeypatch.setattr(image, 'ROI_MATCH_PAD', 2)
  85. Device.__init__(task)
  86. assert image.ROI_MATCH_PAD == 0
  87. def test_live_process_waits_for_window_without_spawning(monkeypatch):
  88. import module.device.desktop_device as lifecycle
  89. task = DesktopDevice()
  90. task.desktop_pid = lambda: 123
  91. task.desktop_window_exists = lambda: False
  92. task._desktop_wait_window_ready = Mock(return_value=False)
  93. task.launch_desktop_client = Mock()
  94. monkeypatch.setattr(lifecycle, 'desktop_pid_alive', lambda pid: True)
  95. assert task._desktop_ensure_launched() is False
  96. task.launch_desktop_client.assert_not_called()
  97. def test_profile_without_state_cannot_adopt_other_accounts(monkeypatch, tmp_path):
  98. window = desktop.DesktopWindow()
  99. window.desktop_profile_dir = lambda: tmp_path
  100. monkeypatch.setattr(desktop, 'list_desktop_windows', Mock(side_effect=AssertionError('must not enumerate other accounts')))
  101. assert window._desktop_locate_window() == (None, 0)
  102. @pytest.mark.parametrize('cleanup_succeeds', [True, False])
  103. def test_restart_stops_after_bounded_failed_logins(cleanup_succeeds):
  104. task = object.__new__(ScriptTask)
  105. task.device = SimpleNamespace(app_start=Mock(), desktop_stop_client=Mock(return_value=cleanup_succeeds))
  106. task.app_handle_login = Mock(side_effect=GameNotRunningError('no window'))
  107. with pytest.raises(RequestHumanTakeover):
  108. task._desktop_start_and_login()
  109. assert task.device.app_start.call_count == (3 if cleanup_succeeds else 1)
  110. def test_profile_environment_does_not_mutate_parent(monkeypatch, tmp_path):
  111. monkeypatch.setenv('USERPROFILE', 'parent-home')
  112. env = desktop.desktop_profile_env(tmp_path)
  113. assert env['USERPROFILE'] == str(tmp_path / 'home')
  114. assert desktop.os.environ['USERPROFILE'] == 'parent-home'
  115. desktop.desktop_write_instance_state(tmp_path, 123)
  116. assert desktop.desktop_read_instance_state(tmp_path) == {'pid': 123}
  117. desktop.desktop_clear_instance_state(tmp_path)
  118. assert desktop.desktop_read_instance_state(tmp_path) == {}
  119. @pytest.mark.parametrize('job_pids,window_pid', [(set(), 123), ({123, 456}, 456)])
  120. def test_isolated_spawn_accepts_owned_window(monkeypatch, tmp_path, job_pids, window_pid):
  121. now = [100.0]
  122. monkeypatch.setattr(desktop, 'time', SimpleNamespace(
  123. time=lambda: now[0], sleep=lambda seconds: now.__setitem__(0, now[0] + seconds)))
  124. monkeypatch.setattr(desktop, 'list_desktop_windows', lambda: [dict(pid=window_pid, hwnd=22)])
  125. monkeypatch.setattr(desktop.subprocess, 'Popen', lambda *a, **kw: SimpleNamespace(pid=123))
  126. monkeypatch.setattr(desktop, '_desktop_attach_job', lambda pid: 99)
  127. monkeypatch.setattr(desktop, '_desktop_job_member_pids', lambda handle: job_pids)
  128. monkeypatch.setattr(desktop, '_desktop_pid_under_root', lambda *args: True)
  129. monkeypatch.setattr(desktop, '_desktop_best_window', lambda pid, hwnd: hwnd)
  130. monkeypatch.setattr(desktop.ctypes, 'windll', SimpleNamespace(kernel32=SimpleNamespace(CloseHandle=lambda handle: None)))
  131. bound = Mock()
  132. pid, spawned = desktop.desktop_spawn_client('game.exe', str(tmp_path), tmp_path / 'account', timeout=4, on_bound=bound)
  133. assert pid == window_pid
  134. assert {123, window_pid}.issubset(spawned)
  135. bound.assert_called_once_with(window_pid, 22)