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

264 lines
13 KiB
Python

from contextlib import nullcontext
from types import SimpleNamespace
from dataclasses import replace
import pytest
from test_post_repair_consent import snapshot
@pytest.mark.parametrize('decision,control', [('continue',6),('skip',7),('cancel',7)])
def test_readwrite_requires_explicit_choice_and_consumes_once(tmp_path,monkeypatch,decision,control):
from cbb_refresh_verify import pcb_open_consent as consent
monkeypatch.setattr(consent,'validate_owner',lambda *a:('bound-owner',))
monkeypatch.setattr(consent,'resource_guard',lambda *a:nullcontext())
job=dict(root=str(tmp_path),block_name='A',lmc_file=str(tmp_path/'lib.lmc'),desktop='CbbVerify_test',
project=str(tmp_path/'A.prj'),pcb=str(tmp_path/'A.pcb'))
controller=consent.OpenController(job)
shown=[];sent=[]
def perform(s,p,phase):
sent.append(p);return SimpleNamespace(accepted_controls=(control,),error_code='',detail='',channel='win32_button_click')
kwargs=dict(target_pid=20,launcher_pid=10,worker_pid=5,show=shown.append,perform=perform)
first=controller.handle(snapshot(),(snapshot(),),**kwargs)
assert not first.error_code and len(shown)==1 and not sent
shown[0].choose(decision)
result=controller.handle(snapshot(),(snapshot(),),**kwargs)
assert len(sent)==1 and sent[0]['target']=={'control_id':control}
assert result.error_code==('' if decision=='continue' else 'PCB_OPEN_SKIPPED' if decision=='skip' else 'USER_CANCELLED')
controller.handle(snapshot(),(snapshot(),),**kwargs)
assert len(sent)==1
def test_no_consent_to_changed_window_or_database_owner(tmp_path,monkeypatch):
from cbb_refresh_verify import pcb_open_consent as consent
monkeypatch.setattr(consent,'validate_owner',lambda *a:('bound',))
def occupied(*a):raise ValueError('target database occupied')
monkeypatch.setattr(consent,'resource_guard',occupied)
controller=consent.OpenController(dict(root=str(tmp_path),block_name='A',lmc_file=str(tmp_path/'lib.lmc'),
desktop='CbbVerify_test',project=str(tmp_path/'A.prj'),pcb=str(tmp_path/'A.pcb')))
shown=[]
kwargs=dict(target_pid=20,launcher_pid=10,worker_pid=5,show=shown.append,perform=lambda *a:pytest.fail('unsafe Yes'))
controller.handle(snapshot(),(snapshot(),),**kwargs)
shown[0].choose('continue')
result=controller.handle(snapshot(),(snapshot(),),**kwargs)
assert result.error_code=='DATABASE_RECOVERY_REQUIRED' and 'occupied' in result.detail
def test_explicit_open_dialog_defaults_to_cancel(qtbot):
from cbb_refresh_verify.pcb_open_consent import OpenChoice
from cbb_refresh_verify.ui.pcb_open_dialog import PcbOpenDialog
choice=OpenChoice('A','lib.lmc')
dialog=PcbOpenDialog(choice);qtbot.addWidget(dialog)
assert dialog.defaultButton() is dialog.skip_button
dialog.skip_button.click()
assert choice.decision=='skip'
def test_normal_open_can_request_a_version_without_automatic_repair(tmp_path,monkeypatch):
from cbb_refresh_verify import pcb_open_consent as consent
from cbb_refresh_verify.pcb_restore_prompt import RestoreController
from test_pcb_version_choice import captured
monkeypatch.setattr(consent,'validate_owner',lambda *a:('owned',))
job=dict(root=str(tmp_path),block_name='A',lmc_file=str(tmp_path/'lib.lmc'),
desktop='CbbVerify_test',project=str(tmp_path/'A.prj'),pcb=str(tmp_path/'A.pcb'))
controller=RestoreController(job,user_open=True)
snap=captured();shown=[];sent=[]
def perform(s,p,phase):
sent.append(p);return SimpleNamespace(accepted_controls=(p['target']['control_id'],),error_code='',detail='',channel='win32_button_click')
kwargs=dict(target_pid=snap.pid,launcher_pid=10,worker_pid=5,companion_pids=(),show=shown.append,perform=perform)
assert not controller.handle(snap,(snap,),**kwargs).error_code
assert len(shown)==1 and not sent
shown[0].choose('last_user_saved')
assert controller.handle(snap,(snap,),**kwargs).action_sent
selected=replace(snap,controls=tuple(replace(c,checked=c.control_id==6213,selected=c.control_id==6213)
if c.control_id in (6213,6206) else c for c in snap.controls))
assert controller.handle(selected,(selected,),**kwargs).action_sent
assert [p['target']['control_id'] for p in sent]==[6213,1]
def test_readwrite_choice_survives_uia_chrome_enrichment(tmp_path,monkeypatch):
from cbb_refresh_verify import pcb_open_consent as consent
from cbb_refresh_verify.dialog_models import ControlSnapshot
monkeypatch.setattr(consent,'validate_owner',lambda *a:('owned',))
monkeypatch.setattr(consent,'resource_guard',lambda *a:nullcontext())
controller=consent.OpenController(dict(root=str(tmp_path),block_name='A',lmc_file='lib.lmc',
project='A.prj',pcb='A.pcb',desktop='CbbVerify_test'))
original=snapshot();shown=[];sent=[]
original=replace(original,controls=tuple(replace(c,name='是(&Y)' if c.control_id==6 else '否(&N)')
if c.class_name=='Button' else c for c in original.controls))
def perform(s,p,phase):
sent.append(p)
return SimpleNamespace(accepted_controls=(6,),error_code='',detail='',channel='win32_button_click')
kwargs=dict(target_pid=20,launcher_pid=10,worker_pid=5,show=shown.append,perform=perform)
controller.handle(original,(original,),**kwargs)
shown[0].choose('continue')
chrome=(ControlSnapshot(original.hwnd,0,original.window_class,original.title,
control_type='Window',patterns=('Window',)),
ControlSnapshot(0,0,'','',control_type='TitleBar',patterns=('Value',)))
enriched=replace(original,controls=tuple(replace(c,name=c.name.replace('&',''))
if c.class_name=='Button' else c for c in reversed(original.controls))+chrome)
assert consent.exact_prompt(enriched)
result=controller.handle(enriched,(enriched,),**kwargs)
assert not result.error_code and len(sent)==1
def test_readwrite_choice_rejects_replaced_native_button(tmp_path,monkeypatch):
from cbb_refresh_verify import pcb_open_consent as consent
monkeypatch.setattr(consent,'validate_owner',lambda *a:('owned',))
controller=consent.OpenController(dict(root=str(tmp_path),block_name='A',lmc_file='lib.lmc'))
original=snapshot();shown=[]
kwargs=dict(target_pid=20,launcher_pid=10,worker_pid=5,show=shown.append,
perform=lambda *a:pytest.fail('changed native button accepted'))
controller.handle(original,(original,),**kwargs)
shown[0].choose('continue')
changed=replace(original,controls=tuple(replace(c,handle=c.handle+1) if c.control_id==6 else c
for c in original.controls))
assert controller.handle(changed,(changed,),**kwargs).error_code=='DATABASE_RECOVERY_REQUIRED'
@pytest.mark.parametrize('origin', ['user', 'timeout_default'])
@pytest.mark.parametrize('guard_error, control, code', [
(None, 6, ''),
(OSError('共享数据库被占用:SymbolLibs/icdb.dat'), 7, 'PCB_OPEN_SKIPPED'),
(TimeoutError('原生检查超时'), 7, 'PCB_OPEN_SKIPPED'),
])
def test_normal_readwrite_uses_same_resource_check(tmp_path, monkeypatch, origin, guard_error, control, code):
from contextlib import contextmanager
import json
from cbb_refresh_verify import pcb_open_consent as consent
monkeypatch.setattr(consent, 'validate_owner', lambda *_: {'target': 'owned'})
events = []
@contextmanager
def guard(*_, require_complete_proof=False):
assert require_complete_proof
events.append('probe')
if guard_error is not None:
raise guard_error
yield
events.append('released_probe_handles')
monkeypatch.setattr(consent, 'resource_guard', guard)
controller = consent.OpenController(dict(root=str(tmp_path), block_name='A', lmc_file='lib.lmc',
project='A.prj', pcb='A.pcb', desktop='CbbVerify_test'), auto_confirm=True)
shown = []
def perform(_, action, phase):
clicked = action['target']['control_id']
events.append(clicked)
return SimpleNamespace(accepted_controls=(clicked,), error_code='', detail='', channel='win32_button_click')
kwargs = dict(target_pid=20, launcher_pid=10, worker_pid=5, show=shown.append, perform=perform)
controller.handle(snapshot(), (snapshot(),), **kwargs)
assert not events
shown[0].choose('continue', origin=origin)
result = controller.handle(snapshot(), (snapshot(),), **kwargs)
assert result.error_code == code
assert events == (['probe', 'released_probe_handles', control] if guard_error is None else ['probe', control])
if guard_error is not None:
assert str(guard_error) in result.detail
record = json.loads((tmp_path/'pcb-open-user-choice.json').read_text(encoding='utf-8'))
assert record['decision_origin'] == origin
assert record['choice'] == ('continue' if control == 6 else 'skip')
controller.handle(snapshot(), (snapshot(),), **kwargs)
assert events.count(control) == 1
def test_unattended_ordinary_dialog_defaults_to_checking_resources(qtbot):
from cbb_refresh_verify.pcb_open_consent import OpenChoice
from cbb_refresh_verify.ui.pcb_open_dialog import PcbOpenDialog
choice = OpenChoice('A', 'lib.lmc', auto_confirm=True)
dialog = PcbOpenDialog(choice)
qtbot.addWidget(dialog)
assert dialog.defaultButton() is dialog.continue_button
dialog.skip_button.click()
assert choice.decision == 'skip'
assert choice.decision_origin == 'user'
def test_unattended_readwrite_checks_actual_shared_database_handle(tmp_path, monkeypatch):
import win32con
import win32file
from cbb_refresh_verify import pcb_open_consent as consent
from cbb_refresh_verify import owner_probe
library = tmp_path/'lib.lmc'
work = tmp_path/'ReusableBlocksLP/A/Work'
project, pcb = work/'A.prj', work/'PCB/A.pcb'
shared = tmp_path/'SymbolLibs/__ReusableBlocksSymb/icdb.dat'
for path in (library, work/'database/icdb.dat', pcb.parent/'Layout/LayoutDB.lyt', shared):
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(b'fixture')
project.write_text('KEY PCBDesignPath "PCB/A.pcb"\nKEY iCDBDir "database"\n')
pcb.write_text('KEY ProjectFile "../A.prj"\n')
owner = {'target': 'bound'}
monkeypatch.setattr(consent, 'validate_owner', lambda *_: owner)
monkeypatch.setattr(owner_probe, 'query_process_snapshot', lambda: [])
def run(attempt, expected_control):
evidence = tmp_path/attempt
evidence.mkdir()
controller = consent.OpenController(dict(root=str(evidence), block_name='A', lmc_file=str(library),
project=str(project), pcb=str(pcb), desktop='CbbVerify_test'), auto_confirm=True)
shown, actions = [], []
def perform(_, action, phase):
actions.append(action['target']['control_id'])
if expected_control == 6:
handle = win32file.CreateFile(str(shared), win32con.GENERIC_READ, 0, None,
win32con.OPEN_EXISTING, 0, None)
handle.Close()
return SimpleNamespace(error_code='', accepted_controls=tuple(actions), detail='', channel='win32_button_click')
options = dict(target_pid=20, launcher_pid=10, worker_pid=5, show=shown.append, perform=perform)
controller.handle(snapshot(), (snapshot(),), **options)
shown[0].choose('continue', origin='timeout_default')
result = controller.handle(snapshot(), (snapshot(),), **options)
assert actions == [expected_control], result.detail
return result, evidence
held = win32file.CreateFile(str(shared), win32con.GENERIC_READ, 0, None,
win32con.OPEN_EXISTING, 0, None)
try:
skipped, evidence = run('occupied', 7)
assert skipped.error_code == 'PCB_OPEN_SKIPPED'
assert str(shared) in skipped.detail
assert not (evidence/'pcb-open-resource-proof.json').exists()
finally:
held.Close()
resumed, evidence = run('released', 6)
assert not resumed.error_code
assert (evidence/'pcb-open-resource-proof.json').is_file()
project.write_text('KEY PCBDesignPath "PCB/A.pcb"\nKEY iCDBDir "../../../outside"\n')
unbound, _ = run('wrong-project-database', 7)
assert 'iCDBDir' in unbound.detail
def test_stop_during_receipt_never_sends_native_yes(tmp_path, monkeypatch):
from cbb_refresh_verify import management
from cbb_refresh_verify import pcb_open_consent as consent
from cbb_refresh_verify.operation_queue import QueueCancelled
stopped = False
original = management._write_json
def write_choice(path, value):
nonlocal stopped
original(path, value)
stopped = True
def check_active():
if stopped:
raise QueueCancelled('cancelled')
monkeypatch.setattr(management, '_write_json', write_choice)
monkeypatch.setattr('cbb_refresh_verify.operation_queue.check_active', check_active)
monkeypatch.setattr(consent, 'validate_owner', lambda *_: {'target': 'bound'})
monkeypatch.setattr(consent, 'resource_guard', lambda *_, **__: nullcontext())
controller = consent.OpenController(dict(root=str(tmp_path), block_name='A', lmc_file='lib.lmc',
project='A.prj', pcb='A.pcb', desktop='CbbVerify_test'), auto_confirm=True)
shown = []
options = dict(target_pid=20, launcher_pid=10, worker_pid=5, show=shown.append,
perform=lambda *_: pytest.fail('sent during cancellation'))
controller.handle(snapshot(), (snapshot(),), **options)
shown[0].choose('continue')
assert controller.handle(snapshot(), (snapshot(),), **options).error_code == 'USER_CANCELLED'