fix: complete legacy CBB import recovery and guard late native submission

This commit is contained in:
阿白叔 committed 2026-11-03 16:03:14 +08:00
1 parent d36b6bcad0
commit 7527800128
12 files changed
+326 -25

No files matched your search

+39
View File
@@ -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):
+4 -3
View File
@@ -25,7 +25,7 @@ def test_raw_dispatch_diagnostics_preserve_hresult_and_known_member_ids(tmp_path
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
import sys, os
source = tmp_path/'source/Block.prj'
source.parent.mkdir()
source.write_text('KEY RootBlock "Block"\nKEY PCBDesignPath "PCB/Block.pcb"\n'
@@ -51,7 +51,7 @@ def test_probe_records_dispatch_before_after_import_and_after_source_alignment(t
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}
'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()]
@@ -134,7 +134,8 @@ def test_probe_converts_desktop_pyhandle_before_uia_boundary(tmp_path, monkeypat
raise RuntimeError('integer UIA boundary reached')
monkeypatch.setitem(sys.modules, 'pywinauto', SimpleNamespace(Desktop=Desktop))
app = SimpleNamespace(OnReusableBlocksEditor=lambda: None)
job = {'operation': 'probe_create_add', 'source': str(source), 'name': 'Block',
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)
+9 -1
View File
@@ -26,13 +26,21 @@ def test_layout_based_pcb_without_independent_icdb_directory_is_complete(healthy
assert engineering_identity(source)['top_level_block'] == 'IP101GR'
@pytest.mark.parametrize('missing', ['database/icdb.dat', 'PCB/Layout/LayoutDB.lyt', 'PCB/pcb.prj'])
@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')
+85
View File
@@ -7,6 +7,91 @@ 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},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()
+29
View File
@@ -72,6 +72,24 @@ def test_assets_require_correct_library_references_and_unknown_bytes(project):
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'])
@@ -199,3 +217,14 @@ def test_edif_only_normalizes_root_written_timestamp_preserving_geometry_and_pro
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')