fix: address defects found in frozen native acceptance

This commit is contained in:
阿白叔 committed 2026-11-12 11:33:44 +08:00
1 parent b86e4e315a
commit 42d0cebc54
15 files changed
+808 -50

No files matched your search

+25
View File
@@ -85,3 +85,28 @@ def test_later_management_invalidates_old_recovery_offer(qtbot, tmp_path, monkey
assert action.isEnabled()
window._invalidate_check_targets('test.lmc', ['Beta'])
assert not action.isEnabled() and not window._reimport_offers
def test_check_release_action_tracks_busy_and_retained_queue(qtbot, tmp_path, monkeypatch):
from test_ui_filters import load_window
from test_review326_queue_guidance import retain
from cbb_refresh_verify.verify_runner import VerifyResult
window = load_window(qtbot, tmp_path, monkeypatch,
verifier=lambda _: VerifyResult('FAIL', safe_to_continue=False))
window._run(['Beta'], maintenance=True)
qtbot.waitUntil(lambda: not window._icdb_active())
action = next(b for b in window.icdb_summary.buttons() if '释放' in b.text())
window.busy = True
window._update()
assert not action.isEnabled(), 'A normal native call cannot admit release yet'
retain(monkeypatch, window.mentor_lmc_path)
window._queue_wait_library = window.mentor_lmc_path
window._update()
assert action.isEnabled(), 'Retained-queue release must stay reachable'
opened = []
monkeypatch.setattr(window, 'check_library_release', lambda **kwargs: opened.append(kwargs))
action.click()
assert opened == [{'queued': True}]
window.busy = False
window._update()
assert action.isEnabled()
+56
View File
@@ -71,6 +71,31 @@ def test_invalid_source_does_not_touch_target(recovery_files):
assert (original.parent/'database/icdb.dat').read_bytes() == b'damaged'
@pytest.mark.parametrize('linked_to_target', [True, False])
def test_legacy_backup_without_auxiliary_pcb_project(recovery_files, linked_to_target):
from cbb_refresh_verify.backup_recovery import recover_from_backup
request, original, source = recovery_files
(source.parent/'PCB/pcb.prj').unlink()
if not linked_to_target:
pcb = source.parent/'PCB/A.pcb'
pcb.write_text(pcb.read_text().replace('A.prj', 'OTHER.prj'))
calls = []
def verify(req, **kwargs):
work = req.lmc_file.parent/'ReusableBlocksLP/A/Work'
assert not (work/'PCB/pcb.prj').exists()
calls.append(req)
return VerifyResult('PASS', library_flag='GREEN')
result = recover_from_backup(request, source, verifier=verify, idle_check=lambda *_: None)
if linked_to_target:
assert result.status == 'PASS', result.stderr
assert len(calls) == 2
assert (original.parent/'database/icdb.dat').read_bytes() == b'healthy'
else:
assert result.status == 'BLOCKED'
assert not calls
assert (original.parent/'database/icdb.dat').read_bytes() == b'damaged'
def test_unusable_backup_never_replaces_target(recovery_files):
from cbb_refresh_verify.backup_recovery import recover_from_backup
request, original, source = recovery_files
@@ -177,6 +202,37 @@ def test_idle_guard_rejects_exact_target_process(recovery_files, monkeypatch):
_idle_check(request.lmc_file, original, target)
@pytest.mark.parametrize('target_state', ['idle', 'open_file', 'address'])
def test_pathless_external_client_uses_target_resource_proof(recovery_files, monkeypatch, target_state):
import pywintypes
import win32con
import win32file
from cbb_refresh_verify import mentor_adapter
from cbb_refresh_verify.backup_recovery import _idle_check
request, original, _ = recovery_files
monkeypatch.setattr(mentor_adapter, '_process_details', lambda name:
[(123, 'viewdraw.exe', 'viewdraw.exe', 0)] if name == 'viewdraw.exe' else [])
address = original.parent/'database/cdbsvr/sAddress.adr'
handle = None
try:
if target_state == 'open_file':
handle = win32file.CreateFile(str(request.lmc_file), win32con.GENERIC_READ,
win32con.FILE_SHARE_READ, None, win32con.OPEN_EXISTING, 0, None)
with pytest.raises(pywintypes.error) as error:
_idle_check(request.lmc_file, original, original.parent/'PCB/A.pcb')
assert error.value.winerror == 32
elif target_state == 'address':
address.parent.mkdir(parents=True, exist_ok=True)
address.write_bytes(b'live or unconfirmed native address')
with pytest.raises(ValueError, match='TARGET_DATABASE_ADDRESS_UNCONFIRMED'):
_idle_check(request.lmc_file, original, original.parent/'PCB/A.pcb')
assert address.read_bytes() == b'live or unconfirmed native address'
else:
_idle_check(request.lmc_file, original, original.parent/'PCB/A.pcb')
finally:
if handle is not None: handle.Close()
def test_prelaunch_recovery_rejection_has_no_unreleased_session(recovery_files):
from cbb_refresh_verify.backup_recovery import recover_from_backup
request, _, source = recovery_files
+48
View File
@@ -221,6 +221,54 @@ def test_export_does_not_adopt_unrelated_existing_native_owner(project, tmp_path
assert len(started) == 3
@pytest.mark.parametrize('remains_alive,database_busy', [(False, False), (True, False), (False, True)])
def test_export_reobserves_access_denied_child_before_deciding_release(
project, tmp_path, monkeypatch, remains_alive, database_busy):
import json
import pywintypes
import win32api
from cbb_refresh_verify import native_engineering_identity as identity
source, _ = project
root = tmp_path/'exports'; root.mkdir()
launched, seen = [], {}
class Finished:
returncode = 0
def __init__(self, *args, **kwargs):
self.pid = 980000+len(launched)*2
launched.append(self)
def poll(self): return 0
def kill(self): pytest.fail('native owner must not be killed')
def snapshot():
if not launched: return []
pid = launched[-1].pid
seen[pid] = seen.get(pid, 0)+1
if seen[pid] == 1 or remains_alive:
return [{'pid': pid+1, 'parent': pid, 'name': 'conhost.exe',
'command': '', 'executable': '', 'created': 'creation-identity'}]
return []
def denied(*args): raise pywintypes.error(5, 'OpenProcess', 'Access is denied')
ticks = iter(i/100 for i in range(1000))
monkeypatch.setattr(identity.time, 'monotonic', lambda: next(ticks))
monkeypatch.setattr(identity.time, 'sleep', lambda _: None)
monkeypatch.setattr(identity.subprocess, 'Popen', Finished)
monkeypatch.setattr(identity, '_process_snapshot', snapshot)
monkeypatch.setattr(identity, '_database_released', lambda _: not launched or not database_busy)
monkeypatch.setattr(identity, 'validate_export_output', lambda *_: None)
monkeypatch.setattr(identity, '_retained_exports', [])
monkeypatch.setattr(win32api, 'OpenProcess', denied)
result = identity._run_exports(source, root, tmp_path, .045)
expected = not remains_alive and not database_busy
assert result['success'] is expected
assert result['safe_to_continue'] is expected
record = json.loads((root/'ascii-process.json').read_text('utf-8'))
assert record['process_identities'][0]['pid'] == launched[0].pid+1
assert record['process_observation_errors'][str(launched[0].pid+1)]['winerror'] == 5
if expected:
assert len(launched) == 3 and not identity._retained_exports
else:
assert 'TIMEOUT' in result['detail'] and identity._retained_exports
def test_export_spawn_failure_does_not_manufacture_native_ownership(project, tmp_path, monkeypatch):
import cbb_refresh_verify.native_engineering_identity as identity
source, _ = project
+134
View File
@@ -0,0 +1,134 @@
"""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']
@@ -37,6 +37,8 @@ def test_thread_read_failure_does_not_poison_another_process(monkeypatch):
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)
+2 -2
View File
@@ -87,7 +87,7 @@ def test_management_records_scoped_changes_without_hashing_unrelated_cbb(setup,
assert 'SymbolLibs/shared/icdb.dat' in report['modified']
assert 'ReusableBlocksLP/Block/Work/Block.prj' in report['modified']
assert result.change_report == report
assert report['rule_version'] == 1
assert report['rule_version'] == 2
assert report['scope'] == {'kind': 'library', 'block_name': 'Block',
'library_name': request.library.name}
from cbb_refresh_verify import scoped_manifest as manifests
@@ -95,7 +95,7 @@ def test_management_records_scoped_changes_without_hashing_unrelated_cbb(setup,
assert report['excluded_suffixes'] == sorted(manifests._NONPRIMARY_SUFFIXES)
runtime = report['runtime_exclusions']
assert runtime['native_directory_names'] == ['dbcheck', 'dbrestore', 'log']
assert runtime['file_names'] == ['saddress.adr']
assert runtime['file_names'] == ['saddress.adr', 'saddress_.adr']
assert runtime['file_name_prefixes'] == ['~$']
assert runtime['relative_directories'] == ['projectbackup/backups']
assert runtime['directory_prefixes'] == ['work.before-restore-']
+1
View File
@@ -128,6 +128,7 @@ def test_native_cancel_requires_same_current_control_and_exact_owned_process(mon
monkeypatch.setattr(sessions, '_handle_identity', lambda _: {k:process[k] for k in ('created_handle','image')})
monkeypatch.setattr(sessions, '_force_ownership', lambda *a: dict(OWNERSHIP))
monkeypatch.setattr(sessions, '_process_windows', lambda _: {10:[window]})
monkeypatch.setattr(sessions, '_window_desktop', lambda *args, **kwargs: nullcontext(None))
monkeypatch.setattr(win32event, 'WaitForSingleObject', lambda *a: win32con.WAIT_TIMEOUT)
monkeypatch.setattr(win32process, 'GetWindowThreadProcessId', lambda _: (1,10))
clicked=[]; monkeypatch.setattr(win32gui, 'PostMessage', lambda *a: clicked.append(a))
+2 -1
View File
@@ -41,7 +41,8 @@ def test_primary_edits_additions_and_deletions_change_semantics(tmp_path, relati
@pytest.mark.parametrize('relative', [
'logs/session.txt', 'log/native.log', 'session.log', 'temp/native.bin',
'tmp/native.bin', 'session.tmp', 'database/icdb.lck',
'database/cdbsvr/sAddress.adr', '.target.cbb-upload.lock',
'database/cdbsvr/sAddress.adr', 'database/cdbsvr/sAddress_.adr',
'PCB/database/cdbsvr/SADDRESS_.ADR', '.target.cbb-upload.lock',
'backups/old/A.prj', 'backup/old/icdb.dat', 'A.prj.bak',
'drawing.pdf', 'output/netlist.txt', 'reports/check.txt',
])