feat: integrate native diagnostics and coordinated CBB transactions
This commit is contained in:
1 parent
9e230e1a46
commit
da67de026f
91 files changed
+14370
-435
No files matched your search
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"source": "Frozen b90a9bb native startup capture: no-history-repair/repair-result.json; HWNDs sanitized. Auxiliary classes/empty titles from coordinator's readback of the same owned native process.",
|
||||
"startup_shell": {
|
||||
"hwnd": 100,
|
||||
"title": "iCDB Project Backup",
|
||||
"class": "Afx:00400000:b:00010003:00000006:5F991B0D",
|
||||
"enabled": true,
|
||||
"children": [
|
||||
{"hwnd": 401, "text": "", "class": "BCGPSlider:400000:8:10003:10", "id": -1, "enabled": true},
|
||||
{"hwnd": 402, "text": "Output ", "class": "BCGPControlBar:400000:8:10003:10", "id": 313, "enabled": true},
|
||||
{"hwnd": 403, "text": "", "class": "#32770", "id": 0, "enabled": true},
|
||||
{"hwnd": 400, "text": "", "class": "RichEdit20A", "id": 1002, "enabled": true},
|
||||
{"hwnd": 404, "text": "", "class": "BCGPStatusBar:400000:8:10003:10", "id": 59393, "enabled": true},
|
||||
{"hwnd": 405, "text": "", "class": "BCGPDockBar:400000:8:10003:10", "id": 59419, "enabled": true},
|
||||
{"hwnd": 406, "text": "Standard", "class": "BCGPToolBar:400000:8:10003:10", "id": 59392, "enabled": true},
|
||||
{"hwnd": 407, "text": "Menu Bar", "class": "BCGPToolBar:400000:8:10003:10", "id": 59398, "enabled": true},
|
||||
{"hwnd": 408, "text": "", "class": "#32770", "id": 59648, "enabled": true}
|
||||
]
|
||||
},
|
||||
"auxiliary_windows": [
|
||||
{"hwnd": 500, "title": "", "class": "UAC_InputIndicatorOverlayWnd", "enabled": true, "children": []},
|
||||
{"hwnd": 501, "title": "", "class": "UAC Input Indicator", "enabled": true, "children": []}
|
||||
],
|
||||
"loaded_title_prefix": "iCDB Project Backup - ",
|
||||
"loaded_output": "Checking if project is in use.\r\nProject is not in use. Full iCDB Project Backup's functionality is available.\r\n"
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"source": "Issue 2 data.zip, verify-86f90ffba911; selected fields only; paths and process identities sanitized",
|
||||
"limitations": "Logs only. No field database, executable fault reproduction or recovery claim.",
|
||||
"block": "1GPHY_8211",
|
||||
"diagnosis": {
|
||||
"error_code": "ICDB_REPAIR_REQUIRED",
|
||||
"scope": "project",
|
||||
"machine": "FIELD-PC",
|
||||
"session": "2026-10-20 14.03.54-18212",
|
||||
"database_relative": "Work/database"
|
||||
},
|
||||
"native_error": "The last server session on different server machine lost the connection to the database. Please use iCDB Project Backup 'Repair project' functionality to fix this issue. (Machine:[FIELD-PC] Path:[<library>/ReusableBlocksLP/1GPHY_8211/Work/database] session:[2026-10-20 14.03.54-18212])",
|
||||
"observed_events": [
|
||||
{"stage": "pcb_launch", "strategy": "reusable_circuit_direct"},
|
||||
{"stage": "pcb_launcher_started", "launcher_pid": 11},
|
||||
{"stage": "pcb_worker_started", "pcb_pid": 12, "binding": "commandline"},
|
||||
{"stage": "native_failure_logs"},
|
||||
{"stage": "process_retained", "safe_to_continue": false},
|
||||
{"stage": "failed", "error": "VERIFY_CANCELLED: stop and normally close target document"}
|
||||
],
|
||||
"dialog": {
|
||||
"pid": 12,
|
||||
"phase": "PCB_STARTING",
|
||||
"action": "acknowledge_fatal",
|
||||
"error_code": "MENTOR_DATABASE_LOAD_FAILED",
|
||||
"text": "Problem encountered while opening one of the database files. See PCBLogFile.txt for details. Loading of the job has failed. Do you wish to view the log file now?"
|
||||
},
|
||||
"original_result": {"status": "FAIL", "error_category": "ICDB_REPAIR_REQUIRED", "error_stage": "PCB_STARTING"},
|
||||
"original_repair": {"status": "BLOCKED", "detail": "REPAIR_DATABASE_IN_USE"}
|
||||
}
|
||||
+183
@@ -0,0 +1,183 @@
|
||||
{
|
||||
"hwnd": 100,
|
||||
"pid": 20,
|
||||
"process_name": "ExpeditionPCB.exe",
|
||||
"process_role": "pcb",
|
||||
"window_class": "#32770",
|
||||
"title": "Database Restoration",
|
||||
"phase": "PCB_STARTING",
|
||||
"controls": [
|
||||
{
|
||||
"handle": 101,
|
||||
"control_id": 65535,
|
||||
"class_name": "Static",
|
||||
"name": "",
|
||||
"automation_id": "65535",
|
||||
"control_type": "Image",
|
||||
"enabled": true,
|
||||
"selected": false,
|
||||
"checked": false,
|
||||
"patterns": []
|
||||
},
|
||||
{
|
||||
"handle": 102,
|
||||
"control_id": 6208,
|
||||
"class_name": "Static",
|
||||
"name": "The system has detected this design abnormally terminated the last time it was used. The user has to decide what database (if any) to associate with the design.",
|
||||
"automation_id": "6208",
|
||||
"control_type": "Text",
|
||||
"enabled": true,
|
||||
"selected": false,
|
||||
"checked": false,
|
||||
"patterns": []
|
||||
},
|
||||
{
|
||||
"handle": 103,
|
||||
"control_id": 6212,
|
||||
"class_name": "Button",
|
||||
"name": "Restore Database",
|
||||
"automation_id": "6212",
|
||||
"control_type": "Group",
|
||||
"enabled": true,
|
||||
"selected": false,
|
||||
"checked": false,
|
||||
"patterns": []
|
||||
},
|
||||
{
|
||||
"handle": 104,
|
||||
"control_id": 6213,
|
||||
"class_name": "Button",
|
||||
"name": "Load the last user saved database dated 2026/9/24 23:06.",
|
||||
"automation_id": "6213",
|
||||
"control_type": "RadioButton",
|
||||
"enabled": true,
|
||||
"selected": false,
|
||||
"checked": false,
|
||||
"patterns": [
|
||||
"Invoke",
|
||||
"SelectionItem"
|
||||
]
|
||||
},
|
||||
{
|
||||
"handle": 105,
|
||||
"control_id": 6206,
|
||||
"class_name": "Button",
|
||||
"name": "Load the autosave database dated 2026/9/24 23:06.",
|
||||
"automation_id": "6206",
|
||||
"control_type": "RadioButton",
|
||||
"enabled": true,
|
||||
"selected": true,
|
||||
"checked": true,
|
||||
"patterns": [
|
||||
"Invoke",
|
||||
"SelectionItem"
|
||||
]
|
||||
},
|
||||
{
|
||||
"handle": 106,
|
||||
"control_id": 6207,
|
||||
"class_name": "Static",
|
||||
"name": "This will restore the design to the last autosave state.",
|
||||
"automation_id": "6207",
|
||||
"control_type": "Text",
|
||||
"enabled": true,
|
||||
"selected": false,
|
||||
"checked": false,
|
||||
"patterns": []
|
||||
},
|
||||
{
|
||||
"handle": 107,
|
||||
"control_id": 6209,
|
||||
"class_name": "Static",
|
||||
"name": "This will restore the design to the data from the last user save.",
|
||||
"automation_id": "6209",
|
||||
"control_type": "Text",
|
||||
"enabled": true,
|
||||
"selected": false,
|
||||
"checked": false,
|
||||
"patterns": []
|
||||
},
|
||||
{
|
||||
"handle": 108,
|
||||
"control_id": 6210,
|
||||
"class_name": "Static",
|
||||
"name": "Autosaved changes will be lost.",
|
||||
"automation_id": "6210",
|
||||
"control_type": "Text",
|
||||
"enabled": true,
|
||||
"selected": false,
|
||||
"checked": false,
|
||||
"patterns": []
|
||||
},
|
||||
{
|
||||
"handle": 109,
|
||||
"control_id": 6211,
|
||||
"class_name": "Static",
|
||||
"name": "* Cancelling will load no design.",
|
||||
"automation_id": "6211",
|
||||
"control_type": "Text",
|
||||
"enabled": true,
|
||||
"selected": false,
|
||||
"checked": false,
|
||||
"patterns": []
|
||||
},
|
||||
{
|
||||
"handle": 110,
|
||||
"control_id": 1,
|
||||
"class_name": "Button",
|
||||
"name": "OK",
|
||||
"automation_id": "1",
|
||||
"control_type": "Button",
|
||||
"enabled": true,
|
||||
"selected": false,
|
||||
"checked": false,
|
||||
"patterns": [
|
||||
"Invoke"
|
||||
]
|
||||
},
|
||||
{
|
||||
"handle": 111,
|
||||
"control_id": 2,
|
||||
"class_name": "Button",
|
||||
"name": "Cancel",
|
||||
"automation_id": "2",
|
||||
"control_type": "Button",
|
||||
"enabled": true,
|
||||
"selected": false,
|
||||
"checked": false,
|
||||
"patterns": [
|
||||
"Invoke"
|
||||
]
|
||||
},
|
||||
{
|
||||
"handle": 100,
|
||||
"control_id": 0,
|
||||
"class_name": "#32770",
|
||||
"name": "Database Restoration",
|
||||
"automation_id": "",
|
||||
"control_type": "Window",
|
||||
"enabled": true,
|
||||
"selected": false,
|
||||
"checked": false,
|
||||
"patterns": [
|
||||
"Window"
|
||||
]
|
||||
},
|
||||
{
|
||||
"handle": 0,
|
||||
"control_id": 0,
|
||||
"class_name": "",
|
||||
"name": "",
|
||||
"automation_id": "",
|
||||
"control_type": "TitleBar",
|
||||
"enabled": true,
|
||||
"selected": false,
|
||||
"checked": false,
|
||||
"patterns": [
|
||||
"Value"
|
||||
]
|
||||
}
|
||||
],
|
||||
"owner_hwnd": 90,
|
||||
"diagnostics": []
|
||||
}
|
||||
@@ -69,7 +69,7 @@ def test_crashed_worker_cannot_pass_even_with_pass_file(tmp_path, monkeypatch, o
|
||||
pytest.fail('A crashed writer must not become PASS via a pre-existing READY flag')
|
||||
result = run_verify(request(tmp_path), port_check=lambda: (True, ''), flag_reader=must_not_query)
|
||||
assert result.status == 'FAIL'
|
||||
assert result.safe_to_continue is False
|
||||
assert result.safe_to_continue is True # Proven release permits another item; crash stays FAIL.
|
||||
|
||||
|
||||
def test_supervisor_crash_stops_registered_save_helper_but_not_native(tmp_path):
|
||||
|
||||
@@ -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):
|
||||
@@ -143,10 +144,68 @@ def test_idle_guard_queries_supported_native_process_names(recovery_files, monke
|
||||
queries.append(query)
|
||||
return []
|
||||
monkeypatch.setattr(win32com.client, 'GetObject', lambda _: EmptyProcesses())
|
||||
from cbb_refresh_verify import owner_probe
|
||||
import subprocess
|
||||
monkeypatch.setattr(owner_probe.subprocess, 'run', lambda command, **kw:
|
||||
subprocess.CompletedProcess(command, owner_probe.owner_probe_main(command[-1])))
|
||||
_idle_check(request.lmc_file, original, original.parent/'PCB/A.pcb')
|
||||
assert any("Name='viewdraw.exe'" in query for query in queries)
|
||||
|
||||
|
||||
def test_idle_guard_ignores_unrelated_project_and_prefix_sibling(recovery_files, monkeypatch):
|
||||
from cbb_refresh_verify.backup_recovery import _idle_check
|
||||
from cbb_refresh_verify import mentor_adapter
|
||||
request, original, _ = recovery_files
|
||||
unrelated = original.parent.with_name(original.parent.name+'Old')/'PCB/A.pcb'
|
||||
monkeypatch.setattr(mentor_adapter, 'pcb_processes', lambda: [(123, '', str(unrelated))])
|
||||
monkeypatch.setattr(mentor_adapter, '_process_details', lambda name:
|
||||
[(123, 'ExpeditionPCB.exe', f'ExpeditionPCB.exe "{unrelated}" -ReusableCircuit', 0)]
|
||||
if name == 'ExpeditionPCB.exe' else [])
|
||||
_idle_check(request.lmc_file, original, original.parent/'PCB/A.pcb')
|
||||
|
||||
|
||||
def test_idle_guard_rejects_exact_target_process(recovery_files, monkeypatch):
|
||||
from cbb_refresh_verify.backup_recovery import _idle_check
|
||||
from cbb_refresh_verify import mentor_adapter
|
||||
request, original, _ = recovery_files
|
||||
target = original.parent/'PCB/A.pcb'
|
||||
monkeypatch.setattr(mentor_adapter, 'pcb_processes', lambda: [])
|
||||
monkeypatch.setattr(mentor_adapter, '_process_details', lambda name:
|
||||
[(123, 'ExpeditionPCB.exe', f'ExpeditionPCB.exe "{target}" -ReusableCircuit', 0)]
|
||||
if name == 'ExpeditionPCB.exe' else [])
|
||||
with pytest.raises(ValueError, match='TARGET_NATIVE_OWNER_ACTIVE'):
|
||||
_idle_check(request.lmc_file, original, target)
|
||||
|
||||
|
||||
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
|
||||
def reject(*args): raise ValueError('target unavailable before launch')
|
||||
result = recover_from_backup(request, source, idle_check=reject,
|
||||
verifier=lambda *a, **k: pytest.fail('prelaunch rejection must not start native'))
|
||||
assert result.status == 'BLOCKED'
|
||||
assert result.safe_to_continue
|
||||
|
||||
|
||||
def test_report_write_failure_does_not_lose_prelaunch_release_fact(recovery_files, monkeypatch):
|
||||
from cbb_refresh_verify.backup_recovery import recover_from_backup
|
||||
import win32event
|
||||
from uuid import uuid4
|
||||
create_mutex = win32event.CreateMutex
|
||||
monkeypatch.setattr(win32event, 'CreateMutex', lambda security, owned, name:
|
||||
create_mutex(security, owned, name+'-test-'+uuid4().hex))
|
||||
request, _, source = recovery_files
|
||||
original_write = Path.write_text
|
||||
def write(path, *args, **kwargs):
|
||||
if path.name == 'recovery-result.json': raise OSError('report disk unavailable')
|
||||
return original_write(path, *args, **kwargs)
|
||||
monkeypatch.setattr(Path, 'write_text', write)
|
||||
def reject(*args): raise ValueError('prelaunch unavailable')
|
||||
result = recover_from_backup(request, source, idle_check=reject)
|
||||
assert result.status == 'BLOCKED' and result.safe_to_continue
|
||||
assert 'report disk unavailable' in result.stderr
|
||||
|
||||
|
||||
def test_copy_refuses_directory_junction_before_copying(tmp_path):
|
||||
import subprocess
|
||||
from cbb_refresh_verify.backup_recovery import _copy_verified
|
||||
@@ -188,3 +247,144 @@ def test_equivalent_library_reference_preserves_native_project_bytes_and_date(re
|
||||
before = original.read_bytes(), original.stat().st_mtime_ns
|
||||
_align_library(original, original.parent/'PCB/A.pcb', request.lmc_file)
|
||||
assert (original.read_bytes(), original.stat().st_mtime_ns) == before
|
||||
|
||||
|
||||
def test_logs_and_unrelated_cbb_changes_after_snapshot_do_not_block_install(recovery_files):
|
||||
from cbb_refresh_verify.backup_recovery import recover_from_backup
|
||||
request, original, source = recovery_files
|
||||
(source.parent/'session.log').write_bytes(b'snapshot log')
|
||||
other = project(request.lmc_file.parent/'ReusableBlocksLP/B/Work', 'B', b'unrelated')
|
||||
calls = []
|
||||
def verify(req, **kwargs):
|
||||
calls.append(req)
|
||||
if len(calls) == 1:
|
||||
(source.parent/'session.log').write_bytes(b'updated source log')
|
||||
(original.parent/'new.log').write_bytes(b'new target log')
|
||||
(other.parent/'database/icdb.dat').write_bytes(b'unrelated update')
|
||||
return VerifyResult('PASS', library_flag='GREEN')
|
||||
result = recover_from_backup(request, source, verifier=verify, idle_check=lambda *_: None)
|
||||
assert result.status == 'PASS'
|
||||
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'
|
||||
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_validation_evidence(recovery_files, location, change):
|
||||
from cbb_refresh_verify.backup_recovery import recover_from_backup
|
||||
request, original, source = recovery_files
|
||||
if location == 'source':
|
||||
conflict = source.parent/'database/icdb.dat'
|
||||
elif location == 'target':
|
||||
conflict = original.parent/'PCB/Layout/LayoutDB.lyt'
|
||||
elif location == 'cert':
|
||||
conflict = original.parent.parent/'Cert/A.prj'
|
||||
else:
|
||||
conflict = request.lmc_file.parent/'SymbolLibs/__ReusableBlocksSymb/icdb.dat'
|
||||
conflict.parent.mkdir(parents=True, exist_ok=True)
|
||||
if location in ('cert', 'shared'):
|
||||
conflict.write_bytes(b'before')
|
||||
calls = []
|
||||
def verify(*args, **kwargs):
|
||||
calls.append(args)
|
||||
if change == 'delete':
|
||||
conflict.unlink()
|
||||
elif change == 'add':
|
||||
(conflict.parent/'new-engineering.bin').write_bytes(b'new')
|
||||
else:
|
||||
conflict.write_bytes(b'concurrent edit')
|
||||
return VerifyResult('PASS', library_flag='GREEN')
|
||||
result = recover_from_backup(request, source, verifier=verify, idle_check=lambda *_: None)
|
||||
assert result.status == 'BLOCKED'
|
||||
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-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):
|
||||
from cbb_refresh_verify import backup_recovery as recovery
|
||||
request, original, source = recovery_files
|
||||
copy = recovery._copy_verified
|
||||
def copy_then_change_source(src, dst, **kwargs):
|
||||
result = copy(src, dst, **kwargs)
|
||||
if dst.name.startswith('Work.restore-'):
|
||||
(source.parent/'database/icdb.dat').write_bytes(b'late concurrent change')
|
||||
return result
|
||||
monkeypatch.setattr(recovery, '_copy_verified', copy_then_change_source)
|
||||
result = recovery.recover_from_backup(request, source,
|
||||
verifier=lambda *a, **k: VerifyResult('PASS', library_flag='GREEN'), idle_check=lambda *_: None)
|
||||
assert result.status == 'BLOCKED'
|
||||
assert (original.parent/'database/icdb.dat').read_bytes() == b'damaged'
|
||||
|
||||
|
||||
def test_source_address_record_is_rechecked_after_validation(recovery_files):
|
||||
from cbb_refresh_verify.backup_recovery import recover_from_backup
|
||||
request, original, source = recovery_files
|
||||
address = source.parent/'database/cdbsvr/sAddress.adr'
|
||||
def idle(library, project, pcb):
|
||||
if project == source and address.exists():
|
||||
raise ValueError('Source database ownership is still active')
|
||||
def verify(*args, **kwargs):
|
||||
address.parent.mkdir(parents=True, exist_ok=True)
|
||||
address.write_bytes(b'live owner')
|
||||
return VerifyResult('PASS', library_flag='GREEN')
|
||||
result = recover_from_backup(request, source, verifier=verify, idle_check=idle)
|
||||
assert result.status == 'BLOCKED'
|
||||
assert 'ownership' in result.stderr
|
||||
assert address.read_bytes() == b'live owner'
|
||||
assert (original.parent/'database/icdb.dat').read_bytes() == b'damaged'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('name', ['Logs', 'tEmP', 'bAcKuP', 'Output'])
|
||||
@pytest.mark.parametrize('role', ['Work', 'Cert'])
|
||||
def test_cbb_names_matching_runtime_labels_do_not_hide_target_conflicts(tmp_path, monkeypatch, name, role):
|
||||
from cbb_refresh_verify.backup_recovery import recover_from_backup
|
||||
monkeypatch.setattr(Path, 'home', lambda: tmp_path/'profile')
|
||||
library = tmp_path/'target/target.lmc'
|
||||
original = project(library.parent/f'ReusableBlocksLP/{name}/Work', name, b'damaged')
|
||||
library.write_bytes(b'library')
|
||||
source = project(tmp_path/'backup/Work', name, b'healthy')
|
||||
request = VerifyRequest(library, name, tmp_path/'evidence')
|
||||
conflict = original.parent.parent/role/'database/icdb.dat'
|
||||
conflict.parent.mkdir(parents=True, exist_ok=True)
|
||||
if role == 'Cert':
|
||||
conflict.write_bytes(b'cert before')
|
||||
calls = []
|
||||
def verify(*args, **kwargs):
|
||||
calls.append(args)
|
||||
conflict.write_bytes(b'concurrent target edit')
|
||||
return VerifyResult('PASS', library_flag='GREEN')
|
||||
result = recover_from_backup(request, source, verifier=verify, idle_check=lambda *_: None)
|
||||
assert result.status == 'BLOCKED'
|
||||
assert len(calls) == 1
|
||||
assert conflict.read_bytes() == b'concurrent target edit'
|
||||
assert not list(original.parent.parent.glob('Work.before-restore-*'))
|
||||
|
||||
|
||||
@pytest.mark.parametrize('relative', ['SymbolLibs/temp/icdb.dat', 'SymbolLibs/Temp_a/device.sym',
|
||||
'SharedDependency/hdl/Logs/design.v'])
|
||||
def test_shared_partition_engineering_conflicts_block_install(recovery_files, relative):
|
||||
from cbb_refresh_verify.backup_recovery import recover_from_backup
|
||||
request, original, source = recovery_files
|
||||
conflict = request.lmc_file.parent/relative
|
||||
conflict.parent.mkdir(parents=True, exist_ok=True)
|
||||
conflict.write_bytes(b'shared before')
|
||||
calls = []
|
||||
def verify(*args, **kwargs):
|
||||
calls.append(args)
|
||||
conflict.write_bytes(b'concurrent shared edit')
|
||||
return VerifyResult('PASS', library_flag='GREEN')
|
||||
result = recover_from_backup(request, source, verifier=verify, idle_check=lambda *_: None)
|
||||
assert result.status == 'BLOCKED'
|
||||
assert len(calls) == 1
|
||||
assert (original.parent/'database/icdb.dat').read_bytes() == b'damaged'
|
||||
assert conflict.read_bytes() == b'concurrent shared edit'
|
||||
@@ -0,0 +1,258 @@
|
||||
"""Only live clients stop a batch; native writes are replaced by fixtures."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
from threading import Event
|
||||
|
||||
import pytest
|
||||
|
||||
from cbb_refresh_verify import verify_runner as runner
|
||||
from test_verify_runner import fixture, request, PORTS_OK
|
||||
|
||||
|
||||
@pytest.mark.parametrize('status,detail', [('FAIL', 'UNKNOWN_DIALOG: native prompt'),
|
||||
('TIMEOUT', 'native operation timed out')])
|
||||
@pytest.mark.parametrize('released', [True, False])
|
||||
def test_batch_continuation_follows_actual_release(tmp_path, monkeypatch, status, detail, released):
|
||||
fixture(tmp_path)
|
||||
launches = []
|
||||
class Worker:
|
||||
desktop = None
|
||||
returncode = 1
|
||||
def __init__(self, command, *_a, **_k):
|
||||
launches.append(command)
|
||||
Path(command[-1]).with_name('outcome.json').write_text(json.dumps({
|
||||
'status': status, 'stderr': detail, 'safe_to_continue': False}))
|
||||
def poll(self): return 1
|
||||
def close(self): pass
|
||||
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', Worker)
|
||||
monkeypatch.setattr(runner, '_cleanup_session_processes', lambda *a, **k:
|
||||
{'safe_to_continue': released, 'remaining_pids': [] if released else [123]})
|
||||
monkeypatch.setattr('cbb_refresh_verify.verify_diagnostics.capture_failure_logs_with_timeout', lambda *_: None)
|
||||
req = request(tmp_path)
|
||||
try:
|
||||
results = runner.run_batch([req, req], verifier=lambda r: runner.run_verify(r, port_check=PORTS_OK))
|
||||
assert results[0].status == status and results[0].safe_to_continue is released
|
||||
assert len(launches) == (2 if released else 1)
|
||||
assert results[1].status == (status if released else 'SKIPPED')
|
||||
finally:
|
||||
from cbb_refresh_verify import library_lock as locks
|
||||
with locks._guard:
|
||||
owner = locks._owners.pop(locks.LibraryLock(req.lmc_file).key, None)
|
||||
if owner: owner['handle'].Close()
|
||||
|
||||
|
||||
def test_item_failure_with_confirmed_release_does_not_stop_unrelated_items(tmp_path):
|
||||
from cbb_refresh_verify.verify_runner import VerifyRequest, VerifyResult
|
||||
library = tmp_path/'library.lmc'; library.touch()
|
||||
requests = [VerifyRequest(library, name, tmp_path/'evidence') for name in ('A', 'B')]
|
||||
calls = []
|
||||
def verify(request):
|
||||
calls.append(request.block_name)
|
||||
return VerifyResult('FAIL' if request.block_name == 'A' else 'PASS',
|
||||
stderr='单项失败但会话已释放' if request.block_name == 'A' else '',
|
||||
safe_to_continue=True)
|
||||
results = runner.run_batch(requests, verifier=verify)
|
||||
assert calls == ['A', 'B']
|
||||
assert [result.status for result in results] == ['FAIL', 'PASS']
|
||||
|
||||
|
||||
def test_stop_worker_escalates_only_after_cooperative_deadline():
|
||||
calls = []
|
||||
class Worker:
|
||||
stopped = False
|
||||
def request_stop(self): calls.append('cancel')
|
||||
def wait(self, timeout=5):
|
||||
calls.append('wait')
|
||||
if not self.stopped: raise TimeoutError()
|
||||
def kill(self): calls.append('client_stop'); self.stopped = True
|
||||
def poll(self): return 1 if self.stopped else None
|
||||
assert runner._stop_worker(Worker(), timeout=.1) is True
|
||||
assert calls == ['cancel', 'wait', 'client_stop', 'wait']
|
||||
|
||||
|
||||
def test_cancel_reaches_current_supervised_worker(tmp_path, monkeypatch):
|
||||
fixture(tmp_path)
|
||||
stop = Event()
|
||||
cancelled = []
|
||||
class Worker:
|
||||
desktop = None
|
||||
returncode = None
|
||||
def __init__(self, command, *_a, **_k):
|
||||
self.job = json.loads(Path(command[-1]).read_text('utf-8'))
|
||||
stop.set()
|
||||
def bind_cancellation(self, path): self.cancel = Path(path)
|
||||
def request_stop(self):
|
||||
self.cancel.touch(); cancelled.append(self.cancel)
|
||||
self.returncode = 1
|
||||
def wait(self, **_k): return 1
|
||||
def poll(self): return self.returncode
|
||||
def close(self): pass
|
||||
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', Worker)
|
||||
monkeypatch.setattr(runner, '_cleanup_session_processes', lambda *a, **k: {'safe_to_continue': True})
|
||||
monkeypatch.setattr('cbb_refresh_verify.verify_diagnostics.capture_failure_logs_with_timeout', lambda *_: None)
|
||||
result = runner.run_verify(request(tmp_path), stop=stop, port_check=PORTS_OK)
|
||||
assert result.status == 'CANCELLED' and result.safe_to_continue
|
||||
assert len(cancelled) == 1 and cancelled[0].is_file()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('text,expected', [
|
||||
('content checking completed successfully! 0 errors, 0 warnings', 'PASS'),
|
||||
('content checking completed successfully! 10 errors', 'FAIL'),
|
||||
('content checking completed successfully! error: missing symbol', 'FAIL'),
|
||||
('content checking completed successfully! 0 errors\nERROR: cannot connect', 'FAIL'),
|
||||
])
|
||||
def test_zero_error_count_does_not_block_content_check(text, expected):
|
||||
assert runner.classify_output(0, text) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize('codec', ['utf-16', 'utf-8-sig', 'mbcs'])
|
||||
def test_preflight_reads_native_project_encodings(tmp_path, codec):
|
||||
work = fixture(tmp_path)
|
||||
(work/'CBB1.prj').write_bytes(('# 中文工程\nKEY PCBDesignPath "PCB\\actual.pcb"\n').encode(codec))
|
||||
project, pcb = runner.preflight(request(tmp_path))
|
||||
assert pcb == work/'PCB/actual.pcb'
|
||||
|
||||
|
||||
def test_unrelated_pcb_does_not_block_target_before_launch(tmp_path, monkeypatch):
|
||||
from test_verify_worker_stability import exercise_worker
|
||||
from cbb_refresh_verify import mentor_adapter as adapter
|
||||
job, events, execute = exercise_worker(tmp_path, monkeypatch)
|
||||
monkeypatch.setattr(adapter, 'pcb_processes', lambda: ((999, 'ExpeditionPCB.exe', '"ExpeditionPCB.exe" "C:\\other\\board.pcb"'),))
|
||||
assert execute()['status'] == 'PASS'
|
||||
assert any(e['stage'] == 'pcb_launch' for e in events)
|
||||
|
||||
|
||||
def test_sampling_ports_only_warn_by_default(tmp_path, monkeypatch):
|
||||
fixture(tmp_path)
|
||||
launches, warnings = [], []
|
||||
class Worker:
|
||||
desktop = None
|
||||
returncode = 0
|
||||
def __init__(self, command, *_a, **_k):
|
||||
launches.append(command)
|
||||
Path(command[-1]).with_name('outcome.json').write_text('{"status":"PASS"}')
|
||||
def poll(self): return 0
|
||||
def close(self): pass
|
||||
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', Worker)
|
||||
monkeypatch.setattr(runner, '_cleanup_session_processes', lambda *a, **k: {'safe_to_continue': True})
|
||||
result = runner.run_verify(request(tmp_path), port_check=lambda: (False, 'sample unavailable'),
|
||||
flag_reader=lambda *_: __import__('cbb_refresh_verify.status_bridge', fromlist=['BridgeResult']).BridgeResult('READY', 'IsVerifiedReuseBlock', 1),
|
||||
progress=warnings.append)
|
||||
assert launches and result.status == 'PASS'
|
||||
assert any(e['stage'] == 'port_warning' for e in warnings)
|
||||
|
||||
|
||||
def test_cleanup_includes_late_native_descendant_without_pcb_argument(monkeypatch):
|
||||
from cbb_refresh_verify import mentor_adapter as adapter
|
||||
rows = [(10, 'ExpeditionPCB.exe', '', 1), (11, 'ExpeditionPCB.exe', '', 10),
|
||||
(99, 'ExpeditionPCB.exe', '', 77)]
|
||||
monkeypatch.setattr(adapter, '_process_details', lambda name: rows if name == 'ExpeditionPCB.exe' else [])
|
||||
result = adapter.cleanup_verify_processes(None, None, 10, baseline_pids={99})
|
||||
assert not result['safe_to_continue'] and result['remaining_pids'] == [10, 11]
|
||||
|
||||
|
||||
def test_save_client_without_worker_still_prevents_continuation(tmp_path, monkeypatch):
|
||||
fixture(tmp_path)
|
||||
class Worker:
|
||||
desktop = None
|
||||
returncode = 1
|
||||
def __init__(self, command, *_a, **_k):
|
||||
Path(command[-1]).with_name('outcome.json').write_text('{"status":"FAIL"}')
|
||||
def poll(self): return 1
|
||||
def close(self): pass
|
||||
def automation_release_state(self): return {'safe_to_continue': False, 'remaining_pids': [333]}
|
||||
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', Worker)
|
||||
monkeypatch.setattr(runner, '_cleanup_session_processes', lambda *a, **k: {'safe_to_continue': True})
|
||||
monkeypatch.setattr('cbb_refresh_verify.verify_diagnostics.capture_failure_logs_with_timeout', lambda *_: None)
|
||||
req = request(tmp_path)
|
||||
try:
|
||||
result = runner.run_verify(req, port_check=PORTS_OK)
|
||||
assert not result.safe_to_continue
|
||||
proof = json.loads(result.evidence_path.with_name('session-release.json').read_text('utf-8'))
|
||||
assert proof['worker_exited'] is True
|
||||
assert proof['automation_release']['remaining_pids'] == [333]
|
||||
assert proof['remaining_pids'] == [333]
|
||||
finally:
|
||||
from cbb_refresh_verify import library_lock as locks
|
||||
with locks._guard:
|
||||
owner = locks._owners.pop(locks.LibraryLock(req.lmc_file).key, None)
|
||||
if owner: owner['handle'].Close()
|
||||
|
||||
|
||||
def test_closed_desktop_worker_keeps_exit_status_without_using_closed_handle(monkeypatch):
|
||||
from types import SimpleNamespace
|
||||
from cbb_refresh_verify import desktop_worker as desktop
|
||||
worker = desktop.DesktopWorker.__new__(desktop.DesktopWorker)
|
||||
handle = SimpleNamespace(closed=False)
|
||||
def close(): handle.closed = True
|
||||
handle.Close = close
|
||||
worker.handle = handle
|
||||
worker.job = SimpleNamespace(Close=lambda: None)
|
||||
worker.desktop = None; worker.companions = []; worker.companion_pids = []
|
||||
def code(h):
|
||||
assert not h.closed, 'Read from a closed Win32 process handle'
|
||||
return 1
|
||||
monkeypatch.setattr(desktop.win32process, 'GetExitCodeProcess', code)
|
||||
worker.close()
|
||||
assert worker.poll() == 1
|
||||
worker.close() # Idempotent cleanup.
|
||||
|
||||
|
||||
def test_native_process_queries_use_bounded_shared_helper(monkeypatch):
|
||||
from cbb_refresh_verify import mentor_adapter as adapter
|
||||
calls = []
|
||||
def query(names):
|
||||
calls.append(names)
|
||||
return [{'pid': 12, 'executable': 'ExpeditionPCB.exe', 'command': 'native', 'parent': 11}]
|
||||
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', query)
|
||||
assert adapter._process_details('ExpeditionPCB.exe') == [(12, 'ExpeditionPCB.exe', 'native', 11)]
|
||||
assert calls == [('ExpeditionPCB.exe',)]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('script', ['save_verified_block.vbs', 'close_failed_block.vbs'])
|
||||
def test_save_and_failure_close_clients_are_both_tracked(script, monkeypatch):
|
||||
from cbb_refresh_verify import desktop_worker as desktop
|
||||
worker = desktop.DesktopWorker.__new__(desktop.DesktopWorker)
|
||||
worker.pid = 11; worker._closed = True; worker._exit_code = 1
|
||||
command = f'cscript.exe //nologo "{Path(desktop.__file__).with_name(script)}" "C:\\fixture\\design.prj"'
|
||||
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_a, **_k: [
|
||||
{'pid': 22, 'parent': 11, 'command': command},
|
||||
{'pid': 33, 'parent': 99, 'command': command},
|
||||
{'pid': 44, 'parent': 11, 'command': 'cscript.exe unrelated.vbs'}])
|
||||
proof = worker.automation_release_state()
|
||||
assert proof['safe_to_continue'] is False and proof['remaining_pids'] == [22]
|
||||
|
||||
|
||||
def test_watchdog_with_cancel_signal_stops_clients_after_supervisor_exit(tmp_path):
|
||||
import subprocess, sys, time
|
||||
import win32api, win32con, win32process
|
||||
supervisor = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(30)'])
|
||||
script = tmp_path/'watchdog.py'; ready = tmp_path/'ready.json'; cancel = tmp_path/'cancel.signal'
|
||||
script.write_text(
|
||||
'import sys, subprocess, time, json\nfrom pathlib import Path\n'
|
||||
'from cbb_refresh_verify.desktop_worker import start_supervisor_watchdog, launch_save_helper\n'
|
||||
f'start_supervisor_watchdog({supervisor.pid}, cancel_path={str(cancel)!r}, stop_clients=True)\n'
|
||||
'native = subprocess.Popen([sys.executable,"-c","import time; time.sleep(30)"])\n'
|
||||
'client = launch_save_helper([sys.executable,"-c","import time; time.sleep(30)"])\n'
|
||||
f'Path({str(ready)!r}).write_text(json.dumps([native.pid,client.pid]))\n'
|
||||
'time.sleep(30)\n', encoding='utf-8')
|
||||
worker = subprocess.Popen([sys.executable, str(script)], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
handles = []
|
||||
try:
|
||||
deadline = time.monotonic()+10
|
||||
while not ready.exists() and worker.poll() is None and time.monotonic()<deadline:
|
||||
time.sleep(.05)
|
||||
assert ready.exists()
|
||||
for pid in json.loads(ready.read_text()):
|
||||
handles.append(win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_TERMINATE, False, pid))
|
||||
supervisor.terminate(); supervisor.wait(5)
|
||||
assert worker.wait(10) == 75 and cancel.is_file()
|
||||
assert win32process.GetExitCodeProcess(handles[0]) == 259
|
||||
assert win32process.GetExitCodeProcess(handles[1]) != 259
|
||||
finally:
|
||||
for p in (supervisor, worker):
|
||||
if p.poll() is None: p.terminate()
|
||||
p.wait(5)
|
||||
for h in handles:
|
||||
if win32process.GetExitCodeProcess(h) == 259: win32process.TerminateProcess(h, 0)
|
||||
h.Close()
|
||||
@@ -99,7 +99,7 @@ def test_timeout_isolated_and_later_item_continues(tmp_path):
|
||||
assert records[1].status == "PENDING"
|
||||
|
||||
|
||||
def test_protocol_path_mismatch_stops_repeating_same_global_failure(tmp_path):
|
||||
def test_protocol_path_mismatch_records_each_queried_item(tmp_path):
|
||||
class BrokenProtocolBridge:
|
||||
def __init__(self):
|
||||
self.requests = []
|
||||
@@ -116,7 +116,7 @@ def test_protocol_path_mismatch_stops_repeating_same_global_failure(tmp_path):
|
||||
['A', 'B', 'C'], lmc, tmp_path / 'scan.jsonl'
|
||||
)
|
||||
|
||||
assert bridge.requests == ['A']
|
||||
assert bridge.requests == ['A', 'B', 'C']
|
||||
assert [record.status for record in records] == ['MALFORMED'] * 3
|
||||
|
||||
|
||||
@@ -172,3 +172,26 @@ def test_authoritative_status_map_never_reuses_previous_scan_status(tmp_path, mo
|
||||
assert first == {'A': 'PENDING'}
|
||||
assert second == {'A': 'READY'}
|
||||
assert calls == ['A', 'A']
|
||||
|
||||
|
||||
def test_retry_rechecks_failed_scan_without_library_changes(tmp_path):
|
||||
lmc = tmp_path/'library.lmc'; lmc.write_bytes(b'library')
|
||||
checkpoint = tmp_path/'scan.jsonl'
|
||||
first = BatchStatusSession(FakeBridge(timeout_name='A')).scan(['A', 'B'], lmc, checkpoint)
|
||||
assert first[0].status == 'TIMEOUT'
|
||||
bridge = FakeBridge()
|
||||
second = BatchStatusSession(bridge).scan(['A', 'B'], lmc, checkpoint)
|
||||
assert bridge.requests == ['A']
|
||||
assert second[0].status == 'READY'
|
||||
|
||||
|
||||
def test_missing_x86_runtime_does_not_restart_for_every_cbb(tmp_path):
|
||||
class BrokenBridge(FakeBridge):
|
||||
def query(self, library, name, **kwargs):
|
||||
self.requests.append(name)
|
||||
raise BridgeResponseError('状态桥进程失败: -1073741515')
|
||||
lmc = tmp_path/'library.lmc'; lmc.write_bytes(b'library')
|
||||
bridge = BrokenBridge()
|
||||
result = BatchStatusSession(bridge).scan(['A', 'B', 'C'], lmc, tmp_path/'scan.jsonl')
|
||||
assert bridge.requests == ['A']
|
||||
assert [row.status for row in result] == ['UNAVAILABLE'] * 3
|
||||
@@ -138,3 +138,70 @@ def test_reader_closes_desktop_when_process_launch_fails(monkeypatch, tmp_path,
|
||||
with pytest.raises(RuntimeError, match='launch failed'):
|
||||
module.read_library_tree_image_map(tmp_path / 'library.lmc', ['Block'])
|
||||
assert closed == ['desktop']
|
||||
|
||||
|
||||
def test_constructor_releases_private_desktop_when_process_launch_fails(monkeypatch):
|
||||
import cbb_refresh_verify.desktop_worker as module
|
||||
|
||||
class Handle:
|
||||
def __init__(self):
|
||||
self.closed = False
|
||||
|
||||
def Close(self):
|
||||
self.closed = True
|
||||
|
||||
def CloseDesktop(self):
|
||||
self.closed = True
|
||||
|
||||
desktop = Handle()
|
||||
job = Handle()
|
||||
|
||||
monkeypatch.setattr(module.win32service, 'CreateDesktop', lambda *args: desktop)
|
||||
monkeypatch.setattr(module.win32job, 'CreateJobObject', lambda *args: job)
|
||||
monkeypatch.setattr(module.win32process, 'STARTUPINFO', lambda: type('Startup', (), {})())
|
||||
monkeypatch.setattr(module.win32process, 'CreateProcess',
|
||||
lambda *args: (_ for _ in ()).throw(RuntimeError('launch failed')))
|
||||
|
||||
with pytest.raises(RuntimeError, match='launch failed') as caught:
|
||||
module.DesktopWorker(['worker.exe'], 'PrivateDesk')
|
||||
|
||||
assert desktop.closed is True
|
||||
assert job.closed is True
|
||||
assert caught.value.worker_launch_release == {
|
||||
'process_created': False, 'safe_to_continue': True, 'worker_exited': True, 'remaining_pids': []}
|
||||
|
||||
|
||||
def test_partial_launch_cleanup_never_claims_native_descendants_released(monkeypatch):
|
||||
import cbb_refresh_verify.desktop_worker as module
|
||||
class Handle:
|
||||
def Close(self): pass
|
||||
def CloseDesktop(self): pass
|
||||
class Thread:
|
||||
def Close(self): raise OSError('thread handle cleanup failed')
|
||||
monkeypatch.setattr(module.win32service, 'CreateDesktop', lambda *args: Handle())
|
||||
monkeypatch.setattr(module.win32job, 'CreateJobObject', lambda *args: Handle())
|
||||
monkeypatch.setattr(module.win32process, 'STARTUPINFO', lambda: type('Startup', (), {})())
|
||||
monkeypatch.setattr(module.win32process, 'CreateProcess', lambda *args: (Handle(), Thread(), 123, 456))
|
||||
terminated = []
|
||||
monkeypatch.setattr(module.win32process, 'TerminateProcess', lambda *args: terminated.append(args))
|
||||
with pytest.raises(OSError, match='thread handle cleanup failed') as caught:
|
||||
module.DesktopWorker(['worker.exe'], 'PrivateDesk')
|
||||
assert caught.value.worker_launch_release == {
|
||||
'process_created': True, 'safe_to_continue': False, 'worker_exited': False, 'remaining_pids': [123]}
|
||||
assert len(terminated) == 1
|
||||
|
||||
|
||||
def test_release_probe_allows_measured_owner_helper_startup_time(monkeypatch):
|
||||
import cbb_refresh_verify.desktop_worker as module
|
||||
from cbb_refresh_verify import owner_probe
|
||||
worker = module.DesktopWorker.__new__(module.DesktopWorker)
|
||||
worker.pid = 123
|
||||
worker._closed = True
|
||||
worker._exit_code = 1
|
||||
def query(names, *, timeout_seconds):
|
||||
# Real helper measured ~4.75s including interpreter + COM startup.
|
||||
if timeout_seconds < 5:
|
||||
raise RuntimeError('OWNER_QUERY_TIMEOUT')
|
||||
return []
|
||||
monkeypatch.setattr(owner_probe, 'query_owners', query)
|
||||
assert worker.automation_release_state() == {'safe_to_continue': True, 'remaining_pids': []}
|
||||
@@ -0,0 +1,338 @@
|
||||
import importlib
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def diagnostic():
|
||||
assert importlib.util.find_spec('cbb_refresh_verify.diagnostic_open') is not None, 'diagnostic open module is missing'
|
||||
return importlib.import_module('cbb_refresh_verify.diagnostic_open')
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def job(tmp_path):
|
||||
project = tmp_path / 'IP101GR'
|
||||
pcb = project / 'PCB/IP101GR.pcb'
|
||||
pcb.parent.mkdir(parents=True)
|
||||
pcb.write_bytes(b'pcb')
|
||||
return {'project': str(project / 'IP101GR.prj'), 'pcb': str(pcb), 'root': str(tmp_path / 'evidence'),
|
||||
'desktop': 'CbbDiagnosticTest', 'timeout': .03}
|
||||
|
||||
|
||||
def write_logs(job, *, pid=42, foreign=False, success=True):
|
||||
project = Path(job['project']).parent
|
||||
logdir = Path(job['pcb']).parent / 'LogFiles'
|
||||
logdir.mkdir(parents=True, exist_ok=True)
|
||||
pcb = str(Path(job['pcb'])) if not foreign else str(project.parent / 'other/PCB/IP101GR.pcb')
|
||||
(logdir / 'PCBAutoSave.txt').write_text('Job Name: ' + pcb + '\n', encoding='utf-8')
|
||||
(logdir / 'PCBLogFile.txt').write_text('Successfully read the design.\n' if success else 'Loading\n', encoding='utf-8')
|
||||
database = str(project / 'database') if not foreign else str(project.parent / 'other/database')
|
||||
logs = project / 'database/cdbsvr/log/current'
|
||||
logs.mkdir(parents=True, exist_ok=True)
|
||||
(logs / 'current.txt').write_text(
|
||||
f'S: Project path [{database}] on file system [NTFS]\n'
|
||||
f'S: Project file (.prj) path [{project / "IP101GR.prj"}] on file system [NTFS]\n'
|
||||
f'S: Started up automatically by iCDB Client: ABS:ABS:{pid}\n'
|
||||
'S: iCDB database loaded\n'
|
||||
f'SC[455]: Registered sub-client [Expedition PCB_123] with ID [1] for session ID [455] host [Abs] user [ABS] process ID [{pid}]\n',
|
||||
encoding='utf-8')
|
||||
|
||||
|
||||
def test_old_success_logs_are_not_current_open_evidence(diagnostic, job):
|
||||
write_logs(job)
|
||||
baseline = diagnostic.snapshot_diagnostic_logs(job)
|
||||
assert diagnostic._load_evidence(job, 42, baseline) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize('pid,foreign,success', [(99, False, True), (42, True, True), (42, False, False)])
|
||||
def test_foreign_pid_path_or_incomplete_load_cannot_pass(diagnostic, job, pid, foreign, success):
|
||||
baseline = diagnostic.snapshot_diagnostic_logs(job)
|
||||
write_logs(job, pid=pid, foreign=foreign, success=success)
|
||||
assert diagnostic._load_evidence(job, 42, baseline) is None
|
||||
|
||||
|
||||
def test_current_full_path_and_pcb_pid_logs_prove_open_only(diagnostic, job):
|
||||
baseline = diagnostic.snapshot_diagnostic_logs(job)
|
||||
write_logs(job)
|
||||
evidence = diagnostic._load_evidence(job, 42, baseline)
|
||||
assert evidence['pcb'] == job['pcb']
|
||||
assert evidence['pcb_pid'] == 42
|
||||
|
||||
|
||||
def test_old_prefix_in_appended_log_cannot_supply_target_identity(diagnostic, job):
|
||||
write_logs(job)
|
||||
baseline = diagnostic.snapshot_diagnostic_logs(job)
|
||||
for path in Path(job['project']).parent.rglob('*.txt'):
|
||||
with path.open('a', encoding='utf-8') as output:
|
||||
output.write('unrelated new record\n')
|
||||
assert diagnostic._load_evidence(job, 42, baseline) is None
|
||||
|
||||
|
||||
def frame(job, *, title='IP101GR'):
|
||||
return {'hwnd': 10, 'pid': 42, 'class': 'Afx:123',
|
||||
'text': f'Expedition PCB - Reusable Block - [{title}]', 'enabled': True,
|
||||
'children': [{'hwnd': 11, 'class': 'MDIClient', 'text': '', 'parent': 10},
|
||||
{'hwnd': 12, 'class': 'Afx:document', 'text': title, 'parent': 11}]}
|
||||
|
||||
|
||||
def test_target_title_without_target_mdi_does_not_pass(diagnostic, job):
|
||||
window = frame(job)
|
||||
window['children'][1]['text'] = 'another_project'
|
||||
assert diagnostic._target_frame([window], Path(job['pcb']).stem) is None
|
||||
|
||||
|
||||
class Session:
|
||||
instances = []
|
||||
def __init__(self, job, pid, launcher):
|
||||
self.alive = True
|
||||
self.closed = False
|
||||
self.posted = []
|
||||
self.instances.append(self)
|
||||
def pcb_alive(self):
|
||||
return self.alive
|
||||
def launcher_alive(self):
|
||||
return self.alive
|
||||
def post(self, hwnd, message):
|
||||
self.posted.append((hwnd, message))
|
||||
self.alive = False
|
||||
def close(self):
|
||||
self.closed = True
|
||||
|
||||
|
||||
def test_unknown_prompt_is_preserved_and_never_closed(diagnostic, job, monkeypatch):
|
||||
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
|
||||
write_logs(job)
|
||||
monkeypatch.setattr(diagnostic, '_NativeSession', Session)
|
||||
monkeypatch.setattr(diagnostic, '_windows', lambda pid: [frame(job),
|
||||
{'hwnd': 20, 'pid': 42, 'class': '#32770', 'text': 'Unknown question', 'children': []}])
|
||||
with pytest.raises(RuntimeError, match='DIAGNOSTIC_CLOSE_UNCONFIRMED'):
|
||||
diagnostic.check_target_window(job, 42, emit=lambda **event: None, error_reader=lambda: None)
|
||||
assert Session.instances[-1].posted == []
|
||||
assert Session.instances[-1].closed
|
||||
|
||||
|
||||
def test_success_posts_one_exact_close_and_reports_only_open_check(diagnostic, job, monkeypatch):
|
||||
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
|
||||
write_logs(job)
|
||||
monkeypatch.setattr(diagnostic, '_NativeSession', Session)
|
||||
monkeypatch.setattr(diagnostic, '_windows', lambda pid: [frame(job)] if Session.instances[-1].alive else [])
|
||||
outcome = diagnostic.check_target_window(job, 42, emit=lambda **event: None, error_reader=lambda: None)
|
||||
assert outcome['status'] == 'PASS'
|
||||
assert outcome['check'] == 'native_open_only'
|
||||
assert outcome['native_processes_exited'] is True
|
||||
assert outcome['library_ownership'] == 'NOT_ASSESSED'
|
||||
assert Session.instances[-1].posted == [(10, 0x10)]
|
||||
assert Session.instances[-1].closed
|
||||
|
||||
|
||||
def test_transient_startup_window_cannot_abort_before_target_is_loaded(diagnostic, job, monkeypatch):
|
||||
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
|
||||
write_logs(job)
|
||||
monkeypatch.setattr(diagnostic, '_NativeSession', Session)
|
||||
calls = []
|
||||
def windows(pid):
|
||||
calls.append(True)
|
||||
if len(calls) == 1:
|
||||
return [{'hwnd': 20, 'pid': 42, 'class': 'VendorSplash', 'text': '', 'children': []}]
|
||||
return [frame(job)] if Session.instances[-1].alive else []
|
||||
monkeypatch.setattr(diagnostic, '_windows', windows)
|
||||
job['timeout'] = 1
|
||||
assert diagnostic.check_target_window(job, 42, emit=lambda **event: None, error_reader=lambda: None)['status'] == 'PASS'
|
||||
assert Session.instances[-1].posted == [(10, 0x10)]
|
||||
|
||||
|
||||
def test_native_caption_variant_uses_proven_target_mdi(diagnostic, job, monkeypatch):
|
||||
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
|
||||
write_logs(job)
|
||||
monkeypatch.setattr(diagnostic, '_NativeSession', Session)
|
||||
target = frame(job)
|
||||
target['text'] = 'Expedition PCB - [IP101GR]'
|
||||
monkeypatch.setattr(diagnostic, '_windows', lambda pid: [target] if Session.instances[-1].alive else [])
|
||||
assert diagnostic.check_target_window(job, 42, emit=lambda **event: None, error_reader=lambda: None)['status'] == 'PASS'
|
||||
|
||||
|
||||
def test_cancel_does_not_wait_for_open_timeout(diagnostic, job, monkeypatch):
|
||||
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
|
||||
cancel = Path(job['root']).parent / 'cancel'
|
||||
cancel.touch()
|
||||
job['cancel_signal'] = str(cancel)
|
||||
monkeypatch.setattr(diagnostic, '_NativeSession', Session)
|
||||
monkeypatch.setattr(diagnostic, '_windows', lambda pid: [])
|
||||
with pytest.raises(RuntimeError, match='VERIFY_CANCELLED'):
|
||||
diagnostic.check_target_window(job, 42, emit=lambda **event: None, error_reader=lambda: None)
|
||||
assert Session.instances[-1].posted == []
|
||||
assert Session.instances[-1].closed
|
||||
|
||||
|
||||
def test_cancel_after_close_request_still_waits_for_own_launcher_exit(diagnostic, job, monkeypatch):
|
||||
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
|
||||
write_logs(job)
|
||||
cancel = Path(job['root']).parent / 'cancel'
|
||||
job['cancel_signal'] = str(cancel)
|
||||
class DelayedLauncher(Session):
|
||||
polls = 0
|
||||
def post(self, hwnd, message):
|
||||
super().post(hwnd, message)
|
||||
cancel.touch()
|
||||
def launcher_alive(self):
|
||||
self.polls += 1
|
||||
return self.polls < 3
|
||||
monkeypatch.setattr(diagnostic, '_NativeSession', DelayedLauncher)
|
||||
monkeypatch.setattr(diagnostic, '_windows', lambda pid: [frame(job)] if Session.instances[-1].alive else [])
|
||||
assert diagnostic.check_target_window(job, 42, emit=lambda **event: None, error_reader=lambda: None)['status'] == 'PASS'
|
||||
assert Session.instances[-1].polls >= 3
|
||||
|
||||
|
||||
@pytest.mark.parametrize('owner,window_class', [(10, 'VendorModal'), (0, 'VendorModal'),
|
||||
(0, 'Internet Explorer_Hidden')])
|
||||
def test_unknown_custom_owned_window_blocks_close(diagnostic, job, monkeypatch, owner, window_class):
|
||||
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
|
||||
write_logs(job)
|
||||
monkeypatch.setattr(diagnostic, '_NativeSession', Session)
|
||||
monkeypatch.setattr(diagnostic, '_windows', lambda pid: [frame(job),
|
||||
{'hwnd': 20, 'pid': 42, 'class': window_class, 'text': 'Unclassified prompt',
|
||||
'owner': owner, 'enabled': True, 'children': []}])
|
||||
with pytest.raises(RuntimeError, match='DIAGNOSTIC_CLOSE_UNCONFIRMED'):
|
||||
diagnostic.check_target_window(job, 42, emit=lambda **event: None, error_reader=lambda: None)
|
||||
assert Session.instances[-1].posted == []
|
||||
|
||||
|
||||
def test_empty_desktop_resets_stale_win32_last_error(diagnostic, monkeypatch):
|
||||
import win32api
|
||||
import win32gui
|
||||
import pywintypes
|
||||
seen = []
|
||||
def empty(callback, context):
|
||||
seen.append(win32api.GetLastError())
|
||||
raise pywintypes.error(0, 'EnumWindows', 'empty desktop')
|
||||
monkeypatch.setattr(win32gui, 'EnumWindows', empty)
|
||||
win32api.SetLastError(170)
|
||||
assert diagnostic._windows(42) == []
|
||||
assert seen == [0]
|
||||
|
||||
|
||||
def test_missing_launcher_cannot_claim_verified_native_release(diagnostic, job):
|
||||
with pytest.raises(RuntimeError, match='DIAGNOSTIC_LAUNCHER_REQUIRED'):
|
||||
diagnostic._NativeSession(job, 42, None)
|
||||
|
||||
|
||||
def test_buffered_full_pcb_path_must_be_verified_after_normal_close(diagnostic, job, monkeypatch):
|
||||
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
|
||||
write_logs(job)
|
||||
autosave = Path(job['pcb']).parent / 'LogFiles/PCBAutoSave.txt'
|
||||
autosave.write_text('', encoding='utf-8')
|
||||
class BufferedSession(Session):
|
||||
def post(self, hwnd, message):
|
||||
super().post(hwnd, message)
|
||||
autosave.write_text('Job Name: ' + job['pcb'] + '\n', encoding='utf-8')
|
||||
monkeypatch.setattr(diagnostic, '_NativeSession', BufferedSession)
|
||||
monkeypatch.setattr(diagnostic, '_windows', lambda pid: [frame(job)] if Session.instances[-1].alive else [])
|
||||
outcome = diagnostic.check_target_window(job, 42, emit=lambda **event: None, error_reader=lambda: None)
|
||||
assert outcome['status'] == 'PASS'
|
||||
assert Session.instances[-1].posted == [(10, 0x10)]
|
||||
|
||||
|
||||
def test_large_unrelated_history_does_not_block_current_evidence(diagnostic, job):
|
||||
logs = Path(job['project']).parent / 'database/cdbsvr/log'
|
||||
for index in range(270):
|
||||
directory = logs / f'2000-01-01 00.00.00-{index:05}'
|
||||
directory.mkdir(parents=True)
|
||||
(directory / '2000.01.01.txt').write_bytes(b'old unrelated history\n' * 14000)
|
||||
baseline = diagnostic.snapshot_diagnostic_logs(job)
|
||||
write_logs(job)
|
||||
assert diagnostic._load_evidence(job, 42, baseline) is not None
|
||||
|
||||
|
||||
def test_pcb_logs_follow_actual_pcb_directory(diagnostic, job):
|
||||
pcb = Path(job['pcb']).parent.parent / 'AlternativePCB/IP101GR.pcb'
|
||||
pcb.parent.mkdir()
|
||||
pcb.write_bytes(b'pcb')
|
||||
job['pcb'] = str(pcb)
|
||||
baseline = diagnostic.snapshot_diagnostic_logs(job)
|
||||
write_logs(job)
|
||||
assert diagnostic._load_evidence(job, 42, baseline)['pcb'] == str(pcb)
|
||||
|
||||
|
||||
def test_only_exact_owned_save_prompt_gets_no_after_diagnostic_close(diagnostic, job, monkeypatch):
|
||||
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
|
||||
write_logs(job)
|
||||
class SaveSession(Session):
|
||||
closing = False
|
||||
def post(self, hwnd, message):
|
||||
self.posted.append((hwnd, message))
|
||||
if message == 0x10:
|
||||
self.closing = True
|
||||
else:
|
||||
self.alive = False
|
||||
closing_scans = []
|
||||
def windows(pid):
|
||||
state = Session.instances[-1]
|
||||
if not state.closing:
|
||||
return [frame(job)]
|
||||
closing_scans.append(True)
|
||||
if len(closing_scans) == 1:
|
||||
return [{'hwnd': 20, 'pid': 42, 'class': '#32770', 'text': '',
|
||||
'owner': 10, 'children': []}]
|
||||
return [{'hwnd': 20, 'pid': 42, 'class': '#32770', 'text': 'Expedition PCB',
|
||||
'owner': 10, 'children': [
|
||||
{'hwnd': 30, 'class': 'Static', 'text': 'Do you want to save the reusable block cell?', 'id': -1},
|
||||
{'hwnd': 31, 'class': 'Button', 'text': '&No', 'id': 7}]}]
|
||||
monkeypatch.setattr(diagnostic, '_NativeSession', SaveSession)
|
||||
monkeypatch.setattr(diagnostic, '_windows', windows)
|
||||
outcome = diagnostic.check_target_window(job, 42, emit=lambda **event: None, error_reader=lambda: None)
|
||||
assert outcome['status'] == 'PASS'
|
||||
assert Session.instances[-1].posted == [(10, 0x10), (31, 0xF5)]
|
||||
|
||||
|
||||
def test_no_pass_when_normal_close_never_flushes_full_pcb_path(diagnostic, job, monkeypatch):
|
||||
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
|
||||
write_logs(job)
|
||||
(Path(job['pcb']).parent / 'LogFiles/PCBAutoSave.txt').write_bytes(b'')
|
||||
monkeypatch.setattr(diagnostic, '_NativeSession', Session)
|
||||
monkeypatch.setattr(diagnostic, '_windows', lambda pid: [frame(job)] if Session.instances[-1].alive else [])
|
||||
with pytest.raises(RuntimeError, match='fresh full PCB path not confirmed after close'):
|
||||
diagnostic.check_target_window(job, 42, emit=lambda **event: None, error_reader=lambda: None)
|
||||
assert Session.instances[-1].posted == [(10, 0x10)]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('filename,accepted', [('IP101GR.pcb', True), ('Foreign.pcb', False)])
|
||||
def test_standard_save_question_requires_exact_target_filename(diagnostic, job, monkeypatch, filename, accepted):
|
||||
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
|
||||
write_logs(job)
|
||||
class SaveSession(Session):
|
||||
closing = False
|
||||
def post(self, hwnd, message):
|
||||
self.posted.append((hwnd, message))
|
||||
if message == 0x10:
|
||||
self.closing = True
|
||||
else:
|
||||
self.alive = False
|
||||
def windows(pid):
|
||||
if not Session.instances[-1].closing:
|
||||
return [frame(job)]
|
||||
return [{'hwnd': 20, 'pid': 42, 'class': '#32770', 'text': 'Expedition PCB', 'owner': 10,
|
||||
'children': [{'hwnd': 30, 'class': 'Static', 'text': f'Save changes to {filename}?', 'id': -1},
|
||||
{'hwnd': 31, 'class': 'Button', 'text': '否(&N)', 'id': 7},
|
||||
{'hwnd': 32, 'class': 'Button', 'text': '是(&Y)', 'id': 6},
|
||||
{'hwnd': 33, 'class': 'Button', 'text': '取消', 'id': 2}]}]
|
||||
monkeypatch.setattr(diagnostic, '_NativeSession', SaveSession)
|
||||
monkeypatch.setattr(diagnostic, '_windows', windows)
|
||||
if accepted:
|
||||
assert diagnostic.check_target_window(job, 42, emit=lambda **event: None, error_reader=lambda: None)['status'] == 'PASS'
|
||||
assert Session.instances[-1].posted == [(10, 0x10), (31, 0xF5)]
|
||||
else:
|
||||
with pytest.raises(RuntimeError, match='DIAGNOSTIC_CLOSE_UNCONFIRMED'):
|
||||
diagnostic.check_target_window(job, 42, emit=lambda **event: None, error_reader=lambda: None)
|
||||
assert Session.instances[-1].posted == [(10, 0x10)]
|
||||
|
||||
|
||||
def test_recycled_window_from_another_pid_never_receives_close(diagnostic, monkeypatch):
|
||||
import win32process
|
||||
session = diagnostic._NativeSession.__new__(diagnostic._NativeSession)
|
||||
session.pid = 42
|
||||
session.pcb_alive = lambda: True
|
||||
monkeypatch.setattr(win32process, 'GetWindowThreadProcessId', lambda hwnd: (1, 99))
|
||||
with pytest.raises(RuntimeError, match='DIAGNOSTIC_STALE_WINDOW'):
|
||||
session.post(10, 0x10)
|
||||
@@ -412,6 +412,79 @@ def test_agent_start_failure_releases_listener(tmp_path):
|
||||
DialogAgentClient.start(FailedWorker(), tmp_path)
|
||||
|
||||
|
||||
def _slow_start_client(tmp_path, monkeypatch, *, delay, stop=None):
|
||||
import socket
|
||||
from types import SimpleNamespace
|
||||
from cbb_refresh_verify import dialog_agent as module
|
||||
client = DialogAgentClient.prepare(tmp_path, desktop_name='test')
|
||||
client.listener.close()
|
||||
elapsed = [0.0]
|
||||
class Listener:
|
||||
closed = False
|
||||
def settimeout(self, timeout): self.timeout = timeout
|
||||
def accept(self):
|
||||
if elapsed[0] < delay:
|
||||
elapsed[0] += self.timeout
|
||||
if stop is not None and elapsed[0] >= .4: stop.set()
|
||||
raise socket.timeout()
|
||||
return SimpleNamespace(setsockopt=lambda *a: None), None
|
||||
def close(self): self.closed = True
|
||||
class Channel:
|
||||
def __init__(self, connection): pass
|
||||
def receive(self, timeout): return {'token': client.paths.token}
|
||||
def send(self, *a): pass
|
||||
def close(self): pass
|
||||
client.listener = Listener()
|
||||
monkeypatch.setattr(module, 'JsonChannel', Channel)
|
||||
monkeypatch.setattr(module.time, 'monotonic', lambda: elapsed[0])
|
||||
monkeypatch.setattr(DialogAgentClient, 'prepare', classmethod(lambda cls, *a, **k: client))
|
||||
worker = SimpleNamespace(name='test', start_companion=lambda command: None)
|
||||
return client, worker, elapsed
|
||||
|
||||
|
||||
def test_frozen_agent_can_initialize_after_the_old_ten_second_deadline(tmp_path, monkeypatch):
|
||||
client, worker, elapsed = _slow_start_client(tmp_path, monkeypatch, delay=12)
|
||||
assert DialogAgentClient.start(worker, tmp_path) is client
|
||||
assert elapsed[0] >= 12 and client.channel is not None
|
||||
assert client.timeout_seconds == 2 # Normal IPC does not inherit the startup budget.
|
||||
|
||||
|
||||
def test_agent_startup_wait_responds_to_cancel_without_starting_pcb(tmp_path, monkeypatch):
|
||||
import pytest
|
||||
from threading import Event
|
||||
stop = Event()
|
||||
client, worker, elapsed = _slow_start_client(tmp_path, monkeypatch, delay=100, stop=stop)
|
||||
with pytest.raises(InterruptedError, match='VERIFY_CANCELLED'):
|
||||
DialogAgentClient.start(worker, tmp_path, stop=stop)
|
||||
assert elapsed[0] < 1 and client.listener.closed
|
||||
|
||||
|
||||
def test_agent_startup_still_has_an_absolute_deadline(tmp_path, monkeypatch):
|
||||
import pytest
|
||||
client, worker, elapsed = _slow_start_client(tmp_path, monkeypatch, delay=100)
|
||||
with pytest.raises(TimeoutError):
|
||||
DialogAgentClient.start(worker, tmp_path)
|
||||
assert 29 <= elapsed[0] <= 31 and client.listener.closed
|
||||
|
||||
|
||||
def test_cancellation_during_authenticated_handshake_never_releases_startup(tmp_path, monkeypatch):
|
||||
import pytest
|
||||
from threading import Event
|
||||
from cbb_refresh_verify import dialog_agent as module
|
||||
stop = Event()
|
||||
client, worker, _ = _slow_start_client(tmp_path, monkeypatch, delay=0)
|
||||
class Channel:
|
||||
def __init__(self, connection): pass
|
||||
def receive(self, timeout):
|
||||
stop.set()
|
||||
return {'token': client.paths.token}
|
||||
def close(self): pass
|
||||
monkeypatch.setattr(module, 'JsonChannel', Channel)
|
||||
with pytest.raises(InterruptedError, match='VERIFY_CANCELLED'):
|
||||
DialogAgentClient.start(worker, tmp_path, stop=stop)
|
||||
assert client.channel is None and client.listener.closed
|
||||
|
||||
|
||||
def test_memory_channel_timeout_is_bounded_and_partial_packets_survive():
|
||||
import socket
|
||||
import pytest
|
||||
@@ -436,7 +509,7 @@ def test_loopback_connection_rejects_wrong_agent_token(tmp_path):
|
||||
import socket
|
||||
import pytest
|
||||
from cbb_refresh_verify.dialog_agent import JsonChannel, DialogAgentProtocolError
|
||||
client = DialogAgentClient.prepare(tmp_path, desktop_name='test', timeout_seconds=.3)
|
||||
client = DialogAgentClient.prepare(tmp_path, desktop_name='test', timeout_seconds=2)
|
||||
wrong = JsonChannel(socket.create_connection(('127.0.0.1', client.paths.port), timeout=1))
|
||||
try:
|
||||
wrong.send({'token': 'not-the-agent'})
|
||||
|
||||
@@ -86,6 +86,18 @@ def test_probe_keeps_visible_non_dialog_classes():
|
||||
assert snapshots[0].process_name == "proc-1010.exe"
|
||||
|
||||
|
||||
def test_pid_scope_excludes_foreign_dialog_before_child_or_uia_read():
|
||||
gui = FakeGui({10: {'class_name': '#32770', 'text': 'owned'},
|
||||
20: {'class_name': '#32770', 'text': 'other project'}})
|
||||
class Uia:
|
||||
def controls(self, hwnd):
|
||||
assert hwnd == 10, 'Foreign project was probed'
|
||||
return ()
|
||||
probe = make_probe(gui, (20, 10), Uia())
|
||||
assert [w.hwnd for w in probe.capture(PHASE, pids={1010})] == [10]
|
||||
assert probe.capture(PHASE, pids=set()) == ()
|
||||
|
||||
|
||||
def test_disappearing_window_is_skipped_without_hiding_other_windows():
|
||||
gui = FakeGui({
|
||||
10: {"class_name": "GXWND", "text": "gone"},
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.mark.parametrize('cancel,gate_present', [(False, False), (True, False), (True, True)])
|
||||
def test_worker_waits_for_cold_agent_but_cancellation_never_opens_pcb(tmp_path, monkeypatch, cancel, gate_present):
|
||||
from cbb_refresh_verify import mentor_adapter as adapter
|
||||
import pythoncom
|
||||
gate, stop = tmp_path/'start.signal', tmp_path/'cancel.signal'
|
||||
if gate_present: gate.touch()
|
||||
if cancel: stop.touch()
|
||||
clock, opened = [0.0], []
|
||||
def advance(seconds):
|
||||
clock[0] += seconds
|
||||
if not cancel and clock[0] >= 20: gate.touch()
|
||||
monkeypatch.setattr(adapter, 'time', SimpleNamespace(monotonic=lambda: clock[0], sleep=advance,
|
||||
strftime=lambda *_: 'test'))
|
||||
monkeypatch.setattr(pythoncom, 'CoInitialize', lambda: None)
|
||||
monkeypatch.setattr(pythoncom, 'CoUninitialize', lambda: None)
|
||||
monkeypatch.setattr(adapter, 'execute_job', lambda *args: opened.append(True) or {'status': 'PASS'})
|
||||
job = tmp_path/'request.json'
|
||||
job.write_text(json.dumps({'root': str(tmp_path), 'block_name': 'fixture',
|
||||
'start_gate': str(gate), 'cancel_signal': str(stop)}), encoding='utf-8')
|
||||
result = adapter.worker_main(job)
|
||||
assert result == (1 if cancel else 0)
|
||||
assert opened == ([] if cancel else [True])
|
||||
if cancel:
|
||||
outcome = json.loads((tmp_path/'outcome.json').read_text('utf-8'))
|
||||
assert 'VERIFY_CANCELLED' in outcome['stderr']
|
||||
@@ -72,7 +72,8 @@ def test_serial_guard_covers_preflight_and_content_check(tmp_path, monkeypatch):
|
||||
try:
|
||||
second = runner.run_verify(VerifyRequest(tmp_path/'lib.lmc', 'second', tmp_path/'evidence'))
|
||||
assert second.status == 'BLOCKED'
|
||||
assert not second.safe_to_continue
|
||||
assert second.safe_to_continue
|
||||
assert second.error_category == 'NATIVE_CHANNEL_BUSY'
|
||||
assert calls == ['first']
|
||||
finally:
|
||||
release.set()
|
||||
@@ -173,19 +174,6 @@ def test_cli_unsafe_batch_preserves_created_drive(tmp_path, monkeypatch):
|
||||
assert lease.drive in backend.existing
|
||||
|
||||
|
||||
def test_ui_unsafe_batch_preserves_created_drive(qtbot, tmp_path):
|
||||
from test_network_path import FakeWNet
|
||||
from cbb_refresh_verify.network_path import LibraryPathLease
|
||||
from cbb_refresh_verify.ui.main_window import MainWindow
|
||||
backend = FakeWNet()
|
||||
lease = LibraryPathLease.acquire(r'\\server\share\lib.lmc', backend=backend)
|
||||
window = MainWindow(data_root=tmp_path)
|
||||
qtbot.addWidget(window)
|
||||
window.library_lease = lease
|
||||
window._batch_done(([VerifyResult('FAIL', safe_to_continue=False)], tmp_path/'batch.log'))
|
||||
window.close()
|
||||
assert not backend.cancelled
|
||||
assert lease.drive in backend.existing
|
||||
|
||||
|
||||
def test_legacy_library_reader_only_requests_owned_window_close(monkeypatch):
|
||||
|
||||
@@ -0,0 +1,366 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from cbb_refresh_verify import failed_session, mentor_adapter
|
||||
|
||||
|
||||
def startup_fixture(tmp_path, monkeypatch):
|
||||
import win32gui, win32process
|
||||
from cbb_refresh_verify import native_repair_ui
|
||||
job = {'root': str(tmp_path), 'pcb': str(tmp_path/'PCB/CBB.pcb'),
|
||||
'project': str(tmp_path/'CBB.prj'), 'lmc_file': str(tmp_path/'lib.lmc'),
|
||||
'desktop': 'CbbVerify_test'}
|
||||
diagnostics = tmp_path/'diagnostics'
|
||||
diagnostics.mkdir()
|
||||
(diagnostics/'icdb-recovery.json').write_text(json.dumps({
|
||||
'error_code': 'ICDB_REPAIR_REQUIRED', 'scope': 'project',
|
||||
'database_path': str(tmp_path/'database'), 'session': 'lost-session'}))
|
||||
records = [(12, r'C:\Mentor\wg\ExpeditionPCB.exe',
|
||||
f'ExpeditionPCB.exe "{job["pcb"]}" -ReusableCircuit', 11)]
|
||||
monkeypatch.setattr(mentor_adapter, '_process_details', lambda _: list(records))
|
||||
monkeypatch.setattr(native_repair_ui, '_current_desktop_name', lambda: 'CbbVerify_test')
|
||||
monkeypatch.setattr(win32gui, 'EnumWindows', lambda fn, arg: fn(100, arg))
|
||||
monkeypatch.setattr(win32gui, 'EnumChildWindows', lambda *args: None)
|
||||
monkeypatch.setattr(win32process, 'GetWindowThreadProcessId', lambda _: (1, 12))
|
||||
monkeypatch.setattr(win32gui, 'IsWindowVisible', lambda _: True)
|
||||
monkeypatch.setattr(win32gui, 'IsWindowEnabled', lambda _: True)
|
||||
monkeypatch.setattr(win32gui, 'GetWindowText', lambda _: 'Expedition PCB')
|
||||
monkeypatch.setattr(win32gui, 'GetClassName', lambda _: 'Afx:main')
|
||||
messages = []
|
||||
def post(hwnd, message, wparam, lparam):
|
||||
messages.append((hwnd, message))
|
||||
records.clear()
|
||||
monkeypatch.setattr(win32gui, 'PostMessage', post)
|
||||
return job, records, messages
|
||||
|
||||
|
||||
@pytest.mark.parametrize('title', ['Expedition PCB', 'Expedition PCB - Reusable Block'])
|
||||
def test_failed_startup_normally_closes_owned_empty_pcb(tmp_path, monkeypatch, title):
|
||||
import win32con
|
||||
import win32gui
|
||||
job, records, messages = startup_fixture(tmp_path, monkeypatch)
|
||||
monkeypatch.setattr(win32gui, 'GetWindowText', lambda _: title)
|
||||
result = failed_session.close_failed_startup(job, 12, baseline_pids=(), timeout_seconds=0)
|
||||
assert result['status'] == 'CLOSED'
|
||||
assert not records
|
||||
assert messages == [(100, win32con.WM_CLOSE)]
|
||||
assert json.loads((tmp_path/'startup-close.json').read_text())['status'] == 'CLOSED'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('obstacle', ['baseline', 'wrong_path', 'path_prefix', 'desktop', 'address',
|
||||
'dialog', 'document_title', 'mdi_document', 'disabled'])
|
||||
def test_failed_startup_preserves_unconfirmed_or_busy_session(tmp_path, monkeypatch, obstacle):
|
||||
import win32gui
|
||||
from cbb_refresh_verify import native_repair_ui
|
||||
job, records, messages = startup_fixture(tmp_path, monkeypatch)
|
||||
baseline = ()
|
||||
if obstacle == 'baseline': baseline = (12,)
|
||||
if obstacle == 'wrong_path': records[0] = (12, records[0][1], 'other.pcb -ReusableCircuit', 11)
|
||||
if obstacle == 'path_prefix':
|
||||
records[0] = (12, records[0][1], f'pcb.exe "{job["pcb"]}.other" -ReusableCircuit', 11)
|
||||
if obstacle == 'desktop': monkeypatch.setattr(native_repair_ui, '_current_desktop_name', lambda: 'Default')
|
||||
if obstacle == 'address':
|
||||
address = tmp_path/'database/cdbsvr/sAddress.adr'
|
||||
address.parent.mkdir(parents=True)
|
||||
address.write_text('owner')
|
||||
if obstacle == 'dialog': monkeypatch.setattr(win32gui, 'GetClassName', lambda _: '#32770')
|
||||
if obstacle == 'document_title': monkeypatch.setattr(win32gui, 'GetWindowText', lambda _: 'CBB.pcb - Expedition PCB')
|
||||
if obstacle == 'mdi_document':
|
||||
monkeypatch.setattr(win32gui, 'EnumChildWindows', lambda hwnd, fn, arg: fn(101, arg))
|
||||
monkeypatch.setattr(win32gui, 'GetClassName', lambda hwnd: 'MDIClient' if hwnd == 101 else 'Afx:main')
|
||||
monkeypatch.setattr(win32gui, 'GetWindow', lambda *args: 102)
|
||||
if obstacle == 'disabled': monkeypatch.setattr(win32gui, 'IsWindowEnabled', lambda _: False)
|
||||
if obstacle == 'no_diagnosis': (tmp_path/'diagnostics/icdb-recovery.json').unlink()
|
||||
result = failed_session.close_failed_startup(job, 12, baseline_pids=baseline, timeout_seconds=0)
|
||||
assert result['status'] == 'RETAINED'
|
||||
assert records
|
||||
assert not messages
|
||||
|
||||
|
||||
def test_owned_empty_shell_closes_without_an_icdb_diagnosis(tmp_path, monkeypatch):
|
||||
job, records, messages = startup_fixture(tmp_path, monkeypatch)
|
||||
(tmp_path/'diagnostics/icdb-recovery.json').unlink()
|
||||
result = failed_session.close_failed_startup(job, 12, timeout_seconds=0)
|
||||
assert result['status'] == 'CLOSED' and not records and len(messages) == 1
|
||||
|
||||
|
||||
def read_write_fixture(tmp_path, monkeypatch):
|
||||
import win32gui, win32con
|
||||
from cbb_refresh_verify.post_repair_consent import PROMPT_TEXT
|
||||
job, records, messages = startup_fixture(tmp_path, monkeypatch)
|
||||
(tmp_path/'diagnostics/icdb-recovery.json').unlink()
|
||||
visible = {100, 200}
|
||||
classes = {100: 'Afx:main', 200: '#32770', 201: 'Button', 202: 'Button', 203: 'Static'}
|
||||
names = {100: 'Expedition PCB', 200: 'Expedition PCB', 201: 'Yes', 202: 'No', 203: PROMPT_TEXT}
|
||||
identifiers = {201: 6, 202: 7, 203: 65535}
|
||||
monkeypatch.setattr(win32gui, 'EnumWindows', lambda fn, arg: [fn(h, arg) for h in tuple(visible)])
|
||||
monkeypatch.setattr(win32gui, 'EnumChildWindows', lambda h, fn, arg:
|
||||
[fn(c, arg) for c in (201, 202, 203)] if h == 200 else None)
|
||||
monkeypatch.setattr(win32gui, 'GetClassName', classes.__getitem__)
|
||||
monkeypatch.setattr(win32gui, 'GetWindowText', names.__getitem__)
|
||||
monkeypatch.setattr(win32gui, 'GetDlgCtrlID', identifiers.__getitem__)
|
||||
monkeypatch.setattr(win32gui, 'IsWindowEnabled', lambda h: h != 100 or 200 not in visible)
|
||||
monkeypatch.setattr(win32gui, 'IsWindowVisible', lambda h: h in visible or h in identifiers)
|
||||
def post(hwnd, message, *_):
|
||||
messages.append((hwnd, message))
|
||||
if hwnd == 202 and message == win32con.BM_CLICK:
|
||||
visible.remove(200)
|
||||
elif hwnd == 100 and message == win32con.WM_CLOSE:
|
||||
records.clear()
|
||||
monkeypatch.setattr(win32gui, 'PostMessage', post)
|
||||
return job, records, messages, names, visible
|
||||
|
||||
|
||||
def test_captured_read_write_question_is_declined_and_own_empty_shell_exits(tmp_path, monkeypatch):
|
||||
import win32con
|
||||
job, records, messages, _, _ = read_write_fixture(tmp_path, monkeypatch)
|
||||
# A pre-existing address must not prevent cancelling our own attempted open.
|
||||
address = tmp_path/'database/cdbsvr/sAddress.adr'
|
||||
address.parent.mkdir(parents=True)
|
||||
address.write_text('existing foreign or stale address')
|
||||
result = failed_session.close_failed_startup(job, 12, timeout_seconds=0)
|
||||
assert result['status'] == 'CLOSED' and result['release']['safe_to_continue']
|
||||
assert messages == [(202, win32con.BM_CLICK), (100, win32con.WM_CLOSE)]
|
||||
assert not records and address.read_text() == 'existing foreign or stale address'
|
||||
assert result['cancelled_prompt'] == 'read_write_access'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('obstacle', ['text', 'foreign_pid', 'baseline', 'wrong_path', 'desktop', 'stuck'])
|
||||
def test_read_write_cancel_never_accepts_unconfirmed_or_unclosed_prompt(tmp_path, monkeypatch, obstacle):
|
||||
import win32gui, win32process, win32con
|
||||
from cbb_refresh_verify import native_repair_ui
|
||||
job, records, messages, names, _ = read_write_fixture(tmp_path, monkeypatch)
|
||||
if obstacle == 'text': names[203] += ' Different recovery operation.'
|
||||
if obstacle == 'foreign_pid':
|
||||
monkeypatch.setattr(win32process, 'GetWindowThreadProcessId', lambda h: (1, 99 if h == 200 else 12))
|
||||
if obstacle == 'wrong_path': records[0] = (12, records[0][1], 'other.pcb -ReusableCircuit', 11)
|
||||
if obstacle == 'desktop': monkeypatch.setattr(native_repair_ui, '_current_desktop_name', lambda: 'Default')
|
||||
if obstacle == 'stuck':
|
||||
monkeypatch.setattr(win32gui, 'PostMessage', lambda h, m, *_: messages.append((h, m)))
|
||||
result = failed_session.close_failed_startup(job, 12,
|
||||
baseline_pids=(12,) if obstacle == 'baseline' else (), timeout_seconds=0)
|
||||
assert result['status'] == 'RETAINED' and records
|
||||
assert messages == ([(202, win32con.BM_CLICK)] if obstacle == 'stuck' else [])
|
||||
|
||||
|
||||
def test_version_choice_is_cancelled_without_selecting_or_confirming_a_version(tmp_path, monkeypatch):
|
||||
import win32gui, win32con
|
||||
from test_pcb_version_choice import captured
|
||||
job, records, messages, _, visible = read_write_fixture(tmp_path, monkeypatch)
|
||||
snapshot = captured()
|
||||
children = [c for c in snapshot.controls if c.handle and c.handle != snapshot.hwnd]
|
||||
mapping = {300+i: c for i, c in enumerate(children)}
|
||||
monkeypatch.setattr(win32gui, 'EnumChildWindows', lambda h, fn, arg:
|
||||
[fn(c, arg) for c in mapping] if h == 200 else None)
|
||||
monkeypatch.setattr(win32gui, 'GetClassName', lambda h: mapping[h].class_name if h in mapping else
|
||||
'#32770' if h == 200 else 'Afx:main')
|
||||
monkeypatch.setattr(win32gui, 'GetWindowText', lambda h: mapping[h].name if h in mapping else
|
||||
'Database Restoration' if h == 200 else 'Expedition PCB')
|
||||
monkeypatch.setattr(win32gui, 'GetDlgCtrlID', lambda h: mapping[h].control_id)
|
||||
cancel = next(h for h, c in mapping.items() if c.control_id == 2)
|
||||
def post(h, m, *_):
|
||||
messages.append((h, m))
|
||||
if h == cancel: visible.remove(200)
|
||||
elif h == 100: records.clear()
|
||||
monkeypatch.setattr(win32gui, 'PostMessage', post)
|
||||
result = failed_session.close_failed_startup(job, 12, timeout_seconds=0)
|
||||
assert result['status'] == 'CLOSED' and result['cancelled_prompt'] == 'pcb_version_choice'
|
||||
assert messages == [(cancel, win32con.BM_CLICK), (100, win32con.WM_CLOSE)]
|
||||
|
||||
|
||||
def test_requested_close_without_exit_is_not_reported_closed(tmp_path, monkeypatch):
|
||||
import win32gui
|
||||
job, records, messages = startup_fixture(tmp_path, monkeypatch)
|
||||
monkeypatch.setattr(win32gui, 'PostMessage', lambda hwnd, message, *_: messages.append((hwnd, message)))
|
||||
result = failed_session.close_failed_startup(job, 12, timeout_seconds=0)
|
||||
assert result['status'] == 'RETAINED'
|
||||
assert 'STARTUP_EXIT_UNCONFIRMED' in result['detail']
|
||||
assert len(messages) == 1
|
||||
assert records
|
||||
|
||||
|
||||
@pytest.mark.parametrize('exits', [True, False])
|
||||
def test_after_owned_close_transient_empty_command_waits_for_exit(tmp_path, monkeypatch, exits):
|
||||
from types import SimpleNamespace
|
||||
import win32gui
|
||||
job, records, messages = startup_fixture(tmp_path, monkeypatch)
|
||||
ticks = [0.0]
|
||||
def post(hwnd, message, *_):
|
||||
messages.append((hwnd, message))
|
||||
records[0] = (12, '', '', 11) # WMI during process teardown.
|
||||
def advance(seconds):
|
||||
ticks[0] += seconds
|
||||
if exits: records.clear()
|
||||
monkeypatch.setattr(win32gui, 'PostMessage', post)
|
||||
monkeypatch.setattr(failed_session, 'time', SimpleNamespace(monotonic=lambda: ticks[0], sleep=advance))
|
||||
result = failed_session.close_failed_startup(job, 12, timeout_seconds=1)
|
||||
assert ticks[0] > 0 and len(messages) == 1
|
||||
assert result['status'] == ('CLOSED' if exits else 'RETAINED')
|
||||
assert 'STARTUP_PROCESS_UNCONFIRMED' not in result.get('detail', '')
|
||||
|
||||
|
||||
@pytest.mark.parametrize('obstacle', ['address', 'dialog', 'process'])
|
||||
def test_startup_close_waits_for_native_state_transitions(tmp_path, monkeypatch, obstacle):
|
||||
from types import SimpleNamespace
|
||||
import win32gui
|
||||
job, records, messages = startup_fixture(tmp_path, monkeypatch)
|
||||
ticks = [0]
|
||||
address = tmp_path/'database/cdbsvr/sAddress.adr'
|
||||
if obstacle == 'address':
|
||||
address.parent.mkdir(parents=True)
|
||||
address.write_text('owner')
|
||||
if obstacle == 'dialog':
|
||||
monkeypatch.setattr(win32gui, 'GetClassName',
|
||||
lambda _: '#32770' if ticks[0] == 0 else 'Afx:main')
|
||||
if obstacle == 'process':
|
||||
monkeypatch.setattr(win32gui, 'PostMessage',
|
||||
lambda hwnd, message, *_: messages.append((hwnd, message)))
|
||||
def advance(seconds):
|
||||
ticks[0] += seconds
|
||||
if obstacle == 'address' and address.exists(): address.unlink()
|
||||
if obstacle == 'process' and messages: records.clear()
|
||||
monkeypatch.setattr(failed_session, 'time', SimpleNamespace(
|
||||
monotonic=lambda: ticks[0], sleep=advance))
|
||||
result = failed_session.close_failed_startup(job, 12, timeout_seconds=1)
|
||||
assert ticks[0] > 0
|
||||
assert result['status'] == 'CLOSED'
|
||||
assert len(messages) == 1
|
||||
assert not records
|
||||
|
||||
|
||||
def test_worker_closes_startup_failure_before_document_identity(tmp_path, monkeypatch):
|
||||
from test_verify_worker_stability import exercise_worker
|
||||
job, events, execute = exercise_worker(tmp_path, monkeypatch)
|
||||
job['desktop'] = 'CbbVerify_test'
|
||||
def fail_open(*args, **kwargs):
|
||||
raise RuntimeError('VERIFY_CANCELLED: database open failed')
|
||||
monkeypatch.setattr('cbb_refresh_verify.pcb_bridge.wait_for_target_document', fail_open)
|
||||
# Native process/window behavior is covered above; here verify the worker
|
||||
# actually reaches startup cleanup instead of requiring a loaded document.
|
||||
def close(job, pid, **kwargs):
|
||||
kwargs['emit'](stage='startup_close_result', status='CLOSED', pcb_pid=pid)
|
||||
return {'status': 'CLOSED'}
|
||||
monkeypatch.setattr(failed_session, 'close_failed_startup', close, raising=False)
|
||||
with pytest.raises(RuntimeError, match='VERIFY_CANCELLED'):
|
||||
execute()
|
||||
assert any(e['stage'] == 'startup_close_result' and e['pcb_pid'] == 2 for e in events)
|
||||
assert not any(e['stage'] == 'save_start' for e in events)
|
||||
|
||||
|
||||
def test_failed_startup_accepts_current_owned_database_failure_dialog(tmp_path, monkeypatch):
|
||||
job, records, messages = startup_fixture(tmp_path, monkeypatch)
|
||||
(tmp_path/'diagnostics/icdb-recovery.json').unlink()
|
||||
(tmp_path/'dialogs.jsonl').write_text(json.dumps({
|
||||
'pid': 12, 'phase': 'PCB_STARTING', 'error_code': 'MENTOR_DATABASE_LOAD_FAILED'})+'\n')
|
||||
result = failed_session.close_failed_startup(job, 12, timeout_seconds=0)
|
||||
assert result['status'] == 'CLOSED'
|
||||
assert not records
|
||||
|
||||
|
||||
@pytest.mark.parametrize('pid,phase', [(99, 'PCB_STARTING'), (12, 'SAVING')])
|
||||
def test_unrelated_failure_record_is_not_needed_to_close_own_empty_shell(tmp_path, monkeypatch, pid, phase):
|
||||
job, records, messages = startup_fixture(tmp_path, monkeypatch)
|
||||
(tmp_path/'diagnostics/icdb-recovery.json').unlink()
|
||||
(tmp_path/'dialogs.jsonl').write_text(json.dumps({
|
||||
'pid': pid, 'phase': phase, 'error_code': 'MENTOR_DATABASE_LOAD_FAILED'})+'\n')
|
||||
assert failed_session.close_failed_startup(job, 12, timeout_seconds=0)['status'] == 'CLOSED'
|
||||
assert len(messages) == 1 and not records
|
||||
|
||||
|
||||
@pytest.mark.parametrize('exits', [True, False])
|
||||
def test_startup_close_waits_for_launcher_after_empty_pcb_exit(tmp_path, monkeypatch, exits):
|
||||
from types import SimpleNamespace
|
||||
job, records, messages = startup_fixture(tmp_path, monkeypatch)
|
||||
ticks = [0.0]
|
||||
launcher = SimpleNamespace(pid=11, poll=lambda: 0 if exits and ticks[0] >= .4 else None)
|
||||
monkeypatch.setattr(failed_session, 'time', SimpleNamespace(
|
||||
monotonic=lambda: ticks[0], sleep=lambda seconds: ticks.__setitem__(0, ticks[0]+seconds)))
|
||||
result = failed_session.close_failed_startup(job, 12, launcher_process=launcher, timeout_seconds=1)
|
||||
assert ticks[0] >= .4
|
||||
assert result['status'] == ('CLOSED' if exits else 'RETAINED')
|
||||
assert result['release']['launcher_exited'] is exits
|
||||
assert result['release']['pcb_exited'] is True
|
||||
assert len(messages) == 1
|
||||
|
||||
|
||||
def test_startup_exit_does_not_hide_late_database_address(tmp_path, monkeypatch):
|
||||
import win32gui
|
||||
job, records, messages = startup_fixture(tmp_path, monkeypatch)
|
||||
def close(*args):
|
||||
records.clear()
|
||||
address = tmp_path/'database/cdbsvr/sAddress.adr'
|
||||
address.parent.mkdir(parents=True)
|
||||
address.write_text('still owned')
|
||||
monkeypatch.setattr(win32gui, 'PostMessage', close)
|
||||
result = failed_session.close_failed_startup(job, 12, timeout_seconds=0)
|
||||
assert result['status'] == 'RETAINED'
|
||||
assert result['release']['addresses']
|
||||
|
||||
|
||||
@pytest.mark.parametrize('window_class,title', [('CustomPrompt', 'Database action pending'),
|
||||
('Afx:tool', ''), ('UAC_InputIndicatorOverlayWnd', 'Unknown prompt'), ('UAC Input Indicator', ' ')])
|
||||
def test_enabled_empty_main_with_unaccounted_owned_window_is_never_closed(tmp_path, monkeypatch, window_class, title):
|
||||
import win32gui
|
||||
job, records, messages = startup_fixture(tmp_path, monkeypatch)
|
||||
monkeypatch.setattr(win32gui, 'EnumWindows', lambda fn, arg: [fn(hwnd, arg) for hwnd in (100, 200)])
|
||||
monkeypatch.setattr(win32gui, 'GetClassName', lambda hwnd: 'Afx:main' if hwnd == 100 else window_class)
|
||||
monkeypatch.setattr(win32gui, 'GetWindowText', lambda hwnd: 'Expedition PCB' if hwnd == 100 else title)
|
||||
result = failed_session.close_failed_startup(job, 12, timeout_seconds=0)
|
||||
assert result['status'] == 'RETAINED' and not result['release']['safe_to_continue']
|
||||
assert messages == [] and records
|
||||
assert result['unknown_windows'] == [{'hwnd': 200, 'class': window_class, 'title': title, 'enabled': True}]
|
||||
assert json.loads((tmp_path/'startup-close.json').read_text(encoding='utf-8'))['unknown_windows'] == result['unknown_windows']
|
||||
|
||||
|
||||
def test_empty_title_known_uac_windows_are_accounted_for_before_normal_close(tmp_path, monkeypatch):
|
||||
import win32gui, win32con
|
||||
job, records, messages = startup_fixture(tmp_path, monkeypatch)
|
||||
classes = {100: 'Afx:main', 200: 'UAC_InputIndicatorOverlayWnd', 201: 'UAC Input Indicator'}
|
||||
monkeypatch.setattr(win32gui, 'EnumWindows', lambda fn, arg: [fn(hwnd, arg) for hwnd in classes])
|
||||
monkeypatch.setattr(win32gui, 'GetClassName', classes.__getitem__)
|
||||
monkeypatch.setattr(win32gui, 'GetWindowText', lambda hwnd: 'Expedition PCB' if hwnd == 100 else '')
|
||||
result = failed_session.close_failed_startup(job, 12, timeout_seconds=0)
|
||||
assert result['status'] == 'CLOSED' and messages == [(100, win32con.WM_CLOSE)]
|
||||
assert result['unknown_windows'] == []
|
||||
assert [entry['hwnd'] for entry in result['benign_auxiliary_windows']] == [200, 201]
|
||||
|
||||
|
||||
def test_custom_prompt_must_disappear_before_main_close(tmp_path, monkeypatch):
|
||||
from types import SimpleNamespace
|
||||
import win32gui
|
||||
job, records, messages = startup_fixture(tmp_path, monkeypatch)
|
||||
ticks = [0.0]
|
||||
monkeypatch.setattr(win32gui, 'EnumWindows', lambda fn, arg:
|
||||
[fn(hwnd, arg) for hwnd in ((100, 200) if ticks[0] == 0 else (100,))])
|
||||
monkeypatch.setattr(win32gui, 'GetClassName', lambda hwnd: 'Afx:main' if hwnd == 100 else 'CustomPrompt')
|
||||
monkeypatch.setattr(win32gui, 'GetWindowText', lambda hwnd: 'Expedition PCB' if hwnd == 100 else 'Still processing')
|
||||
monkeypatch.setattr(failed_session, 'time', SimpleNamespace(monotonic=lambda: ticks[0],
|
||||
sleep=lambda seconds: ticks.__setitem__(0, ticks[0] + seconds)))
|
||||
result = failed_session.close_failed_startup(job, 12, timeout_seconds=1)
|
||||
assert result['status'] == 'CLOSED' and ticks[0] > 0
|
||||
assert len(messages) == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize('obstacle', ['', 'title', 'area', 'children', 'near_class'])
|
||||
def test_only_exact_empty_zero_area_childless_ie_infrastructure_is_benign(tmp_path, monkeypatch, obstacle):
|
||||
import win32gui, win32con
|
||||
job, records, messages = startup_fixture(tmp_path, monkeypatch)
|
||||
monkeypatch.setattr(win32gui, 'EnumWindows', lambda fn, arg: [fn(hwnd, arg) for hwnd in (100, 200)])
|
||||
monkeypatch.setattr(win32gui, 'GetClassName', lambda hwnd: 'Afx:main' if hwnd == 100 else
|
||||
'Internet Explorer_Hidden_other' if obstacle == 'near_class' else 'Internet Explorer_Hidden')
|
||||
monkeypatch.setattr(win32gui, 'GetWindowText', lambda hwnd: 'Expedition PCB' if hwnd == 100 else
|
||||
'Active prompt' if obstacle == 'title' else '')
|
||||
monkeypatch.setattr(win32gui, 'GetWindowRect', lambda hwnd: (0, 0, 100, 50) if obstacle == 'area' else (0, 0, 0, 0))
|
||||
monkeypatch.setattr(win32gui, 'EnumChildWindows', lambda hwnd, fn, arg:
|
||||
fn(201, arg) if hwnd == 200 and obstacle == 'children' else None)
|
||||
result = failed_session.close_failed_startup(job, 12, timeout_seconds=0)
|
||||
if obstacle:
|
||||
assert result['status'] == 'RETAINED' and messages == []
|
||||
assert result['unknown_windows'][0]['hwnd'] == 200
|
||||
else:
|
||||
assert result['status'] == 'CLOSED' and messages == [(100, win32con.WM_CLOSE)]
|
||||
entry = result['benign_auxiliary_windows'][0]
|
||||
assert entry['class'] == 'Internet Explorer_Hidden' and entry['rect'] == [0, 0, 0, 0]
|
||||
assert entry['children'] == []
|
||||
@@ -200,14 +200,14 @@ def test_worker_attempts_normal_close_after_idle_integration_failure(tmp_path, m
|
||||
assert not any(event['stage'] == 'save_start' for event in events)
|
||||
|
||||
|
||||
def test_stop_requests_cooperative_cancel_without_terminating_busy_client(tmp_path):
|
||||
def test_stop_cancels_then_stops_automation_client_after_deadline(tmp_path):
|
||||
calls = []
|
||||
class BusyWorker:
|
||||
def request_stop(self): calls.append('cancel')
|
||||
def wait(self, timeout): raise TimeoutError('native Save still running')
|
||||
def kill(self): calls.append('kill')
|
||||
runner._stop_worker(BusyWorker(), timeout=0)
|
||||
assert calls == ['cancel']
|
||||
assert calls == ['cancel', 'kill']
|
||||
|
||||
|
||||
def test_status_server_close_allows_eof_cleanup_before_termination(tmp_path):
|
||||
@@ -225,21 +225,22 @@ def test_status_server_close_allows_eof_cleanup_before_termination(tmp_path):
|
||||
assert marker.is_file()
|
||||
|
||||
|
||||
def test_shared_symbol_database_owner_blocks_content_check_and_pcb(tmp_path, monkeypatch):
|
||||
def test_shared_address_does_not_block_actual_content_check(tmp_path, monkeypatch):
|
||||
from test_verify_runner import fixture, request
|
||||
fixture(tmp_path)
|
||||
address = tmp_path/'SymbolLibs/__ReusableBlocksSymb/cdbsvr/sAddress.adr'
|
||||
address.parent.mkdir(parents=True)
|
||||
address.write_bytes(b'unknown native owner')
|
||||
req = request(tmp_path, libspec='EE', dms_login_config='login')
|
||||
outcome = runner.run_verify(req, process_runner=lambda *args: pytest.fail('must not launch importer'))
|
||||
assert outcome.status == 'BLOCKED'
|
||||
assert outcome.safe_to_continue is False
|
||||
assert '__ReusableBlocksSymb' in outcome.stderr
|
||||
calls = []
|
||||
outcome = runner.run_verify(req, process_runner=lambda *args:
|
||||
(calls.append(args) or (1, 'ERROR: shared database unavailable', '', False)))
|
||||
assert calls and outcome.status == 'FAIL' and outcome.safe_to_continue
|
||||
assert 'shared database unavailable' in outcome.stderr
|
||||
assert address.read_bytes() == b'unknown native owner'
|
||||
|
||||
|
||||
def test_shared_symbol_database_must_be_released_before_pass(tmp_path, monkeypatch):
|
||||
def test_shared_address_is_diagnostic_after_successful_native_execution(tmp_path, monkeypatch):
|
||||
from test_verify_worker_stability import exercise_worker
|
||||
from cbb_refresh_verify import mentor_adapter as adapter
|
||||
job, events, execute = exercise_worker(tmp_path, monkeypatch)
|
||||
@@ -250,9 +251,8 @@ def test_shared_symbol_database_must_be_released_before_pass(tmp_path, monkeypat
|
||||
address.write_bytes(b'shared owner retained')
|
||||
return original(*args, **kwargs)
|
||||
monkeypatch.setattr(adapter.subprocess, 'Popen', helper)
|
||||
with pytest.raises(RuntimeError, match='ICDB_RELEASE_UNCONFIRMED'):
|
||||
execute()
|
||||
assert not any(event['stage'] == 'complete' for event in events)
|
||||
assert execute()['status'] == 'PASS'
|
||||
assert any(event['stage'] == 'icdb_address_remaining' for event in events)
|
||||
|
||||
|
||||
def test_cooperative_supervisor_loss_keeps_pending_save_helper_alive(tmp_path):
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
"""PCB open errors identify ICDB findings by native content, never by code alone."""
|
||||
from dataclasses import replace
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from test_maintenance_entry import case, no_native_launch
|
||||
|
||||
|
||||
NATIVE_ERROR = (
|
||||
'Database cannot be loaded and the server cannot be started, the project will not be opened. '
|
||||
"Please use iCDB Project Backup 'Repair project' functionality to fix this issue. "
|
||||
'(Database [C:\\isolated\\Work\\database\\icdb.dat] in old, unsupported format)')
|
||||
|
||||
|
||||
@pytest.mark.parametrize('message,expected', [
|
||||
(NATIVE_ERROR, True),
|
||||
('Unable to open iCDB connection.', True),
|
||||
('iCDB database check FAILED', True),
|
||||
('iCDB database check PASSED', False),
|
||||
('0x8004021E: Failed to open document.', False),
|
||||
('ICDB_REPAIR_REQUIRED: Failed to open document.', False),
|
||||
('Cannot open [C:\\icdb\\icdb.dat].', False),
|
||||
('PCB file was not found. Evidence: C:\\icdb\\result.json', False),
|
||||
])
|
||||
def test_error_content_requires_an_icdb_failure_message(message, expected):
|
||||
from cbb_refresh_verify.icdb_recovery import icdb_error_content
|
||||
assert bool(icdb_error_content(message)) is expected
|
||||
|
||||
|
||||
def test_unknown_icdb_description_in_an_actual_open_error_is_retained():
|
||||
from cbb_refresh_verify.icdb_recovery import icdb_error_content
|
||||
assert icdb_error_content('iCDB connection: E_NEW_NATIVE_CODE', error_message=True)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('mode', ['append', 'rewrite', 'retained', 'unchanged'])
|
||||
def test_native_error_content_is_from_this_open_attempt(tmp_path, mode):
|
||||
from cbb_refresh_verify.icdb_recovery import snapshot_log, read_icdb_error
|
||||
path = tmp_path/'PCBLogFile.txt'
|
||||
previous = 'old header\n'+NATIVE_ERROR+'\n' if mode in ('retained','unchanged') else 'old header\n'
|
||||
path.write_text(previous, 'utf-8')
|
||||
baseline = snapshot_log(path)
|
||||
if mode == 'append': path.write_text(previous+NATIVE_ERROR, 'utf-8')
|
||||
elif mode == 'rewrite': path.write_text('new header\n'+NATIVE_ERROR, 'utf-8')
|
||||
elif mode == 'retained': path.write_text('new header\n'+NATIVE_ERROR+'\nNormal startup', 'utf-8')
|
||||
assert bool(read_icdb_error(path, baseline)) is (mode in ('append','rewrite'))
|
||||
|
||||
|
||||
@pytest.mark.parametrize('failure,category', [(NATIVE_ERROR,'ICDB_REPAIR_REQUIRED'),
|
||||
('0x8004021E: Failed to open document.','MENTOR_DATABASE_LOAD_FAILED')])
|
||||
def test_batch_scan_opens_without_repair_and_classifies_native_content(case, monkeypatch, failure, category):
|
||||
from cbb_refresh_verify import maintenance_entry as entry, verify_runner as runner, native_repair
|
||||
request, _, address = case
|
||||
probes=[]
|
||||
monkeypatch.setattr(native_repair,'run_native_repair',lambda *a,**k:pytest.fail('scan dispatched Project Backup'))
|
||||
def diagnose(probe, **kw):
|
||||
probes.append(probe)
|
||||
return runner.VerifyResult('FAIL',stderr=failure,error_category='MENTOR_DATABASE_LOAD_FAILED')
|
||||
monkeypatch.setattr(runner,'run_verify',diagnose)
|
||||
result=entry.run_icdb_check(replace(request,auto_repair=True))
|
||||
assert len(probes)==1 and probes[0].diagnostic_only and not probes[0].maintenance
|
||||
assert not probes[0].auto_repair and not probes[0].native_lm_verify
|
||||
assert result.status=='FAIL' and result.error_category==category and result.safe_to_continue
|
||||
assert result.library_flag=='UNKNOWN' and result.recovery_attempts==()
|
||||
assert address.read_bytes()==b'old server address - preserved'
|
||||
|
||||
|
||||
def test_scan_uses_the_current_open_evidence_even_when_popup_is_generic(case, monkeypatch):
|
||||
from cbb_refresh_verify import maintenance_entry as entry, verify_runner as runner
|
||||
request, _, _=case
|
||||
def diagnose(probe, **kw):
|
||||
root=probe.evidence_dir/'verify-current'; (root/'diagnostics').mkdir(parents=True)
|
||||
(root/'diagnostics/icdb-error-content.json').write_text(json.dumps(
|
||||
{'native_message':NATIVE_ERROR,'source':'PCBLogFile.txt'}),'utf-8')
|
||||
result=root/'result.json'; result.write_text('{}','utf-8')
|
||||
return runner.VerifyResult('FAIL',stderr='Problem encountered while opening one of the database files.',
|
||||
evidence_path=result,error_category='MENTOR_DATABASE_LOAD_FAILED')
|
||||
monkeypatch.setattr(runner,'run_verify',diagnose)
|
||||
result=entry.run_icdb_check(request)
|
||||
assert result.error_category=='ICDB_REPAIR_REQUIRED' and NATIVE_ERROR in result.stderr
|
||||
|
||||
|
||||
def test_scan_does_not_reuse_an_older_operation_error_evidence(case, monkeypatch):
|
||||
from cbb_refresh_verify import maintenance_entry as entry, verify_runner as runner
|
||||
request,_,_=case
|
||||
root=request.evidence_dir/'older-operation';(root/'diagnostics').mkdir(parents=True)
|
||||
(root/'diagnostics/icdb-error-content.json').write_text(json.dumps({'native_message':NATIVE_ERROR}),'utf-8')
|
||||
result=root/'result.json';result.write_text('{}','utf-8')
|
||||
monkeypatch.setattr(runner,'run_verify',lambda *a,**k:runner.VerifyResult('FAIL',
|
||||
stderr='Failed to open document.',error_category='MENTOR_DATABASE_LOAD_FAILED',evidence_path=result))
|
||||
scanned=entry.run_icdb_check(request)
|
||||
assert scanned.error_category=='MENTOR_DATABASE_LOAD_FAILED'
|
||||
|
||||
|
||||
def test_error_capture_retains_the_new_native_corruption_detail(tmp_path):
|
||||
from cbb_refresh_verify.icdb_recovery import snapshot_log
|
||||
from cbb_refresh_verify.verify_diagnostics import collect_native_failure_logs
|
||||
pcb=tmp_path/'PCB/CBB.pcb'; log=pcb.parent/'LogFiles/PCBLogFile.txt'
|
||||
log.parent.mkdir(parents=True)
|
||||
evidence=tmp_path/'evidence'; (evidence/'diagnostics').mkdir(parents=True)
|
||||
baseline=snapshot_log(log)
|
||||
(evidence/'diagnostics/startup-log-baseline.json').write_text(json.dumps(
|
||||
{'source':str(log),'baseline':baseline}),'utf-8')
|
||||
log.write_text(NATIVE_ERROR,'utf-8')
|
||||
collect_native_failure_logs(pcb,evidence)
|
||||
record=json.loads((evidence/'diagnostics/icdb-error-content.json').read_text('utf-8'))
|
||||
assert record['source']==str(log) and record['native_message']==NATIVE_ERROR
|
||||
|
||||
|
||||
@pytest.mark.parametrize('scenario', ['current', 'other_pid', 'old', 'other_database'])
|
||||
def test_repeated_failure_uses_only_this_pcb_process_icdb_log(tmp_path, scenario):
|
||||
import os,time
|
||||
from cbb_refresh_verify.verify_diagnostics import collect_native_client_error
|
||||
root=tmp_path/'evidence'; (root/'diagnostics').mkdir(parents=True)
|
||||
logs=tmp_path/'Client/Logs'
|
||||
pid=123
|
||||
started=time.time_ns()-1_000_000_000
|
||||
folder=logs/('2026-11-05 12.00.00-'+str(321 if scenario=='other_pid' else pid))
|
||||
folder.mkdir(parents=True)
|
||||
source=folder/'2026.11.05.iCDBManager.txt'
|
||||
database=tmp_path/'Work/database'
|
||||
message=f'SingleFile: ERROR: Database [{database}/icdb.dat] in old, unsupported format'
|
||||
if scenario=='other_database': message=message.replace(str(database),'C:/other/database')
|
||||
source.write_text(f'PID [{pid}]\n'+message,'utf-8')
|
||||
if scenario=='old':os.utime(source,ns=(started-1_000_000_000,started-1_000_000_000))
|
||||
(root/'diagnostics/native-client-context.json').write_text(json.dumps(
|
||||
{'native_pid':pid,'started_ns':started,'client_log_root':str(logs),'database':str(database)}),'utf-8')
|
||||
collect_native_client_error(root)
|
||||
result=root/'diagnostics/icdb-error-content.json'
|
||||
assert result.exists() is (scenario=='current')
|
||||
if result.exists():
|
||||
record=json.loads(result.read_text('utf-8'))
|
||||
assert record['native_pid']==pid and 'unsupported format' in record['native_message']
|
||||
@@ -258,7 +258,7 @@ def test_native_log_capture_generates_only_fresh_repair_evidence(tmp_path, name)
|
||||
assert log.read_text('utf-8') == ERROR
|
||||
|
||||
|
||||
def test_contents_session_loss_stops_batch_before_any_pcb_launch(tmp_path, monkeypatch):
|
||||
def test_contents_session_loss_records_each_item_without_launching_pcb_or_repair(tmp_path, monkeypatch):
|
||||
from test_verify_runner import fixture, request
|
||||
fixture(tmp_path)
|
||||
monkeypatch.setattr(runner, 'resolve_importer', lambda *_: Path('ReuseBlockImporter.exe'))
|
||||
@@ -269,11 +269,12 @@ def test_contents_session_loss_stops_batch_before_any_pcb_launch(tmp_path, monke
|
||||
results = runner.run_batch([request(tmp_path, libspec='EE', dms_login_config='login')]*2,
|
||||
verifier=lambda req: runner.run_verify(req, process_runner=content_check,
|
||||
port_check=lambda: pytest.fail('PCB must not start')))
|
||||
assert len(calls) == 1
|
||||
assert len(calls) == 2
|
||||
assert results[0].error_category == 'ICDB_REPAIR_REQUIRED'
|
||||
assert results[0].safe_to_continue is False
|
||||
assert results[0].safe_to_continue is True
|
||||
assert 'Repair project' in results[0].stderr
|
||||
assert results[1].status == 'SKIPPED'
|
||||
assert results[1].status == 'FAIL'
|
||||
assert results[1].error_category == 'ICDB_REPAIR_REQUIRED'
|
||||
|
||||
|
||||
def test_supervisor_enriches_generic_failure_from_fresh_native_log(tmp_path, monkeypatch):
|
||||
@@ -302,7 +303,7 @@ def test_supervisor_enriches_generic_failure_from_fresh_native_log(tmp_path, mon
|
||||
monkeypatch.setattr('cbb_refresh_verify.verify_diagnostics.capture_failure_logs_with_timeout', failure_logs_main)
|
||||
result = runner.run_verify(request(tmp_path), port_check=lambda: (True, ''))
|
||||
assert result.error_category == 'ICDB_REPAIR_REQUIRED'
|
||||
assert result.safe_to_continue is False
|
||||
assert result.safe_to_continue is True
|
||||
assert 'opening failed' in result.stderr
|
||||
assert '200091-CBB' in result.stderr
|
||||
assert '__ReusableBlocksSymb' in result.stderr
|
||||
|
||||
@@ -27,12 +27,11 @@ def test_network_timeout_cannot_remove_database_advertisement(tmp_path, monkeypa
|
||||
|
||||
|
||||
@pytest.mark.parametrize('state', ['LIVE', 'UNREACHABLE', 'INVALID'])
|
||||
def test_existing_database_owner_blocks_before_pcb_launch(tmp_path, monkeypatch, state):
|
||||
def test_address_probe_result_is_not_a_substitute_for_native_verify(tmp_path, monkeypatch, state):
|
||||
job, events, execute = exercise_worker(tmp_path, monkeypatch)
|
||||
monkeypatch.setattr(adapter, 'prepare_icdb_address', lambda *a, **k: {'status': state})
|
||||
with pytest.raises(RuntimeError, match='ICDB_SESSION_UNCONFIRMED'):
|
||||
execute()
|
||||
assert not any(e['stage'] == 'pcb_launch' for e in events)
|
||||
assert execute()['status'] == 'PASS'
|
||||
assert any(e['stage'] == 'pcb_launch' for e in events)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('text', [
|
||||
@@ -114,7 +113,7 @@ def test_desktop_abort_does_not_kill_native_process_tree(monkeypatch):
|
||||
assert worker.handle in terminated
|
||||
|
||||
|
||||
def test_saved_pcb_with_retained_icdb_address_cannot_pass(tmp_path, monkeypatch):
|
||||
def test_saved_pcb_with_address_records_remains_an_execution_result_for_bridge_validation(tmp_path, monkeypatch):
|
||||
job, events, execute = exercise_worker(tmp_path, monkeypatch)
|
||||
original = adapter.subprocess.Popen
|
||||
def helper(*a, **k):
|
||||
@@ -123,9 +122,8 @@ def test_saved_pcb_with_retained_icdb_address_cannot_pass(tmp_path, monkeypatch)
|
||||
address.write_text('still owned', encoding='ascii')
|
||||
return original(*a, **k)
|
||||
monkeypatch.setattr(adapter.subprocess, 'Popen', helper)
|
||||
with pytest.raises(RuntimeError, match='ICDB_RELEASE_UNCONFIRMED'):
|
||||
execute()
|
||||
assert not any(e['stage'] == 'complete' for e in events)
|
||||
assert execute()['status'] == 'PASS'
|
||||
assert any(e['stage'] == 'icdb_address_remaining' for e in events)
|
||||
|
||||
|
||||
def test_retained_pcb_after_close_cannot_pass_or_be_killed(tmp_path, monkeypatch):
|
||||
@@ -189,7 +187,8 @@ def test_supervisor_rejects_pass_when_native_release_is_unconfirmed(tmp_path, mo
|
||||
|
||||
def test_existing_pcb_session_blocks_before_mutating_project(tmp_path, monkeypatch):
|
||||
job, events, execute = exercise_worker(tmp_path, monkeypatch)
|
||||
monkeypatch.setattr(adapter, 'pcb_processes', lambda: ((20, 'ExpeditionPCB.exe', 'user design'),))
|
||||
monkeypatch.setattr(adapter, 'pcb_processes', lambda:
|
||||
((20, 'ExpeditionPCB.exe', f'ExpeditionPCB.exe "{job["pcb"]}"'),))
|
||||
with pytest.raises(RuntimeError, match='PCB_SESSION_ACTIVE'):
|
||||
execute()
|
||||
assert not events
|
||||
@@ -209,7 +208,9 @@ def test_real_windows_job_abort_preserves_native_like_child(tmp_path):
|
||||
script.write_text(
|
||||
'import subprocess, sys, time\nfrom pathlib import Path\n'
|
||||
'child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(30)"])\n'
|
||||
f'Path({str(pid_path)!r}).write_text(str(child.pid))\n'
|
||||
f'pid_file = Path({str(pid_path)!r})\n'
|
||||
'pending = pid_file.with_suffix(".pending")\n'
|
||||
'pending.write_text(str(child.pid)); pending.replace(pid_file)\n'
|
||||
'time.sleep(30)\n', encoding='utf-8')
|
||||
worker = DesktopWorker([sys.executable, str(script)], 'CbbSafetyTest_' + uuid.uuid4().hex[:8])
|
||||
child_handle = None
|
||||
|
||||
@@ -290,6 +290,45 @@ def test_refresh_integration_skips_native_disabled_green_action():
|
||||
assert pi.actions == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize('ces_allowed', [True, False])
|
||||
def test_partial_sync_respects_protected_green_native_actions(ces_allowed):
|
||||
class RestoredVerifiedBlock(GreenProjectIntegration):
|
||||
IsForwardAnnotationAllowed = False
|
||||
BackAnnotationStatus = 1
|
||||
|
||||
def ForwardAnnotate(self):
|
||||
raise RuntimeError('Forward Annotation is not allowed on verified Reusable Blocks')
|
||||
|
||||
def BackAnnotate(self):
|
||||
super().BackAnnotate()
|
||||
self.BackAnnotationStatus = 2
|
||||
return True
|
||||
|
||||
pi = RestoredVerifiedBlock()
|
||||
pi.IsSynchCESAllowed = pi.IsLoadCESAllowed = ces_allowed
|
||||
events = []
|
||||
result = refresh_integration(pi, settle_seconds=0, emit=lambda **e: events.append(e))
|
||||
assert set(result.values()) == {2}
|
||||
assert pi.actions == (['SynchCES', 'LoadCES', 'BackAnnotate'] if ces_allowed else ['BackAnnotate'])
|
||||
assert [e['action'] for e in events if e['stage'] == 'integration_action'] == pi.actions
|
||||
|
||||
|
||||
def test_skipped_green_action_cannot_hide_a_later_required_native_gate():
|
||||
class ChangedAfterCES(GreenProjectIntegration):
|
||||
IsForwardAnnotationAllowed = False
|
||||
BackAnnotationStatus = 1
|
||||
|
||||
def SynchCES(self):
|
||||
super().SynchCES()
|
||||
self.ForwardAnnotationStatus = 1
|
||||
return True
|
||||
|
||||
pi = ChangedAfterCES()
|
||||
with pytest.raises(IntegrationError, match='ForwardAnnotation: required but not allowed'):
|
||||
refresh_integration(pi, settle_seconds=0)
|
||||
assert pi.actions == ['SynchCES']
|
||||
|
||||
|
||||
def test_refresh_integration_never_counts_rejected_green_action_as_completed():
|
||||
class VerifiedProjectIntegration(GreenProjectIntegration):
|
||||
def _blocked(self, action):
|
||||
|
||||
@@ -0,0 +1,286 @@
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
import pytest
|
||||
import win32con
|
||||
import win32file
|
||||
|
||||
|
||||
def test_library_lock_excludes_other_thread_and_uploader_but_reenters(tmp_path):
|
||||
from cbb_refresh_verify.library_lock import LibraryLock, LibraryBusy
|
||||
library = tmp_path/'test.lmc'
|
||||
library.write_bytes(b'fixture')
|
||||
with LibraryLock(library) as lock:
|
||||
assert lock.path.name == '.test.cbb-upload.lock'
|
||||
with LibraryLock(library):
|
||||
assert lock.snapshot_bytes()
|
||||
with pytest.raises(Exception):
|
||||
win32file.CreateFile(str(lock.path), win32con.GENERIC_READ | win32con.GENERIC_WRITE,
|
||||
0, None, win32con.OPEN_ALWAYS, 0, None)
|
||||
def competing():
|
||||
with pytest.raises(LibraryBusy):
|
||||
with LibraryLock(library):
|
||||
pass
|
||||
with ThreadPoolExecutor(1) as pool:
|
||||
pool.submit(competing).result()
|
||||
assert lock.path.exists()
|
||||
with LibraryLock(library):
|
||||
pass
|
||||
|
||||
|
||||
def test_complete_copy_reads_owned_lock_without_reopening(tmp_path):
|
||||
from cbb_refresh_verify.library_lock import LibraryLock
|
||||
from cbb_refresh_verify.scoped_manifest import copy_verified
|
||||
source = tmp_path/'library'
|
||||
source.mkdir()
|
||||
library = source/'test.lmc'
|
||||
library.write_bytes(b'fixture')
|
||||
with LibraryLock(library) as lock:
|
||||
expected = lock.snapshot_bytes()
|
||||
copy_verified(source, tmp_path/'snapshot')
|
||||
assert (tmp_path/'snapshot'/lock.path.name).read_bytes() == expected
|
||||
|
||||
|
||||
def test_external_lock_never_gets_snapshot_exception(tmp_path):
|
||||
from cbb_refresh_verify.scoped_manifest import copy_verified
|
||||
source = tmp_path/'library'
|
||||
source.mkdir()
|
||||
path = source/'.test.cbb-upload.lock'
|
||||
path.write_bytes(b'external')
|
||||
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ | win32con.GENERIC_WRITE,
|
||||
0, None, win32con.OPEN_EXISTING, 0, None)
|
||||
try:
|
||||
with pytest.raises(OSError):
|
||||
copy_verified(source, tmp_path/'snapshot')
|
||||
finally:
|
||||
handle.Close()
|
||||
|
||||
|
||||
def test_verification_refuses_uploader_exclusive_lock_before_native_work(tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.verify_runner as runner
|
||||
library = tmp_path/'lib.lmc'
|
||||
library.touch()
|
||||
lock = tmp_path/'.lib.cbb-upload.lock'
|
||||
handle = win32file.CreateFile(str(lock), win32con.GENERIC_READ | win32con.GENERIC_WRITE,
|
||||
0, None, win32con.OPEN_ALWAYS, 0, None)
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **k: pytest.fail('native work bypassed lock'))
|
||||
try:
|
||||
result = runner.run_verify(runner.VerifyRequest(library, 'Block', tmp_path/'out'))
|
||||
assert result.status == 'FAIL' and result.safe_to_continue
|
||||
finally:
|
||||
handle.Close()
|
||||
|
||||
|
||||
def test_unsafe_verify_records_failure_without_persistent_library_blocker(tmp_path, monkeypatch):
|
||||
import json
|
||||
import cbb_refresh_verify.verify_runner as runner
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
evidence = tmp_path/'out'; evidence.mkdir()
|
||||
(evidence/'session-release.json').write_text(json.dumps({'library': str(library),
|
||||
'block': 'Block', 'worker_exited': True, 'safe_to_continue': True}))
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **k:
|
||||
runner.VerifyResult('FAIL', safe_to_continue=False, evidence_path=evidence/'result.json'))
|
||||
result = runner.run_verify(runner.VerifyRequest(library, 'Block', tmp_path/'out'))
|
||||
assert not result.safe_to_continue
|
||||
assert not locks.blocker_path(library).exists()
|
||||
with locks.LibraryLock(library): pass
|
||||
|
||||
|
||||
def test_explicit_release_requires_fresh_proof_and_never_deletes_sidecar(tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
|
||||
with locks.LibraryLock(library, safe_to_release=lambda: False) as lease:
|
||||
pass
|
||||
try:
|
||||
def denied(*a):
|
||||
raise ValueError('native owner remains')
|
||||
monkeypatch.setattr(locks, '_prove_library_released', denied)
|
||||
with pytest.raises(ValueError, match='native owner'):
|
||||
locks.release_retained_library(library, tmp_path/'release')
|
||||
assert locks.blocker_path(library).is_file()
|
||||
from contextlib import contextmanager
|
||||
@contextmanager
|
||||
def proof(*a):
|
||||
yield {'native_owners': [], 'addresses': [], 'exclusive_files': [str(library)]}
|
||||
monkeypatch.setattr(locks, '_prove_library_released', proof)
|
||||
result = locks.release_retained_library(library, tmp_path/'release')
|
||||
assert result['status'] == 'RELEASE_CONFIRMED'
|
||||
assert lease.path.is_file() and not locks.blocker_path(library).exists()
|
||||
with locks.LibraryLock(library): pass
|
||||
finally:
|
||||
with locks._guard:
|
||||
owner = locks._owners.pop(str(lease.path.resolve()).casefold(), None)
|
||||
if owner: owner['handle'].Close()
|
||||
|
||||
|
||||
def test_release_proof_checks_addresses_and_exclusive_databases(tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
import cbb_refresh_verify.owner_probe as probe
|
||||
monkeypatch.setattr(probe, 'query_owners', lambda *_: [])
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
address = tmp_path/'database/cdbsvr/sAddress.adr'; address.parent.mkdir(parents=True)
|
||||
address.touch()
|
||||
with pytest.raises(locks.LibraryBusy):
|
||||
with locks._prove_library_released(library): pass
|
||||
address.unlink() # Test-created empty marker, never a native address file.
|
||||
handle = win32file.CreateFile(str(library), win32con.GENERIC_READ, 0, None,
|
||||
win32con.OPEN_EXISTING, 0, None)
|
||||
try:
|
||||
with pytest.raises(Exception):
|
||||
with locks._prove_library_released(library): pass
|
||||
finally:
|
||||
handle.Close()
|
||||
with locks._prove_library_released(library) as proof:
|
||||
assert proof['exclusive_files'] == [str(library)]
|
||||
|
||||
|
||||
def test_release_does_not_resolve_every_unrelated_generated_file(tmp_path, monkeypatch):
|
||||
from pathlib import Path
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
import cbb_refresh_verify.owner_probe as probe
|
||||
monkeypatch.setattr(probe, 'query_owners', lambda *_: [])
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
outputs = tmp_path/'generated'; outputs.mkdir()
|
||||
for index in range(100): (outputs/f'{index}.log').touch()
|
||||
database = tmp_path/'database/icdb.dat'; database.parent.mkdir(); database.touch()
|
||||
resolve = Path.resolve
|
||||
def guarded(path, *a, **kw):
|
||||
assert path.parent != outputs, 'Release resolved unrelated generated content'
|
||||
return resolve(path, *a, **kw)
|
||||
monkeypatch.setattr(Path, 'resolve', guarded)
|
||||
with locks._prove_library_released(library) as proof:
|
||||
assert set(proof['exclusive_files']) == {str(library), str(database)}
|
||||
|
||||
|
||||
def test_scoped_release_ignores_another_cbb_address(tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
import cbb_refresh_verify.owner_probe as probe
|
||||
monkeypatch.setattr(probe, 'query_owners', lambda *_: [])
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
other = tmp_path/'ReusableBlocksLP/Other/Work/database/cdbsvr/sAddress.adr'
|
||||
other.parent.mkdir(parents=True); other.touch()
|
||||
with locks._prove_library_released(library, block_name='Target') as proof:
|
||||
assert proof['addresses'] == []
|
||||
|
||||
|
||||
def test_release_probe_timeout_does_not_clear_retained_checkpoint(tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
import cbb_refresh_verify.owner_probe as probe
|
||||
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
|
||||
with locks.LibraryLock(library, safe_to_release=lambda: False) as lease: pass
|
||||
marker = locks.blocker_path(library)
|
||||
before = marker.read_bytes()
|
||||
def timeout(*args): raise RuntimeError('OWNER_QUERY_TIMEOUT')
|
||||
monkeypatch.setattr(probe, 'query_owners', timeout)
|
||||
try:
|
||||
with pytest.raises(RuntimeError, match='OWNER_QUERY_TIMEOUT'):
|
||||
locks.release_retained_library(library, tmp_path/'release')
|
||||
assert marker.read_bytes() == before
|
||||
finally:
|
||||
with locks._guard:
|
||||
owner = locks._owners.pop(lease.key, None)
|
||||
if owner: owner['handle'].Close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('name,command', [
|
||||
('cscript.exe', 'cscript.exe close_failed_block.vbs'),
|
||||
('python.exe', 'python.exe -m cbb_refresh_verify --repair-worker job.json'),
|
||||
])
|
||||
def test_release_proof_waits_for_late_operation_helpers(tmp_path, monkeypatch, name, command):
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
import cbb_refresh_verify.owner_probe as probe
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
monkeypatch.setattr(probe, 'query_owners', lambda names:
|
||||
[{'pid': 123456, 'name': name, 'command': command}] if name in names else [])
|
||||
with pytest.raises(locks.LibraryBusy, match='123456'):
|
||||
with locks._prove_library_released(library): pass
|
||||
|
||||
|
||||
def test_release_rechecks_owners_after_database_handles_are_acquired(tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
import cbb_refresh_verify.owner_probe as probe
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
calls = []
|
||||
def query(names):
|
||||
calls.append(1)
|
||||
return [] if len(calls) == 1 else [{'pid': 123456, 'name': 'cscript.exe', 'command': 'helper'}]
|
||||
monkeypatch.setattr(probe, 'query_owners', query)
|
||||
with pytest.raises(locks.LibraryBusy, match='123456'):
|
||||
with locks._prove_library_released(library): pass
|
||||
|
||||
|
||||
def test_public_verify_initializes_com_in_its_operation_thread(tmp_path, monkeypatch):
|
||||
import ctypes
|
||||
import cbb_refresh_verify.verify_runner as runner
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
def serialized(*a, **k):
|
||||
apartment, qualifier = ctypes.c_int(), ctypes.c_int()
|
||||
ole32 = ctypes.WinDLL('ole32')
|
||||
ole32.CoGetApartmentType.argtypes = [ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int)]
|
||||
initialized = ole32.CoGetApartmentType(ctypes.byref(apartment), ctypes.byref(qualifier)) == 0
|
||||
return runner.VerifyResult('PASS' if initialized else 'FAIL', stderr='COM apartment check')
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', serialized)
|
||||
with ThreadPoolExecutor(1) as pool:
|
||||
result = pool.submit(runner.run_verify, runner.VerifyRequest(library, 'Block', tmp_path/'out')).result()
|
||||
assert result.status == 'PASS'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('mode,expected', [(0, 1), (2, 0)])
|
||||
def test_public_verify_preserves_existing_apartment(tmp_path, monkeypatch, mode, expected):
|
||||
import ctypes, pythoncom
|
||||
import cbb_refresh_verify.verify_runner as runner
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **k: runner.VerifyResult('PASS'))
|
||||
def existing_mta():
|
||||
pythoncom.CoInitializeEx(mode)
|
||||
try:
|
||||
apartment, qualifier = ctypes.c_int(), ctypes.c_int()
|
||||
ole32 = ctypes.WinDLL('ole32')
|
||||
ole32.CoGetApartmentType.argtypes = [ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int)]
|
||||
assert ole32.CoGetApartmentType(ctypes.byref(apartment), ctypes.byref(qualifier)) == 0
|
||||
before = apartment.value
|
||||
# A thread can be the main STA (3) when it creates the process's
|
||||
# first remaining STA. Verify must preserve either STA flavor.
|
||||
assert before in ((1,) if mode == 0 else (0, 3))
|
||||
runner.run_verify(runner.VerifyRequest(library, 'Block', tmp_path/'out'))
|
||||
result = ole32.CoGetApartmentType(ctypes.byref(apartment), ctypes.byref(qualifier))
|
||||
return result, apartment.value, before
|
||||
finally:
|
||||
pythoncom.CoUninitialize()
|
||||
with ThreadPoolExecutor(1) as pool:
|
||||
result, after, before = pool.submit(existing_mta).result()
|
||||
assert result == 0 and after == before
|
||||
|
||||
|
||||
def test_nested_snapshot_retains_runtime_checkpoint_bytes_without_semantic_conflicts(tmp_path):
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
from cbb_refresh_verify.scoped_manifest import copy_verified, build_manifest, ManifestScope
|
||||
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.write_bytes(b'library')
|
||||
scope = ManifestScope.library('Block', library.name)
|
||||
with locks.LibraryLock(library) as lease:
|
||||
before = copy_verified(library.parent, tmp_path/'snapshot', scope=scope)
|
||||
marker = locks.blocker_path(library)
|
||||
assert (tmp_path/'snapshot'/marker.name).read_bytes() == marker.read_bytes()
|
||||
with locks.LibraryLock(library):
|
||||
owner = locks._owners[lease.key]
|
||||
locks._persist_blocker(library, lease_id=owner['lease_id'])
|
||||
assert build_manifest(library.parent, scope=scope) == before
|
||||
assert not marker.exists() and lease.path.exists()
|
||||
|
||||
|
||||
def test_arbitrary_guard_filename_is_preserved_and_primary(tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
from cbb_refresh_verify.scoped_manifest import build_manifest, ManifestScope
|
||||
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
|
||||
marker = locks.blocker_path(library); marker.write_bytes(b'{not a guard record')
|
||||
with pytest.raises(locks.LibraryBusy):
|
||||
with locks.LibraryLock(library): pass
|
||||
manifest = build_manifest(library.parent, scope=ManifestScope.library('Block', library.name))
|
||||
assert marker.name in manifest['files']
|
||||
from contextlib import contextmanager
|
||||
@contextmanager
|
||||
def proof(*a, **kw): yield {'native_owners': [], 'addresses': [], 'exclusive_files': [str(library)]}
|
||||
monkeypatch.setattr(locks, '_prove_library_released', proof)
|
||||
with pytest.raises(locks.LibraryBusy):
|
||||
locks.release_retained_library(library, tmp_path/'release')
|
||||
assert marker.read_bytes() == b'{not a guard record'
|
||||
@@ -0,0 +1,84 @@
|
||||
"""Native occupancy must precede repair even when old addresses remain."""
|
||||
import pytest
|
||||
from test_maintenance_entry import case, no_native_launch, startup_failure, run_legacy_maintenance
|
||||
from test_native_occupancy import output
|
||||
|
||||
|
||||
def inspection(target, *, fault=False):
|
||||
return {'inspection_only': True, 'repair_requested': False, 'native_pid': 777,
|
||||
'native_exit_code': 0, 'project': str(target.project), 'database': str(target.database),
|
||||
'output': output(target.project, target.database, fault=fault),
|
||||
'status': 'NOT_IN_USE', 'repair_required': fault, 'release': {'native_exited': True}}
|
||||
|
||||
|
||||
@pytest.mark.parametrize('old_address', [False, True])
|
||||
def test_diagnosed_native_inspection_holds_lock_after_opening_pcb(case, monkeypatch, old_address):
|
||||
from cbb_refresh_verify import verify_runner as runner, native_repair, library_lock
|
||||
request, project, address = case
|
||||
if not old_address: address.unlink()
|
||||
calls = []
|
||||
def startup(req, **kw):
|
||||
assert req.diagnostic_only
|
||||
calls.append('open')
|
||||
return startup_failure(req)
|
||||
def native(target, root, **kw):
|
||||
assert calls == ['open']
|
||||
key = library_lock.LibraryLock(request.lmc_file).key
|
||||
assert library_lock._owners[key]['depth'] > 0
|
||||
assert kw['inspection_only'] is True
|
||||
assert kw['timeout_seconds'] <= 30
|
||||
return inspection(target)
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', native)
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', startup)
|
||||
result = run_legacy_maintenance(request)
|
||||
assert result.status == 'CHECKED' and result.recovery_attempts == ()
|
||||
assert result.library_flag == 'UNKNOWN'
|
||||
assert result.safe_to_continue is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize('fault', ['missing', 'generic', 'assertion', 'wrong_database', 'stale_verdict', 'not_exited'])
|
||||
def test_unconfirmed_native_inspection_never_repairs(case, monkeypatch, fault):
|
||||
from cbb_refresh_verify import verify_runner as runner, native_repair
|
||||
request, project, address = case
|
||||
def native(target, root, **kw):
|
||||
assert kw['inspection_only'] is True
|
||||
if fault == 'assertion': raise AssertionError('probe failed')
|
||||
if fault == 'missing': return {}
|
||||
record = inspection(target, fault=True)
|
||||
if fault == 'generic': record['output'] = 'DATABASE_SAFETY_STOP'
|
||||
if fault == 'wrong_database': record['database'] = str(project.parent/'other')
|
||||
if fault == 'stale_verdict': record['output'] += 'Checking if project is in use.'
|
||||
if fault == 'not_exited': record['release']['native_exited'] = False
|
||||
return record
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', native)
|
||||
result = run_legacy_maintenance(request)
|
||||
assert result.status == 'BLOCKED' and not result.recovery_attempts
|
||||
|
||||
|
||||
def test_native_fault_repairs_once_without_running_separate_verification(case, monkeypatch):
|
||||
from cbb_refresh_verify import verify_runner as runner, native_repair
|
||||
from test_native_repair import complete_native_success
|
||||
request, project, address = case
|
||||
calls = []
|
||||
def native(target, root, **kw):
|
||||
if kw.get('inspection_only'):
|
||||
assert address.exists()
|
||||
calls.append('inspect')
|
||||
return inspection(target, fault=True)
|
||||
calls.append('repair')
|
||||
address.unlink() # Simulated native repair release only.
|
||||
return complete_native_success(target)
|
||||
def verify(req, **kw):
|
||||
if req.diagnostic_only:
|
||||
calls.append('open')
|
||||
return startup_failure(req)
|
||||
assert req.post_repair_proof is not None and not req.diagnostic_only and not req.auto_repair
|
||||
calls.append('verify')
|
||||
return runner.VerifyResult('PASS', library_flag='GREEN')
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', native)
|
||||
monkeypatch.setattr(native_repair, 'repair_release_state', lambda req, target, result: result['release'])
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', verify)
|
||||
result = run_legacy_maintenance(request)
|
||||
assert calls == ['open', 'inspect', 'repair']
|
||||
assert result.status == 'REPAIRED' and len(result.recovery_attempts) == 1
|
||||
assert result.library_flag == 'UNKNOWN' and not result.recovery_attempts[0]['validation_passed']
|
||||
@@ -0,0 +1,464 @@
|
||||
"""Explicit maintenance for preexisting advertisements; native writes forbidden."""
|
||||
from dataclasses import replace
|
||||
from contextlib import contextmanager
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def no_native_launch(monkeypatch):
|
||||
import subprocess, win32process, win32com.client
|
||||
import cbb_refresh_verify.desktop_worker as desktop
|
||||
def forbidden(*a, **k): raise AssertionError('No native launch allowed in maintenance tests')
|
||||
monkeypatch.setattr(subprocess, 'Popen', forbidden)
|
||||
monkeypatch.setattr(win32process, 'CreateProcess', forbidden)
|
||||
monkeypatch.setattr(win32com.client, 'Dispatch', forbidden)
|
||||
monkeypatch.setattr(win32com.client, 'DispatchEx', forbidden)
|
||||
monkeypatch.setattr(desktop, 'DesktopWorker', forbidden)
|
||||
monkeypatch.setattr('cbb_refresh_verify.verify_runner.runtime_fingerprint', lambda *_: {})
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def case(tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify.verify_runner import VerifyRequest
|
||||
import cbb_refresh_verify.maintenance_entry as entry
|
||||
library = tmp_path/'library/mentor.lmc'; library.parent.mkdir(); library.write_bytes(b'library')
|
||||
work = library.parent/'ReusableBlocksLP/IP101GR/Work'
|
||||
(work/'database/cdbsvr').mkdir(parents=True)
|
||||
(work/'database/icdb.dat').write_bytes(b'schematic')
|
||||
address = work/'database/cdbsvr/sAddress.adr'; address.write_bytes(b'old server address - preserved')
|
||||
(work/'PCB/Layout').mkdir(parents=True)
|
||||
(work/'PCB/Layout/LayoutDB.lyt').write_bytes(b'layout')
|
||||
project = work/'IP101GR.prj'
|
||||
project.write_text('KEY iCDBDir ".\\database"\nKEY PCBDesignPath "PCB/IP101GR.pcb"\n')
|
||||
(work/'PCB/IP101GR.pcb').write_text('KEY ProjectFile "../IP101GR.prj"\n')
|
||||
(work/'PCB/pcb.prj').write_text('KEY CentralLibrary "old.lmc"\n')
|
||||
monkeypatch.setattr(entry, 'assert_native_idle', lambda: None)
|
||||
request = VerifyRequest(library, 'IP101GR', tmp_path/'evidence', maintenance=True)
|
||||
monkeypatch.setattr('cbb_refresh_verify.verify_runner._run_verify_serialized',
|
||||
lambda req, **kw: startup_failure(req))
|
||||
yield request, project, address
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
key = locks.LibraryLock(library).key
|
||||
with locks._guard:
|
||||
owner = locks._owners.pop(key, None)
|
||||
if owner: owner['handle'].Close()
|
||||
|
||||
|
||||
def startup_failure(request):
|
||||
"""Stub the PCB process boundary with a complete current native failure."""
|
||||
from cbb_refresh_verify.verify_runner import VerifyResult
|
||||
database = request.lmc_file.parent/'ReusableBlocksLP'/request.block_name/'Work/database'
|
||||
return VerifyResult('FAIL', safe_to_continue=True, error_category='ICDB_REPAIR_REQUIRED',
|
||||
stderr=("The last server session on different server machine lost the connection to the database. "
|
||||
"Please use iCDB Project Backup 'Repair project' functionality to fix this issue. "
|
||||
f"Machine:[fixture-server] Path:[{database}] session:[fixture-current-session]"))
|
||||
|
||||
|
||||
def run_legacy_maintenance(request, **kwargs):
|
||||
"""Keep explicit recovery helper coverage separate from the batch-check API."""
|
||||
from cbb_refresh_verify import verify_runner as runner, maintenance_entry as entry
|
||||
if not request.maintenance:
|
||||
return runner.run_verify(request, **kwargs)
|
||||
return entry.run_diagnosed_maintenance(request,
|
||||
diagnose=lambda probe: runner.run_verify(probe, **kwargs),
|
||||
progress=kwargs.get('progress'), stop=kwargs.get('stop'))
|
||||
|
||||
|
||||
def patch_verification_after_fault(monkeypatch, runner, verify):
|
||||
"""Inject only native process boundaries; production interprets the Output."""
|
||||
from cbb_refresh_verify import native_repair
|
||||
from test_native_occupancy import output
|
||||
repair = native_repair.run_native_repair
|
||||
def native(target, root, **kw):
|
||||
if not kw.get('inspection_only'):
|
||||
return repair(target, root, **kw)
|
||||
return {'inspection_only': True, 'repair_requested': False, 'native_pid': 777,
|
||||
'native_exit_code': 0, 'project': str(target.project), 'database': str(target.database),
|
||||
'output': output(target.project, target.database, fault=True),
|
||||
'status': 'NOT_IN_USE', 'repair_required': True, 'release': {'native_exited': True}}
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', native)
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized',
|
||||
lambda req, **kw: startup_failure(req) if req.diagnostic_only else verify(req, **kw))
|
||||
|
||||
|
||||
@pytest.mark.parametrize('pcb_config', ['standard', 'legacy_template'])
|
||||
@pytest.mark.parametrize('advertisement', ['present', 'absent'])
|
||||
def test_diagnosed_maintenance_enters_official_repair_once(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')
|
||||
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:
|
||||
{'safe_to_continue': True, 'native_exited': True, 'addresses': []})
|
||||
def verify(req, **kwargs):
|
||||
calls.append('verify')
|
||||
from cbb_refresh_verify.post_repair_consent import PostRepairProof
|
||||
assert isinstance(req.post_repair_proof, PostRepairProof)
|
||||
assert not req.maintenance and not req.auto_repair
|
||||
assert req.lmc_file == request.lmc_file and req.block_name == request.block_name
|
||||
return runner.VerifyResult('PASS', library_flag='GREEN')
|
||||
patch_verification_after_fault(monkeypatch, runner, verify)
|
||||
result = run_legacy_maintenance(request)
|
||||
assert calls == ['repair'] and result.status == 'REPAIRED'
|
||||
assert result.recovery_attempts[0]['validation_passed'] is False
|
||||
assert result.library_flag == 'UNKNOWN'
|
||||
record = json.loads(result.evidence_path.read_text(encoding='utf-8'))
|
||||
assert record['operation'] == 'explicit_project_maintenance'
|
||||
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
|
||||
|
||||
|
||||
def test_guard_reuses_full_tree_scan_but_still_refreshes_before_yield(case, monkeypatch):
|
||||
from cbb_refresh_verify.maintenance_entry import maintenance_target_guard
|
||||
import cbb_refresh_verify.scoped_manifest as manifests
|
||||
request, project, _ = case
|
||||
scans = []
|
||||
original = manifests.scan_tree
|
||||
def scan(root, **kwargs):
|
||||
scans.append(Path(root))
|
||||
return original(root, **kwargs)
|
||||
monkeypatch.setattr(manifests, 'scan_tree', scan)
|
||||
with maintenance_target_guard(request): pass
|
||||
assert request.lmc_file.parent not in scans
|
||||
assert scans.count(project.parent) == 2
|
||||
|
||||
|
||||
def test_guard_rejects_new_native_database_appearing_during_checks(case, monkeypatch):
|
||||
import cbb_refresh_verify.maintenance_entry as entry
|
||||
request, _, _ = case
|
||||
calls = []
|
||||
def idle():
|
||||
calls.append(1)
|
||||
if len(calls) == 2:
|
||||
(request.lmc_file.parent/'new.lmc').write_bytes(b'new native store')
|
||||
monkeypatch.setattr(entry, 'assert_native_idle', idle)
|
||||
with pytest.raises(ValueError, match='MAINTENANCE_SOURCE_CHANGED'):
|
||||
with entry.maintenance_target_guard(request): 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):
|
||||
from cbb_refresh_verify.maintenance_entry import select_maintenance_target
|
||||
request, project, _ = case
|
||||
(project.parent/'PCB/pcb.prj').rename(project.parent/'PCB/template.prj')
|
||||
(project.parent/'PCB/IP101GR.pcb').write_text(back_reference)
|
||||
with pytest.raises(ValueError, match='MAINTENANCE_TARGET_UNCONFIRMED'):
|
||||
select_maintenance_target(request)
|
||||
|
||||
|
||||
def test_legacy_target_does_not_guess_template_for_physical_address(case):
|
||||
from cbb_refresh_verify.maintenance_entry import select_maintenance_target
|
||||
request, project, address = case
|
||||
(project.parent/'PCB/pcb.prj').rename(project.parent/'PCB/template.prj')
|
||||
address.unlink()
|
||||
physical = project.parent/'PCB/database/cdbsvr/sAddress.adr'
|
||||
physical.parent.mkdir(parents=True); physical.write_bytes(b'physical owner')
|
||||
with pytest.raises(ValueError, match='SHARED_DATABASE_REPAIR_UNSUPPORTED'):
|
||||
select_maintenance_target(request)
|
||||
|
||||
|
||||
def test_optional_pcb_project_appearance_invalidates_maintenance_proof(case):
|
||||
from cbb_refresh_verify.maintenance_entry import maintenance_target_guard
|
||||
request, project, _ = case
|
||||
config = project.parent/'PCB/pcb.prj'
|
||||
config.rename(config.with_name('template.prj'))
|
||||
with maintenance_target_guard(request) as proof:
|
||||
before = proof['context']
|
||||
config.write_text('KEY CentralLibrary "different.lmc"\n')
|
||||
with pytest.raises(ValueError, match='MAINTENANCE_SOURCE_CHANGED'):
|
||||
with maintenance_target_guard(request, before): pass
|
||||
|
||||
|
||||
def test_ordinary_verify_calls_native_verifier_despite_existing_address(case, monkeypatch):
|
||||
from cbb_refresh_verify import verify_runner as runner, native_repair
|
||||
request, _, address = case
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', lambda *a, **k: pytest.fail('ordinary verify must not repair'))
|
||||
calls = []
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **k:
|
||||
(calls.append('verify') or runner.VerifyResult('FAIL', stderr='native ICDB problem')))
|
||||
result = run_legacy_maintenance(replace(request, maintenance=False))
|
||||
assert calls == ['verify'] and result.status == 'FAIL' and result.safe_to_continue
|
||||
assert address.read_bytes() == b'old server address - preserved'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('obstacle', ['active_owner', 'exclusive', 'shared_address', 'ambiguous', 'address_mutation'])
|
||||
def test_maintenance_guard_blocks_before_native(case, monkeypatch, obstacle):
|
||||
from cbb_refresh_verify import maintenance_entry as entry, native_repair, verify_runner as runner
|
||||
import win32file, win32con
|
||||
request, project, address = case
|
||||
handle = None
|
||||
if obstacle == 'active_owner':
|
||||
monkeypatch.setattr(entry, 'assert_native_idle', lambda: (_ for _ in ()).throw(ValueError('native owner')))
|
||||
if obstacle == 'exclusive':
|
||||
handle = win32file.CreateFile(str(project.parent/'database/icdb.dat'), win32con.GENERIC_READ,
|
||||
0, None, win32con.OPEN_EXISTING, 0, None)
|
||||
if obstacle == 'shared_address':
|
||||
shared = request.lmc_file.parent/'SymbolLibs/__ReusableBlocksSymb/cdbsvr/sAddress.adr'
|
||||
shared.parent.mkdir(parents=True); shared.write_bytes(b'shared owner')
|
||||
if obstacle == 'ambiguous': project.write_text(project.read_text() + 'KEY iCDBDir "other"\n')
|
||||
if obstacle == 'address_mutation':
|
||||
original = entry.address_snapshot
|
||||
def mutate(paths):
|
||||
result = original(paths)
|
||||
address.write_bytes(b'changed after snapshot')
|
||||
return result
|
||||
monkeypatch.setattr(entry, 'address_snapshot', mutate)
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', lambda *a, **k: pytest.fail('guard bypass'))
|
||||
try:
|
||||
result = run_legacy_maintenance(request)
|
||||
assert result.status == 'BLOCKED' and not result.safe_to_continue
|
||||
assert result.error_stage == 'preflight'
|
||||
finally:
|
||||
if handle: handle.Close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('change', ['dead', 'same_process', 'live_foreign', 'malformed', 'foreign_library', 'guard_failure'])
|
||||
def test_takeover_preserves_old_checkpoint_until_every_guard_passes(case, monkeypatch, change):
|
||||
from cbb_refresh_verify import library_lock as locks, maintenance_entry as entry
|
||||
request, _, address = case
|
||||
library = request.lmc_file
|
||||
with locks.LibraryLock(library, safe_to_release=lambda: False): pass
|
||||
marker = locks.blocker_path(library)
|
||||
record = json.loads(marker.read_text(encoding='utf-8'))
|
||||
if change != 'same_process':
|
||||
with locks._guard: locks._owners.pop(locks.LibraryLock(library).key)['handle'].Close()
|
||||
record['pid'] = 789123
|
||||
if change == 'foreign_library': record['library'] = str(library.parent.parent/'foreign/mentor.lmc')
|
||||
marker.write_text('broken json' if change == 'malformed' else json.dumps(record), encoding='utf-8')
|
||||
old = marker.read_bytes()
|
||||
monkeypatch.setattr(locks, '_recorded_supervisor_alive', lambda record: change == 'live_foreign')
|
||||
if change == 'guard_failure':
|
||||
monkeypatch.setattr(entry, 'assert_native_idle', lambda: (_ for _ in ()).throw(ValueError('guard failed')))
|
||||
archive = request.evidence_dir/'takeover'
|
||||
guard = lambda: entry.maintenance_target_guard(request)
|
||||
if change in ('dead', 'same_process'):
|
||||
lease = locks.LibraryLock.for_maintenance(library, archive, guard, safe_to_release=lambda: True)
|
||||
with lease:
|
||||
assert (archive/'previous-checkpoint.json').read_bytes() == old
|
||||
assert address.exists()
|
||||
import win32file, win32con
|
||||
with pytest.raises(Exception):
|
||||
win32file.CreateFile(str(lease.path), win32con.GENERIC_READ, 0, None, win32con.OPEN_EXISTING, 0, None)
|
||||
assert lease.path.exists() and not marker.exists()
|
||||
else:
|
||||
with pytest.raises((ValueError, OSError)):
|
||||
with locks.LibraryLock.for_maintenance(library, archive, guard): pass
|
||||
assert marker.read_bytes() == old
|
||||
|
||||
|
||||
@pytest.mark.parametrize('status', ['MISSING_HEALTHY_BACKUP', 'RESTORED_REVIEW_REQUIRED', 'DATABASE_BUSY', 'TIMEOUT_UNRELEASED'])
|
||||
def test_nonrepair_outcomes_never_verify_or_count_success(case, monkeypatch, status):
|
||||
from cbb_refresh_verify import native_repair, verify_runner as runner
|
||||
request, _, _ = case
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', lambda *a, **k: {
|
||||
'status': status, 'release': {'safe_to_continue': False}, 'detail': 'native result'})
|
||||
monkeypatch.setattr(native_repair, 'repair_release_state', lambda *a: {'safe_to_continue': False})
|
||||
patch_verification_after_fault(monkeypatch, runner, lambda *a, **k: pytest.fail('unsafe or nonrepair outcome reopened'))
|
||||
result = run_legacy_maintenance(request)
|
||||
assert result.status != 'PASS' and not result.safe_to_continue
|
||||
assert result.recovery_attempts[0]['status'] == status
|
||||
|
||||
|
||||
def test_native_success_cannot_bypass_remaining_address(case, monkeypatch):
|
||||
from cbb_refresh_verify import native_repair, verify_runner as runner
|
||||
from test_native_repair import complete_native_success
|
||||
request, _, _ = case
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', lambda target, *a, **k: complete_native_success(target))
|
||||
patch_verification_after_fault(monkeypatch, runner, lambda *a, **k: pytest.fail('retained address reopened'))
|
||||
# Native release queries remain mocked, actual address/exclusive checks stay real.
|
||||
monkeypatch.setattr('cbb_refresh_verify.mentor_adapter.pcb_processes', lambda: [])
|
||||
monkeypatch.setattr('cbb_refresh_verify.mentor_adapter._process_details', lambda name: [])
|
||||
result = run_legacy_maintenance(request)
|
||||
assert result.status != 'PASS' and not result.safe_to_continue
|
||||
|
||||
|
||||
@pytest.mark.parametrize('output', ['', 'Checking if project is in use.',
|
||||
"Project is not in use. Full iCDB Project Backup's functionality is available.",
|
||||
"Project is not in use. Full iCDB Project Backup's functionality is available.\nProject is in use."])
|
||||
def test_explicit_worker_requires_positive_native_idle_before_repair(tmp_path, monkeypatch, output):
|
||||
import win32con
|
||||
from test_native_repair import repair_worker_fixture
|
||||
import cbb_refresh_verify.maintenance_entry as entry
|
||||
from cbb_refresh_verify.native_repair import RepairTarget
|
||||
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'active')
|
||||
values = json.loads(job.read_text())
|
||||
values['maintenance_context'] = {'library': str(tmp_path/'lib.lmc'), 'block': 'CBB1'}
|
||||
job.write_text(json.dumps(values))
|
||||
@contextmanager
|
||||
def guard(*args, stop=None):
|
||||
assert stop is not None
|
||||
yield {'target': RepairTarget(Path(values['project']), Path(values['database']))}
|
||||
monkeypatch.setattr(entry, 'maintenance_target_guard', guard)
|
||||
monkeypatch.setattr(ui, '_native_output', lambda windows: output)
|
||||
ui.repair_worker_main(job)
|
||||
expected = output == "Project is not in use. Full iCDB Project Backup's functionality is available."
|
||||
assert any(message == win32con.WM_COMMAND for _, message in actions) is expected
|
||||
|
||||
|
||||
def test_worker_rechecks_address_after_access_probe_before_native_launch(tmp_path, monkeypatch):
|
||||
from test_native_repair import repair_worker_fixture
|
||||
import cbb_refresh_verify.maintenance_entry as entry
|
||||
from cbb_refresh_verify.native_repair import RepairTarget
|
||||
ui, root, job, _ = repair_worker_fixture(tmp_path, monkeypatch, 'active')
|
||||
values = json.loads(job.read_text()); values['maintenance_context'] = {'library': str(tmp_path/'lib.lmc'), 'block': 'CBB1'}
|
||||
job.write_text(json.dumps(values))
|
||||
calls = []
|
||||
monkeypatch.setattr('cbb_refresh_verify.native_repair.check_repair_access',
|
||||
lambda *_: calls.append('access'))
|
||||
@contextmanager
|
||||
def guard(*args, stop=None):
|
||||
assert stop is not None
|
||||
calls.append('guard')
|
||||
assert calls == ['access', 'guard']
|
||||
raise ValueError('address changed after access probe')
|
||||
yield {'target': RepairTarget(Path(values['project']), Path(values['database']))}
|
||||
monkeypatch.setattr(entry, 'maintenance_target_guard', guard)
|
||||
monkeypatch.setattr(ui.subprocess, 'Popen', lambda *a, **k: pytest.fail('mutation must stop native launch'))
|
||||
ui.repair_worker_main(job)
|
||||
assert calls == ['access', 'guard']
|
||||
assert 'address changed' in json.loads((root/'repair-result.json').read_text())['detail']
|
||||
|
||||
|
||||
def test_guard_failure_keeps_takeover_checkpoint_byte_exact_when_address_changes(case, monkeypatch):
|
||||
from cbb_refresh_verify import library_lock as locks, maintenance_entry as entry
|
||||
request, _, address = case
|
||||
with locks.LibraryLock(request.lmc_file, safe_to_release=lambda: False): pass
|
||||
marker = locks.blocker_path(request.lmc_file); old = marker.read_bytes()
|
||||
snapshot = entry.address_snapshot
|
||||
def mutate(paths):
|
||||
result = snapshot(paths); address.write_bytes(b'changed'); return result
|
||||
monkeypatch.setattr(entry, 'address_snapshot', mutate)
|
||||
with pytest.raises(ValueError):
|
||||
with locks.LibraryLock.for_maintenance(request.lmc_file, request.evidence_dir/'takeover',
|
||||
lambda: entry.maintenance_target_guard(request)): pass
|
||||
assert marker.read_bytes() == old
|
||||
|
||||
|
||||
def test_independent_cbb_address_does_not_select_or_block_current_project(case):
|
||||
from cbb_refresh_verify.maintenance_entry import maintenance_target_guard
|
||||
request, project, address = case
|
||||
other = request.lmc_file.parent/'ReusableBlocksLP/1GPHY_8212/Work/database/cdbsvr/sAddress.adr'
|
||||
other.parent.mkdir(parents=True); other.write_bytes(b'independent CBB original address')
|
||||
with maintenance_target_guard(request) as checked:
|
||||
assert checked['target'].project == project
|
||||
assert set(checked['context']['addresses']) == {str(address.resolve())}
|
||||
assert other.read_bytes() == b'independent CBB original address'
|
||||
assert other.read_bytes() == b'independent CBB original address'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('status,complete,expected_safe', [
|
||||
('RESTORED_REVIEW_REQUIRED', True, True), ('DATABASE_BUSY', True, True),
|
||||
('UNKNOWN_DIALOG', True, True), ('UNCONFIRMED', True, True),
|
||||
('MISSING_HEALTHY_BACKUP', False, True), ('NATIVE_REPAIR_FAILED', False, True),
|
||||
('MISSING_HEALTHY_BACKUP', True, True), ('NATIVE_REPAIR_FAILED', True, True)])
|
||||
def test_failed_content_does_not_block_other_items_after_actual_release(case, monkeypatch, status, complete, expected_safe):
|
||||
from cbb_refresh_verify import native_repair, verify_runner as runner, library_lock
|
||||
from test_native_repair import complete_native_success
|
||||
request, _, address = case
|
||||
def repair(target, *args, **kwargs):
|
||||
address.unlink() # Simulate official process releasing its test-only advertisement.
|
||||
result = complete_native_success(target)
|
||||
result.update(status=status, detail='native completed')
|
||||
result['evidence']['failure_complete'] = complete
|
||||
return result
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', repair)
|
||||
monkeypatch.setattr(native_repair, 'repair_release_state', lambda req, target, result: result['release'])
|
||||
patch_verification_after_fault(monkeypatch, runner, lambda *a, **k: pytest.fail('nonrepair outcome reopened'))
|
||||
result = run_legacy_maintenance(request)
|
||||
assert result.status != 'PASS'
|
||||
assert result.safe_to_continue is expected_safe
|
||||
assert result.recovery_attempts[0]['status'] == status
|
||||
assert library_lock.has_blocker(request.lmc_file) is not expected_safe
|
||||
|
||||
|
||||
def test_successful_icdb_repair_then_version_choice_reports_partial_completion(case, monkeypatch):
|
||||
from cbb_refresh_verify import native_repair, verify_runner as runner
|
||||
from test_native_repair import complete_native_success
|
||||
request, _, address = case
|
||||
def repair(target, *a, **k):
|
||||
address.unlink()
|
||||
return complete_native_success(target)
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', repair)
|
||||
monkeypatch.setattr(native_repair, 'repair_release_state', lambda req, target, result: result['release'])
|
||||
patch_verification_after_fault(monkeypatch, runner, lambda *a, **k: runner.VerifyResult('FAIL',
|
||||
error_category='PCB_VERSION_CHOICE_REQUIRED', stderr='PCB版本待选:最后用户保存/自动保存 2026/9/24 23:06',
|
||||
safe_to_continue=False, evidence_path=request.evidence_dir/'verify/result.json'))
|
||||
result = run_legacy_maintenance(request)
|
||||
assert result.status == 'REPAIRED' and result.safe_to_continue
|
||||
assert '待单独校验' in result.stdout
|
||||
assert result.recovery_attempts[0]['native_status'] == 'REPAIRED'
|
||||
assert result.recovery_attempts[0]['status'] == 'REPAIRED_UNVERIFIED'
|
||||
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')
|
||||
patch_verification_after_fault(monkeypatch, runner, verify)
|
||||
result = run_legacy_maintenance(request)
|
||||
assert result.status == 'REPAIRED' and result.library_flag == 'UNKNOWN'
|
||||
assert result.recovery_attempts[0]['status'] == 'REPAIRED_UNVERIFIED'
|
||||
assert not (request.evidence_dir/'verify').exists()
|
||||
@@ -0,0 +1,93 @@
|
||||
"""Ownership scoping only: no native process or execution mutex is started."""
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def scope(tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify.native_repair import RepairTarget
|
||||
from cbb_refresh_verify import native_management, native_engineering_identity
|
||||
library = tmp_path/'a/lib.lmc'
|
||||
library.parent.mkdir()
|
||||
library.touch()
|
||||
other = tmp_path/'b/lib.lmc'
|
||||
other.parent.mkdir()
|
||||
other.touch()
|
||||
project = tmp_path/'work/main.prj'
|
||||
project.parent.mkdir()
|
||||
project.write_text(f'KEY CentralLibrary "{library}"\n')
|
||||
target = RepairTarget(project, project.parent/'database')
|
||||
monkeypatch.setattr(native_management, '_retained_workers', [])
|
||||
monkeypatch.setattr(native_engineering_identity, '_retained_exports', [])
|
||||
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_a, **_k: [])
|
||||
return target, library, other
|
||||
|
||||
|
||||
@pytest.mark.parametrize('kind', ['management', 'export'])
|
||||
@pytest.mark.parametrize('ownership', ['same', 'other', 'unknown'])
|
||||
def test_retained_native_ownership_is_scoped_only_with_proven_library(scope, monkeypatch, kind, ownership):
|
||||
from cbb_refresh_verify import maintenance_entry as entry
|
||||
target, library, other = scope
|
||||
claimed = library if ownership == 'same' else other if ownership == 'other' else None
|
||||
worker = SimpleNamespace(poll=lambda: None, cbb_library=claimed)
|
||||
if kind == 'management':
|
||||
monkeypatch.setattr('cbb_refresh_verify.native_management._retained_workers', [worker])
|
||||
else:
|
||||
monkeypatch.setattr('cbb_refresh_verify.native_engineering_identity._retained_exports',
|
||||
[(worker, {}, {'library': str(claimed)} if claimed else {})])
|
||||
if ownership == 'other':
|
||||
entry.assert_native_idle(target)
|
||||
else:
|
||||
with pytest.raises(Exception, match='(OWNER_ACTIVE|exporter)'):
|
||||
entry.assert_native_idle(target)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('reference', ['missing', 'conflicting', 'invalid', 'empty_extra'])
|
||||
def test_unproven_library_does_not_exclude_retained_workers(scope, monkeypatch, reference):
|
||||
from cbb_refresh_verify import maintenance_entry as entry
|
||||
target, library, other = scope
|
||||
target.project.write_text('' if reference == 'missing' else
|
||||
f'KEY CentralLibrary "{library}"\nKEY CentralLibrary "{other}"' if reference == 'conflicting' else
|
||||
f'KEY CentralLibrary "{library}"\nKEY CentralLibrary ""' if reference == 'empty_extra' else
|
||||
'KEY CentralLibrary "missing.lmc"')
|
||||
monkeypatch.setattr('cbb_refresh_verify.native_management._retained_workers',
|
||||
[SimpleNamespace(poll=lambda: None, cbb_library=other)])
|
||||
with pytest.raises(ValueError, match='OWNER_ACTIVE'):
|
||||
entry.assert_native_idle(target)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('source', ['project', 'pcb', 'database', 'lmc', 'shared', 'job', 'unknown', 'other'])
|
||||
def test_native_commands_include_target_and_shared_library_ownership(scope, monkeypatch, tmp_path, source):
|
||||
from cbb_refresh_verify import maintenance_entry as entry
|
||||
target, library, other = scope
|
||||
job = tmp_path/'request.json'
|
||||
job.write_text(json.dumps({'library': str(library)}))
|
||||
command = {
|
||||
'project': f'ExpeditionPCB.exe "{target.project}"',
|
||||
'pcb': f'ExpeditionPCB.exe "{target.project.parent / "PCB/board.pcb"}"',
|
||||
'database': f'iCDBProjectBackup.exe -icdb="{target.database}"',
|
||||
'lmc': f'LibraryManager.exe "{library}"',
|
||||
'shared': f'viewdraw.exe -project="{library.parent / "SymbolLibs/database"}"',
|
||||
'job': f'python.exe --management-worker "{job}"',
|
||||
'unknown': 'ExpeditionPCB.exe',
|
||||
'other': f'LibraryManager.exe "{other}"',
|
||||
}[source]
|
||||
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_a, **_k:
|
||||
[{'pid': 987654, 'name': 'python.exe' if source == 'job' else 'ExpeditionPCB.exe',
|
||||
'command': command}])
|
||||
if source == 'other':
|
||||
entry.assert_native_idle(target)
|
||||
else:
|
||||
with pytest.raises(ValueError, match='OWNER_ACTIVE'):
|
||||
entry.assert_native_idle(target)
|
||||
|
||||
|
||||
def test_no_target_keeps_global_retained_owner_guard(scope, monkeypatch):
|
||||
from cbb_refresh_verify import maintenance_entry as entry
|
||||
_, _, other = scope
|
||||
monkeypatch.setattr('cbb_refresh_verify.native_management._retained_workers',
|
||||
[SimpleNamespace(poll=lambda: None, cbb_library=other)])
|
||||
with pytest.raises(ValueError, match='OWNER_ACTIVE'):
|
||||
entry.assert_native_idle()
|
||||
@@ -0,0 +1,185 @@
|
||||
"""Project Backup is reached only after a current, released PCB startup fault."""
|
||||
from dataclasses import replace
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from test_maintenance_entry import case, no_native_launch, run_legacy_maintenance
|
||||
|
||||
|
||||
def fault_text(database):
|
||||
return ("The last server session on different server machine lost the connection to the database. "
|
||||
"Please use iCDB Project Backup 'Repair project' functionality to fix this issue. "
|
||||
f"Machine:[fixture-server] Path:[{database}] session:[fixture-current-session]")
|
||||
|
||||
|
||||
def install_probe(monkeypatch, result, calls):
|
||||
from cbb_refresh_verify import verify_runner as runner
|
||||
def probe(request, **kwargs):
|
||||
assert request.diagnostic_only and not request.maintenance and not request.auto_repair
|
||||
assert not request.native_lm_verify and request.post_repair_proof is None
|
||||
calls.append('open')
|
||||
return result
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', probe)
|
||||
|
||||
|
||||
def forbid_backup(monkeypatch):
|
||||
from cbb_refresh_verify import native_repair
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair',
|
||||
lambda *a, **k: pytest.fail('Project Backup launched without a current matching startup fault'))
|
||||
|
||||
|
||||
def test_healthy_startup_skips_project_backup_even_with_old_address(case, monkeypatch):
|
||||
from cbb_refresh_verify import verify_runner as runner
|
||||
request, _, address = case
|
||||
calls = []
|
||||
install_probe(monkeypatch, runner.VerifyResult('PASS', safe_to_continue=True), calls)
|
||||
forbid_backup(monkeypatch)
|
||||
result = run_legacy_maintenance(replace(request, native_lm_verify=True))
|
||||
assert calls == ['open']
|
||||
assert result.status == 'CHECKED' and result.library_flag == 'UNKNOWN'
|
||||
assert result.recovery_attempts == () and result.safe_to_continue
|
||||
assert address.read_bytes() == b'old server address - preserved'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('message', ['License unavailable', 'Could not run server',
|
||||
'COM 已连接,尚无目标文档', 'ICDB_REPAIR_REQUIRED',
|
||||
'PCB 文件损坏', 'Lost connection to server'])
|
||||
def test_generic_startup_errors_remain_failures_without_backup(case, monkeypatch, message):
|
||||
from cbb_refresh_verify import verify_runner as runner
|
||||
request, _, _ = case
|
||||
calls = []
|
||||
failed = runner.VerifyResult('FAIL', stderr=message, safe_to_continue=True)
|
||||
install_probe(monkeypatch, failed, calls)
|
||||
forbid_backup(monkeypatch)
|
||||
result = run_legacy_maintenance(request)
|
||||
assert calls == ['open'] and result == failed
|
||||
|
||||
|
||||
@pytest.mark.parametrize('reason', ['shared', 'other_project', 'no_session', 'unreleased', 'timeout', 'cancelled'])
|
||||
def test_unmatched_or_unreleased_icdb_fault_never_enters_backup(case, monkeypatch, reason):
|
||||
from cbb_refresh_verify import verify_runner as runner
|
||||
request, project, _ = case
|
||||
database = (project.parent/'database' if reason not in ('shared', 'other_project') else
|
||||
request.lmc_file.parent/('SymbolLibs/__ReusableBlocksSymb' if reason == 'shared'
|
||||
else 'ReusableBlocksLP/Other/Work/database'))
|
||||
if not database.exists(): database.mkdir(parents=True); (database/'icdb.dat').touch()
|
||||
text = fault_text(database)
|
||||
if reason == 'no_session': text = text.replace('session:[fixture-current-session]', '')
|
||||
failed = runner.VerifyResult('TIMEOUT' if reason == 'timeout' else
|
||||
'CANCELLED' if reason == 'cancelled' else 'FAIL', stderr=text,
|
||||
error_category='ICDB_REPAIR_REQUIRED', safe_to_continue=reason != 'unreleased')
|
||||
calls = []
|
||||
install_probe(monkeypatch, failed, calls)
|
||||
forbid_backup(monkeypatch)
|
||||
result = run_legacy_maintenance(request)
|
||||
assert calls == ['open'] and result.status == failed.status
|
||||
assert not result.recovery_attempts
|
||||
assert result.safe_to_continue is failed.safe_to_continue
|
||||
|
||||
|
||||
def test_only_current_matching_fault_enters_native_maintenance(case, monkeypatch):
|
||||
from cbb_refresh_verify import verify_runner as runner, maintenance_entry as entry
|
||||
request, project, _ = case
|
||||
calls = []
|
||||
failed = runner.VerifyResult('FAIL', stderr=fault_text(project.parent/'database'),
|
||||
error_category='ICDB_REPAIR_REQUIRED', safe_to_continue=True)
|
||||
install_probe(monkeypatch, failed, calls)
|
||||
def maintain(req, *, diagnosed_target, startup_result, **kwargs):
|
||||
assert diagnosed_target.project == project and diagnosed_target.database == project.parent/'database'
|
||||
assert startup_result == failed
|
||||
calls.append('maintenance')
|
||||
return runner.VerifyResult('REPAIRED')
|
||||
monkeypatch.setattr(entry, 'run_existing_address_maintenance', maintain)
|
||||
result = run_legacy_maintenance(request)
|
||||
assert calls == ['open', 'maintenance'] and result.status == 'REPAIRED'
|
||||
|
||||
|
||||
def test_old_saved_diagnosis_does_not_turn_generic_startup_failure_into_repair(case, monkeypatch):
|
||||
from cbb_refresh_verify import verify_runner as runner
|
||||
request, project, _ = case
|
||||
root = request.evidence_dir/'old'; (root/'diagnostics').mkdir(parents=True)
|
||||
(root/'diagnostics/icdb-recovery.json').write_text(json.dumps({
|
||||
'error_code': 'ICDB_REPAIR_REQUIRED', 'native_message': fault_text(project.parent/'database')}))
|
||||
calls = []
|
||||
failure = runner.VerifyResult('FAIL', stderr='License unavailable', evidence_path=root/'result.json')
|
||||
install_probe(monkeypatch, failure, calls)
|
||||
forbid_backup(monkeypatch)
|
||||
assert run_legacy_maintenance(request) == failure
|
||||
assert calls == ['open']
|
||||
|
||||
|
||||
def test_native_admission_cannot_switch_the_diagnosed_database(case, monkeypatch):
|
||||
from cbb_refresh_verify import maintenance_entry as entry, native_repair
|
||||
from test_maintenance_entry import startup_failure
|
||||
request, project, _ = case
|
||||
forbid_backup(monkeypatch)
|
||||
result = entry.run_existing_address_maintenance(request,
|
||||
diagnosed_target=native_repair.RepairTarget(project, project.parent/'other'),
|
||||
startup_result=startup_failure(request))
|
||||
assert result.status == 'FAIL' and result.safe_to_continue
|
||||
assert result.error_category == 'ICDB_TARGET_MISMATCH'
|
||||
|
||||
|
||||
def test_equivalent_diagnosed_path_keeps_the_native_launch_path(case, monkeypatch):
|
||||
from cbb_refresh_verify import maintenance_entry as entry, native_repair
|
||||
from test_maintenance_entry import startup_failure
|
||||
from test_maintenance_diagnosis import inspection
|
||||
request, project, _ = case
|
||||
seen = []
|
||||
def inspect(target, *args, **kwargs):
|
||||
assert kwargs['inspection_only'] is True
|
||||
seen.append(target.project)
|
||||
return inspection(target)
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', inspect)
|
||||
alias = project.parent/'unused/..'
|
||||
result = entry.run_existing_address_maintenance(request,
|
||||
diagnosed_target=native_repair.RepairTarget(alias/project.name, alias/'database'),
|
||||
startup_result=startup_failure(request))
|
||||
assert result.status == 'CHECKED' and result.safe_to_continue, result
|
||||
assert seen == [project]
|
||||
|
||||
|
||||
def test_unsafe_startup_success_is_not_reported_as_healthy(case, monkeypatch):
|
||||
from cbb_refresh_verify import verify_runner as runner
|
||||
request, _, _ = case
|
||||
install_probe(monkeypatch, runner.VerifyResult('PASS', safe_to_continue=False), [])
|
||||
forbid_backup(monkeypatch)
|
||||
result = run_legacy_maintenance(request)
|
||||
assert result.status == 'FAIL' and not result.safe_to_continue
|
||||
|
||||
|
||||
def test_report_write_failure_does_not_block_a_released_healthy_project(case, monkeypatch):
|
||||
from pathlib import Path
|
||||
from cbb_refresh_verify import verify_runner as runner
|
||||
request, _, _ = case
|
||||
evidence = request.evidence_dir/'result.json'; evidence.parent.mkdir(); evidence.write_text('{}')
|
||||
install_probe(monkeypatch, runner.VerifyResult('PASS', evidence_path=evidence), [])
|
||||
forbid_backup(monkeypatch)
|
||||
write = Path.write_text
|
||||
def unavailable(path, *args, **kwargs):
|
||||
if path.name == 'maintenance-result.json': raise PermissionError('report unavailable')
|
||||
return write(path, *args, **kwargs)
|
||||
monkeypatch.setattr(Path, 'write_text', unavailable)
|
||||
result = run_legacy_maintenance(request)
|
||||
assert result.status == 'CHECKED' and result.safe_to_continue
|
||||
assert result.evidence_path == evidence and evidence.read_text() == '{}'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('before_open', [True, False])
|
||||
def test_cancelled_startup_diagnosis_never_requests_repair(case, monkeypatch, before_open):
|
||||
from threading import Event
|
||||
from cbb_refresh_verify import verify_runner as runner
|
||||
from test_maintenance_entry import startup_failure
|
||||
request, _, _ = case
|
||||
stop = Event()
|
||||
if before_open: stop.set()
|
||||
calls = []
|
||||
def probe(req, **kw):
|
||||
calls.append('open'); stop.set()
|
||||
return startup_failure(req)
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', probe)
|
||||
forbid_backup(monkeypatch)
|
||||
result = run_legacy_maintenance(request, stop=stop)
|
||||
assert result.status == 'CANCELLED' and result.safe_to_continue
|
||||
assert calls == ([] if before_open else ['open'])
|
||||
@@ -0,0 +1,362 @@
|
||||
"""Operation safety tests use a file-only native boundary; never launch Mentor."""
|
||||
from dataclasses import replace
|
||||
import json
|
||||
from pathlib import Path
|
||||
from threading import Event
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def project(root, name='Source', marker=b'original'):
|
||||
root.mkdir(parents=True)
|
||||
(root/'database').mkdir()
|
||||
(root/'database/icdb.dat').write_bytes(marker)
|
||||
(root/'PCB/Layout').mkdir(parents=True)
|
||||
(root/'PCB/Layout/LayoutDB.lyt').write_bytes(marker)
|
||||
(root/'PCB/pcb.prj').write_text('KEY iCDBDir "../database"\n', encoding='utf-8')
|
||||
(root/'PCB/main.pcb').write_text(f'KEY ProjectFile "../{name}.prj"\n', encoding='utf-8')
|
||||
path = root/f'{name}.prj'
|
||||
path.write_text('KEY RootBlock "Top"\nKEY PCBDesignPath "PCB/main.pcb"\n'
|
||||
'KEY iCDBDir "database"\n', encoding='utf-8')
|
||||
return path
|
||||
|
||||
|
||||
class FileAdapter:
|
||||
def __init__(self):
|
||||
self.records = []
|
||||
self.calls = []
|
||||
self.fail_add = False
|
||||
self.lie = False
|
||||
self.released = True
|
||||
|
||||
def capabilities(self):
|
||||
from cbb_refresh_verify.management import Capability
|
||||
return {op: Capability(True, 'test boundary') for op in ('add', 'update', 'remove')}
|
||||
|
||||
def catalog(self, library, evidence):
|
||||
from cbb_refresh_verify.management import Catalog
|
||||
return Catalog(library, 1, tuple(self.records), safe_to_continue=self.released)
|
||||
|
||||
def remove(self, request, evidence):
|
||||
from cbb_refresh_verify.management import NativeOutcome
|
||||
self.calls.append('remove')
|
||||
if not self.lie:
|
||||
self.records = [r for r in self.records if r.name != request.name]
|
||||
return NativeOutcome(True, self.released, 'native removal accepted')
|
||||
|
||||
def add(self, request, evidence):
|
||||
from cbb_refresh_verify.management import NativeOutcome, CatalogEntry, engineering_identity
|
||||
self.calls.append(('add', request.source))
|
||||
if self.fail_add:
|
||||
return NativeOutcome(False, self.released, 'native add failed')
|
||||
if not self.lie:
|
||||
self.records.append(CatalogEntry(request.name, request.partition,
|
||||
engineering_identity(request.source)))
|
||||
return NativeOutcome(True, self.released, 'native add accepted')
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def setup(tmp_path):
|
||||
from cbb_refresh_verify.management import ManagementRequest, CatalogEntry
|
||||
library = tmp_path/'library/mentor.lmc'
|
||||
library.parent.mkdir()
|
||||
library.write_bytes(b'library')
|
||||
old = project(library.parent/'ReusableBlocksLP/Block/Work', 'Block')
|
||||
source = project(tmp_path/'source')
|
||||
adapter = FileAdapter()
|
||||
adapter.records = [CatalogEntry('Block', 'Logical-Physical')]
|
||||
request = ManagementRequest('remove', library, 'Block', evidence_dir=tmp_path/'evidence')
|
||||
yield request, adapter, source
|
||||
# FileAdapter never launches native owners. Release only this test's
|
||||
# intentionally retained lease so pytest can remove its temporary tree.
|
||||
from cbb_refresh_verify.library_lock import _guard, _owners
|
||||
key = str(library.with_name('.mentor.cbb-upload.lock').resolve()).casefold()
|
||||
with _guard:
|
||||
owner = _owners.pop(key, None)
|
||||
if owner:
|
||||
owner['handle'].Close()
|
||||
|
||||
|
||||
def execute(request, adapter, **kwargs):
|
||||
from cbb_refresh_verify.management import run_management
|
||||
return run_management(request, adapter=adapter, idle_check=lambda *_: None, **kwargs)
|
||||
|
||||
|
||||
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 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)
|
||||
assert result.status == 'UPLOAD_FAILED' and adapter.calls == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize('verify_status,flag,expected', [('PASS', 'GREEN', 'UPLOADED_VERIFIED'),
|
||||
('FAIL', 'RED', 'UPLOADED_VERIFY_FAILED'), ('PASS', 'UNKNOWN', 'UPLOADED_VERIFY_FAILED')])
|
||||
def test_add_stages_source_and_requires_authoritative_verify(setup, verify_status, flag, expected):
|
||||
from cbb_refresh_verify.verify_runner import VerifyResult
|
||||
request, adapter, source = setup
|
||||
original = source.read_bytes()
|
||||
def verifier(req, **_):
|
||||
assert adapter.released
|
||||
return VerifyResult(verify_status, library_flag=flag)
|
||||
result = execute(replace(request, operation='add', name='New', source=source), adapter,
|
||||
verifier=verifier)
|
||||
assert result.status == expected and source.read_bytes() == original
|
||||
assert adapter.calls[0][1] != source
|
||||
assert adapter.calls[0][1].is_relative_to(result.evidence_path.parent)
|
||||
|
||||
|
||||
def test_add_no_auto_verify_and_reimport_after_remove(setup):
|
||||
request, adapter, source = setup
|
||||
assert execute(request, adapter).status == 'REMOVED'
|
||||
result = execute(replace(request, operation='add', source=source, auto_verify=False), adapter,
|
||||
verifier=lambda *_: pytest.fail('auto verify disabled'))
|
||||
assert result.status == 'UPLOADED'
|
||||
|
||||
|
||||
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)
|
||||
assert result.status == 'RECOVERY_REQUIRED' and result.safe_to_continue
|
||||
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-baseline-manifest.json').is_file()
|
||||
assert not (result.evidence_path.parent/'library-before').exists()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('operation', ['remove', 'add'])
|
||||
def test_lying_native_output_does_not_report_success(setup, operation):
|
||||
request, adapter, source = setup
|
||||
adapter.lie = True
|
||||
request = replace(request, operation=operation, source=source,
|
||||
name='New' if operation == 'add' else 'Block')
|
||||
result = execute(request, adapter)
|
||||
assert result.status == 'RECOVERY_REQUIRED' and result.safe_to_continue
|
||||
|
||||
|
||||
def test_unreleased_native_owner_prevents_postread_and_verification(setup):
|
||||
request, adapter, _ = setup
|
||||
original = adapter.remove
|
||||
def unreleased(*args):
|
||||
adapter.released = False
|
||||
return original(*args)
|
||||
adapter.remove = unreleased
|
||||
reads = []
|
||||
catalog = adapter.catalog
|
||||
adapter.catalog = lambda *a: (reads.append(1) or catalog(*a))
|
||||
result = execute(request, adapter, verifier=lambda *_: pytest.fail('unsafe verify'))
|
||||
assert not result.safe_to_continue and len(reads) == 1
|
||||
from cbb_refresh_verify.library_lock import LibraryLock, LibraryBusy
|
||||
with pytest.raises(LibraryBusy):
|
||||
with LibraryLock(request.library):
|
||||
pass
|
||||
|
||||
|
||||
@pytest.mark.parametrize('name', ['../escape', 'A\tB', 'A\nB', 'A/B', 'NUL', 'a.', ''])
|
||||
def test_invalid_native_identity_rejected_before_writes(setup, name):
|
||||
request, adapter, _ = setup
|
||||
result = execute(replace(request, name=name), adapter)
|
||||
assert result.status == 'BLOCKED' and adapter.calls == []
|
||||
|
||||
|
||||
def test_evidence_inside_target_rejected(setup):
|
||||
request, adapter, _ = setup
|
||||
result = execute(replace(request, evidence_dir=request.library.parent/'evidence'), adapter)
|
||||
assert result.status == 'BLOCKED' and not (request.library.parent/'evidence').exists()
|
||||
|
||||
|
||||
def test_cancel_and_restart_never_replay(setup):
|
||||
from cbb_refresh_verify.management import run_management_batch, unfinished_operations
|
||||
request, adapter, _ = setup
|
||||
stop = Event(); stop.set()
|
||||
assert run_management_batch([request], stop=stop, adapter=adapter) == []
|
||||
checkpoint = request.evidence_dir/'interrupted/checkpoint.json'
|
||||
checkpoint.parent.mkdir(parents=True)
|
||||
checkpoint.write_text('{"stage":"native_remove", "status":"RUNNING"}', encoding='utf-8')
|
||||
found = unfinished_operations(request.evidence_dir)
|
||||
assert len(found) == 1 and found[0]['evidence_path'] == str(checkpoint)
|
||||
assert adapter.calls == []
|
||||
|
||||
|
||||
def test_capability_gate_enforced_below_ui(setup):
|
||||
from cbb_refresh_verify.management import Capability
|
||||
request, adapter, source = setup
|
||||
adapter.capabilities = lambda: {'add': Capability(False, 'isolated add not validated')}
|
||||
result = execute(replace(request, operation='add', name='New', source=source), adapter)
|
||||
assert result.status == 'UNSUPPORTED' and 'isolated' in result.detail
|
||||
assert adapter.calls == []
|
||||
|
||||
|
||||
def test_timeout_stops_batch_and_persists_ambiguous_native_stage(setup):
|
||||
from cbb_refresh_verify.management import run_management_batch
|
||||
request, adapter, _ = setup
|
||||
def timeout(*_):
|
||||
raise TimeoutError('network timeout')
|
||||
adapter.remove = timeout
|
||||
results = run_management_batch([request, replace(request, name='Other')], adapter=adapter,
|
||||
idle_check=lambda *_: None)
|
||||
assert len(results) == 1 and not results[0].safe_to_continue
|
||||
assert results[0].status == 'RECOVERY_REQUIRED'
|
||||
|
||||
|
||||
def test_catalog_timeout_is_not_safe_to_continue(setup):
|
||||
request, adapter, _ = setup
|
||||
def timeout(*_):
|
||||
raise TimeoutError('catalog owner still running')
|
||||
adapter.catalog = timeout
|
||||
result = execute(request, adapter)
|
||||
assert not result.safe_to_continue and adapter.calls == []
|
||||
|
||||
|
||||
def test_replaced_source_bytes_fail_identity_even_with_same_name(setup):
|
||||
request, adapter, source = setup
|
||||
real_add = adapter.add
|
||||
def wrong_source(*args):
|
||||
from cbb_refresh_verify.management import CatalogEntry
|
||||
result = real_add(*args)
|
||||
entry = adapter.records[-1]
|
||||
adapter.records[-1] = CatalogEntry(entry.name, entry.partition, {'wrong': 'project'})
|
||||
return result
|
||||
adapter.add = wrong_source
|
||||
result = execute(replace(request, operation='add', name='New', source=source), adapter)
|
||||
assert result.status == 'RECOVERY_REQUIRED' and result.safe_to_continue
|
||||
|
||||
|
||||
def test_update_success_requires_same_identity_and_no_implicit_partition_move(setup):
|
||||
request, adapter, source = setup
|
||||
result = execute(replace(request, operation='update', source=source, partition='Other'), adapter)
|
||||
assert result.status == 'BLOCKED' and not adapter.calls
|
||||
result = execute(replace(request, operation='update', source=source, auto_verify=False), adapter)
|
||||
assert result.status == 'UPLOADED'
|
||||
assert adapter.calls[0] == 'remove' and adapter.calls[1][0] == 'add'
|
||||
|
||||
|
||||
def test_verify_exception_after_upload_retains_coordination_lock(setup):
|
||||
from cbb_refresh_verify.library_lock import LibraryLock, LibraryBusy
|
||||
request, adapter, source = setup
|
||||
def broken_verifier(*a, **k):
|
||||
raise OSError('verification worker disconnected')
|
||||
result = execute(replace(request, operation='add', name='New', source=source), adapter,
|
||||
verifier=broken_verifier)
|
||||
assert result.status == 'UPLOADED_VERIFY_FAILED' and not result.safe_to_continue
|
||||
with pytest.raises(LibraryBusy):
|
||||
with LibraryLock(request.library):
|
||||
pass
|
||||
|
||||
|
||||
@pytest.mark.parametrize('nested', [True, False])
|
||||
def test_library_inside_source_tree_rejected_before_catalog_or_guard(setup, nested):
|
||||
request, adapter, source = setup
|
||||
library = source.parent/('nested/lib.lmc' if nested else 'lib.lmc')
|
||||
library.parent.mkdir(exist_ok=True)
|
||||
library.write_bytes(b'library')
|
||||
adapter.catalog = lambda *a: pytest.fail('overlapping library reached native catalog')
|
||||
result = execute(replace(request, operation='add', name='New', source=source, library=library), adapter)
|
||||
assert result.status == 'BLOCKED' and not adapter.calls
|
||||
assert not library.with_name('.lib.cbb-upload.lock').exists()
|
||||
assert not request.evidence_dir.exists()
|
||||
|
||||
|
||||
def test_mapped_library_spelling_and_context_survive_engine_verify_boundary(setup, monkeypatch):
|
||||
import shutil
|
||||
from cbb_refresh_verify.verify_runner import VerifyResult
|
||||
request, adapter, source = setup
|
||||
alias_root = request.library.parent
|
||||
canonical_root = alias_root.with_name('canonical-library')
|
||||
shutil.copytree(alias_root, canonical_root)
|
||||
original_resolve = Path.resolve
|
||||
def resolve(path, *a, **k):
|
||||
if path.is_relative_to(alias_root):
|
||||
return original_resolve(canonical_root/path.relative_to(alias_root), *a, **k)
|
||||
return original_resolve(path, *a, **k)
|
||||
monkeypatch.setattr(Path, 'resolve', resolve)
|
||||
catalogs, verified = [], []
|
||||
catalog = adapter.catalog
|
||||
adapter.catalog = lambda library, evidence: (catalogs.append(library) or catalog(library, evidence))
|
||||
def verifier(req, **k):
|
||||
verified.append(req)
|
||||
return VerifyResult('PASS', library_flag='GREEN')
|
||||
request = replace(request, operation='add', name='New', source=source,
|
||||
mapped_drive='S:', mapped_remote_root=r'\\server\share')
|
||||
result = execute(request, adapter, verifier=verifier)
|
||||
assert result.status == 'UPLOADED_VERIFIED'
|
||||
assert catalogs == [request.library, request.library]
|
||||
assert verified[0].lmc_file == request.library
|
||||
assert verified[0].mapped_drive == 'S:' and verified[0].mapped_remote_root == r'\\server\share'
|
||||
|
||||
|
||||
def test_source_inside_target_library_rejected_before_catalog(setup):
|
||||
request, adapter, _ = setup
|
||||
source = request.library.parent/'ReusableBlocksLP/Block/Work/Block.prj'
|
||||
adapter.catalog = lambda *a: pytest.fail('overlapping source reached native catalog')
|
||||
result = execute(replace(request, operation='add', name='New', source=source), adapter)
|
||||
assert result.status == 'BLOCKED' and not request.evidence_dir.exists()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('matched', [True, False])
|
||||
def test_prepared_native_identity_is_required_after_exact_catalog(setup, matched):
|
||||
from cbb_refresh_verify.native_engineering_identity import IdentityOutcome
|
||||
from cbb_refresh_verify.management import NativeOutcome
|
||||
request, adapter, source = setup
|
||||
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-baseline-manifest.json').exists()
|
||||
adapter.calls.append('prepare_identity')
|
||||
return staged, IdentityOutcome(expected, True, 'baseline captured', root)
|
||||
adapter.prepare_add_transaction = prepare
|
||||
original_add = adapter.add
|
||||
def add(staged, evidence):
|
||||
original_add(staged, evidence)
|
||||
return NativeOutcome(True, True, 'native registered', identity_matches=matched,
|
||||
identity_proof=expected if matched else {'different': True})
|
||||
adapter.add = add
|
||||
result = execute(replace(request, operation='update', source=source, auto_verify=False), adapter)
|
||||
assert adapter.calls[0:2] == ['prepare_identity', 'remove']
|
||||
assert result.status == ('UPLOADED' if matched else 'RECOVERY_REQUIRED')
|
||||
@@ -0,0 +1,141 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
from types import ModuleType, SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def test_raw_dispatch_diagnostics_preserve_hresult_and_known_member_ids(tmp_path):
|
||||
from cbb_refresh_verify.native_management import _dispatch_diagnostics
|
||||
class Error(RuntimeError):
|
||||
hresult = -2147221008
|
||||
class Raw:
|
||||
def GetIDsOfNames(self, name):
|
||||
if name == 'Quit': raise Error('COM apartment unavailable')
|
||||
return 17 if name == 'Close' else 21
|
||||
obj = SimpleNamespace(_oleobj_=Raw())
|
||||
_dispatch_diagnostics(tmp_path, 'before-import', obj, obj)
|
||||
record = json.loads((tmp_path/'dispatch-diagnostics.jsonl').read_text(encoding='utf-8'))
|
||||
assert record['members']['application.OnReusableBlocksEditor']['dispid'] == 21
|
||||
assert record['members']['library.Close']['dispid'] == 17
|
||||
error = record['members']['application.Quit']['error']
|
||||
assert error['hresult'] == -2147221008 and error['args'] == ['COM apartment unavailable']
|
||||
assert error['type'].endswith('Error')
|
||||
|
||||
|
||||
def test_probe_records_dispatch_before_after_import_and_after_source_alignment(tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.native_management as native
|
||||
import sys, os
|
||||
source = tmp_path/'source/Block.prj'
|
||||
source.parent.mkdir()
|
||||
source.write_text('KEY RootBlock "Block"\nKEY PCBDesignPath "PCB/Block.pcb"\n'
|
||||
'KEY iCDBDir "database"\nKEY CentralLibrary "old.lmc"\n')
|
||||
(source.parent/'database').mkdir(); (source.parent/'database/icdb.dat').write_bytes(b'fixture')
|
||||
pcb = source.parent/'PCB/Block.pcb'; (pcb.parent/'Layout').mkdir(parents=True)
|
||||
pcb.write_text('KEY ProjectFile "../Block.prj"\n')
|
||||
(pcb.parent/'pcb.prj').write_text('KEY CentralLibrary "old.lmc"\n')
|
||||
(pcb.parent/'Layout/LayoutDB.lyt').write_bytes(b'fixture')
|
||||
root = tmp_path/'native-add'; root.mkdir()
|
||||
library = root/'fixture/mentor_lib.lmc'; library.parent.mkdir(); library.touch()
|
||||
phase = ['before']
|
||||
class Raw:
|
||||
def GetIDsOfNames(self, name): return 1 if phase[0] == 'before' else 2
|
||||
class App:
|
||||
_oleobj_ = Raw()
|
||||
def OnReusableBlocksEditor(self): raise RuntimeError('stop before native UI')
|
||||
class Uia(ModuleType):
|
||||
def __getattr__(self, name):
|
||||
if name == 'Desktop':
|
||||
phase[0] = 'after'
|
||||
return None
|
||||
raise AttributeError(name)
|
||||
monkeypatch.setitem(sys.modules, 'pywinauto', Uia('pywinauto'))
|
||||
job = {'operation': 'probe_create_add', 'source': str(source), 'library': str(library),
|
||||
'name': 'Block', 'timeout_seconds': 0, 'supervisor_pid': os.getpid()}
|
||||
with pytest.raises(RuntimeError, match='stop before native UI'):
|
||||
native._probe_add_dialog_impl(App(), job, None, set(), root, library=SimpleNamespace(_oleobj_=Raw()))
|
||||
records = [json.loads(line) for line in (root/'dispatch-diagnostics.jsonl').read_text(encoding='utf-8').splitlines()]
|
||||
assert [r['stage'] for r in records] == ['before-pywinauto-import', 'after-pywinauto-import', 'after-source-alignment']
|
||||
assert records[0]['members']['application.Quit']['dispid'] == 1
|
||||
assert records[1]['members']['application.Quit']['dispid'] == 2
|
||||
assert records[2]['paths'] == {'source': str(source), 'pcb': str(pcb), 'library_argument': str(library)}
|
||||
assert 'old.lmc' not in source.read_text()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('operation', ['probe_create_add', 'probe_readd', 'catalog'])
|
||||
def test_probe_preloads_uia_before_com_proxy_creation_but_catalog_stays_read_only(tmp_path, monkeypatch, operation):
|
||||
import sys, win32com.client
|
||||
import cbb_refresh_verify.native_management as native
|
||||
import cbb_refresh_verify.mentor_adapter as mentor
|
||||
root = tmp_path/'job'; root.mkdir()
|
||||
library_path = tmp_path/'fixture.lmc'; library_path.touch()
|
||||
events, running = [], [False]
|
||||
class Uia(ModuleType):
|
||||
def __getattr__(self, name):
|
||||
if name == 'Desktop':
|
||||
events.append('uia-loaded')
|
||||
return object
|
||||
raise AttributeError(name)
|
||||
monkeypatch.setitem(sys.modules, 'pywinauto', Uia('pywinauto'))
|
||||
library = SimpleNamespace(FullName=str(library_path), FlowType=1,
|
||||
Partitions=lambda kind: SimpleNamespace(Count=0), Close=lambda: events.append('library-close'))
|
||||
class App:
|
||||
def OpenLibrary(self, path): return library
|
||||
def CreateLibrary(self, path, flow): return library
|
||||
def Quit(self): events.append('quit'); running[0] = False
|
||||
def dispatch(progid):
|
||||
events.append('dispatch'); running[0] = True
|
||||
return App()
|
||||
monkeypatch.setattr(win32com.client, 'DispatchEx', dispatch)
|
||||
monkeypatch.setattr(native, '_current_desktop', lambda:
|
||||
(SimpleNamespace(EnumDesktopWindows=lambda: []), 'CbbManagement_test'))
|
||||
monkeypatch.setattr(mentor, '_process_details', lambda name:
|
||||
[(123, str(tmp_path/'lm/win32/bin/LibraryManager.exe'), '', 0)] if running[0] else [])
|
||||
monkeypatch.setattr(native, 'prepare_probe_library', lambda *a: library_path)
|
||||
monkeypatch.setattr(native, 'validate_probe_readd', lambda *a: library_path)
|
||||
class Disconnected(RuntimeError):
|
||||
hresult = -2147220995
|
||||
def editor(*a, **k): raise Disconnected('controlled native failure')
|
||||
monkeypatch.setattr(native, '_probe_add_dialog', editor)
|
||||
monkeypatch.setattr(native, '_wait_native_exit', lambda pids: True)
|
||||
result = native._catalog_native({'operation': operation, 'desktop': 'CbbManagement_test',
|
||||
'library': str(library_path), 'mentor_home': str(tmp_path), 'probe_token': 'fixture'}, root)
|
||||
assert events[:2] == (['dispatch', 'library-close'] if operation == 'catalog' else ['uia-loaded', 'dispatch'])
|
||||
if operation == 'catalog':
|
||||
assert result['success'] and 'uia-loaded' not in events
|
||||
else:
|
||||
assert result['exception']['hresult'] == -2147220995
|
||||
assert result['exception']['args'] == ['controlled native failure']
|
||||
|
||||
|
||||
def test_probe_converts_desktop_pyhandle_before_uia_boundary(tmp_path, monkeypatch):
|
||||
import sys, win32gui, win32process
|
||||
import cbb_refresh_verify.native_management as native
|
||||
import cbb_refresh_verify.management as management
|
||||
import cbb_refresh_verify.backup_recovery as recovery
|
||||
source = tmp_path/'source/Block.prj'
|
||||
source.parent.mkdir()
|
||||
source.write_bytes(b'file-only UIA boundary fixture')
|
||||
pcb = source.parent/'PCB/Block.pcb'
|
||||
root = tmp_path/'native-add'; root.mkdir()
|
||||
class Handle:
|
||||
def __int__(self): return 200
|
||||
handle = Handle()
|
||||
desktop = SimpleNamespace(EnumDesktopWindows=lambda: [handle])
|
||||
monkeypatch.setattr(win32process, 'GetWindowThreadProcessId', lambda hwnd: (1, 9))
|
||||
monkeypatch.setattr(win32gui, 'IsWindowVisible', lambda hwnd: True)
|
||||
monkeypatch.setattr(win32gui, 'GetWindowText', lambda hwnd: 'Reusable Blocks')
|
||||
monkeypatch.setattr(management, 'source_project', lambda *a: (source, pcb, 'Block'))
|
||||
monkeypatch.setattr(recovery, '_align_library', lambda *a: None)
|
||||
class Desktop:
|
||||
def __init__(self, **kwargs): pass
|
||||
def window(self, *, handle):
|
||||
assert type(handle) is int and handle == 200
|
||||
raise RuntimeError('integer UIA boundary reached')
|
||||
monkeypatch.setitem(sys.modules, 'pywinauto', SimpleNamespace(Desktop=Desktop))
|
||||
app = SimpleNamespace(OnReusableBlocksEditor=lambda: None)
|
||||
import os
|
||||
job = {'operation': 'probe_create_add', 'source': str(source), 'name': 'Block', 'supervisor_pid': os.getpid(),
|
||||
'library': str(root/'fixture/mentor_lib.lmc'), 'timeout_seconds': 5}
|
||||
with pytest.raises(RuntimeError, match='integer UIA boundary reached'):
|
||||
native._probe_add_dialog_impl(app, job, desktop, {9}, root)
|
||||
@@ -0,0 +1,155 @@
|
||||
"""Run the real management engine with only the native/export boundaries faked."""
|
||||
from dataclasses import replace
|
||||
import json
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def transaction(tmp_path, monkeypatch):
|
||||
from test_management import project
|
||||
import cbb_refresh_verify.native_management as native
|
||||
import cbb_refresh_verify.native_engineering_identity as identity
|
||||
import cbb_refresh_verify.backup_recovery as recovery
|
||||
from cbb_refresh_verify.management import ManagementRequest, engineering_identity, _write_json
|
||||
from cbb_refresh_verify.management_transaction import validate_transaction
|
||||
root = tmp_path/'probe'
|
||||
library = root/'native-add/fixture/mentor_lib.lmc'
|
||||
library.parent.mkdir(parents=True); library.write_bytes(b'fixture library')
|
||||
(root/'probe-owner.json').write_text(json.dumps({'library': str(library), 'token': 'owned'}), encoding='utf-8')
|
||||
source = project(tmp_path/'source')
|
||||
for path in (source, source.parent/'PCB/pcb.prj'):
|
||||
with path.open('a') as stream: stream.write(f'KEY CentralLibrary "{library}"\n')
|
||||
state = {'entries': [], 'calls': [], 'corrupt': False, 'fail_add': False}
|
||||
monkeypatch.setattr(native.NativeManagementAdapter, '_binary_capability', lambda _: '')
|
||||
monkeypatch.setattr(identity, 'check_exporters', lambda _: None)
|
||||
monkeypatch.setattr(recovery, '_idle_check', lambda *_: None)
|
||||
def capture(source, evidence, *, expected_library, **kwargs):
|
||||
evidence = Path(evidence); evidence.mkdir(parents=True, exist_ok=False)
|
||||
value = identity.asset_identity(source, expected_library)
|
||||
value.update(ascii_sha256='logical', csv={'work/identity': 'tables'}, edif_sha256='geometry')
|
||||
_write_json(evidence/'identity.json', {'identity': value, 'safe_to_continue': True})
|
||||
return identity.IdentityOutcome(value, True, 'file-only export proof', evidence)
|
||||
monkeypatch.setattr(identity, 'capture_identity', capture)
|
||||
def worker(adapter, job, evidence):
|
||||
evidence = Path(evidence); evidence.mkdir(parents=True, exist_ok=False)
|
||||
state['calls'].append(job['operation'])
|
||||
if job['operation'] == 'catalog':
|
||||
return {'success': True, 'safe_to_continue': True, 'library': str(library), 'flow': 1,
|
||||
'entries': list(state['entries'])}
|
||||
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') == '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)
|
||||
if state['fail_add']: return {'success': False, 'safe_to_continue': True, 'detail': 'native failure'}
|
||||
staged = Path(job['source'])
|
||||
(staged.parent/'database/icdb.dat').write_bytes(b'native database normalization')
|
||||
work = library.parent/'ReusableBlocksLP'/job['name']/'Work'
|
||||
shutil.copytree(staged.parent, work)
|
||||
pcb_project = work/'PCB/pcb.prj'
|
||||
text = pcb_project.read_text()
|
||||
import re
|
||||
pcb_project.write_text(re.sub(r'KEY CentralLibrary "[^"]*"', 'KEY CentralLibrary "wrong-relative.lmc"', text))
|
||||
if state['corrupt'] == 'unknown_cdbsvr':
|
||||
unknown = work/'database/cdbsvr/persistent.dat'; unknown.parent.mkdir(parents=True, exist_ok=True)
|
||||
unknown.write_bytes(b'unexpected engineering content')
|
||||
elif state['corrupt']: (work/'PCB/Layout/LayoutDB.lyt').write_bytes(b'wrong physical design')
|
||||
state['entries'] = [{'name': job['name'], 'partition': job['partition'],
|
||||
'engineering_identity': engineering_identity(work/staged.name)}]
|
||||
return {'success': True, 'safe_to_continue': True, 'identity_matches': False}
|
||||
if job['operation'] == 'remove':
|
||||
state['entries'] = []
|
||||
shutil.rmtree(library.parent/'ReusableBlocksLP'/job['name'])
|
||||
return {'success': True, 'safe_to_continue': True}
|
||||
pytest.fail('unexpected native operation')
|
||||
monkeypatch.setattr(native.NativeManagementAdapter, '_worker', worker)
|
||||
request = ManagementRequest('add', library, 'Block', source=source, auto_verify=False,
|
||||
evidence_dir=tmp_path/'evidence')
|
||||
yield root, request, state
|
||||
from cbb_refresh_verify.library_lock import LibraryLock, _owners, _guard, blocker_path
|
||||
with _guard:
|
||||
owner = _owners.pop(LibraryLock(library).key, None)
|
||||
if owner: owner['handle'].Close()
|
||||
blocker_path(library).unlink(missing_ok=True)
|
||||
|
||||
|
||||
def execute(root, request):
|
||||
from cbb_refresh_verify.native_management import run_owned_fixture_management
|
||||
return run_owned_fixture_management(request, root, probe_token='owned', idle_check=lambda *_: None)
|
||||
|
||||
|
||||
def test_owned_fixture_engine_add_conflict_update_remove_and_identity(transaction):
|
||||
from cbb_refresh_verify.native_engineering_identity import project_library
|
||||
root, request, state = transaction
|
||||
original = request.source.read_bytes()
|
||||
assert execute(root, request).status == 'UPLOADED'
|
||||
registered = request.library.parent/'ReusableBlocksLP/Block/Work/Source.prj'
|
||||
assert project_library(registered) == request.library.resolve()
|
||||
calls = len(state['calls'])
|
||||
assert execute(root, request).status == 'UPLOAD_FAILED'
|
||||
assert state['calls'][calls:] == ['catalog']
|
||||
(request.source.parent/'PCB/Layout/LayoutDB.lyt').write_bytes(b'replacement physical design')
|
||||
assert execute(root, replace(request, operation='update')).status == 'UPLOADED'
|
||||
assert (registered.parent/'PCB/Layout/LayoutDB.lyt').read_bytes() == b'replacement physical design'
|
||||
assert execute(root, replace(request, operation='remove', source=None)).status == 'REMOVED'
|
||||
assert execute(root, request).status == 'UPLOADED'
|
||||
assert request.source.read_bytes() == original
|
||||
|
||||
|
||||
@pytest.mark.parametrize('corrupt', [True, 'unknown_cdbsvr'])
|
||||
def test_native_registered_but_asset_mismatch_retains_recovery(transaction, corrupt):
|
||||
root, request, state = transaction
|
||||
state['corrupt'] = corrupt
|
||||
result = execute(root, request)
|
||||
assert result.status == 'RECOVERY_REQUIRED' and result.safe_to_continue
|
||||
assert execute(root, request).status == 'BLOCKED'
|
||||
|
||||
|
||||
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 result.safe_to_continue
|
||||
assert execute(root, replace(request, operation='update')).status == 'BLOCKED'
|
||||
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']]
|
||||
|
||||
|
||||
def test_fixture_grant_cannot_authorize_arbitrary_library(transaction, tmp_path):
|
||||
from cbb_refresh_verify.native_management import run_owned_fixture_management
|
||||
root, request, state = transaction
|
||||
other = tmp_path/'production.lmc'; other.write_bytes(b'unchanged')
|
||||
with pytest.raises(ValueError):
|
||||
run_owned_fixture_management(replace(request, library=other), root, probe_token='owned')
|
||||
assert other.read_bytes() == b'unchanged' and not state['calls']
|
||||
|
||||
|
||||
@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
|
||||
original = request.source.read_bytes()
|
||||
result = execute(root, request)
|
||||
assert result.status == 'RECOVERY_REQUIRED' and not result.safe_to_continue
|
||||
assert state['entries'] == [] and request.source.read_bytes() == original
|
||||
|
||||
|
||||
def test_long_staged_runtime_path_blocks_update_before_native_remove(transaction):
|
||||
root, request, state = transaction
|
||||
assert execute(root, request).status == 'UPLOADED'
|
||||
runtime = request.source.parent/'CES/LogFiles'/('long-'+'x'*100)/('y'*60+'.log')
|
||||
runtime.parent.mkdir(parents=True); runtime.write_bytes(b'complete original runtime history')
|
||||
before = len(state['calls'])
|
||||
result = execute(root, replace(request, operation='update'))
|
||||
assert result.status == 'UPLOAD_FAILED' and result.safe_to_continue
|
||||
assert 'NATIVE_PATH_TOO_LONG' in result.detail
|
||||
assert state['calls'][before:] == ['catalog']
|
||||
assert len(state['entries']) == 1 and runtime.read_bytes() == b'complete original runtime history'
|
||||
@@ -0,0 +1,189 @@
|
||||
"""Exercise actual guards/snapshots; only the native worker transport is fake."""
|
||||
from dataclasses import asdict
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def prohibit_native_launch(monkeypatch):
|
||||
"""Backstop independent of the boundary under development: no live apps."""
|
||||
import subprocess, win32process, win32com.client
|
||||
import cbb_refresh_verify.desktop_worker as desktop
|
||||
def forbidden(*a, **k):
|
||||
raise AssertionError('Native/process launch is forbidden in probe-guard tests')
|
||||
monkeypatch.setattr(desktop, 'DesktopWorker', forbidden)
|
||||
monkeypatch.setattr(win32process, 'CreateProcess', forbidden)
|
||||
monkeypatch.setattr(subprocess, 'Popen', forbidden)
|
||||
monkeypatch.setattr(win32com.client, 'Dispatch', forbidden)
|
||||
monkeypatch.setattr(win32com.client, 'DispatchEx', forbidden)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def probe_files(tmp_path):
|
||||
def source(root, data):
|
||||
(root/'database').mkdir(parents=True)
|
||||
(root/'database/icdb.dat').write_bytes(data)
|
||||
(root/'PCB/Layout').mkdir(parents=True)
|
||||
(root/'PCB/Layout/LayoutDB.lyt').write_bytes(data)
|
||||
(root/'PCB/pcb.prj').write_text('KEY CentralLibrary "old.lmc"\n')
|
||||
(root/'PCB/Block.pcb').write_text('KEY ProjectFile "../Block.prj"\n')
|
||||
project = root/'Block.prj'
|
||||
project.write_text('KEY RootBlock "Block"\nKEY iCDBDir "database"\nKEY PCBDesignPath "PCB/Block.pcb"\n')
|
||||
return project
|
||||
original = source(tmp_path/'original', b'original')
|
||||
replacement = source(tmp_path/'replacement', b'replacement')
|
||||
root = tmp_path/'probe'
|
||||
yield original, replacement, root
|
||||
# Only file fakes ran; close this test's deliberately retained OS handle.
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
library = root/'native-add/fixture/mentor_lib.lmc'
|
||||
with locks._guard:
|
||||
owner = locks._owners.pop(locks._key(library.with_name('.mentor_lib.cbb-upload.lock')), None)
|
||||
if owner:
|
||||
owner['handle'].Close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('fault', ['create_unsafe', 'first_catalog_exception', 'remove_unsafe',
|
||||
'remove_exception', 'after_remove_exception', 'readd_unsafe', 'readd_exception', 'final_catalog_exception'])
|
||||
def test_isolated_probe_retains_guard_on_uncertain_native_lifecycle(probe_files, monkeypatch, fault):
|
||||
import cbb_refresh_verify.native_management as native
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
from cbb_refresh_verify.management import Capability, CatalogEntry, engineering_identity
|
||||
original, replacement, root = probe_files
|
||||
records = []
|
||||
monkeypatch.setattr(native.NativeManagementAdapter, 'capabilities', lambda self:
|
||||
{'remove': Capability(True, 'file transport fixture')})
|
||||
def launch(self, job, evidence):
|
||||
nonlocal records
|
||||
evidence = Path(evidence)
|
||||
operation = job['operation']
|
||||
library = Path(job['library'])
|
||||
if operation == 'probe_create_add':
|
||||
# Directory creation belongs to the real supervising adapter.
|
||||
assert native.prepare_probe_library(job, evidence) == library
|
||||
library.write_bytes(b'native-created fixture')
|
||||
(root/'probe-owner.json').write_text(json.dumps({'library': str(library), 'token': job['probe_token']}))
|
||||
records = [CatalogEntry(job['name'], 'Logical-Physical', engineering_identity(job['source']))]
|
||||
if fault == 'create_unsafe':
|
||||
return {'success': False, 'safe_to_continue': False, 'detail': 'creation owner retained'}
|
||||
elif operation == 'remove':
|
||||
if fault == 'remove_exception':
|
||||
raise TimeoutError('native removal transport disconnected')
|
||||
if fault == 'remove_unsafe':
|
||||
return {'success': False, 'safe_to_continue': False, 'detail': 'removal owner retained'}
|
||||
records = []
|
||||
elif operation == 'probe_readd':
|
||||
if fault == 'readd_exception':
|
||||
raise TimeoutError('native readd transport disconnected')
|
||||
if fault == 'readd_unsafe':
|
||||
return {'success': False, 'safe_to_continue': False, 'detail': 'readd owner retained'}
|
||||
records = [CatalogEntry(job['name'], 'Logical-Physical', engineering_identity(job['source']))]
|
||||
elif operation == 'catalog':
|
||||
stage_fault = {'reopen': 'first_catalog_exception', 'after-remove': 'after_remove_exception',
|
||||
'reopen-update': 'final_catalog_exception'}.get(evidence.name)
|
||||
if stage_fault == fault:
|
||||
raise TimeoutError('catalog owner release unknown')
|
||||
return {'success': True, 'safe_to_continue': True, 'library': str(library), 'flow': 1,
|
||||
'entries': [asdict(entry) for entry in records], 'detail': 'file fixture result'}
|
||||
class Worker:
|
||||
def __init__(self, command, desktop):
|
||||
request = Path(command[-1])
|
||||
job = json.loads(request.read_text(encoding='utf-8'))
|
||||
result = launch(None, job, request.parent)
|
||||
(request.parent/'result.json').write_text(json.dumps(result), encoding='utf-8')
|
||||
def poll(self): return 0
|
||||
def close(self): pass
|
||||
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', Worker)
|
||||
try:
|
||||
native.run_isolated_probe(original, root, 'Block', replacement_source=replacement)
|
||||
except TimeoutError:
|
||||
pass
|
||||
library = root/'native-add/fixture/mentor_lib.lmc'
|
||||
assert locks.has_blocker(library)
|
||||
with pytest.raises(locks.LibraryBusy):
|
||||
with locks.LibraryLock(library): pass
|
||||
assert (root/'probe-result.json').is_file()
|
||||
from contextlib import contextmanager
|
||||
@contextmanager
|
||||
def denied(*a):
|
||||
raise locks.LibraryBusy('fresh proof still sees a native owner')
|
||||
yield
|
||||
monkeypatch.setattr(locks, '_prove_library_released', denied)
|
||||
with pytest.raises(locks.LibraryBusy):
|
||||
locks.release_retained_library(library, root/'release-checks')
|
||||
assert locks.has_blocker(library)
|
||||
@contextmanager
|
||||
def released(*a):
|
||||
yield {'native_owners': [], 'addresses': [], 'exclusive_files': [str(library)]}
|
||||
monkeypatch.setattr(locks, '_prove_library_released', released)
|
||||
assert locks.release_retained_library(library, root/'release-checks')['status'] == 'RELEASE_CONFIRMED'
|
||||
with locks.LibraryLock(library): pass
|
||||
|
||||
|
||||
def test_mapping_context_is_serialized_and_restored_before_catalog(tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.native_management as native
|
||||
import cbb_refresh_verify.network_path as network
|
||||
captured = []
|
||||
class Worker:
|
||||
def __init__(self, command, desktop):
|
||||
request = Path(command[-1])
|
||||
job = json.loads(request.read_text(encoding='utf-8'))
|
||||
captured.append(job)
|
||||
(request.parent/'result.json').write_text(json.dumps({'success': True, 'safe_to_continue': True,
|
||||
'library': job['library'], 'flow': 1, 'entries': []}), encoding='utf-8')
|
||||
def poll(self): return 0
|
||||
def close(self): pass
|
||||
adapter = native.NativeManagementAdapter(worker_factory=Worker)
|
||||
adapter.bind_library_mapping('S:', r'\\server\share')
|
||||
library = Path('S:/library/mentor.lmc')
|
||||
adapter.catalog(library, tmp_path/'catalog')
|
||||
assert captured[0]['library'] == str(library)
|
||||
assert captured[0]['mapped_drive'] == 'S:'
|
||||
order = []
|
||||
monkeypatch.setattr(native, '_current_desktop', lambda: (None, captured[0]['desktop']))
|
||||
monkeypatch.setattr(network, 'ensure_mapped_drive_visible', lambda drive, remote:
|
||||
order.append(('mapping', drive, remote)))
|
||||
monkeypatch.setattr(native, '_catalog_native', lambda job, root:
|
||||
(order.append(('catalog', job['library'])) or {'success': True, 'safe_to_continue': True}))
|
||||
assert native.management_worker_main(tmp_path/'catalog/request.json') == 0
|
||||
assert order == [('mapping', 'S:', r'\\server\share'), ('catalog', str(library))]
|
||||
|
||||
|
||||
def test_removal_cli_keeps_mapped_drive_spelling(tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.native_management as native
|
||||
from cbb_refresh_verify.management import Capability
|
||||
job = {'operation': 'remove', 'library': 'S:\\library\\mentor.lmc', 'name': 'Block',
|
||||
'partition': 'Logical-Physical', 'desktop': 'CbbManagement_fixture',
|
||||
'mentor_home': str(tmp_path), 'timeout_seconds': 10}
|
||||
request = tmp_path/'request.json'; request.write_text(json.dumps(job), encoding='utf-8')
|
||||
monkeypatch.setattr(native, '_current_desktop', lambda: (None, job['desktop']))
|
||||
monkeypatch.setattr(native.NativeManagementAdapter, 'capabilities', lambda self: {'remove': Capability(True, 'fake transport')})
|
||||
commands = []
|
||||
class Process:
|
||||
pid = 1234
|
||||
def __init__(self, command, *, stdout, **kwargs):
|
||||
commands.append(command)
|
||||
stdout.write(b"# Note: Removed REUSE_BLOCK 'Block' from partition 'Logical-Physical'.\n")
|
||||
stdout.flush()
|
||||
def wait(self, **kwargs): return 0
|
||||
monkeypatch.setattr(native.subprocess, 'Popen', Process)
|
||||
assert native.management_worker_main(request) == 0
|
||||
assert commands[0][1] == job['library']
|
||||
|
||||
|
||||
def test_staged_project_alignment_keeps_selected_mapped_drive(tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify.backup_recovery import _align_library
|
||||
project = tmp_path/'Block.prj'
|
||||
project.write_text('KEY CentralLibrary "old.lmc"\n', encoding='utf-8')
|
||||
pcb = tmp_path/'PCB/Block.pcb'; pcb.parent.mkdir(); pcb.touch()
|
||||
pcb_project = pcb.parent/'pcb.prj'
|
||||
pcb_project.write_text('KEY CentralLibrary "old.lmc"\n', encoding='utf-8')
|
||||
library = Path('S:/library/mentor.lmc')
|
||||
original_resolve = Path.resolve
|
||||
monkeypatch.setattr(Path, 'resolve', lambda path, *a, **k:
|
||||
Path(r'\\server\share\library\mentor.lmc') if path == library else original_resolve(path, *a, **k))
|
||||
_align_library(project, pcb, library)
|
||||
for path in (project, pcb_project):
|
||||
assert 'KEY CentralLibrary "S:\\library\\mentor.lmc"' in path.read_text(encoding='utf-8')
|
||||
@@ -0,0 +1,571 @@
|
||||
"""Retry boundaries use fake native outcomes and temporary libraries only."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from test_management import setup, execute
|
||||
from test_management_native_transaction import transaction
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def isolated_mutex(monkeypatch):
|
||||
import win32event
|
||||
from uuid import uuid4
|
||||
original = win32event.CreateMutex
|
||||
suffix = uuid4().hex
|
||||
monkeypatch.setattr(win32event, 'CreateMutex', lambda security, owned, name:
|
||||
original(security, owned, name + suffix))
|
||||
|
||||
|
||||
def test_released_catalog_failure_does_not_retain_management_lease(setup, monkeypatch):
|
||||
from cbb_refresh_verify.native_management import NativeManagementAdapter
|
||||
from cbb_refresh_verify.library_lock import LibraryLock, blocker_path
|
||||
request, _, _ = setup
|
||||
adapter = NativeManagementAdapter(mentor_home=request.library.parent)
|
||||
monkeypatch.setattr(adapter, 'capabilities', lambda: {'remove': SimpleNamespace(supported=True)})
|
||||
monkeypatch.setattr(adapter, '_worker', lambda *_: {
|
||||
'success': False, 'safe_to_continue': True, 'detail': 'catalog read failed after exit'})
|
||||
result = execute(request, adapter)
|
||||
assert result.safe_to_continue
|
||||
assert not blocker_path(request.library).exists()
|
||||
with LibraryLock(request.library):
|
||||
pass
|
||||
|
||||
|
||||
@pytest.mark.parametrize('busy', [False, True])
|
||||
def test_legacy_blocker_is_rechecked_before_management_without_inventing_new_owner(setup, monkeypatch, isolated_mutex, busy):
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
request, adapter, _ = setup
|
||||
marker = locks.blocker_path(request.library)
|
||||
legacy = {'protocol': 'cbb-refresh-verify-library-lease', 'version': 1,
|
||||
'lease_id': 'eae80a06f23e4664b00c70b6bf81b01d', 'library': str(request.library),
|
||||
'status': 'OWNER_RELEASE_UNCONFIRMED', 'pid': 57076, 'time': '2026-11-04T09:43:50.830958+00:00'}
|
||||
marker.write_text(json.dumps(legacy), encoding='utf-8')
|
||||
before = marker.read_bytes()
|
||||
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
|
||||
address = request.library.parent/'database/cdbsvr/sAddress.adr'
|
||||
if busy:
|
||||
address.parent.mkdir(parents=True); address.write_bytes(b'actual address')
|
||||
result = execute(request, adapter)
|
||||
assert result.safe_to_continue, 'No new native session was started by a blocked release check'
|
||||
assert result.evidence_path and result.evidence_path.is_file()
|
||||
if busy:
|
||||
assert result.status == 'BLOCKED' and adapter.calls == []
|
||||
assert marker.read_bytes() == before and address.read_bytes() == b'actual address'
|
||||
assert '地址' in result.detail
|
||||
else:
|
||||
assert result.status == 'REMOVED' and adapter.calls == ['remove']
|
||||
assert result.release_proof['status'] == 'RELEASE_CONFIRMED'
|
||||
archive = Path(result.release_proof['evidence_path']).with_name('blocker-before-0.json')
|
||||
assert archive.read_bytes() == before and not marker.exists()
|
||||
|
||||
|
||||
def test_busy_execution_channel_does_not_create_unreleased_management_owner(setup, monkeypatch):
|
||||
import win32con, win32event
|
||||
request, adapter, _ = setup
|
||||
monkeypatch.setattr(win32event, 'WaitForSingleObject', lambda *_: win32con.WAIT_TIMEOUT)
|
||||
result = execute(request, adapter)
|
||||
assert result.status == 'BLOCKED' and result.safe_to_continue and not adapter.calls
|
||||
assert result.evidence_path.is_file()
|
||||
|
||||
|
||||
|
||||
|
||||
def test_management_worker_prelaunch_failure_is_safe(tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.native_management as native
|
||||
job = tmp_path/'request.json'
|
||||
job.write_text(json.dumps({'operation': 'catalog', 'desktop': 'CbbManagement_test',
|
||||
'library': str(tmp_path/'lib.lmc')}), encoding='utf-8')
|
||||
monkeypatch.setattr(native, '_current_desktop', lambda: (None, 'wrong desktop'))
|
||||
assert native.management_worker_main(job) == 2
|
||||
result = json.loads((tmp_path/'result.json').read_text('utf-8'))
|
||||
assert result['safe_to_continue'] is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize('code,busy', [(5, False), (32, True), (33, True)])
|
||||
def test_coordination_open_error_preserves_access_failure(tmp_path, monkeypatch, code, busy):
|
||||
import pywintypes
|
||||
import win32file
|
||||
from cbb_refresh_verify.library_lock import LibraryLock, LibraryBusy
|
||||
def denied(*_):
|
||||
raise pywintypes.error(code, 'CreateFile', 'test failure')
|
||||
monkeypatch.setattr(win32file, 'CreateFile', denied)
|
||||
with pytest.raises((OSError, pywintypes.error)) as error:
|
||||
with LibraryLock(tmp_path/'lib.lmc'):
|
||||
pass
|
||||
assert isinstance(error.value, LibraryBusy) is busy
|
||||
|
||||
|
||||
def test_retained_checkpoint_lease_can_reprobe_exact_release(tmp_path):
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
released = False
|
||||
lease = locks.LibraryLock(library, safe_to_release=lambda: released)
|
||||
try:
|
||||
with lease:
|
||||
pass
|
||||
with pytest.raises(locks.LibraryBusy):
|
||||
with locks.LibraryLock(library):
|
||||
pass
|
||||
released = True
|
||||
with locks.LibraryLock(library):
|
||||
pass
|
||||
assert not locks.blocker_path(library).exists()
|
||||
finally:
|
||||
owner = locks._owners.pop(lease.key, None)
|
||||
if owner:
|
||||
owner['handle'].Close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('failure', ['enumerate', 'cancel'])
|
||||
def test_owned_mapping_close_retries_after_transient_failure(monkeypatch, failure):
|
||||
from test_network_path import FakeWNet
|
||||
from cbb_refresh_verify.network_path import LibraryPathLease, NetworkPathError
|
||||
backend = FakeWNet()
|
||||
lease = LibraryPathLease.acquire(r'\\server\share\lib.lmc', backend=backend)
|
||||
method = 'mappings' if failure == 'enumerate' else 'cancel_mapping'
|
||||
original = getattr(backend, method)
|
||||
def broken(*_):
|
||||
raise OSError('temporary disconnect')
|
||||
monkeypatch.setattr(backend, method, broken)
|
||||
with pytest.raises(NetworkPathError):
|
||||
lease.close()
|
||||
monkeypatch.setattr(backend, method, original)
|
||||
lease.close()
|
||||
assert backend.cancelled == [lease.drive]
|
||||
|
||||
|
||||
def test_batch_mismatch_isolated_to_item(tmp_path):
|
||||
from cbb_refresh_verify.batch_status import BatchStatusSession
|
||||
from cbb_refresh_verify.status_bridge import BridgeResponseError, BridgeResult
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
class Bridge:
|
||||
def __init__(self): self.calls = []; self.restarts = 0
|
||||
def start(self): pass
|
||||
def close(self): pass
|
||||
def restart(self): self.restarts += 1
|
||||
def query(self, library, name, **kwargs):
|
||||
self.calls.append(name)
|
||||
if name == 'Bad': raise BridgeResponseError('CBB mismatch')
|
||||
return BridgeResult('PENDING', 'test')
|
||||
bridge = Bridge()
|
||||
results = BatchStatusSession(bridge).scan(['Bad', 'Good'], library, tmp_path/'scan.jsonl')
|
||||
assert [result.status for result in results] == ['MALFORMED', 'PENDING']
|
||||
assert bridge.calls == ['Bad', 'Good'] and bridge.restarts == 1
|
||||
|
||||
|
||||
def test_batch_cache_binds_exact_library_identity(tmp_path):
|
||||
from cbb_refresh_verify.batch_status import fingerprint_library
|
||||
first = tmp_path/'a/lib.lmc'; first.parent.mkdir(); first.write_bytes(b'same')
|
||||
second = tmp_path/'b/lib.lmc'; second.parent.mkdir(); second.write_bytes(b'same')
|
||||
stat = first.stat(); os.utime(second, ns=(stat.st_atime_ns, stat.st_mtime_ns))
|
||||
assert fingerprint_library(first).sha256 != fingerprint_library(second).sha256
|
||||
|
||||
|
||||
def test_timed_out_management_worker_releases_only_after_its_result(tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.native_management as native
|
||||
state = {'exit': None}
|
||||
worker = SimpleNamespace(poll=lambda: state['exit'], close=lambda: None)
|
||||
adapter = native.NativeManagementAdapter(mentor_home=tmp_path, worker_factory=lambda *_: worker)
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
evidence = tmp_path/'run'; evidence.mkdir()
|
||||
result = adapter._launch_worker({'library': str(library), 'operation': 'catalog',
|
||||
'desktop': 'CbbManagement_test', 'timeout_seconds': 0}, evidence)
|
||||
try:
|
||||
assert result['safe_to_continue'] is False
|
||||
assert adapter.release_confirmed(library) is False
|
||||
state['exit'] = 2
|
||||
assert adapter.release_confirmed(library) is False
|
||||
(evidence/'result.json').write_text(json.dumps({'success': False, 'safe_to_continue': True}))
|
||||
assert adapter.release_confirmed(tmp_path/'other.lmc') is False
|
||||
assert adapter.release_confirmed(library) is True
|
||||
assert worker not in native._retained_workers
|
||||
finally:
|
||||
if worker in native._retained_workers:
|
||||
native._retained_workers.remove(worker)
|
||||
|
||||
|
||||
def test_existing_library_manager_refusal_preserves_prelaunch_release(tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.native_management as native
|
||||
monkeypatch.setattr(native, '_current_desktop', lambda: (None, 'CbbManagement_test'))
|
||||
monkeypatch.setattr('cbb_refresh_verify.mentor_adapter._process_details', lambda *_: [(123, 'other')])
|
||||
with pytest.raises(RuntimeError) as error:
|
||||
native._catalog_native({'operation': 'catalog', 'desktop': 'CbbManagement_test'}, tmp_path)
|
||||
assert error.value.safe_to_continue is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize('stage,expected', [('catalog_before', 'REMOVED'), ('native_remove', 'BLOCKED')])
|
||||
def test_prewrite_failure_evidence_does_not_permanently_prevent_retry(setup, stage, expected):
|
||||
request, adapter, _ = setup
|
||||
checkpoint = request.evidence_dir/'interrupted/checkpoint.json'
|
||||
checkpoint.parent.mkdir(parents=True)
|
||||
checkpoint.write_text(json.dumps({'library': str(request.library), 'stage': 'complete',
|
||||
'status': 'BLOCKED', 'safe_to_continue': False, 'history': [{'stage': stage}]}), encoding='utf-8')
|
||||
result = execute(request, adapter)
|
||||
assert result.status == expected
|
||||
|
||||
|
||||
def test_scoped_release_includes_shared_database_addresses(tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
address = tmp_path/'SymbolLibs/__ReusableBlocksSymb/cdbsvr/sAddress.adr'
|
||||
address.parent.mkdir(parents=True); address.write_bytes(b'preserve shared native address')
|
||||
with pytest.raises(locks.LibraryBusy):
|
||||
with locks._prove_library_released(library, block_name='Target'):
|
||||
pass
|
||||
assert address.read_bytes() == b'preserve shared native address'
|
||||
|
||||
|
||||
def test_valid_relocated_pending_checkpoint_does_not_block_snapshot(tmp_path):
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
library = tmp_path/'copy/lib.lmc'; library.parent.mkdir(); library.touch()
|
||||
pending = locks.blocker_path(library).with_suffix('.pending')
|
||||
pending.write_text(json.dumps({'protocol': 'cbb-refresh-verify-library-lease', 'version': 1,
|
||||
'library': str(tmp_path/'source/lib.lmc'), 'pid': os.getpid(),
|
||||
'status': 'OPERATION_IN_PROGRESS', 'lease_id': 'a'*32, 'time': '2026-11-05'}))
|
||||
assert not locks.has_blocker(library)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('content', ['{torn json', '{"unrecognized":"metadata"}'])
|
||||
def test_unknown_checkpoint_release_archives_only_after_full_fresh_proof(tmp_path, monkeypatch, content):
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
|
||||
monkeypatch.setattr('cbb_refresh_verify.native_engineering_identity._process_snapshot', lambda: [])
|
||||
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
|
||||
marker = locks.blocker_path(library); marker.write_text(content)
|
||||
result = locks.release_retained_library(library, tmp_path/'evidence', block_name='Target')
|
||||
assert result['status'] == 'RELEASE_CONFIRMED'
|
||||
assert Path(result['evidence_path']).with_name('blocker-before-0.json').read_text() == content
|
||||
assert not marker.exists()
|
||||
assert library.with_name('.lib.cbb-upload.lock').exists()
|
||||
|
||||
|
||||
def test_unknown_checkpoint_cannot_use_selected_target_to_ignore_other_owners(tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
|
||||
monkeypatch.setattr('cbb_refresh_verify.native_engineering_identity._process_snapshot', lambda: [])
|
||||
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
|
||||
marker = locks.blocker_path(library); marker.write_bytes(b'{torn checkpoint')
|
||||
address = library.parent/'ReusableBlocksLP/Other/Work/database/cdbsvr/sAddress.adr'
|
||||
address.parent.mkdir(parents=True); address.write_bytes(b'preserve owner record')
|
||||
with pytest.raises(locks.LibraryBusy):
|
||||
locks.release_retained_library(library, tmp_path/'evidence', block_name='Target')
|
||||
assert marker.read_bytes() == b'{torn checkpoint'
|
||||
assert address.read_bytes() == b'preserve owner record'
|
||||
|
||||
|
||||
def test_status_cache_does_not_reuse_a_different_block_type(tmp_path):
|
||||
from cbb_refresh_verify.batch_status import BatchStatusSession
|
||||
from cbb_refresh_verify.status_bridge import BridgeResult
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
calls = []
|
||||
class Bridge:
|
||||
def query(self, library, name, **kwargs):
|
||||
calls.append(kwargs['block_type'])
|
||||
return BridgeResult('READY', 'test')
|
||||
session = BatchStatusSession(Bridge())
|
||||
session.scan(['Block'], library, tmp_path/'scan.jsonl', block_type='RULP')
|
||||
session.scan(['Block'], library, tmp_path/'scan.jsonl', block_type='Other')
|
||||
assert calls == ['RULP', 'Other']
|
||||
|
||||
|
||||
@pytest.mark.parametrize('case,relevant', [('other', False), ('prefix', False),
|
||||
('target', True), ('shared', True), ('worker_target', True), ('worker_other', False)])
|
||||
def test_release_owner_scope_uses_exact_paths_and_bound_worker_request(tmp_path, monkeypatch, case, relevant):
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
|
||||
target = library.parent/'ReusableBlocksLP/Target/Work'
|
||||
locations = {'other': tmp_path/'other/Other.prj', 'prefix': target.with_name('WorkOld')/'Other.prj',
|
||||
'target': target/'Target.prj', 'shared': library.parent/'SymbolLibs/shared/database'}
|
||||
if case.startswith('worker_'):
|
||||
job = tmp_path/'worker.json'
|
||||
job.write_text(json.dumps({'library': str(library if case == 'worker_target' else tmp_path/'other/lib.lmc')}))
|
||||
name, command = 'python.exe', f'python.exe --management-worker "{job}"'
|
||||
else:
|
||||
name, command = 'ExpeditionPCB.exe', f'ExpeditionPCB.exe -project="{locations[case]}"'
|
||||
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [
|
||||
{'pid': 123456, 'name': name, 'command': command, 'parent': 0}])
|
||||
if relevant:
|
||||
with pytest.raises(locks.LibraryBusy):
|
||||
with locks._prove_library_released(library, block_name='Target'):
|
||||
pass
|
||||
else:
|
||||
with locks._prove_library_released(library, block_name='Target'):
|
||||
pass
|
||||
|
||||
|
||||
def test_release_ignores_retained_management_worker_for_other_library(tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
import cbb_refresh_verify.native_management as native
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
other = SimpleNamespace(poll=lambda: None, cbb_library=str(tmp_path/'other.lmc'))
|
||||
monkeypatch.setattr(native, '_retained_workers', [other])
|
||||
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
|
||||
with locks._prove_library_released(library):
|
||||
pass
|
||||
|
||||
|
||||
def test_retained_mapping_can_close_after_exact_release_proof():
|
||||
from test_network_path import FakeWNet
|
||||
from cbb_refresh_verify.network_path import LibraryPathLease
|
||||
backend = FakeWNet()
|
||||
lease = LibraryPathLease.acquire(r'\\server\share\lib.lmc', backend=backend)
|
||||
lease.retain_for_recovery()
|
||||
lease.close()
|
||||
assert backend.cancelled == []
|
||||
assert not lease.release_after_recovery({'status': 'RELEASE_CONFIRMED', 'library': r'\\other\share\lib.lmc'})
|
||||
assert lease.release_after_recovery({'status': 'RELEASE_CONFIRMED', 'library': r'\\server\share\lib.lmc'})
|
||||
lease.close()
|
||||
assert backend.cancelled == [lease.drive]
|
||||
|
||||
|
||||
def test_target_mapping_query_ignores_unrelated_enumeration_failure():
|
||||
from test_network_path import FakeWNet
|
||||
from cbb_refresh_verify.network_path import ensure_mapped_drive_visible
|
||||
class Backend(FakeWNet):
|
||||
def mapping(self, drive):
|
||||
assert drive == 'S:'
|
||||
return r'\\server\share'
|
||||
def mappings(self):
|
||||
raise OSError('unrelated drive enumeration failed')
|
||||
result = ensure_mapped_drive_visible('S:', r'\\server\share', backend=Backend())
|
||||
assert result['created'] is False
|
||||
|
||||
|
||||
def test_windows_mapping_enumeration_reserves_unavailable_drive():
|
||||
from cbb_refresh_verify.network_path import WindowsWNetBackend
|
||||
backend = WindowsWNetBackend.__new__(WindowsWNetBackend)
|
||||
def connection(drive, buffer, size):
|
||||
if drive == 'D:': return 5
|
||||
if drive == 'Y:':
|
||||
buffer.value = r'\\server\share'
|
||||
return 0
|
||||
return 2250
|
||||
backend._mpr = SimpleNamespace(WNetGetConnectionW=connection)
|
||||
backend._kernel32 = SimpleNamespace(GetLogicalDrives=lambda: 0)
|
||||
assert backend.mappings() == {'Y:': r'\\server\share'}
|
||||
assert 'D:' in backend.used_drives()
|
||||
|
||||
|
||||
def test_postnative_idle_failure_preserves_known_release(setup, isolated_mutex):
|
||||
from cbb_refresh_verify.management import run_management
|
||||
from cbb_refresh_verify.library_lock import LibraryLock
|
||||
request, adapter, _ = setup
|
||||
checks = []
|
||||
def idle(*_):
|
||||
checks.append(1)
|
||||
if len(checks) == 3:
|
||||
raise OSError('passive owner query unavailable after native exit')
|
||||
result = run_management(request, adapter=adapter, idle_check=idle)
|
||||
assert result.status == 'RECOVERY_REQUIRED' and result.safe_to_continue
|
||||
with LibraryLock(request.library):
|
||||
pass
|
||||
|
||||
|
||||
def test_final_report_failure_does_not_discard_release_result(setup, monkeypatch, isolated_mutex):
|
||||
import cbb_refresh_verify.management as management
|
||||
request, adapter, _ = setup
|
||||
original = management._write_json
|
||||
def write(path, record):
|
||||
if record.get('stage') == 'complete':
|
||||
raise OSError('evidence volume unavailable')
|
||||
return original(path, record)
|
||||
monkeypatch.setattr(management, '_write_json', write)
|
||||
result = execute(request, adapter)
|
||||
assert result.status == 'REMOVED' and result.safe_to_continue
|
||||
assert 'evidence volume unavailable' in result.detail
|
||||
|
||||
|
||||
def test_legacy_checkpoint_cannot_clear_other_target_owner(tmp_path, monkeypatch, isolated_mutex):
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
|
||||
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
|
||||
marker = locks.blocker_path(library)
|
||||
locks._persist_blocker(library, lease_id='b'*32)
|
||||
original = marker.read_bytes()
|
||||
address = library.parent/'ReusableBlocksLP/Other/Work/database/cdbsvr/sAddress.adr'
|
||||
address.parent.mkdir(parents=True); address.write_bytes(b'keep actual owner address')
|
||||
with pytest.raises(locks.LibraryBusy):
|
||||
locks.release_retained_library(library, tmp_path/'evidence', block_name='Target')
|
||||
assert marker.read_bytes() == original
|
||||
assert address.read_bytes() == b'keep actual owner address'
|
||||
|
||||
|
||||
def test_release_proof_recovers_old_mapping_lease_and_transfers_shared_drive():
|
||||
import cbb_refresh_verify.network_path as network
|
||||
from test_network_path import FakeWNet
|
||||
backend = FakeWNet()
|
||||
old = network.LibraryPathLease.acquire(r'\\server\share\A\lib.lmc', backend=backend)
|
||||
current = network.LibraryPathLease.acquire(r'\\server\share\B\lib.lmc', backend=backend)
|
||||
old.retain_for_recovery(); old.close()
|
||||
proof = {'status': 'RELEASE_CONFIRMED', 'library': r'\\server\share\A\lib.lmc'}
|
||||
assert network.release_retained_path_leases(proof, current_lease=current) == 1
|
||||
assert backend.cancelled == [] and current.created
|
||||
current.close()
|
||||
assert backend.cancelled == [current.drive]
|
||||
|
||||
|
||||
def test_clean_failed_mutation_keeps_recovery_requirement_and_released_owner(setup, isolated_mutex):
|
||||
from dataclasses import replace
|
||||
from cbb_refresh_verify.management import run_management
|
||||
request, adapter, source = setup
|
||||
adapter.fail_add = True
|
||||
failed = execute(replace(request, operation='update', source=source, auto_verify=False), adapter)
|
||||
assert failed.status == 'RECOVERY_REQUIRED' and failed.safe_to_continue
|
||||
adapter.fail_add = False
|
||||
same = execute(replace(request, operation='add', source=source, auto_verify=False), adapter)
|
||||
assert same.status == 'BLOCKED'
|
||||
other = execute(replace(request, operation='add', name='Independent', source=source, auto_verify=False), adapter)
|
||||
assert other.status == 'UPLOADED' and other.safe_to_continue
|
||||
|
||||
|
||||
@pytest.mark.parametrize('history', [None, [], [{'stage': 'native_remove'}, {'stage': 'prepare_identity'}]])
|
||||
def test_prewrite_stage_alone_does_not_override_unknown_or_mutated_history(history):
|
||||
from cbb_refresh_verify.management import _may_have_mutated
|
||||
record = {'stage': 'prepare_identity', 'history': history, 'status': 'RUNNING'}
|
||||
assert _may_have_mutated(record)
|
||||
|
||||
|
||||
def test_library_checkpoint_binds_supervisor_creation_identity(tmp_path):
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
locks._persist_blocker(library, lease_id='c'*32)
|
||||
record = json.loads(locks.blocker_path(library).read_text())
|
||||
assert record.get('supervisor_created')
|
||||
assert locks._recorded_supervisor_alive(record) is True
|
||||
assert locks._recorded_supervisor_alive({**record, 'supervisor_created': 'other process'}) is False
|
||||
legacy = {key: value for key, value in record.items() if key not in ('machine', 'supervisor_created')}
|
||||
assert locks._recorded_supervisor_alive(legacy) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize('proof,safe', [
|
||||
({'safe_to_continue': True, 'process_created': False, 'worker_exited': True, 'remaining_pids': []}, True),
|
||||
({'safe_to_continue': True, 'process_created': True, 'worker_exited': True, 'remaining_pids': []}, False),
|
||||
({'safe_to_continue': True, 'process_created': False, 'worker_exited': False, 'remaining_pids': []}, False),
|
||||
(None, False)])
|
||||
def test_management_worker_launch_exception_uses_explicit_release_protocol(tmp_path, proof, safe):
|
||||
from cbb_refresh_verify.native_management import NativeManagementAdapter
|
||||
error = OSError('private desktop creation failed')
|
||||
error.worker_launch_release = proof
|
||||
def fail(*_): raise error
|
||||
adapter = NativeManagementAdapter(mentor_home=tmp_path, worker_factory=fail)
|
||||
with pytest.raises(OSError) as caught:
|
||||
adapter._launch_worker({'library': str(tmp_path/'lib.lmc'), 'operation': 'catalog',
|
||||
'desktop': 'CbbManagement_test', 'timeout_seconds': 1}, tmp_path)
|
||||
assert getattr(caught.value, 'safe_to_continue', None) is safe
|
||||
|
||||
|
||||
def test_native_add_passive_postcheck_failure_preserves_release(transaction, monkeypatch, isolated_mutex):
|
||||
from test_management_native_transaction import execute as execute_transaction
|
||||
root, request, state = transaction
|
||||
def unavailable(*_): raise OSError('passive target check unavailable')
|
||||
monkeypatch.setattr('cbb_refresh_verify.backup_recovery._idle_check', unavailable)
|
||||
result = execute_transaction(root, request)
|
||||
assert result.status == 'RECOVERY_REQUIRED' and result.safe_to_continue
|
||||
|
||||
|
||||
@pytest.mark.parametrize('case,safe', [('exit_output_error', True), ('popen_missing', True),
|
||||
('popen_denied', True), ('popen_unknown', False), ('timeout', False)])
|
||||
def test_remove_worker_preserves_exit_and_known_creation_rejection(tmp_path, monkeypatch, case, safe):
|
||||
import cbb_refresh_verify.native_management as native
|
||||
job = tmp_path/'request.json'
|
||||
job.write_text(json.dumps({'operation': 'remove', 'desktop': 'CbbManagement_test',
|
||||
'mentor_home': str(tmp_path), 'library': str(tmp_path/'lib.lmc'), 'name': 'Block',
|
||||
'partition': 'Logical-Physical', 'timeout_seconds': 1}), encoding='utf-8')
|
||||
monkeypatch.setattr(native, '_current_desktop', lambda: (None, 'CbbManagement_test'))
|
||||
monkeypatch.setattr(native.NativeManagementAdapter, 'capabilities', lambda _: {
|
||||
'remove': SimpleNamespace(supported=True)})
|
||||
observed = {'waited': False}
|
||||
def wait(timeout):
|
||||
if case == 'timeout':
|
||||
raise native.subprocess.TimeoutExpired('fake CleanWGLib', timeout)
|
||||
observed['waited'] = True
|
||||
return 0
|
||||
def popen(*args, **kwargs):
|
||||
failures = {'popen_missing': FileNotFoundError('native binary disappeared'),
|
||||
'popen_denied': PermissionError('native creation denied'),
|
||||
'popen_unknown': OSError('unconfirmed process creation')}
|
||||
if case in failures:
|
||||
raise failures[case]
|
||||
return SimpleNamespace(pid=123456, wait=wait)
|
||||
monkeypatch.setattr(native.subprocess, 'Popen', popen)
|
||||
original_read = Path.read_bytes
|
||||
def read(path):
|
||||
if path.name == 'native-output.txt' and case == 'exit_output_error':
|
||||
assert observed['waited']
|
||||
raise OSError('native output storage unavailable after exit')
|
||||
return original_read(path)
|
||||
monkeypatch.setattr(Path, 'read_bytes', read)
|
||||
assert native.management_worker_main(job) == 2
|
||||
result = json.loads((tmp_path/'result.json').read_text('utf-8'))
|
||||
assert result['safe_to_continue'] is safe
|
||||
if case == 'exit_output_error':
|
||||
assert result['exit_code'] == 0 and 'storage unavailable' in result['detail']
|
||||
|
||||
|
||||
def test_add_source_missing_central_library_fails_before_capture_without_retaining(setup, monkeypatch, isolated_mutex):
|
||||
from dataclasses import replace
|
||||
import cbb_refresh_verify.native_management as native
|
||||
from cbb_refresh_verify.management import Catalog
|
||||
from cbb_refresh_verify.library_lock import LibraryLock, blocker_path
|
||||
request, _, source = setup
|
||||
adapter = native.NativeManagementAdapter(mentor_home=source.parent)
|
||||
monkeypatch.setattr(adapter, 'capabilities', lambda: {'add': SimpleNamespace(supported=True)})
|
||||
monkeypatch.setattr(adapter, 'catalog', lambda library, evidence: Catalog(library, 1, ()))
|
||||
monkeypatch.setattr('cbb_refresh_verify.native_engineering_identity.capture_identity',
|
||||
lambda *_a, **_kw: pytest.fail('incomplete source reached native capture'))
|
||||
result = execute(replace(request, operation='add', name='New', source=source, auto_verify=False), adapter)
|
||||
assert result.status == 'UPLOAD_FAILED' and result.safe_to_continue
|
||||
assert 'CentralLibrary' in result.detail
|
||||
assert not blocker_path(request.library).exists()
|
||||
with LibraryLock(request.library):
|
||||
pass
|
||||
|
||||
|
||||
def test_prepared_transaction_storage_failure_preserves_capture_release(transaction, monkeypatch, isolated_mutex):
|
||||
from test_management_native_transaction import execute as execute_transaction
|
||||
root, request, _ = transaction
|
||||
def unavailable(*_a, **_kw): raise OSError('prepared transaction storage unavailable')
|
||||
monkeypatch.setattr('cbb_refresh_verify.management_transaction.prepare_transaction', unavailable)
|
||||
result = execute_transaction(root, request)
|
||||
assert result.status == 'UPLOAD_FAILED' and result.safe_to_continue
|
||||
assert 'prepared transaction storage unavailable' in result.detail
|
||||
|
||||
|
||||
@pytest.mark.parametrize('flag,relevant', [('-icdb', False), ('-icdb=', False),
|
||||
('-ICDB', True), ('-icdb=', True)])
|
||||
def test_release_owner_scope_parses_actual_edif_database_argument(tmp_path, flag, relevant):
|
||||
from cbb_refresh_verify.library_lock import _owner_matches_scope
|
||||
library = tmp_path/'Target/lib.lmc'
|
||||
database = library.parent/'Work/database'
|
||||
selected = database if relevant else tmp_path/'Other project/database'
|
||||
argument = flag + ('' if flag.endswith('=') else ' ') + f'"{selected}"'
|
||||
item = {'command': f'edifExporter.exe -schematic {argument} -isnap DxD'}
|
||||
assert _owner_matches_scope(item, library, (database,)) is relevant
|
||||
|
||||
|
||||
def test_release_owner_scope_does_not_match_edif_database_prefix(tmp_path):
|
||||
from cbb_refresh_verify.library_lock import _owner_matches_scope
|
||||
database = tmp_path/'Target/database'
|
||||
item = {'command': f'edifExporter.exe -schematic -icdb "{database}_old" -isnap DxD'}
|
||||
assert _owner_matches_scope(item, tmp_path/'Target/lib.lmc', (database,)) is False
|
||||
|
||||
|
||||
def test_same_target_recovery_gate_preserves_release_and_batch_continues(setup, isolated_mutex):
|
||||
from dataclasses import replace
|
||||
from cbb_refresh_verify.management import run_management_batch
|
||||
request, adapter, source = setup
|
||||
adapter.fail_add = True
|
||||
failed = execute(replace(request, operation='update', source=source, auto_verify=False), adapter)
|
||||
assert failed.status == 'RECOVERY_REQUIRED' and failed.safe_to_continue
|
||||
adapter.fail_add = False
|
||||
results = run_management_batch([
|
||||
replace(request, operation='add', source=source, auto_verify=False),
|
||||
replace(request, operation='add', name='Independent', source=source, auto_verify=False)],
|
||||
adapter=adapter, idle_check=lambda *_: None)
|
||||
assert [result.status for result in results] == ['BLOCKED', 'UPLOADED']
|
||||
assert all(result.safe_to_continue for result in results)
|
||||
@@ -0,0 +1,66 @@
|
||||
"""Real EE7.9.5 PRJ shape: PCB pcb.prj may use LayoutDB without iCDBDir."""
|
||||
import pytest
|
||||
|
||||
from cbb_refresh_verify.management import source_project, engineering_identity
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def healthy_source(tmp_path):
|
||||
(tmp_path/'database').mkdir()
|
||||
(tmp_path/'database/icdb.dat').write_bytes(b'schematic database')
|
||||
(tmp_path/'PCB/Layout').mkdir(parents=True)
|
||||
(tmp_path/'PCB/Layout/LayoutDB.lyt').write_bytes(b'layout database')
|
||||
source = tmp_path/'IP101GR.prj'
|
||||
source.write_text('KEY RootBlock "IP101GR"\nKEY FlowType "DX"\n'
|
||||
'KEY iCDBDir ".\\database"\nKEY PCBDesignPath "PCB\\IP101GR.pcb"\n', encoding='utf-8')
|
||||
(tmp_path/'PCB/IP101GR.pcb').write_text('KEY ProjectFile "..\\IP101GR.prj"\n', encoding='utf-8')
|
||||
(tmp_path/'PCB/pcb.prj').write_text('SECTION Project\nKEY CentralLibrary "old.lmc"\nENDSECTION\n', encoding='utf-8')
|
||||
return source
|
||||
|
||||
|
||||
def test_layout_based_pcb_without_independent_icdb_directory_is_complete(healthy_source):
|
||||
source, pcb, top = source_project(healthy_source)
|
||||
assert source == healthy_source
|
||||
assert pcb == healthy_source.parent/'PCB/IP101GR.pcb'
|
||||
assert top == 'IP101GR'
|
||||
assert engineering_identity(source)['top_level_block'] == 'IP101GR'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('missing', ['database/icdb.dat', 'PCB/Layout/LayoutDB.lyt'])
|
||||
def test_optional_pcb_icdb_does_not_relax_required_engineering_files(healthy_source, missing):
|
||||
(healthy_source.parent/missing).unlink()
|
||||
with pytest.raises(ValueError):
|
||||
source_project(healthy_source)
|
||||
|
||||
|
||||
def test_linked_legacy_pcb_uses_explicit_main_project_without_guessing_template(healthy_source):
|
||||
(healthy_source.parent/'PCB/pcb.prj').rename(healthy_source.parent/'PCB/template.prj')
|
||||
assert source_project(healthy_source)[0] == healthy_source
|
||||
(healthy_source.parent/'PCB/IP101GR.pcb').write_text('KEY ProjectFile "../wrong.prj"\n')
|
||||
with pytest.raises(ValueError, match='PCB'):
|
||||
source_project(healthy_source)
|
||||
|
||||
|
||||
def test_main_schematic_icdb_declaration_remains_required(healthy_source):
|
||||
text = healthy_source.read_text(encoding='utf-8').replace('KEY iCDBDir ".\\database"\n', '')
|
||||
healthy_source.write_text(text, encoding='utf-8')
|
||||
with pytest.raises(ValueError, match='iCDBDir'):
|
||||
source_project(healthy_source)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('declared', [
|
||||
'KEY iCDBDir "missing"\n',
|
||||
'KEY iCDBDir "..\\..\\outside"\n',
|
||||
'KEY iCDBDir "C:\\external"\n',
|
||||
'KEY iCDBDir ""\n',
|
||||
'KEY iCDBDir "..\\database"\nKEY iCDBDir "..\\database"\n',
|
||||
])
|
||||
def test_explicit_pcb_icdb_reference_must_be_unique_contained_and_exist(healthy_source, declared):
|
||||
(healthy_source.parent/'PCB/pcb.prj').write_text(declared, encoding='utf-8')
|
||||
with pytest.raises(ValueError):
|
||||
source_project(healthy_source)
|
||||
|
||||
|
||||
def test_valid_explicit_pcb_icdb_directory_remains_supported(healthy_source):
|
||||
(healthy_source.parent/'PCB/pcb.prj').write_text('KEY iCDBDir "..\\database"\n', encoding='utf-8')
|
||||
assert source_project(healthy_source)[0] == healthy_source
|
||||
@@ -0,0 +1,195 @@
|
||||
"""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.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
|
||||
|
||||
|
||||
def test_cancellation_during_log_evidence_prevents_native_submit(tmp_path, monkeypatch):
|
||||
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,99))
|
||||
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')
|
||||
monkeypatch.setattr(native,'_set_probe_field',lambda *a:None)
|
||||
def post(h,*args):
|
||||
state['posted'].append(h)
|
||||
if h==110:state['new']=True
|
||||
monkeypatch.setattr(win32gui,'PostMessage',post)
|
||||
original=native._write_json
|
||||
def write(path,data):
|
||||
original(path,data)
|
||||
if path.name=='native-add-log-baseline.json':(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()}
|
||||
with pytest.raises(RuntimeError,match='NATIVE_ADD_CANCELLED'):
|
||||
native._probe_add_dialog_impl(SimpleNamespace(OnReusableBlocksEditor=lambda:None),job,desktop,{99},root)
|
||||
assert state['posted']==[110]
|
||||
|
||||
|
||||
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'
|
||||
@@ -0,0 +1,465 @@
|
||||
"""Native export and asset identity boundaries; never launch native tools."""
|
||||
from pathlib import Path
|
||||
import pytest
|
||||
|
||||
|
||||
def ascii_report(date=b'Tue Nov 03 11:19:39 2026', directory=b'C:\\copy\\database'):
|
||||
return (b'iCDB Ascii Report Generation Date: '+date+b'\r\n\r\n\r\n\tReport Criteria:\r\n'
|
||||
b'\t iCDB directory: '+directory+b'\r\n\t DATE: '+date+b'\r\n\r\n'
|
||||
b'\t REPORT FORMAT: FREEFORM\r\n\t MODE: HIER AND FLAT BLOCKS\r\n'
|
||||
b'\t CONNECTION LISTS: ON\r\n\t TEXT LISTS: ON\r\n\r\n'
|
||||
b'Block Top \tRoot\r\n\tPort A\r\nConfig default\tview none\r\n\tPin A\r\n')
|
||||
|
||||
|
||||
def test_ascii_only_normalizes_three_validated_header_values():
|
||||
from cbb_refresh_verify.native_engineering_identity import normalize_ascii
|
||||
first = ascii_report()
|
||||
changed = ascii_report(b'Wed Nov 04 12:00:00 2026', b'D:\\other\\database')
|
||||
assert normalize_ascii(first, 'Top') == normalize_ascii(changed, 'Top')
|
||||
assert normalize_ascii(first, 'Top') != normalize_ascii(first.replace(b'Port A', b'Port B'), 'Top')
|
||||
body = b'\tiCDB Ascii Report Generation Date: design property\r\n'
|
||||
assert normalize_ascii(first+body, 'Top') != normalize_ascii(first+body.replace(b'property', b'value'), 'Top')
|
||||
|
||||
|
||||
@pytest.mark.parametrize('change', ['empty', 'wrong_root', 'missing_config', 'header_duplicate', 'wrong_mode'])
|
||||
def test_ascii_rejects_missing_or_unrecognized_structure(change):
|
||||
from cbb_refresh_verify.native_engineering_identity import normalize_ascii
|
||||
data = ascii_report()
|
||||
data = {'empty': b'', 'wrong_root': data.replace(b'Block Top ', b'Block Other '),
|
||||
'missing_config': data.replace(b'Config default', b'Partial default'),
|
||||
'header_duplicate': data.replace(b'\tReport Criteria:', b'\t DATE: extra'),
|
||||
'wrong_mode': data.replace(b'HIER AND FLAT BLOCKS', b'FLAT ONLY')}[change]
|
||||
with pytest.raises(ValueError): normalize_ascii(data, 'Top')
|
||||
|
||||
|
||||
def test_inf_only_normalizes_unique_timestamp_column():
|
||||
from cbb_refresh_verify.native_engineering_identity import normalize_inf, INF_HEADER
|
||||
row = [b'identity', b'Design Capture', b'VB99.0', b'11/03/26 11:21:34']+[b'value']*12
|
||||
first = INF_HEADER+b'\r\n'+b'\t'.join(row)+b'\r\n'
|
||||
assert normalize_inf(first) == normalize_inf(first.replace(b'11:21:34', b'11:21:37'))
|
||||
assert normalize_inf(first) != normalize_inf(first.replace(b'value', b'changed', 1))
|
||||
with pytest.raises(ValueError): normalize_inf(first.replace(b'System_Date', b'Unknown'))
|
||||
with pytest.raises(ValueError): normalize_inf(first+b'extra row\r\n')
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def project(tmp_path):
|
||||
from test_management import project
|
||||
source = project(tmp_path/'project', name='Source')
|
||||
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.write_bytes(b'library')
|
||||
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')
|
||||
return source, library
|
||||
|
||||
|
||||
def test_assets_require_correct_library_references_and_unknown_bytes(project):
|
||||
from cbb_refresh_verify.native_engineering_identity import asset_identity
|
||||
source, library = project
|
||||
before = asset_identity(source, library)
|
||||
runtime = source.parent/'database/cdbsvr/events/events.dat'
|
||||
runtime.parent.mkdir(parents=True); runtime.write_bytes(b'runtime')
|
||||
(source.parent/'database/icdb.dat').write_bytes(b'native normalized database')
|
||||
assert asset_identity(source, library) == before
|
||||
unknown = source.parent/'unknown-engineering.bin'; unknown.write_bytes(b'engineering')
|
||||
assert asset_identity(source, library) != before
|
||||
unknown.unlink()
|
||||
(source.parent/'PCB/Layout/LayoutDB.lyt').write_bytes(b'changed physical design')
|
||||
assert asset_identity(source, library) != before
|
||||
text = (source.parent/'PCB/pcb.prj').read_text()
|
||||
(source.parent/'PCB/pcb.prj').write_text(text.replace(str(library), 'missing.lmc'))
|
||||
with pytest.raises(ValueError, match='CentralLibrary'):
|
||||
asset_identity(source, library)
|
||||
|
||||
|
||||
def test_linked_legacy_identity_preserves_template_bytes_and_aligns_only_active_project(project, tmp_path):
|
||||
from cbb_refresh_verify.native_engineering_identity import asset_identity, project_library
|
||||
from cbb_refresh_verify.backup_recovery import _align_library
|
||||
source, library = project
|
||||
template = source.parent/'PCB/template.prj'
|
||||
(source.parent/'PCB/pcb.prj').rename(template)
|
||||
original = template.read_bytes()
|
||||
before = asset_identity(source, library)
|
||||
assert 'PCB/template.prj' in before['assets']
|
||||
other = tmp_path/'other.lmc'; other.write_bytes(b'other library')
|
||||
_align_library(source, next((source.parent/'PCB').glob('*.pcb')), other)
|
||||
assert template.read_bytes() == original
|
||||
assert project_library(source) == other
|
||||
assert asset_identity(source, other) == before
|
||||
template.write_bytes(original+b'unknown engineering change')
|
||||
assert asset_identity(source, other) != before
|
||||
|
||||
|
||||
@pytest.mark.parametrize('relative', ['database/cdbsvr/persistent.dat',
|
||||
'database/cdbsvr/new-engineering/config.bin', 'database/cdbsvr/events/custom.dat',
|
||||
'database/cdbsvr/plog/unknown-engineering.bin'])
|
||||
def test_unknown_cdbsvr_assets_remain_part_of_identity(project, relative):
|
||||
from cbb_refresh_verify.native_engineering_identity import asset_identity
|
||||
source, library = project
|
||||
baseline = asset_identity(source, library)
|
||||
unknown = source.parent/relative; unknown.parent.mkdir(parents=True, exist_ok=True)
|
||||
unknown.write_bytes(b'first engineering content')
|
||||
added = asset_identity(source, library)
|
||||
assert added != baseline
|
||||
unknown.write_bytes(b'changed engineering content')
|
||||
assert asset_identity(source, library) != added
|
||||
unknown.unlink()
|
||||
assert asset_identity(source, library) == baseline
|
||||
|
||||
|
||||
def test_observed_guid_and_events_runtime_does_not_change_identity(project):
|
||||
from cbb_refresh_verify.native_engineering_identity import asset_identity
|
||||
source, library = project
|
||||
baseline = asset_identity(source, library)
|
||||
for relative in ['database/cdbsvr/plog/2026.11.03.guid.48432.txt',
|
||||
'database/cdbsvr/events/events.dat', 'database/cdbsvr/events/events.idx']:
|
||||
path = source.parent/relative; path.parent.mkdir(parents=True, exist_ok=True); path.write_bytes(b'runtime')
|
||||
assert asset_identity(source, library) == baseline
|
||||
|
||||
|
||||
@pytest.mark.parametrize('failure', ['empty', 'missing_completion', 'error', 'exit'])
|
||||
def test_export_evidence_requires_successful_complete_native_output(tmp_path, failure):
|
||||
from cbb_refresh_verify.native_engineering_identity import validate_export_output
|
||||
report = tmp_path/'design.rpt'; report.write_bytes(b'report')
|
||||
log = tmp_path/'native.log'
|
||||
log.write_text(f'Report generation complete, report file is {report}\n')
|
||||
code = 0
|
||||
if failure == 'empty': report.write_bytes(b'')
|
||||
if failure == 'missing_completion': log.write_text('partial report\n')
|
||||
if failure == 'error':
|
||||
with log.open('a') as stream: stream.write('ERROR: database corrupt\n')
|
||||
if failure == 'exit': code = 2
|
||||
with pytest.raises(ValueError): validate_export_output('ascii', code, report, log)
|
||||
|
||||
|
||||
def test_capture_only_exports_fresh_copy_and_leaves_source_unchanged(project, tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.native_engineering_identity as identity
|
||||
from cbb_refresh_verify.library_lock import LibraryLock
|
||||
from cbb_refresh_verify.scoped_manifest import build_manifest
|
||||
source, library = project
|
||||
original = build_manifest(source.parent)
|
||||
monkeypatch.setattr(identity, 'check_exporters', lambda _: None)
|
||||
monkeypatch.setattr(identity, '_process_snapshot', lambda: [])
|
||||
def exports(clone, root, *_):
|
||||
assert clone.parent == root/'project' and clone != source
|
||||
(clone.parent/'database/icdb.dat').write_bytes(b'export changed disposable copy')
|
||||
(root/'design.rpt').write_bytes(ascii_report())
|
||||
(root/'design.edf').write_bytes(edif_report())
|
||||
(root/'export-launch.json').write_text('{"started": false}')
|
||||
return {'success': True, 'safe_to_continue': True, 'detail': ''}
|
||||
monkeypatch.setattr(identity, '_run_exports', exports)
|
||||
monkeypatch.setattr(identity, 'csv_identity', lambda _: {'work/identity': 'csv proof'})
|
||||
with LibraryLock(library):
|
||||
result = identity.capture_identity(source, tmp_path/'analysis', expected_library=library,
|
||||
owner_library=library, mentor_home=tmp_path)
|
||||
assert result.identity['policy'] == identity.POLICY and result.safe_to_continue
|
||||
assert build_manifest(source.parent) == original
|
||||
|
||||
|
||||
def test_capture_unreleased_exporter_retains_caller_lease(project, tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.native_engineering_identity as identity
|
||||
from cbb_refresh_verify.library_lock import LibraryLock, LibraryBusy, blocker_path, _owners, _guard
|
||||
source, library = project
|
||||
monkeypatch.setattr(identity, 'check_exporters', lambda _: None)
|
||||
monkeypatch.setattr(identity, '_run_exports', lambda *a: {
|
||||
'success': False, 'safe_to_continue': False, 'detail': 'TIMEOUT: native exporter retained'})
|
||||
lease = LibraryLock(library)
|
||||
try:
|
||||
with lease:
|
||||
result = identity.capture_identity(source, tmp_path/'analysis', expected_library=library,
|
||||
owner_library=library, mentor_home=tmp_path)
|
||||
assert result.identity is None and not result.safe_to_continue
|
||||
with pytest.raises(LibraryBusy):
|
||||
with LibraryLock(library): pass
|
||||
finally:
|
||||
with _guard:
|
||||
owner = _owners.pop(lease.key, None)
|
||||
if owner: owner['handle'].Close()
|
||||
blocker_path(library).unlink(missing_ok=True)
|
||||
|
||||
|
||||
def test_export_timeout_retains_process_without_kill(project, tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.native_engineering_identity as identity
|
||||
source, _ = project
|
||||
root = tmp_path/'exports'; root.mkdir()
|
||||
seen = []
|
||||
class Running:
|
||||
pid = 987654
|
||||
def __init__(self, command, **kwargs): seen.append(command)
|
||||
def poll(self): return None
|
||||
def kill(self): pytest.fail('native owner cannot be killed')
|
||||
def terminate(self): pytest.fail('native owner cannot be terminated')
|
||||
monkeypatch.setattr(identity, '_retained_exports', [])
|
||||
monkeypatch.setattr(identity.subprocess, 'Popen', Running)
|
||||
monkeypatch.setattr(identity, '_process_snapshot', lambda: [])
|
||||
monkeypatch.setattr(identity, '_database_released', lambda _: True)
|
||||
result = identity._run_exports(source, root, tmp_path, 0)
|
||||
assert not result['safe_to_continue'] and 'TIMEOUT' in result['detail']
|
||||
assert len(identity._retained_exports) == 1
|
||||
assert seen[0][-5:] == ['-f', '-h', '-c', '-t', '-nostrip']
|
||||
assert (root/'ascii-process.json').is_file()
|
||||
|
||||
|
||||
def test_export_does_not_adopt_unrelated_existing_native_owner(project, tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.native_engineering_identity as identity
|
||||
source, _ = project
|
||||
root = tmp_path/'exports'; root.mkdir()
|
||||
unrelated = {'pid': 888888, 'parent': 0, 'name': 'iCDBNetServer.exe',
|
||||
'executable': 'native', 'command': 'iCDBNetServer.exe C:\\other\\database'}
|
||||
monkeypatch.setattr(identity, '_process_snapshot', lambda: [unrelated])
|
||||
monkeypatch.setattr(identity, '_database_released', lambda _: True)
|
||||
monkeypatch.setattr(identity, 'validate_export_output', lambda *_: None)
|
||||
started = []
|
||||
class Finished:
|
||||
pid = 987654
|
||||
returncode = 0
|
||||
def __init__(self, command, **kwargs): started.append(command)
|
||||
def poll(self): return 0
|
||||
monkeypatch.setattr(identity.subprocess, 'Popen', Finished)
|
||||
result = identity._run_exports(source, root, tmp_path, 1)
|
||||
assert result['success'] and result['safe_to_continue']
|
||||
assert len(started) == 3
|
||||
|
||||
|
||||
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
|
||||
root = tmp_path/'exports'; root.mkdir()
|
||||
monkeypatch.setattr(identity, '_process_snapshot', lambda: [])
|
||||
monkeypatch.setattr(identity, '_database_released', lambda _: True)
|
||||
def fail(*a, **k): raise FileNotFoundError('missing exporter')
|
||||
monkeypatch.setattr(identity.subprocess, 'Popen', fail)
|
||||
result = identity._run_exports(source, root, tmp_path, 1)
|
||||
assert not result['success'] and result['safe_to_continue']
|
||||
assert 'missing exporter' in result['detail']
|
||||
|
||||
|
||||
def test_unconfirmed_export_constructor_failure_retains_ownership(project, tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.native_engineering_identity as identity
|
||||
source, _ = project
|
||||
root = tmp_path/'exports'; root.mkdir()
|
||||
monkeypatch.setattr(identity, '_process_snapshot', lambda: [])
|
||||
monkeypatch.setattr(identity, '_database_released', lambda _: True)
|
||||
def fail(*a, **k): raise RuntimeError('uncertain partially-created process')
|
||||
monkeypatch.setattr(identity.subprocess, 'Popen', fail)
|
||||
result = identity._run_exports(source, root, tmp_path, 1)
|
||||
assert not result['success'] and not result['safe_to_continue']
|
||||
|
||||
|
||||
@pytest.mark.parametrize('summary', ['native-outcome.json', 'identity.json'])
|
||||
def test_export_summary_write_failure_preserves_confirmed_release(project, tmp_path, monkeypatch, summary):
|
||||
import cbb_refresh_verify.native_engineering_identity as identity
|
||||
from cbb_refresh_verify.library_lock import LibraryLock, blocker_path
|
||||
import win32event
|
||||
from uuid import uuid4
|
||||
create_mutex = win32event.CreateMutex
|
||||
monkeypatch.setattr(win32event, 'CreateMutex', lambda security, owned, name:
|
||||
create_mutex(security, owned, name+'-test-'+uuid4().hex))
|
||||
source, library = project
|
||||
monkeypatch.setattr(identity, 'check_exporters', lambda _: None)
|
||||
monkeypatch.setattr(identity, '_process_snapshot', lambda: [])
|
||||
def exports(clone, root, *_):
|
||||
(root/'export-launch.json').write_text('{"started": false}')
|
||||
return {'success': False, 'safe_to_continue': True, 'detail': 'export rejected before start'}
|
||||
monkeypatch.setattr(identity, '_run_exports', exports)
|
||||
original_write = identity._write_json
|
||||
def write(path, record):
|
||||
if path.name == summary: raise OSError('summary unavailable')
|
||||
return original_write(path, record)
|
||||
monkeypatch.setattr(identity, '_write_json', write)
|
||||
with LibraryLock(library):
|
||||
result = identity.capture_identity(source, tmp_path/'analysis', expected_library=library,
|
||||
owner_library=library, mentor_home=tmp_path)
|
||||
assert result.identity is None and result.safe_to_continue
|
||||
assert 'summary unavailable' in result.detail
|
||||
assert not blocker_path(library).exists()
|
||||
|
||||
|
||||
def test_export_snapshot_uses_bounded_read_only_helper(monkeypatch):
|
||||
from cbb_refresh_verify import native_engineering_identity as identity, owner_probe
|
||||
rows = [{'pid': 42, 'parent': 10, 'name': 'unknown-child.exe'}]
|
||||
calls = []
|
||||
def query(**kwargs):
|
||||
calls.append(kwargs)
|
||||
return rows
|
||||
monkeypatch.setattr(owner_probe, 'query_process_snapshot', query)
|
||||
assert identity._process_snapshot() == rows
|
||||
assert calls == [{'timeout_seconds': 10}]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('after_launch', [False, True])
|
||||
def test_export_snapshot_timeout_preserves_launch_extent(project, tmp_path, monkeypatch, after_launch):
|
||||
from cbb_refresh_verify import native_engineering_identity as identity
|
||||
source, _ = project
|
||||
root = tmp_path/'exports'; root.mkdir()
|
||||
calls = []
|
||||
def snapshot():
|
||||
calls.append('snapshot')
|
||||
if after_launch and len(calls) == 1: return []
|
||||
raise RuntimeError('OWNER_QUERY_TIMEOUT: WMI timed out')
|
||||
monkeypatch.setattr(identity, '_process_snapshot', snapshot)
|
||||
monkeypatch.setattr(identity, '_database_released', lambda _: True)
|
||||
monkeypatch.setattr(identity, '_retained_exports', [])
|
||||
launched = []
|
||||
class Running:
|
||||
pid = 987654
|
||||
def __init__(self, *a, **k): launched.append(self)
|
||||
def poll(self): return None
|
||||
monkeypatch.setattr(identity.subprocess, 'Popen', Running)
|
||||
result = identity._run_exports(source, root, tmp_path, 1)
|
||||
assert not result['success']
|
||||
assert result['safe_to_continue'] is (not after_launch)
|
||||
assert result['native_started'] is after_launch
|
||||
assert 'OWNER_QUERY_TIMEOUT' in result['detail']
|
||||
assert bool(launched) is after_launch
|
||||
assert bool(identity._retained_exports) is after_launch
|
||||
|
||||
|
||||
def test_prelaunch_snapshot_timeout_releases_only_own_unstarted_guard(project, tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify import native_engineering_identity as identity
|
||||
from cbb_refresh_verify.library_lock import LibraryLock, blocker_path
|
||||
import win32event
|
||||
from uuid import uuid4
|
||||
source, library = project
|
||||
create_mutex = win32event.CreateMutex
|
||||
monkeypatch.setattr(win32event, 'CreateMutex', lambda security, owned, name:
|
||||
create_mutex(security, owned, name+'-test-'+uuid4().hex))
|
||||
monkeypatch.setattr(identity, 'check_exporters', lambda _: None)
|
||||
calls = []
|
||||
def snapshot():
|
||||
calls.append('query')
|
||||
raise RuntimeError('OWNER_QUERY_TIMEOUT: process tree unavailable')
|
||||
monkeypatch.setattr(identity, '_process_snapshot', snapshot)
|
||||
with LibraryLock(library):
|
||||
result = identity.capture_identity(source, tmp_path/'analysis', expected_library=library,
|
||||
owner_library=library, mentor_home=tmp_path)
|
||||
assert result.identity is None and result.safe_to_continue
|
||||
assert 'OWNER_QUERY_TIMEOUT' in result.detail
|
||||
assert calls == ['query']
|
||||
assert not blocker_path(library).exists()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('failure', ['source', 'lease', 'scope', 'exporters', 'directory', 'mutex'])
|
||||
def test_capture_prevalidation_failure_explicitly_reports_no_native_session(project, tmp_path, monkeypatch, failure):
|
||||
from cbb_refresh_verify import native_engineering_identity as identity, library_lock
|
||||
import win32event
|
||||
source, library = project
|
||||
root = tmp_path/'analysis'
|
||||
def reject(*args, **kwargs): raise OSError(f'prevalidation {failure} unavailable')
|
||||
monkeypatch.setattr(library_lock, 'owned_snapshot', lambda _: b'owned lease')
|
||||
monkeypatch.setattr(identity, 'check_exporters', lambda _: None)
|
||||
monkeypatch.setattr(identity, '_run_exports', lambda *a, **k: pytest.fail('native export must not start'))
|
||||
if failure == 'source': monkeypatch.setattr(identity, 'source_project', reject)
|
||||
if failure == 'lease': monkeypatch.setattr(library_lock, 'owned_snapshot', lambda _: None)
|
||||
if failure == 'scope': root = source.parent/'analysis'
|
||||
if failure == 'exporters': monkeypatch.setattr(identity, 'check_exporters', reject)
|
||||
if failure == 'directory':
|
||||
mkdir = Path.mkdir
|
||||
def create(path, *args, **kwargs):
|
||||
if path == root: return reject()
|
||||
return mkdir(path, *args, **kwargs)
|
||||
monkeypatch.setattr(Path, 'mkdir', create)
|
||||
if failure == 'mutex': monkeypatch.setattr(win32event, 'CreateMutex', reject)
|
||||
result = identity.capture_identity(source, root, expected_library=library,
|
||||
owner_library=library, mentor_home=tmp_path)
|
||||
assert result.identity is None and result.safe_to_continue
|
||||
assert result.detail
|
||||
|
||||
|
||||
@pytest.mark.parametrize('failure', ['initial_launch_record', 'final_process_record'])
|
||||
def test_export_record_io_preserves_known_launch_extent(project, tmp_path, monkeypatch, failure):
|
||||
from cbb_refresh_verify import native_engineering_identity as identity, library_lock
|
||||
import win32event
|
||||
from uuid import uuid4
|
||||
source, library = project
|
||||
create_mutex = win32event.CreateMutex
|
||||
monkeypatch.setattr(win32event, 'CreateMutex', lambda security, owned, name:
|
||||
create_mutex(security, owned, name+'-test-'+uuid4().hex))
|
||||
monkeypatch.setattr(identity, 'check_exporters', lambda _: None)
|
||||
monkeypatch.setattr(identity, '_process_snapshot', lambda: [])
|
||||
monkeypatch.setattr(identity, '_database_released', lambda _: True)
|
||||
monkeypatch.setattr(library_lock, '_supervisor_alive', lambda _: False)
|
||||
launched = []
|
||||
class Finished:
|
||||
pid = 987654
|
||||
returncode = 0
|
||||
def __init__(self, *args, **kwargs): launched.append(self)
|
||||
def poll(self): return 0
|
||||
monkeypatch.setattr(identity.subprocess, 'Popen', Finished)
|
||||
def content_failure(*args): raise ValueError('native export content rejected')
|
||||
monkeypatch.setattr(identity, 'validate_export_output', content_failure)
|
||||
write = identity._write_json
|
||||
process_writes = []
|
||||
def fail(path, record):
|
||||
if path.name == 'export-launch.json' and failure == 'initial_launch_record':
|
||||
raise OSError('launch metadata unavailable')
|
||||
if path.name == 'ascii-process.json':
|
||||
process_writes.append(record.copy())
|
||||
if failure == 'final_process_record' and len(process_writes) == 2:
|
||||
raise OSError('final process metadata unavailable')
|
||||
return write(path, record)
|
||||
monkeypatch.setattr(identity, '_write_json', fail)
|
||||
with library_lock.LibraryLock(library):
|
||||
result = identity.capture_identity(source, tmp_path/'analysis', expected_library=library,
|
||||
owner_library=library, mentor_home=tmp_path)
|
||||
assert result.identity is None and result.safe_to_continue
|
||||
assert 'metadata unavailable' in result.detail
|
||||
assert bool(launched) is (failure == 'final_process_record')
|
||||
assert not library_lock.blocker_path(library).exists()
|
||||
with library_lock.LibraryLock(library): pass
|
||||
|
||||
|
||||
def test_successful_export_keeps_release_when_final_diagnostic_write_fails(project, tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify import native_engineering_identity as identity
|
||||
source, _ = project
|
||||
root = tmp_path/'exports'; root.mkdir()
|
||||
monkeypatch.setattr(identity, '_process_snapshot', lambda: [])
|
||||
monkeypatch.setattr(identity, '_database_released', lambda _: True)
|
||||
monkeypatch.setattr(identity, 'validate_export_output', lambda *_: None)
|
||||
class Finished:
|
||||
pid = 987654
|
||||
returncode = 0
|
||||
def __init__(self, *args, **kwargs): pass
|
||||
def poll(self): return 0
|
||||
monkeypatch.setattr(identity.subprocess, 'Popen', Finished)
|
||||
write = identity._write_json
|
||||
counts = {}
|
||||
def fail(path, record):
|
||||
if path.name.endswith('-process.json'):
|
||||
counts[path] = counts.get(path, 0)+1
|
||||
if counts[path] == 2: raise OSError('final metadata unavailable')
|
||||
return write(path, record)
|
||||
monkeypatch.setattr(identity, '_write_json', fail)
|
||||
result = identity._run_exports(source, root, tmp_path, 1)
|
||||
assert result['success'] and result['safe_to_continue']
|
||||
assert 'final metadata unavailable' in result['detail']
|
||||
|
||||
|
||||
def edif_report(timestamp=b'2026 11 3 11 40 56'):
|
||||
return (b'(edif DxD (edifVersion 2 0 0) (status (written (timestamp '+timestamp+b')'
|
||||
b' (program "DxDesigner Edif Exporter"))) (library Board1 (cell Top'
|
||||
b' (view SCHEMATIC_VIEW (viewType SCHEMATIC) (page sheet1 (figure LINE (pt 1 2)))'
|
||||
b' (property timestamp (string "2026 11 3 11 40 56")))))'
|
||||
b' (design Board1 (cellRef Top (libraryRef Board1))))')
|
||||
|
||||
|
||||
def test_edif_only_normalizes_root_written_timestamp_preserving_geometry_and_properties():
|
||||
from cbb_refresh_verify.native_engineering_identity import normalize_edif
|
||||
first = edif_report()
|
||||
assert normalize_edif(first, 'Top') == normalize_edif(edif_report(b'2026 11 3 11 40 59'), 'Top')
|
||||
assert normalize_edif(first, 'Top') != normalize_edif(first.replace(b'(pt 1 2)', b'(pt 1 3)'), 'Top')
|
||||
assert normalize_edif(first, 'Top') != normalize_edif(first.replace(b'"2026 11 3 11 40 56"', b'"changed"'), 'Top')
|
||||
for bad in [first[:-1], first.replace(b'(edifVersion 2 0 0)', b'(edifVersion 1 0 0)'),
|
||||
first.replace(b'(cellRef Top', b'(cellRef Other'), first.replace(b'(pt 1 2)', b'')]:
|
||||
with pytest.raises(ValueError): normalize_edif(bad, 'Top')
|
||||
|
||||
|
||||
def test_edif_binds_native_escaped_digit_initial_root_without_changing_design_bytes():
|
||||
from cbb_refresh_verify.native_engineering_identity import normalize_edif
|
||||
report = edif_report().replace(b'cell Top', b'cell &1GPHY_8212').replace(b'cellRef Top', b'cellRef &1GPHY_8212')
|
||||
normalized = normalize_edif(report, '1GPHY_8212')
|
||||
assert b'(cell &1GPHY_8212' in normalized and b'(cellRef &1GPHY_8212' in normalized
|
||||
for wrong in ('1GPHY_8211', '&1GPHY_8212'):
|
||||
with pytest.raises(ValueError): normalize_edif(report, wrong)
|
||||
with pytest.raises(ValueError):
|
||||
normalize_edif(report.replace(b'&1GPHY_8212', b'1GPHY_8212'), '1GPHY_8212')
|
||||
@@ -0,0 +1,198 @@
|
||||
"""Fresh release/adoption proof for retained export copies; no native launch."""
|
||||
from contextlib import contextmanager
|
||||
import json
|
||||
import os
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def export_case(tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
import cbb_refresh_verify.native_engineering_identity as identity
|
||||
import win32com.client
|
||||
monkeypatch.setattr(win32com.client, 'GetObject', lambda *_: SimpleNamespace(ExecQuery=lambda *_: []))
|
||||
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_a, **_k: [])
|
||||
monkeypatch.setattr(identity, '_process_snapshot', lambda: [])
|
||||
monkeypatch.setattr(identity, '_retained_exports', [])
|
||||
monkeypatch.setattr(locks, '_supervisor_alive', lambda _: False)
|
||||
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.write_bytes(b'original library')
|
||||
root = tmp_path/'analysis'; (root/'project/database').mkdir(parents=True)
|
||||
source = root/'project/Source.prj'; source.write_bytes(b'copied project')
|
||||
(root/'project/database/icdb.dat').write_bytes(b'copied database')
|
||||
lease = locks.LibraryLock(library, safe_to_release=lambda: False)
|
||||
with lease:
|
||||
from cbb_refresh_verify.native_export_guard import begin_export_analysis
|
||||
token = begin_export_analysis(library, root, source)
|
||||
(root/'ascii-process.json').write_text(json.dumps({'pid': 123456, 'observed_pids': [123456],
|
||||
'command': ['icdb2ascii.exe'], 'safe_to_continue': False}))
|
||||
yield library, root, token, lease
|
||||
with locks._guard:
|
||||
owner = locks._owners.pop(lease.key, None)
|
||||
if owner: owner['handle'].Close()
|
||||
locks.blocker_path(library).unlink(missing_ok=True)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('action', ['release', 'maintenance'])
|
||||
@pytest.mark.parametrize('obstacle', ['active_exporter', 'active_child', 'copy_address', 'copy_exclusive', 'invalid_record', 'missing_copy'])
|
||||
def test_release_and_takeover_cannot_bypass_export_copy(export_case, monkeypatch, tmp_path, action, obstacle):
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
import cbb_refresh_verify.native_engineering_identity as identity
|
||||
import win32api, win32con, win32file
|
||||
library, root, token, lease = export_case
|
||||
handle = None
|
||||
if obstacle == 'active_exporter':
|
||||
# Restart case: no in-memory exporter, but a known native owner remains.
|
||||
monkeypatch.setattr(identity, '_process_snapshot', lambda: [
|
||||
{'pid': 123456, 'name': 'iCDBNetServer.exe', 'parent': 0, 'executable': 'native'}])
|
||||
if obstacle == 'active_child':
|
||||
handle = win32api.OpenProcess(win32con.SYNCHRONIZE, False, os.getpid())
|
||||
monkeypatch.setattr(identity, '_retained_exports', [(SimpleNamespace(poll=lambda: 0), {os.getpid(): handle})])
|
||||
if obstacle == 'copy_address':
|
||||
address = root/'project/database/cdbsvr/sAddress.adr'; address.parent.mkdir(); address.write_bytes(b'copy owner')
|
||||
if obstacle == 'copy_exclusive':
|
||||
handle = win32file.CreateFile(str(root/'project/database/icdb.dat'), win32con.GENERIC_READ,
|
||||
0, None, win32con.OPEN_EXISTING, 0, None)
|
||||
if obstacle == 'invalid_record': (root/'export-owner.json').write_text('{invalid')
|
||||
if obstacle == 'missing_copy': (root/'project/database/icdb.dat').unlink()
|
||||
@contextmanager
|
||||
def target_guard(): yield {'target': 'file-only maintenance proof'}
|
||||
try:
|
||||
marker = locks.blocker_path(library); before = marker.read_bytes()
|
||||
with pytest.raises((ValueError, OSError)):
|
||||
if action == 'release': locks.release_retained_library(library, tmp_path/'release')
|
||||
else:
|
||||
with locks.LibraryLock.for_maintenance(library, tmp_path/'takeover', target_guard,
|
||||
safe_to_release=lambda: True): pass
|
||||
assert marker.read_bytes() == before
|
||||
assert lease.path.exists()
|
||||
finally:
|
||||
if handle: handle.Close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('action', ['release', 'maintenance'])
|
||||
def test_restarted_export_copy_can_release_only_after_fresh_proof(export_case, tmp_path, action):
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
library, root, token, lease = export_case
|
||||
# Simulate interpreter exit: all process-local registries/lease handles lost.
|
||||
with locks._guard: locks._owners.pop(lease.key)['handle'].Close()
|
||||
@contextmanager
|
||||
def target_guard(): yield {'target': 'file-only maintenance proof'}
|
||||
if action == 'release':
|
||||
assert locks.release_retained_library(library, tmp_path/'release')['status'] == 'RELEASE_CONFIRMED'
|
||||
else:
|
||||
with locks.LibraryLock.for_maintenance(library, tmp_path/'takeover', target_guard,
|
||||
safe_to_release=lambda: True): pass
|
||||
assert not locks.blocker_path(library).exists()
|
||||
assert (root/'project/database/icdb.dat').read_bytes() == b'copied database'
|
||||
|
||||
|
||||
def test_maintenance_idle_guard_recognizes_new_exporter_names(monkeypatch):
|
||||
from cbb_refresh_verify.maintenance_entry import assert_native_idle
|
||||
def query(names):
|
||||
assert 'icdb2ascii.exe' in [n.casefold() for n in names] and 'icdbnetserver.exe' in [n.casefold() for n in names]
|
||||
return [{'pid': 123456, 'name': 'icdb2ascii.exe', 'command': 'export'}]
|
||||
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', query)
|
||||
with pytest.raises(ValueError, match='MAINTENANCE_OWNER_ACTIVE'): assert_native_idle()
|
||||
|
||||
|
||||
def test_successful_export_clears_only_its_bound_guard_after_fresh_copy_proof(tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
import cbb_refresh_verify.native_engineering_identity as identity
|
||||
from cbb_refresh_verify.native_export_guard import begin_export_analysis, finish_export_analysis
|
||||
monkeypatch.setattr(identity, '_process_snapshot', lambda: [])
|
||||
monkeypatch.setattr(identity, '_retained_exports', [])
|
||||
monkeypatch.setattr(locks, '_supervisor_alive', lambda _: False)
|
||||
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
|
||||
root = tmp_path/'analysis'; (root/'project/database').mkdir(parents=True)
|
||||
project = root/'project/Source.prj'; project.touch()
|
||||
(project.parent/'database/icdb.dat').write_bytes(b'copied db')
|
||||
with locks.LibraryLock(library):
|
||||
token = begin_export_analysis(library, root, project)
|
||||
marker = locks.blocker_path(library)
|
||||
assert json.loads(marker.read_text())['export_analysis'][0]['token'] == token
|
||||
(root/'export-launch.json').write_text('{"started": false}')
|
||||
finish_export_analysis(library, token)
|
||||
assert 'export_analysis' not in json.loads(marker.read_text())
|
||||
assert not marker.exists()
|
||||
|
||||
|
||||
def test_unrelated_same_name_server_does_not_prevent_copy_release(export_case, monkeypatch):
|
||||
import cbb_refresh_verify.native_engineering_identity as identity
|
||||
from cbb_refresh_verify.native_export_guard import prove_export_copies_released
|
||||
library, root, *_ = export_case
|
||||
monkeypatch.setattr(identity, '_process_snapshot', lambda: [
|
||||
{'pid': 777777, 'name': 'iCDBNetServer.exe', 'parent': 0, 'executable': 'native',
|
||||
'command': 'iCDBNetServer.exe C:\\other\\database'}])
|
||||
with prove_export_copies_released(library) as copies:
|
||||
assert copies == [str(root/'project')]
|
||||
|
||||
|
||||
def test_retained_export_registry_is_scoped_to_its_library(tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.native_engineering_identity as identity
|
||||
from cbb_refresh_verify.native_export_guard import assert_retained_exports_idle
|
||||
from cbb_refresh_verify.library_lock import LibraryBusy
|
||||
library_a, library_b = tmp_path/'a.lmc', tmp_path/'b.lmc'
|
||||
monkeypatch.setattr(identity, '_retained_exports', [
|
||||
(SimpleNamespace(poll=lambda: None), {}, {'library': str(library_a.resolve())})])
|
||||
assert_retained_exports_idle(library_b)
|
||||
with pytest.raises(LibraryBusy): assert_retained_exports_idle(library_a)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('created,blocked', [('new-process', False), ('original-process', True)])
|
||||
def test_recorded_export_pid_reuse_requires_matching_creation_identity(export_case, monkeypatch, created, blocked):
|
||||
import cbb_refresh_verify.native_engineering_identity as identity
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
from cbb_refresh_verify.native_export_guard import prove_export_copies_released
|
||||
library, root, *_ = export_case
|
||||
path = root/'ascii-process.json'
|
||||
record = json.loads(path.read_text('utf-8'))
|
||||
record['process_identities'] = [{'pid': 123456, 'created': 'original-process', 'executable': 'native'}]
|
||||
path.write_text(json.dumps(record), encoding='utf-8')
|
||||
monkeypatch.setattr(locks, '_supervisor_alive', lambda _: True)
|
||||
monkeypatch.setattr(identity, '_process_snapshot', lambda: [
|
||||
{'pid': 123456, 'name': 'unrelated.exe', 'parent': 0,
|
||||
'executable': 'native', 'created': created, 'command': ''}])
|
||||
if blocked:
|
||||
with pytest.raises(locks.LibraryBusy):
|
||||
with prove_export_copies_released(library): pass
|
||||
else:
|
||||
with prove_export_copies_released(library): pass
|
||||
|
||||
|
||||
@pytest.mark.parametrize('active', [False, True])
|
||||
def test_unknown_checkpoint_requires_explicit_full_proof_and_no_native_export_owner(tmp_path, monkeypatch, active):
|
||||
import cbb_refresh_verify.native_engineering_identity as identity
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
from cbb_refresh_verify.native_export_guard import prove_export_copies_released
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
locks.blocker_path(library).write_text('{torn metadata')
|
||||
monkeypatch.setattr(identity, '_retained_exports', [])
|
||||
monkeypatch.setattr(identity, '_process_snapshot', lambda: [
|
||||
{'pid': 12345, 'name': 'iCDBNetServer.exe', 'parent': 0}] if active else [])
|
||||
with pytest.raises(locks.LibraryBusy):
|
||||
with prove_export_copies_released(library): pass
|
||||
if active:
|
||||
with pytest.raises(locks.LibraryBusy):
|
||||
with prove_export_copies_released(library, allow_unknown_checkpoint=True): pass
|
||||
else:
|
||||
with prove_export_copies_released(library, allow_unknown_checkpoint=True) as copies:
|
||||
assert copies == []
|
||||
assert locks.blocker_path(library).read_text() == '{torn metadata'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('no_start_proven', [False, True])
|
||||
def test_missing_pid_requires_bound_no_start_evidence(export_case, no_start_proven):
|
||||
from cbb_refresh_verify.native_export_guard import prove_export_copies_released
|
||||
from cbb_refresh_verify.library_lock import LibraryBusy
|
||||
library, root, *_ = export_case
|
||||
record = {'success': False, 'safe_to_continue': True}
|
||||
if no_start_proven: record['native_started'] = False
|
||||
(root/'ascii-process.json').write_text(json.dumps(record), encoding='utf-8')
|
||||
(root/'export-launch.json').write_text(json.dumps({'started': not no_start_proven}), encoding='utf-8')
|
||||
if no_start_proven:
|
||||
with prove_export_copies_released(library): pass
|
||||
else:
|
||||
with pytest.raises(LibraryBusy):
|
||||
with prove_export_copies_released(library): pass
|
||||
@@ -0,0 +1,102 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def test_empty_private_desktop_does_not_inherit_stale_windows_error(tmp_path):
|
||||
from cbb_refresh_verify.desktop_worker import DesktopWorker
|
||||
script = tmp_path/'enumerate.py'
|
||||
result = tmp_path/'result.json'
|
||||
script.write_text(
|
||||
'import sys,json,win32api,win32gui,win32process\nfrom pathlib import Path\n'
|
||||
f'sys.path.insert(0,{str(Path("src").resolve())!r})\n'
|
||||
'from cbb_refresh_verify.native_repair_ui import _windows\n'
|
||||
'win32api.SetLastError(2)\n'
|
||||
'try:\n record={"windows":_windows(999999)}\n'
|
||||
'except Exception as error:\n record={"error":str(error)}\n'
|
||||
f'Path({str(result)!r}).write_text(json.dumps(record))\n', encoding='utf-8')
|
||||
worker = DesktopWorker([sys.executable, str(script)], 'CbbProbe_' + uuid4().hex[:12])
|
||||
try:
|
||||
assert worker.wait(timeout=20) == 0
|
||||
finally:
|
||||
worker.close()
|
||||
assert json.loads(result.read_text()) == {'windows': []}
|
||||
|
||||
|
||||
def test_real_window_enumeration_errors_still_propagate(monkeypatch):
|
||||
import win32gui, pywintypes
|
||||
from cbb_refresh_verify.native_repair_ui import _windows
|
||||
def denied(*args): raise pywintypes.error(5, 'EnumWindows', 'denied')
|
||||
monkeypatch.setattr(win32gui, 'EnumWindows', denied)
|
||||
with pytest.raises(pywintypes.error): _windows(123)
|
||||
|
||||
|
||||
def test_cancel_reaches_prelaunch_scan(tmp_path, monkeypatch):
|
||||
from contextlib import contextmanager
|
||||
from test_native_repair import repair_worker_fixture
|
||||
from cbb_refresh_verify.native_repair import RepairTarget
|
||||
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'active')
|
||||
data = json.loads(job.read_text('utf-8'))
|
||||
data['maintenance_context'] = {'library': str(tmp_path/'lib.lmc'), 'block': 'CBB1'}
|
||||
job.write_text(json.dumps(data), encoding='utf-8')
|
||||
calls, interrupted = [], []
|
||||
@contextmanager
|
||||
def guard(*args, stop=None, **kwargs):
|
||||
calls.append(1)
|
||||
assert stop is not None, 'worker scan has no cancellation input'
|
||||
if len(calls) == 1:
|
||||
Path(data['cancel_signal']).touch()
|
||||
assert stop.is_set()
|
||||
interrupted.append(1)
|
||||
raise ValueError('MAINTENANCE_CANCELLED')
|
||||
yield {'target': RepairTarget(Path(data['project']), Path(data['database']))}
|
||||
monkeypatch.setattr('cbb_refresh_verify.maintenance_entry.maintenance_target_guard', guard)
|
||||
monkeypatch.setattr(ui.subprocess, 'Popen', lambda *a, **kw: pytest.fail('cancelled native launch'))
|
||||
assert ui.repair_worker_main(job) == 1
|
||||
assert interrupted == [1] and not actions
|
||||
|
||||
|
||||
def test_worker_uses_one_complete_guard_immediately_before_native_launch(tmp_path, monkeypatch):
|
||||
from contextlib import contextmanager
|
||||
from test_native_repair import repair_worker_fixture
|
||||
from cbb_refresh_verify.native_repair import RepairTarget
|
||||
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'active')
|
||||
data = json.loads(job.read_text('utf-8'))
|
||||
data['maintenance_context'] = {'library': str(tmp_path/'lib.lmc'), 'block': 'CBB1'}
|
||||
job.write_text(json.dumps(data), encoding='utf-8')
|
||||
order = []
|
||||
@contextmanager
|
||||
def guard(*args, stop=None, **kwargs):
|
||||
assert stop is not None
|
||||
order.append('guard')
|
||||
yield {'target': RepairTarget(Path(data['project']), Path(data['database']))}
|
||||
order.append('guard_complete')
|
||||
monkeypatch.setattr('cbb_refresh_verify.maintenance_entry.maintenance_target_guard', guard)
|
||||
popen = ui.subprocess.Popen
|
||||
def launch(*args, **kwargs):
|
||||
order.append('launch')
|
||||
return popen(*args, **kwargs)
|
||||
monkeypatch.setattr(ui.subprocess, 'Popen', launch)
|
||||
ui.repair_worker_main(job)
|
||||
assert order == ['guard', 'guard_complete', 'launch']
|
||||
|
||||
|
||||
def test_file_cancellation_polling_is_bounded_and_latches_cancel(tmp_path, monkeypatch):
|
||||
from types import SimpleNamespace
|
||||
import cbb_refresh_verify.native_repair_ui as ui
|
||||
now = [1.0]
|
||||
monkeypatch.setattr(ui, 'time', SimpleNamespace(monotonic=lambda: now[0]))
|
||||
signal = ui._CancellationFile(tmp_path/'cancel.signal')
|
||||
reads = []
|
||||
signal.path = SimpleNamespace(exists=lambda: reads.append(1) or len(reads) > 1)
|
||||
for _ in range(50000):
|
||||
assert not signal.is_set()
|
||||
assert len(reads) == 1
|
||||
now[0] += .11
|
||||
assert signal.is_set()
|
||||
signal.path = SimpleNamespace(exists=lambda: pytest.fail('cancel must stay latched'))
|
||||
now[0] += 1
|
||||
assert signal.is_set()
|
||||
@@ -0,0 +1,468 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def test_installed_binary_mismatch_disables_removal(tmp_path):
|
||||
from cbb_refresh_verify.native_management import NativeManagementAdapter
|
||||
adapter = NativeManagementAdapter(mentor_home=tmp_path)
|
||||
caps = adapter.capabilities()
|
||||
assert not caps['remove'].supported and 'CleanWGLib' in caps['remove'].reason
|
||||
assert not caps['add'].supported and not caps['update'].supported
|
||||
|
||||
|
||||
def test_public_add_cannot_bypass_disabled_capability(tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.native_management as native
|
||||
from cbb_refresh_verify.management import ManagementRequest
|
||||
adapter = native.NativeManagementAdapter(mentor_home=tmp_path)
|
||||
monkeypatch.setattr(adapter, '_worker', lambda *a: pytest.fail('public disabled Add launched worker'))
|
||||
monkeypatch.setattr(native, 'engineering_identity', lambda *a: pytest.fail('public disabled Add accessed source'))
|
||||
result = adapter.add(ManagementRequest('add', tmp_path/'arbitrary.lmc', 'Block',
|
||||
source=tmp_path/'source/original.prj'), tmp_path/'add')
|
||||
assert not result.success and result.safe_to_continue
|
||||
|
||||
|
||||
def test_empty_fixture_creation_uses_existing_new_library_guard_route(tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.native_management as native
|
||||
seen = []
|
||||
monkeypatch.setattr(native.NativeManagementAdapter, '_binary_capability', lambda _: '')
|
||||
monkeypatch.setattr(native.NativeManagementAdapter, '_worker',
|
||||
lambda adapter, job, evidence: (seen.append((job, evidence)) or
|
||||
{'success': True, 'safe_to_continue': True, 'entries': []}))
|
||||
root = tmp_path/'fresh'
|
||||
result = native.create_owned_fixture(root)
|
||||
assert result['success'] and result['entries'] == []
|
||||
assert seen[0][0]['operation'] == 'probe_create'
|
||||
assert Path(seen[0][0]['library']) == root/'native-add/fixture/mentor_lib.lmc'
|
||||
assert seen[0][0]['probe_token'] == result['probe_token']
|
||||
existing = tmp_path/'existing'; existing.mkdir()
|
||||
with pytest.raises(ValueError): native.create_owned_fixture(existing)
|
||||
assert len(seen) == 1
|
||||
|
||||
|
||||
def test_unprepared_add_rejected_before_native_activation(tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.native_management as native
|
||||
import win32com.client
|
||||
monkeypatch.setattr(win32com.client, 'DispatchEx', lambda *a: pytest.fail('unprepared native activation'))
|
||||
with pytest.raises(ValueError):
|
||||
native._catalog_com({'operation': 'add', 'library': str(tmp_path/'arbitrary.lmc')}, tmp_path/'add')
|
||||
|
||||
|
||||
def test_removed_marker_cannot_cross_carriage_return_record():
|
||||
from cbb_refresh_verify.native_management import removal_output_ok
|
||||
assert not removal_output_ok(0, "# Note: Removed unrelated\rrecord 'Block' from partition 'Logical-Physical'.",
|
||||
'Block', 'Logical-Physical')
|
||||
|
||||
|
||||
@pytest.mark.parametrize('invalid', ['', 'nonce', 'lease', 'source', 'backup', 'expired', 'token'])
|
||||
def test_fixture_add_authority_requires_live_lease_and_fresh_staging(tmp_path, monkeypatch, invalid):
|
||||
import cbb_refresh_verify.native_management as native
|
||||
from cbb_refresh_verify.management import ManagementRequest
|
||||
from cbb_refresh_verify.library_lock import LibraryLock
|
||||
library = tmp_path/'native-add/fixture/mentor_lib.lmc'
|
||||
library.parent.mkdir(parents=True); library.write_bytes(b'owned fixture')
|
||||
source = tmp_path/'original/Source.prj'
|
||||
source.parent.mkdir(); source.write_bytes(b'original source')
|
||||
(tmp_path/'probe-owner.json').write_text(json.dumps({'library': str(library), 'token': 'owned'}), encoding='utf-8')
|
||||
adapter = native.NativeManagementAdapter(mentor_home=tmp_path)
|
||||
monkeypatch.setattr(adapter, 'route_capabilities', lambda: {'add': native.Capability(True, 'ready')})
|
||||
monkeypatch.setattr(native, 'engineering_identity', lambda _: {'source': 'bytes'})
|
||||
def launch(job, root):
|
||||
staged = Path(job['source'])
|
||||
assert staged == root/'source/Source.prj' and staged != source
|
||||
prepared_path = root/'add-prepared.json'
|
||||
prepared = json.loads(prepared_path.read_text(encoding='utf-8'))
|
||||
if invalid == 'nonce': job['transaction_nonce'] = 'foreign'
|
||||
if invalid == 'token': job['probe_token'] = 'foreign'
|
||||
if invalid == 'lease': prepared['lease_id'] = 'foreign'
|
||||
if invalid == 'source': job['source'] = str(source)
|
||||
if invalid == 'backup': (root/'library-before/mentor_lib.lmc').write_bytes(b'changed')
|
||||
if invalid == 'expired':
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
monkeypatch.setattr(locks, '_supervisor_alive', lambda _: False)
|
||||
prepared_path.write_text(json.dumps(prepared), encoding='utf-8')
|
||||
if invalid:
|
||||
with pytest.raises(ValueError): native.validate_owned_fixture_add(job, root)
|
||||
else:
|
||||
assert native.validate_owned_fixture_add(job, root) == staged
|
||||
assert source.read_bytes() == b'original source'
|
||||
return {'success': not invalid, 'safe_to_continue': True, 'identity_matches': not invalid}
|
||||
monkeypatch.setattr(adapter, '_launch_worker', launch)
|
||||
with LibraryLock(library):
|
||||
result = adapter.add_owned_fixture(ManagementRequest('add', library, 'Block', source=source),
|
||||
tmp_path/'shared-add', probe_token='owned')
|
||||
assert result.success is (not invalid)
|
||||
|
||||
|
||||
def test_fixture_metadata_without_current_thread_lease_cannot_stage_source(tmp_path):
|
||||
import cbb_refresh_verify.native_management as native
|
||||
library = tmp_path/'native-add/fixture/mentor_lib.lmc'
|
||||
library.parent.mkdir(parents=True); library.touch()
|
||||
(tmp_path/'probe-owner.json').write_text(json.dumps({'library': str(library), 'token': 'owned'}), encoding='utf-8')
|
||||
root = tmp_path/'add'; root.mkdir()
|
||||
with pytest.raises(ValueError, match='current thread'):
|
||||
native.prepare_owned_fixture_add({'library': str(library), 'probe_token': 'owned'}, root)
|
||||
assert not (root/'source').exists()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('outcome', ['unsafe', 'exception', 'safe'])
|
||||
def test_owned_fixture_retains_default_caller_lease_until_native_release(tmp_path, monkeypatch, outcome):
|
||||
import cbb_refresh_verify.native_management as native
|
||||
from cbb_refresh_verify.management import ManagementRequest
|
||||
from cbb_refresh_verify.library_lock import LibraryLock, LibraryBusy, blocker_path, _owners, _guard
|
||||
library = tmp_path/'native-add/fixture/mentor_lib.lmc'
|
||||
library.parent.mkdir(parents=True); library.write_bytes(b'fixture')
|
||||
source = tmp_path/'original/Source.prj'; source.parent.mkdir(); source.write_bytes(b'source')
|
||||
(tmp_path/'probe-owner.json').write_text(json.dumps({'library': str(library), 'token': 'owned'}), encoding='utf-8')
|
||||
adapter = native.NativeManagementAdapter(mentor_home=tmp_path)
|
||||
monkeypatch.setattr(adapter, 'route_capabilities', lambda: {'add': native.Capability(True, 'ready')})
|
||||
monkeypatch.setattr(native, 'engineering_identity', lambda _: {'source': 'bytes'})
|
||||
def launch(*args):
|
||||
if outcome == 'exception': raise OSError('worker result lost after dispatch')
|
||||
return {'success': outcome == 'safe', 'safe_to_continue': outcome == 'safe'}
|
||||
monkeypatch.setattr(adapter, '_launch_worker', launch)
|
||||
lease = LibraryLock(library)
|
||||
try:
|
||||
with lease:
|
||||
if outcome == 'exception':
|
||||
with pytest.raises(OSError, match='after dispatch'):
|
||||
adapter.add_owned_fixture(ManagementRequest('add', library, 'Block', source=source),
|
||||
tmp_path/'add', probe_token='owned')
|
||||
else:
|
||||
adapter.add_owned_fixture(ManagementRequest('add', library, 'Block', source=source),
|
||||
tmp_path/'add', probe_token='owned')
|
||||
assert blocker_path(library).exists() is (outcome != 'safe')
|
||||
if outcome != 'safe':
|
||||
with pytest.raises(LibraryBusy):
|
||||
with LibraryLock(library): pass
|
||||
import win32file, win32con, pywintypes
|
||||
with pytest.raises(pywintypes.error):
|
||||
win32file.CreateFile(str(lease.path), win32con.GENERIC_READ, 0, None,
|
||||
win32con.OPEN_EXISTING, 0, None)
|
||||
else:
|
||||
with LibraryLock(library): pass
|
||||
finally:
|
||||
# Only the file-only fake worker above ran; release its test lease.
|
||||
with _guard:
|
||||
owner = _owners.pop(lease.key, None)
|
||||
if owner: owner['handle'].Close()
|
||||
blocker_path(library).unlink(missing_ok=True)
|
||||
|
||||
|
||||
def test_fixture_nested_inside_source_tree_rejected_before_staging(tmp_path):
|
||||
import cbb_refresh_verify.native_management as native
|
||||
from cbb_refresh_verify.library_lock import LibraryLock
|
||||
library = tmp_path/'native-add/fixture/mentor_lib.lmc'
|
||||
library.parent.mkdir(parents=True); library.write_bytes(b'fixture')
|
||||
source = tmp_path/'native-add/Source.prj'; source.write_bytes(b'original source')
|
||||
(tmp_path/'probe-owner.json').write_text(json.dumps({'library': str(library), 'token': 'owned'}), encoding='utf-8')
|
||||
root = tmp_path/'add'; root.mkdir()
|
||||
with LibraryLock(library):
|
||||
with pytest.raises(ValueError, match='independent'):
|
||||
native.prepare_owned_fixture_add({'library': str(library), 'source': str(source),
|
||||
'name': 'Block', 'partition': 'Logical-Physical', 'source_identity': {},
|
||||
'probe_token': 'owned'}, root)
|
||||
assert source.read_bytes() == b'original source' and library.read_bytes() == b'fixture'
|
||||
assert not (root/'source').exists()
|
||||
|
||||
|
||||
def test_add_route_readiness_is_separate_from_conservative_capability_gate(tmp_path, monkeypatch):
|
||||
import hashlib
|
||||
import cbb_refresh_verify.native_management as native
|
||||
proof = {'lm/win32/bin/CleanWGLib.exe': hashlib.sha256(b'verified').hexdigest()}
|
||||
monkeypatch.setattr(native, '_BINARY_PROOF', proof)
|
||||
path = tmp_path/next(iter(proof)); path.parent.mkdir(parents=True); path.write_bytes(b'verified')
|
||||
adapter = native.NativeManagementAdapter(mentor_home=tmp_path)
|
||||
assert adapter.route_capabilities()['add'].supported
|
||||
assert not adapter.capabilities()['add'].supported
|
||||
assert 'icdb2ascii' in adapter.capabilities()['add'].reason
|
||||
|
||||
|
||||
@pytest.mark.parametrize('bad', [None, 'CleanWGLib.exe', 'LibraryManager.exe', 'LMCDLL70.dll',
|
||||
'LMCDocAddin70.dll', 'icdb2ascii.exe', 'icdb2csv.exe', 'edifExporter.exe'])
|
||||
def test_public_crud_requires_pinned_core_and_every_identity_exporter(tmp_path, monkeypatch, bad):
|
||||
import hashlib
|
||||
import cbb_refresh_verify.native_management as native
|
||||
import cbb_refresh_verify.native_engineering_identity as identity
|
||||
core = {relative: hashlib.sha256(Path(relative).name.encode()).hexdigest() for relative in native._BINARY_PROOF}
|
||||
exporters = {name: hashlib.sha256(name.encode()).hexdigest() for name in identity.EXPORTER_PROOF}
|
||||
monkeypatch.setattr(native, '_BINARY_PROOF', core)
|
||||
monkeypatch.setattr(identity, 'EXPORTER_PROOF', exporters)
|
||||
for relative in core:
|
||||
path = tmp_path/relative; path.parent.mkdir(parents=True, exist_ok=True); path.write_bytes(path.name.encode())
|
||||
for name in exporters:
|
||||
path = tmp_path/('wv/win32/bin' if name == 'edifExporter.exe' else 'iCDB/win32/bin')/name
|
||||
path.parent.mkdir(parents=True, exist_ok=True); path.write_bytes(name.encode())
|
||||
if bad:
|
||||
next(tmp_path.rglob(bad)).write_bytes(b'changed binary')
|
||||
caps = native.NativeManagementAdapter(mentor_home=tmp_path).capabilities()
|
||||
assert caps['add'].supported is (bad is None)
|
||||
assert caps['update'].supported is (bad is None)
|
||||
if bad in exporters: assert caps['remove'].supported
|
||||
|
||||
|
||||
@pytest.mark.parametrize('operation', ['add', 'update', 'remove'])
|
||||
@pytest.mark.parametrize('flow,partition', [(2, 'Logical-Physical'), (1, 'Unsupported')])
|
||||
def test_public_crud_scope_refuses_unproven_flow_or_partition(tmp_path, operation, flow, partition):
|
||||
from cbb_refresh_verify.management import ManagementRequest, Catalog
|
||||
from cbb_refresh_verify.native_management import NativeManagementAdapter
|
||||
request = ManagementRequest(operation, tmp_path/'lib.lmc', 'Block', partition=partition)
|
||||
with pytest.raises(ValueError):
|
||||
NativeManagementAdapter(mentor_home=tmp_path).preflight(request, Catalog(request.library, flow, ()))
|
||||
|
||||
|
||||
def test_owned_fixture_add_passes_existing_library_and_source_to_worker(tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify.management import ManagementRequest
|
||||
import cbb_refresh_verify.native_management as native
|
||||
source = tmp_path/'source.prj'; source.write_bytes(b'source')
|
||||
library = tmp_path/'library.lmc'; library.write_bytes(b'library')
|
||||
seen = {}
|
||||
adapter = native.NativeManagementAdapter(mentor_home=tmp_path)
|
||||
monkeypatch.setattr(adapter, 'route_capabilities', lambda: {
|
||||
'add': native.Capability(True, 'route ready')})
|
||||
monkeypatch.setattr(native, 'engineering_identity', lambda path: {'source': str(path)})
|
||||
def worker(job, evidence):
|
||||
seen.update(job=job, evidence=evidence)
|
||||
return {'success': True, 'safe_to_continue': True, 'identity_matches': True,
|
||||
'detail': 'native add accepted'}
|
||||
monkeypatch.setattr(adapter, '_worker', worker)
|
||||
request = ManagementRequest('add', library, 'Block', source=source,
|
||||
mapped_drive='S:', mapped_remote_root=r'\\server\share', timeout_seconds=23)
|
||||
result = adapter.add_owned_fixture(request, tmp_path/'evidence', probe_token='owned')
|
||||
assert result.success and result.safe_to_continue and result.identity_matches is True
|
||||
assert seen['job'] == {
|
||||
'operation': 'add', 'library': str(library), 'source': str(source),
|
||||
'name': 'Block', 'partition': 'Logical-Physical', 'top_level_block': '',
|
||||
'mapped_drive': 'S:', 'mapped_remote_root': r'\\server\share',
|
||||
'timeout_seconds': 23, 'source_identity': {'source': str(source)}, 'probe_token': 'owned',
|
||||
}
|
||||
|
||||
|
||||
def test_native_add_identity_mismatch_is_native_success_with_evidence(tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify.management import ManagementRequest
|
||||
import cbb_refresh_verify.native_management as native
|
||||
source = tmp_path/'source.prj'; source.write_bytes(b'source')
|
||||
library = tmp_path/'library.lmc'; library.write_bytes(b'library')
|
||||
adapter = native.NativeManagementAdapter(mentor_home=tmp_path)
|
||||
monkeypatch.setattr(adapter, 'route_capabilities', lambda: {
|
||||
'add': native.Capability(True, 'route ready')})
|
||||
monkeypatch.setattr(native, 'engineering_identity', lambda path: {'source': str(path)})
|
||||
monkeypatch.setattr(adapter, '_worker', lambda job, evidence: {
|
||||
'success': True, 'safe_to_continue': True, 'identity_matches': False,
|
||||
'detail': 'engineering identity readback mismatch',
|
||||
})
|
||||
original = source.read_bytes()
|
||||
result = adapter.add_owned_fixture(ManagementRequest('add', library, 'Block', source=source),
|
||||
tmp_path/'evidence', probe_token='owned')
|
||||
assert result.success and result.identity_matches is False
|
||||
assert 'identity' in result.detail
|
||||
assert result.evidence_path == tmp_path/'evidence'
|
||||
assert source.read_bytes() == original
|
||||
|
||||
|
||||
@pytest.mark.parametrize('name', ['A\tB', 'A\nB', '../A', '中文'])
|
||||
def test_delete_record_rejects_ambiguous_encoding_or_injection(name):
|
||||
from cbb_refresh_verify.native_management import removal_input
|
||||
with pytest.raises(ValueError):
|
||||
removal_input(name, 'Logical-Physical')
|
||||
|
||||
|
||||
def test_delete_record_is_exact_shipped_tcl_contract():
|
||||
from cbb_refresh_verify.native_management import removal_input, removal_output_ok
|
||||
assert removal_input('Block', 'Logical-Physical') == b'REUSE_BLOCK\tLogical-Physical\tBlock\n'
|
||||
assert not removal_output_ok(0, '', 'Block', 'Logical-Physical')
|
||||
assert not removal_output_ok(0, "# Warning: Unable to remove REUSE_BLOCK 'Block' from partition 'Logical-Physical'.", 'Block', 'Logical-Physical')
|
||||
assert removal_output_ok(0, "# Note: Removed REUSE_BLOCK 'Block' from partition 'Logical-Physical'.", 'Block', 'Logical-Physical')
|
||||
|
||||
|
||||
def test_upgrade_dialog_is_refused_and_only_cancel_is_allowed():
|
||||
from cbb_refresh_verify.native_management import catalog_dialog_action
|
||||
assert catalog_dialog_action('Library Manager', 'This Central Library must be updated before it can be opened in Library Manager. Select OK to continue.') == 'cancel'
|
||||
assert catalog_dialog_action('Select flow type', '') == 'cancel'
|
||||
assert catalog_dialog_action('Library Manager', 'Would you like to save?') == 'observe'
|
||||
|
||||
|
||||
def test_catalog_never_falls_back_to_folder_list(tmp_path):
|
||||
from cbb_refresh_verify.native_management import NativeManagementAdapter
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
(tmp_path/'ReusableBlocksLP/Ghost').mkdir(parents=True)
|
||||
adapter = NativeManagementAdapter()
|
||||
adapter._worker = lambda *_: {'success': False, 'safe_to_continue': True, 'detail': 'upgrade refused'}
|
||||
with pytest.raises(RuntimeError, match='upgrade refused'):
|
||||
adapter.catalog(library, tmp_path/'evidence')
|
||||
|
||||
|
||||
def test_private_worker_timeout_retains_native_and_never_kills(tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.native_management as native
|
||||
monkeypatch.setattr(native, '_retained_workers', [])
|
||||
from cbb_refresh_verify.native_management import NativeManagementAdapter
|
||||
class Running:
|
||||
def __init__(self, *a): pass
|
||||
def poll(self): return None
|
||||
def close(self): pytest.fail('closing live DesktopWorker kills automation')
|
||||
def kill(self): pytest.fail('must preserve native owner')
|
||||
adapter = NativeManagementAdapter(worker_factory=Running, timeout_seconds=0)
|
||||
result = adapter._worker({'operation': 'catalog', 'library': str(tmp_path/'lib.lmc')}, tmp_path/'out')
|
||||
assert result['safe_to_continue'] is False
|
||||
assert 'TIMEOUT' in result['detail']
|
||||
|
||||
|
||||
def test_hidden_worker_and_probe_dispatch_before_qt(monkeypatch, tmp_path):
|
||||
import cbb_refresh_verify.native_management as native
|
||||
from cbb_refresh_verify.application import main
|
||||
seen = []
|
||||
monkeypatch.setattr(native, 'management_worker_main', lambda p: (seen.append(p) or 17))
|
||||
assert main(['--management-worker', str(tmp_path/'job.json')]) == 17
|
||||
assert seen == [tmp_path/'job.json']
|
||||
|
||||
|
||||
def test_probe_cannot_use_existing_fixture_or_mutate_source(tmp_path):
|
||||
from cbb_refresh_verify.native_management import run_isolated_probe
|
||||
existing = tmp_path/'existing'
|
||||
existing.mkdir()
|
||||
with pytest.raises(ValueError, match='new|新'):
|
||||
run_isolated_probe(tmp_path/'source.prj', existing, 'Block')
|
||||
|
||||
|
||||
def test_probe_requires_owned_new_native_library_path(tmp_path):
|
||||
import os
|
||||
from cbb_refresh_verify.native_management import prepare_probe_library
|
||||
from cbb_refresh_verify.library_lock import LibraryLock
|
||||
outside = tmp_path/'production.lmc'; outside.write_bytes(b'unchanged')
|
||||
root = tmp_path/'worker'; root.mkdir()
|
||||
with pytest.raises(ValueError):
|
||||
prepare_probe_library({'library': str(outside)}, root)
|
||||
assert outside.read_bytes() == b'unchanged'
|
||||
owned = root/'fixture/mentor_lib.lmc'
|
||||
owned.parent.mkdir()
|
||||
job = {'library': str(owned), 'probe_token': 'test-token', 'supervisor_pid': os.getpid()}
|
||||
(root/'probe-prepared.json').write_text(json.dumps({'library': str(owned), 'token': 'test-token',
|
||||
'supervisor_pid': os.getpid()}), encoding='utf-8')
|
||||
with LibraryLock(owned):
|
||||
assert prepare_probe_library(job, root) == owned
|
||||
owned.write_bytes(b'first creation')
|
||||
with pytest.raises(ValueError):
|
||||
prepare_probe_library(job, root)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('records', [[], [('Actual', 'Logical-Physical')]])
|
||||
@pytest.mark.parametrize('mapped', [False, True])
|
||||
@pytest.mark.parametrize('flow', [1, 2])
|
||||
def test_native_catalog_only_uses_com_records_and_checks_exact_process(tmp_path, monkeypatch, records, mapped, flow):
|
||||
import cbb_refresh_verify.native_management as native
|
||||
import cbb_refresh_verify.mentor_adapter as mentor
|
||||
import win32com.client
|
||||
library_path = tmp_path/'lib.lmc'; library_path.touch()
|
||||
if mapped:
|
||||
original_resolve = Path.resolve
|
||||
def resolve(path, *a, **k):
|
||||
return tmp_path/'canonical/lib.lmc' if path == library_path else original_resolve(path, *a, **k)
|
||||
monkeypatch.setattr(Path, 'resolve', resolve)
|
||||
(tmp_path/'ReusableBlocksLP/Ghost').mkdir(parents=True)
|
||||
class Collection:
|
||||
def __init__(self, items): self.items = items; self.Count = len(items)
|
||||
def Item(self, index): return self.items[index - 1]
|
||||
items = Collection([SimpleNamespace(Name=name, PartitionName=partition) for name, partition in records])
|
||||
class Library:
|
||||
FullName = str(library_path)
|
||||
FlowType = flow
|
||||
def Partitions(self, kind):
|
||||
assert kind == 7
|
||||
return Collection([items])
|
||||
def Close(self): pass
|
||||
state = {'running': False}
|
||||
class App:
|
||||
def OpenLibrary(self, path):
|
||||
assert path == str(library_path)
|
||||
return Library()
|
||||
def Quit(self): state['running'] = False
|
||||
def dispatch(_): state['running'] = True; return App()
|
||||
monkeypatch.setattr(win32com.client, 'DispatchEx', dispatch)
|
||||
monkeypatch.setattr(native, '_current_desktop', lambda: (SimpleNamespace(EnumDesktopWindows=lambda: []), 'CbbManagement_test'))
|
||||
monkeypatch.setattr(mentor, '_process_details', lambda _: [(123, str(tmp_path/'lm/win32/bin/LibraryManager.exe'), '', 0)] if state['running'] else [])
|
||||
monkeypatch.setattr(native, '_wait_native_exit', lambda _: not state['running'])
|
||||
result = native._catalog_native({'operation': 'catalog', 'library': str(library_path),
|
||||
'desktop': 'CbbManagement_test', 'mentor_home': str(tmp_path)}, tmp_path)
|
||||
assert result['success'] and result['safe_to_continue']
|
||||
assert [(entry['name'], entry['partition']) for entry in result['entries']] == records
|
||||
assert result['flow'] == flow
|
||||
|
||||
|
||||
def test_production_caps_require_all_validated_binary_hashes(tmp_path, monkeypatch):
|
||||
import hashlib
|
||||
import cbb_refresh_verify.native_management as native
|
||||
proof = {'lm/win32/bin/CleanWGLib.exe': hashlib.sha256(b'verified').hexdigest()}
|
||||
monkeypatch.setattr(native, '_BINARY_PROOF', proof)
|
||||
path = tmp_path/next(iter(proof)); path.parent.mkdir(parents=True); path.write_bytes(b'verified')
|
||||
adapter = native.NativeManagementAdapter(mentor_home=tmp_path)
|
||||
assert adapter.capabilities()['remove'].supported
|
||||
assert not adapter.capabilities()['add'].supported
|
||||
path.write_bytes(b'different')
|
||||
assert not adapter.capabilities()['remove'].supported
|
||||
|
||||
|
||||
def test_probe_readd_requires_creation_token_and_fixed_owned_library(tmp_path):
|
||||
from cbb_refresh_verify.native_management import validate_probe_readd
|
||||
root = tmp_path/'native-readd'; root.mkdir()
|
||||
library = tmp_path/'native-add/fixture/mentor_lib.lmc'
|
||||
library.parent.mkdir(parents=True); library.touch()
|
||||
job = {'library': str(library), 'probe_token': 'owned-token'}
|
||||
with pytest.raises(ValueError):
|
||||
validate_probe_readd(job, root)
|
||||
(tmp_path/'probe-owner.json').write_text(json.dumps({'library': str(library), 'token': 'other'}), encoding='utf-8')
|
||||
with pytest.raises(ValueError):
|
||||
validate_probe_readd(job, root)
|
||||
(tmp_path/'probe-owner.json').write_text(json.dumps({'library': str(library), 'token': 'owned-token'}), encoding='utf-8')
|
||||
assert validate_probe_readd(job, root) == library
|
||||
outside = tmp_path/'production.lmc'; outside.touch()
|
||||
with pytest.raises(ValueError):
|
||||
validate_probe_readd({**job, 'library': str(outside)}, root)
|
||||
|
||||
|
||||
def test_com_failure_without_owner_identity_cannot_claim_release(tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.native_management as native
|
||||
monkeypatch.setattr(native, '_catalog_com', lambda *a: {'success': False,
|
||||
'safe_to_continue': False, 'native_pids': [], 'detail': 'COM startup ambiguous'})
|
||||
assert native._catalog_native({}, tmp_path)['safe_to_continue'] is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize('registered', [True, False])
|
||||
def test_shared_add_reopens_exact_catalog_and_reports_identity_mismatch(tmp_path, monkeypatch, registered):
|
||||
import cbb_refresh_verify.native_management as native
|
||||
import cbb_refresh_verify.mentor_adapter as mentor
|
||||
import win32com.client
|
||||
library_path = tmp_path/'lib.lmc'; library_path.touch()
|
||||
events = []
|
||||
class Collection:
|
||||
def __init__(self, items): self.items = items; self.Count = len(items)
|
||||
def Item(self, index): return self.items[index - 1]
|
||||
class Library:
|
||||
FullName = str(library_path)
|
||||
FlowType = 1
|
||||
def Partitions(self, kind):
|
||||
events.append('catalog')
|
||||
return Collection([Collection([SimpleNamespace(Name='Block', PartitionName='Logical-Physical')]
|
||||
if registered else [])])
|
||||
def Close(self): events.append('close')
|
||||
state = {'running': False}
|
||||
class App:
|
||||
def OpenLibrary(self, path):
|
||||
assert path == str(library_path)
|
||||
events.append('open')
|
||||
return Library()
|
||||
def Quit(self): state['running'] = False
|
||||
def dispatch(_): state['running'] = True; return App()
|
||||
monkeypatch.setattr(win32com.client, 'DispatchEx', dispatch)
|
||||
monkeypatch.setattr(native, '_current_desktop', lambda: (SimpleNamespace(EnumDesktopWindows=lambda: []), 'CbbManagement_test'))
|
||||
monkeypatch.setattr(mentor, '_process_details', lambda _: [(123, str(tmp_path/'lm/win32/bin/LibraryManager.exe'), '', 0)] if state['running'] else [])
|
||||
monkeypatch.setattr(native, '_probe_add_dialog', lambda *a, **k: events.append('add'))
|
||||
monkeypatch.setattr(native, 'validate_owned_fixture_add', lambda *a: None)
|
||||
result = native._catalog_com({'operation': 'add', 'library': str(library_path),
|
||||
'desktop': 'CbbManagement_test', 'mentor_home': str(tmp_path),
|
||||
'name': 'Block', 'partition': 'Logical-Physical', 'source_identity': {'expected': 'bytes'}}, tmp_path)
|
||||
assert events == ['open', 'add', 'close', 'open', 'catalog', 'close']
|
||||
assert result['success'] is registered
|
||||
assert result['identity_matches'] is False
|
||||
assert ('engineering identity' if registered else 'exact name and partition') in result['detail']
|
||||
@@ -0,0 +1,58 @@
|
||||
import ctypes
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.mark.parametrize('expected,actual', [('S:\\source\\项目.prj', 'S:\\source\\项目.prj'), ('', '')])
|
||||
def test_field_uses_bounded_set_and_remote_gettext_with_exact_readback(tmp_path, monkeypatch, expected, actual):
|
||||
from cbb_refresh_verify import native_management as native
|
||||
calls = []
|
||||
class Send:
|
||||
def __call__(self, hwnd, message, wparam, lparam, flags, timeout, result):
|
||||
calls.append((hwnd, message, flags, timeout))
|
||||
if message == 0x000C:
|
||||
assert ctypes.wstring_at(lparam) == expected
|
||||
result._obj.value = 1
|
||||
elif message == 0x000D:
|
||||
buffer = ctypes.create_unicode_buffer(actual)
|
||||
ctypes.memmove(lparam, ctypes.addressof(buffer), ctypes.sizeof(buffer))
|
||||
result._obj.value = len(actual)
|
||||
else:
|
||||
pytest.fail('unproven field message')
|
||||
return 1
|
||||
monkeypatch.setattr(native.ctypes, 'WinDLL', lambda *a, **k: SimpleNamespace(SendMessageTimeoutW=Send()))
|
||||
assert native._set_probe_field(123, 1217, expected, tmp_path) == actual
|
||||
assert [item[1] for item in calls] == [0x000C, 0x000D]
|
||||
assert all(item[0] == 123 and item[2] == 0x0002 and 0 < item[3] <= 1000 for item in calls)
|
||||
record = json.loads((tmp_path/'native-field-readback.jsonl').read_text(encoding='utf-8'))
|
||||
assert record['expected'] == expected and record['actual'] == actual and record['matched']
|
||||
|
||||
|
||||
@pytest.mark.parametrize('failure', ['empty', 'mismatch', 'set_timeout', 'read_timeout', 'set_rejected', 'truncated'])
|
||||
def test_field_failure_is_recorded_before_rejection_without_foreground_fallback(tmp_path, monkeypatch, failure):
|
||||
from cbb_refresh_verify import native_management as native
|
||||
calls = []
|
||||
class Send:
|
||||
def __call__(self, hwnd, message, wparam, lparam, flags, timeout, result):
|
||||
calls.append(message)
|
||||
if message == 0x000C:
|
||||
result._obj.value = 0 if failure == 'set_rejected' else 1
|
||||
return 0 if failure == 'set_timeout' else 1
|
||||
if failure == 'read_timeout': return 0
|
||||
actual = '' if failure == 'empty' else 'other project'
|
||||
buffer = ctypes.create_unicode_buffer(actual)
|
||||
ctypes.memmove(lparam, ctypes.addressof(buffer), ctypes.sizeof(buffer))
|
||||
result._obj.value = wparam - 1 if failure == 'truncated' else len(actual)
|
||||
return 1
|
||||
monkeypatch.setattr(native.ctypes, 'WinDLL', lambda *a, **k: SimpleNamespace(SendMessageTimeoutW=Send()))
|
||||
with pytest.raises((RuntimeError, TimeoutError)):
|
||||
native._set_probe_field(123, 1217, 'expected project', tmp_path)
|
||||
record = json.loads((tmp_path/'native-field-readback.jsonl').read_text(encoding='utf-8'))
|
||||
assert record['expected'] == 'expected project' and not record['matched']
|
||||
assert record['control_id'] == 1217 and record['exception']['type']
|
||||
if failure in ('empty', 'mismatch'):
|
||||
assert record['actual'] == ('' if failure == 'empty' else 'other project')
|
||||
if failure in ('set_timeout', 'set_rejected'):
|
||||
assert calls == [0x000C]
|
||||
@@ -0,0 +1,169 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
import pytest
|
||||
|
||||
|
||||
def output(project, database, *, fault=False, busy=False):
|
||||
text = f'Loading project file [{project}].\nChecking if project is in use.\n'
|
||||
if fault:
|
||||
text += (f'Project database [{database}] is inconsistent. It has been manually copied while the iCDB Server was running. '
|
||||
"Please use iCDB Project Backup 'Repair project' functionality to fix this issue.\n")
|
||||
return text + ('Project is in use.\n' if busy else
|
||||
"Project is not in use. Full iCDB Project Backup's functionality is available.\nBackup information loaded correctly.\n")
|
||||
|
||||
|
||||
@pytest.mark.parametrize('fault,busy,status,repair', [
|
||||
(False, False, 'NOT_IN_USE', False), (True, False, 'NOT_IN_USE', True),
|
||||
(True, True, 'IN_USE', False), (False, True, 'IN_USE', False)])
|
||||
def test_native_ownership_and_repair_need_are_separate(tmp_path, fault, busy, status, repair):
|
||||
from cbb_refresh_verify.native_occupancy import classify_inspection
|
||||
project, database = tmp_path/'A.prj', tmp_path/'database'
|
||||
result = classify_inspection(project, database, output(project, database, fault=fault, busy=busy))
|
||||
assert result['status'] == status
|
||||
assert result['repair_required'] is repair
|
||||
|
||||
|
||||
@pytest.mark.parametrize('case', ['progress', 'wrong_project', 'wrong_database', 'stale_verdict', 'generic_repair'])
|
||||
def test_incomplete_or_foreign_output_cannot_authorize_repair(tmp_path, case):
|
||||
from cbb_refresh_verify.native_occupancy import classify_inspection
|
||||
project, database = tmp_path/'A.prj', tmp_path/'database'
|
||||
text = output(project, database, fault=True)
|
||||
if case == 'progress': text = f'Loading project file [{project}].\nChecking if project is in use.'
|
||||
if case == 'wrong_project': text = output(tmp_path/'Other.prj', database, fault=True)
|
||||
if case == 'wrong_database': text = output(project, tmp_path/'other', fault=True)
|
||||
if case == 'stale_verdict': text += 'Checking if project is in use.\n'
|
||||
if case == 'generic_repair': text = output(project, database) + 'Please try to repair the project!'
|
||||
assert classify_inspection(project, database, text)['repair_required'] is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize('fault,busy', [(False, False), (True, False), (False, True)])
|
||||
def test_inspection_mode_only_observes_and_closes_its_tool(tmp_path, monkeypatch, fault, busy):
|
||||
import win32con
|
||||
from test_native_repair import repair_worker_fixture
|
||||
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'active')
|
||||
data = json.loads(job.read_text('utf-8')); data['inspection_only'] = True
|
||||
job.write_text(json.dumps(data), encoding='utf-8')
|
||||
monkeypatch.setattr(ui, '_repair_command', lambda *a: pytest.fail('inspection resolved Repair command'))
|
||||
monkeypatch.setattr(ui, '_native_output', lambda *_: output(data['project'], data['database'], fault=fault, busy=busy))
|
||||
assert ui.repair_worker_main(job) == 0
|
||||
result = json.loads((root/'repair-result.json').read_text('utf-8'))
|
||||
assert result['status'] == ('IN_USE' if busy else 'NOT_IN_USE')
|
||||
assert result['release']['native_exited'] is True
|
||||
assert result['repair_required'] is (fault and not busy)
|
||||
assert actions == [(100, win32con.WM_CLOSE)]
|
||||
|
||||
|
||||
def test_generic_project_backup_shell_is_accepted_as_the_single_target_window(tmp_path, monkeypatch):
|
||||
import json
|
||||
from test_native_repair import repair_worker_fixture
|
||||
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'active')
|
||||
data = json.loads(job.read_text('utf-8')); data['inspection_only'] = True
|
||||
job.write_text(json.dumps(data), encoding='utf-8')
|
||||
monkeypatch.setattr(ui, '_native_output', lambda windows: (
|
||||
f'Loading project file [{data["project"]}].\nChecking if project is in use.\n'
|
||||
"Project is not in use. Full iCDB Project Backup's functionality is available.\n"
|
||||
'Backup information loaded correctly.'))
|
||||
assert ui.repair_worker_main(job) == 0
|
||||
|
||||
|
||||
def test_only_check_never_counts_as_repair_success():
|
||||
from cbb_refresh_verify.icdb_maintenance import maintenance_counts
|
||||
from cbb_refresh_verify.verify_runner import VerifyResult
|
||||
counts = maintenance_counts([VerifyResult('CHECKED', safe_to_continue=True)])
|
||||
assert counts['passed'] == counts['repaired'] == 0
|
||||
assert counts['checked_without_repair'] == 1
|
||||
|
||||
|
||||
def test_cancelled_probe_returns_within_grace_without_killing_native(tmp_path, monkeypatch):
|
||||
from threading import Event
|
||||
from types import SimpleNamespace
|
||||
from cbb_refresh_verify import native_repair as native
|
||||
from cbb_refresh_verify.native_repair import RepairTarget
|
||||
stop = Event(); ticks = [0.0]; actions = []
|
||||
def sleep(seconds):
|
||||
ticks[0] += seconds
|
||||
stop.set()
|
||||
monkeypatch.setattr(native, 'time', SimpleNamespace(monotonic=lambda: ticks[0], sleep=sleep))
|
||||
class Worker:
|
||||
pid = 123
|
||||
def __init__(self, *a): pass
|
||||
def bind_cancellation(self, p): pass
|
||||
def poll(self): return None
|
||||
def request_stop(self): actions.append('cancel')
|
||||
def close(self): actions.append('close_handles')
|
||||
def kill(self): pytest.fail('native owner must not be killed')
|
||||
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', Worker)
|
||||
result = native.run_native_repair(RepairTarget(tmp_path/'A.prj', tmp_path/'database'),
|
||||
tmp_path/'evidence', timeout_seconds=600, inspection_only=True, stop=stop)
|
||||
assert ticks[0] < 6
|
||||
assert result['status'] == 'CANCELLED_UNRELEASED'
|
||||
assert result['release']['safe_to_continue'] is False
|
||||
assert actions[-1] == 'close_handles'
|
||||
|
||||
|
||||
|
||||
|
||||
@pytest.mark.parametrize('extra', ['foreign_session', 'extra_error'])
|
||||
def test_foreign_or_additional_fault_is_never_a_clean_inspection(tmp_path, extra):
|
||||
from cbb_refresh_verify.native_occupancy import classify_inspection
|
||||
project, database = tmp_path/'A.prj', tmp_path/'database'
|
||||
text = output(project, database, fault=extra == 'extra_error')
|
||||
if extra == 'foreign_session':
|
||||
text += ('The last server session on different server machine lost the connection to the database. '
|
||||
'Machine:[SERVER] Path:[C:/Other/Work/database] session:[old]')
|
||||
else:
|
||||
text += 'ERROR: shared symbol database unavailable'
|
||||
assert classify_inspection(project, database, text)['status'] == 'UNCONFIRMED'
|
||||
|
||||
|
||||
def test_unconfirmed_inspection_closes_known_main_at_timeout(tmp_path, monkeypatch):
|
||||
import win32con
|
||||
from test_native_repair import repair_worker_fixture
|
||||
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'active')
|
||||
data = json.loads(job.read_text('utf-8')); data['inspection_only'] = True
|
||||
job.write_text(json.dumps(data), encoding='utf-8')
|
||||
monkeypatch.setattr(ui, '_native_output', lambda *_: 'Unrecognized response')
|
||||
assert ui.repair_worker_main(job) == 1
|
||||
result = json.loads((root/'repair-result.json').read_text('utf-8'))
|
||||
assert result['status'] == 'UNCONFIRMED'
|
||||
assert result['release']['native_exited'] is True
|
||||
assert actions == [(100, win32con.WM_CLOSE)]
|
||||
|
||||
|
||||
def test_directory_scan_honors_cancel_between_entries(tmp_path):
|
||||
from cbb_refresh_verify.scoped_manifest import scan_tree
|
||||
for i in range(10): (tmp_path/f'{i}.dat').touch()
|
||||
calls = []
|
||||
def cancel():
|
||||
calls.append(True)
|
||||
if len(calls) == 3: raise RuntimeError('CANCELLED')
|
||||
with pytest.raises(RuntimeError, match='CANCELLED'):
|
||||
scan_tree(tmp_path, check=cancel)
|
||||
assert len(calls) == 3
|
||||
|
||||
|
||||
def test_cancel_during_final_guard_cannot_launch_native_tool(tmp_path, monkeypatch):
|
||||
from contextlib import contextmanager
|
||||
from test_native_repair import repair_worker_fixture
|
||||
from cbb_refresh_verify.native_repair import RepairTarget
|
||||
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'active')
|
||||
data = json.loads(job.read_text('utf-8'))
|
||||
data['maintenance_context'] = {'library': str(tmp_path/'lib.lmc'), 'block': 'CBB1'}
|
||||
job.write_text(json.dumps(data), encoding='utf-8')
|
||||
calls = []
|
||||
@contextmanager
|
||||
def guard(*a, **kw):
|
||||
calls.append(True)
|
||||
yield {'target': RepairTarget(Path(data['project']), Path(data['database']))}
|
||||
Path(data['cancel_signal']).touch()
|
||||
monkeypatch.setattr('cbb_refresh_verify.maintenance_entry.maintenance_target_guard', guard)
|
||||
monkeypatch.setattr(ui.subprocess, 'Popen', lambda *a, **kw: pytest.fail('late native launch'))
|
||||
assert ui.repair_worker_main(job) == 1
|
||||
assert len(calls) == 1 and not actions
|
||||
|
||||
|
||||
def test_verified_cbb_refusal_is_not_hidden_by_secondary_release_failure():
|
||||
from cbb_refresh_verify.verify_runner import classify_failure_category
|
||||
detail = ('BackAnnotate: Back Annotation is not allowed on verified (or once verified) Reusable Blocks.'
|
||||
'\nPCB_RELEASE_UNCONFIRMED: not released')
|
||||
assert classify_failure_category(detail) == 'CBB_REIMPORT_REQUIRED'
|
||||
+732
-9
@@ -5,6 +5,7 @@ import pytest
|
||||
|
||||
|
||||
def target_fixture(tmp_path):
|
||||
from dataclasses import replace
|
||||
from test_verify_runner import fixture, request
|
||||
from cbb_refresh_verify.native_repair import select_repair_target
|
||||
work = fixture(tmp_path)
|
||||
@@ -13,7 +14,21 @@ def target_fixture(tmp_path):
|
||||
(database/'icdb.dat').write_bytes(b'original damaged database')
|
||||
diagnosis = {'error_code': 'ICDB_REPAIR_REQUIRED', 'machine': 'OLD-PC',
|
||||
'database_path': str(database), 'session': '2026-10-24 08.22.29-10308', 'scope': 'project'}
|
||||
return request(tmp_path), diagnosis, select_repair_target(request(tmp_path), diagnosis)
|
||||
req = replace(request(tmp_path), auto_repair=True)
|
||||
return req, diagnosis, select_repair_target(req, diagnosis)
|
||||
|
||||
|
||||
def complete_native_success(target):
|
||||
"""A complete successful worker result, with no contradictory native state."""
|
||||
return {'status': 'REPAIRED', 'project': str(target.project), 'database': str(target.database),
|
||||
'native_pid': 777,
|
||||
'release': {'native_exited': True, 'safe_to_continue': True, 'addresses': []},
|
||||
'evidence': {'confirmed': True, 'native_backup': True, 'outcome': 'UNCONFIRMED',
|
||||
'failure_complete': False, 'restore_complete': False, 'restored_from_backup': '',
|
||||
'diagnostic_tail': 'Diagnostic: START\nDiagnostic: FINISH',
|
||||
'database_tail': f'{target.database}\niCDBProjectBackupRepair\nIC: Closing project',
|
||||
'restore_tail': '', 'output_tail': '', 'backup_log_tail': '',
|
||||
'log_paths': []}}
|
||||
|
||||
|
||||
def test_repair_target_matches_actual_database_not_guessed_cbb_name(tmp_path):
|
||||
@@ -22,7 +37,7 @@ def test_repair_target_matches_actual_database_not_guessed_cbb_name(tmp_path):
|
||||
assert target.database == target.project.parent/'database'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('change', ['foreign', 'shared', 'missing_session'])
|
||||
@pytest.mark.parametrize('change', ['foreign', 'shared', 'missing_session', 'unknown_scope'])
|
||||
def test_repair_target_rejects_unresolved_or_shared_database(tmp_path, change):
|
||||
from cbb_refresh_verify.native_repair import select_repair_target
|
||||
request, record, target = target_fixture(tmp_path)
|
||||
@@ -30,6 +45,7 @@ def test_repair_target_rejects_unresolved_or_shared_database(tmp_path, change):
|
||||
if change == 'shared':
|
||||
record.update(scope='central_library', database_path=str(tmp_path/'SymbolLibs/__ReusableBlocksSymb'))
|
||||
if change == 'missing_session': record['session'] = ''
|
||||
if change == 'unknown_scope': record['scope'] = 'unknown'
|
||||
with pytest.raises(ValueError):
|
||||
select_repair_target(request, record)
|
||||
|
||||
@@ -134,12 +150,40 @@ def test_automatic_repair_retries_only_once_and_preserves_original_failure(tmp_p
|
||||
calls.append(req)
|
||||
return original
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', verify)
|
||||
monkeypatch.setattr(native_repair, 'attempt_recovery', lambda *a, **kw: {'status':'REPAIRED'})
|
||||
monkeypatch.setattr(native_repair, 'attempt_recovery', lambda *a, **kw: complete_native_success(target))
|
||||
outcome = runner.run_verify(request)
|
||||
assert len(calls) == 2
|
||||
assert outcome.status == 'FAIL'
|
||||
assert outcome.stderr == 'native lost session'
|
||||
assert outcome.recovery_attempts[0]['original_error'] == 'native lost session'
|
||||
assert outcome.recovery_attempts[0]['status'] == 'REPAIR_VALIDATION_FAILED'
|
||||
assert outcome.recovery_attempts[0]['native_status'] == 'REPAIRED'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('text,expected,terminal', [
|
||||
('There is no backup of iCDB.\nRepair project error [Cannot repair the project - there is no backup of missing iCDB].',
|
||||
'MISSING_HEALTHY_BACKUP', True),
|
||||
('Repair project error [Database validation failed].', 'NATIVE_REPAIR_FAILED', True),
|
||||
('Project is in use. Full functionality is unavailable.', 'DATABASE_BUSY', False),
|
||||
('Repairing the project. Diagnostic: START', 'UNCONFIRMED', False),
|
||||
])
|
||||
def test_current_native_output_classifies_failure_and_terminal_evidence(text, expected, terminal):
|
||||
from cbb_refresh_verify.native_repair_ui import classify_repair_evidence
|
||||
result = classify_repair_evidence('', '', '', text)
|
||||
assert result['outcome'] == expected
|
||||
assert result['failure_complete'] is terminal
|
||||
|
||||
|
||||
def test_historical_no_backup_output_replay_is_conclusive_failure():
|
||||
from cbb_refresh_verify.native_repair_ui import classify_repair_evidence
|
||||
# Sanitized actual native Output from the 2026-10-28 no-history fixture.
|
||||
text = ('Repairing the project [<project>/CBB.prj].\n'
|
||||
'Repair backup [repair.zip] created successfully.\n'
|
||||
'The iCDB database is corrupted.\nThere is no backup of iCDB.\n'
|
||||
'Repair project error [Cannot repair the project - there is no backup of missing iCDB].\n'
|
||||
'The project is probably in inconsistent state. Please restore the project from one of previous backups.')
|
||||
result = classify_repair_evidence('', '', '', text)
|
||||
assert result == {'outcome': 'MISSING_HEALTHY_BACKUP', 'failure_complete': True}
|
||||
|
||||
|
||||
@pytest.mark.parametrize('repair_status', ['BLOCKED', 'RESTORED_REVIEW_REQUIRED'])
|
||||
@@ -192,7 +236,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'
|
||||
@@ -209,15 +253,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):
|
||||
@@ -264,3 +308,682 @@ def test_backup_detects_a_file_added_during_the_copy(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(native_repair.shutil, 'copy2', changed)
|
||||
with pytest.raises(OSError, match='REPAIR_BACKUP_CHANGED'):
|
||||
native_repair.backup_project(target, tmp_path/'backup')
|
||||
|
||||
|
||||
def repair_worker_fixture(tmp_path, monkeypatch, scenario):
|
||||
"""Replay native window/log transitions without launching a native client."""
|
||||
from types import SimpleNamespace
|
||||
import win32con, win32gui
|
||||
from cbb_refresh_verify import native_repair_ui as ui, native_repair, mentor_adapter
|
||||
request, diagnosis, target = target_fixture(tmp_path)
|
||||
root = tmp_path/'worker'
|
||||
root.mkdir()
|
||||
job = root/'request.json'
|
||||
job.write_text(json.dumps({'project': str(target.project), 'database': str(target.database),
|
||||
'root': str(root), 'cancel_signal': str(root/'cancel.signal'), 'timeout': 1,
|
||||
'supervisor_pid': 123, 'desktop': 'CbbRepair_test'}))
|
||||
ticks = [0.0]
|
||||
state = {'requested': False, 'confirmed': False, 'closed': False}
|
||||
actions = []
|
||||
monkeypatch.setattr(ui, 'time', SimpleNamespace(monotonic=lambda: ticks[0], time_ns=lambda: 0,
|
||||
sleep=lambda seconds: ticks.__setitem__(0, ticks[0]+seconds)))
|
||||
monkeypatch.setattr(ui, '_current_desktop_name', lambda: 'CbbRepair_test')
|
||||
monkeypatch.setattr(ui, '_repair_command', lambda *_: 32924)
|
||||
monkeypatch.setattr(ui, 'discover_sdd_home', lambda *_: tmp_path, raising=False)
|
||||
monkeypatch.setattr('cbb_refresh_verify.mentor_paths.discover_sdd_home', lambda *_: tmp_path)
|
||||
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.start_supervisor_watchdog', lambda *a, **kw: None)
|
||||
monkeypatch.setattr(native_repair, 'backup_project', lambda *a: {})
|
||||
monkeypatch.setattr(mentor_adapter, 'pcb_processes', lambda: [])
|
||||
monkeypatch.setattr(mentor_adapter, '_process_details', lambda *_: [])
|
||||
monkeypatch.setattr(ui.subprocess, 'Popen', lambda *a, **kw: SimpleNamespace(
|
||||
pid=777, poll=lambda: 0 if state['closed'] and ticks[0] >= .6 else None))
|
||||
terminal = 'Repair project error [Cannot repair the project - there is no backup of missing iCDB].'
|
||||
def output(_):
|
||||
if scenario == 'busy_before': return 'Project is in use. Full functionality is unavailable.'
|
||||
if scenario == 'stale': return terminal
|
||||
if not state['confirmed']: return ''
|
||||
if scenario == 'busy': return 'Repair project error [Project is in use].'
|
||||
if scenario == 'active': return 'Repairing the project. Please wait.'
|
||||
if scenario in {'success', 'restore'}: return 'Repair project finished.'
|
||||
return terminal
|
||||
monkeypatch.setattr(ui, '_native_output', output, raising=False)
|
||||
def windows(_):
|
||||
main = {'hwnd': 100, 'class': 'Afx:main', 'title': 'iCDB Project Backup - '+str(target.project),
|
||||
'enabled': True, 'children': []}
|
||||
if state['confirmed'] and scenario in {'unknown', 'custom_prompt'}:
|
||||
return [main, {'hwnd': 300, 'class': 'CustomDialog' if scenario == 'custom_prompt' else '#32770', 'title': 'Unexpected',
|
||||
'enabled': True, 'children': [{'text': 'Overwrite design?', 'class': 'Button',
|
||||
'id': 1, 'hwnd': 301, 'enabled': True}]}]
|
||||
if state['requested'] and not state['confirmed']:
|
||||
return [main, {'hwnd': 200, 'class': '#32770', 'title': '', 'enabled': True,
|
||||
'children': [{'hwnd': 201, 'class': 'Button', 'id': 1, 'enabled': True,
|
||||
'text': 'The project content will be validated and repaired if necessary.\n'
|
||||
'A project backup will be created before any action take place.\n'
|
||||
'You will be able to revert all changes using that backup.'}]}]
|
||||
return [main]
|
||||
monkeypatch.setattr(ui, '_windows', windows)
|
||||
def post(hwnd, message, *args):
|
||||
actions.append((hwnd, message))
|
||||
if message == win32con.WM_COMMAND: state['requested'] = True
|
||||
if message == win32con.BM_CLICK:
|
||||
state['confirmed'] = True
|
||||
if scenario in {'success', 'restore'}:
|
||||
import zipfile
|
||||
log = target.project.parent/'Log Files/ProjectBackupLog.txt'
|
||||
log.parent.mkdir(parents=True)
|
||||
log.write_text('Successfully created [Project Repair] backup [repair.zip]')
|
||||
archive = target.project.parent/'ProjectBackup/backups/repair.zip'
|
||||
archive.parent.mkdir(parents=True)
|
||||
with zipfile.ZipFile(archive, 'w') as zipped: zipped.writestr('database/icdb.dat', b'backup')
|
||||
logs = {'dbcheck': 'Diagnostic: START\nDiagnostic: FINISH',
|
||||
'log': f'{target.database}\niCDBProjectBackupRepair\nIC: Closing project'}
|
||||
if scenario == 'restore':
|
||||
logs['dbrestore'] = 'iCDB database restored from backup: old.zip\n[0] DONE'
|
||||
for folder, text in logs.items():
|
||||
path = target.database/'cdbsvr'/folder/'new-777/log.txt'
|
||||
path.parent.mkdir(parents=True)
|
||||
path.write_text(text)
|
||||
if scenario == 'address':
|
||||
address = target.database/'cdbsvr/sAddress.adr'
|
||||
address.parent.mkdir(parents=True)
|
||||
address.write_text('owner')
|
||||
if message == win32con.WM_CLOSE: state['closed'] = True
|
||||
monkeypatch.setattr(win32gui, 'PostMessage', post)
|
||||
return ui, root, job, actions
|
||||
|
||||
|
||||
@pytest.mark.parametrize('scenario,expected,closed', [
|
||||
('failed', 'MISSING_HEALTHY_BACKUP', True), ('busy', 'DATABASE_BUSY', False),
|
||||
('unknown', 'UNKNOWN_DIALOG', False), ('custom_prompt', 'UNKNOWN_DIALOG', False),
|
||||
('active', 'TIMEOUT_UNRELEASED', False),
|
||||
('stale', 'TIMEOUT_UNRELEASED', False), ('address', 'MISSING_HEALTHY_BACKUP', False),
|
||||
])
|
||||
def test_native_worker_closes_only_conclusively_failed_idle_tool(tmp_path, monkeypatch, scenario, expected, closed):
|
||||
import win32con
|
||||
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, scenario)
|
||||
assert ui.repair_worker_main(job) == 1
|
||||
result = json.loads((root/'repair-result.json').read_text('utf-8'))
|
||||
assert result['status'] == expected
|
||||
assert result['release']['safe_to_continue'] is closed
|
||||
assert ((100, win32con.WM_CLOSE) in actions) is closed
|
||||
assert actions[:2] == [(100, win32con.WM_COMMAND), (201, win32con.BM_CLICK)]
|
||||
assert bool(result['evidence']['output_tail']) is (scenario != 'stale')
|
||||
if scenario == 'unknown': assert result['unknown_dialogs'][0]['title'] == 'Unexpected'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('scenario,expected', [('success', 'REPAIRED'), ('restore', 'RESTORED_REVIEW_REQUIRED')])
|
||||
def test_native_worker_preserves_success_and_historical_restore_distinction(tmp_path, monkeypatch, scenario, expected):
|
||||
from cbb_refresh_verify.native_repair import RepairTarget, native_success_confirmed
|
||||
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, scenario)
|
||||
assert ui.repair_worker_main(job) == (0 if scenario == 'success' else 1)
|
||||
result = json.loads((root/'repair-result.json').read_text('utf-8'))
|
||||
assert result['status'] == expected
|
||||
assert result['release']['safe_to_continue'] is True
|
||||
assert result['evidence']['native_backup'] is True
|
||||
assert result['evidence']['confirmed'] is (scenario == 'success')
|
||||
assert (root/'native-logs/dbcheck/new-777/log.txt').exists()
|
||||
request = json.loads(job.read_text('utf-8'))
|
||||
target = RepairTarget(Path(request['project']), Path(request['database']))
|
||||
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(encoding='utf-8'))['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
|
||||
result = json.loads((root/'repair-result.json').read_text('utf-8'))
|
||||
assert result['status'] == 'DATABASE_BUSY'
|
||||
assert actions == []
|
||||
assert not result['release']['safe_to_continue']
|
||||
|
||||
|
||||
@pytest.mark.parametrize('readback', ['missing', 'timeout', 'truncated'])
|
||||
def test_unavailable_initial_output_never_requests_or_confirms_repair(tmp_path, monkeypatch, readback):
|
||||
from types import SimpleNamespace
|
||||
from cbb_refresh_verify import native_repair_ui as module
|
||||
actual_read = module._native_output
|
||||
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'active')
|
||||
windows = ui._windows
|
||||
def observe(pid):
|
||||
result = windows(pid)
|
||||
if readback != 'missing':
|
||||
result[0]['children'].append({'hwnd': 400, 'class': 'RichEdit20A'})
|
||||
return result
|
||||
monkeypatch.setattr(ui, '_windows', observe)
|
||||
class Readback:
|
||||
def __call__(self, hwnd, message, length, buffer, flags, timeout, copied):
|
||||
if readback == 'timeout': return 0
|
||||
copied._obj.value = length-1
|
||||
return 1
|
||||
monkeypatch.setattr(ui.ctypes, 'WinDLL', lambda *a, **kw: SimpleNamespace(SendMessageTimeoutW=Readback()))
|
||||
monkeypatch.setattr(ui, '_native_output', actual_read)
|
||||
assert ui.repair_worker_main(job) == 1
|
||||
result = json.loads((root/'repair-result.json').read_text('utf-8'))
|
||||
assert actions == []
|
||||
assert result['status'] == 'TIMEOUT_UNRELEASED'
|
||||
assert result['release']['safe_to_continue'] is False
|
||||
assert json.loads((root/'native-output.json').read_text('utf-8'))['baseline'] is None
|
||||
|
||||
|
||||
def test_initial_output_waits_until_readable_and_accepts_empty_baseline(tmp_path, monkeypatch):
|
||||
import win32con
|
||||
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'active')
|
||||
reads = []
|
||||
def output(_):
|
||||
reads.append(len(reads))
|
||||
if len(reads) <= 2:
|
||||
assert not actions
|
||||
return None
|
||||
return ''
|
||||
monkeypatch.setattr(ui, '_native_output', output)
|
||||
assert ui.repair_worker_main(job) == 1
|
||||
assert actions == [(100, win32con.WM_COMMAND), (201, win32con.BM_CLICK)]
|
||||
assert json.loads((root/'native-output.json').read_text('utf-8'))['baseline'] == ''
|
||||
|
||||
|
||||
def test_invoked_busy_native_result_never_reopens_or_continues_queue(tmp_path, monkeypatch):
|
||||
import win32con
|
||||
from test_verify_runner import request
|
||||
from cbb_refresh_verify import verify_runner as runner, native_repair
|
||||
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'busy')
|
||||
assert ui.repair_worker_main(job) == 1
|
||||
busy = json.loads((root/'repair-result.json').read_text('utf-8'))
|
||||
assert (100, win32con.WM_CLOSE) not in actions
|
||||
assert busy['status'] == 'DATABASE_BUSY' and busy['release']['native_exited'] is False
|
||||
from dataclasses import replace
|
||||
req = replace(request(tmp_path), auto_repair=True)
|
||||
target = json.loads(job.read_text('utf-8'))
|
||||
evidence = tmp_path/'first/result.json'
|
||||
evidence.parent.mkdir()
|
||||
(evidence.parent/'diagnostics').mkdir()
|
||||
(evidence.parent/'diagnostics/icdb-recovery.json').write_text(json.dumps({
|
||||
'error_code': 'ICDB_REPAIR_REQUIRED', 'scope': 'project',
|
||||
'session': 'original-session', 'database_path': target['database']}))
|
||||
opens = []
|
||||
def verify(*a, **kw):
|
||||
opens.append('open')
|
||||
return runner.VerifyResult('FAIL', error_category='ICDB_REPAIR_REQUIRED',
|
||||
safe_to_continue=False, evidence_path=evidence)
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', verify)
|
||||
monkeypatch.setattr(native_repair, 'attempt_recovery', lambda *a, **kw: busy)
|
||||
results = runner.run_batch([req, req], verifier=runner.run_verify)
|
||||
assert opens == ['open']
|
||||
assert results[0].recovery_attempts[0]['status'] == 'DATABASE_BUSY'
|
||||
assert results[0].safe_to_continue is False and results[1].status == 'SKIPPED'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('status,released,scope,expected', [
|
||||
('MISSING_HEALTHY_BACKUP', True, 'project', True),
|
||||
('NATIVE_REPAIR_FAILED', True, 'project', True),
|
||||
('MISSING_HEALTHY_BACKUP', False, 'project', False),
|
||||
('MISSING_HEALTHY_BACKUP', True, 'central_library', False),
|
||||
('MISSING_HEALTHY_BACKUP', True, 'unknown', False),
|
||||
('UNKNOWN_DIALOG', True, 'project', False), ('TIMEOUT_UNRELEASED', True, 'project', False),
|
||||
('DATABASE_BUSY', True, 'project', False),
|
||||
])
|
||||
def test_failed_repair_continues_only_released_project_local_items(
|
||||
tmp_path, monkeypatch, status, released, scope, expected):
|
||||
from cbb_refresh_verify import verify_runner as runner, native_repair
|
||||
request, diagnosis, target = target_fixture(tmp_path)
|
||||
diagnosis['scope'] = scope
|
||||
evidence = tmp_path/'first/result.json'
|
||||
evidence.parent.mkdir()
|
||||
(evidence.parent/'diagnostics').mkdir()
|
||||
(evidence.parent/'diagnostics/icdb-recovery.json').write_text(json.dumps(diagnosis))
|
||||
original = runner.VerifyResult('FAIL', stderr='original session lost', safe_to_continue=False,
|
||||
error_category='ICDB_REPAIR_REQUIRED', error_stage='PCB_STARTING', evidence_path=evidence)
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **kw: original)
|
||||
monkeypatch.setattr(native_repair, 'attempt_recovery', lambda *a, **kw: {
|
||||
'status': status, 'release': {'safe_to_continue': released},
|
||||
'evidence': {'failure_complete': True}, 'project': str(target.project),
|
||||
'database': str(target.database)})
|
||||
result = runner.run_verify(request)
|
||||
assert result.safe_to_continue is expected
|
||||
assert result.status == 'FAIL'
|
||||
assert result.error_stage == 'PCB_STARTING'
|
||||
assert result.stderr.startswith('original session lost')
|
||||
assert status in result.stderr
|
||||
assert result.recovery_attempts[0]['original_stage'] == 'PCB_STARTING'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('validation_status,flag,expected', [
|
||||
('PASS', 'GREEN', True), ('PASS', 'UNKNOWN', False), ('FAIL', 'GREEN', False),
|
||||
])
|
||||
def test_maintenance_counts_require_native_success_then_verify_green(
|
||||
tmp_path, monkeypatch, validation_status, flag, expected):
|
||||
from cbb_refresh_verify import verify_runner as runner, native_repair
|
||||
from cbb_refresh_verify.icdb_maintenance import maintenance_counts
|
||||
request, diagnosis, target = target_fixture(tmp_path)
|
||||
evidence = tmp_path/'first/result.json'
|
||||
evidence.parent.mkdir()
|
||||
(evidence.parent/'diagnostics').mkdir()
|
||||
(evidence.parent/'diagnostics/icdb-recovery.json').write_text(json.dumps(diagnosis))
|
||||
original = runner.VerifyResult('FAIL', stderr='original lost session', safe_to_continue=False,
|
||||
error_category='ICDB_REPAIR_REQUIRED', evidence_path=evidence)
|
||||
evidence.write_text(json.dumps({'stderr': original.stderr}))
|
||||
validated = runner.VerifyResult(validation_status, library_flag=flag,
|
||||
evidence_path=tmp_path/'second.json', safe_to_continue=True)
|
||||
calls = []
|
||||
def verify(req, **kwargs):
|
||||
calls.append(req)
|
||||
return original if len(calls) == 1 else validated
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', verify)
|
||||
monkeypatch.setattr(native_repair, 'attempt_recovery', lambda *a, **kw: complete_native_success(target))
|
||||
result = runner.run_verify(request)
|
||||
assert len(calls) == 2 and calls[1].auto_repair is False
|
||||
assert result.recovery_attempts[0]['validation_passed'] is expected
|
||||
assert maintenance_counts([result])['repaired'] == int(expected)
|
||||
assert original.evidence_path.exists(), 'Original result evidence must remain available'
|
||||
assert json.loads(original.evidence_path.read_text('utf-8'))['stderr'] == 'original lost session'
|
||||
|
||||
|
||||
def test_native_success_without_release_does_not_reopen(tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify import verify_runner as runner, native_repair
|
||||
request, diagnosis, target = target_fixture(tmp_path)
|
||||
evidence = tmp_path/'first/result.json'
|
||||
evidence.parent.mkdir()
|
||||
(evidence.parent/'diagnostics').mkdir()
|
||||
(evidence.parent/'diagnostics/icdb-recovery.json').write_text(json.dumps(diagnosis))
|
||||
calls = []
|
||||
def verify(*args, **kwargs):
|
||||
calls.append('open')
|
||||
return runner.VerifyResult('FAIL', error_category='ICDB_REPAIR_REQUIRED',
|
||||
safe_to_continue=False, evidence_path=evidence)
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', verify)
|
||||
monkeypatch.setattr(native_repair, 'attempt_recovery', lambda *a, **kw: {'status': 'REPAIRED'})
|
||||
result = runner.run_verify(request)
|
||||
assert calls == ['open']
|
||||
assert not result.safe_to_continue
|
||||
assert result.recovery_attempts[0]['status'] == 'UNCONFIRMED'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('obstacle', ['none', 'launcher', 'repair_tool', 'importer', 'address', 'handle', 'shared_handle', 'probe'])
|
||||
def test_repair_release_requires_process_address_and_database_handle_release(tmp_path, monkeypatch, obstacle):
|
||||
import win32con, win32file
|
||||
from cbb_refresh_verify import native_repair, mentor_adapter
|
||||
request, diagnosis, target = target_fixture(tmp_path)
|
||||
monkeypatch.setattr(mentor_adapter, 'pcb_processes', lambda:
|
||||
[(123, 'ExpeditionPCB.exe', 'launcher')] if obstacle == 'launcher' else [])
|
||||
def processes(name):
|
||||
if obstacle == 'probe': raise OSError('process observation unavailable')
|
||||
if ((obstacle == 'repair_tool' and name == 'iCDBProjectBackup.exe')
|
||||
or (obstacle == 'importer' and name == 'ReuseBlockImporter.exe')):
|
||||
return [(456, name, 'unconfirmed owner', 0)]
|
||||
return []
|
||||
monkeypatch.setattr(mentor_adapter, '_process_details', processes)
|
||||
if obstacle == 'address':
|
||||
address = target.database/'cdbsvr/sAddress.adr'
|
||||
address.parent.mkdir(parents=True)
|
||||
address.touch()
|
||||
handle = None
|
||||
try:
|
||||
if obstacle in {'handle', 'shared_handle'}:
|
||||
database_file = target.database/'icdb.dat'
|
||||
if obstacle == 'shared_handle':
|
||||
database_file = request.lmc_file.parent/'SymbolLibs/__ReusableBlocksSymb/icdb.dat'
|
||||
database_file.parent.mkdir(parents=True)
|
||||
database_file.touch()
|
||||
handle = win32file.CreateFile(str(database_file), win32con.GENERIC_READ,
|
||||
0, None, win32con.OPEN_EXISTING, 0, None)
|
||||
result = native_repair.repair_release_state(request, target, complete_native_success(target))
|
||||
assert result['safe_to_continue'] is (obstacle == 'none')
|
||||
finally:
|
||||
if handle: handle.Close()
|
||||
|
||||
|
||||
def test_attempt_persists_distinct_native_failure_and_release_result(tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify import native_repair, mentor_adapter
|
||||
request, diagnosis, target = target_fixture(tmp_path)
|
||||
evidence = tmp_path/'evidence'
|
||||
evidence.mkdir()
|
||||
monkeypatch.setattr(mentor_adapter, 'pcb_processes', lambda: [])
|
||||
monkeypatch.setattr(mentor_adapter, '_process_details', lambda *_: [])
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', lambda *a, **kw: {
|
||||
'status': 'MISSING_HEALTHY_BACKUP', 'project': str(target.project),
|
||||
'database': str(target.database), 'native_pid': 777,
|
||||
'release': {'safe_to_continue': True, 'native_exited': True, 'addresses': []},
|
||||
'evidence': {'failure_complete': True, 'output_tail': 'no backup'}})
|
||||
result = native_repair.attempt_recovery(request, diagnosis, evidence)
|
||||
assert result['status'] == 'MISSING_HEALTHY_BACKUP'
|
||||
assert result['release']['database_exclusive'] is True
|
||||
assert result['release']['safe_to_continue'] is True
|
||||
assert isinstance(result['evidence'], dict)
|
||||
assert result['evidence_path'] == str(evidence/'native-repair')
|
||||
assert json.loads((evidence/'native-repair/attempt.json').read_text('utf-8')) == result
|
||||
|
||||
|
||||
def test_retry_exception_keeps_original_error_and_native_repair_evidence(tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify import verify_runner as runner, native_repair
|
||||
request, diagnosis, target = target_fixture(tmp_path)
|
||||
evidence = tmp_path/'first/result.json'
|
||||
evidence.parent.mkdir()
|
||||
(evidence.parent/'diagnostics').mkdir()
|
||||
(evidence.parent/'diagnostics/icdb-recovery.json').write_text(json.dumps(diagnosis))
|
||||
calls = []
|
||||
def verify(*a, **kw):
|
||||
calls.append('open')
|
||||
if len(calls) > 1: raise OSError('retry infrastructure failure')
|
||||
return runner.VerifyResult('FAIL', stderr='original native error', safe_to_continue=False,
|
||||
error_category='ICDB_REPAIR_REQUIRED', evidence_path=evidence)
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', verify)
|
||||
native_result = complete_native_success(target)
|
||||
native_result['evidence']['diagnostic_tail'] += '\noriginal repair evidence'
|
||||
monkeypatch.setattr(native_repair, 'attempt_recovery', lambda *a, **kw: native_result)
|
||||
result = runner.run_verify(request)
|
||||
assert not result.safe_to_continue
|
||||
assert 'original native error' in result.stderr
|
||||
assert 'retry infrastructure failure' in result.stderr
|
||||
assert 'original repair evidence' in result.recovery_attempts[0]['evidence']['diagnostic_tail']
|
||||
assert result.recovery_attempts[0]['status'] == 'REPAIR_VALIDATION_FAILED'
|
||||
assert json.loads(evidence.read_text('utf-8'))['recovery_attempts']
|
||||
|
||||
|
||||
def test_sanitized_field_open_failure_replay_closes_launcher_then_repairs_once(tmp_path, monkeypatch):
|
||||
from types import SimpleNamespace
|
||||
from dataclasses import replace
|
||||
from test_failed_startup import startup_fixture
|
||||
from cbb_refresh_verify import verify_runner as runner, native_repair, failed_session, mentor_adapter
|
||||
from cbb_refresh_verify.pcb_bridge import wait_for_target_document, PcbBridgeError
|
||||
replay = json.loads((Path(__file__).parent/'fixtures/issue2-lost-session-sanitized.json').read_text('utf-8'))
|
||||
request, diagnosis, target = target_fixture(tmp_path)
|
||||
# Retain a different PRJ name: the field CBB name never authorizes guessing it.
|
||||
block_root = target.project.parent.parent
|
||||
block_root.rename(block_root.with_name(replay['block']))
|
||||
request = replace(request, block_name=replay['block'])
|
||||
project, pcb = runner.preflight(request)
|
||||
diagnosis['database_path'] = str(project.parent/'database')
|
||||
target = native_repair.select_repair_target(request, diagnosis)
|
||||
job, records, messages = startup_fixture(tmp_path, monkeypatch)
|
||||
job.update(project=str(project), pcb=str(pcb), lmc_file=str(request.lmc_file))
|
||||
records[0] = (12, records[0][1], f'ExpeditionPCB.exe "{pcb}" -ReusableCircuit', 11)
|
||||
diagnosis.update(session=replay['diagnosis']['session'], machine='FIELD-PC')
|
||||
(tmp_path/'diagnostics/icdb-recovery.json').write_text(json.dumps(diagnosis))
|
||||
(tmp_path/'dialogs.jsonl').write_text(json.dumps(replay['dialog'])+'\n')
|
||||
ticks = [0.0]
|
||||
monkeypatch.setattr(failed_session, 'time', SimpleNamespace(monotonic=lambda: ticks[0],
|
||||
sleep=lambda seconds: ticks.__setitem__(0, ticks[0]+seconds)))
|
||||
launcher = SimpleNamespace(pid=11, poll=lambda: 0 if ticks[0] >= .4 else None)
|
||||
monkeypatch.setattr(mentor_adapter, 'pcb_processes', lambda: [])
|
||||
trace = []
|
||||
evidence = tmp_path/'result.json'
|
||||
original = runner.VerifyResult('FAIL', stderr=replay['native_error'], safe_to_continue=False,
|
||||
error_category=replay['original_result']['error_category'],
|
||||
error_stage=replay['original_result']['error_stage'], evidence_path=evidence)
|
||||
assert runner.classify_failure_category(original.stderr) == original.error_category
|
||||
assert runner.phase_for_event(replay['observed_events'][2]).value == original.error_stage
|
||||
opens = []
|
||||
def verify(req, **kwargs):
|
||||
opens.append(req)
|
||||
trace.append('open')
|
||||
if len(opens) == 1:
|
||||
errors = iter(('', replay['native_error']))
|
||||
with pytest.raises(PcbBridgeError, match='Repair project'):
|
||||
wait_for_target_document(job, lambda: SimpleNamespace(ActiveDocument=None),
|
||||
process_alive=lambda: True, error_reader=lambda: next(errors),
|
||||
emit=lambda **e: trace.append(e['stage']), sleep=lambda _: None)
|
||||
closed = failed_session.close_failed_startup(job, 12, launcher_process=launcher,
|
||||
emit=lambda **e: trace.append(e['stage']), timeout_seconds=1)
|
||||
assert closed['status'] == 'CLOSED'
|
||||
trace.append('launcher_exited')
|
||||
return original # Repeated field error after one repair must not loop.
|
||||
def repair(actual, root, **kwargs):
|
||||
assert actual == target
|
||||
assert trace[-1] == 'launcher_exited'
|
||||
assert not records and launcher.poll() == 0
|
||||
trace.append('native_repair')
|
||||
return complete_native_success(actual)
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', verify)
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', repair)
|
||||
result = runner.run_verify(request)
|
||||
assert trace == ['open', 'pcb_document_wait', 'startup_close_requested', 'startup_close_result',
|
||||
'launcher_exited', 'native_repair', 'open']
|
||||
assert len(opens) == 2 and opens[1].auto_repair is False
|
||||
assert result.error_stage == 'PCB_STARTING'
|
||||
assert result.recovery_attempts[0]['status'] == 'REPAIR_VALIDATION_FAILED'
|
||||
assert result.recovery_attempts[0]['original_error'] == replay['native_error']
|
||||
assert json.loads((tmp_path/'pre-repair-result.json').read_text('utf-8'))['stderr'] == replay['native_error']
|
||||
|
||||
|
||||
MALFORMED_SUCCESS = [
|
||||
('minimal', None),
|
||||
('native_pid', None), ('native_pid', True),
|
||||
('project', None), ('project', '<other>/CBB.prj'), ('project', []),
|
||||
('database', None), ('database', '<other>/database'),
|
||||
('release', []), ('release', 'released'),
|
||||
('release.native_exited', None), ('release.native_exited', False),
|
||||
('release.native_exited', 1), ('release.native_exited', 'true'),
|
||||
('release.safe_to_continue', 1), ('release.addresses', ['owner']), ('release.addresses', ''),
|
||||
('evidence', None), ('evidence', []), ('evidence', 'confirmed'),
|
||||
('evidence.confirmed', None), ('evidence.confirmed', False),
|
||||
('evidence.confirmed', 1), ('evidence.confirmed', 'true'),
|
||||
('evidence.native_backup', False), ('evidence.failure_complete', True),
|
||||
('evidence.outcome', 'DATABASE_BUSY'), ('evidence.restore_complete', True),
|
||||
('evidence.restored_from_backup', 'old.zip'), ('unknown_dialogs', [{'title': 'Unknown'}]),
|
||||
]
|
||||
|
||||
|
||||
def malformed_native_success(target, key, value):
|
||||
result = complete_native_success(target)
|
||||
if key == 'minimal': return {'status': 'REPAIRED', 'release': {'safe_to_continue': True}}
|
||||
if key in {'project', 'database'} and isinstance(value, str) and value.startswith('<other>'):
|
||||
other = target.project.parent.parent.parent/'other-target'
|
||||
other.mkdir(exist_ok=True)
|
||||
if key == 'project':
|
||||
other = other/'other.prj'
|
||||
other.touch()
|
||||
value = str(other.resolve())
|
||||
if '.' in key:
|
||||
parent, field = key.split('.')
|
||||
result[parent][field] = value
|
||||
else:
|
||||
result[key] = value
|
||||
return result
|
||||
|
||||
|
||||
@pytest.mark.parametrize('key,value', MALFORMED_SUCCESS)
|
||||
def test_malformed_native_success_never_authorizes_release(tmp_path, monkeypatch, key, value):
|
||||
from cbb_refresh_verify import native_repair, mentor_adapter
|
||||
request, diagnosis, target = target_fixture(tmp_path)
|
||||
monkeypatch.setattr(mentor_adapter, 'pcb_processes', lambda: [])
|
||||
monkeypatch.setattr(mentor_adapter, '_process_details', lambda *_: [])
|
||||
result = native_repair.repair_release_state(request, target, malformed_native_success(target, key, value))
|
||||
assert result['safe_to_continue'] is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize('key,value', MALFORMED_SUCCESS)
|
||||
def test_malformed_native_success_never_reopens_or_counts_repaired(tmp_path, monkeypatch, key, value):
|
||||
from cbb_refresh_verify import verify_runner as runner, native_repair
|
||||
from cbb_refresh_verify.icdb_maintenance import maintenance_counts
|
||||
request, diagnosis, target = target_fixture(tmp_path)
|
||||
evidence = tmp_path/'first/result.json'
|
||||
evidence.parent.mkdir()
|
||||
(evidence.parent/'diagnostics').mkdir()
|
||||
(evidence.parent/'diagnostics/icdb-recovery.json').write_text(json.dumps(diagnosis))
|
||||
calls = []
|
||||
def verify(*a, **kw):
|
||||
calls.append('open')
|
||||
if len(calls) == 1:
|
||||
return runner.VerifyResult('FAIL', stderr='original error', error_category='ICDB_REPAIR_REQUIRED',
|
||||
safe_to_continue=False, evidence_path=evidence)
|
||||
return runner.VerifyResult('PASS', library_flag='GREEN', evidence_path=evidence)
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', verify)
|
||||
monkeypatch.setattr(native_repair, 'attempt_recovery', lambda *a, **kw:
|
||||
malformed_native_success(target, key, value))
|
||||
result = runner.run_verify(request)
|
||||
assert calls == ['open']
|
||||
assert result.status == 'FAIL' and result.safe_to_continue is False
|
||||
assert result.recovery_attempts[0]['status'] == 'UNCONFIRMED'
|
||||
assert result.recovery_attempts[0]['release']['safe_to_continue'] is False
|
||||
assert maintenance_counts([result])['repaired'] == 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize('owner', [None, 'iCDBProjectBackup.exe', 'ReuseBlockImporter.exe'])
|
||||
def test_repair_release_uses_real_process_query_contract(tmp_path, monkeypatch, owner):
|
||||
from types import SimpleNamespace
|
||||
import win32com.client
|
||||
from cbb_refresh_verify.native_repair import repair_release_state
|
||||
request, diagnosis, target = target_fixture(tmp_path)
|
||||
queried = []
|
||||
names = ('ExpeditionPCB.exe', 'LibraryManager.exe', 'iCDBProjectBackup.exe',
|
||||
'ReuseBlockImporter.exe', 'cscript.exe')
|
||||
queries = {"SELECT ProcessId,Name,CommandLine,ExecutablePath,ParentProcessId "
|
||||
f"FROM Win32_Process WHERE Name='{name}'": name for name in names}
|
||||
def query(wql):
|
||||
name = queries[wql]
|
||||
queried.append(name)
|
||||
return ([SimpleNamespace(ProcessId='456', ParentProcessId='1', Name=name,
|
||||
ExecutablePath=f'C:\\Mentor\\{name}', CommandLine=f'{name} target')]
|
||||
if name == owner else [])
|
||||
def service(moniker):
|
||||
assert moniker == 'winmgmts:'
|
||||
return SimpleNamespace(ExecQuery=query)
|
||||
monkeypatch.setattr(win32com.client, 'GetObject', service)
|
||||
from cbb_refresh_verify import owner_probe
|
||||
import subprocess
|
||||
monkeypatch.setattr(owner_probe.subprocess, 'run', lambda command, **kw:
|
||||
subprocess.CompletedProcess(command, owner_probe.owner_probe_main(command[-1])))
|
||||
# Keep pcb_processes, _processes, _process_details and release validation real.
|
||||
state = repair_release_state(request, target, complete_native_success(target))
|
||||
assert 'error' not in state
|
||||
assert queried == list(names)
|
||||
assert state['safe_to_continue'] is (owner is None)
|
||||
assert state['remaining_pids'] == ([] if owner is None else [456])
|
||||
assert state['database_exclusive'] is (owner is None)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('name', [
|
||||
'other.exe', 'icdbprojectbackup.exe',
|
||||
"iCDBProjectBackup.exe' OR Name='other.exe",
|
||||
"ReuseBlockImporter.exe' OR Name='other.exe",
|
||||
])
|
||||
def test_repair_process_queries_still_reject_arbitrary_input(monkeypatch, name):
|
||||
import win32com.client
|
||||
from cbb_refresh_verify.mentor_adapter import _process_details
|
||||
monkeypatch.setattr(win32com.client, 'GetObject', lambda *a: pytest.fail('Unsupported name reached WMI'))
|
||||
with pytest.raises(ValueError, match='Unsupported process query'):
|
||||
_process_details(name)
|
||||
|
||||
|
||||
def real_shape_repair_fixture(tmp_path, monkeypatch, scenario, window_state='loads'):
|
||||
"""Replay recorded UI structures through the real bounded Output reader."""
|
||||
from copy import deepcopy
|
||||
from types import SimpleNamespace
|
||||
from cbb_refresh_verify import native_repair_ui
|
||||
actual_output_reader = native_repair_ui._native_output
|
||||
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, scenario)
|
||||
capture = json.loads((Path(__file__).parent/'fixtures/icdb-repair-startup-windows-sanitized.json').read_text('utf-8'))
|
||||
project = json.loads(job.read_text('utf-8'))['project']
|
||||
original_windows, operation_output = ui._windows, ui._native_output
|
||||
polls = []
|
||||
current = {'loading': True}
|
||||
def windows(pid):
|
||||
polls.append(ui.time.monotonic())
|
||||
loading = len(polls) <= 2 or window_state == 'shell_stuck'
|
||||
if loading: assert not actions, 'Startup shell must never receive a command'
|
||||
original = original_windows(pid)
|
||||
main = deepcopy(capture['startup_shell'])
|
||||
current['loading'] = loading
|
||||
if not loading:
|
||||
main['title'] = capture['loaded_title_prefix']+project
|
||||
if window_state == 'wrong_target': main['title'] = capture['loaded_title_prefix']+'C:\\Other\\other.prj'
|
||||
if window_state == 'shell_after_invoke' and actions: main['title'] = 'iCDB Project Backup'
|
||||
auxiliary = deepcopy(capture['auxiliary_windows'])
|
||||
if window_state == 'named_aux': auxiliary[0]['title'] = 'Unrecognized prompt'
|
||||
if window_state == 'lookalike_aux': auxiliary[0]['class'] += '.Other'
|
||||
if window_state == 'duplicate_shell' and loading:
|
||||
auxiliary.append({**deepcopy(main), 'hwnd': 101})
|
||||
if window_state == 'duplicate_target' and not loading:
|
||||
auxiliary.append({**deepcopy(main), 'hwnd': 101})
|
||||
return [main, *original[1:], *auxiliary]
|
||||
class Readback:
|
||||
def __call__(self, hwnd, message, length, buffer, flags, timeout, copied):
|
||||
assert hwnd == 400
|
||||
if window_state == 'missing_output': return 0
|
||||
text = '' if current['loading'] else capture['loaded_output']+operation_output([])
|
||||
if window_state == 'busy_loading': text = 'Project is in use. Full functionality is unavailable.'
|
||||
ui.ctypes.cast(buffer, ui.ctypes.POINTER(ui.ctypes.c_wchar * length)).contents.value = text
|
||||
copied._obj.value = len(text)
|
||||
return 1
|
||||
monkeypatch.setattr(ui, '_windows', windows)
|
||||
monkeypatch.setattr(ui.ctypes, 'WinDLL', lambda *a, **kw: SimpleNamespace(SendMessageTimeoutW=Readback()))
|
||||
monkeypatch.setattr(ui, '_native_output', actual_output_reader)
|
||||
return ui, root, job, actions, polls
|
||||
|
||||
|
||||
@pytest.mark.parametrize('scenario,expected,closed', [
|
||||
('failed', 'MISSING_HEALTHY_BACKUP', True), ('success', 'REPAIRED', True),
|
||||
('restore', 'RESTORED_REVIEW_REQUIRED', True), ('busy', 'DATABASE_BUSY', False),
|
||||
('unknown', 'UNKNOWN_DIALOG', False),
|
||||
])
|
||||
def test_recorded_startup_shell_loads_target_with_input_indicator_windows(
|
||||
tmp_path, monkeypatch, scenario, expected, closed):
|
||||
import win32con
|
||||
ui, root, job, actions, polls = real_shape_repair_fixture(tmp_path, monkeypatch, scenario)
|
||||
assert ui.repair_worker_main(job) == (0 if scenario == 'success' else 1)
|
||||
result = json.loads((root/'repair-result.json').read_text('utf-8'))
|
||||
assert len(polls) >= 4 and polls[2] >= .4
|
||||
assert result['status'] == expected
|
||||
assert actions[:2] == [(100, win32con.WM_COMMAND), (201, win32con.BM_CLICK)]
|
||||
assert ((100, win32con.WM_CLOSE) in actions) is closed
|
||||
assert result['release']['safe_to_continue'] is closed
|
||||
assert 'Project is not in use' in json.loads((root/'native-output.json').read_text('utf-8'))['baseline']
|
||||
|
||||
|
||||
@pytest.mark.parametrize('state,expected', [
|
||||
('shell_stuck', 'TIMEOUT_UNRELEASED'), ('wrong_target', 'UNKNOWN_DIALOG'),
|
||||
('duplicate_shell', 'UNKNOWN_DIALOG'), ('duplicate_target', 'UNKNOWN_DIALOG'),
|
||||
('named_aux', 'UNKNOWN_DIALOG'), ('lookalike_aux', 'UNKNOWN_DIALOG'),
|
||||
('missing_output', 'TIMEOUT_UNRELEASED'), ('busy_loading', 'DATABASE_BUSY'),
|
||||
])
|
||||
def test_recorded_startup_shape_retains_unconfirmed_or_unknown_state(tmp_path, monkeypatch, state, expected):
|
||||
ui, root, job, actions, polls = real_shape_repair_fixture(tmp_path, monkeypatch, 'failed', state)
|
||||
assert ui.repair_worker_main(job) == 1
|
||||
result = json.loads((root/'repair-result.json').read_text('utf-8'))
|
||||
assert result['status'] == expected
|
||||
assert actions == []
|
||||
assert result['release']['safe_to_continue'] is False
|
||||
|
||||
|
||||
def test_generic_shell_after_invocation_is_not_a_startup_exception(tmp_path, monkeypatch):
|
||||
import win32con
|
||||
ui, root, job, actions, polls = real_shape_repair_fixture(tmp_path, monkeypatch, 'failed', 'shell_after_invoke')
|
||||
assert ui.repair_worker_main(job) == 1
|
||||
result = json.loads((root/'repair-result.json').read_text('utf-8'))
|
||||
assert result['status'] == 'UNKNOWN_DIALOG'
|
||||
assert actions == [(100, win32con.WM_COMMAND)]
|
||||
assert result['release']['safe_to_continue'] is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize('verdict,expected', [
|
||||
('', 'UNCONFIRMED'),
|
||||
("Project is not in use. Full iCDB Project Backup's functionality is available.", 'UNCONFIRMED'),
|
||||
('Project is in use. Full functionality is unavailable.', 'DATABASE_BUSY'),
|
||||
])
|
||||
def test_native_usage_check_progress_waits_for_actual_busy_verdict(verdict, expected):
|
||||
from cbb_refresh_verify.native_repair_ui import classify_repair_evidence
|
||||
output = '[2026-11-02 12:00:00] Checking if project is in use.\r\n'
|
||||
output += '[2026-11-02 12:00:00] '+verdict
|
||||
assert classify_repair_evidence('', '', '', output)['outcome'] == expected
|
||||
@@ -0,0 +1,65 @@
|
||||
from cbb_refresh_verify import network_path as network
|
||||
from test_network_path import FakeWNet
|
||||
|
||||
|
||||
def test_releasing_a_keeps_shared_mapping_until_retained_b_releases(monkeypatch):
|
||||
monkeypatch.setattr(network, '_retained_path_leases', {})
|
||||
backend = FakeWNet()
|
||||
original_a = network.LibraryPathLease.acquire(r'\\server\share\A\lib.lmc', backend=backend)
|
||||
b = network.LibraryPathLease.acquire(r'\\server\share\B\lib.lmc', backend=backend)
|
||||
original_a.retain_for_recovery(); b.retain_for_recovery()
|
||||
current_a = network.LibraryPathLease.acquire(r'\\server\share\A\lib.lmc', backend=backend)
|
||||
network.release_retained_path_leases(
|
||||
{'status': 'RELEASE_CONFIRMED', 'library': str(original_a.mentor_path)}, current_lease=current_a)
|
||||
current_a.close()
|
||||
assert backend.cancelled == [] and b._retained_for_recovery and b.created
|
||||
network.release_retained_path_leases({'status': 'RELEASE_CONFIRMED', 'library': str(b.mentor_path)})
|
||||
assert backend.cancelled == [original_a.drive]
|
||||
|
||||
|
||||
def test_unbound_directory_cannot_accept_an_arbitrary_sibling_library_proof(monkeypatch):
|
||||
monkeypatch.setattr(network, '_retained_path_leases', {})
|
||||
lease = network.LibraryPathLease.acquire(r'\\server\share\Folder', backend=FakeWNet())
|
||||
lease.retain_for_recovery()
|
||||
proof = {'status': 'RELEASE_CONFIRMED', 'library': r'\\server\share\Folder\other.lmc'}
|
||||
assert not lease.release_after_recovery(proof)
|
||||
# The library reader binds the selected LMC before retaining a loaded lease.
|
||||
lease.mentor_path = lease.mentor_path/'chosen.lmc'
|
||||
assert not lease.release_after_recovery(proof)
|
||||
proof['library'] = r'\\server\share\Folder\chosen.lmc'
|
||||
assert lease.release_after_recovery(proof)
|
||||
|
||||
|
||||
def test_closing_scanner_lease_preserves_an_unpublished_live_reader_lease():
|
||||
backend = FakeWNet()
|
||||
scanner = network.LibraryPathLease.acquire(r'\\server\share\A\lib.lmc', backend=backend)
|
||||
reader = network.LibraryPathLease.acquire(r'\\server\share\B\lib.lmc', backend=backend)
|
||||
scanner.close()
|
||||
assert not backend.cancelled and reader.created
|
||||
reader.close()
|
||||
assert backend.cancelled == [scanner.drive]
|
||||
|
||||
|
||||
def test_acquire_and_close_do_not_race_before_new_reader_is_registered():
|
||||
from threading import Event, Thread
|
||||
entered, release = Event(), Event()
|
||||
class Backend(FakeWNet):
|
||||
block = False
|
||||
def mappings(self):
|
||||
snapshot = super().mappings()
|
||||
if self.block:
|
||||
entered.set(); assert release.wait(3)
|
||||
return snapshot
|
||||
backend = Backend()
|
||||
scanner = network.LibraryPathLease.acquire(r'\\server\share\A\lib.lmc', backend=backend)
|
||||
backend.block = True
|
||||
leases = []
|
||||
reader = Thread(target=lambda: leases.append(network.LibraryPathLease.acquire(
|
||||
r'\\server\share\B\lib.lmc', backend=backend)))
|
||||
closer = Thread(target=scanner.close)
|
||||
reader.start(); assert entered.wait(1)
|
||||
closer.start(); release.set()
|
||||
reader.join(2); closer.join(2)
|
||||
assert leases and not backend.cancelled and leases[0].created
|
||||
leases[0].close()
|
||||
assert backend.cancelled == [scanner.drive]
|
||||
@@ -12,3 +12,17 @@ def test_spec_packages_adaptive_dialog_rules_and_uia_modules():
|
||||
text = Path('packaging/CbbRefreshVerify.spec').read_text(encoding='utf-8')
|
||||
assert 'dialog_rules.v1.json' in text
|
||||
assert 'pywinauto' in text
|
||||
|
||||
|
||||
def test_spec_analysis_includes_pywin32_timezone_dynamic_import():
|
||||
from types import SimpleNamespace
|
||||
captured = {}
|
||||
def analysis(*args, **kwargs):
|
||||
captured.update(kwargs)
|
||||
return SimpleNamespace(pure=[], scripts=[], binaries=[], zipfiles=[], datas=[])
|
||||
path = Path('packaging/CbbRefreshVerify.spec')
|
||||
namespace = {'SPECPATH': str(path.parent.resolve()), 'Analysis': analysis,
|
||||
'PYZ': lambda *a, **k: None, 'EXE': lambda *a, **k: None,
|
||||
'COLLECT': lambda *a, **k: None}
|
||||
exec(compile(path.read_text(encoding='utf-8'), str(path), 'exec'), namespace)
|
||||
assert 'win32timezone' in captured['hiddenimports']
|
||||
@@ -89,3 +89,15 @@ def test_success_requires_save_and_pcb_exit():
|
||||
assert execution_outcome(save_complete=True, pcb_exited=True)['status'] == 'PASS'
|
||||
assert execution_outcome(save_complete=False, pcb_exited=True)['status'] == 'FAIL'
|
||||
assert execution_outcome(save_complete=True, pcb_exited=False)['status'] == 'FAIL'
|
||||
|
||||
|
||||
def test_connected_com_without_document_remains_startup_and_checks_native_failure(tmp_path):
|
||||
errors = iter(('', 'ICDB_REPAIR_REQUIRED: original lost session'))
|
||||
events = []
|
||||
with pytest.raises(PcbBridgeError) as raised:
|
||||
wait_for_target_document(job(tmp_path), lambda: Application(None), process_alive=lambda: True,
|
||||
error_reader=lambda: next(errors), emit=lambda **e: events.append(e), sleep=lambda _: None)
|
||||
assert raised.value.error_code == 'PCB_STARTUP_FAILED'
|
||||
assert 'original lost session' in str(raised.value)
|
||||
assert [e['stage'] for e in events] == ['pcb_document_wait']
|
||||
assert events[0]['error_code'] == 'PCB_DOCUMENT_NOT_READY'
|
||||
@@ -0,0 +1,51 @@
|
||||
from dataclasses import replace
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from cbb_refresh_verify.dialog_models import WindowSnapshot
|
||||
|
||||
|
||||
def captured():
|
||||
path = Path(__file__).parent/'fixtures/pcb-version-choice-sanitized.json'
|
||||
return WindowSnapshot.from_record(json.loads(path.read_text(encoding='utf-8')))
|
||||
|
||||
|
||||
def test_actual_version_choice_is_descriptive_fatal_without_action(tmp_path):
|
||||
from cbb_refresh_verify.dialog_rules import decide, pcb_version_choice, archive_version_choice
|
||||
from cbb_refresh_verify.post_repair_consent import exact_prompt
|
||||
value = captured()
|
||||
decision = decide(value, ())
|
||||
assert decision.error_code == 'PCB_VERSION_CHOICE_REQUIRED' and not decision.action and not decision.channels
|
||||
assert '2026/9/24 23:06' in decision.detail
|
||||
assert '最后用户保存' in decision.detail and '自动保存' in decision.detail
|
||||
assert not exact_prompt(value)
|
||||
choice = pcb_version_choice(value)
|
||||
assert [c['kind'] for c in choice['candidates']] == ['last_user_saved', 'autosave']
|
||||
assert [c['date'] for c in choice['candidates']] == ['2026/9/24 23:06'] * 2
|
||||
assert [c['selected'] for c in choice['candidates']] == [False, True]
|
||||
path = archive_version_choice(value, tmp_path)
|
||||
record = json.loads(path.read_text(encoding='utf-8'))
|
||||
assert WindowSnapshot.from_record(record['snapshot']) == value
|
||||
assert record['candidates'] == choice['candidates']
|
||||
assert record['automatic_selection'] is False
|
||||
|
||||
|
||||
def test_nonmatching_restoration_remains_blocked_with_original_context():
|
||||
from cbb_refresh_verify.dialog_rules import decide, pcb_version_choice
|
||||
value = replace(captured(), title='Other recovery choice')
|
||||
decision = decide(value, ())
|
||||
assert pcb_version_choice(value) is None
|
||||
assert decision.error_code == 'DATABASE_RECOVERY_REQUIRED' and not decision.action
|
||||
assert 'last user saved' in decision.detail
|
||||
|
||||
|
||||
def test_version_choice_counts_as_pending_review_not_unknown_native_repair():
|
||||
from cbb_refresh_verify.icdb_maintenance import maintenance_counts
|
||||
from cbb_refresh_verify.verify_runner import VerifyResult, classify_failure_category
|
||||
result = VerifyResult('FAIL', error_category='PCB_VERSION_CHOICE_REQUIRED', safe_to_continue=False,
|
||||
recovery_attempts=({'status': 'PCB_VERSION_CHOICE_REQUIRED', 'native_status': 'REPAIRED',
|
||||
'validation_passed': False},))
|
||||
counts = maintenance_counts([result])
|
||||
assert counts['repaired'] == 0 and counts['version_choice_required'] == 1
|
||||
assert counts['repair_unconfirmed'] == 0 and counts['passed'] == 0
|
||||
assert classify_failure_category('PCB_VERSION_CHOICE_REQUIRED: version pending\nPCB_RELEASE_UNCONFIRMED') == 'PCB_VERSION_CHOICE_REQUIRED'
|
||||
@@ -0,0 +1,247 @@
|
||||
"""Local recovery consent boundaries. No native application may be launched."""
|
||||
from dataclasses import replace
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def no_native_launch(monkeypatch):
|
||||
import subprocess, win32process, win32com.client
|
||||
def forbidden(*a, **k): raise AssertionError('native launching forbidden in consent tests')
|
||||
monkeypatch.setattr(subprocess, 'Popen', forbidden)
|
||||
monkeypatch.setattr(win32process, 'CreateProcess', forbidden)
|
||||
monkeypatch.setattr(win32com.client, 'DispatchEx', forbidden)
|
||||
monkeypatch.setattr(win32com.client, 'Dispatch', forbidden)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def context(tmp_path, monkeypatch):
|
||||
from test_native_repair import target_fixture, complete_native_success
|
||||
from cbb_refresh_verify import post_repair_consent as consent
|
||||
request, _, target = target_fixture(tmp_path)
|
||||
request = replace(request, maintenance=True)
|
||||
# Existing fixture contains only required native files and no address.
|
||||
(target.project.parent/'PCB/pcb.prj').write_text('KEY CentralLibrary "old.lmc"\n')
|
||||
monkeypatch.setattr(consent, '_process_records', lambda: [])
|
||||
monkeypatch.setattr('cbb_refresh_verify.native_repair_ui._current_desktop_name', lambda: 'CbbVerify_fixture')
|
||||
proof = consent.PostRepairProof.create(request, target, complete_native_success(target))
|
||||
job = {'root': str(tmp_path/'verify'), 'lmc_file': str(request.lmc_file),
|
||||
'project': str(target.project), 'pcb': str(target.project.parent/'PCB/actual.pcb'),
|
||||
'block_name': request.block_name, 'desktop': 'CbbVerify_fixture', 'supervisor_pid': 55,
|
||||
'interactive_input': False, 'native_lm_verify': False}
|
||||
Path(job['root']).mkdir()
|
||||
job['post_repair_consent'] = proof.for_job(job)
|
||||
return request, target, proof, job
|
||||
|
||||
|
||||
def snapshot():
|
||||
from cbb_refresh_verify.post_repair_consent import PROMPT_TEXT
|
||||
from cbb_refresh_verify.dialog_models import WindowSnapshot, ControlSnapshot, DialogPhase
|
||||
return WindowSnapshot(100, 20, 'ExpeditionPCB.exe', 'pcb', '#32770', 'Expedition PCB',
|
||||
DialogPhase.PCB_STARTING, (
|
||||
ControlSnapshot(106, 6, 'Button', '是(&Y)'), ControlSnapshot(107, 7, 'Button', '否(&N)'),
|
||||
ControlSnapshot(120, 20, 'Static', ''), ControlSnapshot(199, 65535, 'Static', PROMPT_TEXT)))
|
||||
|
||||
|
||||
def test_no_generic_maintenance_flag_can_mint_consent(tmp_path):
|
||||
from cbb_refresh_verify.post_repair_consent import PostRepairProof
|
||||
from test_native_repair import target_fixture, complete_native_success
|
||||
request, _, target = target_fixture(tmp_path)
|
||||
with pytest.raises(ValueError): PostRepairProof.create(request, target, complete_native_success(target))
|
||||
for status in ('RESTORED_REVIEW_REQUIRED', 'UNCONFIRMED', 'FAIL'):
|
||||
result = complete_native_success(target); result['status'] = status
|
||||
with pytest.raises(ValueError): PostRepairProof.create(replace(request, maintenance=True), target, result)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('kind', ['unc', 'network', 'removable', 'reparse'])
|
||||
def test_consent_rejects_nonlocal_or_reparse_paths(context, monkeypatch, kind):
|
||||
from cbb_refresh_verify import post_repair_consent as consent
|
||||
request, _, _, _ = context
|
||||
path = request.lmc_file
|
||||
if kind == 'unc': path = Path(r'\\server\share\library.lmc')
|
||||
monkeypatch.setattr(consent, '_drive_type', lambda path: {'network': 4, 'removable': 2}.get(kind, 3))
|
||||
if kind == 'reparse':
|
||||
original = Path.lstat
|
||||
monkeypatch.setattr(Path, 'lstat', lambda self: SimpleNamespace(st_file_attributes=0x400)
|
||||
if self == path.parent else original(self))
|
||||
with pytest.raises(ValueError, match='LOCAL_FIXED'):
|
||||
consent.require_local_fixed(path)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('obstacle', ['owner', 'address', 'exclusive', 'wrong_target', 'network', 'desktop'])
|
||||
def test_prelaunch_proof_blocks_without_launch(context, monkeypatch, obstacle):
|
||||
import win32file, win32con
|
||||
from cbb_refresh_verify import post_repair_consent as consent
|
||||
_, target, _, job = context
|
||||
handle = None
|
||||
if obstacle == 'owner': monkeypatch.setattr(consent, '_process_records', lambda: [(777, 'viewdraw.exe', '', '', 0)])
|
||||
if obstacle == 'address':
|
||||
p = target.database/'cdbsvr/sAddress.adr'; p.parent.mkdir(parents=True); p.touch()
|
||||
if obstacle == 'exclusive':
|
||||
handle = win32file.CreateFile(str(target.project.parent/'PCB/Layout/LayoutDB.lyt'), win32con.GENERIC_READ,
|
||||
0, None, win32con.OPEN_EXISTING, 0, None)
|
||||
if obstacle == 'wrong_target': job['pcb'] = str(Path(job['pcb']).with_name('other.pcb'))
|
||||
if obstacle == 'network': monkeypatch.setattr(consent, '_drive_type', lambda path: 4)
|
||||
if obstacle == 'desktop': monkeypatch.setattr('cbb_refresh_verify.native_repair_ui._current_desktop_name', lambda: 'Default')
|
||||
try:
|
||||
with pytest.raises((ValueError, OSError)):
|
||||
consent.prepare_launch(job, ['C:/Mentor/common/win32/bin/ExpeditionPCB.exe', job['pcb'], '-ReusableCircuit'])
|
||||
assert not (Path(job['root'])/'post-repair-prelaunch.json').exists()
|
||||
finally:
|
||||
if handle: handle.Close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('pcb_config', ['standard', 'legacy_template'])
|
||||
def test_exact_dialog_after_bound_prelaunch_is_allowed_only_once(context, monkeypatch, pcb_config):
|
||||
from cbb_refresh_verify import post_repair_consent as consent
|
||||
_, _, proof, job = context
|
||||
if pcb_config == 'legacy_template':
|
||||
pcb = Path(job['pcb'])
|
||||
(pcb.parent/'pcb.prj').rename(pcb.parent/'template.prj')
|
||||
pcb.write_text('KEY ProjectFile "../'+Path(job['project']).name+'"\n')
|
||||
command = ['C:/Mentor/common/win32/bin/ExpeditionPCB.exe', job['pcb'], '-ReusableCircuit']
|
||||
consent.prepare_launch(job, command)
|
||||
controller = consent.ConsentController(proof, job)
|
||||
monkeypatch.setattr(consent, '_validate_current_processes', lambda *args: None)
|
||||
calls = []
|
||||
def perform(snap, payload, phase):
|
||||
calls.append(payload)
|
||||
return SimpleNamespace(accepted_controls=(6,), channel='win32_button_click', error_code='', detail='')
|
||||
first = controller.handle(snapshot(), (snapshot(),), target_pid=20, launcher_pid=19,
|
||||
worker_pid=os.getpid(), companion_pids=(), perform=perform)
|
||||
assert first.action_sent and calls[0]['target'] == {'control_id': 6}
|
||||
again = controller.handle(snapshot(), (snapshot(),), target_pid=20, launcher_pid=19,
|
||||
worker_pid=os.getpid(), companion_pids=(), perform=perform)
|
||||
assert not again.action_sent and len(calls) == 1
|
||||
changed = replace(snapshot(), hwnd=101)
|
||||
rejected = controller.handle(changed, (changed,), target_pid=20, launcher_pid=19,
|
||||
worker_pid=os.getpid(), companion_pids=(), perform=perform)
|
||||
assert rejected.error_code == 'DATABASE_RECOVERY_REQUIRED' and len(calls) == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize('change', ['pid', 'phase', 'text', 'button', 'extra', 'proof', 'foreign_owner'])
|
||||
def test_consent_rejects_unbound_or_changed_prompt(context, monkeypatch, change):
|
||||
from cbb_refresh_verify import post_repair_consent as consent
|
||||
from cbb_refresh_verify.dialog_models import DialogPhase, ControlSnapshot
|
||||
_, _, proof, job = context
|
||||
consent.prepare_launch(job, ['C:/Mentor/common/win32/bin/ExpeditionPCB.exe', job['pcb'], '-ReusableCircuit'])
|
||||
controller = consent.ConsentController(proof, job)
|
||||
snap = snapshot()
|
||||
if change == 'pid': snap = replace(snap, pid=99)
|
||||
if change == 'phase': snap = replace(snap, phase=DialogPhase.SAVE)
|
||||
if change == 'text': snap = replace(snap, controls=(*snap.controls[:-1], replace(snap.controls[-1], name='Confirm read/write?')))
|
||||
if change == 'button': snap = replace(snap, controls=(replace(snap.controls[0], enabled=False), *snap.controls[1:]))
|
||||
if change == 'extra': snap = replace(snap, controls=(*snap.controls, ControlSnapshot(300, 99, 'Button', 'Overwrite')))
|
||||
if change == 'proof': (Path(job['root'])/'post-repair-prelaunch.json').write_text('{}')
|
||||
def processes(*a):
|
||||
if change == 'foreign_owner': raise ValueError('unexpected owner')
|
||||
monkeypatch.setattr(consent, '_validate_current_processes', processes)
|
||||
result = controller.handle(snap, (snap,), target_pid=20, launcher_pid=19, worker_pid=os.getpid(),
|
||||
companion_pids=(), perform=lambda *a: pytest.fail('unapproved consent sent'))
|
||||
assert result.error_code == 'DATABASE_RECOVERY_REQUIRED'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('change', ['', 'other_owner', 'target_command', 'launcher_command', 'target_parent',
|
||||
'launcher_parent', 'executable', 'missing_launcher'])
|
||||
def test_current_process_identity_requires_exact_owned_launch_chain(context, monkeypatch, change):
|
||||
from cbb_refresh_verify import post_repair_consent as consent
|
||||
_, _, _, job = context
|
||||
launcher = r'C:\Mentor\common\win32\bin\ExpeditionPCB.exe'
|
||||
worker = r'C:\Mentor\wg\win32\bin\ExpeditionPCB.exe'
|
||||
command = lambda exe: f'"{exe}" "{job["pcb"]}" -ReusableCircuit'
|
||||
rows = [(19, 'ExpeditionPCB.exe', launcher, command(launcher), 18),
|
||||
(20, 'ExpeditionPCB.exe', worker, command(worker), 19)]
|
||||
if change == 'other_owner': rows.append((99, 'viewdraw.exe', 'viewdraw.exe', '', 0))
|
||||
if change == 'target_command': rows[1] = (20, 'ExpeditionPCB.exe', worker, 'other.pcb -ReusableCircuit', 19)
|
||||
if change == 'launcher_command': rows[0] = (19, 'ExpeditionPCB.exe', launcher, 'other.pcb -ReusableCircuit', 18)
|
||||
if change == 'target_parent': rows[1] = (*rows[1][:4], 999)
|
||||
if change == 'launcher_parent': rows[0] = (*rows[0][:4], 999)
|
||||
if change == 'executable': rows[1] = (20, 'ExpeditionPCB.exe', 'C:/unrelated/ExpeditionPCB.exe', command(worker), 19)
|
||||
if change == 'missing_launcher': rows.pop(0)
|
||||
monkeypatch.setattr(consent, '_process_records', lambda: rows)
|
||||
args = (job, {'command': [launcher, job['pcb'], '-ReusableCircuit']}, 20, 19, 18, ())
|
||||
if change:
|
||||
with pytest.raises(ValueError): consent._validate_current_processes(*args)
|
||||
else:
|
||||
consent._validate_current_processes(*args)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('change', ['', 'desktop', 'pid', 'text', 'button', 'generic_action'])
|
||||
def test_agent_revalidates_real_window_before_single_button_message(monkeypatch, change):
|
||||
import win32gui, win32process
|
||||
from cbb_refresh_verify.dialog_agent import DialogActionExecutor
|
||||
from cbb_refresh_verify import native_repair_ui
|
||||
value = snapshot()
|
||||
controls = {c.handle: c for c in value.controls}
|
||||
monkeypatch.setattr(native_repair_ui, '_current_desktop_name', lambda: 'Default' if change == 'desktop' else 'CbbVerify_fixture')
|
||||
monkeypatch.setattr(win32process, 'GetWindowThreadProcessId', lambda hwnd: (1, 99 if change == 'pid' else 20))
|
||||
monkeypatch.setattr(win32gui, 'GetClassName', lambda hwnd: '#32770' if hwnd == 100 else controls[hwnd].class_name)
|
||||
monkeypatch.setattr(win32gui, 'GetWindowText', lambda hwnd: 'Expedition PCB' if hwnd == 100 else
|
||||
'changed prompt' if change == 'text' and hwnd == 199 else controls[hwnd].name)
|
||||
monkeypatch.setattr(win32gui, 'IsWindowVisible', lambda hwnd: True)
|
||||
monkeypatch.setattr(win32gui, 'IsWindowEnabled', lambda hwnd: not (change == 'button' and hwnd == 106))
|
||||
monkeypatch.setattr(win32gui, 'GetDlgCtrlID', lambda hwnd: controls[hwnd].control_id)
|
||||
monkeypatch.setattr(win32gui, 'EnumChildWindows', lambda hwnd, callback, arg:
|
||||
[callback(child, arg) for child in controls])
|
||||
calls = []
|
||||
monkeypatch.setattr(win32gui, 'PostMessage', lambda *args: calls.append(args))
|
||||
payload = {'action': 'post_repair_local_read_write', 'channels': ['win32_button_click'],
|
||||
'target': {'control_id': 6}, 'pid': 20, 'desktop': 'CbbVerify_fixture'}
|
||||
if change == 'generic_action': payload.pop('desktop')
|
||||
result = DialogActionExecutor().perform(value, payload)
|
||||
assert bool(result.accepted_controls) is (not change)
|
||||
assert len(calls) == (0 if change else 1)
|
||||
|
||||
|
||||
def test_ordinary_rule_remains_hard_blocked_for_exact_recovery_prompt():
|
||||
from cbb_refresh_verify.dialog_rules import decide
|
||||
assert decide(snapshot(), ()).error_code == 'DATABASE_RECOVERY_REQUIRED'
|
||||
|
||||
|
||||
def enriched_snapshot():
|
||||
"""Sanitized actual aa-r2 merged Win32/UIA capture (only HWNDs changed)."""
|
||||
from cbb_refresh_verify.dialog_models import ControlSnapshot
|
||||
value = snapshot()
|
||||
native = (replace(value.controls[0], name='是(Y)', automation_id='6', control_type='Button', patterns=('Invoke',)),
|
||||
replace(value.controls[1], name='否(N)', automation_id='7', control_type='Button', patterns=('Invoke',)),
|
||||
replace(value.controls[2], automation_id='20', control_type='Image'),
|
||||
replace(value.controls[3], automation_id='65535', control_type='Text'))
|
||||
return replace(value, controls=(*native,
|
||||
ControlSnapshot(value.hwnd, 0, '#32770', 'Expedition PCB', control_type='Window', patterns=('Window',)),
|
||||
ControlSnapshot(0, 0, '', '', control_type='TitleBar', patterns=('Value',)),
|
||||
ControlSnapshot(0, 0, '', '关闭', control_type='Button', enabled=False, patterns=('Invoke',))))
|
||||
|
||||
|
||||
@pytest.mark.parametrize('change', ['', 'extra_real_child', 'enabled_close', 'titlebar_text', 'other_self'])
|
||||
def test_enriched_native_prompt_ignores_only_observed_uia_chrome(change):
|
||||
from cbb_refresh_verify.post_repair_consent import exact_prompt
|
||||
from cbb_refresh_verify.dialog_models import ControlSnapshot
|
||||
value = enriched_snapshot()
|
||||
if change == 'extra_real_child':
|
||||
value = replace(value, controls=(*value.controls, ControlSnapshot(888, 0, '', '关闭',
|
||||
control_type='Button', enabled=False, patterns=('Invoke',))))
|
||||
if change == 'enabled_close': value = replace(value, controls=(*value.controls[:-1], replace(value.controls[-1], enabled=True)))
|
||||
if change == 'titlebar_text': value = replace(value, controls=(*value.controls[:-2], replace(value.controls[-2], name='unexpected'), value.controls[-1]))
|
||||
if change == 'other_self': value = replace(value, controls=(*value.controls[:4], replace(value.controls[4], handle=999), *value.controls[5:]))
|
||||
assert exact_prompt(value) is (not change)
|
||||
|
||||
|
||||
def test_enriched_prompt_still_reaches_live_native_child_check(monkeypatch):
|
||||
import win32gui, win32process
|
||||
from cbb_refresh_verify.post_repair_consent import validate_action_window
|
||||
from cbb_refresh_verify import native_repair_ui
|
||||
value = enriched_snapshot()
|
||||
native = {c.handle: c for c in value.controls[:4]}
|
||||
monkeypatch.setattr(native_repair_ui, '_current_desktop_name', lambda: 'CbbVerify_fixture')
|
||||
monkeypatch.setattr(win32process, 'GetWindowThreadProcessId', lambda hwnd: (1, 20))
|
||||
monkeypatch.setattr(win32gui, 'IsWindowVisible', lambda hwnd: True)
|
||||
monkeypatch.setattr(win32gui, 'IsWindowEnabled', lambda hwnd: True)
|
||||
monkeypatch.setattr(win32gui, 'GetClassName', lambda hwnd: value.window_class if hwnd == value.hwnd else native[hwnd].class_name)
|
||||
monkeypatch.setattr(win32gui, 'GetWindowText', lambda hwnd: value.title if hwnd == value.hwnd else native[hwnd].name)
|
||||
monkeypatch.setattr(win32gui, 'GetDlgCtrlID', lambda hwnd: native[hwnd].control_id)
|
||||
monkeypatch.setattr(win32gui, 'EnumChildWindows', lambda hwnd, fn, arg: [fn(child, arg) for child in native])
|
||||
validate_action_window(value, {'pid':20, 'desktop':'CbbVerify_fixture'})
|
||||
@@ -12,6 +12,17 @@ def test_phase_duration_uses_worker_monotonic_time_not_delayed_poll_time():
|
||||
assert timer.snapshot()[0]['pcb_startup'] == 132.0
|
||||
|
||||
|
||||
def test_opening_check_ends_startup_and_close_without_starting_integration():
|
||||
timer = RunTimings(clock=lambda: 50.0)
|
||||
timer.record({'stage': 'pcb_launch', 'monotonic_seconds': 10})
|
||||
timer.record({'stage': 'diagnostic_native_loaded_candidate', 'monotonic_seconds': 30})
|
||||
timer.record({'stage': 'diagnostic_complete', 'monotonic_seconds': 38})
|
||||
values, unfinished = timer.snapshot()
|
||||
assert values['pcb_startup'] == 20
|
||||
assert values['diagnostic_close'] == 8
|
||||
assert 'integration' not in values and not unfinished
|
||||
|
||||
|
||||
def test_action_and_save_subtimings_accumulate_real_durations():
|
||||
timer = RunTimings(clock=lambda: 1000.0)
|
||||
timer.record({'stage': 'integration_action_complete', 'action': 'ForwardAnnotate',
|
||||
|
||||
@@ -7,6 +7,10 @@ dialog and not user input. Native Project Backup Repair is restricted to an
|
||||
owned private desktop/PID, a resolved resource command and an exact PRJ.
|
||||
"""
|
||||
from pathlib import Path
|
||||
import ast
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
SOURCE_ROOT = Path(__file__).resolve().parents[1]/'src'/'cbb_refresh_verify'
|
||||
|
||||
@@ -104,9 +108,45 @@ def test_desktop_worker_close_kills_unbound_worker_tree():
|
||||
assert 'self.kill()' in text
|
||||
|
||||
|
||||
def _without_authorized_checkpoint_cleanup(text):
|
||||
"""Exempt exact protocol-checkpoint callsites, never the whole module."""
|
||||
tree = ast.parse(text)
|
||||
parents = {child: parent for parent in ast.walk(tree) for child in ast.iter_child_nodes(parent)}
|
||||
allowed = {('LibraryLock', '_exit_owned'): 'marker', ('LibraryLock', '__enter__'): 'marker',
|
||||
('release_retained_library',): 'checkpoint'}
|
||||
used, spans = set(), []
|
||||
for call in ast.walk(tree):
|
||||
if not (isinstance(call, ast.Call) and isinstance(call.func, ast.Attribute)
|
||||
and call.func.attr == 'unlink' and isinstance(call.func.value, ast.Name) and not call.args):
|
||||
continue
|
||||
scope, parent = [], parents.get(call)
|
||||
while parent is not None:
|
||||
if isinstance(parent, (ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)):
|
||||
scope.insert(0, parent.name)
|
||||
parent = parents.get(parent)
|
||||
scope = tuple(scope)
|
||||
if scope in used or allowed.get(scope) != call.func.value.id:
|
||||
continue
|
||||
expected = ([('missing_ok', True)] if scope == ('LibraryLock', '_exit_owned') else [])
|
||||
keywords = [(k.arg, k.value.value if isinstance(k.value, ast.Constant) else None) for k in call.keywords]
|
||||
if keywords == expected and call.lineno == call.end_lineno:
|
||||
spans.append((call.lineno - 1, call.col_offset, call.end_col_offset))
|
||||
used.add(scope)
|
||||
lines = text.splitlines(keepends=True)
|
||||
for line, start, end in sorted(spans, reverse=True):
|
||||
# AST column offsets are UTF-8 byte offsets.
|
||||
data = lines[line].encode('utf-8')
|
||||
lines[line] = (data[:start] + b'checkpoint_cleanup' + data[end:]).decode('utf-8')
|
||||
return ''.join(lines)
|
||||
|
||||
|
||||
def test_verification_never_deletes_or_moves_library_files():
|
||||
for path in production_sources():
|
||||
text = path.read_text(encoding='utf-8')
|
||||
if path == SOURCE_ROOT/'library_lock.py':
|
||||
# Approved runtime JSON lifecycle only. Actual sidecar/engineering
|
||||
# protection is also exercised against real files below.
|
||||
text = _without_authorized_checkpoint_cleanup(text)
|
||||
for operation in ('os.remove', '.unlink('):
|
||||
assert operation not in text, f'{path.name} 不得删除/移动中心库文件'
|
||||
adapter = (SOURCE_ROOT/'mentor_adapter.py').read_text(encoding='utf-8')
|
||||
@@ -116,3 +156,55 @@ def test_verification_never_deletes_or_moves_library_files():
|
||||
# cdbsvr address advertisement; stable CBB content remains untouched.
|
||||
assert 'shutil.move' not in adapter
|
||||
assert "sAddress.adr" in adapter
|
||||
|
||||
|
||||
def test_checkpoint_cleanup_exception_does_not_allow_other_deletions():
|
||||
source = '''
|
||||
class LibraryLock:
|
||||
def _exit_owned(self):
|
||||
marker.unlink(missing_ok=True)
|
||||
self.path.unlink()
|
||||
def release_retained_library():
|
||||
checkpoint.unlink()
|
||||
os.remove('lib.lmc')
|
||||
def other_operation():
|
||||
marker.unlink(missing_ok=True)
|
||||
'''
|
||||
checked = _without_authorized_checkpoint_cleanup(source)
|
||||
assert 'self.path.unlink()' in checked and 'os.remove(' in checked
|
||||
assert checked.count('marker.unlink(missing_ok=True)') == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize('replacement', ['', 'malformed', 'foreign_lease'])
|
||||
def test_guard_cleanup_only_removes_current_validated_checkpoint(tmp_path, replacement):
|
||||
from cbb_refresh_verify import library_lock as locks
|
||||
library = tmp_path/'library.lmc'
|
||||
protected = {library: b'LMC engineering', tmp_path/'icdb.dat': b'schematic engineering',
|
||||
tmp_path/'LayoutDB.lyt': b'layout engineering', tmp_path/'ordinary.json': b'ordinary data'}
|
||||
for path, data in protected.items(): path.write_bytes(data)
|
||||
lease = locks.LibraryLock(library)
|
||||
lease.__enter__()
|
||||
marker = locks.blocker_path(library)
|
||||
try:
|
||||
if replacement:
|
||||
if replacement == 'malformed':
|
||||
data = b'ordinary file replacing a checkpoint'
|
||||
else:
|
||||
record = json.loads(marker.read_text(encoding='utf-8'))
|
||||
record['lease_id'] = '0' * 32
|
||||
data = json.dumps(record).encode('utf-8')
|
||||
marker.write_bytes(data)
|
||||
with pytest.raises(locks.LibraryBusy): lease.__exit__(None, None, None)
|
||||
assert marker.read_bytes() == data
|
||||
with pytest.raises(locks.LibraryBusy):
|
||||
with locks.LibraryLock(library): pass
|
||||
else:
|
||||
lease.__exit__(None, None, None)
|
||||
assert not marker.exists()
|
||||
assert lease.path.is_file() # The uploader's actual exclusive sidecar is never deleted.
|
||||
assert all(path.read_bytes() == data for path, data in protected.items())
|
||||
finally:
|
||||
# This test never launches native owners; release only its retained fake lease.
|
||||
with locks._guard:
|
||||
owner = locks._owners.pop(lease.key, None)
|
||||
if owner: owner['handle'].Close()
|
||||
@@ -8,7 +8,8 @@ from cbb_refresh_verify.runtime_timing import parse_save_progress
|
||||
|
||||
|
||||
@pytest.mark.parametrize('save_ok', [True, False])
|
||||
def test_packaged_vbs_measures_real_save_call_and_preserves_failure_gate(tmp_path, save_ok):
|
||||
@pytest.mark.parametrize('other_document', [True, False])
|
||||
def test_packaged_vbs_measures_real_save_call_and_preserves_failure_gate(tmp_path, save_ok, other_document):
|
||||
# Execute the real helper in its target 32-bit host. Only external COM
|
||||
# object creation is replaced; Save/Validate/Close order and timers are real.
|
||||
script = Path(__file__).parents[1] / 'src/cbb_refresh_verify/save_verified_block.vbs'
|
||||
@@ -39,14 +40,20 @@ Class FakeDoc
|
||||
IsSaved = True
|
||||
End Function
|
||||
Public Function Close(saveChanges)
|
||||
closedDoc = True
|
||||
Close = True
|
||||
End Function
|
||||
End Class
|
||||
Class FakeApp
|
||||
Public Property Get ActiveDocument
|
||||
Set ActiveDocument = New FakeDoc
|
||||
If closedDoc And Not OTHER_DOCUMENT Then
|
||||
Set ActiveDocument = Nothing
|
||||
Else
|
||||
Set ActiveDocument = New FakeDoc
|
||||
End If
|
||||
End Property
|
||||
Public Sub Quit()
|
||||
WScript.Echo "TEST_QUIT"
|
||||
End Sub
|
||||
End Class
|
||||
Class FakeLic
|
||||
@@ -55,7 +62,8 @@ Class FakeLic
|
||||
End Function
|
||||
End Class
|
||||
'''
|
||||
source = source.replace('Option Explicit', 'Option Explicit\n' + classes.replace('SAVE_RETURN', str(save_ok)))
|
||||
source = source.replace('Option Explicit', 'Option Explicit\nDim closedDoc\n'
|
||||
+ classes.replace('SAVE_RETURN', str(save_ok)).replace('OTHER_DOCUMENT', str(other_document)))
|
||||
source = source.replace('GetObject(, "MGCPCB.Application")', 'New FakeApp')
|
||||
source = source.replace('CreateObject("MGCPCBAutomationLicensing.Application")', 'New FakeLic')
|
||||
harness = tmp_path/'save_harness.vbs'
|
||||
@@ -66,11 +74,13 @@ End Class
|
||||
parsed = parse_save_progress(completed.stdout)
|
||||
assert parsed['timings_seconds']['save'] >= .08
|
||||
if save_ok:
|
||||
assert completed.returncode == 0, completed.stderr
|
||||
assert completed.returncode == (10 if other_document else 0), completed.stderr
|
||||
assert 'SAVE_OK' in parsed['markers']
|
||||
assert 'CLOSE_OK' in parsed['markers']
|
||||
assert parsed['timings_seconds']['post_save_check'] >= 0
|
||||
assert parsed['timings_seconds']['close'] >= 0
|
||||
assert ('TEST_QUIT' in completed.stdout) is (not other_document)
|
||||
assert ('APP_RETAINED_OTHER_DOCUMENT' in completed.stdout) is other_document
|
||||
else:
|
||||
assert completed.returncode == 4, completed.stderr
|
||||
assert 'SAVE_OK' not in parsed['markers']
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Foreign PCB windows must not become this scan's evidence or cleanup targets."""
|
||||
from dataclasses import replace
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.mark.parametrize('suffix,flag', [('.backup', '-ReusableCircuit'), ('', '-ReusableCircuitOther')])
|
||||
def test_reusable_pcb_binding_requires_exact_path_and_switch(tmp_path, suffix, flag):
|
||||
from cbb_refresh_verify.mentor_adapter import is_reusable_circuit_pcb
|
||||
pcb = tmp_path/'Board.pcb'
|
||||
assert not is_reusable_circuit_pcb('C:/Mentor/ExpeditionPCB.exe',
|
||||
f'ExpeditionPCB.exe "{pcb}{suffix}" {flag}', pcb)
|
||||
|
||||
|
||||
def test_agent_roundtrip_applies_pid_scope_and_rejects_window_changed_to_foreign_owner(tmp_path):
|
||||
from test_dialog_agent import running_protocol, snapshot, FakeExecutor
|
||||
from cbb_refresh_verify.dialog_models import DialogPhase, stable_fingerprint
|
||||
class Probe:
|
||||
value = snapshot()
|
||||
scopes = []
|
||||
def capture(self, phase, *, pids=None):
|
||||
self.scopes.append(pids)
|
||||
return (self.value,) if self.value.pid in pids else ()
|
||||
def matches_identity(self, expected):
|
||||
return self.value.pid == expected.pid
|
||||
probe, executor = Probe(), FakeExecutor()
|
||||
client, _, thread = running_protocol(tmp_path, probe, executor)
|
||||
try:
|
||||
assert client.observe(DialogPhase.PCB_STARTING, pids={99}) == ()
|
||||
owned = client.observe(DialogPhase.PCB_STARTING, pids={20})[0]
|
||||
probe.value = replace(probe.value, pid=99)
|
||||
result = client.perform(hwnd=owned.hwnd, fingerprint=stable_fingerprint(owned),
|
||||
action={'action': 'confirm', 'channels': ['win32_button_click']}, phase=DialogPhase.PCB_STARTING)
|
||||
assert result.error_code == 'STALE_DIALOG' and not executor.calls
|
||||
finally:
|
||||
client.close(); thread.join(2)
|
||||
|
||||
|
||||
def test_process_watch_polls_bound_handles_without_wmi(monkeypatch):
|
||||
from cbb_refresh_verify import owner_probe
|
||||
from cbb_refresh_verify.pcb_bridge import ProcessWatch
|
||||
monkeypatch.setattr(owner_probe, 'query_owners', lambda *a, **kw: pytest.fail('Polled WMI during COM attach'))
|
||||
with ProcessWatch({os.getpid()}) as watch:
|
||||
assert all(watch.alive() for _ in range(20))
|
||||
@@ -0,0 +1,335 @@
|
||||
"""File-level regressions: complete snapshots, scoped semantic conflicts."""
|
||||
import hashlib
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
|
||||
import pytest
|
||||
|
||||
from cbb_refresh_verify import backup_recovery as recovery
|
||||
|
||||
|
||||
def put(root, relative, data=b'engineering'):
|
||||
path = root / relative
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(data)
|
||||
return path
|
||||
|
||||
|
||||
@pytest.mark.parametrize('relative', [
|
||||
'A.prj', 'PCB/A.pcb', 'PCB/A.dxp', 'database/icdb.dat',
|
||||
'PCB/Layout/LayoutDB.lyt', 'schematic/sheet.1', 'logic/block.1',
|
||||
'symbols/device.sym', 'CES/constraints.ces', 'config/native.cfg',
|
||||
'unknown/new-engineering-format.bin', 'notes.txt',
|
||||
])
|
||||
def test_primary_edits_additions_and_deletions_change_semantics(tmp_path, relative):
|
||||
path = put(tmp_path, relative)
|
||||
before = recovery._manifest(tmp_path)
|
||||
assert before['version'] == 1
|
||||
entry = before['files'][relative]
|
||||
assert entry == {'size': len(b'engineering'),
|
||||
'sha256': hashlib.sha256(b'engineering').hexdigest(), 'scope': 'project'}
|
||||
path.write_bytes(b'changed')
|
||||
assert recovery._manifest(tmp_path) != before
|
||||
path.unlink()
|
||||
assert recovery._manifest(tmp_path) != before
|
||||
put(tmp_path, relative, b'engineering')
|
||||
put(tmp_path, 'additional.dat')
|
||||
assert recovery._manifest(tmp_path) != before
|
||||
|
||||
|
||||
@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',
|
||||
'backups/old/A.prj', 'backup/old/icdb.dat', 'A.prj.bak',
|
||||
'drawing.pdf', 'output/netlist.txt', 'reports/check.txt',
|
||||
])
|
||||
def test_runtime_history_and_generated_content_is_copied_but_not_hashed(tmp_path, relative):
|
||||
source = tmp_path/'source'
|
||||
put(source, 'A.prj')
|
||||
runtime = put(source, relative, b'old')
|
||||
destination = tmp_path/'copy'
|
||||
progress = []
|
||||
manifest = recovery._copy_verified(source, destination, progress=progress.append)
|
||||
assert (destination/relative).read_bytes() == b'old'
|
||||
assert manifest['version'] == 1
|
||||
assert set(manifest['files']) == {'A.prj'}
|
||||
assert progress[-1]['hashed_files'] == 1
|
||||
assert progress[-1]['hashed_bytes'] == len(b'engineering')
|
||||
assert progress[-1]['stage'] == 'copy'
|
||||
runtime.write_bytes(b'new runtime content')
|
||||
put(source, 'logs/new-session.log')
|
||||
assert recovery._manifest(source) == manifest
|
||||
runtime.unlink()
|
||||
assert recovery._manifest(source) == manifest
|
||||
|
||||
|
||||
def test_central_scope_hashes_target_work_cert_root_config_and_shared_dependencies(tmp_path):
|
||||
from cbb_refresh_verify.scoped_manifest import ManifestScope
|
||||
scope = ManifestScope.library('A', 'target.lmc')
|
||||
expected = {
|
||||
'target.lmc': 'library_config',
|
||||
'library.xml': 'library_config',
|
||||
'ReusableBlocksLP/A/Work/A.prj': 'target_work',
|
||||
'ReusableBlocksLP/A/Cert/A.prj': 'target_cert',
|
||||
'SymbolLibs/__ReusableBlocksSymb/icdb.dat': 'shared_dependency',
|
||||
'CellDB/custom.cell': 'shared_dependency',
|
||||
'PartDB/parts.pdb': 'shared_dependency',
|
||||
'NewRequiredDependency/native.bin': 'shared_dependency',
|
||||
}
|
||||
for relative in expected:
|
||||
put(tmp_path, relative)
|
||||
unrelated = put(tmp_path, 'ReusableBlocksLP/B/Work/B.prj')
|
||||
put(tmp_path, 'ReusableBlocksLP/A/Backups/old.prj')
|
||||
put(tmp_path, 'other.lmc')
|
||||
before = recovery._manifest(tmp_path, scope=scope)
|
||||
assert before['scope'] == {'kind': 'library', 'block_name': 'A', 'library_name': 'target.lmc'}
|
||||
assert {p: e['scope'] for p, e in before['files'].items()} == expected
|
||||
unrelated.write_bytes(b'other project changed')
|
||||
put(tmp_path, 'ReusableBlocksLP/C/Work/C.prj')
|
||||
assert recovery._manifest(tmp_path, scope=scope) == before
|
||||
for relative in expected:
|
||||
path = tmp_path/relative
|
||||
path.write_bytes(b'changed')
|
||||
assert recovery._manifest(tmp_path, scope=scope) != before
|
||||
path.write_bytes(b'engineering')
|
||||
destination = tmp_path.parent/(tmp_path.name + '-copy')
|
||||
assert recovery._copy_verified(tmp_path, destination, scope=scope) == before
|
||||
assert (destination/'ReusableBlocksLP/B/Work/B.prj').read_bytes() == b'other project changed'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('relative', ['A.prj', 'database/icdb.dat', 'target.lmc'])
|
||||
def test_corrupted_destination_bytes_are_rejected_and_evidence_is_preserved(tmp_path, monkeypatch, relative):
|
||||
source = tmp_path/'source'
|
||||
put(source, relative)
|
||||
destination = tmp_path/'destination'
|
||||
real_hash = recovery._hash
|
||||
def corrupt_then_hash(path):
|
||||
if path == destination/relative:
|
||||
metadata = path.stat()
|
||||
path.write_bytes(b'X' * metadata.st_size)
|
||||
os.utime(path, ns=(metadata.st_atime_ns, metadata.st_mtime_ns))
|
||||
return real_hash(path)
|
||||
monkeypatch.setattr(recovery, '_hash', corrupt_then_hash)
|
||||
with pytest.raises(OSError):
|
||||
recovery._copy_verified(source, destination)
|
||||
assert (source/relative).read_bytes() == b'engineering'
|
||||
assert (destination/relative).exists()
|
||||
|
||||
|
||||
def test_source_byte_changes_with_preserved_metadata_are_rejected(tmp_path, monkeypatch):
|
||||
source, destination = tmp_path/'source', tmp_path/'destination'
|
||||
primary = put(source, 'A.prj')
|
||||
real_copy = shutil.copy2
|
||||
def copy_then_change_source(src, dst, *args, **kwargs):
|
||||
result = real_copy(src, dst, *args, **kwargs)
|
||||
metadata = primary.stat()
|
||||
primary.write_bytes(b'X' * metadata.st_size)
|
||||
os.utime(primary, ns=(metadata.st_atime_ns, metadata.st_mtime_ns))
|
||||
return result
|
||||
monkeypatch.setattr(shutil, 'copy2', copy_then_change_source)
|
||||
with pytest.raises(OSError):
|
||||
recovery._copy_verified(source, destination)
|
||||
assert (destination/'A.prj').read_bytes() == b'engineering'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('change', ['changed', 'deleted', 'added'])
|
||||
def test_complete_tree_metadata_must_stay_stable_during_copy(tmp_path, monkeypatch, change):
|
||||
source = tmp_path/'source'
|
||||
put(source, 'A.prj')
|
||||
runtime = put(source, 'logs/session.log')
|
||||
destination = tmp_path/'destination'
|
||||
real_copy = shutil.copy2
|
||||
def copy_then_mutate(src, dst, *args, **kwargs):
|
||||
result = real_copy(src, dst, *args, **kwargs)
|
||||
if Path(src).name == 'A.prj':
|
||||
if change == 'changed':
|
||||
runtime.write_bytes(b'changed while copying')
|
||||
elif change == 'deleted':
|
||||
runtime.unlink()
|
||||
else:
|
||||
put(source, 'logs/added.log')
|
||||
return result
|
||||
monkeypatch.setattr(shutil, 'copy2', copy_then_mutate)
|
||||
with pytest.raises(OSError):
|
||||
recovery._copy_verified(source, destination)
|
||||
assert destination.exists()
|
||||
|
||||
|
||||
def test_destination_nonprimary_membership_and_size_are_validated(tmp_path, monkeypatch):
|
||||
source = tmp_path/'source'
|
||||
put(source, 'logs/session.log')
|
||||
destination = tmp_path/'destination'
|
||||
real_copy = shutil.copy2
|
||||
def truncated(src, dst, *args, **kwargs):
|
||||
result = real_copy(src, dst, *args, **kwargs)
|
||||
Path(dst).write_bytes(b'x')
|
||||
return result
|
||||
monkeypatch.setattr(shutil, 'copy2', truncated)
|
||||
with pytest.raises(OSError):
|
||||
recovery._copy_verified(source, destination)
|
||||
|
||||
|
||||
def test_semantic_scan_does_not_visit_runtime_or_unrelated_cbb_trees(tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify.scoped_manifest import ManifestScope
|
||||
scope = ManifestScope.library('A', 'target.lmc')
|
||||
put(tmp_path, 'target.lmc')
|
||||
put(tmp_path, 'ReusableBlocksLP/A/Work/A.prj')
|
||||
put(tmp_path, 'ReusableBlocksLP/B/Work/B.prj')
|
||||
put(tmp_path, 'logs/transient.log')
|
||||
before = recovery._manifest(tmp_path, scope=scope)
|
||||
real_scan = os.scandir
|
||||
def runtime_unavailable(path):
|
||||
# These trees may be actively changing after the successful snapshot.
|
||||
if Path(path) in (tmp_path/'logs', tmp_path/'ReusableBlocksLP/B'):
|
||||
raise OSError('transient runtime/unrelated tree is unavailable')
|
||||
return real_scan(path)
|
||||
monkeypatch.setattr(os, 'scandir', runtime_unavailable)
|
||||
assert recovery._manifest(tmp_path, scope=scope) == before
|
||||
|
||||
|
||||
def test_only_primary_paths_are_read_for_sha256_and_manifest_is_relocatable(tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify.scoped_manifest import ManifestScope
|
||||
scope = ManifestScope.library('A', 'target.lmc')
|
||||
source, destination = tmp_path/'source', tmp_path/'destination'
|
||||
primary = {'target.lmc', 'ReusableBlocksLP/A/Work/A.prj',
|
||||
'SymbolLibs/shared/icdb.dat', 'config.xml'}
|
||||
excluded = {'ReusableBlocksLP/B/Work/B.prj', 'logs/native.log', 'export.pdf',
|
||||
'.target.cbb-upload.lock', 'backup/old/icdb.dat'}
|
||||
for relative in primary | excluded:
|
||||
put(source, relative)
|
||||
real_hash = recovery._hash
|
||||
hashed = []
|
||||
def record_hash(path):
|
||||
root = source if path.is_relative_to(source) else destination
|
||||
relative = path.relative_to(root).as_posix()
|
||||
assert relative in primary, f'Nonprimary content hashed: {relative}'
|
||||
hashed.append(relative)
|
||||
return real_hash(path)
|
||||
monkeypatch.setattr(recovery, '_hash', record_hash)
|
||||
manifest = recovery._copy_verified(source, destination, scope=scope)
|
||||
assert set(hashed) == primary
|
||||
assert recovery._manifest(source, scope=scope) == manifest
|
||||
assert recovery._manifest(destination, scope=scope) == manifest
|
||||
assert {p.relative_to(destination).as_posix() for p in destination.rglob('*') if p.is_file()} == primary | excluded
|
||||
|
||||
|
||||
@pytest.mark.parametrize('block', ['Logs', 'lOgS', 'Temp', 'tEmP', 'Backup', 'bAcKuP', 'Output', 'rEpOrT',
|
||||
'Log Files', 'ProjectBackup', 'Work.before-restore-engineering'])
|
||||
@pytest.mark.parametrize('role', ['Work', 'Cert'])
|
||||
def test_structural_cbb_identity_is_primary_in_semantic_and_copy_manifests(tmp_path, block, role):
|
||||
from cbb_refresh_verify.scoped_manifest import ManifestScope
|
||||
scope = ManifestScope.library(block, 'target.lmc')
|
||||
source, destination = tmp_path/'source', tmp_path/'destination'
|
||||
relative = f'ReusableBlocksLP/{block}/{role}/database/icdb.dat'
|
||||
primary = put(source, relative)
|
||||
runtime = f'ReusableBlocksLP/{block}/{role}/logs/session.txt'
|
||||
put(source, runtime)
|
||||
before = recovery._copy_verified(source, destination, scope=scope)
|
||||
assert set(before['files']) == {relative}
|
||||
assert (destination/runtime).read_bytes() == b'engineering'
|
||||
assert recovery._manifest(source, scope=scope) == before
|
||||
primary.write_bytes(b'concurrent primary edit')
|
||||
assert recovery._manifest(source, scope=scope) != before
|
||||
|
||||
|
||||
@pytest.mark.parametrize('relative', [
|
||||
'SymbolLibs/temp/icdb.dat', 'SymbolLibs/Temp_a/device.sym',
|
||||
'SymbolLibs/Logs/device.sym', 'SymbolLibs/BACKUP/device.sym',
|
||||
'SymbolLibs/temp/cdbsvr/persistent.bin',
|
||||
'ReusableBlocksLP/A/Work/hdl/Logs/design.v',
|
||||
'ReusableBlocksLP/A/Cert/hdl/bAcKuP/design.v',
|
||||
'SymbolLibs/temp/hdl/Backup/design.v', 'SharedDependency/hdl/Logs/design.v',
|
||||
])
|
||||
def test_library_engineering_partition_names_are_not_runtime_categories(tmp_path, relative):
|
||||
from cbb_refresh_verify.scoped_manifest import ManifestScope
|
||||
scope = ManifestScope.library('A', 'target.lmc')
|
||||
source, destination = tmp_path/'source', tmp_path/'destination'
|
||||
primary = put(source, relative)
|
||||
before = recovery._copy_verified(source, destination, scope=scope)
|
||||
assert relative in before['files']
|
||||
assert recovery._manifest(source, scope=scope) == before
|
||||
primary.write_bytes(b'concurrent shared/design edit')
|
||||
assert recovery._manifest(source, scope=scope) != before
|
||||
|
||||
|
||||
@pytest.mark.parametrize('relative', ['hdl/Logs/design.v', 'hdl/Backup/design.v', 'symbols/Temp/device.sym',
|
||||
'hdl/Log Files/design.v', 'hdl/ProjectBackup/backups/design.v',
|
||||
'hdl/Work.before-restore-engineering/design.v', 'database/cdbsvr/persistent.bin'])
|
||||
def test_nested_project_engineering_names_remain_primary(tmp_path, relative):
|
||||
primary = put(tmp_path, relative)
|
||||
before = recovery._manifest(tmp_path)
|
||||
assert relative in before['files']
|
||||
primary.unlink()
|
||||
assert recovery._manifest(tmp_path) != before
|
||||
|
||||
|
||||
@pytest.mark.parametrize('relative', [
|
||||
'ReusableBlocksLP/Logs/Work/Logs.prj',
|
||||
'ReusableBlocksLP/Backup/Cert/Backup.prj',
|
||||
'SymbolLibs/temp/device.sym', 'SharedDependency/hdl/Logs/design.v',
|
||||
])
|
||||
@pytest.mark.parametrize('side', ['source', 'destination'])
|
||||
def test_colliding_engineering_names_cannot_bypass_primary_copy_byte_checks(tmp_path, monkeypatch, relative, side):
|
||||
from cbb_refresh_verify.scoped_manifest import ManifestScope
|
||||
block = relative.split('/')[1] if relative.startswith('ReusableBlocksLP/') else 'A'
|
||||
scope = ManifestScope.library(block, 'target.lmc')
|
||||
source, destination = tmp_path/'source', tmp_path/'destination'
|
||||
put(source, relative)
|
||||
real_copy = shutil.copy2
|
||||
def copy_then_corrupt(src, dst, *args, **kwargs):
|
||||
result = real_copy(src, dst, *args, **kwargs)
|
||||
corrupt = Path(src) if side == 'source' else Path(dst)
|
||||
metadata = corrupt.stat()
|
||||
corrupt.write_bytes(b'X' * metadata.st_size)
|
||||
os.utime(corrupt, ns=(metadata.st_atime_ns, metadata.st_mtime_ns))
|
||||
return result
|
||||
monkeypatch.setattr(shutil, 'copy2', copy_then_corrupt)
|
||||
with pytest.raises(OSError):
|
||||
recovery._copy_verified(source, destination, scope=scope)
|
||||
assert (destination/relative).exists()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('prefix', ['', 'ReusableBlocksLP/Logs/Work/', 'ReusableBlocksLP/Temp/Cert/'])
|
||||
@pytest.mark.parametrize('relative', [
|
||||
'Log Files/ProjectBackupLog.txt', 'ProjectBackup/backups/old.zip',
|
||||
'database/cdbsvr/log/session/text.txt', 'database/cdbsvr/dbcheck/session/text.txt',
|
||||
'PCB/database/cdbsvr/dbrestore/session/text.txt',
|
||||
])
|
||||
def test_known_native_runtime_and_history_locations_are_ignored_contextually(tmp_path, prefix, relative):
|
||||
from cbb_refresh_verify.scoped_manifest import ManifestScope
|
||||
scope = ManifestScope.library(prefix.split('/')[1], 'target.lmc') if prefix else None
|
||||
runtime = put(tmp_path, prefix + relative)
|
||||
before = recovery._manifest(tmp_path, scope=scope)
|
||||
assert not before['files']
|
||||
runtime.write_bytes(b'updated runtime')
|
||||
assert recovery._manifest(tmp_path, scope=scope) == before
|
||||
|
||||
|
||||
@pytest.mark.parametrize('relative', ['SymbolLibs/temp/icdb.dat',
|
||||
'ReusableBlocksLP/Logs/Work/database/icdb.dat'])
|
||||
def test_locked_critical_bytes_in_colliding_names_are_checked_independently(tmp_path, relative):
|
||||
from cbb_refresh_verify.scoped_manifest import ManifestScope
|
||||
source, destination = tmp_path/'source', tmp_path/'destination'
|
||||
put(source, relative)
|
||||
def corrupt_after_copy(event):
|
||||
if event['copied_files'] == event['total_files']:
|
||||
copied = destination/relative
|
||||
metadata = copied.stat()
|
||||
copied.write_bytes(b'X' * metadata.st_size)
|
||||
os.utime(copied, ns=(metadata.st_atime_ns, metadata.st_mtime_ns))
|
||||
with pytest.raises(OSError):
|
||||
recovery._copy_verified(source, destination,
|
||||
scope=ManifestScope.library('Logs', 'target.lmc'), progress=corrupt_after_copy)
|
||||
assert (source/relative).read_bytes() == b'engineering'
|
||||
assert (destination/relative).read_bytes() == b'XXXXXXXXXXX'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('relative', ['SymbolLibs/temp/cdbsvr/log/session/text.txt',
|
||||
'SymbolLibs/Temp_a/cdbsvr/dbcheck/session/text.txt',
|
||||
'CellDB/cdbsvr/dbrestore/session/text.txt'])
|
||||
def test_shared_native_runtime_has_explicit_database_context(tmp_path, relative):
|
||||
from cbb_refresh_verify.scoped_manifest import ManifestScope
|
||||
put(tmp_path, relative)
|
||||
assert not recovery._manifest(tmp_path, scope=ManifestScope.library('A', 'target.lmc'))['files']
|
||||
+10
-10
@@ -499,7 +499,7 @@ def test_parallelism_rejected_for_shared_library(tmp_path):
|
||||
run_batch([], max_workers=2)
|
||||
|
||||
|
||||
def test_timeout_stops_automation_and_blocks_next_item(tmp_path, monkeypatch):
|
||||
def test_timeout_stops_automation_and_allows_retry_when_no_native_owner_remains(tmp_path, monkeypatch):
|
||||
"""A timed-out item must not leave a Mentor process holding the library."""
|
||||
fixture(tmp_path)
|
||||
killed = []
|
||||
@@ -508,9 +508,9 @@ def test_timeout_stops_automation_and_blocks_next_item(tmp_path, monkeypatch):
|
||||
def __init__(self, command, name):
|
||||
self.name = name
|
||||
self.desktop = None
|
||||
def poll(self): return None
|
||||
def poll(self): return self.returncode
|
||||
returncode = None
|
||||
def kill(self): killed.append(True)
|
||||
def kill(self): killed.append(True); self.returncode = 1
|
||||
def wait(self, timeout=5): return 0
|
||||
def close(self): pass
|
||||
|
||||
@@ -521,7 +521,7 @@ def test_timeout_stops_automation_and_blocks_next_item(tmp_path, monkeypatch):
|
||||
|
||||
assert result.status == 'TIMEOUT'
|
||||
assert killed == [True]
|
||||
assert not result.safe_to_continue
|
||||
assert result.safe_to_continue
|
||||
|
||||
|
||||
def test_fatal_dialog_terminates_current_worker_and_cannot_become_pass(tmp_path, monkeypatch):
|
||||
@@ -532,8 +532,8 @@ def test_fatal_dialog_terminates_current_worker_and_cannot_become_pass(tmp_path,
|
||||
desktop = object()
|
||||
returncode = None
|
||||
def __init__(self, command, name): pass
|
||||
def poll(self): return None
|
||||
def kill(self): killed.append(True)
|
||||
def poll(self): return self.returncode
|
||||
def kill(self): killed.append(True); self.returncode = 1
|
||||
def wait(self, timeout=5): return 1
|
||||
def close(self): pass
|
||||
|
||||
@@ -598,8 +598,8 @@ def test_unknown_dialog_writes_snapshot_before_current_item_fails(tmp_path, monk
|
||||
companion_pids = [701]
|
||||
returncode = None
|
||||
def __init__(self, command, name): self.name = name
|
||||
def poll(self): return None
|
||||
def kill(self): killed.append(True)
|
||||
def poll(self): return self.returncode
|
||||
def kill(self): killed.append(True); self.returncode = 1
|
||||
def wait(self, timeout=5): return 1
|
||||
def close(self): pass
|
||||
|
||||
@@ -747,7 +747,7 @@ def test_reserved_design_server_ports_block_the_item_fast(tmp_path):
|
||||
assert result.evidence_path.is_file()
|
||||
|
||||
|
||||
def test_reserved_design_server_ports_block_by_default_before_worker(tmp_path, monkeypatch):
|
||||
def test_reserved_design_server_ports_block_only_in_explicit_strict_mode(tmp_path, monkeypatch):
|
||||
fixture(tmp_path)
|
||||
class FakeWorker:
|
||||
def __init__(self, command, name):
|
||||
@@ -757,7 +757,7 @@ def test_reserved_design_server_ports_block_by_default_before_worker(tmp_path, m
|
||||
def close(self): pass
|
||||
import cbb_refresh_verify.desktop_worker as desktop_worker
|
||||
monkeypatch.setattr(desktop_worker, 'DesktopWorker', FakeWorker)
|
||||
result = run_verify(request(tmp_path), port_check=lambda: (False, '端口区间被系统保留'),
|
||||
result = run_verify(request(tmp_path, strict_port_check=True), port_check=lambda: (False, '端口区间被系统保留'),
|
||||
progress=lambda event: None)
|
||||
assert result.status == 'BLOCKED'
|
||||
assert '保留' in result.stderr
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in new issue
Block a user