Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d954b527f5 |
No files matched your search
@@ -0,0 +1,37 @@
|
|||||||
|
# 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
|
||||||
|
```
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
# Issue 33 D5 · BOM 未知列验收
|
|
||||||
|
|
||||||
现场 B3 的 `INVALID_C1_bad_header_extra_col.xlsx` 带有 `extra_column`。名称归一化将未知列映射为空,后续只复制模板定义的列。导入成功时,工作区原先只报告保存行数与失败行数。
|
|
||||||
|
|
||||||
现在 BOM 导入保留模板列的精确映射,并为每个被忽略的具名列显示来源文件、原始列名与警告计数。详情和任务事件同时记录这些警告。缺失必需列时,导入停止,错误详情列出具体缺失项并对相近列名给出改名建议。
|
|
||||||
|
|
||||||
## Windows 11 重放
|
|
||||||
|
|
||||||
通过 Qt 工作区的“导入 BOM”按钮和真实任务服务运行,测试替换的是文件选择对话框的返回值。现场文件复制到临时目录,仅把第一条记录的工程名称与路径绑定到临时工程,保留了原始表头和替换字段。
|
|
||||||
|
|
||||||
| 工作簿 | 结果 |
|
|
||||||
| --- | --- |
|
|
||||||
| 两个额外列「供应商」「备注」 | 保存 1 行、失败 0 行、警告 2 项。详情逐列列名,任务事件记录同一组警告 |
|
|
||||||
| 现场 B3 `extra_column` | 保存 1 行、失败 0 行、警告 1 项。详情保留该列名 |
|
|
||||||
| 用「新料号编码」替换必需的「新料号」 | 指出缺少「新料号」,并建议将「新料号编码」改为「新料号」 |
|
|
||||||
| 缺少「新料号」 | 指出具体缺失项 |
|
|
||||||
| 表头公式与额外列中的数据公式 | 分别拒绝表头公式和第 2 行公式 |
|
|
||||||
| 原模板 | 保存 1 行、失败 0 行,无警告 |
|
|
||||||
|
|
||||||
BOM 草稿导入时未启动工程位号采集。回归还检查了由监督子进程返回的真实预览报告能携带同样的警告。包含现场工作簿重放的定向回归共通过 110 项。
|
|
||||||
|
|
||||||
## 复跑
|
|
||||||
|
|
||||||
在仓库根目录运行。现场文件从工单附件 `05_实测证据/paper2_bom` 解出。普通回归可省略 `DX_ISSUE33_D5_FIELD`,此时跳过现场文件重放。
|
|
||||||
|
|
||||||
```powershell
|
|
||||||
$env:PYTHONUTF8 = '1'
|
|
||||||
$env:PYTHONPATH = (Resolve-Path src).Path
|
|
||||||
$env:DX_ISSUE33_D5_FIELD = 'C:/path/to/INVALID_C1_bad_header_extra_col.xlsx'
|
|
||||||
python -m pytest -q -s tests/v1_1/test_bom_header_feedback.py tests/v1_1/test_bom_import_report.py tests/v1_1/test_bom_pending.py tests/v1_1/test_bom_sources_supervision.py tests/trial_task_center/test_bom_import_review.py tests/trial_task_center/test_item_value_and_bom_sources.py
|
|
||||||
```
|
|
||||||
@@ -48,7 +48,6 @@ class BomImportReport:
|
|||||||
source_map_path: Path | None = None
|
source_map_path: Path | None = None
|
||||||
passed_preview: BomBatchPreview | None = None
|
passed_preview: BomBatchPreview | None = None
|
||||||
deferred: bool = False
|
deferred: bool = False
|
||||||
warnings: tuple[str, ...] = ()
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def total_rows(self):
|
def total_rows(self):
|
||||||
|
|||||||
@@ -77,9 +77,7 @@ def resolution_binding(store, task_id):
|
|||||||
|
|
||||||
def import_drafts(service, task_id, sources, *, stop_event=None, on_progress=None, on_phase=None, allow_partial=False):
|
def import_drafts(service, task_id, sources, *, stop_event=None, on_progress=None, on_phase=None, allow_partial=False):
|
||||||
"""Persist routed spreadsheet requests without opening CAD or resolving parts."""
|
"""Persist routed spreadsheet requests without opening CAD or resolving parts."""
|
||||||
warnings = []
|
rows = load_sources(sources, stop_event=stop_event, on_progress=on_progress, allow_partial=allow_partial)
|
||||||
rows = load_sources(sources, stop_event=stop_event, on_progress=on_progress,
|
|
||||||
allow_partial=allow_partial, warnings=warnings)
|
|
||||||
scope = _scope(service._store, task_id)
|
scope = _scope(service._store, task_id)
|
||||||
paths = tuple(project.path for _, project in scope)
|
paths = tuple(project.path for _, project in scope)
|
||||||
names = {project.path: task.name for task, project in scope}
|
names = {project.path: task.name for task, project in scope}
|
||||||
@@ -95,8 +93,7 @@ def import_drafts(service, task_id, sources, *, stop_event=None, on_progress=Non
|
|||||||
write_routed_bom(normalized, rows, routes, project_names=names)
|
write_routed_bom(normalized, rows, routes, project_names=names)
|
||||||
append_task_event(service._logging, level='INFO', task_id=task_id,
|
append_task_event(service._logging, level='INFO', task_id=task_id,
|
||||||
operation='import_bom_drafts', message='BOM 表格来源记录已保存,工程位号待核验',
|
operation='import_bom_drafts', message='BOM 表格来源记录已保存,工程位号待核验',
|
||||||
details={'source_map_path': str(mapping), 'source_count': len({row.source for row in rows}),
|
details={'source_map_path': str(mapping), 'source_count': len({row.source for row in rows})})
|
||||||
'warnings': warnings})
|
|
||||||
try:
|
try:
|
||||||
report = inspect_batch(service, task_id, normalized, stop_event=stop_event, on_progress=on_progress,
|
report = inspect_batch(service, task_id, normalized, stop_event=stop_event, on_progress=on_progress,
|
||||||
on_phase=on_phase, spreadsheet_only=True, allow_partial=allow_partial)
|
on_phase=on_phase, spreadsheet_only=True, allow_partial=allow_partial)
|
||||||
@@ -113,7 +110,7 @@ def import_drafts(service, task_id, sources, *, stop_event=None, on_progress=Non
|
|||||||
if report.deferred and result.project_path not in failed_paths:
|
if report.deferred and result.project_path not in failed_paths:
|
||||||
reason = '表格已保存,执行前核验工程位号'
|
reason = '表格已保存,执行前核验工程位号'
|
||||||
annotated.append(replace(result, source_file=str(source.source), source_row=source.excel_row, reason=reason))
|
annotated.append(replace(result, source_file=str(source.source), source_row=source.excel_row, reason=reason))
|
||||||
report = replace(report, rows=tuple(annotated), source_map_path=mapping, warnings=tuple(warnings))
|
report = replace(report, rows=tuple(annotated), source_map_path=mapping)
|
||||||
if report.deferred:
|
if report.deferred:
|
||||||
accepted_sources = tuple(source for result, source in zip(report.rows, rows, strict=True)
|
accepted_sources = tuple(source for result, source in zip(report.rows, rows, strict=True)
|
||||||
if result.project_path not in failed_paths)
|
if result.project_path not in failed_paths)
|
||||||
|
|||||||
@@ -27,3 +27,7 @@ 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 TaskCenterError
|
from .errors import ProjectPathError, 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,15 +62,18 @@ class LoggingContext:
|
|||||||
reported = error
|
reported = error
|
||||||
else:
|
else:
|
||||||
reported = TaskCenterError("unhandled_exception", "发生未处理异常")
|
reported = TaskCenterError("unhandled_exception", "发生未处理异常")
|
||||||
|
message = reported.message
|
||||||
|
if not isinstance(error, ProjectPathError):
|
||||||
detail = "".join(
|
detail = "".join(
|
||||||
traceback.format_exception(type(error), error, traceback_object or error.__traceback__)
|
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 message=%s\n%s",
|
"error_id=%s operation=%s code=%s message=%s",
|
||||||
reported.error_id,
|
reported.error_id,
|
||||||
operation,
|
operation,
|
||||||
reported.message,
|
reported.code,
|
||||||
detail.rstrip(),
|
message,
|
||||||
)
|
)
|
||||||
_flush_handlers(self.logger)
|
_flush_handlers(self.logger)
|
||||||
return reported
|
return reported
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
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
|
||||||
@@ -10,20 +11,44 @@ from pathlib import Path
|
|||||||
import stat
|
import stat
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
||||||
from .errors import TaskCenterError
|
from .errors import ProjectPathError, 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()
|
||||||
|
_reject_reparse(details, ancestor)
|
||||||
|
if not stat.S_ISDIR(details.st_mode):
|
||||||
|
raise _not_directory(root)
|
||||||
root = canonical_path(root, strict=True)
|
root = canonical_path(root, strict=True)
|
||||||
if not internal_path(root).is_dir():
|
|
||||||
raise TaskCenterError("discovery_root", "project root is not a directory")
|
|
||||||
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")
|
||||||
@@ -50,8 +75,9 @@ 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):
|
||||||
|
_reject_reparse(internal_path(directory).lstat(), directory)
|
||||||
with os.scandir(internal_path(directory)) as entries:
|
with os.scandir(internal_path(directory)) as entries:
|
||||||
for entry in entries:
|
for entry in entries:
|
||||||
check_cancelled()
|
check_cancelled()
|
||||||
@@ -63,6 +89,7 @@ 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):
|
||||||
@@ -84,14 +111,18 @@ 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 not path.is_relative_to(root) or any(path.is_relative_to(blocked) for blocked in excluded):
|
if path == root or 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)
|
||||||
|
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")
|
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
|
||||||
@@ -99,11 +130,12 @@ def _validate_selected(root: Path, selected_paths: tuple[Path, ...], excluded: t
|
|||||||
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 os.scandir(internal_path(directory)) as entries:
|
with _path_errors(directory), 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):
|
||||||
@@ -112,6 +144,7 @@ def _validate_selected(root: Path, selected_paths: tuple[Path, ...], excluded: t
|
|||||||
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()))
|
||||||
|
|
||||||
|
|||||||
@@ -245,8 +245,7 @@ class TaskCenterService:
|
|||||||
on_phase(BomImportPhase.READING, message)
|
on_phase(BomImportPhase.READING, message)
|
||||||
if on_progress is not None:
|
if on_progress is not None:
|
||||||
on_progress(message)
|
on_progress(message)
|
||||||
warnings = []
|
rows = load_sources(sources, stop_event=stop_event, on_progress=on_progress,
|
||||||
rows = load_sources(sources, stop_event=stop_event, on_progress=on_progress, warnings=warnings,
|
|
||||||
**({'allow_partial': True} if allow_partial else {}))
|
**({'allow_partial': True} if allow_partial else {}))
|
||||||
scope = _scope(self._store, task_id)
|
scope = _scope(self._store, task_id)
|
||||||
paths = tuple(project.path for _, project in scope)
|
paths = tuple(project.path for _, project in scope)
|
||||||
@@ -279,7 +278,7 @@ class TaskCenterService:
|
|||||||
reason = '位号在 BOM 中重复(' + ';'.join(locations) + ')'
|
reason = '位号在 BOM 中重复(' + ';'.join(locations) + ')'
|
||||||
annotated.append(replace(row, source_file=str(source.source), source_row=source.excel_row,
|
annotated.append(replace(row, source_file=str(source.source), source_row=source.excel_row,
|
||||||
reason=reason + f';来源:{source.source} 第 {source.excel_row} 行'))
|
reason=reason + f';来源:{source.source} 第 {source.excel_row} 行'))
|
||||||
annotated_report = replace(report, rows=tuple(annotated), source_map_path=mapping, warnings=tuple(warnings))
|
annotated_report = replace(report, rows=tuple(annotated), source_map_path=mapping)
|
||||||
return bind_source_report(annotated_report,
|
return bind_source_report(annotated_report,
|
||||||
tuple(dict.fromkeys((str(row.source), row.source_sha256) for row in rows)), mapping)
|
tuple(dict.fromkeys((str(row.source), row.source_sha256) for row in rows)), mapping)
|
||||||
|
|
||||||
@@ -291,8 +290,7 @@ class TaskCenterService:
|
|||||||
write_routed_bom(normalized, rows, routes, project_names=names)
|
write_routed_bom(normalized, rows, routes, project_names=names)
|
||||||
append_task_event(self._logging, level='INFO', task_id=task_id,
|
append_task_event(self._logging, level='INFO', task_id=task_id,
|
||||||
operation='preview_bom_sources', message='BOM 导入来源记录已保存',
|
operation='preview_bom_sources', message='BOM 导入来源记录已保存',
|
||||||
details={'source_map_path': str(mapping), 'source_count': len({row.source for row in rows}),
|
details={'source_map_path': str(mapping), 'source_count': len({row.source for row in rows})})
|
||||||
'warnings': warnings})
|
|
||||||
report = inspect_batch(self, task_id, normalized, stop_event=stop_event,
|
report = inspect_batch(self, task_id, normalized, stop_event=stop_event,
|
||||||
on_progress=on_progress, on_phase=inspection_phase, runtime=runtime,
|
on_progress=on_progress, on_phase=inspection_phase, runtime=runtime,
|
||||||
**({'allow_partial': True} if allow_partial else {}))
|
**({'allow_partial': True} if allow_partial else {}))
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ 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': '操作已强制中断,结果待核验。',
|
||||||
@@ -57,6 +59,8 @@ 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,6 +19,8 @@ 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
|
||||||
|
|
||||||
@@ -44,6 +46,9 @@ 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)
|
||||||
@@ -137,6 +142,9 @@ 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(format_operation_error(error))
|
||||||
|
else:
|
||||||
self.summary.setText(getattr(error, 'message', str(error)))
|
self.summary.setText(getattr(error, 'message', str(error)))
|
||||||
|
|
||||||
def _finished(self):
|
def _finished(self):
|
||||||
@@ -779,22 +787,21 @@ class ProjectPlanPanel(QWidget):
|
|||||||
report = state.report
|
report = state.report
|
||||||
if report is None:
|
if report is None:
|
||||||
return '', '', ''
|
return '', '', ''
|
||||||
warning_summary = f' · 警告 {len(report.warnings)} 项' if report.warnings else ''
|
|
||||||
if report.deferred:
|
if report.deferred:
|
||||||
failed_paths = {row.project_path for row in report.rows if row.status == 'failed'}
|
failed_paths = {row.project_path for row in report.rows if row.status == 'failed'}
|
||||||
accepted = tuple(row for row in report.rows if row.project_path not in failed_paths)
|
accepted = tuple(row for row in report.rows if row.project_path not in failed_paths)
|
||||||
summary = (f'BOM 表格已保存,工程位号待核验:{len(accepted)} 行、'
|
summary = (f'BOM 表格已保存,工程位号待核验:{len(accepted)} 行、'
|
||||||
f'{len({row.project_path for row in accepted})} 个工程;失败 {report.failed_rows} 行{warning_summary}。')
|
f'{len({row.project_path for row in accepted})} 个工程;失败 {report.failed_rows} 行。')
|
||||||
details = [summary, *report.warnings, '确认执行后仅核验当前工程;本次导入未读取工程位号。']
|
details = [summary, '确认执行后仅核验当前工程;本次导入未读取工程位号。']
|
||||||
details.extend(f'{row.project_name} · {Path(row.source_file).name} 第 {row.source_row} 行:{row.reason}'
|
details.extend(f'{row.project_name} · {Path(row.source_file).name} 第 {row.source_row} 行:{row.reason}'
|
||||||
for row in report.rows)
|
for row in report.rows)
|
||||||
return summary, '\n'.join(details), f'BOM 已保存 · 待核验{warning_summary} · 详情'
|
return summary, '\n'.join(details), 'BOM 已保存 · 待核验 · 详情'
|
||||||
outcome = '校验通过' if state.phase is BomImportPhase.PREVIEW_READY else '校验未通过'
|
outcome = '校验通过' if state.phase is BomImportPhase.PREVIEW_READY else '校验未通过'
|
||||||
summary = (f'BOM {outcome}:共 {report.total_rows} 行,通过 {report.passed_rows} 行、'
|
summary = (f'BOM {outcome}:共 {report.total_rows} 行,通过 {report.passed_rows} 行、'
|
||||||
f'失败 {report.failed_rows} 行、未检查 {report.unchecked_rows} 行;'
|
f'失败 {report.failed_rows} 行、未检查 {report.unchecked_rows} 行;'
|
||||||
f'共 {report.total_projects} 个工程,通过 {report.passed_projects} 个、'
|
f'共 {report.total_projects} 个工程,通过 {report.passed_projects} 个、'
|
||||||
f'失败 {report.failed_projects} 个、未检查 {report.unchecked_projects} 个{warning_summary}。')
|
f'失败 {report.failed_projects} 个、未检查 {report.unchecked_projects} 个。')
|
||||||
details = [summary, *report.errors, *report.warnings]
|
details = [summary, *report.errors]
|
||||||
if report.source_map_path is not None:
|
if report.source_map_path is not None:
|
||||||
details.append(f'导入来源记录:{report.source_map_path}')
|
details.append(f'导入来源记录:{report.source_map_path}')
|
||||||
details.extend(f'{Path(row.source_file).name + " · " if row.source_file else ""}'
|
details.extend(f'{Path(row.source_file).name + " · " if row.source_file else ""}'
|
||||||
|
|||||||
@@ -1,13 +1,11 @@
|
|||||||
"""Safe multi-file BOM loading and project routing for workspace imports."""
|
"""Safe multi-file BOM loading and project routing for workspace imports."""
|
||||||
|
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from difflib import get_close_matches
|
|
||||||
import hashlib
|
import hashlib
|
||||||
from pathlib import Path, PureWindowsPath
|
from pathlib import Path, PureWindowsPath
|
||||||
|
|
||||||
from openpyxl import load_workbook
|
from openpyxl import load_workbook
|
||||||
|
|
||||||
from .bom_import_report import BomImportReport, BomInspectionError
|
|
||||||
from .bom_plan import BOM_HEADERS, _normal_headers, _part_number_text, write_bom_template
|
from .bom_plan import BOM_HEADERS, _normal_headers, _part_number_text, write_bom_template
|
||||||
from .errors import TaskCenterError
|
from .errors import TaskCenterError
|
||||||
|
|
||||||
@@ -57,37 +55,7 @@ def _selected_xlsx(sources):
|
|||||||
return tuple(sorted(paths, key=lambda path: str(path).casefold()))
|
return tuple(sorted(paths, key=lambda path: str(path).casefold()))
|
||||||
|
|
||||||
|
|
||||||
_REQUIRED_HEADERS = (
|
def load_sources(sources, *, stop_event=None, on_progress=None, allow_partial=False):
|
||||||
('old_part_number', '旧料号'), ('new_part_number', '新料号'), ('refdes', '位号'),
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def _source_headers(path, cells):
|
|
||||||
headers = _normal_headers(tuple(cell.value for cell in cells))
|
|
||||||
names = tuple(name for name in headers if name)
|
|
||||||
unknown = tuple(str(cell.value).strip() for cell, name in zip(cells, headers, strict=True)
|
|
||||||
if not name and cell.value is not None and str(cell.value).strip())
|
|
||||||
if any(cell.data_type == 'f' for cell in cells):
|
|
||||||
reason = 'BOM 表头不接受公式'
|
|
||||||
elif len(names) != len(set(names)):
|
|
||||||
reason = 'BOM 列名重复'
|
|
||||||
else:
|
|
||||||
missing = [(name, label) for name, label in _REQUIRED_HEADERS if name not in names]
|
|
||||||
if not missing:
|
|
||||||
return {name: index for index, name in enumerate(headers) if name}, unknown
|
|
||||||
labels = '、'.join(label for _, label in missing)
|
|
||||||
hints = []
|
|
||||||
for name, label in missing:
|
|
||||||
matches = (get_close_matches(label, unknown, n=1, cutoff=.7)
|
|
||||||
or get_close_matches(name, unknown, n=1, cutoff=.8))
|
|
||||||
if matches:
|
|
||||||
hints.append(f'请将「{matches[0]}」改为「{label}」')
|
|
||||||
reason = '。'.join([f'BOM 缺少必需列「{labels}」', *hints])
|
|
||||||
message = f'{path.name} 第 1 行:{reason}'
|
|
||||||
raise BomInspectionError(TaskCenterError('bom_import', message), BomImportReport((), (), errors=(message,)))
|
|
||||||
|
|
||||||
|
|
||||||
def load_sources(sources, *, stop_event=None, on_progress=None, allow_partial=False, warnings=None):
|
|
||||||
"""Read every selected workbook before any CAD operation starts."""
|
"""Read every selected workbook before any CAD operation starts."""
|
||||||
from .operation_control import check_cancelled
|
from .operation_control import check_cancelled
|
||||||
|
|
||||||
@@ -106,7 +74,17 @@ def load_sources(sources, *, stop_event=None, on_progress=None, allow_partial=Fa
|
|||||||
if len(workbook.worksheets) != 1:
|
if len(workbook.worksheets) != 1:
|
||||||
raise ValueError('BOM 只能包含一个工作表')
|
raise ValueError('BOM 只能包含一个工作表')
|
||||||
rows = iter(workbook.active.iter_rows())
|
rows = iter(workbook.active.iter_rows())
|
||||||
positions, unknown = _source_headers(path, next(rows, ()))
|
header_cells = next(rows, ())
|
||||||
|
headers = _normal_headers(tuple(cell.value for cell in header_cells))
|
||||||
|
names = tuple(name for name in headers if name)
|
||||||
|
if len(names) != len(set(names)):
|
||||||
|
raise ValueError('BOM 列名重复')
|
||||||
|
required = {'old_part_number', 'new_part_number', 'refdes'}
|
||||||
|
if not required <= set(names):
|
||||||
|
raise ValueError('BOM 必须包含旧料号、新料号和位号列')
|
||||||
|
if any(cell.data_type == 'f' for cell in header_cells):
|
||||||
|
raise ValueError('BOM 表头不接受公式')
|
||||||
|
positions = {name: index for index, name in enumerate(headers) if name}
|
||||||
for excel_row, cells in enumerate(rows, 2):
|
for excel_row, cells in enumerate(rows, 2):
|
||||||
check_cancelled(stop_event)
|
check_cancelled(stop_event)
|
||||||
formula = any(cell.data_type == 'f' for cell in cells)
|
formula = any(cell.data_type == 'f' for cell in cells)
|
||||||
@@ -138,8 +116,6 @@ def load_sources(sources, *, stop_event=None, on_progress=None, allow_partial=Fa
|
|||||||
result.append(SourceRow(path, excel_row, values, value_mode, source_sha256))
|
result.append(SourceRow(path, excel_row, values, value_mode, source_sha256))
|
||||||
if hashlib.sha256(path.read_bytes()).hexdigest() != source_sha256:
|
if hashlib.sha256(path.read_bytes()).hexdigest() != source_sha256:
|
||||||
raise ValueError('BOM 来源在读取期间已改变,请重新导入')
|
raise ValueError('BOM 来源在读取期间已改变,请重新导入')
|
||||||
if warnings is not None:
|
|
||||||
warnings.extend(f'{path.name}:已忽略未知列「{name}」' for name in unknown)
|
|
||||||
except TaskCenterError:
|
except TaskCenterError:
|
||||||
raise
|
raise
|
||||||
except Exception as error:
|
except Exception as error:
|
||||||
|
|||||||
@@ -1,99 +0,0 @@
|
|||||||
import json
|
|
||||||
import os
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
from openpyxl import load_workbook
|
|
||||||
from PySide6.QtWidgets import QFileDialog
|
|
||||||
|
|
||||||
from test_bom_batch import batch, records_for
|
|
||||||
from dx_productivity.trial_task_center.bom_plan import write_bom_template
|
|
||||||
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize('case', ['extra', 'near', 'missing', 'header_formula', 'row_formula', 'original'])
|
|
||||||
def test_bom_header_feedback_through_workspace(case, batch, tmp_path, qtbot, monkeypatch):
|
|
||||||
service, _, tasks, targets, inventory_calls = batch
|
|
||||||
task = tasks[0]
|
|
||||||
record = records_for(tasks, targets)[0]
|
|
||||||
source = write_bom_template(tmp_path / f'{case}.xlsx', [record])
|
|
||||||
workbook = load_workbook(source)
|
|
||||||
sheet = workbook.active
|
|
||||||
if case == 'extra':
|
|
||||||
sheet['L1'], sheet['L2'] = '供应商', 'Example supplier'
|
|
||||||
sheet['M1'], sheet['M2'] = '备注', 'Example note'
|
|
||||||
elif case == 'near':
|
|
||||||
sheet['D1'] = '新料号编码'
|
|
||||||
elif case == 'missing':
|
|
||||||
sheet['D1'] = None
|
|
||||||
elif case == 'header_formula':
|
|
||||||
sheet['L1'] = '=1+1'
|
|
||||||
elif case == 'row_formula':
|
|
||||||
sheet['L1'], sheet['L2'] = '备注', '=1+1'
|
|
||||||
workbook.save(source)
|
|
||||||
workbook.close()
|
|
||||||
assert_workspace_import(case, source, task, service, inventory_calls, qtbot, monkeypatch)
|
|
||||||
|
|
||||||
|
|
||||||
def test_field_extra_column_through_workspace(batch, tmp_path, qtbot, monkeypatch):
|
|
||||||
field = os.environ.get('DX_ISSUE33_D5_FIELD')
|
|
||||||
if not field:
|
|
||||||
pytest.skip('set DX_ISSUE33_D5_FIELD to replay the field attachment')
|
|
||||||
service, _, tasks, targets, inventory_calls = batch
|
|
||||||
source = tmp_path / Path(field).name
|
|
||||||
workbook = load_workbook(field)
|
|
||||||
sheet = workbook.active
|
|
||||||
# Rebind to the local fixture project. Keep the original Excel header and BOM cells.
|
|
||||||
sheet['A2'] = tasks[0].name
|
|
||||||
sheet['B2'] = str(targets[tasks[0].task_id][0].project_path)
|
|
||||||
workbook.save(source)
|
|
||||||
workbook.close()
|
|
||||||
assert_workspace_import('field', source, tasks[0], service, inventory_calls, qtbot, monkeypatch)
|
|
||||||
|
|
||||||
|
|
||||||
def assert_workspace_import(case, source, task, service, inventory_calls, qtbot, monkeypatch):
|
|
||||||
window = TrialTaskCenterWindow(service)
|
|
||||||
window.auto_intervention_check.setChecked(False)
|
|
||||||
qtbot.addWidget(window)
|
|
||||||
window.open_task(task.task_id)
|
|
||||||
panel = window.plan_panel
|
|
||||||
qtbot.waitUntil(panel.import_bom_button.isEnabled, timeout=5000)
|
|
||||||
monkeypatch.setattr(QFileDialog, 'getOpenFileNames', lambda *args: ([str(source)], 'Excel (*.xlsx)'))
|
|
||||||
panel.import_bom_button.click()
|
|
||||||
qtbot.waitUntil(lambda: not window._workers, timeout=8000)
|
|
||||||
status = window.run_panel.operator_band.text()
|
|
||||||
print(status)
|
|
||||||
pending = service.pending_bom(task.task_id)
|
|
||||||
assert not inventory_calls
|
|
||||||
if case in {'extra', 'field', 'original', 'near', 'missing', 'header_formula'}:
|
|
||||||
panel.report_toggle.setChecked(True)
|
|
||||||
assert panel.report_dialog is not None
|
|
||||||
details = panel.report_dialog.view.toPlainText()
|
|
||||||
print(details)
|
|
||||||
if case in {'extra', 'field', 'original'}:
|
|
||||||
assert len(pending) == 1
|
|
||||||
assert panel.last_bom_report.failed_rows == 0 and panel.last_bom_report.deferred
|
|
||||||
if case == 'extra':
|
|
||||||
assert '失败 0 行' in status and '警告 2 项' in status
|
|
||||||
assert all(text in details for text in ('已忽略', '供应商', '备注', source.name))
|
|
||||||
assert pending[0].record.new == 'NEW-0'
|
|
||||||
events = (service._logging.root / 'tasks' / task.task_id / 'events.jsonl').read_text(encoding='utf-8')
|
|
||||||
entries = [json.loads(line) for line in events.splitlines()]
|
|
||||||
entry = next(event for event in entries if event['operation'] == 'import_bom_drafts')
|
|
||||||
assert tuple(entry['details']['warnings']) == panel.last_bom_report.warnings
|
|
||||||
elif case == 'field':
|
|
||||||
assert '警告 1 项' in status and 'extra_column' in details
|
|
||||||
else:
|
|
||||||
assert '警告' not in status and '已忽略' not in details
|
|
||||||
else:
|
|
||||||
assert not pending
|
|
||||||
if case == 'near':
|
|
||||||
assert '缺少必需列「新料号」' in status
|
|
||||||
assert '「新料号编码」' in details and '改为「新料号」' in details
|
|
||||||
elif case == 'missing':
|
|
||||||
assert '缺少必需列「新料号」' in status and '新料号' in details
|
|
||||||
elif case == 'header_formula':
|
|
||||||
assert 'BOM 表头不接受公式' in status and 'BOM 表头不接受公式' in details
|
|
||||||
else:
|
|
||||||
assert '第 2 行不接受公式' in status
|
|
||||||
window.close()
|
|
||||||
@@ -9,8 +9,6 @@ from test_bom_batch import batch
|
|||||||
|
|
||||||
|
|
||||||
def test_real_supervised_sources_roundtrip_origin_metadata_and_preview(batch, tmp_path):
|
def test_real_supervised_sources_roundtrip_origin_metadata_and_preview(batch, tmp_path):
|
||||||
from openpyxl import load_workbook
|
|
||||||
|
|
||||||
from dx_productivity.trial_task_center.bom_plan import write_bom_template
|
from dx_productivity.trial_task_center.bom_plan import write_bom_template
|
||||||
service, store, tasks, targets, calls = batch
|
service, store, tasks, targets, calls = batch
|
||||||
for task in tasks:
|
for task in tasks:
|
||||||
@@ -19,14 +17,9 @@ def test_real_supervised_sources_roundtrip_origin_metadata_and_preview(batch, tm
|
|||||||
'project_name': task.name, 'project_path': str(targets[task.task_id][0].project_path),
|
'project_name': task.name, 'project_path': str(targets[task.task_id][0].project_path),
|
||||||
'old_part_number': 'OLD', 'new_part_number': 'NEW', 'refdes': 'R1', 'value_mode': 'part_number',
|
'old_part_number': 'OLD', 'new_part_number': 'NEW', 'refdes': 'R1', 'value_mode': 'part_number',
|
||||||
},)) for index, task in enumerate(tasks))
|
},)) for index, task in enumerate(tasks))
|
||||||
workbook = load_workbook(sources[0])
|
|
||||||
workbook.active['M1'] = '备注'
|
|
||||||
workbook.save(sources[0])
|
|
||||||
workbook.close()
|
|
||||||
service._supervised = True
|
service._supervised = True
|
||||||
report = service.preview_bom_sources(tasks[0].task_id, sources)
|
report = service.preview_bom_sources(tasks[0].task_id, sources)
|
||||||
assert report.passed_rows == 2 and report.preview is not None
|
assert report.passed_rows == 2 and report.preview is not None
|
||||||
assert report.warnings == ('source-0.xlsx:已忽略未知列「备注」',)
|
|
||||||
assert tuple(row.source_file for row in report.rows) == tuple(str(path.resolve()) for path in sources)
|
assert tuple(row.source_file for row in report.rows) == tuple(str(path.resolve()) for path in sources)
|
||||||
assert all(row.source_row == 2 for row in report.rows)
|
assert all(row.source_row == 2 for row in report.rows)
|
||||||
assert report.source_map_path.is_file()
|
assert report.source_map_path.is_file()
|
||||||
|
|||||||
@@ -0,0 +1,134 @@
|
|||||||
|
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
|
||||||
Reference in new issue
Block a user