174 lines
10 KiB
Python
174 lines
10 KiB
Python
from contextlib import nullcontext
|
|
import json
|
|
import sys
|
|
import time
|
|
from pathlib import Path
|
|
from types import SimpleNamespace
|
|
from uuid import uuid4
|
|
|
|
import pytest
|
|
|
|
from cbb_refresh_verify import residual_sessions as sessions
|
|
from test_residual_sessions import row, OWNERSHIP
|
|
|
|
|
|
def window():
|
|
return dict(hwnd=100, title='Design - Expedition PCB', desktop='Default',
|
|
**{'class': 'Afx:main'}, enabled=True, children=[], documents=[])
|
|
|
|
|
|
class PartialWindows(dict):
|
|
incomplete = {10: 'target thread inaccessible'}
|
|
|
|
|
|
def test_thread_read_failure_does_not_poison_another_process(monkeypatch):
|
|
import win32gui, win32process, win32service
|
|
def global_failure(*args):
|
|
raise OSError('an unrelated desktop is inaccessible')
|
|
monkeypatch.setattr(win32gui, 'EnumWindows', global_failure)
|
|
monkeypatch.setattr(win32service, 'GetProcessWindowStation',
|
|
lambda: SimpleNamespace(EnumDesktops=lambda: ['Default', 'CbbManagement_Unrelated']))
|
|
monkeypatch.setattr(sessions, '_process_threads', lambda _: {10: [100], 20: [200]}, raising=False)
|
|
monkeypatch.setattr(sessions, '_thread_desktop_name',
|
|
lambda tid: 'Default' if tid == 100 else 'CbbManagement_Broken', raising=False)
|
|
def open_desktop(name, *args):
|
|
if name == 'CbbManagement_Broken':
|
|
raise PermissionError('only process 20 is unreadable')
|
|
assert name == 'Default', 'an unrelated desktop must not be inspected'
|
|
return SimpleNamespace(EnumDesktopWindows=lambda: [1000], CloseDesktop=lambda: None)
|
|
monkeypatch.setattr(win32service, 'OpenDesktop', open_desktop)
|
|
monkeypatch.setattr(sessions, '_window_desktop', lambda name, **kwargs: nullcontext(open_desktop(name)))
|
|
monkeypatch.setattr(sessions, '_desktop_windows', lambda desktop: desktop.EnumDesktopWindows())
|
|
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 _: 'Design - Expedition PCB')
|
|
monkeypatch.setattr(win32gui, 'GetClassName', lambda _: 'Afx:main')
|
|
monkeypatch.setattr(win32gui, 'IsWindowEnabled', lambda _: True)
|
|
monkeypatch.setattr(win32gui, 'GetWindowRect', lambda _: (0, 0, 100, 100))
|
|
result = sessions._process_windows({10, 20})
|
|
assert [w['hwnd'] for w in result[10]] == [1000]
|
|
assert 10 not in result.incomplete and 'unreadable' in result.incomplete[20]
|
|
assert result[20] == [], 'a read error must not be represented as a native modal window'
|
|
assert sessions.close_target('ExpeditionPCB.exe', result[10])[0]
|
|
|
|
|
|
def test_preview_exposes_only_target_process_incomplete_state(tmp_path, monkeypatch):
|
|
library = tmp_path/'lib.lmc'; library.touch()
|
|
processes = [row(pid, tmp_path/f'ReusableBlocksLP/{pid}/Work/{pid}.prj', name='ExpeditionPCB.exe')
|
|
for pid in (10, 20)]
|
|
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: processes)
|
|
monkeypatch.setattr(sessions, '_process_identity', lambda r: dict(created_handle='creation',
|
|
image=r['executable'], **OWNERSHIP))
|
|
monkeypatch.setattr(sessions, '_process_windows', lambda _: PartialWindows({10: [window()], 20: [window()]}))
|
|
affected, healthy = sessions.inspect_residual_sessions(library)['sessions']
|
|
assert affected['windows_incomplete'] and not affected['can_close'] and not affected['force_allowed']
|
|
assert affected['native_activity']['status'] == 'UNCONFIRMED'
|
|
assert '读取' in affected['detail'] and '弹窗' not in affected['detail']
|
|
assert healthy['can_close'] and healthy['force_allowed']
|
|
|
|
|
|
def test_action_rechecks_incomplete_read_before_force_termination(monkeypatch):
|
|
import win32api, win32con, win32event
|
|
process = dict(row(10, 'C:/library/A.prj', name='ExpeditionPCB.exe'),
|
|
created_handle='creation', image='C:/Mentor/ExpeditionPCB.exe', scope_confirmed=True, **OWNERSHIP)
|
|
monkeypatch.setattr(sessions, '_process_handle', lambda *a, **kw: nullcontext(123))
|
|
monkeypatch.setattr(sessions, '_handle_identity', lambda _: {k: process[k] for k in ('created_handle', 'image')})
|
|
monkeypatch.setattr(sessions, '_force_ownership', lambda *args: dict(OWNERSHIP))
|
|
monkeypatch.setattr(win32event, 'WaitForSingleObject', lambda *args: win32con.WAIT_TIMEOUT)
|
|
monkeypatch.setattr(sessions, '_process_windows', lambda _: PartialWindows({10: [window()]}))
|
|
monkeypatch.setattr(win32api, 'TerminateProcess', lambda *args: pytest.fail('unreadable target was ended'))
|
|
result = sessions._force_close(process)
|
|
assert result['release_status'] == 'WAITING' and result['native_activity']['status'] == 'UNCONFIRMED'
|
|
|
|
|
|
def test_identity_read_failure_keeps_the_other_preview_row_available(tmp_path, monkeypatch):
|
|
library = tmp_path/'lib.lmc'; library.touch()
|
|
processes = [row(pid, tmp_path/f'ReusableBlocksLP/{pid}/Work/A.prj', name='ExpeditionPCB.exe')
|
|
for pid in (10, 20)]
|
|
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: processes)
|
|
def identity(process):
|
|
if process['pid'] == 10:
|
|
raise PermissionError('token inaccessible')
|
|
return dict(created_handle='creation', image=process['executable'], **OWNERSHIP)
|
|
monkeypatch.setattr(sessions, '_process_identity', identity)
|
|
monkeypatch.setattr(sessions, '_process_windows', lambda _: {pid: [window()] for pid in (10, 20)})
|
|
affected, healthy = sessions.inspect_residual_sessions(library)['sessions']
|
|
assert not affected['force_allowed'] and 'token inaccessible' in affected['detail']
|
|
assert healthy['force_allowed'] and healthy['can_close']
|
|
|
|
|
|
def test_native_cancel_retains_exact_preview_scope(tmp_path, monkeypatch):
|
|
from cbb_refresh_verify import library_lock
|
|
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
|
|
process = dict(row(10, library.parent/'ReusableBlocksLP/A/Work/A.prj'),
|
|
scope_confirmed=True, block_names=['A'], cancel_prompt={'hwnd': 100})
|
|
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: [process])
|
|
monkeypatch.setattr(sessions, '_process_windows', lambda _: {})
|
|
expected = (library.parent/'ReusableBlocksLP/A/Work', library.parent/'SymbolLibs')
|
|
def scoped(actual, selected_library, roots):
|
|
assert roots == expected, 'Cancel widened the scope from its preview'
|
|
return True
|
|
monkeypatch.setattr(library_lock, '_owner_matches_scope', scoped)
|
|
monkeypatch.setattr(sessions, '_request_native_cancel', lambda *a, **kw:
|
|
dict(release_status='WAITING', detail='cancel requested'))
|
|
result = sessions.request_native_cancel(process, library, tmp_path/'evidence')
|
|
assert result['sessions'][0]['detail'] == 'cancel requested'
|
|
|
|
|
|
def test_persisted_release_evidence_is_bounded_without_changing_preview(tmp_path, monkeypatch):
|
|
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
|
|
output = '原生输出' * 100000
|
|
observed = dict(window(), output=output, children=[dict(text=output, **{'class': 'RichEdit'})])
|
|
process = dict(row(10, library.parent/'ReusableBlocksLP/A/Work/A.prj', name='ExpeditionPCB.exe'),
|
|
created_handle='creation', image='C:/Mentor/ExpeditionPCB.exe', scope_confirmed=True,
|
|
windows=[observed], native_activity={'status': 'IDLE', 'output': output}, **OWNERSHIP)
|
|
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: [process])
|
|
monkeypatch.setattr(sessions, '_process_windows', lambda _: {})
|
|
monkeypatch.setattr(sessions, '_force_close', lambda *a, **kw: dict(release_status='RELEASED', detail='ended'))
|
|
monkeypatch.setattr(sessions, '_finish_library_release', lambda *args:
|
|
dict(status='RELEASE_CONFIRMED', library=str(library)))
|
|
result = sessions.release_residual_sessions(dict(library=str(library), sessions=[process]),
|
|
tmp_path/'evidence', force=True)
|
|
assert result['status'] == 'RELEASE_CONFIRMED'
|
|
for path in (Path(result['evidence_path']), Path(result['consent_path'])):
|
|
assert path.stat().st_size < 20000
|
|
saved = json.loads(path.read_text('utf-8'))['sessions'][0]
|
|
assert 'output' not in saved['native_activity']
|
|
assert 'children' not in saved['windows'][0] and 'output' not in saved['windows'][0]
|
|
assert len(saved['windows'][0]['output_excerpt'].encode('utf-8')) <= 4096
|
|
assert saved['windows'][0]['output_truncated'] is True
|
|
assert process['windows'][0]['output'] == output
|
|
|
|
|
|
def test_real_private_desktop_is_read_through_its_process_threads(tmp_path):
|
|
from cbb_refresh_verify.desktop_worker import DesktopWorker
|
|
ready, stop = tmp_path/'ready.json', tmp_path/'stop'
|
|
script = tmp_path/'window.py'
|
|
name = 'CbbManagement_Review_'+uuid4().hex[:10]
|
|
script.write_text('import json,time,win32api,win32con,win32gui\nfrom pathlib import Path\n'
|
|
'wc=win32gui.WNDCLASS()\nwc.hInstance=win32api.GetModuleHandle(None)\n'
|
|
'wc.lpszClassName="CbbReviewWindow"\nwc.lpfnWndProc=win32gui.DefWindowProc\n'
|
|
'atom=win32gui.RegisterClass(wc)\n'
|
|
'hwnd=win32gui.CreateWindow(atom,"Controlled review fixture",'
|
|
'win32con.WS_OVERLAPPEDWINDOW|win32con.WS_VISIBLE,0,0,300,200,0,0,wc.hInstance,None)\n'
|
|
f'Path({str(ready)!r}).write_text(json.dumps(dict(hwnd=hwnd)))\n'
|
|
f'while not Path({str(stop)!r}).exists():\n'
|
|
' win32gui.PumpWaitingMessages();time.sleep(.02)\n'
|
|
'win32gui.DestroyWindow(hwnd)\n', encoding='utf-8')
|
|
worker = DesktopWorker([sys.executable, str(script)], name)
|
|
try:
|
|
deadline = time.monotonic()+8
|
|
while not ready.exists() and worker.poll() is None and time.monotonic()<deadline:
|
|
time.sleep(.02)
|
|
assert ready.exists()
|
|
hwnd = json.loads(ready.read_text())['hwnd']
|
|
snapshot = sessions._process_windows({worker.pid})
|
|
assert worker.pid not in snapshot.incomplete, snapshot.incomplete
|
|
target = next(w for w in snapshot[worker.pid] if w['hwnd'] == hwnd)
|
|
assert target['desktop'] == name and target['title'] == 'Controlled review fixture'
|
|
finally:
|
|
stop.touch()
|
|
worker.wait(5)
|
|
worker.close()
|