Files
cbb-refresh-verify-795/tests/test_private_desktop_discovery.py

135 lines
6.4 KiB
Python

"""Exercise Windows across real processes; thread-desktop mocks miss access denial."""
import json
import sys
import time
from uuid import uuid4
import pytest
@pytest.mark.parametrize('thread_access_denied', [False, True])
def test_foreign_private_desktop_window_is_readable(tmp_path, monkeypatch, thread_access_denied):
import win32con
import win32gui
from cbb_refresh_verify.desktop_worker import DesktopWorker
from cbb_refresh_verify.residual_sessions import _process_windows
from cbb_refresh_verify import residual_sessions
if thread_access_denied:
def denied(_): raise PermissionError(5, 'GetThreadDesktop access denied')
monkeypatch.setattr(residual_sessions, '_thread_desktop_name', denied)
ready = tmp_path/'ready.json'
child = tmp_path/'window.py'
child.write_text('''
import json,sys,os
from pathlib import Path
import win32api,win32con,win32gui
def procedure(hwnd,message,wparam,lparam):
if message==win32con.WM_CLOSE:
win32gui.DestroyWindow(hwnd); return 0
if message==win32con.WM_DESTROY:
win32gui.PostQuitMessage(0); return 0
return win32gui.DefWindowProc(hwnd,message,wparam,lparam)
window=win32gui.WNDCLASS()
window.hInstance=win32api.GetModuleHandle(None)
window.lpszClassName='CbbPrivateDesktopTest'
window.lpfnWndProc=procedure
win32gui.RegisterClass(window)
hwnd=win32gui.CreateWindow(window.lpszClassName,'CBB private desktop discovery',
win32con.WS_OVERLAPPEDWINDOW|win32con.WS_VISIBLE,0,0,300,150,0,0,window.hInstance,None)
Path(sys.argv[1]).write_text(json.dumps({'pid':os.getpid(),'hwnd':hwnd}),'utf-8')
win32gui.PumpMessages()
''', encoding='utf-8')
name = 'CbbDiscoveryTest_'+uuid4().hex[:10]
worker = DesktopWorker([sys.executable, str(child), str(ready)], name)
row = None
try:
deadline = time.monotonic()+10
while not ready.exists() and worker.poll() is None and time.monotonic()<deadline:
time.sleep(.02)
assert ready.exists(), 'The real Windows test helper failed to start'
row = json.loads(ready.read_text('utf-8'))
snapshot = _process_windows({row['pid']})
assert not snapshot.incomplete, snapshot.incomplete
observed = [w for w in snapshot[row['pid']] if w['hwnd'] == row['hwnd']]
assert len(observed) == 1
assert observed[0]['title'] == 'CBB private desktop discovery'
assert observed[0]['desktop'] == name
# A fresh process has no mapped heap for this desktop. Merely keeping
# OpenDesktop's handle alive does not make its HWNDs readable.
import subprocess
probe = tmp_path/'probe.py'
probe.write_text('''
import sys
import win32process
from cbb_refresh_verify.residual_sessions import _window_desktop
with _window_desktop(sys.argv[1], write=True):
actual = win32process.GetWindowThreadProcessId(int(sys.argv[2]))
assert actual[0] and actual[1] == int(sys.argv[3]), actual
''', encoding='utf-8')
checked = subprocess.run([sys.executable, str(probe), name, str(row['hwnd']), str(row['pid'])],
capture_output=True, text=True, timeout=15)
assert checked.returncode == 0, checked.stdout+checked.stderr
residual_sessions._post_window_message(observed[0], row['hwnd'], row['pid'], win32con.WM_CLOSE)
worker.wait(timeout=5)
finally:
if row is not None:
with residual_sessions._window_desktop(name, write=True):
if win32gui.IsWindow(row['hwnd']):
win32gui.PostMessage(row['hwnd'], win32con.WM_CLOSE, 0, 0)
try: worker.wait(timeout=5)
finally: worker.close() # This helper is Python only; it never opens Mentor or a DB.
def test_fallback_desktop_failure_keeps_known_other_process_available(monkeypatch):
from contextlib import nullcontext
import win32gui, win32process
from cbb_refresh_verify import residual_sessions as sessions
monkeypatch.setattr(sessions, '_process_threads', lambda _: {10: [100], 20: [200]})
def desktop(tid):
if tid == 200: raise PermissionError('native thread desktop denied')
return 'Default'
monkeypatch.setattr(sessions, '_thread_desktop_name', desktop)
monkeypatch.setattr(sessions, '_desktop_names', lambda: ['Default', 'PrivateBroken'])
def opened(name, **kwargs):
if name == 'PrivateBroken': raise PermissionError('private desktop unreadable')
return nullcontext(name)
monkeypatch.setattr(sessions, '_window_desktop', opened)
monkeypatch.setattr(sessions, '_desktop_windows', lambda _: [1000])
monkeypatch.setattr(win32process, 'GetWindowThreadProcessId', lambda _: (100, 10))
monkeypatch.setattr(win32gui, 'IsWindowVisible', lambda _: True)
monkeypatch.setattr(win32gui, 'EnumChildWindows', lambda *args: None)
monkeypatch.setattr(win32gui, 'GetWindowText', lambda _: 'Expedition PCB')
monkeypatch.setattr(win32gui, 'GetClassName', lambda _: 'Afx:main')
monkeypatch.setattr(win32gui, 'IsWindowEnabled', lambda _: True)
monkeypatch.setattr(win32gui, 'GetWindowRect', lambda _: (0, 0, 100, 100))
snapshot = sessions._process_windows({10, 20})
assert 10 not in snapshot.incomplete and snapshot[10][0]['hwnd'] == 1000
assert 'unreadable' in snapshot.incomplete[20]
assert sessions.close_target('ExpeditionPCB.exe', snapshot[20], incomplete=snapshot.incomplete[20])[0] is None
@pytest.mark.parametrize('actual_pid', [10, 20])
def test_native_message_holds_desktop_and_rechecks_pid(monkeypatch, actual_pid):
from contextlib import contextmanager
import win32gui, win32process
from cbb_refresh_verify import residual_sessions as sessions
events = []
@contextmanager
def opened(name, *, write):
assert name == 'Private' and write is True
events.append('open')
try: yield 123
finally: events.append('close')
monkeypatch.setattr(sessions, '_window_desktop', opened)
monkeypatch.setattr(win32process, 'GetWindowThreadProcessId', lambda _: (1, actual_pid))
def post(*args):
assert events == ['open']
events.append('post')
monkeypatch.setattr(win32gui, 'PostMessage', post)
if actual_pid == 10:
sessions._post_window_message({'desktop': 'Private'}, 100, 10, 16)
assert events == ['open', 'post', 'close']
else:
with pytest.raises(ValueError, match='归属已变化'):
sessions._post_window_message({'desktop': 'Private'}, 100, 10, 16)
assert events == ['open', 'close']