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)
+27 -2
View File
@@ -236,12 +236,14 @@ def test_cancellation_during_excel_parsing_keeps_operation_cancelled(batch, tmp_
def test_ui_report_is_persistent_and_failure_does_not_stage(batch, tmp_path, qtbot, monkeypatch):
from types import SimpleNamespace
from PySide6.QtWidgets import QFileDialog
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
service, store, tasks, targets, calls = batch
# Exercise the real async import callback without any blocking message box.
monkeypatch.setattr(service, 'inspect_bom_batch', lambda *args, **kwargs: inspect_batch(
service, *args, **kwargs), raising=False)
preview = service.preview_bom_sources
monkeypatch.setattr(service, 'preview_bom_sources', lambda *args, **kwargs: preview(
*args, runtime=SimpleNamespace(bind_logs=lambda *_: None), **kwargs))
records = list(records_for(tasks, targets))
records[1]['new_part_number'] = ''
path = write_bom_template(tmp_path / 'bad-ui.xlsx', records)
@@ -249,6 +251,7 @@ def test_ui_report_is_persistent_and_failure_does_not_stage(batch, tmp_path, qtb
qtbot.addWidget(window)
window.open_task(tasks[0].task_id)
qtbot.waitUntil(lambda: not window._loading and not window._context_query.busy)
qtbot.waitUntil(window.plan_panel.import_bom_button.isEnabled)
monkeypatch.setattr(QFileDialog, 'getOpenFileNames', lambda *args: ([str(path)], 'Excel (*.xlsx)'))
window.plan_panel.import_bom_button.click()
qtbot.waitUntil(lambda: not window._workers)
@@ -264,10 +267,14 @@ def test_ui_report_is_persistent_and_failure_does_not_stage(batch, tmp_path, qtb
def test_ui_cleanup_failure_keeps_details_and_retry_clears_previous_result(batch, tmp_path, qtbot, monkeypatch):
from types import SimpleNamespace
from PySide6.QtWidgets import QFileDialog
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
from dx_productivity.trial_task_center.bom_import_state import BomImportPhase
service, store, tasks, targets, calls = batch
preview = service.preview_bom_sources
monkeypatch.setattr(service, 'preview_bom_sources', lambda *args, **kwargs: preview(
*args, runtime=SimpleNamespace(bind_logs=lambda *_: None), **kwargs))
preparer = service.for_project_task(tasks[0].task_id)._quick_run_preparer
original_reader = preparer.collect_inventory
def failed_reader(*args, **kwargs):
@@ -278,6 +285,7 @@ def test_ui_cleanup_failure_keeps_details_and_retry_clears_previous_result(batch
qtbot.addWidget(window)
window.open_task(tasks[0].task_id)
qtbot.waitUntil(lambda: not window._loading and not window._context_query.busy)
qtbot.waitUntil(window.plan_panel.import_bom_button.isEnabled)
monkeypatch.setattr(QFileDialog, 'getOpenFileNames', lambda *args: ([str(path)], 'Excel (*.xlsx)'))
panel = window.plan_panel
panel.import_bom_button.click()
@@ -287,6 +295,7 @@ def test_ui_cleanup_failure_keeps_details_and_retry_clears_previous_result(batch
assert 'UI-CLEANUP-1' in panel.report_text and panel.report_toggle.isVisibleTo(panel)
assert not panel._bom_batches and not calls
qtbot.waitUntil(lambda: not window._loading and not window._context_query.busy)
qtbot.waitUntil(panel.import_bom_button.isEnabled)
preparer.collect_inventory = original_reader
panel.import_bom_button.click()
assert panel.last_bom_report is None and not panel.report_toggle.isVisibleTo(panel)
@@ -296,3 +305,19 @@ def test_ui_cleanup_failure_keeps_details_and_retry_clears_previous_result(batch
assert all(not store.list_target_plan(task.task_id) for task in tasks)
panel.discard_all()
window.close()
def test_ui_report_uses_original_workbook_row_and_links_source_evidence(tmp_path):
from types import SimpleNamespace
from dx_productivity.trial_task_center.bom_import_report import BomImportReport, BomRowResult
from dx_productivity.trial_task_center.bom_import_state import BomImportPhase
from dx_productivity.trial_task_center.ui.project_plan import ProjectPlanPanel
report = BomImportReport((BomRowResult(3, 'board.prj', 'Board', 'failed', 'duplicate',
source_file=str(tmp_path / 'second.xlsx'), source_row=5),), (),
source_map_path=tmp_path / 'source-map.json')
state = SimpleNamespace(report=report, phase=BomImportPhase.FAILED, notice='')
_, text, _ = ProjectPlanPanel._format_bom_report(state)
assert 'second.xlsx · Excel 第 5 行' in text
assert 'Excel 第 3 行' not in text
assert str(report.source_map_path) in text
+126
View File
@@ -0,0 +1,126 @@
import json
import os
from contextlib import closing
import sys
import textwrap
import pytest
from test_bom_batch import batch
def test_real_supervised_sources_roundtrip_origin_metadata_and_preview(batch, tmp_path):
from dx_productivity.trial_task_center.bom_plan import write_bom_template
service, store, tasks, targets, calls = batch
for task in tasks:
store.record_target_inventory(task.task_id, targets[task.task_id])
sources = tuple(write_bom_template(tmp_path / f'source-{index}.xlsx', ({
'project_name': task.name, 'project_path': str(targets[task.task_id][0].project_path),
'old_part_number': 'OLD', 'new_part_number': 'NEW', 'refdes': 'R1', 'value_mode': 'part_number',
},)) for index, task in enumerate(tasks))
service._supervised = True
report = service.preview_bom_sources(tasks[0].task_id, sources)
assert report.passed_rows == 2 and report.preview is not None
assert tuple(row.source_file for row in report.rows) == tuple(str(path.resolve()) for path in sources)
assert all(row.source_row == 2 for row in report.rows)
assert report.source_map_path.is_file()
assert not report.source_map_path.with_name('normalized-bom.xlsx').exists()
assert all(project.rows[0].value_mode == 'part_number' for project in report.preview.projects)
assert not calls
assert all(not row.enabled for task in tasks for row in store.list_target_plan(task.task_id))
def test_bom_sources_run_in_one_worker_with_import_controls(tmp_path, monkeypatch):
"""Exercise real request admission and resource release, without opening CAD."""
from dx_productivity.trial_task_center import batch_supervisor
from dx_productivity.trial_task_center.bom_import_state import BomImportPhase
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
bootstrap = textwrap.dedent('''
import os, sys
from pathlib import Path
from dx_productivity.trial_task_center.batch_worker import run
from dx_productivity.trial_task_center.bom_import_report import BomImportReport, BomRowResult
from dx_productivity.trial_task_center.bom_import_state import BomImportPhase
from dx_productivity.trial_task_center.service import TaskCenterService
def business(self, task_id, sources, *, runtime, stop_event, on_progress, on_phase):
assert task_id == 'task'
assert type(sources) is tuple and len(sources) == 2
assert all(isinstance(source, Path) for source in sources)
assert tuple(source.name for source in sources) == ('first.xlsx', 'second.xlsx')
assert runtime.kind == 'bom_import'
assert runtime.stop_event is stop_event
on_progress('read both sources')
on_phase(BomImportPhase.READING, 'reading sources')
return BomImportReport((BomRowResult(2, str(os.getpid()), 'Board', 'passed'),), ())
TaskCenterService.preview_bom_sources = business
run(Path(sys.argv[1]))
''')
monkeypatch.setattr(batch_supervisor, '_command',
lambda request: (sys.executable, '-c', bootstrap, str(request)))
progress, phases = [], []
with closing(TaskStore(tmp_path / 'task-center.db')) as store:
service = TaskCenterService(store, configure_logging(tmp_path))
report = batch_supervisor.run_supervised(service, 'preview_bom_sources',
{'task_id': 'task', 'sources': (tmp_path / 'first.xlsx', tmp_path / 'second.xlsx')},
on_progress=progress.append, on_phase=lambda phase, message: phases.append(phase))
assert report.rows[0].project_name == 'Board'
assert report.rows[0].project_path != str(os.getpid())
assert progress == ['read both sources']
assert phases == [BomImportPhase.READING, BomImportPhase.RELEASING]
directory = next((tmp_path / 'batch-resources').iterdir())
journal = json.loads((directory / 'supervisor.json').read_text(encoding='utf-8'))
assert journal['state'] == 'finished'
assert journal['operation'] == 'preview_bom_sources'
assert journal['task_ids'] == ['task']
batch_supervisor.assert_supervisor_idle(tmp_path)
def test_bom_sources_supervisor_rejects_wrong_result_type():
from dx_productivity.trial_task_center.supervisor_protocol import encode
from dx_productivity.trial_task_center.supervisor_result import validated_outcome
with pytest.raises(ValueError, match='result type'):
validated_outcome('preview_bom_sources',
{'business_succeeded': True, 'status': 'ok', 'result': encode(())})
@pytest.mark.parametrize('shutdown_failed', [False, True])
@pytest.mark.parametrize('business_succeeded', [False, True])
def test_bom_sources_cleanup_preserves_rows_without_preview(
tmp_path, monkeypatch, shutdown_failed, business_succeeded):
from dx_productivity.trial_task_center import batch_resources
from dx_productivity.trial_task_center.batch_supervisor import _finish_response
from dx_productivity.trial_task_center.bom_batch import BomBatchPreview
from dx_productivity.trial_task_center.bom_import_report import BomImportReport, BomRowResult
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.supervisor_protocol import encode, encode_error
report = BomImportReport((BomRowResult(4, 'board.prj', 'Board', 'passed'),), (),
BomBatchPreview('task', (), ()))
journal = {'operation': 'preview_bom_sources', 'batch_id': 'a' * 32, 'state': 'running'}
directory = tmp_path / 'batch-resources' / journal['batch_id']
if shutdown_failed:
batch_resources.write_record(directory / 'session.json',
{'cad_shutdown': {'orderly_shutdown': False}})
pending = () if shutdown_failed else ({'session_id': journal['batch_id']},)
monkeypatch.setattr(batch_resources, 'cleanup_pending_resources', lambda *args, **kwargs: pending)
response = {'business_succeeded': business_succeeded, 'status': 'error',
'error': encode_error(TaskCenterError('batch_resources_pending', 'Quit failed'))}
if business_succeeded:
response['result'] = encode(report)
else:
primary = TaskCenterError('inventory_cleanup', 'Reader failed')
primary.bom_report = report
response['operation_error'] = encode_error(primary)
with pytest.raises(TaskCenterError) as caught:
_finish_response(tmp_path, journal, response, configure_logging(tmp_path))
assert caught.value.code == ('application_shutdown_failed' if shutdown_failed else 'batch_resources_pending')
assert caught.value.bom_report.rows == report.rows
assert caught.value.bom_report.preview is None
if business_succeeded:
assert caught.value.completed_result.preview is None
else:
assert caught.value.primary_error.code == 'inventory_cleanup'
+1 -1
View File
@@ -152,7 +152,7 @@ def test_blank_bom_can_be_downloaded_without_task_or_inventory(qtbot, tmp_path,
qtbot.waitUntil(lambda: not window._workers and output.exists())
workbook = load_workbook(output)
try:
assert tuple(cell.value for cell in workbook.active[1]) == BOM_HEADERS
assert tuple(cell.value for cell in workbook.active[1]) == BOM_HEADERS + ('value_mode',)
# The first editing row is explicitly text-formatted to preserve zeroes.
assert workbook.active.max_row == 2
assert all(cell.value is None for cell in workbook.active[2])