257 lines
15 KiB
Python
257 lines
15 KiB
Python
"""File-only native failure and legacy path-boundary checks."""
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
|
|
|
|
ERROR = b'REUSE BLOCK: INFORMATION: Block\tError! Cannot copy iCDB base of Reusable Block project.\r\n'
|
|
|
|
|
|
@pytest.fixture
|
|
def owned_add_process(monkeypatch):
|
|
import subprocess, sys
|
|
from cbb_refresh_verify import desktop_worker
|
|
monkeypatch.setattr(desktop_worker, '_automation_clients', [])
|
|
process = subprocess.Popen([sys.executable, '-c', 'input()'], stdin=subprocess.PIPE, text=True)
|
|
try:
|
|
yield process
|
|
finally:
|
|
process.communicate('\n', timeout=3)
|
|
for operation in desktop_worker._automation_clients:
|
|
assert operation.poll() is not None
|
|
|
|
|
|
@pytest.mark.parametrize('change', ['', 'target', 'pcb_present', 'question', 'extra_button', 'wrong_button', 'escape'])
|
|
def test_editor_missing_pcb_notice_is_only_for_unrelated_incomplete_entries(tmp_path, change):
|
|
from cbb_refresh_verify.native_add_failures import missing_other_pcb_notice
|
|
library = tmp_path/'lib.lmc'; library.touch()
|
|
work = tmp_path/'ReusableBlocksLP/Missing/Work'
|
|
(work/'PCB/Layout').mkdir(parents=True)
|
|
(work/'Missing.prj').write_text('KEY PCBDesignPath "PCB/Missing.pcb"\n')
|
|
text = ('The following Reusable Blocks do not contain PCB files and will not appear in the list of available reusable blocks:'
|
|
'\n\n\tMissing')
|
|
buttons = [{'hwnd':123, 'id':2, 'class':'Button', 'text':'确定', 'enabled':True}]
|
|
target = 'Missing' if change == 'target' else 'Current'
|
|
if change == 'pcb_present':
|
|
(work/'PCB/Missing.pcb').touch(); (work/'PCB/Layout/LayoutDB.lyt').touch()
|
|
if change == 'question': text += '\nOverwrite existing files?'
|
|
if change == 'extra_button': buttons.append({**buttons[0], 'hwnd':456})
|
|
if change == 'wrong_button': buttons[0]['text']='Yes'
|
|
if change == 'escape': text=text.replace('\tMissing', '\t../other')
|
|
result = missing_other_pcb_notice(library, target, 'Library Manager', text, buttons)
|
|
assert result == ({'names':['Missing'], 'button':123} if not change else None)
|
|
|
|
|
|
@pytest.mark.parametrize('reason', ['cancelled', 'supervisor_exited'])
|
|
def test_add_cannot_submit_after_timeout_or_supervisor_exit(tmp_path, monkeypatch, reason):
|
|
from cbb_refresh_verify.native_management import _require_add_supervisor
|
|
import cbb_refresh_verify.library_lock as locks
|
|
if reason == 'cancelled': (tmp_path/'cancel-native-add.signal').touch()
|
|
monkeypatch.setattr(locks, '_supervisor_alive', lambda _:reason != 'supervisor_exited')
|
|
with pytest.raises(RuntimeError, match='NATIVE_ADD_CANCELLED'):
|
|
_require_add_supervisor({'supervisor_pid':123}, tmp_path)
|
|
|
|
|
|
def test_add_timeout_publishes_cancellation_without_killing_native_owner(tmp_path, monkeypatch):
|
|
import cbb_refresh_verify.native_management as native
|
|
monkeypatch.setattr(native, '_retained_workers', [])
|
|
class Running:
|
|
def __init__(self, *args): pass
|
|
def poll(self): return None
|
|
def close(self): pytest.fail('live worker must not be killed')
|
|
adapter=native.NativeManagementAdapter(worker_factory=Running)
|
|
result=adapter._launch_worker({'operation':'add','desktop':'CbbManagement_test','timeout_seconds':0,
|
|
'library':str(tmp_path/'library.lmc')},tmp_path)
|
|
assert not result['safe_to_continue'] and (tmp_path/'cancel-native-add.signal').exists()
|
|
assert len(native._retained_workers)==1
|
|
|
|
|
|
@pytest.mark.parametrize('cancel', [True, False])
|
|
@pytest.mark.parametrize('journal_error', [False, True])
|
|
@pytest.mark.parametrize('changed_name', [False, True])
|
|
def test_cancellation_and_phase_at_native_add_submit(tmp_path, monkeypatch, cancel, journal_error, changed_name, owned_add_process):
|
|
import os,sys
|
|
from types import SimpleNamespace
|
|
import win32gui,win32process
|
|
import cbb_refresh_verify.native_management as native
|
|
import cbb_refresh_verify.native_add_failures as failures
|
|
from test_management import project
|
|
source=project(tmp_path/'source',name='Block')
|
|
root=tmp_path/'native-add';root.mkdir()
|
|
library=root/'fixture/lib.lmc';library.parent.mkdir();library.touch()
|
|
for path in (source,source.parent/'PCB/pcb.prj'):
|
|
with path.open('a',encoding='utf-8') as stream:stream.write(f'KEY CentralLibrary "{library}"\n')
|
|
state={'new':False,'posted':[]}
|
|
tab=SimpleNamespace(window_text=lambda:'Logical - Physical',is_selected=lambda:True)
|
|
monkeypatch.setitem(sys.modules,'pywinauto',SimpleNamespace(Desktop=lambda **k:SimpleNamespace(
|
|
window=lambda **k:SimpleNamespace(descendants=lambda **k:[tab]))))
|
|
monkeypatch.setattr(win32process,'GetWindowThreadProcessId',lambda h:(1,owned_add_process.pid))
|
|
monkeypatch.setattr(win32gui,'IsWindowVisible',lambda h:True)
|
|
monkeypatch.setattr(win32gui,'IsWindowEnabled',lambda h:True)
|
|
monkeypatch.setattr(win32gui,'GetWindowText',lambda h:{100:'Reusable Blocks',200:'New Reusable Block'}[int(h)])
|
|
monkeypatch.setattr(win32gui,'GetDlgItem',lambda h,c:110 if h==100 else 210 if c==1083 else c+1000)
|
|
monkeypatch.setattr(win32gui,'GetClassName',lambda h:'Edit')
|
|
def field(*args, read_only=False):
|
|
if read_only and args[1] == 1215 and changed_name:
|
|
raise RuntimeError('NATIVE_ADD_NAME_CHANGED')
|
|
monkeypatch.setattr(native,'_set_probe_field',field)
|
|
def post(h,*args):
|
|
state['posted'].append(h)
|
|
if h==110:state['new']=True
|
|
if h==210:
|
|
from cbb_refresh_verify.session_record import read_session_record
|
|
assert read_session_record(root/'worker-state.json', evidence_root=root)['phase'] == 'NATIVE_CALL'
|
|
monkeypatch.setattr(win32gui,'PostMessage',post)
|
|
original=native._write_json
|
|
def write(path,data):
|
|
original(path,data)
|
|
if path.name=='native-add-log-baseline.json' and cancel:(root/'cancel-native-add.signal').touch()
|
|
monkeypatch.setattr(native,'_write_json',write)
|
|
monkeypatch.setattr(failures,'observe_add_failure',lambda *a:(_ for _ in ()).throw(RuntimeError('unsafe OK posted')))
|
|
desktop=SimpleNamespace(EnumDesktopWindows=lambda:[100,200] if state['new'] else [100])
|
|
job={'operation':'probe_create_add','source':str(source),'library':str(library),
|
|
'name':'Block','timeout_seconds':5,'supervisor_pid':os.getpid(),
|
|
'operation_id':'test-add-phase','session_record_path':str(root/'session.json')}
|
|
from cbb_refresh_verify.session_record import write_session_record
|
|
write_session_record(root/'worker-state.json', {'operation_id': 'test-add-phase', 'phase':'POSTCALL', 'processes':[]})
|
|
if journal_error:
|
|
def fail(*a, **kw): raise OSError('phase journal unavailable')
|
|
monkeypatch.setattr('cbb_refresh_verify.session_record.write_session_record', fail)
|
|
expected = OSError if journal_error and not cancel and not changed_name else RuntimeError
|
|
message = ('NATIVE_ADD_NAME_CHANGED' if changed_name else 'NATIVE_ADD_CANCELLED' if cancel
|
|
else 'phase journal unavailable' if journal_error else 'unsafe OK posted')
|
|
with pytest.raises(expected, match=message):
|
|
native._probe_add_dialog_impl(SimpleNamespace(OnReusableBlocksEditor=lambda:None),job,desktop,{owned_add_process.pid},root)
|
|
assert state['posted']==([110] if cancel or journal_error or changed_name else [110,210])
|
|
|
|
|
|
def test_unknown_pending_add_does_not_send_cleanup_dialog_actions(tmp_path, monkeypatch):
|
|
from cbb_refresh_verify import native_management as native
|
|
def pending(app, job, *a, **kw):
|
|
job['_native_add_pending'] = True
|
|
raise TimeoutError('native Add pending')
|
|
monkeypatch.setattr(native, '_probe_add_dialog_impl', pending)
|
|
monkeypatch.setattr(native, '_close_probe_dialogs', lambda *a: pytest.fail('closing a pending Add'))
|
|
with pytest.raises(TimeoutError):
|
|
native._probe_add_dialog(None, {}, None, set(), tmp_path)
|
|
|
|
|
|
@pytest.mark.parametrize('acknowledged', [False, True])
|
|
def test_add_failure_only_allows_cleanup_after_confirmed_native_ack(tmp_path, monkeypatch, acknowledged):
|
|
import json
|
|
from cbb_refresh_verify import native_management as native
|
|
job = {}
|
|
def failed(app, job, *a, **kw):
|
|
job['_native_add_pending'] = True
|
|
(tmp_path/'native-add-output.json').write_text(json.dumps({'failure': {'acknowledged': acknowledged}}))
|
|
raise RuntimeError('NATIVE_ADD_FAILED: simulated complete error')
|
|
closed = []
|
|
monkeypatch.setattr(native, '_probe_add_dialog_impl', failed)
|
|
monkeypatch.setattr(native, '_close_probe_dialogs', lambda *a: closed.append(True))
|
|
with pytest.raises(RuntimeError, match='NATIVE_ADD_FAILED'):
|
|
native._probe_add_dialog(None, job, None, set(), tmp_path)
|
|
assert bool(closed) is acknowledged
|
|
assert job['_native_add_pending'] is not acknowledged
|
|
|
|
|
|
def test_copy_failure_log_must_be_new_and_match_current_block(tmp_path):
|
|
from cbb_refresh_verify.native_add_failures import snapshot_add_log, fresh_add_failure
|
|
library = tmp_path/'lib.lmc'; library.touch()
|
|
log = tmp_path/'LogFiles/ReuseBlockLogLO.txt'; log.parent.mkdir(); log.write_bytes(ERROR)
|
|
baseline = snapshot_add_log(library)
|
|
assert fresh_add_failure(baseline, 'Block') is None
|
|
with log.open('ab') as stream: stream.write(ERROR.replace(b'Block\t', b'Other\t'))
|
|
assert fresh_add_failure(baseline, 'Block') is None
|
|
with log.open('ab') as stream: stream.write(ERROR)
|
|
assert 'Cannot copy iCDB base' in fresh_add_failure(baseline, 'Block')
|
|
# A replaced/rotated prefix is not evidence that an old error is new.
|
|
log.write_bytes(b'replaced\n'+ERROR)
|
|
assert fresh_add_failure(baseline, 'Block') is None
|
|
|
|
|
|
def test_newly_created_failure_log_is_current_round_evidence(tmp_path):
|
|
from cbb_refresh_verify.native_add_failures import snapshot_add_log, fresh_add_failure
|
|
library = tmp_path/'lib.lmc'
|
|
baseline = snapshot_add_log(library)
|
|
log = tmp_path/'LogFiles/ReuseBlockLogLO.txt'; log.parent.mkdir(); log.write_bytes(ERROR)
|
|
assert fresh_add_failure(baseline, 'Block')
|
|
|
|
|
|
@pytest.mark.parametrize('change', ['none', 'title', 'question', 'button_id', 'button_text', 'disabled', 'extra_button'])
|
|
def test_only_observed_path_error_dialog_can_be_acknowledged(change):
|
|
from cbb_refresh_verify.native_add_failures import failure_ack_button
|
|
title, text = 'Library Manager', '\n系统找不到指定的路径。\r\n'
|
|
buttons = [{'hwnd': 123, 'id': 2, 'class': 'Button', 'text': '确定', 'enabled': True}]
|
|
if change == 'title': title = 'Unrelated'
|
|
if change == 'question': text += '是否继续?'
|
|
if change == 'button_id': buttons[0]['id'] = 1
|
|
if change == 'button_text': buttons[0]['text'] = '是'
|
|
if change == 'disabled': buttons[0]['enabled'] = False
|
|
if change == 'extra_button': buttons.append({**buttons[0], 'hwnd': 456})
|
|
assert failure_ack_button(title, text, buttons) == (123 if change == 'none' else None)
|
|
|
|
|
|
def test_native_path_guard_includes_runtime_files_and_projected_target(tmp_path):
|
|
from cbb_refresh_verify.native_add_failures import validate_native_copy_paths
|
|
source = tmp_path/'source/Block.prj'; source.parent.mkdir(); source.touch()
|
|
validate_native_copy_paths(source, tmp_path/'library/lib.lmc', 'Block')
|
|
runtime = source.parent/'CES/LogFiles'/('x'*120)/('y'*90+'.log')
|
|
runtime.parent.mkdir(parents=True); runtime.touch()
|
|
with pytest.raises(ValueError, match='NATIVE_PATH_TOO_LONG'):
|
|
validate_native_copy_paths(source, tmp_path/'library/lib.lmc', 'Block')
|
|
assert runtime.exists()
|
|
runtime.unlink()
|
|
# Even a short staged tree can exceed the legacy limit at its target.
|
|
target = tmp_path/('library-'+'x'*150)/'lib.lmc'
|
|
with pytest.raises(ValueError, match='目标'):
|
|
validate_native_copy_paths(source, target, 'Block')
|
|
|
|
|
|
@pytest.mark.parametrize('kind', ['known', 'unknown', 'foreign'])
|
|
def test_failure_observer_only_acknowledges_owned_known_dialog(tmp_path, monkeypatch, kind):
|
|
import json
|
|
from types import SimpleNamespace
|
|
import win32gui, win32process
|
|
from cbb_refresh_verify.native_add_failures import observe_add_failure, snapshot_add_log
|
|
state = {'open': True, 'clicks': []}
|
|
monkeypatch.setattr(win32process, 'GetWindowThreadProcessId', lambda _: (1, 999 if kind == 'foreign' else 123))
|
|
monkeypatch.setattr(win32gui, 'IsWindowVisible', lambda _: True)
|
|
monkeypatch.setattr(win32gui, 'GetClassName', lambda h: {1: '#32770', 10: 'Button', 11: 'Static'}[h])
|
|
monkeypatch.setattr(win32gui, 'GetWindowText', lambda h: {1: 'Library Manager', 10: '确定',
|
|
11: '系统找不到指定的路径。' if kind == 'known' else '未确认的原生提示'}[h])
|
|
monkeypatch.setattr(win32gui, 'EnumChildWindows', lambda h, callback, p: [callback(c, p) for c in [10, 11]])
|
|
monkeypatch.setattr(win32gui, 'GetDlgCtrlID', lambda h: 2 if h == 10 else 0)
|
|
monkeypatch.setattr(win32gui, 'IsWindowEnabled', lambda _: True)
|
|
monkeypatch.setattr(win32gui, 'IsWindow', lambda _: state['open'])
|
|
def post(hwnd, message, *_):
|
|
state['clicks'].append(hwnd); state['open'] = False
|
|
monkeypatch.setattr(win32gui, 'PostMessage', post)
|
|
monkeypatch.setattr(win32gui, 'SetForegroundWindow', lambda *_: pytest.fail('foreground input is forbidden'))
|
|
args = (SimpleNamespace(EnumDesktopWindows=lambda: [1]), {123}, tmp_path,
|
|
snapshot_add_log(tmp_path/'lib.lmc'), 'Block', {})
|
|
if kind == 'known':
|
|
with pytest.raises(RuntimeError, match='NATIVE_ADD_FAILED'): observe_add_failure(*args)
|
|
result = json.loads((tmp_path/'native-add-output.json').read_text(encoding='utf-8'))
|
|
assert result['success_message'] is None and result['failure']['acknowledged']
|
|
assert state['clicks'] == [10]
|
|
else:
|
|
observe_add_failure(*args)
|
|
assert not state['clicks'] and not (tmp_path/'native-add-output.json').exists()
|
|
assert (tmp_path/'native-add-dialogs.jsonl').exists() is (kind == 'unknown')
|
|
|
|
|
|
def test_path_rejection_returns_safe_before_any_native_identity_or_alignment(tmp_path, monkeypatch):
|
|
from cbb_refresh_verify.management import Capability, ManagementRequest
|
|
from cbb_refresh_verify.native_management import NativeManagementAdapter
|
|
import cbb_refresh_verify.management_transaction as authority
|
|
source = tmp_path/'source/Block.prj'; source.parent.mkdir(); source.touch()
|
|
runtime = source.parent/('x'*150)/('y'*100+'.log')
|
|
runtime.parent.mkdir(); runtime.write_bytes(b'preserved history')
|
|
adapter = NativeManagementAdapter(mentor_home=tmp_path)
|
|
monkeypatch.setattr(adapter, 'capabilities', lambda: {'add': Capability(True, 'test boundary')})
|
|
monkeypatch.setattr(authority, 'current_lease', lambda _: pytest.fail('long path reached native transaction setup'))
|
|
request = ManagementRequest('update', tmp_path/'lib.lmc', 'Block', source=source)
|
|
staged, result = adapter.prepare_add_transaction(request, tmp_path/'evidence', original_source=source)
|
|
assert staged == request and result.identity is None and result.safe_to_continue
|
|
assert 'NATIVE_PATH_TOO_LONG' in result.detail and runtime.read_bytes() == b'preserved history'
|