fix: allow replacement without an explicit target cell

This commit is contained in:
阿白叔 committed 2026-10-19 16:15:21 +08:00
1 parent 81a8547352
commit d12478efd8
10 files changed
+141 -68

No files matched your search

+31
View File
@@ -329,3 +329,34 @@ def test_standalone_recovery_allows_cold_catalog_preflight_before_worker(interru
return run_worker(command, timeout)
interrupted.preparer._process_runner = run
assert invoke(interrupted).state == 'restored_ok'
@pytest.mark.parametrize('queue_has_cell_column', [False, True])
def test_recovery_without_cell_retains_protection_until_verified_without_catalog(interrupted, queue_has_cell_column):
f = interrupted
f.rules = (SimpleNamespace(old_part_number='OLD', new_part_number='NEW', enabled=True, target_cell=''),)
lines = f.handoff.command_path.read_text(encoding='utf-8').splitlines()
header, row = lines[0].split('\t'), lines[1].split('\t')
index = header.index('target_cell')
if queue_has_cell_column:
row[index] = ''
else:
header.pop(index); row.pop(index)
f.handoff.command_path.write_text('\t'.join(header)+'\n'+'\t'.join(row)+'\n',encoding='utf-8')
f.snapshot.write_text(f.snapshot.read_text().replace('L\tCELL\n',''),encoding='utf-8')
metadata, components = read_snapshot(f.snapshot)
f.report['transaction'] = transaction_binding(f.snapshot, metadata, components,
['library', 'NEW', 'symbol', '', 'cap', 'label'], 'symbol')
f.snapshot.with_suffix('.tsv.native.json').write_text(json.dumps(f.report),encoding='utf-8')
f.catalog_reads.clear()
run_worker = worker_result(f)
def run(command, timeout):
assert not f.catalog_reads
worker = Path(command[3])
text = (worker/'command.tsv').read_text(encoding='utf-8')
assert 'target_cell' not in text.splitlines()[0]
assert 'recovery_library_path' not in text.splitlines()[0]
return run_worker(command, timeout)
f.preparer._process_runner = run
assert invoke(f).state == 'restored_ok'
assert not f.lock.exists() and not f.catalog_reads
+64 -10
View File
@@ -41,12 +41,14 @@ def test_native_binding_binds_cell_and_rejects_changed_selection(tmp_path):
native_helper.require_resumable_transaction(snapshot,report,meta,records)
def test_native_missing_cell_stops_before_attaching_to_cad(tmp_path,monkeypatch):
def test_native_without_cell_reaches_cad_without_reading_cell_catalog(tmp_path,monkeypatch):
snapshot=tmp_path/'snapshot.tsv';snapshot.write_text('M\tproject\tOLD\tNEW\tsheet\nC\tuid\tR1\t0\t0\t0\t1\tpins\n')
calls=[];monkeypatch.setattr(native_helper,'attach',lambda:calls.append('attach'))
with pytest.raises(ValueError,match='Cell'):
def attach():
raise RuntimeError('CAD boundary reached')
monkeypatch.setattr(native_helper,'attach',attach)
with pytest.raises(RuntimeError,match='CAD boundary reached'):
native_helper.run_native(snapshot,{})
assert calls==[]
@pytest.mark.parametrize('mode',['ok','missing','readonly'])
def test_cell_instance_write_is_explicit_and_verified(tmp_path,mode):
@@ -113,13 +115,13 @@ def test_actual_project_library_catalog_controls_choice(tmp_path,monkeypatch,cho
assert captured==[(library,'NEW',{'allow_cold_read':False})]
@pytest.mark.parametrize('fail_at', [1, 2])
@pytest.mark.parametrize('fail_at', [None, 1, 2])
def test_native_catalog_checks_cannot_cold_read_or_submit_on_miss(tmp_path, monkeypatch, fail_at):
import ctypes
import sys
snapshot = tmp_path / 'snapshot.tsv'
snapshot.write_text('M\tproject\tOLD\tNEW\tsheet\tpreserve\nL\tCELL_OK\nC\tuid\tR1\t0\t0\t0\t1\tpins\n')
snapshot.write_text('M\tproject\tOLD\tNEW\tsheet\tpreserve\n' + ('L\tCELL_OK\n' if fail_at else '') + 'C\tuid\tR1\t0\t0\t0\t1\tpins\n')
library = tmp_path / 'lib.lmc'
app = SimpleNamespace(ActiveViewHandle=1, GetProjectData=lambda: SimpleNamespace(
CentralLibraryPath=str(library), GetSlotsCount=lambda *args: 1))
@@ -149,6 +151,7 @@ def test_native_catalog_checks_cannot_cold_read_or_submit_on_miss(tmp_path, monk
ctypes.memmove(lparam, buffer, ctypes.sizeof(buffer))
elif code == 0xF5 and handle == 1695:
submits.append(handle)
raise RuntimeError('native submit reached')
gui = SimpleNamespace(error=RuntimeError, GetAncestor=lambda *args: 1, EnumWindows=enum_windows,
EnumChildWindows=lambda *args: None, IsWindowVisible=lambda handle: True,
GetClassName=lambda handle: {2: '#32770', 3: 'SysListView32', 4: 'Edit'}.get(handle, 'Main'),
@@ -179,18 +182,46 @@ def test_native_catalog_checks_cannot_cold_read_or_submit_on_miss(tmp_path, monk
monkeypatch.setattr(native_helper, 'wait_for_library_rows', lambda callback, *args: callback())
monkeypatch.setattr(native_helper, 'wait_for_native_target', lambda callback, *args: callback())
report = {}
with pytest.raises(ValueError, match='重新读取目标封装'):
with pytest.raises(ValueError if fail_at else RuntimeError, match='重新读取目标封装' if fail_at else 'native submit reached'):
native_helper.run_native(snapshot, report)
if fail_at is None:
assert not reads and submits == [1695]
assert 'target_cell' not in report['transaction']
assert 'cell_catalog' not in report['transaction']
return
assert reads == [(library, 'NEW', {'allow_cold_read': False})] * fail_at
assert not submits
assert 'transaction' not in report and 'stage' not in report
def test_legacy_recovery_evidence_cannot_upgrade_without_explicit_cell(tmp_path):
@pytest.mark.parametrize('binding', [{}, {'target_cell':'CELL'}, {'cell_catalog':{}}])
def test_no_cell_recovery_does_not_read_catalog_or_accept_added_cell_proof(tmp_path, binding, monkeypatch):
from dx_productivity.trial_task_center import recovery
snapshot=tmp_path/'snapshot.tsv';snapshot.write_text('M\tproject\tOLD\tNEW\tsheet\n')
with pytest.raises(ValueError,match='Cell'):
recovery.require_current_cell_binding(snapshot,{},tmp_path/'project.prj',['M','project','OLD','NEW','sheet'])
def unexpected(*args, **kwargs):
raise AssertionError('Optional Cell must not read a catalog')
monkeypatch.setattr(recovery,'cell_catalog_binding',unexpected)
if binding:
with pytest.raises(ValueError,match='Cell'):
recovery.require_current_cell_binding(snapshot,binding,tmp_path/'project.prj',['M','project','OLD','NEW','sheet'])
else:
assert recovery.require_current_cell_binding(snapshot,binding,tmp_path/'project.prj',['M','project','OLD','NEW','sheet']) is None
@pytest.mark.parametrize('field', [None, ''])
def test_vbs_optional_cell_does_not_inspect_or_write_component(tmp_path,field):
import test_accuracy_vbs_guards as guards
output=guards.run_vbs(tmp_path,['QPSetTargetCell','QPVerifyTargetCell','QPTargetCell','QPDecode','QPFindCurrentAttribute','QPEffectiveAttributeValue','QPRequiredAttributeValue'],'''
Dim Comp,Command
Set Comp=Nothing:Set Command=CreateObject("Scripting.Dictionary")
'''+('Command.Add "target_cell",""' if field == '' else '')+'''
QPSetTargetCell Comp,Command
QPVerifyTargetCell Comp,Command
WScript.Echo "UNCHANGED"
''')
assert output.strip()=='UNCHANGED'
@pytest.mark.parametrize('fault',['','duplicate','empty','extra'])
def test_vbs_cell_snapshot_roundtrip_rejects_malformed_selection(tmp_path,fault):
@@ -221,3 +252,26 @@ def test_cell_catalog_cache_is_shared_by_project_tasks_but_outside_queue(tmp_pat
assert native_helper.cell_catalog_evidence_root(snapshot)==data/'cell-catalog'
plain=data/'quick-run'/'snapshot-job.tsv';plain.parent.mkdir();plain.write_text('snapshot')
assert native_helper.cell_catalog_evidence_root(plain)==data/'cell-catalog'
def test_mixed_optional_cells_roundtrip_and_binding_changes_invalidate_queue(tmp_path):
project=SimpleNamespace(path=tmp_path/'one.prj')
path=tmp_path/'command.tsv'
rules=(rule(''),rule('CELL_A'))
path.write_text(quick_run._command_text('task','token',(project,),rules,'preserve'),encoding='utf8',newline='')
commands=quick_run._read_commands(path)
assert list(quick_run._read_command_cells(path).values())==['','CELL_A']
assert quick_run._queue_matches_inputs(path,commands,(project,),rules)
assert not quick_run._queue_matches_inputs(path,commands,(project,),(rule('CELL_A'),rule('')))
@pytest.mark.parametrize('extra', [{'target_cell':'CELL'}, {'cell_catalog':{}}])
def test_unselected_snapshot_rejects_added_cell_transaction_evidence(tmp_path, extra):
snapshot=tmp_path/'snapshot.tsv';snapshot.write_text('M\tproject\tOLD\tNEW\tsheet\n')
metadata=['M','project','OLD','NEW','sheet'];records=[['C','uid','R1','0','0','0','1','pins']]
binding=native_helper.transaction_binding(snapshot,metadata,records,['lib','NEW','sym','','part','label'],'sym')
report={'stage':'native_replace_verified','transaction':binding}
assert native_helper.require_resumable_transaction(snapshot,report,metadata,records)==binding
binding.update(extra)
with pytest.raises(ValueError,match='Cell'):
native_helper.require_resumable_transaction(snapshot,report,metadata,records)
+12 -14
View File
@@ -96,16 +96,13 @@ def test_bom_keeps_same_mapping_cell_and_clears_changed_mapping(batch, tmp_path)
assert match_bom_records(baseline, changed)[0].target_cell == ''
def test_missing_cell_preflight_blocks_enabled_rules_but_allows_disabled_draft(batch):
app, store, tasks = batch
task = tasks[0]
rule = app.add_rule(task.task_id, 'OLD', 'NEW')
with pytest.raises(TaskCenterError, match='封装'):
app.validate_target_cells(task.task_id)
app.update_rule(rule.rule_id, old_part_number='OLD', new_part_number='NEW', enabled=True, target_cell='CellA')
app.validate_target_cells(task.task_id)
app.update_rule(rule.rule_id, old_part_number='OLD', new_part_number='OTHER', enabled=False)
app.validate_target_cells(task.task_id)
def test_mapping_dialog_accepts_unselected_optional_cell(qtbot):
dialog = _MappingDialog(None, 'OLD', 'NEW')
qtbot.addWidget(dialog)
dialog._accept_if_valid()
assert dialog.result() == dialog.DialogCode.Accepted
assert dialog.target_cell == ''
assert '可选' in dialog.cell_combo.itemText(0)
def test_dialog_pn_changes_clear_selection_and_stale_async_results(qtbot):
@@ -212,7 +209,7 @@ def test_catalog_includes_every_batch_project_even_when_unselected_or_unavailabl
@pytest.mark.parametrize('batch_run', [False, True])
def test_gui_preflight_blocks_before_confirmation_or_execution(window, qtbot, tmp_path, monkeypatch, batch_run):
def test_gui_optional_cell_reaches_confirmation_without_starting_execution(window, qtbot, tmp_path, monkeypatch, batch_run):
from test_ui_batch_retry import open_project
tasks = open_project(window, qtbot, tmp_path, multiple=True)
window.service.add_rule(tasks[0].task_id, 'OLD', 'NEW')
@@ -220,12 +217,13 @@ def test_gui_preflight_blocks_before_confirmation_or_execution(window, qtbot, tm
qtbot.waitUntil(lambda: not window._loading and not window._context_query.busy)
errors, confirmations = [], []
monkeypatch.setattr(window, '_show_error', errors.append)
window._quick_run_confirmer = lambda *args: confirmations.append(args) or True
window._quick_run_confirmer = lambda *args: confirmations.append(args) or False
window.run_panel.quick_run_button.setEnabled(True)
window.task_list.queue_button.setEnabled(True)
(window._execute_project_tasks if batch_run else window._prepare_quick_run)()
assert [error.code for error in errors] == ['target_cell_required']
assert not confirmations and not window._workers and window._batch_stop is None
assert not errors
assert len(confirmations) == 1
assert not window._workers and window._batch_stop is None
def test_dialog_single_choice_requires_selection_and_failures_allow_retry(qtbot):