feat: report BOM validation and start new rounds from completed batches

This commit is contained in:
阿白叔 committed 2026-10-15 17:12:55 +08:00
1 parent ff06f86f62
commit 7f0ec29d31
11 files changed
+924 -37

No files matched your search

+125
View File
@@ -0,0 +1,125 @@
from dataclasses import replace
from threading import Event
import pytest
from test_bom_batch import batch, records_for
from dx_productivity.trial_task_center.bom_plan import write_bom_template
from dx_productivity.trial_task_center.bom_import_report import inspect_batch
from dx_productivity.trial_task_center.errors import TaskCenterError
def test_reports_independent_excel_errors_without_collecting_or_partial_preview(batch, tmp_path):
service, store, tasks, targets, calls = batch
records = list(records_for(tasks, targets))
records.extend([dict(records[0], new_part_number='', refdes='R2'),
dict(records[1], new_part_number='=1+1')])
report = inspect_batch(service, tasks[0].task_id, write_bom_template(tmp_path / 'bad.xlsx', records))
assert (report.total_rows, report.passed_rows, report.failed_rows, report.unchecked_rows) == (4, 0, 2, 2)
assert [row.excel_row for row in report.rows if row.status == 'failed'] == [4, 5]
assert report.preview is None and not calls
assert all(not store.list_target_plan(task.task_id) for task in tasks)
def test_reports_all_matching_errors_and_success_is_read_only(batch, tmp_path):
service, store, tasks, targets, calls = batch
records = list(records_for(tasks, targets))
records[0]['refdes'] = 'R9'
records[1]['refdes'] = 'R8'
report = inspect_batch(service, tasks[0].task_id, write_bom_template(tmp_path / 'bad.xlsx', records))
assert report.failed_rows == 2 and report.failed_projects == 2 and report.preview is None
assert all(row.project_path and row.reason for row in report.rows)
report = inspect_batch(service, tasks[0].task_id,
write_bom_template(tmp_path / 'good.xlsx', records_for(tasks, targets)))
assert report.passed_rows == 2 and report.passed_projects == 2 and report.preview
assert all(not store.list_target_plan(task.task_id) for task in tasks)
def test_duplicate_marks_both_rows_and_cross_row_chain_rejected(batch, tmp_path):
service, store, tasks, targets, calls = batch
record = records_for(tasks, targets)[0]
report = inspect_batch(service, tasks[0].task_id,
write_bom_template(tmp_path / 'dup.xlsx', [record, record]))
assert report.failed_rows == 2 and report.preview is None
target = targets[tasks[0].task_id][1]
targets[tasks[0].task_id] = (targets[tasks[0].task_id][0], replace(target, old_part_number='NEW-0'))
report = inspect_batch(service, tasks[0].task_id, write_bom_template(tmp_path / 'chain.xlsx',
[record, dict(record, old_part_number='NEW-0', new_part_number='NEXT', refdes='R2')]))
assert report.failed_rows == 2 and report.preview is None
def test_cancel_and_native_cleanup_errors_propagate_without_next_project(batch, tmp_path):
service, store, tasks, targets, calls = batch
path = write_bom_template(tmp_path / 'bom.xlsx', records_for(tasks, targets))
stop = Event()
stop.set()
with pytest.raises(TaskCenterError, match='取消'):
inspect_batch(service, tasks[0].task_id, path, stop_event=stop)
assert not calls
def unsafe(*args, **kwargs):
raise TaskCenterError('native_cleanup', 'cleanup failed')
service.for_project_task(tasks[0].task_id)._quick_run_preparer.collect_inventory = unsafe
with pytest.raises(TaskCenterError, match='cleanup failed'):
inspect_batch(service, tasks[0].task_id, path)
assert not calls
def test_cancellation_after_reader_prevents_opening_next_project(batch, tmp_path):
service, store, tasks, targets, calls = batch
stop = Event()
path = write_bom_template(tmp_path / 'bom.xlsx', records_for(tasks, targets))
def cancel_after_read(*args, **kwargs):
calls.append(tasks[0].task_id)
stop.set()
return targets[tasks[0].task_id]
service.for_project_task(tasks[0].task_id)._quick_run_preparer.collect_inventory = cancel_after_read
with pytest.raises(TaskCenterError, match='取消'):
inspect_batch(service, tasks[0].task_id, path, stop_event=stop)
assert calls == [tasks[0].task_id]
assert all(not store.list_target_plan(task.task_id) for task in tasks)
def test_scaffolds_skipped_but_header_and_bool_errors_report_excel_rows(batch, tmp_path):
from openpyxl import load_workbook
service, store, tasks, targets, calls = batch
path = service.export_bom_template(tasks[0].task_id, tmp_path / 'scaffold.xlsx')
report = inspect_batch(service, tasks[0].task_id, path)
assert report.total_rows == 0 and report.preview is None and report.errors and not calls
path = write_bom_template(tmp_path / 'bool.xlsx', [dict(records_for(tasks, targets)[0], enabled='maybe')])
report = inspect_batch(service, tasks[0].task_id, path)
assert report.rows[0].excel_row == 2 and report.failed_rows == 1 and 'TRUE/FALSE' in report.rows[0].reason
workbook = load_workbook(path)
workbook.active['C1'] = 'wrong header'
workbook.save(path)
workbook.close()
report = inspect_batch(service, tasks[0].task_id, path)
assert report.failed_rows == 1 and '第 1 行' in report.errors[0] and not calls
def test_ui_report_is_persistent_and_failure_does_not_stage(batch, tmp_path, qtbot, monkeypatch):
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)
records = list(records_for(tasks, targets))
records[1]['new_part_number'] = ''
path = write_bom_template(tmp_path / 'bad-ui.xlsx', records)
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)'))
window.plan_panel.import_bom_button.click()
qtbot.waitUntil(lambda: not window._workers)
panel = window.plan_panel
assert panel.last_bom_report.failed_rows == 1
assert 'Excel 第 3 行' in panel.bom_report.toPlainText()
assert '未检查 1 行' in panel.bom_report.toPlainText()
assert not panel._bom_batches and not panel._drafts and not calls
panel._summary()
assert '失败 1 行' in panel.bom_report.toPlainText()
assert all(not store.list_target_plan(task.task_id) for task in tasks)
window.close()
+275
View File
@@ -0,0 +1,275 @@
from dataclasses import replace
import json
import pytest
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.models import TaskStatus, ProjectStatus
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, TargetPlanRow
@pytest.fixture
def completed(tmp_path):
store = TaskStore(tmp_path / 'tasks.db')
service = TaskCenterService(store, configure_logging(tmp_path / 'data'))
path = tmp_path / 'board.prj'
path.touch()
task = store.create_task('board')
project = store.sync_projects(task.task_id, tmp_path, (path,))[0]
store.set_project_selected(project.project_id, True)
store.bind_project_task(task.task_id, project.project_id, 'batch', 0)
service.add_rule(task.task_id, 'OLD', 'NEW')
target = ComponentTarget(path, 'MAIN', '1', 'u1', 'R1', 'OLD', 'before')
store.record_target_inventory(task.task_id, (target,))
store.replace_target_plan(task.task_id, (TargetPlanRow(target, True, 'NEW'),))
store.record_quick_run_progress(task.task_id, (project.project_id,), queue_complete=True, has_progress=True)
yield service, store, task.task_id, project.project_id, target
store.close()
def test_restart_preserves_plan_and_evidence_but_requires_new_baseline(completed):
service, store, task_id, project_id, target = completed
root = service.for_project_task(task_id)._quick_run_preparer.data_root
history = root / 'quick-run-history' / 'obsolete-test'
history.mkdir(parents=True)
(history / 'native.log').write_text('original evidence')
old_task = store.get_task(task_id)
restarted = service.start_new_round(task_id)
assert [t.task_id for t in restarted] == [task_id]
task = store.get_task(task_id)
assert task.status is TaskStatus.DRAFT and task.target_plan_mode
assert task.group_id == old_task.group_id and task.primary_project_id == project_id
assert task.completed_utc is None and task.started_utc is None
assert store.get_project(project_id).status is ProjectStatus.PENDING
assert not store.list_target_plan(task_id)
archives = list((root / 'rounds').glob('*/plan.json'))
assert len(archives) == 1
snapshot = json.loads(archives[0].read_text(encoding='utf-8'))
assert snapshot['targets'][0]['target']['old_part_number'] == 'OLD'
assert (archives[0].parent / 'quick-run-history' / 'obsolete-test' / 'native.log').read_text() == 'original evidence'
assert not service.task_context(task_id).has_evidence
assert not service.task_context(task_id).progress.next_project_path
# Previous UID with current PN/value becomes a new baseline only after collection.
current = replace(target, old_part_number='NEW', old_value='after')
store.record_target_inventory(task_id, (current,))
store.replace_target_plan(task_id, (TargetPlanRow(current, True, 'NEXT'),))
assert service.task_context(task_id).progress.next_old_part_number == 'NEW'
with pytest.raises(TaskCenterError):
service.start_new_round(task_id)
assert len(list((root / 'rounds').glob('*/plan.json'))) == 1
def test_restart_rejects_interrupted_and_noncompleted_without_changing_plan(completed):
service, store, task_id, _, _ = completed
root = service.for_project_task(task_id)._quick_run_preparer.data_root / 'quick-run'
root.mkdir(parents=True)
(root / 'uncertain.flag').write_text('uncertain')
before = store.list_target_plan(task_id)
with pytest.raises(TaskCenterError):
service.start_new_round(task_id)
assert store.get_task(task_id).status is TaskStatus.COMPLETED
assert store.list_target_plan(task_id) == before
assert (root / 'uncertain.flag').exists()
def test_restart_rolls_back_files_when_database_reset_fails(completed, monkeypatch):
service, store, task_id, _, _ = completed
root = service.for_project_task(task_id)._quick_run_preparer.data_root
history = root / 'quick-run-history'
history.mkdir(parents=True)
(history / 'proof.txt').write_text('retain')
def fail(*args):
raise RuntimeError('database failure')
monkeypatch.setattr(store, 'reset_completed_round', fail)
with pytest.raises(TaskCenterError):
service.start_new_round(task_id)
assert (history / 'proof.txt').read_text() == 'retain'
assert store.get_task(task_id).status is TaskStatus.COMPLETED
assert store.list_target_plan(task_id)
def test_completed_group_restarts_together_and_rules_are_editable(completed, tmp_path):
service, store, task_id, _, _ = completed
other = store.create_task('second')
path = tmp_path / 'second.prj'
path.touch()
project = store.sync_projects(other.task_id, tmp_path, (path,))[0]
store.set_project_selected(project.project_id, True)
store.bind_project_task(other.task_id, project.project_id, 'batch', 1)
store.record_quick_run_progress(other.task_id, (project.project_id,), queue_complete=True, has_progress=True)
assert len(service.start_new_round(task_id)) == 2
service.update_rule(store.list_rules(task_id)[0].rule_id, old_part_number='NEW', new_part_number='NEXT', enabled=True)
assert store.list_rules(other.task_id)[-1].old_part_number == 'NEW'
assert all(t.status is TaskStatus.DRAFT for t in store.list_project_group('batch'))
def test_pristine_group_sibling_is_preserved_and_does_not_lock_rules(completed, tmp_path):
service, store, task_id, _, _ = completed
other = store.create_task('untouched')
path = tmp_path / 'untouched.prj'
path.touch()
project = store.sync_projects(other.task_id, tmp_path, (path,))[0]
store.bind_project_task(other.task_id, project.project_id, 'batch', 1)
before = store.get_task(other.task_id)
service.start_new_round(task_id)
assert store.get_task(other.task_id) == before
service.update_rule(store.list_rules(task_id)[0].rule_id, old_part_number='NEW', new_part_number='NEXT', enabled=True)
assert store.list_rules(other.task_id)[-1].new_part_number == 'NEXT'
def test_archived_handoff_cannot_supply_next_round_old_values(completed):
service, store, task_id, project_id, _ = completed
from dx_productivity.trial_task_center.target_plan import compile_target_rules
facade = service.for_project_task(task_id)
root = facade._quick_run_preparer.data_root
handoff = facade._quick_run_preparer.prepare(task_id,
(replace(store.get_project(project_id), status=ProjectStatus.PENDING),),
compile_target_rules(store.list_target_plan(task_id)),
sheet_targets={str(store.get_project(project_id).path).casefold(): (('MAIN', '1'),)})
command = handoff.command_path.read_text(encoding='utf-8').splitlines()[1].split('\t')
header = handoff.command_path.read_text(encoding='utf-8').splitlines()[0].split('\t')
job = dict(zip(header, command))['job_id']
handoff.status_path.write_text(f'job_id\tstate\tcode\tmessage\n{job}\tsaved_ok\t\tverified\n', encoding='utf-8')
old_bytes = handoff.command_path.read_bytes()
service.start_new_round(task_id)
assert not service.task_context(task_id).has_evidence
assert not service.task_context(task_id).progress.next_project_path
archives = list((root / 'rounds').glob('*/quick-run/command.tsv'))
assert len(archives) == 1 and archives[0].read_bytes() == old_bytes
assert not handoff.command_path.exists()
def test_pending_journal_recovers_interrupted_archival_before_retry(completed):
service, store, task_id, _, _ = completed
root = service.for_project_task(task_id)._quick_run_preparer.data_root
archive = root / 'rounds' / 'crashed' / 'quick-run-history'
archive.mkdir(parents=True)
(archive / 'evidence').write_text('unchanged')
journal = service._logging.root / 'round-transitions' / 'crashed'
journal.mkdir(parents=True)
source = root / 'quick-run-history'
(journal / 'journal.json').write_text(json.dumps(dict(task_ids=[task_id], summary='uncommitted round',
moves=[(str(source), str(archive))])), encoding='utf-8')
service.start_new_round(task_id)
assert (journal / 'rolled-back').exists()
assert any(path.read_text() == 'unchanged' for path in (root / 'rounds').glob('*/quick-run-history/evidence'))
def test_restart_is_rejected_while_execution_lease_is_held(completed):
service, store, task_id, _, _ = completed
from dx_productivity.trial_task_center.service import _quick_run_lease
with _quick_run_lease(service._logging.root):
with pytest.raises(TaskCenterError) as error:
service.start_new_round(task_id)
assert error.value.code == 'quick_run_busy'
assert store.get_task(task_id).status is TaskStatus.COMPLETED
def test_new_round_ui_confirms_scope_and_invalidates_paused_queue_token(completed, qtbot, monkeypatch):
from PySide6.QtWidgets import QMessageBox
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
service, store, task_id, _, _ = completed
window = TrialTaskCenterWindow(service)
qtbot.addWidget(window)
window.open_task(task_id)
qtbot.waitUntil(lambda: not window._loading and not window._context_query.busy)
assert window.run_panel.new_round_button.isEnabled()
assert not window.run_panel.quick_run_button.isEnabled()
assert window.plan_panel.table.rowCount() == 1
window._project_queues['batch'] = ('old-queue-token', (task_id,))
monkeypatch.setattr(QMessageBox, 'question', lambda *args: QMessageBox.StandardButton.Yes)
window.run_panel.new_round_button.click()
qtbot.waitUntil(lambda: not window._workers and not window._loading and not window._context_query.busy)
assert 'batch' not in window._project_queues
assert window.plan_panel.table.rowCount() == 0
assert not window.run_panel.quick_run_button.isEnabled()
assert window.add_mapping_button.isEnabled()
assert store.get_task(task_id).status is TaskStatus.DRAFT
window.close()
def test_commit_failure_rolls_back_database_and_restores_handoff(completed):
service, store, task_id, _, _ = completed
root = service.for_project_task(task_id)._quick_run_preparer.data_root
history = root / 'quick-run-history'
history.mkdir(parents=True)
(history / 'proof').write_text('original')
original = store._connection
class FailCommit:
def execute(self, sql, *args):
if sql == 'COMMIT':
raise RuntimeError('injected commit failure')
return original.execute(sql, *args)
def __getattr__(self, name):
return getattr(original, name)
store._connection = FailCommit()
try:
with pytest.raises(TaskCenterError):
service.start_new_round(task_id)
assert not original.in_transaction
assert store._transaction_depth == 0
assert store.get_task(task_id).status is TaskStatus.COMPLETED
assert store.list_target_plan(task_id)
assert (history / 'proof').read_text() == 'original'
finally:
store._connection = original
def test_committed_journal_uses_immutable_token_after_task_summary_changes(completed):
from dx_productivity.trial_task_center.new_round import recover_archives
service, store, task_id, _, _ = completed
root = service.for_project_task(task_id)._quick_run_preparer.data_root
history = root / 'quick-run-history'
history.mkdir(parents=True)
(history / 'proof').write_text('original')
service.start_new_round(task_id)
journal = next((service._logging.root / 'round-transitions').glob('*/journal.json'))
(journal.parent / 'committed').unlink()
store._connection.execute("UPDATE tasks SET summary = 'later edit' WHERE task_id = ?", (task_id,))
recover_archives(service)
assert (journal.parent / 'committed').exists()
assert not history.exists()
assert next((root / 'rounds').glob('*/quick-run-history/proof')).read_text() == 'original'
def test_pristine_target_mode_sibling_with_no_enabled_rows_is_not_execution_validated(completed, tmp_path):
service, store, task_id, _, target = completed
other = store.create_task('draft-empty-plan')
path = tmp_path / 'draft.prj'
path.touch()
project = store.sync_projects(other.task_id, tmp_path, (path,))[0]
store.bind_project_task(other.task_id, project.project_id, 'batch', 1)
store.record_target_inventory(other.task_id, (replace(target, project_path=path),))
before = store.list_target_plan(other.task_id)
service.start_new_round(task_id)
assert store.list_target_plan(other.task_id) == before
assert store.get_task(other.task_id).status is TaskStatus.DRAFT
@pytest.mark.parametrize('marker', ['committed', 'rolled-back'])
def test_terminal_corrupted_journal_does_not_block_round_recovery(completed, marker):
from dx_productivity.trial_task_center.new_round import recover_archives
service, _, _, _, _ = completed
folder = service._logging.root / 'round-transitions' / 'terminal'
folder.mkdir(parents=True)
(folder / 'journal.json').write_text('{truncated')
(folder / marker).touch()
recover_archives(service)
def test_failed_atomic_journal_write_does_not_publish_truncated_json(tmp_path, monkeypatch):
from pathlib import Path
from dx_productivity.trial_task_center.new_round import _write
destination = tmp_path / 'journal.json'
original = Path.write_text
def fail_partial(path, text, **options):
original(path, text[:4], **options)
raise OSError('injected partial write')
monkeypatch.setattr(Path, 'write_text', fail_partial)
with pytest.raises(OSError, match='partial write'):
_write(destination, {'moves': ['complete']})
assert not destination.exists()
assert not tuple(tmp_path.iterdir())