feat: prefer isolated native CLI for component inventory

This commit is contained in:
阿白叔 committed 2026-10-16 23:29:41 +08:00
1 parent 72853900de
commit 0415ecc73c
10 files changed
+629 -1

No files matched your search

+87
View File
@@ -0,0 +1,87 @@
import pytest
from dx_productivity.trial_task_center import native_inventory_protocol as protocol
def report(tmp_path):
path = tmp_path / 'report.txt'
path.write_text('iCDB Ascii Report Generation Date: test\n'
' REPORT FORMAT: FREEFORM\n MODE: HIER BLOCKS\n TEXT LISTS: ON\n'
' SYMBOLS ONLY: OFF\n NETS ONLY: OFF\n USER BLOCKS: NONE\n'
'Block board \tRoot\n'
' Symbol $27I100\tpage MAIN\n\tSymbol name res.1 type Primitive Frozen ForwardPCB \n'
'\tProp Ref Designator R1\n\tProp Part Number OLD\n\tProp Value 10K/NC\n'
'\tPin 1\ttype 1\n\t\tProp Value PIN_VALUE_MUST_NOT_OVERRIDE_COMPONENT\n'
' Symbol IN_PORT\tpage MAIN\n\tSymbol name input.1 type \n'
'Block disconnected \tRoot\n'
' Symbol $28I200\tpage AUX\n\tSymbol name res.1 type Primitive Frozen ForwardPCB \n'
'\tProp Value 20K\n\tProp Ref Designator R2\n\tProp Part Number OLD\n')
return path
def test_offline_full_project_report_includes_disconnected_schematic_and_exact_uid(tmp_path):
path = report(tmp_path)
project = tmp_path / 'source.prj'
result = protocol.read_ascii_discovery(project, path, ('old',))
assert result.sheets == (('board', 'MAIN'), ('disconnected', 'AUX'))
assert [(t.project_path, t.schematic_name, t.sheet_number, t.uid, t.refdes, t.old_part_number, t.old_value)
for t in result.components] == [
(project, 'board', 'MAIN', '$27I100', 'R1', 'OLD', '10K/NC'),
(project, 'disconnected', 'AUX', '$28I200', 'R2', 'OLD', '20K')]
assert result.matched_old_parts == {
('board', 'MAIN'): frozenset({'old'}), ('disconnected', 'AUX'): frozenset({'old'})}
assert result.complete_sheet_manifest is False
@pytest.mark.parametrize('change', ['flat', 'filtered', 'no_properties', 'symbols_only', 'nets_only',
'table_format', 'bad_uid', 'duplicate', 'duplicate_property', 'missing_ref'])
def test_filtered_or_ambiguous_ascii_report_requires_com_fallback(tmp_path, change):
path = report(tmp_path)
text = path.read_text()
substitutions = {
'flat': ('MODE: HIER BLOCKS', 'MODE: FLAT'),
'filtered': ('USER BLOCKS: NONE', 'USER BLOCKS: board'),
'no_properties': ('TEXT LISTS: ON', 'TEXT LISTS: OFF'),
'symbols_only': ('SYMBOLS ONLY: OFF', 'SYMBOLS ONLY: ON'),
'nets_only': ('NETS ONLY: OFF', 'NETS ONLY: ON'),
'table_format': ('REPORT FORMAT: FREEFORM', 'REPORT FORMAT: TABULAR'),
'bad_uid': ('$27I100', 'unknown_uid'),
'duplicate_property': ('\tProp Value 10K/NC', '\tProp Value 10K/NC\n\tProp Value 20K'),
'missing_ref': ('\tProp Ref Designator R1\n', ''),
}
if change == 'duplicate':
text += ' Symbol $28I200\tpage AUX\n\tProp Ref Designator R2\n\tProp Part Number OLD\n\tProp Value 20K\n'
else:
old, new = substitutions[change]
text = text.replace(old, new)
path.write_text(text)
with pytest.raises(protocol.NativeInventoryUnsupported):
protocol.read_ascii_discovery(tmp_path / 'source.prj', path, ('OLD',))
def test_absent_requested_part_returns_empty_inventory_with_available_sheets(tmp_path):
result = protocol.read_ascii_discovery(tmp_path / 'source.prj', report(tmp_path), ('OTHER',))
assert not result.components
assert result.matched_old_parts == {('board', 'MAIN'): frozenset(), ('disconnected', 'AUX'): frozenset()}
def test_component_cache_cannot_substitute_for_complete_page_discovery(tmp_path):
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
from dx_productivity.trial_task_center.quick_run_protocol import ProjectDiscovery
project = tmp_path / 'project/board.prj'
project.parent.mkdir()
project.write_text('project')
preparer = QuickRunPreparer(tmp_path / 'data')
calls = []
def discover(path, parts, *, collect_components=False, **controls):
calls.append(collect_components)
if collect_components:
return protocol.read_ascii_discovery(project, report(tmp_path), parts)
return ProjectDiscovery((('board', 'MAIN'), ('disconnected', 'AUX'), ('empty', 'BLANK')),
{('board', 'MAIN'): frozenset({'old'}), ('disconnected', 'AUX'): frozenset({'old'}),
('empty', 'BLANK'): frozenset()})
preparer._discover_project_sheets = discover
assert len(preparer.collect_inventory(project, ('OLD',))) == 2
full = preparer.discover_project(project, ('OLD',))
assert ('empty', 'BLANK') in full.sheets
assert calls == [True, False]
+159
View File
@@ -0,0 +1,159 @@
import json
from pathlib import Path
from threading import Event
from types import SimpleNamespace
import pytest
from dx_productivity.trial_task_center import native_inventory as runtime
from dx_productivity.trial_task_center.errors import TaskCenterError
def reader_fixture(tmp_path, *, fail_cleanup=False, cancel=False, corrupt=False, timeout=False):
source = tmp_path / 'source' / 'board.prj'
source.parent.mkdir()
source.write_text('SECTION DesignInfo\nKEY FrontEndSnapshot "DxD"\nENDSECTION\n'
'SECTION Board1\nKEY RootBlock "board"\nENDSECTION\n'
'SECTION iCDB\nKEY iCDBDir "database"\nKEY DedicatedServerName ""\nENDSECTION\n')
(source.parent / 'database').mkdir()
(source.parent / 'database/icdb.dat').write_bytes(b'disposable database')
tools = tmp_path / 'bin'
tools.mkdir()
(tools / 'icdb2ascii.exe').touch()
calls, released = [], []
stop = Event()
class Desktop:
cleanup_record = {'desktop_confirmation': {'released': True}}
def __init__(self, name, **kwargs):
self.name = name
def __enter__(self):
return self
def start_process(self, command, **kwargs):
calls.append(command)
options = dict(arg[1:].split('=', 1) for arg in command[1:] if '=' in arg)
snapshot = Path(options.get('prj') or options['project'])
assert snapshot != source
assert (snapshot.parent / 'database/icdb.dat').read_bytes() == b'disposable database'
assert str(source.parent) not in snapshot.read_text()
Path(options['file']).write_text(
(' REPORT FORMAT: TABULAR\n' if corrupt else ' REPORT FORMAT: FREEFORM\n') +
' MODE: HIER BLOCKS\n USER BLOCKS: NONE\n TEXT LISTS: ON\n'
' SYMBOLS ONLY: OFF\n NETS ONLY: OFF\n'
'Block board \tRoot\n Symbol $27I100\tpage MAIN\n'
'\tProp Ref Designator R1\n\tProp Part Number OLD\n\tProp Value 10K\n')
def poll():
if cancel:
stop.set()
return None
return None if timeout else 0
return SimpleNamespace(poll=poll, pid=42)
def close(self):
released.append(True)
if fail_cleanup:
raise OSError('owned desktop remained alive')
reader = runtime.NativeInventoryReader(tmp_path / 'evidence', tool_directory=tools,
desktop_factory=Desktop, temporary_root=tmp_path / 'temporary', timeout=0.02 if timeout else 30)
return source, reader, stop, calls, released
def test_reader_uses_a_disposable_database_and_returns_certified_native_identity(tmp_path):
project, reader, stop, calls, released = reader_fixture(tmp_path)
before = project.read_bytes(), (project.parent / 'database/icdb.dat').read_bytes()
messages = []
result = reader.read(project, ('OLD',), stop_event=stop, on_progress=messages.append)
assert len(calls) == 1 and released == [True]
assert [(c.refdes, c.uid, c.sheet_number) for c in result.components] == [('R1', '$27I100', 'MAIN')]
assert before == (project.read_bytes(), (project.parent / 'database/icdb.dat').read_bytes())
assert not list((tmp_path / 'temporary').iterdir())
record = json.loads(next((tmp_path / 'evidence').rglob('native-inventory.json')).read_text())
assert record['state'] == 'ready' and len(record['tools']) == 1
assert messages
@pytest.mark.parametrize('failure', ['malformed', 'timeout'])
def test_safe_native_failure_allows_com_fallback_only_after_desktop_release(tmp_path, failure):
project, reader, stop, calls, released = reader_fixture(
tmp_path, corrupt=failure == 'malformed', timeout=failure == 'timeout')
assert reader.read(project, ('OLD',), stop_event=stop) is None
assert released == [True]
assert not list((tmp_path / 'temporary').iterdir())
def test_cancellation_waits_for_owned_cleanup_and_never_falls_back(tmp_path):
project, reader, stop, calls, released = reader_fixture(tmp_path, cancel=True)
with pytest.raises(TaskCenterError) as caught:
reader.read(project, ('OLD',), stop_event=stop)
assert caught.value.code == 'operation_cancelled'
assert released == [True] and len(calls) == 1
def test_native_cleanup_failure_blocks_fallback_and_keeps_recovery_evidence(tmp_path):
project, reader, stop, calls, released = reader_fixture(tmp_path, fail_cleanup=True, cancel=True)
with pytest.raises(TaskCenterError) as caught:
reader.read(project, ('OLD',), stop_event=stop)
assert caught.value.code == 'inventory_cleanup'
assert released == [True] and list((tmp_path / 'evidence').rglob('uncertain.flag'))
assert list((tmp_path / 'temporary').iterdir())
def test_marker_write_failure_cannot_turn_uncertain_cleanup_into_a_fallback(tmp_path, monkeypatch):
project, reader, stop, calls, released = reader_fixture(tmp_path, fail_cleanup=True)
original = Path.write_text
def write(path, *args, **kwargs):
if path.name == 'uncertain.flag':
raise PermissionError('marker unavailable')
return original(path, *args, **kwargs)
monkeypatch.setattr(Path, 'write_text', write)
with pytest.raises(TaskCenterError) as caught:
reader.read(project, ('OLD',))
assert caught.value.code == 'inventory_cleanup'
record = json.loads(next((tmp_path / 'evidence').rglob('native-inventory.json')).read_text())
assert record['state'] == 'uncertain'
def test_source_change_during_a_failed_native_call_blocks_fallback(tmp_path, monkeypatch):
project, reader, stop, calls, released = reader_fixture(tmp_path)
def changed_source(*args):
(project.parent / 'database/icdb.dat').write_bytes(b'externally edited')
raise runtime.NativeInventoryUnsupported('native command failed')
monkeypatch.setattr(reader, '_run_tool', changed_source)
with pytest.raises(TaskCenterError) as caught:
reader.read(project, ('OLD',))
assert caught.value.code == 'target_identity'
assert released == [True]
def test_unsupported_project_does_not_launch_any_native_process(tmp_path):
project, reader, stop, calls, released = reader_fixture(tmp_path)
project.write_text(project.read_text() + 'KEY RootBlock "another board"\n')
assert reader.read(project, ('OLD',)) is None
assert calls == [] and released == []
@pytest.mark.parametrize('outcome', ['native', 'fallback', 'cleanup_failure'])
def test_default_inventory_prefers_native_but_never_falls_back_after_uncertain_cleanup(tmp_path, monkeypatch, outcome):
from dx_productivity.trial_task_center import quick_run, project_discovery
from dx_productivity.trial_task_center.quick_run_protocol import ProjectDiscovery
expected = ProjectDiscovery((('board', 'MAIN'),), {('board', 'MAIN'): frozenset()})
events = []
stop = Event()
messages = []
monkeypatch.setattr(project_discovery, 'discover_project', lambda *args, **kwargs: events.append('cad') or expected)
preparer = quick_run.QuickRunPreparer(tmp_path / 'evidence')
progress = messages.append
def read_controlled(project, parts, **controls):
assert controls['stop_event'] is stop and controls['on_progress'] is progress
events.append('native')
if outcome == 'cleanup_failure':
raise TaskCenterError('inventory_cleanup', 'desktop is uncertain')
return expected if outcome == 'native' else None
monkeypatch.setattr(runtime, 'NativeInventoryReader', lambda root: SimpleNamespace(read=read_controlled))
if outcome == 'cleanup_failure':
with pytest.raises(TaskCenterError) as caught:
preparer._discover_project_sheets(tmp_path / 'board.prj', ('OLD',), collect_components=True,
stop_event=stop, on_progress=progress)
assert caught.value.code == 'inventory_cleanup'
else:
assert preparer._discover_project_sheets(tmp_path / 'board.prj', ('OLD',), collect_components=True,
stop_event=stop, on_progress=progress) is expected
assert events == (['native', 'cad'] if outcome == 'fallback' else ['native'])