perf: replace automatic backups with manual backup reminders

This commit is contained in:
阿白叔 committed 2026-11-03 16:44:30 +08:00
1 parent 7527800128
commit c85696080d
26 files changed
+385 -102

No files matched your search

+9 -5
View File
@@ -56,7 +56,8 @@ def test_restore_checks_source_in_library_copy_then_opens_actual_target(recovery
retained = list(original.parent.parent.glob('Work.before-restore-*'))
assert len(retained) == 1
assert (retained[0]/'database/icdb.dat').read_bytes() == b'damaged'
assert list(request.evidence_dir.rglob('library-before/target.lmc'))
assert not list(request.evidence_dir.rglob('library-before'))
assert not list(request.evidence_dir.rglob('source-before'))
def test_invalid_source_does_not_touch_target(recovery_files):
@@ -208,14 +209,15 @@ def test_logs_and_unrelated_cbb_changes_after_snapshot_do_not_block_install(reco
assert len(calls) == 2
assert (original.parent/'database/icdb.dat').read_bytes() == b'healthy'
assert (other.parent/'database/icdb.dat').read_bytes() == b'unrelated update'
assert list(request.evidence_dir.rglob('source-before/session.log'))[0].read_bytes() == b'snapshot log'
staged = calls[0].lmc_file.parent/'ReusableBlocksLP/A/Work'
assert (staged/'session.log').read_bytes() == b'snapshot log'
@pytest.mark.parametrize('location,change', [
('source', 'edit'), ('source', 'delete'), ('source', 'add'),
('target', 'delete'), ('target', 'add'), ('cert', 'edit'), ('shared', 'edit'),
])
def test_primary_conflicts_preserve_target_and_complete_recovery_copies(recovery_files, location, change):
def test_primary_conflicts_preserve_target_and_validation_evidence(recovery_files, location, change):
from cbb_refresh_verify.backup_recovery import recover_from_backup
request, original, source = recovery_files
if location == 'source':
@@ -244,8 +246,10 @@ def test_primary_conflicts_preserve_target_and_complete_recovery_copies(recovery
assert len(calls) == 1
assert (original.parent/'database/icdb.dat').read_bytes() == b'damaged'
assert not list(original.parent.parent.glob('Work.before-restore-*'))
assert list(request.evidence_dir.rglob('library-before/target.lmc'))
assert list(request.evidence_dir.rglob('source-before/database/icdb.dat'))
assert list(request.evidence_dir.rglob('library-baseline-manifest.json'))
assert list(request.evidence_dir.rglob('source-manifest.json'))
assert calls[0][0].lmc_file.is_file()
assert not list(request.evidence_dir.rglob('library-before'))
def test_source_conflict_while_preparing_incoming_work_blocks_install(recovery_files, monkeypatch):
+7
View File
@@ -2,6 +2,13 @@ from pathlib import Path
from threading import Event
from cbb_refresh_verify.verify_runner import VerifyRequest, VerifyResult
import pytest
@pytest.fixture(autouse=True)
def accept_manual_backup_reminder(monkeypatch):
from PySide6.QtWidgets import QMessageBox
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes)
def test_backup_dialog_requires_a_project_and_passes_selected_target(qtbot, tmp_path):
+42 -6
View File
@@ -82,17 +82,52 @@ def execute(request, adapter, **kwargs):
return run_management(request, adapter=adapter, idle_check=lambda *_: None, **kwargs)
def test_remove_backup_and_strict_absence(setup):
def test_remove_uses_baseline_without_automatic_library_backup(setup):
request, adapter, _ = setup
result = execute(request, adapter)
assert result.status == 'REMOVED' and result.safe_to_continue
assert (result.evidence_path.parent/'library-before/mentor.lmc').read_bytes() == b'library'
assert (result.evidence_path.parent/'library-before/ReusableBlocksLP/Block/Work/Block.prj').is_file()
assert not (result.evidence_path.parent/'library-before').exists()
assert (result.evidence_path.parent/'library-baseline-manifest.json').is_file()
assert '已备份' not in result.detail
record = json.loads(result.evidence_path.read_text(encoding='utf-8'))
assert record['operation'] == 'remove' and record['partition'] == 'Logical-Physical'
assert record['stage'] == 'complete'
@pytest.mark.parametrize('operation', ['add', 'update', 'remove'])
def test_management_never_copies_target_library(setup, monkeypatch, operation):
import cbb_refresh_verify.management as management
request, adapter, source = setup
real_copy = management.copy_verified
def copy(source_path, destination, **kwargs):
assert Path(source_path).resolve() != request.library.parent.resolve(), 'automatic whole-library backup'
return real_copy(source_path, destination, **kwargs)
monkeypatch.setattr(management, 'copy_verified', copy)
result = execute(replace(request, operation=operation, source=source if operation != 'remove' else None,
name='New' if operation == 'add' else 'Block', auto_verify=False), adapter)
assert result.status == ('REMOVED' if operation == 'remove' else 'UPLOADED')
@pytest.mark.parametrize('relative', ['mentor.lmc', 'SymbolLibs/shared/icdb.dat',
'ReusableBlocksLP/Other/Work/database/icdb.dat'])
def test_manual_backup_policy_still_rejects_external_shared_read_owner(setup, relative):
import win32con, win32file
request, adapter, _ = setup
path = request.library.parent/relative
path.parent.mkdir(parents=True, exist_ok=True)
if not path.exists():
path.write_bytes(b'owned database')
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, win32con.FILE_SHARE_READ, None,
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
try:
result = execute(request, adapter)
assert result.status == 'BLOCKED'
assert not adapter.calls, 'An existing reader must block native writes even without address/process evidence'
assert not list(request.evidence_dir.rglob('library-before'))
finally:
handle.Close()
def test_add_conflict_cannot_overwrite(setup):
request, adapter, source = setup
result = execute(replace(request, operation='add', source=source), adapter)
@@ -123,7 +158,7 @@ def test_add_no_auto_verify_and_reimport_after_remove(setup):
assert result.status == 'UPLOADED'
def test_update_failed_readd_keeps_removed_checkpoint_and_recovery_snapshot(setup):
def test_update_failed_readd_keeps_removed_checkpoint_and_baseline(setup):
request, adapter, source = setup
adapter.fail_add = True
result = execute(replace(request, operation='update', source=source), adapter)
@@ -131,7 +166,8 @@ def test_update_failed_readd_keeps_removed_checkpoint_and_recovery_snapshot(setu
assert adapter.records == []
history = json.loads(result.evidence_path.read_text(encoding='utf-8'))['history']
assert 'removed' in [x['stage'] for x in history]
assert (result.evidence_path.parent/'library-before/mentor.lmc').is_file()
assert (result.evidence_path.parent/'library-baseline-manifest.json').is_file()
assert not (result.evidence_path.parent/'library-before').exists()
@pytest.mark.parametrize('operation', ['remove', 'add'])
@@ -311,7 +347,7 @@ def test_prepared_native_identity_is_required_after_exact_catalog(setup, matched
expected = {'policy': 'native-test', 'logical': 'same', 'physical': 'same'}
def prepare(staged, root, *, original_source):
assert original_source == source and staged.source != source
assert (root/'library-before/mentor.lmc').exists()
assert (root/'library-baseline-manifest.json').exists()
adapter.calls.append('prepare_identity')
return staged, IdentityOutcome(expected, True, 'baseline captured', root)
adapter.prepare_add_transaction = prepare
+6 -5
View File
@@ -42,8 +42,8 @@ def transaction(tmp_path, monkeypatch):
if job['operation'] == 'add':
if state.get('tamper') == 'nonce': job['transaction_nonce'] = 'foreign'
if state.get('tamper') == 'supervisor': job['supervisor_pid'] = -1
if state.get('tamper') == 'backup':
(evidence.parent/'library-before'/library.name).write_bytes(b'corrupted backup')
if state.get('tamper') == 'baseline':
(evidence.parent/'library-baseline-manifest.json').write_text('{}')
if state.get('tamper') == 'source':
(Path(job['source']).parent/'database/icdb.dat').write_bytes(b'changed staged input')
validate_transaction(job, evidence.parent)
@@ -110,13 +110,14 @@ def test_native_registered_but_asset_mismatch_retains_recovery(transaction, corr
assert result.status == 'RECOVERY_REQUIRED' and not result.safe_to_continue
def test_update_readd_failure_preserves_snapshot_and_removed_checkpoint(transaction):
def test_update_readd_failure_preserves_baseline_and_removed_checkpoint(transaction):
root, request, state = transaction
assert execute(root, request).status == 'UPLOADED'
state['fail_add'] = True
result = execute(root, replace(request, operation='update'))
assert result.status == 'RECOVERY_REQUIRED' and not result.safe_to_continue
assert (result.evidence_path.parent/'library-before/ReusableBlocksLP/Block/Work/Source.prj').exists()
assert (result.evidence_path.parent/'library-baseline-manifest.json').exists()
assert not (result.evidence_path.parent/'library-before').exists()
assert 'removed' in [entry['stage'] for entry in json.loads(result.evidence_path.read_text())['history']]
@@ -129,7 +130,7 @@ def test_fixture_grant_cannot_authorize_arbitrary_library(transaction, tmp_path)
assert other.read_bytes() == b'unchanged' and not state['calls']
@pytest.mark.parametrize('tamper', ['nonce', 'supervisor', 'backup', 'source'])
@pytest.mark.parametrize('tamper', ['nonce', 'supervisor', 'baseline', 'source'])
def test_worker_rejects_modified_management_authority_before_add(transaction, tamper):
root, request, state = transaction
state['tamper'] = tamper
+1 -1
View File
@@ -41,7 +41,7 @@ def test_management_dialog_preview_confirmation_and_result_status(qtbot, tmp_pat
qtbot.addWidget(dialog)
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: (confirmations.append(a[2]) or QMessageBox.No))
dialog.execute_button.click()
assert not calls and 'Block' in confirmations[0] and '完整' in confirmations[0]
assert not calls and 'Block' in confirmations[0] and '手动备份' in confirmations[0]
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes)
dialog.execute_button.click()
qtbot.waitUntil(lambda: not dialog.busy)
+51
View File
@@ -0,0 +1,51 @@
from pathlib import Path
import pytest
from PySide6.QtWidgets import QMessageBox
@pytest.mark.parametrize('operation', ['add', 'update', 'remove'])
def test_management_prompts_for_manual_backup_and_cancel_starts_nothing(qtbot, tmp_path, monkeypatch, operation):
from cbb_refresh_verify.management import ManagementRequest
from cbb_refresh_verify.ui.management_dialog import ManagementDialog
source = tmp_path/'Block.prj'; source.touch()
seen, calls = [], []
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: (seen.append(a[2]) or QMessageBox.No))
dialog = ManagementDialog([ManagementRequest(operation, tmp_path/'lib.lmc', 'Block', source=source)],
runner=lambda *a, **k: calls.append(a))
qtbot.addWidget(dialog)
dialog.execute_button.click()
assert not calls and not dialog.busy
assert len(seen) == 1 and '手动备份' in seen[0] and '不会自动备份' in seen[0]
assert '完整备份与检查点' not in seen[0]
@pytest.mark.parametrize('action', ['verify_all', 'verify_selected', 'repair_icdb_all'])
def test_batch_prompts_once_for_manual_backup_and_cancel_does_not_start(qtbot, tmp_path, monkeypatch, action):
from cbb_refresh_verify.ui.main_window import MainWindow
from cbb_refresh_verify.models import CbbRecord, LibraryReadResult
window = MainWindow(reader=lambda _: LibraryReadResult((CbbRecord('Block', 'LP'),)), data_root=tmp_path)
qtbot.addWidget(window)
window.lmc_edit.setText('library.lmc'); window.load_library()
qtbot.waitUntil(lambda: not window.busy)
window.select_visible_button.click()
seen, calls = [], []
monkeypatch.setattr(window, '_run', lambda *a, **k: calls.append(a))
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: (seen.append(a[2]) or QMessageBox.No))
getattr(window, action)()
assert not calls
assert len(seen) == 1 and '手动备份' in seen[0] and '不会自动备份' in seen[0]
def test_restore_prompts_for_manual_backup_before_starting_worker(qtbot, tmp_path, monkeypatch):
from cbb_refresh_verify.verify_runner import VerifyRequest, VerifyResult
from cbb_refresh_verify.ui.backup_recovery_dialog import BackupRecoveryDialog
calls, seen = [], []
source = tmp_path/'Block.prj'; source.touch()
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: (seen.append(a[2]) or QMessageBox.No))
dialog = BackupRecoveryDialog(['Block'], lambda n: VerifyRequest(tmp_path/'lib.lmc', n, tmp_path/'out'),
recoverer=lambda *a, **k: (calls.append(a) or VerifyResult('PASS')))
qtbot.addWidget(dialog)
dialog.source_edit.setText(str(source)); dialog.restore_button.click()
qtbot.waitUntil(lambda: not dialog.busy)
assert not calls
assert len(seen) == 1 and '手动备份' in seen[0] and '不会自动备份' in seen[0]
+30 -6
View File
@@ -234,7 +234,7 @@ def test_retained_importer_blocks_repair_even_without_an_open_database_handle(tm
assert 'IMPORTER_RELEASE_UNCONFIRMED' in outcome['detail']
def test_repair_cancellation_during_backup_prevents_native_launch(tmp_path, monkeypatch):
def test_repair_cancellation_during_access_check_prevents_native_launch(tmp_path, monkeypatch):
from cbb_refresh_verify import native_repair_ui as ui, native_repair, mentor_adapter
request, record, target = target_fixture(tmp_path)
root = tmp_path/'worker'
@@ -251,15 +251,15 @@ def test_repair_cancellation_during_backup_prevents_native_launch(tmp_path, monk
monkeypatch.setattr(ui, '_repair_command', lambda *_: 32924)
monkeypatch.setattr(mentor_adapter, 'pcb_processes', lambda: [])
monkeypatch.setattr(mentor_adapter, '_process_details', lambda *_: [])
def backup(*a):
assert calls == ['watchdog'], 'Watch supervisor before the potentially long backup'
def check(*a):
assert calls == ['watchdog'], 'Watch supervisor before filesystem checks'
cancel.touch()
calls.append('backup')
monkeypatch.setattr(native_repair, 'backup_project', backup)
calls.append('check')
monkeypatch.setattr(native_repair, 'check_repair_access', check)
monkeypatch.setattr(ui.subprocess, 'Popen', lambda *a, **kw: pytest.fail('Repair must not start'))
assert ui.repair_worker_main(job) == 1
outcome = json.loads((root/'repair-result.json').read_text('utf-8'))
assert 'REPAIR_CANCELLED_AFTER_BACKUP' in outcome['detail']
assert 'REPAIR_CANCELLED_BEFORE_LAUNCH' in outcome['detail']
def test_repair_worker_refuses_the_input_desktop_before_backup(tmp_path, monkeypatch):
@@ -425,6 +425,30 @@ def test_native_worker_preserves_success_and_historical_restore_distinction(tmp_
assert native_success_confirmed(target, result) is (scenario == 'success')
def test_repair_skips_application_backup_but_keeps_native_repair_backup(tmp_path, monkeypatch):
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'success')
monkeypatch.setattr('cbb_refresh_verify.native_repair.backup_project',
lambda *a: pytest.fail('application project backup must not run'))
assert ui.repair_worker_main(job) == 0
result = json.loads((root/'repair-result.json').read_text('utf-8'))
assert result['evidence']['native_backup'] is True
assert not (root/'complete-backup').exists()
def test_repair_without_application_backup_still_rejects_busy_database(tmp_path, monkeypatch):
import win32con, win32file
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'success')
database = Path(json.loads(job.read_text())['database'])/'icdb.dat'
handle = win32file.CreateFile(str(database), win32con.GENERIC_READ, 0, None,
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
try:
monkeypatch.setattr(ui.subprocess, 'Popen', lambda *a, **kw: pytest.fail('busy database launched'))
assert ui.repair_worker_main(job) == 1
assert 'REPAIR_DATABASE_IN_USE' in json.loads((root/'repair-result.json').read_text())['detail']
finally:
handle.Close()
def test_native_busy_project_on_load_never_invokes_repair(tmp_path, monkeypatch):
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'busy_before')
assert ui.repair_worker_main(job) == 1
+2
View File
@@ -25,6 +25,8 @@ def fake_reader(_): return LibraryReadResult((CbbRecord('CBB1','Reusable Blocks'
@pytest.fixture(autouse=True)
def isolate_authoritative_native_refresh(monkeypatch):
from PySide6.QtWidgets import QMessageBox
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes)
# Production refresh crosses the native Mentor boundary; these are UI tests.
monkeypatch.setattr('cbb_refresh_verify.ui.main_window.authoritative_status_map',
lambda names, *_: {name: 'READY' for name in names})
+1
View File
@@ -24,6 +24,7 @@ MIXED = (
def load_window(qtbot, tmp_path, monkeypatch, records=MIXED, **kwargs):
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes)
import cbb_refresh_verify.ui.main_window as ui
monkeypatch.setattr(ui, 'preflight_skip_reason',
lambda _, name: 'missing project' if name == 'Missing' else None)
+9
View File
@@ -54,6 +54,15 @@ def test_missing_cert_cannot_block_saved_and_closed_worker(tmp_path, monkeypatch
assert any(e['stage'] == 'cert_diagnostics' and e['non_blocking'] for e in events)
def test_verify_does_not_create_automatic_project_backup(tmp_path, monkeypatch):
job, events, execute = exercise_worker(tmp_path, monkeypatch)
monkeypatch.setattr(adapter, 'best_effort_backup',
lambda *a, **kw: pytest.fail('automatic project backup must not run'))
assert execute()['status'] == 'PASS'
assert not (Path(job['root'])/'backup').exists()
assert any(e['stage'] == 'backup_skipped' and e['reason'] == 'manual_backup_policy' for e in events)
def test_cert_diagnostic_io_failure_is_nonblocking(tmp_path, monkeypatch):
from cbb_refresh_verify.mentor_adapter import collect_cert_evidence
original = Path.stat