fix: address PR21 BOM routing and supervision review
Core regression / Python core and release configuration (push) Successful in 19s
Core regression / JavaScript syntax (push) Successful in 4s
Core regression / Python core and release configuration (pull_request) Successful in 17s
Core regression / JavaScript syntax (pull_request) Successful in 3s

This commit is contained in:
阿白叔 committed 2026-11-05 12:42:20 +08:00
1 parent 8b5509d64f
commit 94a873f929
19 files changed
+619 -67

No files matched your search

@@ -0,0 +1,218 @@
"""PR21 routing, source evidence and operation-boundary regressions; no CAD."""
import json
from pathlib import Path
from types import SimpleNamespace
import zipfile
from openpyxl import Workbook, load_workbook
import pytest
from dx_productivity.trial_task_center.bom_import_report import BomImportReport
from dx_productivity.trial_task_center.bom_plan import BOM_HEADERS
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.target_plan import ComponentTarget
from dx_productivity.trial_task_center.workspace_bom import load_sources, route_sources, write_routed_bom
@pytest.fixture
def case(tmp_path):
root = tmp_path / 'projects'
for name in ('BoardA', 'BoardB'):
project = root / name / (name + '.prj')
project.parent.mkdir(parents=True)
project.write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n')
store = TaskStore(tmp_path / 'tasks.db')
service = TaskCenterService(store, configure_logging(tmp_path / 'data'))
tasks = service.create_project_tasks(root)
paths = tuple(service.projects(t.task_id)[0].path for t in tasks)
for task, path in zip(tasks, paths):
store.record_target_inventory(task.task_id, (
ComponentTarget(path, 'MAIN', '1', 'u1', 'R1', 'OLD', '10nF'),))
yield SimpleNamespace(service=service, store=store, tasks=tasks, paths=paths,
runtime=SimpleNamespace(bind_logs=lambda *_: None), root=tmp_path / 'data')
store.close()
def source(path, *, name='BoardA.prj', project='Z:/old/BoardA.prj', row=2):
book = Workbook()
sheet = book.active
sheet.append(BOM_HEADERS)
for _ in range(2, row):
sheet.append([None] * len(BOM_HEADERS))
sheet.append([name, project, 'OLD', 'NEW', 'R1', '', '', '', True, '', True])
book.save(path)
book.close()
return path
def test_renamed_task_template_routes_stale_path_in_multi_project_batch(case, tmp_path):
task = case.tasks[0]
case.service.update_task(task.task_id, name='音频板', note='')
path = case.service.export_bom_template(task.task_id, tmp_path / 'renamed.xlsx')
book = load_workbook(path)
sheet = book.active
sheet['B2'] = 'Z:/moved/BoardA.prj'
sheet['C2'], sheet['D2'], sheet['E2'] = 'OLD', 'NEW', 'R1'
book.save(path)
book.close()
report = case.service.preview_bom_sources(task.task_id, (path,), runtime=case.runtime)
assert report.passed_rows == 1 and report.preview
assert report.preview.projects[0].project_path == case.paths[0]
assert json.loads(report.source_map_path.read_text(encoding='utf-8'))[0]['match_reason'] == 'migrated_task_name'
def test_single_project_blank_path_keeps_legacy_display_name_binding(case, tmp_path):
task_id = case.tasks[0].task_id
case.store._connection.execute('UPDATE tasks SET group_id = NULL WHERE task_id = ?', (task_id,))
path = source(tmp_path / 'blank-path.xlsx', name='display name from another machine', project='')
report = case.service.preview_bom_sources(task_id, (path,), runtime=case.runtime)
assert report.passed_rows == 1 and report.preview
assert json.loads(report.source_map_path.read_text(encoding='utf-8'))[0]['match_reason'] == 'single_project'
def test_duplicate_messages_use_both_original_workbook_coordinates(case, tmp_path):
first = source(tmp_path / 'first.xlsx')
second = source(tmp_path / 'second.xlsx', row=5)
report = case.service.preview_bom_sources(case.tasks[0].task_id, (first, second), runtime=case.runtime)
assert report.preview is None and report.failed_rows == 2
assert [row.source_row for row in report.rows] == [2, 5]
for row in report.rows:
assert 'first.xlsx 第 2 行' in row.reason
assert 'second.xlsx 第 5 行' in row.reason
assert 'Excel 行 2, 3' not in row.reason
def test_import_evidence_is_referenced_exportable_and_discards_bom_copy(case, tmp_path):
from dx_productivity.trial_task_center.diagnostics_bundle import export_diagnostic_bundle
path = source(tmp_path / 'original.xlsx')
report = case.service.preview_bom_sources(case.tasks[0].task_id, (path,), runtime=case.runtime)
mapping = report.source_map_path
assert mapping.is_file()
assert not mapping.with_name('normalized-bom.xlsx').exists()
task_events = case.root / 'tasks' / case.tasks[0].task_id / 'events.jsonl'
assert any(json.loads(line).get('details', {}).get('source_map_path') == str(mapping)
for line in task_events.read_text(encoding='utf-8').splitlines())
bundle = export_diagnostic_bundle(case.root, tmp_path / 'diagnostics.zip')
with zipfile.ZipFile(bundle) as archive:
assert mapping.relative_to(case.root).as_posix() in archive.namelist()
assert not any(name.endswith('.xlsx') for name in archive.namelist())
def test_source_map_has_bounded_existing_history_retention(case, tmp_path):
from dx_productivity.trial_task_center.retention import maintain_quick_run_storage
path = source(tmp_path / 'source.xlsx')
first = case.service.preview_bom_sources(case.tasks[0].task_id, (path,), runtime=case.runtime)
second = case.service.preview_bom_sources(case.tasks[0].task_id, (path,), runtime=case.runtime)
task_root = case.root / 'tasks' / case.tasks[0].task_id
maintain_quick_run_storage(task_root, max_entries=1, min_entries=0)
assert not first.source_map_path.exists()
assert second.source_map_path.is_file()
def test_relative_project_path_is_rejected_before_normalization(tmp_path):
path = source(tmp_path / 'relative.xlsx', project='sub/BoardA.prj')
with pytest.raises(TaskCenterError, match='完整路径'):
load_sources((path,))
def test_failed_source_map_replace_preserves_previous_valid_json(tmp_path, monkeypatch):
import dx_productivity.trial_task_center.batch_resources as resources
path = source(tmp_path / 'source.xlsx')
rows = load_sources((path,))
routes = route_sources(rows, (tmp_path / 'BoardA.prj',))
mapping = tmp_path / 'source-map.json'
mapping.write_text('[{"previous":true}]', encoding='utf-8')
real_replace = resources.os.replace
def deny(source_path, destination_path):
if Path(destination_path).name == 'source-map.json':
raise OSError('controlled disk write failure')
return real_replace(source_path, destination_path)
monkeypatch.setattr(resources.os, 'replace', deny)
with pytest.raises(OSError, match='controlled disk'):
write_routed_bom(tmp_path / 'normalized.xlsx', rows, routes)
assert json.loads(mapping.read_text(encoding='utf-8')) == [{'previous': True}]
assert not list(tmp_path.glob('source-map.json.*.tmp'))
def test_supervised_import_dispatches_before_reading_any_source(case, tmp_path, monkeypatch):
import dx_productivity.trial_task_center.workspace_bom as workspace
case.service._supervised = True
path = source(tmp_path / 'source.xlsx')
monkeypatch.setattr(workspace, 'load_sources', lambda *_a, **_kw: pytest.fail('source read escaped supervisor'))
def supervise(operation, arguments, **controls):
assert operation == 'preview_bom_sources'
assert arguments['sources'] == (path,)
return BomImportReport((), ())
monkeypatch.setattr(case.service, '_supervise', supervise)
assert case.service.preview_bom_sources(case.tasks[0].task_id, (path,)).total_rows == 0
def test_each_source_reports_read_progress_before_inspection(case, tmp_path, monkeypatch):
import dx_productivity.trial_task_center.bom_import_report as inspection
from dx_productivity.trial_task_center.bom_import_state import BomImportPhase
paths = (source(tmp_path / 'first.xlsx'), source(tmp_path / 'second.xlsx', name='BoardB.prj', project='Z:/old/BoardB.prj'))
progress, phases = [], []
original = inspection.inspect_batch
def inspect(*args, **kwargs):
assert any('first.xlsx' in message for message in progress)
assert any('second.xlsx' in message for message in progress)
assert phases[0] is BomImportPhase.READING
return original(*args, **kwargs)
monkeypatch.setattr(inspection, 'inspect_batch', inspect)
report = case.service.preview_bom_sources(case.tasks[0].task_id, paths, runtime=case.runtime,
on_progress=progress.append, on_phase=lambda phase, _: phases.append(phase))
assert report.passed_rows == 2
def test_single_lease_covers_source_read_and_inspection(case, tmp_path, monkeypatch):
import dx_productivity.trial_task_center.workspace_bom as workspace
import dx_productivity.trial_task_center.bom_import_report as inspection
from dx_productivity.trial_task_center.service import _quick_run_lease
checked = []
def assert_busy():
with pytest.raises(TaskCenterError) as failure:
with _quick_run_lease(case.root):
pytest.fail('import operation released its lease')
assert failure.value.code == 'quick_run_busy'
original_load, original_inspect = workspace.load_sources, inspection.inspect_batch
def load(*args, **kwargs):
assert_busy()
checked.append('read')
return original_load(*args, **kwargs)
def inspect(*args, **kwargs):
assert_busy()
checked.append('inspect')
return original_inspect(*args, **kwargs)
monkeypatch.setattr(workspace, 'load_sources', load)
monkeypatch.setattr(inspection, 'inspect_batch', inspect)
report = case.service.preview_bom_sources(case.tasks[0].task_id,
(source(tmp_path / 'source.xlsx'),), runtime=case.runtime)
assert report.passed_rows == 1 and checked == ['read', 'inspect']
with _quick_run_lease(case.root):
pass
def test_duplicate_task_alias_blocks_but_exact_path_wins(case, tmp_path):
from dx_productivity.trial_task_center.workspace_bom import resolve_project
names = dict.fromkeys(case.paths, 'same display name')
assert resolve_project('Z:/old/BoardA.prj', 'same display name', case.paths, project_names=names) is None
assert resolve_project(str(case.paths[0]), 'same display name', case.paths, project_names=names) == case.paths[0]
@pytest.mark.parametrize('name,project,reason', [
('BoardA.prj', '', 'exact_name'),
('', '', 'single_project'),
('BoardA.prj', 'Z:/old/BoardA.prj', 'migrated_exact_name'),
])
def test_source_map_distinguishes_name_migration_from_blank_fallback(case, tmp_path, name, project, reason):
task_id = case.tasks[0].task_id
case.store._connection.execute('UPDATE tasks SET group_id = NULL WHERE task_id = ?', (task_id,))
path = source(tmp_path / 'source.xlsx', name=name, project=project)
report = case.service.preview_bom_sources(task_id, (path,), runtime=case.runtime)
assert report.passed_rows == 1
assert json.loads(report.source_map_path.read_text(encoding='utf-8'))[0]['match_reason'] == reason
@@ -0,0 +1,81 @@
"""Portable XLSX and item Value contracts; no CAD, Qt, or Windows runtime."""
import pytest
from openpyxl import load_workbook
from dx_productivity.trial_task_center.bom_batch import export_template
from dx_productivity.trial_task_center.bom_plan import (
BOM_HEADERS, match_bom_records, read_bom_records, write_bom_template,
)
from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.target_plan import ComponentTarget, TargetPlanRow, compile_target_rules
@pytest.mark.parametrize('with_task', [False, True])
def test_user_template_exposes_editable_value_source_without_inventory(tmp_path, with_task):
store = TaskStore(tmp_path / 'tasks.db')
try:
task_id = None
if with_task:
task_id = store.create_task('Board').task_id
store.sync_projects(task_id, tmp_path, (tmp_path / 'Board.prj',))
path = export_template(store, task_id, tmp_path / 'template.xlsx')
book = load_workbook(path)
try:
sheet = book.active
assert tuple(cell.value for cell in sheet[1]) == BOM_HEADERS + ('value_mode',)
header = sheet['L1']
assert header.font.bold and header.font.color.rgb == '00FFFFFF'
assert header.fill.patternType == 'solid' and header.fill.fgColor.rgb == '001D3557'
assert header.comment and all(mode in header.comment.text for mode in (
'inherit', 'preserve', 'part_label', 'part_number', 'custom'))
assert any(validation.formula1 == '"inherit,preserve,part_label,part_number,custom"'
and 'L2' in validation for validation in sheet.data_validations.dataValidation)
assert sheet['C2'].number_format == sheet['D2'].number_format == '@'
if with_task:
assert sheet['B2'].value == str(tmp_path / 'Board.prj')
assert not store.list_target_plan(task_id)
finally:
book.close()
assert read_bom_records(path) == ()
finally:
store.close()
def test_legacy_writer_keeps_eleven_columns_and_custom_value_inference(tmp_path):
path = write_bom_template(tmp_path / 'legacy.xlsx', ({
'old_part_number': '001', 'new_part_number': '002', 'refdes': 'R1', 'custom_value': '47k',
},))
book = load_workbook(path)
try:
assert len(BOM_HEADERS) == 11
assert tuple(cell.value for cell in book.active[1]) == BOM_HEADERS
finally:
book.close()
record, = read_bom_records(path)
assert (record.old, record.new, record.value_mode, record.custom) == ('001', '002', 'custom', '47k')
@pytest.mark.parametrize('mode,custom,expected', [
('inherit', '', 'part_label'),
('preserve', '', 'preserve'),
('part_label', '', 'part_label'),
('part_number', '', 'part_number'),
('custom', '47k', 'custom'),
])
def test_record_value_source_roundtrips_and_compiles_with_task_default(tmp_path, mode, custom, expected):
path = write_bom_template(tmp_path / 'values.xlsx', ({
'old_part_number': '001', 'new_part_number': '002', 'refdes': 'R1',
'value_mode': mode, 'custom_value': custom,
},))
book = load_workbook(path)
try:
assert book.active['L1'].comment is not None
assert book.active['L1'].font.bold
finally:
book.close()
target = ComponentTarget(tmp_path / 'Board.prj', 'MAIN', '1', 'u1', 'R1', '001', '10nF')
records = read_bom_records(path)
rows = match_bom_records((TargetPlanRow(target),), records)
rule, = compile_target_rules(rows, default_value_mode='part_label')
assert (rows[0].value_mode, rule.value_mode, rule.custom_value) == (mode, expected, custom)
@@ -282,6 +282,7 @@ def test_service_multi_file_preview_normalizes_migrated_routes_before_cad(tmp_pa
def fake_inspect(_service, _task_id, path, **_options):
seen['path'] = Path(path)
assert seen['path'].is_file()
return report_module.BomImportReport(
rows=(report_module.BomRowResult(2, str(current), 'Board', 'passed', 'validated'),),
projects=(report_module.BomProjectResult(str(current), 'Board', 'passed', (2,)),),
@@ -292,7 +293,8 @@ def test_service_multi_file_preview_normalizes_migrated_routes_before_cad(tmp_pa
report = service.preview_bom_sources(task.task_id, (source,))
assert report.rows[0].reason.startswith('validated;来源:')
assert 'migrated.xlsx' in report.rows[0].reason and '第 2 行' in report.rows[0].reason
assert seen['path'].is_file()
assert not seen['path'].exists()
assert report.source_map_path == seen['path'].parent / 'source-map.json'
assert (seen['path'].parent / 'source-map.json').is_file()
finally:
store.close()
@@ -398,8 +400,8 @@ def test_multi_source_import_reuses_supervised_inspection(tmp_path, monkeypatch)
_write_bom(source, 'Board.prj', r'Z:\old\Board.prj', 'R1')
phases = []
def supervised(operation, arguments, **controls):
assert operation == 'inspect_bom_batch'
assert Path(arguments['path']).is_file()
assert operation == 'preview_bom_sources'
assert arguments['sources'] == (source,)
controls['on_phase']('validating', 'normalized')
return BomImportReport((), ())
monkeypatch.setattr(service, '_supervise', supervised)