From 2fdbe3acb3116a90e565106b8da73340a3bdce3d 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: Thu, 15 Oct 2026 19:27:15 +0800 Subject: [PATCH] test: verify Part Label copying through live UI replacement and independent readback --- docs/testing/2026-10-15-bom-live-roundtrip.md | 2 + docs/testing/2026-10-15-part-label-live.md | 42 +++ tools/probe_part_label_live.py | 246 ++++++++++++++++++ 3 files changed, 290 insertions(+) create mode 100644 docs/testing/2026-10-15-part-label-live.md create mode 100644 tools/probe_part_label_live.py diff --git a/docs/testing/2026-10-15-bom-live-roundtrip.md b/docs/testing/2026-10-15-bom-live-roundtrip.md index 93c4652..25f7148 100644 --- a/docs/testing/2026-10-15-bom-live-roundtrip.md +++ b/docs/testing/2026-10-15-bom-live-roundtrip.md @@ -43,6 +43,8 @@ 未勾选复制 Value 时,沿用既有语义:保留原生替换后的目标 Value,不强制恢复旧 Value。选中器件的空 Value 不能单独作为替换失败依据;未选中 RV11 则应保持料号、位号、UID 和 Value 不变。 +后续补测已开启复制开关,真实替换后独立读取确认 `Part Label=0R`、`Value=0R`,详见 [Part Label 实测记录](2026-10-15-part-label-live.md)。 + ## 最终回读与回归 两个任务第二轮均返回 `saved_ok / session_verified`,包括真实保存、关闭、重开回读;之后另开全新后台 CAD 独立读取,得到: diff --git a/docs/testing/2026-10-15-part-label-live.md b/docs/testing/2026-10-15-part-label-live.md new file mode 100644 index 0000000..78b5658 --- /dev/null +++ b/docs/testing/2026-10-15-part-label-live.md @@ -0,0 +1,42 @@ +# Part Label 写入 Value 的实际替换验证 + +本次补测开启“替换后将 Part Label 写入 Value”的路径。功能代码没有修改;新增可重复运行的探针 `tools/probe_part_label_live.py`。证据位于 `build/part-label-live-20261015`,没有打包或发布。 + +使用原始 Audio_T605A 的新副本,导出默认 BOM 模板后填写 RV05 替换项,通过界面导入、保存、勾选复制开关,再点击执行当前任务。Qt 使用真实鼠标事件,文件选择返回值由探针注入,Excel 单元格用 openpyxl 编辑;CAD 替换、保存和读取均为本机真实 DxDesigner 调用。第一次探针鼠标坐标落在复选框留白,停在修改前;修正探针点击坐标后复用已保存计划继续,实际替换只执行一次。 + +## 结果 + +| 检查项 | 实际结果 | +| --- | --- | +| BOM 导入 | 1 行通过、0 行失败;库存 RV05、RV11 共 2 项,只启用 RV05 | +| 界面开关 | 已勾选,并持久化到任务 | +| 实际执行策略 | 命令的 `value_mode`、`base_value_mode` 均为 `part_label`;自定义 Value 关闭 | +| RV05 料号 | `4100-CA0000-T7` → `4100-CA0000-T0` | +| RV05 独立读取 | UID `$2I2014`,Part Label **0R**,Value **0R** | +| RV11 未选中 | UID `$2I2022`、料号 `4100-CA0000-T7`、Value **0R** 均保持原样 | +| 保存核验 | 原生替换、属性回读、保存、关闭、重开核验通过,任务完成 | +| 额外独立核验 | 另开全新私有 CAD 会话,直接读新料号、Part Label 和 Value;成功后不保存关闭 | +| 原工程 | 全目录文件哈希未变,且与上一轮对照测试的原工程哈希一致 | +| 主桌面及释放 | 1231 次采样均能读取主桌面文件,输入桌面保持 Default,自有 CAD 未抢前台;观察到的 7 个自有 CAD PID、7 个私有 desktop 均释放 | + +本次没有出现 CAD 启动超时,独立读取会话启动约 27.484 秒、收尾约 1.531 秒。最终系统仍只有用户原来的 CAD PID 18732,临时路径别名清理无错误。 + +与上一轮相同料号替换的对照: + +| 复制开关 | 替换后的料号 | 独立取得的 Value | +| --- | --- | --- | +| 关闭(上轮) | 4100-CA0000-T0 | 空,保留原生目标 Value | +| 开启(本轮) | 4100-CA0000-T0 | **0R,与 Part Label 一致** | + +关闭时的证据来自上一轮 `report.json` 的新轮采集结果;本次检查了两轮原工程哈希一致。对照数据另存为 `control-comparison.json`。因此本次验证了开关实际改变写入结果,而不只是界面状态或命令字段发生变化。 + +## 耗时与证据 + +- BOM 导入及真实库存采集:126.910 秒。 +- 点击执行至保存重开核验完成:231.631 秒,包含重新确认库存、启动 CAD 和实际替换。 +- 全新会话独立读取及退出:45.771 秒。 +- 分阶段计时:`execution-measurements.csv`;原生事务、日志和私有会话记录保存在任务 `quick-run` 及 `quick-run-history` 中。 +- 独立结果:`independent-attributes.json`;最终 `report.json` 为 `verified=true`、`source_project_unchanged=true`。 +- 界面截图:`01-part-label-enabled.png`、`02-part-label-completed.png`。 + +本次仅补齐普通 Part Label 复制路径的真实验证,没有把既有 COM 偶发启动阻塞或千步性能目标记作已解决,也没有重新跑整套基础测试。 diff --git a/tools/probe_part_label_live.py b/tools/probe_part_label_live.py new file mode 100644 index 0000000..903ca65 --- /dev/null +++ b/tools/probe_part_label_live.py @@ -0,0 +1,246 @@ +"""Verify the UI Part Label option and saved attributes on a disposable CAD copy.""" +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path +import re +import shutil +import sys +import time +import traceback + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'src')) + + +def inspect_native(project, schematic, sheet, destination): + import pythoncom + import win32com.client + from dx_productivity.trial_task_center.cad_identity import project_file_path, verify_application + from dx_productivity.trial_task_center.native_helper import attach, attribute_value, components_on_sheet + pythoncom.CoInitialize() + try: + app = win32com.client.GetActiveObject('Viewdraw.Application') + verify_application(app, require_view=False) + assert not project_file_path(app), 'independent reader cannot take over an open project' + assert app.OpenProject(str(project)) + assert Path(project_file_path(app)).resolve() == project.resolve() + document = app.SchematicSheetDocuments().Open(schematic, sheet) + document.Activate() + app, api = attach() # Certify the active view's owned PID before reading. + rows = [] + for component in components_on_sheet(app, api): + if str(component.Refdes) not in {'RV05', 'RV11'}: + continue + rows.append(dict(uid=str(component.UID), refdes=str(component.Refdes), + part_number=attribute_value(component, 'Part Number'), + part_label=attribute_value(component, 'Part Label'), + value=attribute_value(component, 'Value'))) + assert len(rows) == 2 + document.Close(False, '') + app.CloseProject() + assert not project_file_path(app) + destination.write_text(json.dumps(rows, ensure_ascii=False, indent=2), encoding='utf-8') + finally: + pythoncom.CoUninitialize() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--source', type=Path) + parser.add_argument('--library', type=Path) + parser.add_argument('--output', type=Path, required=True) + parser.add_argument('--inspect-project', type=Path) + parser.add_argument('--schematic') + parser.add_argument('--sheet') + parser.add_argument('--resume', action='store_true') + args = parser.parse_args() + if args.inspect_project: + inspect_native(args.inspect_project, args.schematic, args.sheet, args.output) + return 0 + if not args.source or not args.library: + parser.error('--source and --library are required for the live UI probe') + os.environ.setdefault('QT_QPA_PLATFORM', 'offscreen') + from openpyxl import load_workbook + from PySide6.QtCore import QPoint, QThreadPool, Qt + from PySide6.QtGui import QFont, QFontDatabase + from PySide6.QtTest import QTest + from PySide6.QtWidgets import QApplication, QCheckBox, QFileDialog + from dx_productivity.trial_task_center.isolated_cad import IsolatedCadSession + from dx_productivity.trial_task_center.legacy_paths import cleanup_worker_aliases + from dx_productivity.trial_task_center.logging_setup import configure_logging + from dx_productivity.trial_task_center.models import TaskStatus + from dx_productivity.trial_task_center.service import TaskCenterService + from dx_productivity.trial_task_center.store import TaskStore + from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow + from private_desktop_observer import PrivateDesktopObserver + from probe_bom_live_roundtrip import export_measurements, hashes + + output, source = args.output.resolve(), args.source.resolve(strict=True) + assert not output.is_relative_to(source.parent) + output.mkdir(parents=True, exist_ok=args.resume) + source_hashes = hashes(source) + if not args.resume: + shutil.copytree(source.parent, output / 'project') + project = output / 'project' / source.name + text, count = re.subn(r'(?m)^KEY CentralLibrary .*$', + lambda _: f'KEY CentralLibrary "{args.library.resolve(strict=True).as_posix()}"', + project.read_text(encoding='utf-8-sig')) + assert count == 1 + if not args.resume: + project.write_text(text, encoding='utf-8') + store = TaskStore(output / 'tasks.db') + service = TaskCenterService(store, configure_logging(output / 'data')) + app = QApplication.instance() or QApplication([]) + font_id = QFontDatabase.addApplicationFont(str(Path(os.environ['WINDIR']) / 'Fonts/msyh.ttc')) + families = QFontDatabase.applicationFontFamilies(font_id) + if families: + app.setFont(QFont(families[0], 10)) + window = TrialTaskCenterWindow(service, quick_run_confirmer=lambda *_: True, + close_plan_confirmer=lambda: 'discard') + report = (json.loads((output / 'report.json').read_text(encoding='utf-8')) if args.resume else + {'source': str(source), 'project': str(project), 'steps': [], 'errors': []}) + report.pop('error', None) + report.pop('verified', None) + def record(stage, started=None, **details): + entry = {'stage': stage, **details} + if started is not None: + entry['seconds'] = time.perf_counter() - started + report['steps'].append(entry) + (output / 'report.json').write_text(json.dumps(report, ensure_ascii=False, indent=2, default=str), encoding='utf-8') + print(json.dumps(entry, ensure_ascii=False, default=str), flush=True) + def idle(): + deadline = time.monotonic() + 900 + while (window._workers or window._loading or window._task_query.busy or window._context_query.busy + or window._log_presenter.query.busy or window._feedback_query.busy): + if time.monotonic() > deadline: + raise TimeoutError('live Part Label UI probe deadline exceeded') + app.processEvents() + time.sleep(.02) + app.processEvents() + def click(button): + assert button.isEnabled(), button.objectName() + if isinstance(button, QCheckBox): + QTest.mouseClick(button, Qt.MouseButton.LeftButton, pos=QPoint(8, button.height() // 2)) + else: + QTest.mouseClick(button, Qt.MouseButton.LeftButton) + original_error = window._show_error + def error_received(error, **options): + report['errors'].append(str(error)) + original_error(error, **options) + window._show_error = error_received + template, filled = output / 'default-template.xlsx', output / 'part-label-bom.xlsx' + original_open, original_save = QFileDialog.getOpenFileName, QFileDialog.getSaveFileName + QFileDialog.getSaveFileName = lambda *_a, **_k: (str(template), 'Excel (*.xlsx)') + QFileDialog.getOpenFileName = lambda *_a, **_k: (str(filled), 'Excel (*.xlsx)') + try: + window.show() + idle() + task = service.tasks()[0] if args.resume else service.create_project_tasks(project.parent)[0] + report['task_id'] = task.task_id + window.open_task(task.task_id) + idle() + window.mapping_tabs.setCurrentIndex(1) + if not args.resume: + click(window.plan_panel.export_bom_button) + idle() + book = load_workbook(template) + worksheet = book.active + headers = [cell.value for cell in worksheet[1]] + scaffold = dict(zip(headers, next(worksheet.iter_rows(min_row=2, values_only=True)))) + worksheet.delete_rows(2, worksheet.max_row) + row = scaffold | dict(old_part_number='4100-CA0000-T7', new_part_number='4100-CA0000-T0', + refdes='RV05', enabled=True, sync_nc=True) + worksheet.append([row.get(header, '') for header in headers]) + book.save(filled) + book.close() + with PrivateDesktopObserver(output): + if not service.target_plan(task.task_id): + started = time.perf_counter() + click(window.plan_panel.import_bom_button) + idle() + result = window.plan_panel.last_bom_report + assert result and result.preview and result.passed_rows == 1 and not result.failed_rows, report['errors'] + record('import_bom', started, passed=result.passed_rows, failed=result.failed_rows) + click(window.plan_panel.save_button) + idle() + before = service.target_plan(task.task_id) + assert {row.target.refdes for row in before} == {'RV05', 'RV11'} + assert sum(row.enabled for row in before) == 1 + if not window.run_panel.copy_value_check.isChecked(): + click(window.run_panel.copy_value_check) + idle() + assert window.run_panel.copy_value_check.isChecked() + assert service.get_task(task.task_id).copy_part_number_to_value + record('ui_part_label_copy_enabled') + window.grab().save(str(output / '01-part-label-enabled.png')) + started = time.perf_counter() + did_execute = service.get_task(task.task_id).status is not TaskStatus.COMPLETED + if did_execute: + click(window.run_panel.quick_run_button) + idle() + assert service.get_task(task.task_id).status is TaskStatus.COMPLETED, report['errors'] + if did_execute: + record('native_replacement_saved_and_reopened', started) + else: + record('reuse_completed_task_for_readback') + window.grab().save(str(output / '02-part-label-completed.png')) + facade = service.for_project_task(task.task_id) + command = facade._quick_run_preparer.data_root / 'quick-run/command.tsv' + fields = command.read_text(encoding='utf-8-sig').splitlines() + job = dict(zip(fields[0].split('\t'), fields[1].split('\t'))) + assert job['value_mode'] == 'part_label' + selected = next(row.target for row in before if row.enabled) + reader = facade._quick_run_preparer.data_root / 'quick-run-history/sheet-discovery-partlabel-independent' + reader.mkdir(parents=True, exist_ok=True) + destination = output / 'independent-attributes.json' + started = time.perf_counter() + with IsolatedCadSession(reader) as session: + process = session.start_worker((sys.executable, str(Path(__file__).resolve()), + '--inspect-project', str(project), '--schematic', selected.schematic_name, + '--sheet', selected.sheet_number, '--output', str(destination)), stdout=-1, stderr=-1) + deadline = time.monotonic() + 150 + while process.poll() is None and time.monotonic() < deadline: + time.sleep(.1) + if process.poll() is None: + raise TimeoutError('independent Part Label read did not finish') + stdout, stderr = process.stdout.read(), process.stderr.read() + (reader / 'worker-output.txt').write_bytes(stdout + b'\n' + stderr) + assert process.poll() == 0, stderr.decode('utf-8', errors='replace') + actual = json.loads(destination.read_text(encoding='utf-8')) + targets = {row['refdes']: row for row in actual} + copied = targets['RV05'] + assert copied['part_number'] == '4100-CA0000-T0' + assert copied['part_label'] and copied['value'] == copied['part_label'] + for row in before: + after = targets[row.target.refdes] + assert after['uid'] == row.target.uid + if not row.enabled: + assert after['part_number'] == row.target.old_part_number and after['value'] == row.target.old_value + record('independent_saved_attributes', started, components=actual) + observation = json.loads((output / 'desktop-observation.json').read_text(encoding='utf-8')) + assert not observation['observer_errors'] + assert observation['input_desktop_before'] == observation['input_desktop_after'] + assert not observation['owned_cad_became_foreground'] and not observation['owned_cad_on_input_desktop'] + assert all(observation['cad_exit_confirmed'].values()) and all(observation['desktop_absent'].values()) + report['verified'] = True + except Exception as error: + report['error'] = str(error) + traceback.print_exc() + finally: + idle() + report['source_project_unchanged'] = hashes(source) == source_hashes + QFileDialog.getOpenFileName, QFileDialog.getSaveFileName = original_open, original_save + window.close() + QThreadPool.globalInstance().waitForDone() + store.close() + report['alias_cleanup_errors'] = [str(error) for error in cleanup_worker_aliases()] + report['measurements'] = str(export_measurements(output)) + (output / 'report.json').write_text(json.dumps(report, ensure_ascii=False, indent=2, default=str), encoding='utf-8') + print(json.dumps({key: report[key] for key in ('verified', 'error', 'source_project_unchanged') if key in report}), flush=True) + return 0 if report.get('verified') and report['source_project_unchanged'] and not report['alias_cleanup_errors'] else 1 + + +if __name__ == '__main__': + raise SystemExit(main())