Compare commits

..
Author SHA1 Message Date
阿白叔 0759739e11 chore: prepare DxPartReplace v1.3.2
Core regression / Python core, intervention UI and release configuration (push) Successful in 36m51s
Core regression / JavaScript syntax (push) Successful in 11s
2026-11-20 17:38:49 +08:00
12 changed files with 58 additions and 271 deletions

No files matched your search

+5 -4
View File
@@ -10,13 +10,13 @@
2026-11-13 的 [PR #27 审查修复与复核](docs/testing/2026-11-13-pr27-review-fixes.md) 单列最新结果:停滞计时、执行回执、BOM 错误、网表范围与确认后状态检查已修复;新候选启动及冻结校验通过,新 20 项实机仍因 Mentor 退出超时未完成,尚未发布。 2026-11-13 的 [PR #27 审查修复与复核](docs/testing/2026-11-13-pr27-review-fixes.md) 单列最新结果:停滞计时、执行回执、BOM 错误、网表范围与确认后状态检查已修复;新候选启动及冻结校验通过,新 20 项实机仍因 Mentor 退出超时未完成,尚未发布。
**当前版本:V1.3.1(实机测试预发布)** · [本版变更与已知问题](docs/releases/v1.3.1.md) · [完整使用说明](docs/user/v1.1.0-project-tasks.md) **当前版本:V1.3.2(实机测试预发布)** · [本版变更](docs/releases/v1.3.2.md) · [完整使用说明](docs/user/v1.1.0-project-tasks.md)
V1.3.1 包含 PR #27 的原生 BOM 按需核验、Mentor 批内复用、前后网表比对、完整普通 Harness 及审查修复,沿用紫蓝双环图标和原生三栏 DSH 助手。错误触发自有 Mentor 自动回收,确认相关进程退出后才释放桌面;具体时限与恢复要求见[停止与恢复说明](docs/user/safe-stop-and-recovery.md)。 V1.3.2 集成 DeepSeek Harness `0.2.2-rc.5`,新增独立工程校验工作台,并改进批量替换的保存锁处理、结果回执恢复和自有桌面复用。
本地交付目录为 `outputs/releases/v1.3.1`,包含自解压 EXE、ZIP 便携包、SHA256、逐文件清单和本次构建验证报告。两种包均保留完整 Node/Harness、Qt WebEngine 和应用资源。升级前退出旧程序并备份 `data`,解压到新目录,完整保留 EXE 与 `_internal`,不要只替换 EXE。 发布页包含自解压 EXE、ZIP 便携包、SHA256、逐文件清单和构建验证报告。两种包均包含 Node/Harness、Qt WebEngine 和应用资源。升级前退出旧程序并备份 `data`,解压到新目录,完整保留 EXE 与 `_internal`。
**V1.3.1 下载** · [自解压 EXE](https://git.simgreek.com/Skyworth_Digital_Hardware/dxdesigner-part-replacement/releases/download/v1.3.1/DxPartReplace-1.3.1.exe) · [ZIP 便携包](https://git.simgreek.com/Skyworth_Digital_Hardware/dxdesigner-part-replacement/releases/download/v1.3.1/DxPartReplace-1.3.1.zip) · [版本说明与附件](https://git.simgreek.com/Skyworth_Digital_Hardware/dxdesigner-part-replacement/releases/tag/v1.3.1)。本版 Mentor 退出超时仍待实机复核,最新 20 项 CAD 验收未完成。 **V1.3.2 下载** · [自解压 EXE](https://git.simgreek.com/Skyworth_Digital_Hardware/dxdesigner-part-replacement/releases/download/v1.3.2/DxPartReplace-1.3.2.exe) · [ZIP 便携包](https://git.simgreek.com/Skyworth_Digital_Hardware/dxdesigner-part-replacement/releases/download/v1.3.2/DxPartReplace-1.3.2.zip) · [版本说明与附件](https://git.simgreek.com/Skyworth_Digital_Hardware/dxdesigner-part-replacement/releases/tag/v1.3.2)
本版提供[目标封装选择](docs/user/target-cell-selection.md):目标封装可留空,此时工具不主动覆写封装,可后续与中心库同步;需要指定时,在料号规则中读取并选择合法封装。BOM 保持原 11 列。 本版提供[目标封装选择](docs/user/target-cell-selection.md):目标封装可留空,此时工具不主动覆写封装,可后续与中心库同步;需要指定时,在料号规则中读取并选择合法封装。BOM 保持原 11 列。
@@ -273,6 +273,7 @@ py -3.12 -m venv .venv
- [历史流程和独立 CLI 说明](docs/user/trial-task-center.md) - [历史流程和独立 CLI 说明](docs/user/trial-task-center.md)
- [CLI 与原生批处理集成](docs/user/part-replacement.md) - [CLI 与原生批处理集成](docs/user/part-replacement.md)
- [V1.1.3 版本说明](docs/releases/v1.1.3.md) - [V1.1.3 版本说明](docs/releases/v1.1.3.md)
- [V1.3.2 实机测试版说明](docs/releases/v1.3.2.md)
- [V1.3.1 实机测试版说明](docs/releases/v1.3.1.md) - [V1.3.1 实机测试版说明](docs/releases/v1.3.1.md)
- [V1.3.0 版本说明](docs/releases/v1.3.0.md) - [V1.3.0 版本说明](docs/releases/v1.3.0.md)
- [V1.3.0 构建记录与校验值](docs/releases/v1.3.0-build.md) - [V1.3.0 构建记录与校验值](docs/releases/v1.3.0-build.md)
+9
View File
@@ -0,0 +1,9 @@
# v1.3.2 实机测试版
- DSH 助手升级到 DeepSeek Harness `0.2.2-rc.5`。源码环境支持从 npm 更新到 `latest` 或指定版本,便携版随应用携带运行时。见 [PR #32](https://git.simgreek.com/Skyworth_Digital_Hardware/dxdesigner-part-replacement/pulls/32)
- 新增独立工程校验工作台,支持批量导入工程对、网表与引脚比对、查看证据及历史结果。见 [PR #30](https://git.simgreek.com/Skyworth_Digital_Hardware/dxdesigner-part-replacement/pulls/30)
- 批量替换改进了保存锁处理、结果回执恢复和自有桌面复用。见 [PR #31](https://git.simgreek.com/Skyworth_Digital_Hardware/dxdesigner-part-replacement/pulls/31)
退出旧程序并备份 `data`,将自解压 EXE 或便携 ZIP 解压到新目录。保留 `DxPartReplace.exe` 与 `_internal`,运行 `启动程序.cmd`。如需迁移旧数据,把备份复制到新目录的 `data`。
本版沿用实机测试预发布形式。云端模型回复及真实 CAD 批量替换仍需在实际工程环境验证。
@@ -1,37 +0,0 @@
# Issue 33 D2 · 工程路径错误提示验收
工程读取和任务创建的路径检查直接调用 `lstat()`。目录不存在或扫描后工程移走时,文件系统异常进入统一兜底,现场报告仅能看到“发生未处理异常”。目录存在且能读取属性时,`scandir()` 仍可能因缺少列目录权限失败。
修复在路径检查和读取处分类处理这些预期错误。读取对话框和创建任务的错误提示均显示完整路径、分类代码、处理建议和可关联日志的 `DXT` 编号。预期错误写入一条应用日志。未知异常保留 traceback。
## Windows 11 实测
使用 Qt 按钮启动读取、真实文件系统与任务库。第五例在成功扫描两个候选工程后重命名其中一个文件,从实际服务入口创建选定任务并检查主窗口所用的错误格式和任务数据库。
| 输入 | 基线 `46deb9c` | 修复后代码 | 修复后错误编号 |
| --- | --- | --- | --- |
| 不存在的目录 | 通用兜底 | `path_missing` | `DXT-20261125-3EE8F667` |
| 普通文件作为目录 | 英文非目录文案 | `path_not_directory` | `DXT-20261125-92876D74` |
| 路径中途遇到普通文件 | 通用兜底 | `path_not_directory` | `DXT-20261125-0C615FE8` |
| ACL 拒绝列目录 | 通用兜底 | `path_denied` | `DXT-20261125-ED64EEA9` |
| 工程在扫描后被移走 | 通用兜底 | `path_missing` | `DXT-20261125-CA48D2FF` |
ACL 测试对临时目录中的当前用户拒绝 `FILE_LIST_DIRECTORY`,两个版本的文件系统操作均触发原生 `WinError 5`。创建任务失败后库中仍有 0 条任务。五个路径输入的通用兜底率从 4/5 降到 0/5。额外注入的 `RuntimeError` 对照组仍触发一次 `unhandled_exception`,并保留 traceback。
## 复跑
在仓库根目录运行。使用未占用的临时目录保存测试日志。
```powershell
$env:PYTHONUTF8 = '1'
python -m pytest -q -s tests/v1_1/test_project_path_errors.py tests/v1_1/test_scan_responsiveness.py tests/v1_1/test_project_long_paths.py tests/v1_1/test_path_access.py tests/trial_task_center/test_logging_setup.py --basetemp build/issue33-d2
```
实测 35 项通过。以下命令按错误记录统计扫描和创建任务的通用兜底率。路径用例与故障对照分别统计时,从相应测试目录读取日志。
```powershell
$rows = Get-ChildItem build/issue33-d2 -Recurse -Filter application.log |
Select-String 'error_id=\S+ operation=(scan_project_directory|create_project_tasks) (code=\S+ )?message='
$generic = $rows | Where-Object { $_.Line -match 'code=unhandled_exception |message=发生未处理异常$' }
'{0}/{1}' -f @($generic).Count, @($rows).Count
```
+4 -4
View File
@@ -1,8 +1,8 @@
# UTF-8 # UTF-8
VSVersionInfo( VSVersionInfo(
ffi=FixedFileInfo( ffi=FixedFileInfo(
filevers=(1, 3, 1, 0), filevers=(1, 3, 2, 0),
prodvers=(1, 3, 1, 0), prodvers=(1, 3, 2, 0),
mask=0x3f, mask=0x3f,
flags=0x0, flags=0x0,
OS=0x40004, OS=0x40004,
@@ -15,11 +15,11 @@ VSVersionInfo(
StringTable('040904B0', [ StringTable('040904B0', [
StringStruct('CompanyName', 'DxProductivity'), StringStruct('CompanyName', 'DxProductivity'),
StringStruct('FileDescription', 'DxDesigner Part Replacement'), StringStruct('FileDescription', 'DxDesigner Part Replacement'),
StringStruct('FileVersion', '1.3.1.0'), StringStruct('FileVersion', '1.3.2.0'),
StringStruct('InternalName', 'DxPartReplace'), StringStruct('InternalName', 'DxPartReplace'),
StringStruct('OriginalFilename', 'DxPartReplace.exe'), StringStruct('OriginalFilename', 'DxPartReplace.exe'),
StringStruct('ProductName', 'DxDesigner Part Replacement'), StringStruct('ProductName', 'DxDesigner Part Replacement'),
StringStruct('ProductVersion', '1.3.1') StringStruct('ProductVersion', '1.3.2')
]) ])
]), ]),
VarFileInfo([VarStruct('Translation', [1033, 1200])]) VarFileInfo([VarStruct('Translation', [1033, 1200])])
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project] [project]
name = "dx-productivity" name = "dx-productivity"
version = "1.3.1" version = "1.3.2"
requires-python = ">=3.12,<3.13" requires-python = ">=3.12,<3.13"
dependencies = ["PySide6>=6.7,<7", "pywin32>=306", "pywinauto>=0.6.9,<1", "openpyxl>=3.1,<4"] dependencies = ["PySide6>=6.7,<7", "pywin32>=306", "pywinauto>=0.6.9,<1", "openpyxl>=3.1,<4"]
@@ -27,7 +27,3 @@ class TaskCenterError(ValueError):
def _new_error_id() -> str: def _new_error_id() -> str:
date = datetime.now(timezone.utc).strftime("%Y%m%d") date = datetime.now(timezone.utc).strftime("%Y%m%d")
return f"DXT-{date}-{secrets.token_hex(4).upper()}" return f"DXT-{date}-{secrets.token_hex(4).upper()}"
class ProjectPathError(TaskCenterError):
"""An expected filesystem failure while reading or selecting projects."""
@@ -17,7 +17,7 @@ import time
import traceback import traceback
from typing import Any, Mapping from typing import Any, Mapping
from .errors import ProjectPathError, TaskCenterError from .errors import TaskCenterError
from .path_access import internal_path from .path_access import internal_path
from .retention import rotate_text_log from .retention import rotate_text_log
@@ -62,18 +62,15 @@ class LoggingContext:
reported = error reported = error
else: else:
reported = TaskCenterError("unhandled_exception", "发生未处理异常") reported = TaskCenterError("unhandled_exception", "发生未处理异常")
message = reported.message detail = "".join(
if not isinstance(error, ProjectPathError): traceback.format_exception(type(error), error, traceback_object or error.__traceback__)
detail = "".join( )
traceback.format_exception(type(error), error, traceback_object or error.__traceback__)
)
message += "\n" + detail.rstrip()
self.logger.error( self.logger.error(
"error_id=%s operation=%s code=%s message=%s", "error_id=%s operation=%s message=%s\n%s",
reported.error_id, reported.error_id,
operation, operation,
reported.code, reported.message,
message, detail.rstrip(),
) )
_flush_handlers(self.logger) _flush_handlers(self.logger)
return reported return reported
@@ -3,7 +3,6 @@
from __future__ import annotations from __future__ import annotations
from collections.abc import Callable from collections.abc import Callable
from contextlib import contextmanager
from threading import Event from threading import Event
import os import os
@@ -11,44 +10,20 @@ from pathlib import Path
import stat import stat
from uuid import uuid4 from uuid import uuid4
from .errors import ProjectPathError, TaskCenterError from .errors import TaskCenterError
from .path_access import canonical_path, internal_path, strip_extended_prefix from .path_access import canonical_path, internal_path, strip_extended_prefix
from .models import TaskRecord, TaskStatus from .models import TaskRecord, TaskStatus
from .scanner import _is_schematic_project, _reject_reparse from .scanner import _is_schematic_project, _reject_reparse
from .store import TaskStore from .store import TaskStore
@contextmanager
def _path_errors(path: Path):
try:
yield
except FileNotFoundError as error:
raise ProjectPathError(
"path_missing", f"找不到路径「{path}」。请确认目录或工程是否已移动或删除,然后重新选择并读取。"
) from error
except PermissionError as error:
raise ProjectPathError(
"path_denied", f"无法读取路径「{path}」。请检查当前用户的读取权限,然后重试。"
) from error
except NotADirectoryError as error:
raise _not_directory(path) from error
def _not_directory(path: Path) -> ProjectPathError:
return ProjectPathError(
"path_not_directory", f"路径「{path}」中有一项不是目录。请选择工程目录后重试。"
)
def _validated_root(root: Path, excluded_roots: tuple[Path, ...]) -> tuple[Path, tuple[Path, ...]]: def _validated_root(root: Path, excluded_roots: tuple[Path, ...]) -> tuple[Path, tuple[Path, ...]]:
root = Path(os.path.abspath(strip_extended_prefix(root))) root = Path(os.path.abspath(strip_extended_prefix(root)))
with _path_errors(root): for ancestor in (*reversed(root.parents), root):
for ancestor in (*reversed(root.parents), root): _reject_reparse(internal_path(ancestor).lstat(), ancestor)
details = internal_path(ancestor).lstat() root = canonical_path(root, strict=True)
_reject_reparse(details, ancestor) if not internal_path(root).is_dir():
if not stat.S_ISDIR(details.st_mode): raise TaskCenterError("discovery_root", "project root is not a directory")
raise _not_directory(root)
root = canonical_path(root, strict=True)
excluded = tuple(canonical_path(path) for path in excluded_roots) excluded = tuple(canonical_path(path) for path in excluded_roots)
if any(root.is_relative_to(blocked) for blocked in excluded): if any(root.is_relative_to(blocked) for blocked in excluded):
raise TaskCenterError("discovery_root", "project root is inside an excluded directory") raise TaskCenterError("discovery_root", "project root is inside an excluded directory")
@@ -75,13 +50,12 @@ def scan_project_directory(root: Path, *, excluded_roots: tuple[Path, ...] = (),
while pending: while pending:
check_cancelled() check_cancelled()
directory = pending.pop() directory = pending.pop()
_reject_reparse(internal_path(directory).lstat(), directory)
children = [] children = []
with _path_errors(directory): with os.scandir(internal_path(directory)) as entries:
_reject_reparse(internal_path(directory).lstat(), directory) for entry in entries:
with os.scandir(internal_path(directory)) as entries: check_cancelled()
for entry in entries: children.append(entry)
check_cancelled()
children.append(entry)
projects: list[Path] = [] projects: list[Path] = []
folders: list[Path] = [] folders: list[Path] = []
for entry in sorted(children, key=lambda item: item.name.casefold()): for entry in sorted(children, key=lambda item: item.name.casefold()):
@@ -89,13 +63,12 @@ def scan_project_directory(root: Path, *, excluded_roots: tuple[Path, ...] = (),
path = Path(strip_extended_prefix(entry.path)) path = Path(strip_extended_prefix(entry.path))
if any(path.is_relative_to(blocked) for blocked in excluded): if any(path.is_relative_to(blocked) for blocked in excluded):
continue continue
with _path_errors(path): details = entry.stat(follow_symlinks=False)
details = entry.stat(follow_symlinks=False) _reject_reparse(details, path)
_reject_reparse(details, path) if stat.S_ISDIR(details.st_mode):
if stat.S_ISDIR(details.st_mode): folders.append(path)
folders.append(path) elif stat.S_ISREG(details.st_mode) and path.suffix.casefold() == ".prj" and _is_schematic_project(path):
elif stat.S_ISREG(details.st_mode) and path.suffix.casefold() == ".prj" and _is_schematic_project(path): projects.append(canonical_path(path, strict=True))
projects.append(canonical_path(path, strict=True))
found.extend(projects) found.extend(projects)
visited += 1 visited += 1
if on_progress is not None: if on_progress is not None:
@@ -111,41 +84,35 @@ def _validate_selected(root: Path, selected_paths: tuple[Path, ...], excluded: t
ancestor_projects: dict[Path, bool] = {} ancestor_projects: dict[Path, bool] = {}
for candidate in selected_paths: for candidate in selected_paths:
path = Path(os.path.abspath(strip_extended_prefix(candidate))) path = Path(os.path.abspath(strip_extended_prefix(candidate)))
if path == root or not path.is_relative_to(root) or any(path.is_relative_to(blocked) for blocked in excluded): if not path.is_relative_to(root) or any(path.is_relative_to(blocked) for blocked in excluded):
raise TaskCenterError("project_selection", "selected project is outside discovery results") raise TaskCenterError("project_selection", "selected project is outside discovery results")
relative = path.relative_to(root) relative = path.relative_to(root)
cursor = root cursor = root
with _path_errors(path): for part in relative.parts:
for part in relative.parts: cursor /= part
cursor /= part _reject_reparse(internal_path(cursor).lstat(), cursor)
details = internal_path(cursor).lstat() if not internal_path(path).is_file() or path.suffix.casefold() != ".prj" or not _is_schematic_project(path):
_reject_reparse(details, cursor) raise TaskCenterError("project_selection", "selected file is not a schematic project")
if cursor != path and not stat.S_ISDIR(details.st_mode):
raise _not_directory(path)
if not stat.S_ISREG(details.st_mode) or path.suffix.casefold() != ".prj" or not _is_schematic_project(path):
raise TaskCenterError("project_selection", "selected file is not a schematic project")
# A project in any ancestor directory stops discovery below that directory. # A project in any ancestor directory stops discovery below that directory.
directory = path.parent directory = path.parent
while directory != root: while directory != root:
directory = directory.parent directory = directory.parent
if directory not in ancestor_projects: if directory not in ancestor_projects:
has_project = False has_project = False
with _path_errors(directory), os.scandir(internal_path(directory)) as entries: with os.scandir(internal_path(directory)) as entries:
for entry in entries: for entry in entries:
sibling = Path(strip_extended_prefix(entry.path)) sibling = Path(strip_extended_prefix(entry.path))
if sibling.suffix.casefold() != ".prj" or any(sibling.is_relative_to(b) for b in excluded): if sibling.suffix.casefold() != ".prj" or any(sibling.is_relative_to(b) for b in excluded):
continue continue
with _path_errors(sibling): details = entry.stat(follow_symlinks=False)
details = entry.stat(follow_symlinks=False) _reject_reparse(details, sibling)
_reject_reparse(details, sibling) if stat.S_ISREG(details.st_mode) and _is_schematic_project(sibling):
if stat.S_ISREG(details.st_mode) and _is_schematic_project(sibling): has_project = True
has_project = True break
break
ancestor_projects[directory] = has_project ancestor_projects[directory] = has_project
if ancestor_projects[directory]: if ancestor_projects[directory]:
raise TaskCenterError("project_selection", "selected project is hidden by an ancestor project") raise TaskCenterError("project_selection", "selected project is hidden by an ancestor project")
with _path_errors(path): selected.add(canonical_path(path, strict=True))
selected.add(canonical_path(path, strict=True))
return tuple(sorted(selected, key=lambda path: str(path).casefold())) return tuple(sorted(selected, key=lambda path: str(path).casefold()))
@@ -3,8 +3,6 @@ from datetime import datetime
import json import json
import re import re
from ..errors import ProjectPathError
ERROR_TEXT = { ERROR_TEXT = {
"dsh_startup": "DSH助手启动失败,请检查发布包中的运行时和 Node.js。", "dsh_startup": "DSH助手启动失败,请检查发布包中的运行时和 Node.js。",
'user_forced_stop': '操作已强制中断,结果待核验。', 'user_forced_stop': '操作已强制中断,结果待核验。',
@@ -59,8 +57,6 @@ ERROR_TEXT = {
def format_operation_error(error): def format_operation_error(error):
if isinstance(error, ProjectPathError):
return f'{error.message}\n错误代码:{error.code} · 错误编号:{error.error_id}'
title = ERROR_TEXT.get(error.code, '操作未完成') title = ERROR_TEXT.get(error.code, '操作未完成')
report = getattr(error, 'bom_report', None) report = getattr(error, 'bom_report', None)
if report is not None: if report is not None:
@@ -19,8 +19,6 @@ from .workers import ServiceWorker
from .operation_state import OperationPhase from .operation_state import OperationPhase
from .command_menu import CommandMenu from .command_menu import CommandMenu
from .icons import icon from .icons import icon
from .messages import format_operation_error
from ..errors import ProjectPathError
from ..bom_import_state import BomImportMachine, BomImportPhase, BomImportState from ..bom_import_state import BomImportMachine, BomImportPhase, BomImportState
from ..bom_pending import retained_bom_rows from ..bom_pending import retained_bom_rows
@@ -46,9 +44,6 @@ class DirectoryTaskDialog(QDialog):
self.scan = QPushButton('读取工程', objectName='readTaskProjects') self.scan = QPushButton('读取工程', objectName='readTaskProjects')
self.projects = QListWidget(objectName='taskProjectCandidates') self.projects = QListWidget(objectName='taskProjectCandidates')
self.summary = QLabel('先读取工程,再勾选需要创建任务的项目。') self.summary = QLabel('先读取工程,再勾选需要创建任务的项目。')
self.summary.setWordWrap(True)
self.summary.setTextFormat(Qt.TextFormat.PlainText)
self.summary.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
self.buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel) self.buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
self.buttons.button(QDialogButtonBox.StandardButton.Ok).setText('创建任务') self.buttons.button(QDialogButtonBox.StandardButton.Ok).setText('创建任务')
self.buttons.button(QDialogButtonBox.StandardButton.Ok).setEnabled(False) self.buttons.button(QDialogButtonBox.StandardButton.Ok).setEnabled(False)
@@ -142,10 +137,7 @@ class DirectoryTaskDialog(QDialog):
if self._closed: if self._closed:
return return
self._scanned_root = None self._scanned_root = None
if isinstance(error, ProjectPathError): self.summary.setText(getattr(error, 'message', str(error)))
self.summary.setText(format_operation_error(error))
else:
self.summary.setText(getattr(error, 'message', str(error)))
def _finished(self): def _finished(self):
self._worker = None self._worker = None
@@ -1 +1 @@
VERSION = "1.3.1" VERSION = "1.3.2"
-134
View File
@@ -1,134 +0,0 @@
from contextlib import closing
import os
from pathlib import Path
import pytest
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QDialogButtonBox
from dx_productivity.trial_task_center import project_tasks
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.service import TaskCenterService
from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.ui.messages import format_operation_error
from dx_productivity.trial_task_center.ui.project_plan import DirectoryTaskDialog
@pytest.fixture
def service(tmp_path):
log = configure_logging(tmp_path / 'data')
with closing(TaskStore(tmp_path / 'tasks.db')) as store:
yield TaskCenterService(store, log), store, log.application_log_path
def deny_directory_listing(folder, request):
if os.name != 'nt':
pytest.skip('requires a Windows filesystem ACL')
import ntsecuritycon
import win32api
import win32con
import win32security
flag = win32security.DACL_SECURITY_INFORMATION
path = str(folder)
original = win32security.GetFileSecurity(path, flag)
token = win32security.OpenProcessToken(win32api.GetCurrentProcess(), win32con.TOKEN_QUERY)
try:
sid = win32security.GetTokenInformation(token, win32security.TokenUser)[0]
finally:
token.Close()
dacl = win32security.ACL()
dacl.AddAccessDeniedAce(win32security.ACL_REVISION, ntsecuritycon.FILE_LIST_DIRECTORY, sid)
dacl.AddAccessAllowedAce(win32security.ACL_REVISION, ntsecuritycon.FILE_ALL_ACCESS, sid)
descriptor = win32security.SECURITY_DESCRIPTOR()
descriptor.SetSecurityDescriptorDacl(True, dacl, False)
request.addfinalizer(lambda: win32security.SetFileSecurity(path, flag, original))
win32security.SetFileSecurity(path, flag, descriptor)
with pytest.raises(PermissionError) as failure, os.scandir(folder):
pytest.fail('directory ACL did not deny enumeration')
assert failure.value.winerror == 5
print('Windows ACL produced WinError 5')
def assert_operator_error(text, path, code, advice):
print(text)
assert str(path) in text
assert code in text and 'DXT-' in text
assert advice in text
assert 'Traceback' not in text
assert '发生未处理异常' not in text
@pytest.mark.parametrize(('case', 'code', 'advice'), [
('missing', 'path_missing', '移动或删除'),
('file', 'path_not_directory', '请选择工程目录'),
('file_parent', 'path_not_directory', '请选择工程目录'),
('denied', 'path_denied', '读取权限'),
])
def test_directory_dialog_shows_actionable_path_error(qtbot, tmp_path, request, service, case, code, advice):
api, store, log = service
folder = tmp_path / case
requested = folder
if case in {'file', 'file_parent'}:
folder.touch()
if case == 'file_parent':
requested = folder / 'subfolder'
if case == 'denied':
folder.mkdir()
deny_directory_listing(folder, request)
dialog = DirectoryTaskDialog(api)
qtbot.addWidget(dialog)
dialog.directory.setText(str(requested))
dialog.show()
qtbot.mouseClick(dialog.scan, Qt.MouseButton.LeftButton)
qtbot.waitUntil(lambda: dialog._worker is None, timeout=5000)
assert dialog.directory.isEnabled()
assert not dialog.buttons.button(QDialogButtonBox.StandardButton.Ok).isEnabled()
assert_operator_error(dialog.summary.text(), requested, code, advice)
assert store.list_tasks() == ()
contents = log.read_text(encoding='utf-8')
assert f'operation=scan_project_directory code={code}' in contents
assert 'Traceback' not in contents
def test_moved_project_fails_after_scan_without_creating_partial_tasks(qtbot, tmp_path, service):
api, store, log = service
root = tmp_path / 'projects'
root.mkdir()
for name in ('one.prj', 'two.prj'):
(root / name).write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n')
dialog = DirectoryTaskDialog(api)
qtbot.addWidget(dialog)
dialog.directory.setText(str(root))
dialog.show()
qtbot.mouseClick(dialog.scan, Qt.MouseButton.LeftButton)
create = dialog.buttons.button(QDialogButtonBox.StandardButton.Ok)
qtbot.waitUntil(create.isEnabled, timeout=5000)
moved = root / 'two.prj'
moved.rename(root / 'relocated.prj')
qtbot.mouseClick(create, Qt.MouseButton.LeftButton)
with pytest.raises(TaskCenterError) as failure:
api.create_project_tasks(dialog.values()[0], selected_paths=dialog.values()[1])
assert_operator_error(format_operation_error(failure.value), moved, 'path_missing', '移动或删除')
assert store.list_tasks() == ()
contents = log.read_text(encoding='utf-8')
assert 'operation=create_project_tasks code=path_missing' in contents
assert 'Traceback' not in contents
def test_unexpected_scan_fault_remains_traceable_in_application_log(tmp_path, monkeypatch, service):
api, _, log = service
def fail(*args, **kwargs):
raise RuntimeError('injected non-filesystem failure')
monkeypatch.setattr(project_tasks, '_validated_root', fail)
with pytest.raises(TaskCenterError) as failure:
api.scan_project_directory(tmp_path)
assert failure.value.code == 'unhandled_exception'
contents = log.read_text(encoding='utf-8')
assert 'operation=scan_project_directory code=unhandled_exception' in contents
assert 'Traceback' in contents and failure.value.error_id in contents