From d12478efd89f340baa7587b37b8d0eac925e04b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=98=BF=E7=99=BD=E5=8F=94?= <11794527+absfan@user.noreply.gitee.com> Date: Mon, 19 Oct 2026 16:15:21 +0800 Subject: [PATCH] fix: allow replacement without an explicit target cell --- docs/user/target-cell-selection.md | 14 ++-- .../dxdesigner795/QuickPartReplace.vbs | 5 +- .../trial_task_center/native_helper.py | 10 ++- .../trial_task_center/recovery.py | 15 ++-- .../trial_task_center/service.py | 7 -- .../trial_task_center/ui/dialogs.py | 16 ++-- .../trial_task_center/ui/main_window.py | 11 --- tests/trial_task_center/test_recovery.py | 31 ++++++++ tests/v1_1/test_target_cell_execution.py | 74 ++++++++++++++++--- tests/v1_1/test_target_cell_rules.py | 26 +++---- 10 files changed, 141 insertions(+), 68 deletions(-) diff --git a/docs/user/target-cell-selection.md b/docs/user/target-cell-selection.md index 9bbd68b..4db8150 100644 --- a/docs/user/target-cell-selection.md +++ b/docs/user/target-cell-selection.md @@ -2,17 +2,17 @@ 此功能属于当前开发分支,尚未打包到 V1.1.2 下载包。 -一个新料号可能关联多个合法封装。工具要求明确选择目标 Cell Name;未选择时可以保存草稿,但不能执行。不会自动选第一个候选,也不会自动沿用旧器件封装。升级前的规则会保留为空,需要补选。 +一个新料号可能关联多个合法封装。目标 Cell Name 为可选项:留空可以直接执行,工具不主动覆写封装,可后续与中心库同步;原生替换本身可能更新库关联属性,因此留空不承诺封装保持不变。需要本次指定封装时,再读取并明确选择;工具不会自动选第一个候选。升级前的规则保留为空,不需要为执行而补选。 ## 配置步骤 1. 创建工程任务,打开顶部 **本批料号规则**,添加或编辑旧、新料号。 -2. 点击 **读取封装**,等待后台读取中央库。在 **目标封装** 下拉框中明确选择一项;只有一个候选时也需要选择。 +2. 无需本次修改封装时,保留 **不指定封装(可选)** 即可。如需指定,点击 **读取封装**,等待后台读取中央库,再明确选择一项;不会自动选择单一候选。 3. 保存规则,在 **本批料号规则** 中核对对应旧、新料号的 **目标封装**。直接采集位号或导入 BOM,保存计划后执行。 ![目标封装规则编辑器](media/target-cell-rule-editor.png) -也可以先导入并保存 BOM,再添加与计划中旧、新料号一致的规则并选择封装。相同映射中尚未选择封装的计划行会补齐;已有独立选择、自定义 Value、NC 和位号勾选会保留。手动修改计划的新料号后,原封装选择会清空,需要在对应规则中重新配置。 +也可以先导入并保存 BOM,再添加与计划中旧、新料号一致的规则并选择封装。相同映射中尚未选择封装的计划行会补齐;已有独立选择、自定义 Value、NC 和位号勾选会保留。手动修改计划的新料号后,原封装选择会清空;需要本次指定封装时,再到对应规则重新配置。 默认 BOM 继续使用原来的 **11 列**,没有增加封装列。同批规则由所有任务共享,候选取本批各工程中央库的共同可用项;无共同候选时,需要检查库配置或将工程分成不同批次。 @@ -20,10 +20,10 @@ 读取期间可以继续操作界面。更换新料号、改变工程范围或关闭弹窗后,旧请求返回的结果不会覆盖新选择。失败后可以再次点击 **读取封装**。已有 Library Manager 正在运行时,请关闭它后重试候选读取。 -工具通过中央库副本读取关联,不打开原库进行编辑。首次读取可能较慢;本机样例冷读取约 84 秒,缓存命中约 2~4 秒,其他机器和库不保证相同时间。执行前和原生替换提交前都只复用已核验缓存,并重新核对实际工程的完整源库指纹与所选候选。缓存缺失、损坏或源库变化时,会在替换提交前停止,提示 **请在料号规则中重新读取目标封装**;重新读取并核对选择后再执行。 +工具通过中央库副本读取关联,不打开原库进行编辑。首次读取可能较慢;本机样例冷读取约 84 秒,缓存命中约 2~4 秒,其他机器和库不保证相同时间。只有明确选择封装的步骤会执行库目录核验;留空步骤不读取封装目录、不等待 Library Manager。已选择时,执行前和原生替换提交前都只复用已核验缓存,并重新核对实际工程的完整源库指纹与所选候选。缓存缺失、损坏或源库变化时,会在替换提交前停止,提示 **请在料号规则中重新读取目标封装**;重新读取并核对选择后再执行。 -替换后显式写入选定的 Cell Name,并在保存前和磁盘重开后检查有效值。成功日志包含 `Target Cell verified` 及所选封装。属性写入、保存或回读不符合要求时,不会给出已保存成功结果。 +明确选择时,替换后显式写入选定的 Cell Name,并在保存前和磁盘重开后检查有效值。成功日志包含 `Target Cell verified` 及所选封装。属性写入、保存或回读不符合要求时,不会给出已保存成功结果。 -有中断或状态不确定的旧轮次时,先使用原版本完成核验恢复再升级。旧记录没有显式封装证据时,新流程不会把它自动认定为封装核验成功。 +有中断或状态不确定的旧轮次时,先使用原版本完成核验恢复再升级。未选封装的记录仍按原事务证据恢复,不增加封装成功声明;已选封装的记录必须保留并核对原封装证据。 -当前版本的中断任务仍保持保护时,规则编辑可能被锁定。使用 **核验恢复** 后,工具会在启动恢复 CAD 前独立预检封装;缓存被删除或失效时,可通过库副本重新读取,沿用读取器的互斥等待和工作进程超时限制。预检必须与原事务的源库、指纹、料号、分区、完整候选及封装选择完全一致;不一致或读取失败时保留保护,不启动恢复 CAD。原生替换过程仍只允许复用已核验缓存。 +当前版本的中断任务仍保持保护时,规则编辑可能被锁定。使用 **核验恢复** 后,只有原事务明确选择封装时,工具才会在启动恢复 CAD 前独立预检封装;缓存被删除或失效时,可通过库副本重新读取,沿用读取器的互斥等待和工作进程超时限制。预检必须与原事务的源库、指纹、料号、分区、完整候选及封装选择完全一致;不一致或读取失败时保留保护,不启动恢复 CAD。原生替换过程仍只允许复用已核验缓存。 diff --git a/integration/dxdesigner795/QuickPartReplace.vbs b/integration/dxdesigner795/QuickPartReplace.vbs index 403ee6d..061f085 100644 --- a/integration/dxdesigner795/QuickPartReplace.vbs +++ b/integration/dxdesigner795/QuickPartReplace.vbs @@ -2238,8 +2238,9 @@ Function QPTargetCell(ByRef Record) QPTargetCell = "" If Not Record.Exists("target_cell") Then Exit Function Value = QPDecode(CStr(Record("target_cell"))) - If Len(Value) = 0 Or Trim(Value) <> Value Then _ - Err.Raise vbObjectError + 878, "QuickPartReplace.Cell", "target Cell selection is empty or invalid" + If Len(Value) = 0 Then Exit Function + If Trim(Value) <> Value Then _ + Err.Raise vbObjectError + 878, "QuickPartReplace.Cell", "target Cell selection is invalid" For Index = 1 To Len(Value) If AscW(Mid(Value, Index, 1)) >= 0 And AscW(Mid(Value, Index, 1)) < 32 Then _ Err.Raise vbObjectError + 878, "QuickPartReplace.Cell", "invalid control character in target Cell" diff --git a/src/dx_productivity/trial_task_center/native_helper.py b/src/dx_productivity/trial_task_center/native_helper.py index d01e5f0..7350902 100644 --- a/src/dx_productivity/trial_task_center/native_helper.py +++ b/src/dx_productivity/trial_task_center/native_helper.py @@ -131,7 +131,7 @@ def transaction_binding(snapshot, metadata, records, library_row, symbol, slot_c if cell is not None: result["target_cell"] = cell if cell_catalog is not None: - if cell_catalog.get("selected") != cell or cell_catalog.get("part_partition") != str(library_row[0]): + if cell is None or cell_catalog.get("selected") != cell or cell_catalog.get("part_partition") != str(library_row[0]): raise ValueError("Native library row differs from authoritative Cell catalog") result["cell_catalog"] = cell_catalog return result @@ -160,6 +160,8 @@ def require_resumable_transaction(snapshot, report, metadata, records): expected["target_cell"] = cell if not isinstance(binding, dict) or any(binding.get(key) != value for key, value in expected.items()): raise ValueError("Native replacement evidence does not match this snapshot") + if cell is None and ("target_cell" in binding or "cell_catalog" in binding): + raise ValueError("Unexpected target Cell evidence for an unselected snapshot") library_row = binding.get("library_row") if not isinstance(library_row, list) or len(library_row) < 6: raise ValueError("Native replacement evidence has no target library identity") @@ -511,11 +513,11 @@ def run_native(snapshot, report): from pywinauto import Desktop metadata, records = read_snapshot(snapshot) - target_cell = snapshot_target_cell(snapshot) + target_cell = snapshot_target_cell(snapshot, required=False) require_part_label = snapshot_value_mode(metadata) == "part_label" app, api = attach() check_active_context(app, metadata) - cell_proof = target_cell_catalog(app, snapshot, metadata, target_cell) + cell_proof = target_cell_catalog(app, snapshot, metadata, target_cell) if target_cell is not None else None components = components_on_sheet(app, api) wanted = {row[1] for row in records} if len(metadata) == 10: @@ -697,7 +699,7 @@ def run_native(snapshot, report): if read_target() != ready: raise ValueError('Native target changed during final context verification') symbol = ready[1] - current_cell_proof = target_cell_catalog(app, snapshot, metadata, target_cell) + current_cell_proof = target_cell_catalog(app, snapshot, metadata, target_cell) if target_cell is not None else None if current_cell_proof != cell_proof: raise ValueError("Cell catalog changed before native replacement; no replacement submitted") report["transaction"] = transaction_binding(snapshot, metadata, records, columns, symbol, slot_count, diff --git a/src/dx_productivity/trial_task_center/recovery.py b/src/dx_productivity/trial_task_center/recovery.py index e0e10d4..58c43e7 100644 --- a/src/dx_productivity/trial_task_center/recovery.py +++ b/src/dx_productivity/trial_task_center/recovery.py @@ -86,7 +86,11 @@ def _recovery_copytree(source: Path, destination: Path) -> None: def require_current_cell_binding(snapshot, binding, project, metadata): - cell = snapshot_target_cell(snapshot) + cell = snapshot_target_cell(snapshot, required=False) + if cell is None: + if 'target_cell' in binding or 'cell_catalog' in binding: + raise ValueError('Unexpected target Cell evidence for an unselected snapshot') + return None if binding.get('target_cell') != cell or not isinstance(binding.get('cell_catalog'), dict): raise ValueError('Recovery has no bound target Cell catalog') from .cell_catalog import project_library_path @@ -160,8 +164,8 @@ def recover(preparer, task_id, projects, rules, *, copy_part_number_to_value=Fal raise ValueError('snapshot target scope missing from command') report = json.loads(snapshot.with_suffix('.tsv.native.json').read_text(encoding='utf-8')) binding = require_resumable_transaction(snapshot, report, metadata, components) - selected_cell = _read_command_cells(root / 'command.tsv').get(job_id) - if selected_cell != snapshot_target_cell(snapshot): + selected_cell = _read_command_cells(root / 'command.tsv').get(job_id) or None + if selected_cell != snapshot_target_cell(snapshot, required=False): raise ValueError('snapshot target Cell mismatch') cell_proof = require_current_cell_binding(snapshot, binding, Path(selected[2]), metadata) identity = binding['library_row'][4:6] @@ -213,8 +217,9 @@ def recover(preparer, task_id, projects, rules, *, copy_part_number_to_value=Fal if len(metadata) == 10: header += '\ttarget_scope\ttarget_selectors' row = (*row, 'targets', selectors) - header += '\ttarget_cell\trecovery_library_path' - row = (*row, _encode_vbs_field(selected_cell), _encode_vbs_field(cell_proof['library_path'])) + if selected_cell is not None: + header += '\ttarget_cell\trecovery_library_path' + row = (*row, _encode_vbs_field(selected_cell), _encode_vbs_field(cell_proof['library_path'])) (worker / 'command.tsv').write_text(header + '\n' + '\t'.join(row) + '\n', encoding='utf-8') _write_status_details(worker / 'status.tsv', ()) from .quick_run import _vbs_worker_paths diff --git a/src/dx_productivity/trial_task_center/service.py b/src/dx_productivity/trial_task_center/service.py index 9f2dbee..fc8003e 100644 --- a/src/dx_productivity/trial_task_center/service.py +++ b/src/dx_productivity/trial_task_center/service.py @@ -352,13 +352,6 @@ class TaskCenterService: ), ) - def validate_target_cells(self, task_id: str) -> None: - """Cheap draft preflight; the native commit revalidates library authority.""" - for rule in self._execution_rules(task_id): - if rule.enabled and not rule.target_cell.strip(): - raise TaskCenterError('target_cell_required', - f'新料号 {rule.new_part_number} 未选择目标封装,请编辑料号规则并读取选择 Cell Name') - def target_cell_projects(self, task_id: str) -> tuple[Path, ...]: """Capture the project scope used to bind asynchronous Cell choices.""" from .batch_rules import members diff --git a/src/dx_productivity/trial_task_center/ui/dialogs.py b/src/dx_productivity/trial_task_center/ui/dialogs.py index 3dc0fba..6d705b9 100644 --- a/src/dx_productivity/trial_task_center/ui/dialogs.py +++ b/src/dx_productivity/trial_task_center/ui/dialogs.py @@ -59,13 +59,13 @@ class _MappingDialog(QDialog): self._cell_workers = set() self._cell_closed = False self.cell_combo = QComboBox(objectName='targetCellCombo') - self.cell_combo.addItem('请选择目标封装', '') + self.cell_combo.addItem('不指定封装(可选)', '') if target_cell: self.cell_combo.addItem(target_cell, target_cell) self.cell_combo.setCurrentIndex(1) self.cell_load_button = QPushButton('读取封装', objectName='loadTargetCells') self.cell_load_button.setEnabled(cell_loader is not None) - self.cell_status = QLabel('已保存选择;可重新读取核对' if target_cell else '输入新料号后读取并选择封装') + self.cell_status = QLabel('已保存选择;可重新读取核对' if target_cell else '未指定时不主动修改封装,可后续与中心库同步') self.new_edit.textChanged.connect(self._new_part_changed) self.cell_combo.currentIndexChanged.connect(self._cell_selection_changed) self.cell_load_button.clicked.connect(self._load_cells) @@ -86,7 +86,7 @@ class _MappingDialog(QDialog): cell_row = QHBoxLayout() cell_row.addWidget(self.cell_combo, 1) cell_row.addWidget(self.cell_load_button) - form.addRow('目标封装', cell_row) + form.addRow('目标封装(可选)', cell_row) form.addRow('', self.cell_status) form.addRow("执行状态", self.enabled_check) form.addRow("自定义 Value", self.custom_value_check) @@ -119,14 +119,14 @@ class _MappingDialog(QDialog): def _cell_selection_changed(self, _index): self._cell_generation += 1 self.cell_load_button.setEnabled(self._cell_loader is not None) - self.cell_status.setText('已选择目标封装' if self.target_cell else '未选择目标封装,可保存草稿') + self.cell_status.setText('已选择目标封装' if self.target_cell else '未指定时不主动修改封装,可后续与中心库同步') def _new_part_changed(self, _text): self._cell_generation += 1 with QSignalBlocker(self.cell_combo): self.cell_combo.clear() - self.cell_combo.addItem('请选择目标封装', '') - self.cell_status.setText('新料号已改变,请重新读取封装') + self.cell_combo.addItem('不指定封装(可选)', '') + self.cell_status.setText('新料号已改变;如需指定封装,请重新读取') self.cell_load_button.setEnabled(self._cell_loader is not None) def _close_cells(self, _result): @@ -166,12 +166,12 @@ class _MappingDialog(QDialog): return with QSignalBlocker(self.cell_combo): self.cell_combo.clear() - self.cell_combo.addItem('请选择目标封装', '') + self.cell_combo.addItem('不指定封装(可选)', '') for choice in choices: self.cell_combo.addItem(choice, choice) index = self.cell_combo.findData(selected) self.cell_combo.setCurrentIndex(max(0, index)) - self.cell_status.setText(f'已读取 {len(choices)} 个封装,请明确选择' if choices else '未找到可用封装') + self.cell_status.setText(f'已读取 {len(choices)} 个封装;可留空或明确选择' if choices else '未找到可用封装') self.cell_load_button.setEnabled(True) def failed(error): if current(): diff --git a/src/dx_productivity/trial_task_center/ui/main_window.py b/src/dx_productivity/trial_task_center/ui/main_window.py index 8097a9f..c05dc55 100644 --- a/src/dx_productivity/trial_task_center/ui/main_window.py +++ b/src/dx_productivity/trial_task_center/ui/main_window.py @@ -494,11 +494,6 @@ class TrialTaskCenterWindow(QMainWindow): if not self.run_panel.quick_run_button.isEnabled(): return context = self._context - try: - self.service.validate_target_cells(context.task.task_id) - except TaskCenterError as error: - self._show_error(error) - return enabled = sum(row.enabled for row in context.targets) if context.task.target_plan_mode else sum(r.enabled for r in context.rules) if not self._quick_run_confirmer('current', 1, enabled): return @@ -519,12 +514,6 @@ class TrialTaskCenterWindow(QMainWindow): key=lambda t: t.group_position) if not tasks: return - try: - for task in tasks: - self.service.validate_target_cells(task.task_id) - except TaskCenterError as error: - self._show_error(error) - return token, ids = self._project_queues.get(group, (None, tuple(t.task_id for t in tasks))) if self.plan_panel.has_unsaved_plan(ids): self._set_operator_message('本批任务有未保存计划,请先逐个保存。', 'warning') diff --git a/tests/trial_task_center/test_recovery.py b/tests/trial_task_center/test_recovery.py index e2013f3..fa37ced 100644 --- a/tests/trial_task_center/test_recovery.py +++ b/tests/trial_task_center/test_recovery.py @@ -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 diff --git a/tests/v1_1/test_target_cell_execution.py b/tests/v1_1/test_target_cell_execution.py index e22fc2e..e8cf09d 100644 --- a/tests/v1_1/test_target_cell_execution.py +++ b/tests/v1_1/test_target_cell_execution.py @@ -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) diff --git a/tests/v1_1/test_target_cell_rules.py b/tests/v1_1/test_target_cell_rules.py index 5d07f8a..4b9bec3 100644 --- a/tests/v1_1/test_target_cell_rules.py +++ b/tests/v1_1/test_target_cell_rules.py @@ -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):