fix: inspect addressless ICDB projects and ask for PCB recovery version

This commit is contained in:
阿白叔 committed 2026-11-03 17:42:33 +08:00
1 parent c85696080d
commit de952a68d6
11 files changed
+558 -22

No files matched your search

+64 -7
View File
@@ -47,21 +47,25 @@ def case(tmp_path, monkeypatch):
@pytest.mark.parametrize('pcb_config', ['standard', 'legacy_template'])
def test_explicit_maintenance_enters_official_repair_once_without_lostsession_fabrication(case, monkeypatch, pcb_config):
@pytest.mark.parametrize('advertisement', ['present', 'absent'])
def test_explicit_maintenance_enters_official_repair_once_without_lostsession_fabrication(case, monkeypatch, pcb_config, advertisement):
from cbb_refresh_verify import verify_runner as runner, native_repair
from test_native_repair import complete_native_success
request, project, address = case
if advertisement == 'absent':
address.unlink()
if pcb_config == 'legacy_template':
(project.parent/'PCB/pcb.prj').rename(project.parent/'PCB/template.prj')
calls = []
def repair(target, root, **kwargs):
calls.append('repair')
assert address.read_bytes() == b'old server address - preserved'
assert kwargs['maintenance_context']['addresses'][str(address.resolve())]['sha256']
# Native boundary fake simulates official removal of its address.
native_repair.backup_project(target, root/'complete-backup')
assert (root/'complete-backup/database/cdbsvr/sAddress.adr').read_bytes() == address.read_bytes()
address.unlink()
if advertisement == 'present':
assert address.read_bytes() == b'old server address - preserved'
assert kwargs['maintenance_context']['addresses'][str(address.resolve())]['sha256']
address.unlink() # Simulated native release, never a production cleanup.
else:
assert kwargs['maintenance_context']['addresses'] == {}
assert target.project == project
return complete_native_success(target)
monkeypatch.setattr(native_repair, 'run_native_repair', repair)
monkeypatch.setattr(native_repair, 'repair_release_state', lambda *a:
@@ -82,6 +86,40 @@ def test_explicit_maintenance_enters_official_repair_once_without_lostsession_fa
assert 'session' not in record['maintenance_context']
def test_addressless_target_binds_unique_project_and_rejects_new_address(case):
from cbb_refresh_verify.maintenance_entry import maintenance_target_guard
request, project, address = case
address.unlink()
with maintenance_target_guard(request) as checked:
context = checked['context']
assert checked['target'].project == project and context['addresses'] == {}
address.write_bytes(b'owner appeared after preflight')
with pytest.raises(ValueError, match='MAINTENANCE_SOURCE_CHANGED'):
with maintenance_target_guard(request, context): pass
@pytest.mark.parametrize('reference', ['', 'KEY ProjectFile "../Other.prj"\n',
'KEY ProjectFile "../IP101GR.prj"\nKEY ProjectFile "../IP101GR.prj"\n'])
def test_addressless_target_requires_exact_pcb_back_reference(case, reference):
from cbb_refresh_verify.maintenance_entry import select_maintenance_target
request, project, address = case
address.unlink()
(project.parent/'PCB/IP101GR.pcb').write_text(reference)
with pytest.raises(ValueError, match='PCB.*ProjectFile'):
select_maintenance_target(request)
def test_addressless_multiple_project_databases_are_not_guessed(case):
from cbb_refresh_verify.maintenance_entry import select_maintenance_target
request, project, address = case
address.unlink()
(project.parent/'PCB/pcb.prj').write_text('KEY iCDBDir "database"\n')
database = project.parent/'PCB/database'; database.mkdir()
(database/'icdb.dat').write_bytes(b'another native database')
with pytest.raises(ValueError, match='多个工程数据库'):
select_maintenance_target(request)
@pytest.mark.parametrize('back_reference', ['', 'KEY ProjectFile "../other.prj"\n',
'KEY ProjectFile "../IP101GR.prj"\nKEY ProjectFile "../IP101GR.prj"\n'])
def test_legacy_maintenance_requires_unambiguous_pcb_back_reference(case, back_reference):
@@ -328,3 +366,22 @@ def test_successful_icdb_repair_then_version_choice_reports_partial_completion(c
assert result.recovery_attempts[0]['native_status'] == 'REPAIRED'
assert result.recovery_attempts[0]['status'] == 'PCB_VERSION_CHOICE_REQUIRED'
assert result.recovery_attempts[0]['validation_passed'] is False
def test_user_chosen_pcb_history_is_not_reported_as_lossless_repair(case, monkeypatch):
from cbb_refresh_verify import native_repair, verify_runner as runner
from test_native_repair import complete_native_success
request, project, address = case
address.unlink()
monkeypatch.setattr(native_repair, 'run_native_repair', lambda target, *a, **k: complete_native_success(target))
monkeypatch.setattr(native_repair, 'repair_release_state', lambda req, target, result: result['release'])
def verify(*a, **k):
root = request.evidence_dir/'verify'; root.mkdir(exist_ok=True)
(root/'pcb-version-restoration.json').write_text(json.dumps({'project': str(project),
'choice': 'last_user_saved', 'date': '2026/9/24 23:06', 'confirm_sent': True, 'historical_restore': True}))
return runner.VerifyResult('PASS', library_flag='GREEN', evidence_path=root/'result.json')
monkeypatch.setattr(runner, '_run_verify_serialized', verify)
result = runner.run_verify(request)
assert result.status == 'PASS'
assert result.recovery_attempts[0]['status'] == 'RESTORED_REVIEW_REQUIRED'
assert result.recovery_attempts[0]['pcb_version']['choice'] == 'last_user_saved'
+132
View File
@@ -0,0 +1,132 @@
from dataclasses import replace
import json
from pathlib import Path
from types import SimpleNamespace
import pytest
from test_pcb_version_choice import captured
from test_post_repair_consent import context, no_native_launch
@pytest.fixture
def session(context, monkeypatch):
from cbb_refresh_verify import post_repair_consent as consent
from cbb_refresh_verify.pcb_restore_prompt import RestoreController
_, _, proof, job = context
consent.prepare_launch(job, ['C:/Mentor/common/win32/bin/ExpeditionPCB.exe', job['pcb'], '-ReusableCircuit'])
monkeypatch.setattr(consent, '_validate_current_processes', lambda *a: None)
snapshot = captured()
controller = RestoreController(job)
prompts, calls = [], []
def perform(snap, payload, phase):
calls.append(payload)
return SimpleNamespace(accepted_controls=(payload['target']['control_id'],),
channel='win32_button_click', error_code='', detail='')
def poll(snap=snapshot, snapshots=None):
return controller.handle(snap, snapshots or (snap,), target_pid=snapshot.pid,
launcher_pid=10, worker_pid=__import__('os').getpid(), companion_pids=(),
show=prompts.append, perform=perform)
return controller, snapshot, prompts, calls, poll, job
def test_waits_for_user_once_and_rechecks_radio_before_confirm(session):
controller, snapshot, prompts, calls, poll, job = session
assert not poll().error_code
poll()
assert len(prompts) == 1 and not calls
prompts[0].choose('last_user_saved')
assert poll().action_sent and calls[-1]['target']['control_id'] == 6213
assert not poll().action_sent and len(calls) == 1
selected = replace(snapshot, 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 snapshot.controls))
assert poll(selected).action_sent and calls[-1]['target']['control_id'] == 1
assert not poll(selected).action_sent and len(calls) == 2
result = json.loads((Path(job['root'])/'pcb-version-restoration.json').read_text(encoding='utf-8'))
assert result['choice'] == 'last_user_saved' and result['date'] == '2026/9/24 23:06'
assert result['historical_restore'] and result['confirm_sent']
def test_cancel_never_selects_or_confirms_a_version(session):
_, _, prompts, calls, poll, _ = session
poll(); prompts[0].choose('cancel')
result = poll()
assert result.error_code == 'PCB_VERSION_CHOICE_REQUIRED'
assert '取消' in result.detail and not calls
@pytest.mark.parametrize('change', ['date', 'pid', 'window', 'extra'])
def test_changed_native_choice_invalidates_user_answer(session, change):
_, snapshot, prompts, calls, poll, _ = session
poll(); prompts[0].choose('last_user_saved')
changed = snapshot
if change == 'date':
changed = replace(snapshot, controls=tuple(replace(c, name=c.name.replace('23:06', '23:07'))
if c.control_id == 6213 else c for c in snapshot.controls))
if change == 'pid': changed = replace(snapshot, pid=snapshot.pid + 1)
if change == 'window': changed = replace(snapshot, hwnd=snapshot.hwnd + 1)
result = poll(changed, (changed, changed) if change == 'extra' else None)
assert result.error_code and not calls
def test_native_action_failure_never_retries_or_confirms(session):
controller, snapshot, prompts, calls, poll, _ = session
poll(); prompts[0].choose('last_user_saved')
def failed(*a):
return SimpleNamespace(accepted_controls=(), channel='', error_code='ACTION_CHANNEL_FAILED', detail='timeout')
result = controller.handle(snapshot, (snapshot,), target_pid=snapshot.pid, launcher_pid=10,
worker_pid=__import__('os').getpid(), companion_pids=(), show=prompts.append, perform=failed)
assert result.error_code == 'ACTION_CHANNEL_FAILED'
assert poll().error_code and not calls
def test_version_dialog_shows_dates_and_explicit_choices(qtbot):
from cbb_refresh_verify.pcb_restore_prompt import RestoreChoice
from cbb_refresh_verify.ui.pcb_restore_dialog import PcbRestoreDialog
from cbb_refresh_verify.dialog_rules import pcb_version_choice
choice = RestoreChoice('Block', 'library.lmc', pcb_version_choice(captured())['candidates'])
dialog = PcbRestoreDialog(choice)
qtbot.addWidget(dialog)
assert '2026/9/24 23:06' in dialog.text()
assert choice.decision is None
dialog.manual_button.click()
assert choice.decision == 'last_user_saved'
def test_closing_version_dialog_is_cancel_not_a_default_selection(qtbot):
from cbb_refresh_verify.pcb_restore_prompt import RestoreChoice
from cbb_refresh_verify.ui.pcb_restore_dialog import PcbRestoreDialog
from cbb_refresh_verify.dialog_rules import pcb_version_choice
choice = RestoreChoice('Block', 'library.lmc', pcb_version_choice(captured())['candidates'])
dialog = PcbRestoreDialog(choice)
qtbot.addWidget(dialog)
dialog.reject()
assert choice.decision == 'cancel'
@pytest.mark.parametrize('change', ['', 'desktop', 'pid', 'date', 'disabled', 'selection', 'channel'])
def test_private_agent_rechecks_live_version_before_confirmation(monkeypatch, change):
import win32gui, win32process
from cbb_refresh_verify.dialog_agent import DialogActionExecutor
from cbb_refresh_verify.dialog_rules import pcb_version_choice
snapshot = replace(captured(), 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 captured().controls))
controls = {c.handle: c for c in snapshot.controls if c.handle and c.class_name in ('Static', 'Button')}
monkeypatch.setattr('cbb_refresh_verify.native_repair_ui._current_desktop_name',
lambda: 'Default' if change == 'desktop' else 'CbbVerify_fixture')
monkeypatch.setattr(win32process, 'GetWindowThreadProcessId', lambda h: (1, snapshot.pid + (change == 'pid')))
monkeypatch.setattr(win32gui, 'GetClassName', lambda h: snapshot.window_class if h == snapshot.hwnd else controls[h].class_name)
monkeypatch.setattr(win32gui, 'GetWindowText', lambda h: snapshot.title if h == snapshot.hwnd else
controls[h].name.replace('23:06', '23:07') if change == 'date' else controls[h].name)
monkeypatch.setattr(win32gui, 'IsWindowVisible', lambda h: True)
monkeypatch.setattr(win32gui, 'IsWindowEnabled', lambda h: not (change == 'disabled' and controls[h].control_id == 6213))
monkeypatch.setattr(win32gui, 'GetDlgCtrlID', lambda h: controls[h].control_id)
monkeypatch.setattr(win32gui, 'EnumChildWindows', lambda h, callback, arg: [callback(c, arg) for c in controls])
monkeypatch.setattr(win32gui, 'SendMessageTimeout', lambda h, *a: int(controls[h].control_id == (6206 if change == 'selection' else 6213)))
calls = []
monkeypatch.setattr(win32gui, 'PostMessage', lambda *a: calls.append(a))
action = {'action': 'user_selected_pcb_version', 'channels': ['uia_invoke' if change == 'channel' else 'win32_button_click'],
'target': {'control_id': 1}, 'pid': snapshot.pid, 'desktop': 'CbbVerify_fixture',
'choice': 'last_user_saved', 'candidates': pcb_version_choice(snapshot)['candidates']}
result = DialogActionExecutor().perform(snapshot, action)
assert bool(result.accepted_controls) is (change == '')
assert len(calls) == (1 if change == '' else 0)