Merge origin/main and preserve readonly AI handling for BOM source failures
Core regression / Python 3.12 core, intervention UI and release configuration (push) Failing after 21s
Core regression / JavaScript syntax (push) Successful in 3s
Core regression / Python 3.12 core, intervention UI and release configuration (pull_request) Failing after 21s
Core regression / JavaScript syntax (pull_request) Successful in 3s

This commit is contained in:
阿白叔 committed 2026-11-05 14:42:00 +08:00
commit bd06bbc7d2
45 files changed
+2068 -98

No files matched your search

@@ -0,0 +1,225 @@
"""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 = []
operations = []
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)
original_operation = case.service._idle_quick_run_operation
def operation(name, task_id, action, **kwargs):
operations.append(name)
return original_operation(name, task_id, action, **kwargs)
monkeypatch.setattr(case.service, '_idle_quick_run_operation', operation)
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']
assert operations == ['preview_bom_sources']
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)
@@ -0,0 +1,481 @@
from pathlib import Path
import pytest
from openpyxl import Workbook
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.target_plan import (
ComponentTarget,
TargetPlanRow,
compile_target_rules,
)
from dx_productivity.trial_task_center.models import ProjectRecord, ProjectStatus
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
def _target(tmp_path, uid, refdes):
return ComponentTarget(tmp_path / 'migrated.prj', 'MAIN', '1', uid, refdes, 'OLD', '10nF')
def test_each_enabled_item_freezes_its_own_value_mode(tmp_path):
rows = (
TargetPlanRow(_target(tmp_path, 'u1', 'R1'), True, 'NEW', value_mode='preserve'),
TargetPlanRow(_target(tmp_path, 'u2', 'R2'), True, 'NEW', value_mode='part_label'),
TargetPlanRow(_target(tmp_path, 'u3', 'R3'), True, 'NEW', value_mode='custom', custom_value='47k'),
)
rules = compile_target_rules(rows)
assert rows[2].custom_value_enabled
assert {(rule.targets[0].refdes, rule.value_mode, rule.custom_value) for rule in rules} == {
('R1', 'preserve', ''), ('R2', 'part_label', ''), ('R3', 'custom', '47k')
}
def test_inherit_item_uses_task_default_but_explicit_item_override_wins(tmp_path):
rows = (
TargetPlanRow(_target(tmp_path, 'u1', 'R1'), True, 'NEW', value_mode='inherit'),
TargetPlanRow(_target(tmp_path, 'u2', 'R2'), True, 'NEW', value_mode='preserve'),
)
rules = compile_target_rules(rows, default_value_mode='part_label')
assert [(rule.targets[0].refdes, rule.value_mode) for rule in rules] == [
('R1', 'part_label'), ('R2', 'preserve')
]
def test_service_execution_rules_resolve_task_default_for_inherited_items(tmp_path):
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
store = TaskStore(tmp_path / 'execution-default.db')
service = TaskCenterService(store, configure_logging(tmp_path / 'data'))
task = service.create_task('default policy')
project = tmp_path / 'board.prj'
store.sync_projects(task.task_id, tmp_path, (project,))
targets = (
ComponentTarget(project, 'MAIN', '1', 'u1', 'R1', 'OLD1', '10nF'),
ComponentTarget(project, 'MAIN', '1', 'u2', 'R2', 'OLD2', '10nF'),
)
store.record_target_inventory(task.task_id, targets)
store.replace_target_plan(task.task_id, (
TargetPlanRow(targets[0], True, 'NEW1', value_mode='inherit'),
TargetPlanRow(targets[1], True, 'NEW2', value_mode='preserve'),
))
service.set_copy_part_number_to_value(task.task_id, True)
try:
rules = service._execution_rules(task.task_id)
assert [(rule.targets[0].refdes, rule.value_mode) for rule in rules] == [
('R1', 'part_label'), ('R2', 'preserve')
]
finally:
store.close()
def test_execution_command_preserves_item_value_modes(tmp_path):
projects = (ProjectRecord('p1', 'task', 'Board', tmp_path / 'migrated.prj', tmp_path,
True, True, ProjectStatus.PENDING, 0),)
rows = (
TargetPlanRow(_target(tmp_path, 'u1', 'R1'), True, 'NEW', value_mode='preserve'),
TargetPlanRow(_target(tmp_path, 'u2', 'R2'), True, 'NEW', value_mode='part_label'),
)
rules = compile_target_rules(rows)
command = QuickRunPreparer(tmp_path / 'data', script_source=Path(__file__)).prepare(
'task', projects, rules, copy_part_number_to_value=False,
sheet_targets={str(projects[0].path).casefold(): (('MAIN', '1'),)},
).command_path.read_text(encoding='utf-8')
header, first, second = command.splitlines()
mode = header.split('\t').index('value_mode')
assert [first.split('\t')[mode], second.split('\t')[mode]] == ['preserve', 'part_label']
def test_invalid_item_value_options_are_rejected(tmp_path):
with pytest.raises(TaskCenterError, match='Value'):
TargetPlanRow(_target(tmp_path, 'u1', 'R1'), True, 'NEW', value_mode='automatic')
with pytest.raises(TaskCenterError, match='custom Value is empty'):
compile_target_rules((TargetPlanRow(_target(tmp_path, 'u1', 'R1'), True, 'NEW',
value_mode='custom'),))
def test_legacy_bom_custom_value_remains_custom_after_normalization(tmp_path):
from dx_productivity.trial_task_center.bom_plan import read_bom_records, write_bom_template
from dx_productivity.trial_task_center.workspace_bom import load_sources, route_sources, write_routed_bom
source = write_bom_template(tmp_path / 'legacy.xlsx', ({
'project_name': 'Board.prj', 'project_path': r'Z:\old\Board.prj',
'old_part_number': 'OLD', 'new_part_number': 'NEW', 'refdes': 'R1',
'custom_value': '47k',
},))
rows = load_sources((source,))
normalized = write_routed_bom(tmp_path / 'normalized.xlsx', rows,
route_sources(rows, (tmp_path / 'Board.prj',)))
record, = read_bom_records(normalized)
assert record.value_mode == 'custom' and record.custom == '47k'
def test_target_context_keeps_editable_mapping_rules_after_item_overrides(tmp_path):
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
store = TaskStore(tmp_path / 'context.db')
service = TaskCenterService(store, configure_logging(tmp_path / 'data'))
project = tmp_path / 'board.prj'
project.write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n')
task, = service.create_project_tasks(tmp_path, selected_paths=(project,))
original = service.add_rule(task.task_id, 'OLD', 'NEW')
target = ComponentTarget(project, 'MAIN', '1', 'u1', 'R1', 'OLD', '10nF')
store.record_target_inventory(task.task_id, (target,))
store.replace_target_plan(task.task_id, (TargetPlanRow(target, True, 'OTHER', value_mode='part_label'),))
try:
context = service.task_context(task.task_id)
assert [(r.rule_id, r.new_part_number) for r in context.rules] == [(original.rule_id, 'NEW')]
assert service._execution_rules(task.task_id)[0].new_part_number == 'OTHER'
finally:
store.close()
def _write_bom(path, project_name, project_path, refdes):
book = Workbook()
sheet = book.active
sheet.append(['project_name', 'project_path', 'old_part_number', 'new_part_number', 'refdes', 'value_mode'])
sheet.append([project_name, project_path, 'OLD', 'NEW', refdes, 'part_label'])
book.save(path)
def test_multi_file_bom_load_preserves_sources_and_migrates_exact_project_name(tmp_path):
from dx_productivity.trial_task_center.workspace_bom import load_sources, route_sources
first = tmp_path / 'first.xlsx'
second = tmp_path / 'second.xlsx'
_write_bom(first, 'Board.prj', r'Z:\old\Board.prj', 'R1')
_write_bom(second, 'Board.prj', r'Z:\old\Board.prj', 'R2')
current = tmp_path / 'Board.prj'
rows = load_sources((first, second))
routes = route_sources(rows, (current,))
assert [row.source.name for row in rows] == ['first.xlsx', 'second.xlsx']
assert [row.excel_row for row in rows] == [2, 2]
assert routes[rows[0].project_key] == current
def test_migrated_name_match_is_ambiguous_without_manual_route(tmp_path):
from dx_productivity.trial_task_center.workspace_bom import load_sources, route_sources
source = tmp_path / 'one.xlsx'
_write_bom(source, 'Board.prj', r'Z:\old\Board.prj', 'R1')
candidates = (tmp_path / 'a' / 'Board.prj', tmp_path / 'b' / 'Board.prj')
for candidate in candidates:
candidate.parent.mkdir()
candidate.touch()
rows = load_sources((source,))
routes = route_sources(rows, candidates)
assert routes[rows[0].project_key] is None
def test_distinct_project_names_route_independently_when_stale_paths_are_identical(tmp_path):
from dx_productivity.trial_task_center.workspace_bom import load_sources, route_sources
sources = (tmp_path / 'first.xlsx', tmp_path / 'second.xlsx')
_write_bom(sources[0], 'BoardA.prj', r'Z:\old\wrong.prj', 'R1')
_write_bom(sources[1], 'BoardB.prj', r'Z:\old\wrong.prj', 'R1')
paths = (tmp_path / 'BoardA.prj', tmp_path / 'BoardB.prj')
rows = load_sources(sources)
routes = route_sources(rows, paths)
assert tuple(routes[row.project_key] for row in rows) == paths
def test_routed_bom_writes_source_map_for_closed_loop_diagnostics(tmp_path):
from dx_productivity.trial_task_center.workspace_bom import load_sources, route_sources, write_routed_bom
source = tmp_path / 'one.xlsx'
_write_bom(source, 'Board.prj', r'Z:\old\Board.prj', 'R1')
current = tmp_path / 'Board.prj'
rows = load_sources((source,))
routes = route_sources(rows, (current,))
destination = tmp_path / 'normalized' / 'bom.xlsx'
write_routed_bom(destination, rows, routes)
source_map = destination.with_name('source-map.json').read_text(encoding='utf-8')
assert 'migrated_exact_name' in source_map
assert 'one.xlsx' in source_map and '"source_row": 2' in source_map
def test_target_plan_schema_migrates_value_mode_for_existing_inventory(tmp_path):
from dx_productivity.trial_task_center.store import TaskStore
path = tmp_path / 'tasks.db'
store = TaskStore(path)
task = store.create_task('migration')
project = tmp_path / 'board.prj'
store.sync_projects(task.task_id, tmp_path, (project,))
store.record_target_inventory(task.task_id, (ComponentTarget(project, 'MAIN', '1', 'u1', 'R1', 'OLD', '10nF'),))
store.close()
import sqlite3
with sqlite3.connect(path) as connection:
connection.execute('ALTER TABLE target_plan DROP COLUMN value_mode')
store = TaskStore(path)
try:
# Existing inventory must inherit the task policy after migration.
assert store.list_target_plan(task.task_id)[0].value_mode == 'inherit'
finally:
store.close()
def test_closed_loop_persists_plan_reopens_and_freezes_command_modes(tmp_path):
from dx_productivity.trial_task_center.models import ProjectStatus, ProjectRecord
from dx_productivity.trial_task_center.store import TaskStore
database_path = tmp_path / 'closed-loop.db'
project = tmp_path / 'board.prj'
store = TaskStore(database_path)
task = store.create_task('closed-loop')
store.sync_projects(task.task_id, tmp_path, (project,))
targets = (_target(tmp_path, 'u1', 'R1'), _target(tmp_path, 'u2', 'R2'))
targets = tuple(ComponentTarget(project, t.schematic_name, t.sheet_number, t.uid, t.refdes,
t.old_part_number, t.old_value) for t in targets)
store.record_target_inventory(task.task_id, targets)
rows = (TargetPlanRow(targets[0], True, 'NEW', value_mode='preserve'),
TargetPlanRow(targets[1], True, 'NEW', value_mode='part_label'))
store.replace_target_plan(task.task_id, rows)
store.close()
reopened = TaskStore(database_path)
try:
frozen = reopened.list_target_plan(task.task_id)
rules = compile_target_rules(frozen)
command = QuickRunPreparer(tmp_path / 'evidence', script_source=Path(__file__)).prepare(
task.task_id,
(ProjectRecord('p1', task.task_id, 'Board', project, tmp_path, True, True,
ProjectStatus.PENDING, 0),),
rules,
copy_part_number_to_value=False,
sheet_targets={str(project).casefold(): (('MAIN', '1'),)},
).command_path.read_text(encoding='utf-8')
header, *command_rows = command.splitlines()
mode_index = header.split('\t').index('value_mode')
assert [row.split('\t')[mode_index] for row in command_rows] == ['preserve', 'part_label']
finally:
reopened.close()
def test_service_multi_file_preview_normalizes_migrated_routes_before_cad(tmp_path, monkeypatch):
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
import dx_productivity.trial_task_center.bom_import_report as report_module
source = tmp_path / 'migrated.xlsx'
_write_bom(source, 'Board.prj', r'Z:\old\Board.prj', 'R1')
current = tmp_path / 'Board.prj'
store = TaskStore(tmp_path / 'service.db')
service = TaskCenterService(store, configure_logging(tmp_path / 'data'))
task = service.create_task('BOM')
store.sync_projects(task.task_id, tmp_path, (current,))
seen = {}
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,)),),
)
monkeypatch.setattr(report_module, 'inspect_batch', fake_inspect)
try:
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 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()
@pytest.fixture
def simulated_bom_workspace(tmp_path):
from types import SimpleNamespace
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
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 / 'simulation.db')
service = TaskCenterService(store, configure_logging(tmp_path / 'evidence'))
tasks = service.create_project_tasks(root)
for task in tasks:
project = service.projects(task.task_id)[0].path
targets = tuple(ComponentTarget(project, 'MAIN', '1', f'u{i}', f'R{i}', 'OLD', '10nF')
for i in (1, 2))
store.record_target_inventory(task.task_id, targets)
runtime = SimpleNamespace(bind_logs=lambda *_: None)
yield service, store, tasks, runtime
store.close()
def test_two_excel_imports_save_reopen_freeze_and_recovery_readback(simulated_bom_workspace, tmp_path):
from dataclasses import replace
from dx_productivity.trial_task_center.bom_plan import write_bom_template
from dx_productivity.trial_task_center.bom_import_state import BomImportPhase as Phase
from dx_productivity.trial_task_center.quick_run import _read_command_options, _read_commands, _queue_matches_inputs
from dx_productivity.trial_task_center.store import TaskStore
service, store, tasks, runtime = simulated_bom_workspace
service.set_copy_part_number_to_value(tasks[0].task_id, True)
sources = []
for task, modes in zip(tasks, (('inherit', 'preserve'), ('custom', 'part_number'))):
project = service.projects(task.task_id)[0].path
sources.append(write_bom_template(tmp_path / (project.stem + '.xlsx'), tuple({
'project_name': task.name, 'project_path': 'Z:/old/' + project.name,
'old_part_number': 'OLD', 'new_part_number': 'NEW', 'refdes': f'R{i}',
'value_mode': mode, 'custom_value': '47k' if mode == 'custom' else '',
} for i, mode in enumerate(modes, 1))))
phases = []
report = service.preview_bom_sources(tasks[0].task_id, sources, runtime=runtime,
on_phase=lambda phase, _: phases.append(phase))
assert report.passed_rows == 4 and report.preview is not None
assert phases == [Phase.READING, Phase.VALIDATING, Phase.INVENTORY, Phase.MATCHING,
Phase.INVENTORY, Phase.MATCHING]
assert all(not row.enabled for task in tasks for row in store.list_target_plan(task.task_id))
for row, filename, number in zip(report.rows, ('BoardA.xlsx', 'BoardA.xlsx', 'BoardB.xlsx', 'BoardB.xlsx'), (2, 3, 2, 3)):
assert filename in row.reason and f'第 {number} 行' in row.reason
service.save_bom_batch(report.preview, {p.task_id: p.rows for p in report.preview.projects})
reopened = TaskStore(store.path)
try:
for task, expected in zip(tasks, ((('part_label', ''), ('preserve', '')),
(('custom', '47k'), ('part_number', '')))):
policy = reopened.get_task(task.task_id).copy_part_number_to_value
rules = compile_target_rules(reopened.list_target_plan(task.task_id),
default_value_mode='part_label' if policy else 'preserve')
projects = reopened.list_projects(task.task_id)
command = QuickRunPreparer(tmp_path / task.task_id, script_source=Path(__file__)).prepare(
task.task_id, projects, rules, copy_part_number_to_value=policy,
sheet_targets={str(projects[0].path).casefold(): (('MAIN', '1'),)},
).command_path
options = _read_command_options(command)
assert tuple((mode, custom) for mode, custom, _, _ in options.values()) == expected
commands = _read_commands(command)
assert _queue_matches_inputs(command, commands, projects, rules)
changed = (replace(rules[0], custom_value='changed') if rules[0].value_mode == 'custom'
else replace(rules[0], value_mode='part_number'))
assert not _queue_matches_inputs(command, commands, projects, (changed, *rules[1:]))
finally:
reopened.close()
def test_cross_file_duplicate_blocks_every_plan_with_original_sources(simulated_bom_workspace, tmp_path):
service, store, tasks, runtime = simulated_bom_workspace
sources = (tmp_path / 'first.xlsx', tmp_path / 'second.xlsx')
for source in sources:
_write_bom(source, 'BoardA.prj', r'Z:\old\BoardA.prj', 'R1')
report = service.preview_bom_sources(tasks[0].task_id, sources, runtime=runtime)
assert report.preview is None and report.failed_rows == 2
assert 'first.xlsx' in report.rows[0].reason and 'second.xlsx' in report.rows[1].reason
assert all(not row.enabled for task in tasks for row in store.list_target_plan(task.task_id))
def test_multi_source_import_reuses_supervised_inspection(tmp_path, monkeypatch):
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.bom_import_report import BomImportReport
store = TaskStore(tmp_path / 'supervised.db')
service = TaskCenterService(store, configure_logging(tmp_path / 'data'), supervised=True)
task = store.create_task('board')
store.sync_projects(task.task_id, tmp_path, (tmp_path / 'Board.prj',))
source = tmp_path / 'one.xlsx'
_write_bom(source, 'Board.prj', r'Z:\old\Board.prj', 'R1')
phases = []
def supervised(operation, arguments, **controls):
assert operation == 'preview_bom_sources'
assert arguments['sources'] == (source,)
controls['on_phase']('validating', 'normalized')
return BomImportReport((), ())
monkeypatch.setattr(service, '_supervise', supervised)
try:
service.preview_bom_sources(task.task_id, (source,), on_phase=lambda phase, _: phases.append(phase))
assert phases == ['validating']
finally:
store.close()
def test_legacy_plan_text_false_inherits_without_enabling_custom(simulated_bom_workspace, tmp_path):
from openpyxl import load_workbook
from dx_productivity.trial_task_center.spreadsheet_plan import export_target_plan, read_target_plan
_, store, tasks, _ = simulated_bom_workspace
task_id = tasks[0].task_id
path = export_target_plan(store, task_id, tmp_path / 'legacy-plan.xlsx')
book = load_workbook(path)
book.active.delete_cols(14)
book.active['I2'] = True
book.active['J2'] = 'NEW'
book.active['K2'] = 'FALSE'
book.save(path)
book.close()
imported = read_target_plan(store, task_id, path)
assert imported[0].enabled and imported[0].value_mode == 'inherit'
assert not imported[0].custom_value_enabled
@pytest.mark.parametrize('invalid', ['=1+1', '#N/A'])
def test_malformed_second_excel_is_blocked_before_inspection(simulated_bom_workspace, tmp_path, monkeypatch, invalid):
from openpyxl import load_workbook
service, store, tasks, _ = simulated_bom_workspace
first, second = tmp_path / 'first.xlsx', tmp_path / 'second.xlsx'
for source in (first, second):
_write_bom(source, 'BoardA.prj', r'Z:\old\BoardA.prj', 'R1')
book = load_workbook(second)
book.active['D2'] = invalid
book.save(second)
book.close()
monkeypatch.setattr(service, 'inspect_bom_batch', lambda *_a, **_k: pytest.fail('invalid source reached inspection'))
with pytest.raises(TaskCenterError, match='second.xlsx.*2'):
service.preview_bom_sources(tasks[0].task_id, (first, second))
assert all(not row.enabled for task in tasks for row in store.list_target_plan(task.task_id))
@pytest.mark.parametrize('mode', ['preserve', 'part_label', 'part_number'])
def test_batch_custom_default_does_not_overwrite_explicit_item_mode(simulated_bom_workspace, mode):
from dataclasses import replace
service, store, tasks, _ = simulated_bom_workspace
task_id = tasks[0].task_id
rule = service.add_rule(task_id, 'OLD', 'NEW')
rows = store.list_target_plan(task_id)
store.replace_target_plan(task_id, (replace(rows[0], enabled=True, value_mode=mode), rows[1]))
service.update_rule(rule.rule_id, old_part_number='OLD', new_part_number='NEW', enabled=True,
custom_value_enabled=True, custom_value='47k')
row = store.list_target_plan(task_id)[0]
assert row.value_mode == mode and not row.custom_value_enabled
assert service._execution_rules(task_id)[0].value_mode == mode
def test_disabling_seeded_custom_default_restores_inherited_policy(simulated_bom_workspace):
from dataclasses import replace
service, store, tasks, _ = simulated_bom_workspace
task_id = tasks[0].task_id
rule = service.add_rule(task_id, 'OLD', 'NEW', custom_value_enabled=True, custom_value='47k')
rows = store.list_target_plan(task_id)
store.replace_target_plan(task_id, (replace(rows[0], enabled=True), rows[1]))
service.set_copy_part_number_to_value(task_id, True)
service.update_rule(rule.rule_id, old_part_number='OLD', new_part_number='NEW', enabled=True,
custom_value_enabled=False, custom_value='')
row = store.list_target_plan(task_id)[0]
assert row.value_mode == 'inherit' and not row.custom_value_enabled
assert service._execution_rules(task_id)[0].value_mode == 'part_label'
+41 -3
View File
@@ -31,7 +31,7 @@ def test_bom_validation_reports_original_owner_and_bounded_evidence(ui, blockers
panel = ui.window.plan_panel
owner = ui.tasks[0].task_id
pending = []
monkeypatch.setattr(QFileDialog, 'getOpenFileName', lambda *args: ('bad.xlsx', ''))
monkeypatch.setattr(QFileDialog, 'getOpenFileNames', lambda *args: (['bad.xlsx'], ''))
monkeypatch.setattr(panel, '_dispatch_cancellable', lambda operation, callback, button, **kwargs: pending.append(callback))
panel.import_bom()
ui.open(ui.tasks[1])
@@ -55,10 +55,10 @@ def test_bom_new_attempt_clears_scope_but_cancelled_file_dialog_does_not(ui, blo
panel._received_bom_report(report, scope=scope)
source = reports(blockers)[-1][1][0]
blockers.clear()
monkeypatch.setattr(QFileDialog, 'getOpenFileName', lambda *args: ('', ''))
monkeypatch.setattr(QFileDialog, 'getOpenFileNames', lambda *args: ([], ''))
panel.import_bom()
assert not blockers
monkeypatch.setattr(QFileDialog, 'getOpenFileName', lambda *args: ('new.xlsx', ''))
monkeypatch.setattr(QFileDialog, 'getOpenFileNames', lambda *args: (['new.xlsx'], ''))
monkeypatch.setattr(panel, '_dispatch', lambda *args, **kwargs: None)
panel.import_bom()
assert ('clear', (source,), {}) in blockers
@@ -182,6 +182,44 @@ def test_bom_operational_report_and_progress_keep_import_owner_after_selection_c
assert not ui.calls
@pytest.mark.parametrize('code', ['bom_import', 'project_binding'])
def test_bom_source_failure_without_report_keeps_readonly_scope_and_original_owner(ui, blockers, monkeypatch, code):
window = ui.window
panel = window.plan_panel
owner = panel.task_id
scope = panel._report_scope(owner)
window._dsh_authorized_tasks.add(owner)
window._dsh_run_id = 'previous-authorized-execution'
monkeypatch.setattr(panel, '_dispatch', lambda *args, **kwargs: None)
panel._dispatch_cancellable(lambda *args: None, lambda _: None, panel.import_bom_button, bom_scope=scope)
ui.open(ui.tasks[1])
monkeypatch.setattr(window, '_queue_dsh_incident', lambda *a: pytest.fail('BOM failure must not inherit CAD authorization'))
error = TaskCenterError(code, 'Source workbook validation failed')
window._show_error(error, owner_task_id=owner, operation_area='bom')
assert not reports(blockers)
panel.finish_operation(error=error)
args, options = reports(blockers)[-1][1:]
assert args[1:3] == (owner, code)
assert args[4]['scope'] == list(scope)
assert options['read_only'] is True
assert panel.bom_import_state.report is None
assert not ui.calls
def test_unrelated_query_error_during_bom_import_keeps_its_own_incident(ui, blockers, monkeypatch):
window = ui.window
panel = window.plan_panel
queued = []
monkeypatch.setattr(panel, '_dispatch', lambda *args, **kwargs: None)
panel._dispatch_cancellable(lambda *args: None, lambda _: None, panel.import_bom_button,
bom_scope=panel._report_scope(panel.task_id))
monkeypatch.setattr(window, '_queue_dsh_incident', lambda *args: queued.append(args) or True)
window._show_error(TaskCenterError('task_read_failed', 'Unrelated task list read failed'))
assert len(queued) == 1 and queued[0][1] == 'task_read_failed'
assert not reports(blockers)
panel.finish_operation(error=TaskCenterError('operation_cancelled', 'test cleanup'))
def test_lifecycle_direct_rejection_is_reported_once(ui, blockers, monkeypatch):
setup_view(ui, monkeypatch)
ctl = ui.window._dsh_lifecycle
+51
View File
@@ -21,6 +21,57 @@ def test_mapping_dialog_exposes_custom_value_nc_and_optional_cell(qtbot):
assert dialog.target_cell=='' and '可选' in dialog.cell_combo.itemText(0)
def test_target_table_exposes_item_value_mode_selector(qtbot):
from pathlib import Path
from dx_productivity.trial_task_center.target_plan import ComponentTarget, TargetPlanRow
from dx_productivity.trial_task_center.ui.target_table import TargetTable
table = TargetTable()
qtbot.addWidget(table)
row = TargetPlanRow(ComponentTarget(Path('C:/board.prj'), 'MAIN', '1', 'u1', 'R1', 'OLD', '10nF'),
True, 'NEW')
table.populate((row,))
assert table.model().index(0, 10).data() == 'inherit'
assert table.model().setData(table.model().index(0, 10), 'part_label')
assert table.rows()[0].value_mode == 'part_label'
assert not table.rows()[0].custom_value_enabled
assert table.model().setData(table.model().index(0, 10), 'custom')
assert table.rows()[0].value_mode == 'custom' and table.rows()[0].custom_value_enabled
from PySide6.QtCore import Qt
assert table.model().setData(table.model().index(0, 7), Qt.CheckState.Unchecked,
Qt.ItemDataRole.CheckStateRole)
assert table.rows()[0].value_mode == 'inherit' and not table.rows()[0].custom_value_enabled
assert table.plan_model.headerData(10, Qt.Orientation.Horizontal, Qt.ItemDataRole.ToolTipRole)
def test_target_value_editor_commits_selection_and_escape_cancels(qtbot):
from pathlib import Path
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QComboBox
from dx_productivity.trial_task_center.target_plan import ComponentTarget, TargetPlanRow
from dx_productivity.trial_task_center.ui.target_table import TargetTable
table = TargetTable()
qtbot.addWidget(table)
table.resize(1400, 200)
table.populate((TargetPlanRow(ComponentTarget(Path('C:/board.prj'), 'MAIN', '1', 'u1',
'R1', 'OLD', '10nF'), True, 'NEW'),))
table.show()
index = table.model().index(0, 10)
table.edit(index)
editor = table.findChild(QComboBox)
assert editor.currentText() == 'inherit'
editor.setCurrentText('part_number')
qtbot.keyClick(editor, Qt.Key.Key_Tab)
assert table.rows()[0].value_mode == 'part_number'
table.edit(index)
editor = next(e for e in table.findChildren(QComboBox) if e.isVisible())
editor.setCurrentText('custom')
qtbot.keyClick(editor, Qt.Key.Key_Escape)
assert table.rows()[0].value_mode == 'part_number'
def test_small_window_keeps_splitters_and_opens_log_in_disposable_window(ui,qtbot):
w=ui.window;w.resize(980,700);qtbot.wait(30)
assert w.width()==980 and w.height()==700
+3 -2
View File
@@ -160,12 +160,13 @@ def test_ui_previews_each_project_and_confirms_the_batch_once(batch, tmp_path, q
from PySide6.QtWidgets import QFileDialog
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
service, store, tasks, targets, calls = batch
path = write_bom_template(tmp_path / 'bom.xlsx', records_for(tasks, targets))
paths = [write_bom_template(tmp_path / f'bom-{i}.xlsx', (record,))
for i, record in enumerate(records_for(tasks, targets))]
window = TrialTaskCenterWindow(service)
qtbot.addWidget(window)
window.open_task(tasks[0].task_id)
qtbot.waitUntil(lambda: not window._loading and not window._context_query.busy)
monkeypatch.setattr(QFileDialog, 'getOpenFileName', lambda *args: (str(path), 'Excel (*.xlsx)'))
monkeypatch.setattr(QFileDialog, 'getOpenFileNames', lambda *args: ([str(path) for path in paths], 'Excel (*.xlsx)'))
window.plan_panel.import_bom_button.click()
qtbot.waitUntil(lambda: not window._workers, timeout=5000)
assert window.plan_panel.table.rows()[0].new_part_number == 'NEW-0'
+29 -4
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,7 +251,8 @@ 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)
monkeypatch.setattr(QFileDialog, 'getOpenFileName', lambda *args: (str(path), 'Excel (*.xlsx)'))
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)
panel = window.plan_panel
@@ -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,7 +285,8 @@ 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)
monkeypatch.setattr(QFileDialog, 'getOpenFileName', lambda *args: (str(path), 'Excel (*.xlsx)'))
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()
qtbot.waitUntil(lambda: not window._workers)
@@ -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'
@@ -116,6 +116,21 @@ def test_value_policy_records_actual_change_and_ignores_repeated_value(case):
assert case.history.page().rows==before
def test_item_value_only_change_is_recorded_in_history(case):
from dataclasses import replace
task = bound_task(case)
case.service.collect_target_inventory(task.task_id, ('OLD',), runtime=object())
row, = case.service.target_plan(task.task_id)
before = len(events(case, 'replace_target_plan'))
case.service.replace_target_plan(task.task_id, (replace(row, value_mode='part_label'),))
rows = events(case, 'replace_target_plan')
assert len(rows) == before + 1
change, = rows[0]['details']['changes']
assert change['table'] == 'target_plan'
assert change['before'] == {'value_mode': 'inherit'}
assert change['after'] == {'value_mode': 'part_label'}
@pytest.mark.parametrize('operation',['create_assistant_project_tasks','collect_target_inventory','refresh_bound_project','set_value_policy'])
def test_history_write_failure_rolls_back_each_real_service_mutation(case,monkeypatch,operation):
task=None if operation=='create_assistant_project_tasks' else bound_task(case)
+38
View File
@@ -68,3 +68,41 @@ def test_native_short_path_never_passes_extended_prefix_to_wsh(tmp_path):
if result is None:
pytest.skip('filesystem does not provide short paths')
assert not result.startswith(chr(92) * 2 + '?')
def test_batch_resource_record_retries_reader_denied_atomic_replace(tmp_path, monkeypatch):
import json
import os
from threading import Timer
if os.name != 'nt':
pytest.skip('Windows delete-sharing boundary')
import win32con
import win32file
from dx_productivity.trial_task_center import batch_resources
path = tmp_path / 'session.json'
path.write_text('{"stage": "before"}', encoding='utf-8')
reader = win32file.CreateFile(str(path), win32con.GENERIC_READ,
win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE, None,
win32con.OPEN_EXISTING, 0, None)
real_replace = os.replace
denials, timers = [], []
def replace(source, target):
try:
return real_replace(source, target)
except PermissionError as error:
denials.append(error.winerror)
timer = Timer(.02, reader.Close)
timers.append(timer)
timer.start()
raise
monkeypatch.setattr(batch_resources.os, 'replace', replace)
try:
batch_resources.write_record(path, {'stage': 'saved'})
assert denials == [5]
assert json.loads(path.read_text(encoding='utf-8')) == {'stage': 'saved'}
assert not list(tmp_path.glob('*.tmp'))
finally:
for timer in timers:
timer.join()
reader.Close()
+45
View File
@@ -134,3 +134,48 @@ def test_completed_failure_is_delivered_and_next_step_starts_fresh_worker(tmp_pa
assert scope.run_step(project, command, 3).returncode == 0
assert scope.worker is not previous
assert (tmp_path / 'closed.txt').exists()
@pytest.mark.parametrize('release_reader', [True, False])
def test_real_vbs_session_result_write_handles_reader_contention(tmp_path, release_reader):
import os
import re
from threading import Timer
if os.name != 'nt':
pytest.skip('Windows ADODB.Stream sharing boundary')
import win32con
import win32file
source = Path(__file__).resolve().parents[2] / 'integration/dxdesigner795/QuickPartReplace.vbs'
writer = re.search(r'(?ms)^Sub QPWriteUtf8\(.*?^End Sub', source.read_text(encoding='utf-8')).group()
script = tmp_path / 'write-result.vbs'
script.write_text('Set QP_Fso = CreateObject("Scripting.FileSystemObject")\n'
'WScript.Echo "ready"\nOn Error Resume Next\nQPWriteUtf8 WScript.Arguments(0), "verified"\n'
'If Err.Number <> 0 Then\nWScript.StdErr.WriteLine Err.Description\nWScript.Quit 1\nEnd If\n'
'WScript.Quit 0\n' + writer,
encoding='ascii')
path = tmp_path / 'project-session-result.tsv'
path.write_text('before', encoding='utf-8')
reader = win32file.CreateFile(str(path), win32con.GENERIC_READ, win32con.FILE_SHARE_READ,
None, win32con.OPEN_EXISTING, 0, None)
timer = None
process = subprocess.Popen((r'C:\Windows\SysWOW64\cscript.exe', '//nologo', str(script), str(path)),
stdout=subprocess.PIPE, stderr=subprocess.PIPE, creationflags=subprocess.CREATE_NO_WINDOW)
try:
assert process.stdout.readline().strip() == b'ready'
if release_reader:
timer = Timer(.15, reader.Close)
timer.start()
_, stderr = process.communicate(timeout=5)
if release_reader:
assert process.returncode == 0, stderr
assert path.read_text(encoding='utf-8-sig') == 'verified'
else:
assert process.returncode != 0
assert path.read_text(encoding='utf-8') == 'before'
finally:
if timer:
timer.join()
reader.Close()
if process.poll() is None:
process.kill()
process.wait()
+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])
+5 -5
View File
@@ -106,8 +106,8 @@ def test_bom_retry_replaces_old_report_with_live_state(window, qtbot, monkeypatc
if outcome == 'error':
raise TaskCenterError('bom_import', '本次文件无法读取')
return new
monkeypatch.setattr(window.service, 'inspect_bom_batch', inspect)
monkeypatch.setattr(QFileDialog, 'getOpenFileName', lambda *args: ('retry.xlsx', ''))
monkeypatch.setattr(window.service, 'preview_bom_sources', inspect)
monkeypatch.setattr(QFileDialog, 'getOpenFileNames', lambda *args: (['retry.xlsx'], ''))
panel.import_bom()
assert 'Excel' in panel.summary.text()
try:
@@ -147,7 +147,7 @@ def test_cancelling_bom_file_picker_keeps_previous_report(window, qtbot, monkeyp
panel = window.plan_panel
report = BomImportReport((), (), errors=('原有报告',))
panel._received_bom_report(report)
monkeypatch.setattr(QFileDialog, 'getOpenFileName', lambda *args: ('', ''))
monkeypatch.setattr(QFileDialog, 'getOpenFileNames', lambda *args: ([], ''))
panel.import_bom()
assert panel.last_bom_report is report
assert '原有报告' in panel.report_text
@@ -170,8 +170,8 @@ def test_import_phases_drive_ui_and_cancelling_cannot_be_overwritten(window, qtb
assert release.wait(5)
phase(BomImportPhase.INVENTORY, 'late next project')
return BomImportReport((), (), errors=('late report',))
monkeypatch.setattr(window.service, 'inspect_bom_batch', inspect)
monkeypatch.setattr(QFileDialog, 'getOpenFileName', lambda *args: ('phased.xlsx', ''))
monkeypatch.setattr(window.service, 'preview_bom_sources', inspect)
monkeypatch.setattr(QFileDialog, 'getOpenFileNames', lambda *args: (['phased.xlsx'], ''))
panel.import_bom()
try:
qtbot.waitUntil(lambda: panel.bom_import_state.phase is BomImportPhase.MATCHING)