Implement v1.1 target plans and project task backend

This commit is contained in:
阿白叔 committed 2026-10-14 13:30:30 +08:00
1 parent a7e1b9bd33
commit 235a1005e9
18 files changed
+1536 -45

No files matched your search

+180
View File
@@ -0,0 +1,180 @@
from pathlib import Path
import pytest
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.project_tasks import create_project_tasks
from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.target_plan import ComponentTarget, TargetPlanRow, compile_target_rules
def target(uid: str, refdes: str) -> ComponentTarget:
return ComponentTarget(Path('board.prj'), 'MAIN', '1', uid, refdes, 'OLD', 'V0')
def test_directory_creates_one_task_per_project_and_deduplicates_active_paths(tmp_path):
root = tmp_path / 'projects'
for folder in ('left', 'right'):
path = root / folder / 'same.prj'
path.parent.mkdir(parents=True)
path.write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n', encoding='ascii')
store = TaskStore(tmp_path / 'tasks.db')
created = create_project_tasks(store, root)
again = create_project_tasks(store, root)
assert len(created) == 2
assert again == ()
assert {task.name for task in created} == {'left/same.prj', 'right/same.prj'}
assert all(len(store.list_projects(task.task_id)) == 1 for task in created)
store.close()
reopened = TaskStore(tmp_path / 'tasks.db')
assert len(reopened.list_tasks()) == 2
def test_directory_creation_rolls_back_on_second_project_failure(tmp_path, monkeypatch):
root = tmp_path / 'projects'
root.mkdir()
for name in ('a.prj', 'b.prj'):
(root / name).write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n', encoding='ascii')
store = TaskStore(tmp_path / 'tasks.db')
original = store.sync_projects
calls = 0
def fail_second(*args, **kwargs):
nonlocal calls
calls += 1
if calls == 2:
raise TaskCenterError('test_failure', 'injected failure')
return original(*args, **kwargs)
monkeypatch.setattr(store, 'sync_projects', fail_second)
with pytest.raises(TaskCenterError):
create_project_tasks(store, root)
assert store.list_tasks() == ()
def test_completed_project_can_be_created_as_new_task(tmp_path):
root = tmp_path / 'projects'
root.mkdir()
(root / 'a.prj').write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n', encoding='ascii')
store = TaskStore(tmp_path / 'tasks.db')
first = create_project_tasks(store, root)[0]
from dx_productivity.trial_task_center.models import TaskStatus
store.set_task_status(first.task_id, TaskStatus.READY)
store.set_task_status(first.task_id, TaskStatus.RUNNING)
store.set_task_status(first.task_id, TaskStatus.COMPLETED)
second = create_project_tasks(store, root)
assert len(second) == 1
assert second[0].name == 'a.prj (2)'
assert second[0].primary_project_id != first.primary_project_id
def test_target_rules_preserve_distinct_subsets_of_same_old_part():
rows = (
TargetPlanRow(target('u1', 'R1'), True, 'NEW-A'),
TargetPlanRow(target('u2', 'R2'), False, ''),
TargetPlanRow(target('u3', 'R3'), True, 'NEW-B', True, 'VALUE', False),
)
rules = compile_target_rules(rows)
assert len(rules) == 2
assert {(rule.new_part_number, tuple(item.uid for item in rule.targets)) for rule in rules} == {
('NEW-A', ('u1',)), ('NEW-B', ('u3',))
}
@pytest.mark.parametrize('new_part', ['', 'OLD'])
def test_enabled_target_requires_valid_replacement(new_part):
with pytest.raises(TaskCenterError):
compile_target_rules((TargetPlanRow(target('u1', 'R1'), True, new_part),))
def test_empty_target_group_rejected():
from dx_productivity.trial_task_center.target_plan import TargetRule
with pytest.raises(TaskCenterError):
TargetRule('OLD', 'NEW', ())
def test_plan_edit_is_atomic_and_survives_reopen(tmp_path):
store = TaskStore(tmp_path / 'tasks.db')
task = store.create_task('board')
path = tmp_path / 'board.prj'
store.sync_projects(task.task_id, tmp_path, (path,))
base = ComponentTarget(path, 'MAIN', '1', 'u1', 'R1', 'OLD', 'V0')
store.record_target_inventory(task.task_id, (base,))
saved = store.replace_target_plan(task.task_id, (TargetPlanRow(base, True, 'NEW', True, 'V1', False),))
assert saved[0].new_part_number == 'NEW'
with pytest.raises(TaskCenterError):
forged = ComponentTarget(path, 'MAIN', '1', 'u1', 'R1', 'WRONG', 'V0')
store.replace_target_plan(task.task_id, (TargetPlanRow(forged, True, 'OTHER'),))
assert store.list_target_plan(task.task_id) == saved
store.close()
reopened = TaskStore(tmp_path / 'tasks.db')
assert reopened.list_target_plan(task.task_id) == saved
def test_plan_rejects_duplicate_uid_and_chain(tmp_path):
store = TaskStore(tmp_path / 'tasks.db')
task = store.create_task('board')
path = tmp_path / 'board.prj'
store.sync_projects(task.task_id, tmp_path, (path,))
a = ComponentTarget(path, 'MAIN', '1', 'u1', 'R1', 'OLD', '')
b = ComponentTarget(path, 'MAIN', '1', 'u2', 'R2', 'NEW', '')
store.record_target_inventory(task.task_id, (a, b))
with pytest.raises(TaskCenterError):
store.replace_target_plan(task.task_id, (TargetPlanRow(a), TargetPlanRow(a)))
with pytest.raises(TaskCenterError):
store.replace_target_plan(task.task_id, (TargetPlanRow(a, True, 'NEW'), TargetPlanRow(b, True, 'NEXT')))
def test_forged_initial_plan_cannot_create_inventory(tmp_path):
store = TaskStore(tmp_path / 'tasks.db')
task = store.create_task('board')
path = tmp_path / 'board.prj'
store.sync_projects(task.task_id, tmp_path, (path,))
forged = ComponentTarget(path, 'MAIN', '1', 'forged', 'R1', 'OLD', '')
with pytest.raises(TaskCenterError):
store.replace_target_plan(task.task_id, (TargetPlanRow(forged, True, 'NEW'),))
assert store.get_task(task.task_id).target_plan_mode is False
def test_purge_deletes_target_plan_with_its_task(tmp_path):
store = TaskStore(tmp_path / 'tasks.db')
task = store.create_task('board')
path = tmp_path / 'board.prj'
store.sync_projects(task.task_id, tmp_path, (path,))
store.record_target_inventory(task.task_id, (ComponentTarget(path, 'MAIN', '1', 'u1', 'R1', 'OLD', ''),))
store.soft_delete_task(task.task_id)
assert store.purge_task(task.task_id) == task.task_id
assert store.list_tasks() == ()
def test_schema_five_migrates_without_changing_historic_task_and_rules(tmp_path):
import sqlite3
path = tmp_path / 'tasks.db'
store = TaskStore(path)
task = store.create_task('historic')
rule = store.add_rule(task.task_id, 'OLD', 'NEW')
store.close()
connection = sqlite3.connect(path)
connection.execute('DROP TABLE target_plan')
for column in ('target_plan_mode', 'primary_project_id', 'group_position', 'group_id'):
connection.execute(f'ALTER TABLE tasks DROP COLUMN {column}')
connection.execute("UPDATE metadata SET value = '5' WHERE key = 'schema_version'")
connection.commit()
connection.close()
migrated = TaskStore(path)
assert migrated.get_task(task.task_id).name == 'historic'
assert migrated.get_task(task.task_id).target_plan_mode is False
assert migrated.list_rules(task.task_id) == (rule,)
+36
View File
@@ -0,0 +1,36 @@
from pathlib import Path
import pytest
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.inventory import read_component_inventory
def test_inventory_reads_distinct_uids_on_same_sheet(tmp_path):
project = tmp_path / 'board.prj'
inventory = tmp_path / 'components.tsv'
inventory.write_text(
'project_path\tschematic_name\tsheet_number\tuid\trefdes\told_part\told_value\n'
f'{project}\tMAIN\t1\tu1\tR1\tOLD\tV1\n'
f'{project}\tMAIN\t1\tu2\tR2\tOLD\tV2\n', encoding='utf-8')
rows = read_component_inventory(inventory, project, (('MAIN', '1'),))
assert [(row.uid, row.refdes, row.old_value) for row in rows] == [
('u1', 'R1', 'V1'), ('u2', 'R2', 'V2')]
def test_inventory_rejects_forged_sheet_or_duplicate_uid(tmp_path):
project = tmp_path / 'board.prj'
inventory = tmp_path / 'components.tsv'
inventory.write_text(
'project_path\tschematic_name\tsheet_number\tuid\trefdes\told_part\told_value\n'
f'{project}\tOTHER\t1\tu1\tR1\tOLD\tV1\n', encoding='utf-8')
with pytest.raises(TaskCenterError):
read_component_inventory(inventory, project, (('MAIN', '1'),))
inventory.write_text(
'project_path\tschematic_name\tsheet_number\tuid\trefdes\told_part\told_value\n'
f'{project}\tMAIN\t1\tu1\tR1\tOLD\tV1\n'
f'{project}\tMAIN\t1\tu1\tR1\tOLD\tV1\n', encoding='utf-8')
with pytest.raises(TaskCenterError):
read_component_inventory(inventory, project, (('MAIN', '1'),))
@@ -0,0 +1,56 @@
from pathlib import Path
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.quick_run import QuickRunPreparer
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
def service(tmp_path):
store = TaskStore(tmp_path / 'tasks.db')
script = tmp_path / 'QuickPartReplace.vbs'
script.write_text("' fixture\n", encoding='ascii')
logging = configure_logging(tmp_path / 'data')
preparer = QuickRunPreparer(logging.root, script_source=script,
run_token_factory=lambda: 'run_abc',
sheet_discoverer=lambda path: (('MAIN', '1'),))
return TaskCenterService(store, logging, quick_run_preparer=preparer), store
def test_bound_task_handoff_uses_per_task_root_and_only_target_rules(tmp_path):
app, store = service(tmp_path)
task = store.create_task('board')
path = tmp_path / 'board.prj'
path.touch()
project = store.sync_projects(task.task_id, tmp_path, (path,))[0]
project = store.set_project_selected(project.project_id, True)
store.bind_project_task(task.task_id, project.project_id, 'group', 0)
store.add_rule(task.task_id, 'OLD', 'WHOLE-SHEET')
target = ComponentTarget(path, 'MAIN', '1', 'u1', 'R1', 'OLD', 'V0')
store.record_target_inventory(task.task_id, (target,))
store.replace_target_plan(task.task_id, (TargetPlanRow(target, True, 'ONLY-R1'),))
result = app.prepare_quick_run(task.task_id)
assert result.command_path.parent == app._logging.root / 'tasks' / task.task_id / 'quick-run'
command = result.command_path.read_text(encoding='utf-8')
assert 'ONLY-R1' in command
assert 'WHOLE-SHEET' not in command
assert app.has_quick_run_evidence(task.task_id)
def test_empty_collected_inventory_never_uses_legacy_full_match(tmp_path):
app, store = service(tmp_path)
task = store.create_task('board')
path = tmp_path / 'board.prj'
project = store.sync_projects(task.task_id, tmp_path, (path,))[0]
store.bind_project_task(task.task_id, project.project_id, 'group', 0)
store.add_rule(task.task_id, 'OLD', 'WHOLE-SHEET')
store.record_target_inventory(task.task_id, ())
with pytest.raises(TaskCenterError):
app.for_project_task(task.task_id)._execution_rules(task.task_id)
+74
View File
@@ -0,0 +1,74 @@
from pathlib import Path
import pytest
from openpyxl import load_workbook
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.spreadsheet_plan import export_target_plan, import_target_plan, read_target_plan
from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.target_plan import ComponentTarget, TargetPlanRow
def prepared(tmp_path):
store = TaskStore(tmp_path / 'tasks.db')
task = store.create_task('board')
path = tmp_path / 'board.prj'
store.sync_projects(task.task_id, tmp_path, (path,))
base = ComponentTarget(path, 'MAIN', '1', 'u1', 'R1', 'OLD', 'V0')
store.record_target_inventory(task.task_id, (base,))
return store, task
def test_excel_roundtrip_edits_value_and_nc(tmp_path):
store, task = prepared(tmp_path)
xlsx = tmp_path / 'plan.xlsx'
export_target_plan(store, task.task_id, xlsx)
workbook = load_workbook(xlsx)
sheet = workbook.active
sheet['I2'] = True
sheet['J2'] = 'NEW'
sheet['K2'] = True
sheet['L2'] = 'VALUE'
sheet['M2'] = False
workbook.save(xlsx)
imported = import_target_plan(store, task.task_id, xlsx)
assert imported == store.list_target_plan(task.task_id)
assert (imported[0].enabled, imported[0].new_part_number, imported[0].custom_value,
imported[0].sync_nc) == (True, 'NEW', 'VALUE', False)
def test_excel_preview_rejects_equal_rule_without_mutating_saved_plan(tmp_path):
store, task = prepared(tmp_path)
xlsx = tmp_path / 'plan.xlsx'
export_target_plan(store, task.task_id, xlsx)
workbook = load_workbook(xlsx)
sheet = workbook.active
sheet['I2'] = True
sheet['J2'] = 'OLD'
workbook.save(xlsx)
with pytest.raises(TaskCenterError):
read_target_plan(store, task.task_id, xlsx)
assert store.list_target_plan(task.task_id)[0].enabled is False
@pytest.mark.parametrize('change', ['forged', 'duplicate'])
def test_excel_rejects_forged_or_duplicate_identity_atomically(tmp_path, change):
store, task = prepared(tmp_path)
xlsx = tmp_path / 'plan.xlsx'
export_target_plan(store, task.task_id, xlsx)
workbook = load_workbook(xlsx)
sheet = workbook.active
if change == 'forged':
sheet['E2'] = 'forged-uid'
else:
sheet.append([cell.value for cell in sheet[2]])
workbook.save(xlsx)
with pytest.raises(TaskCenterError):
import_target_plan(store, task.task_id, xlsx)
assert store.list_target_plan(task.task_id)[0].enabled is False
+129
View File
@@ -0,0 +1,129 @@
from datetime import datetime, timezone
from pathlib import Path
import pytest
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.models import ProjectRecord, ProjectStatus
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer, _queue_matches_inputs, _read_commands
from dx_productivity.trial_task_center.target_plan import ComponentTarget, TargetPlanRow, compile_target_rules
from dx_productivity.trial_task_center.native_helper import check_context, verify_unselected_snapshot
from dx_productivity.trial_task_center.recovery import _recovery_command
def setup_queue(tmp_path):
script = tmp_path / 'QuickPartReplace.vbs'
script.write_text("' test script\n", encoding='ascii')
project_path = tmp_path / 'board.prj'
project_path.touch()
project = ProjectRecord('p', 't', 'board', project_path, tmp_path, True, True,
ProjectStatus.PENDING, 0)
rows = (
TargetPlanRow(ComponentTarget(project_path, 'MAIN', '1', 'u1', 'R1', 'OLD', 'A'), True, 'NEW-A'),
TargetPlanRow(ComponentTarget(project_path, 'MAIN', '1', 'u2', 'R2', 'OLD', 'B')),
TargetPlanRow(ComponentTarget(project_path, 'MAIN', '1', 'u3', 'R3', 'OLD', 'C'), True, 'NEW-B'),
)
rules = compile_target_rules(rows)
preparer = QuickRunPreparer(tmp_path / 'data', script_source=script,
run_token_factory=lambda: 'run_abc')
return preparer, project, rules
def test_target_queue_contains_only_selected_uid_refdes_pairs(tmp_path):
preparer, project, rules = setup_queue(tmp_path)
handoff = preparer.prepare('t', (project,), rules,
sheet_targets={str(project.path).casefold(): (('MAIN', '1'),)})
lines = handoff.command_path.read_text(encoding='utf-8').splitlines()
header = lines[0].split('\t')
values = [dict(zip(header, line.split('\t'))) for line in lines[1:]]
assert len(values) == 2
assert [value['target_scope'] for value in values] == ['targets', 'targets']
assert [value['target_selectors'] for value in values] == ['u1%001FR1%001FA', 'u3%001FR3%001FC']
assert _queue_matches_inputs(handoff.command_path, _read_commands(handoff.command_path),
(project,), rules)
changed = compile_target_rules((TargetPlanRow(rules[0].targets[0], True, 'OTHER'),))
assert not _queue_matches_inputs(handoff.command_path, _read_commands(handoff.command_path),
(project,), changed)
def test_target_queue_rejects_missing_scanned_sheet(tmp_path):
preparer, project, rules = setup_queue(tmp_path)
with pytest.raises(TaskCenterError):
preparer.prepare('t', (project,), rules,
sheet_targets={str(project.path).casefold(): (('OTHER', '1'),)})
def test_recovery_selects_saved_unverified_job_before_next_pending_job():
commands = (('t', 'a', 'board.prj', 'OLD', 'NEW'),
('t', 'b', 'board.prj', 'OTHER', 'NEXT'))
statuses = (('a', 'batch_saved_unverified', '', 'readback failed'),)
assert _recovery_command(commands, statuses) == commands[0]
def test_native_context_rejects_missing_or_changed_target_without_no_match():
class Component:
def __init__(self, uid, refdes, part, value):
self.UID, self.Refdes = uid, refdes
self.attributes = {'Part Number': part, 'Value': value}
self.Selected = False
self._oleobj_ = self
def FindAttribute(self, name):
value = self.attributes.get(name)
return None if value is None else type('Attr', (), {'InstanceValue': value, 'Value': value})()
class View:
def __init__(self, components):
self.components = components
self.Block = type('Block', (), {'SheetNum': '1'})()
def GetName(self, index):
return 'MAIN'
def Query(self, kind, selected):
return [item for item in self.components if not selected or item.Selected]
class App:
def __init__(self, components):
self.ActiveView = View(components)
def GetProjectData(self):
return type('Project', (), {'GetProjectFilePath': lambda self: 'C:/board.prj'})()
class Api:
IVdComp = staticmethod(lambda value: value)
metadata = ['M', 'C:/board.prj', 'OLD', 'NEW', 'MAIN:1', 'preserve', '', '1',
'targets', 'u1\x1fR1\x1fA']
record = ['C', 'u1', 'R1', '0', '0', '0', '0', '']
components = [Component('u1', 'R1', 'OLD', 'A'), Component('u2', 'R2', 'OLD', 'B')]
components[0].Selected = True
assert len(check_context(App(components), Api, metadata, [record])) == 2
components[0].attributes['Value'] = 'changed'
with pytest.raises(ValueError):
check_context(App(components), Api, metadata, [record])
components[0].attributes['Value'] = 'A'
components.pop(0)
with pytest.raises(ValueError):
check_context(App(components), Api, metadata, [record])
def test_native_rejects_changed_unselected_component_since_snapshot(tmp_path):
class Component:
UID = 'u2'
Refdes = 'R2'
def FindAttribute(self, name):
values = {'Part Number': 'OLD', 'Value': 'CHANGED', 'Part Name': '', 'Part Label': ''}
value = values[name]
return type('Attr', (), {'InstanceValue': value, 'Value': value})()
snapshot = tmp_path / 'snapshot.tsv'
snapshot.write_text('M\tC:/board.prj\tOLD\tNEW\tMAIN:1\tpreserve\t\t1\ttargets\tu1%001FR1%001FA\n'
'C\tu1\tR1\t0\t0\t0\t0\t\n'
'U\tu2\tR2\tOLD\tORIGINAL\t\t\n', encoding='utf-8')
with pytest.raises(ValueError):
verify_unselected_snapshot(snapshot, [Component()], {'u1'})