diff --git a/packaging/CbbRefreshVerify.spec b/packaging/CbbRefreshVerify.spec index 3a0ef58..c5d45aa 100644 --- a/packaging/CbbRefreshVerify.spec +++ b/packaging/CbbRefreshVerify.spec @@ -1,5 +1,6 @@ from pathlib import Path import os +from shutil import copyfile import struct project_root = Path(SPECPATH).parent assets_root = project_root / 'src' / 'cbb_refresh_verify' / 'assets' @@ -42,3 +43,4 @@ pyz = PYZ(a.pure) exe = EXE(pyz, a.scripts, [], exclude_binaries=True, name='CbbRefreshVerify', console=False, icon=str(assets_root / 'cbb_refresh_verify.ico')) coll = COLLECT(exe, a.binaries, a.zipfiles, a.datas, name='CbbRefreshVerify-Background') +copyfile(project_root / 'packaging' / '使用说明.txt', Path(coll.name) / '使用说明.txt') diff --git a/packaging/使用说明.txt b/packaging/使用说明.txt new file mode 100644 index 0000000..c797935 --- /dev/null +++ b/packaging/使用说明.txt @@ -0,0 +1,27 @@ +CBB 刷新校验使用说明 + +将 ZIP 完整解压到可写文件夹,保留 CbbRefreshVerify.exe 和 _internal, +双击 CbbRefreshVerify.exe。目标电脑需要安装 Mentor EE 7.9.5, +并能访问中心库及其依赖。写入或恢复前请手动保留可用备份。 + +在「检验」页选择 .lmc 文件并点击「读取 CBB」。目录预览先出现, +READY 和待验证状态会随后由 Mentor 核对。确认中心库和目标工程后 +开始校验。校验会保存工程,经 Mentor 确认为 READY 才显示通过。 + +点击「取消当前任务并停止队列」后,程序等待原生操作安全退出。 +重新提交同库任务时,若仍在收尾,界面会显示等待原因。可通过 +「释放残留会话」核对占用的库、工程和进程,查看历史操作记录。 + +应用默认把日志、批次报告和证据保存在程序旁的 data 目录下。 +可在「检验」页点「打开日志目录」。使用命令行时,可指定数据目录。 +data\logs\application.log 包含启动和任务状态,data\reports 包含批次结果。 + +PowerShell 批次示例(在 CbbRefreshVerify.exe 所在目录中运行) + + $run = Start-Process .\CbbRefreshVerify.exe -ArgumentList '--batch-lmc', '"D:\测试库\mentor_lib.lmc"', '--block', 'CBB_01', '--data-root', '"D:\CBB日志"' -RedirectStandardError .\batch-error.txt -PassThru -Wait + $run.ExitCode + +--block 可重复指定工程。--auto-confirm-pcb-open 允许命令行在核验 +资源可写后继续处理已识别的 PCB 读写确认。退出码 0 表示所选项全部 +通过,1 表示输入或启动失败,2 表示批次有未通过项或命令参数错误。 +启动或输入错误写入重定向的 batch-error.txt。 diff --git a/src/cbb_refresh_verify/application.py b/src/cbb_refresh_verify/application.py index a1125e1..6a9e494 100644 --- a/src/cbb_refresh_verify/application.py +++ b/src/cbb_refresh_verify/application.py @@ -3,6 +3,7 @@ import argparse, os, sys from contextlib import contextmanager from pathlib import Path from typing import Sequence +from .network_path import NetworkPathError from .runtime_logging import configure @@ -62,6 +63,29 @@ def resolve_data_root(cli_value: Path | None) -> Path: local = os.environ.get("LOCALAPPDATA") return (Path(local) / "CbbRefreshVerify" if local else Path.home() / "AppData" / "Local" / "CbbRefreshVerify").resolve() +def _report_entry_error(message: str, *, command_line: bool) -> int: + if not command_line: + import win32api + import win32con + win32api.MessageBox(None, message, 'CBB 刷新校验启动失败', win32con.MB_ICONERROR) + elif sys.stderr is not None: + print(message, file=sys.stderr, flush=True) + elif os.name == 'nt': + # PyInstaller's windowed executable leaves sys.stderr unset even + # when the caller supplied a redirected Windows stderr handle. + import pywintypes + import win32api + import win32console + import win32file + try: + handle = win32api.GetStdHandle(win32console.STD_ERROR_HANDLE) + if handle: + win32file.WriteFile(handle, (message + '\n').encode('utf-8')) + except pywintypes.error: + pass + return 1 + + def _positive_int(value): try: number = int(value) @@ -171,14 +195,24 @@ def main(argv: Sequence[str] | None = None) -> int: return dialog_agent_main(args.dialog_agent) if args.verify_worker: return _native_worker_entry('verify', args.verify_worker) - context = configure(resolve_data_root(args.data_root)); logger = context.logger; logger.info("application_start") + command_line = bool(args.batch_lmc or args.smoke_test) + data_root = args.data_root + try: + data_root = resolve_data_root(data_root) + context = configure(data_root) + except (OSError, ValueError, RuntimeError): + location = data_root if data_root is not None else '默认数据目录' + return _report_entry_error(f'DATA_ROOT_UNWRITABLE: 无法写入数据目录 {location}。' + '请指定可写的 --data-root。', command_line=command_line) + logger = context.logger + logger.info("application_start") try: if args.batch_lmc: from .verify_runner import (VerifyRequest, native_lm_verify_enabled, run_batch, write_batch_report, failure_report_path) from .library_reader import read_library_fast from .batch_status import authoritative_status_map - from .network_path import LibraryPathLease, select_library_file + from .network_path import LibraryPathLease, select_library_file, validate_library_file with LibraryPathLease.acquire(args.batch_lmc) as lease: mentor_path = select_library_file(lease.mentor_path) logger.info( @@ -186,15 +220,18 @@ def main(argv: Sequence[str] | None = None) -> int: lease.display_path, mentor_path, lease.drive or '-', lease.remote_root or '-', lease.created) names = list(args.block) - if not names: + if names: + validate_library_file(mentor_path) + else: library = read_library_fast( mentor_path, status_reader=lambda path, names: authoritative_status_map( names, path, context.root/'status-scan.jsonl'), ) - if library.error: raise RuntimeError(library.error) + if library.error: raise NetworkPathError(library.error) names = [record.name for record in library.records if record.status != 'READY'] - if not names: raise RuntimeError('中心库未读取到需要校验的 CBB') + if not names: + raise NetworkPathError('INPUT_NO_BLOCKS: 中心库未读取到需要校验的 CBB。') total = len(names) if args.limit is not None: names = names[:args.limit] @@ -248,6 +285,12 @@ def main(argv: Sequence[str] | None = None) -> int: logger.info('gui_smoke_window_created title=%s', window.windowTitle()) QTimer.singleShot(250, app.quit) code = int(app.exec()); logger.info("application_clean_shutdown exit_code=%s", code); return code - except Exception: logger.exception("application_startup_failure"); return 1 + except NetworkPathError as error: + logger.warning('application_input_failure %s', error) + return _report_entry_error(str(error), command_line=command_line) + except Exception: + logger.exception('application_startup_failure') + return _report_entry_error(f'APPLICATION_STARTUP_FAILED: 无法完成启动或批次,请查看日志目录 {context.root}。', + command_line=command_line) finally: for handler in logger.handlers: handler.flush() diff --git a/src/cbb_refresh_verify/library_reader.py b/src/cbb_refresh_verify/library_reader.py index f576b73..0cf9575 100644 --- a/src/cbb_refresh_verify/library_reader.py +++ b/src/cbb_refresh_verify/library_reader.py @@ -4,7 +4,7 @@ import logging import json from collections import Counter, defaultdict from .models import CbbRecord, LibraryReadResult -from .network_path import absolute_preserving_drive +from .network_path import absolute_preserving_drive, validate_library_file logger = logging.getLogger(__name__) CACHE_SCHEMA_VERSION = 2 @@ -206,15 +206,7 @@ def read_library_fast(path: Path, *, status_reader=None): """Discover directories; this does not validate native format/registration.""" try: path = Path(path) - if path.suffix.casefold() != '.lmc': - return LibraryReadResult((), 'INPUT_SUFFIX: 请选择 .lmc 中心库文件。') - if not path.is_file(): - return LibraryReadResult((), f'INPUT_MISSING: 中心库不存在或不是文件: {path}') - with path.open('rb') as stream: - if not stream.read(1): - return LibraryReadResult((), 'INPUT_EMPTY: 中心库文件为空。') - if any(lock.is_dir() for lock in (path.with_suffix('.lock'), path.with_name('.'+path.stem+'.cbb-upload.lock'))): - return LibraryReadResult((), 'INPUT_LOCK_DIRECTORY: 中心库锁路径是目录。') + validate_library_file(path) folder = path.parent/'ReusableBlocksLP' if folder.exists() and not folder.is_dir(): return LibraryReadResult((), f'INPUT_DIRECTORY: ReusableBlocksLP 不是目录: {folder}') diff --git a/src/cbb_refresh_verify/network_path.py b/src/cbb_refresh_verify/network_path.py index e1981af..bef864e 100644 --- a/src/cbb_refresh_verify/network_path.py +++ b/src/cbb_refresh_verify/network_path.py @@ -183,22 +183,41 @@ def _normalize_input_path(path) -> str: def select_library_file(path) -> Path: """Return a concrete LMC, accepting a directory with exactly one LMC.""" candidate = Path(path) - if candidate.is_file(): - if candidate.suffix.casefold() != ".lmc": - raise NetworkPathError(f"中心库文件必须是 .lmc: {candidate}") - return candidate - if candidate.is_dir(): - files = sorted( - (item for item in candidate.iterdir() - if item.is_file() and item.suffix.casefold() == ".lmc"), - key=lambda item: item.name.casefold(), - ) - if len(files) != 1: - raise NetworkPathError( - f"中心库目录必须包含唯一的 .lmc 文件,当前找到 {len(files)} 个: {candidate}" - ) - return files[0] - raise NetworkPathError(f"中心库路径不存在或不可访问: {candidate}") + try: + if candidate.is_file(): + if candidate.suffix.casefold() != ".lmc": + raise NetworkPathError(f"INPUT_SUFFIX: 中心库文件必须是 .lmc: {candidate}") + return candidate + if candidate.is_dir(): + files = [item for item in candidate.iterdir() + if item.suffix.casefold() == ".lmc" and item.is_file()] + if len(files) != 1: + raise NetworkPathError( + f"INPUT_DIRECTORY: 中心库目录必须包含唯一的 .lmc 文件,当前找到 {len(files)} 个: {candidate}" + ) + return files[0] + except PermissionError as error: + raise NetworkPathError(f"INPUT_PERMISSION: 无权读取中心库: {candidate}") from error + raise NetworkPathError(f"INPUT_MISSING: 中心库路径不存在或不可访问: {candidate}") + + +def validate_library_file(path: Path) -> None: + """Reject invalid LMC inputs before a directory scan or native dispatch.""" + if path.suffix.casefold() != '.lmc': + raise NetworkPathError(f'INPUT_SUFFIX: 请选择 .lmc 中心库文件: {path}') + try: + if not path.is_file(): + raise NetworkPathError(f'INPUT_MISSING: 中心库不存在或不是文件: {path}') + with path.open('rb') as stream: + if not stream.read(1): + raise NetworkPathError(f'INPUT_EMPTY: 中心库文件为空: {path}') + if any(lock.is_dir() for lock in + (path.with_suffix('.lock'), path.with_name('.' + path.stem + '.cbb-upload.lock'))): + raise NetworkPathError(f'INPUT_LOCK_DIRECTORY: 中心库锁路径是目录: {path}') + except FileNotFoundError as error: + raise NetworkPathError(f'INPUT_MISSING: 中心库不存在: {path}') from error + except PermissionError as error: + raise NetworkPathError(f'INPUT_PERMISSION: 无权读取中心库: {path}') from error @dataclass diff --git a/tests/support/frozen_input_smoke.py b/tests/support/frozen_input_smoke.py new file mode 100644 index 0000000..975ae2b --- /dev/null +++ b/tests/support/frozen_input_smoke.py @@ -0,0 +1,118 @@ +"""Verify the Windows desktop and CLI input paths in a candidate package.""" + +from contextlib import contextmanager +import json +import locale +from pathlib import Path +import subprocess +import sys +import time +from uuid import uuid4 + +import ntsecuritycon +import pywintypes +import win32api +import win32con +import win32gui +import win32process +import win32security + + +@contextmanager +def deny_access(path, rights): + dacl_info = win32security.DACL_SECURITY_INFORMATION + original = win32security.GetFileSecurity(str(path), dacl_info) + sid, _, _ = win32security.LookupAccountName(None, win32api.GetUserName()) + acl = win32security.ACL() + acl.AddAccessDeniedAce(win32security.ACL_REVISION, rights, sid) + acl.AddAccessAllowedAce(win32security.ACL_REVISION, win32con.GENERIC_ALL, sid) + restricted = win32security.SECURITY_DESCRIPTOR() + restricted.SetSecurityDescriptorDacl(True, acl, False) + win32security.SetFileSecurity(str(path), dacl_info, restricted) + try: + yield + finally: + win32security.SetFileSecurity(str(path), dacl_info, original) + + +def cli(exe, library, data_root, expected): + result = subprocess.run( + [str(exe), '--batch-lmc', str(library), '--block', 'Fixture', '--data-root', str(data_root)], + capture_output=True, timeout=15, creationflags=subprocess.CREATE_NO_WINDOW, + ) + try: + detail = result.stderr.decode('utf-8') + except UnicodeDecodeError: + detail = result.stderr.decode(locale.getencoding()) + assert result.returncode == 1 and expected in detail, (result.returncode, detail) + assert 'Traceback' not in detail and not (data_root / 'reports').exists() + return {'exit_code': result.returncode, 'message': detail.strip()} + + +def startup_dialog(exe, data_root): + from cbb_refresh_verify.desktop_worker import DesktopWorker + + worker = DesktopWorker([str(exe), '--data-root', str(data_root)], 'CbbInputSmoke_' + uuid4().hex[:8]) + try: + deadline = time.monotonic() + 15 + while worker.poll() is None and time.monotonic() < deadline: + try: + windows = worker.desktop.EnumDesktopWindows() + except pywintypes.error as error: + if error.winerror != 0: + raise + windows = () + for hwnd in windows: + if win32process.GetWindowThreadProcessId(hwnd)[1] != worker.pid or not win32gui.IsWindowVisible(hwnd): + continue + title = win32gui.GetWindowText(hwnd) + assert title == 'CBB 刷新校验启动失败', title + if win32gui.GetClassName(hwnd) != '#32770': + continue + children = [] + win32gui.EnumChildWindows(hwnd, lambda child, _: children.append(child) or True, None) + button = next((child for child in children if win32gui.GetClassName(child) == 'Button'), None) + if button is None: + continue + texts = [win32gui.GetWindowText(child) for child in children] + message = next((text for text in texts if 'DATA_ROOT_UNWRITABLE' in text), '') + assert str(data_root) in message and '无法写入数据目录' in message, texts + win32gui.PostMessage(button, win32con.BM_CLICK, 0, 0) + code = worker.wait(5) + assert code == 1 + return {'exit_code': code, 'title': title, 'message': message} + time.sleep(0.1) + raise AssertionError(f'Startup dialog did not appear, exit={worker.poll()}') + finally: + if worker.poll() is None: + win32process.TerminateProcess(worker.handle, 1) + worker.wait(5) + worker.close() + + +def main(): + workspace, executable, evidence_dir = (Path(arg).resolve() for arg in sys.argv[1:]) + sys.path.insert(0, str(workspace / 'src')) + evidence_dir.mkdir(parents=True, exist_ok=False) + assert (executable.parent / '使用说明.txt').read_bytes() == (workspace / 'packaging' / '使用说明.txt').read_bytes() + empty_library = evidence_dir / 'empty.lmc' + empty_library.touch() + unreadable_library = evidence_dir / 'unreadable.lmc' + unreadable_library.write_bytes(b'fixture') + data_root = evidence_dir / 'data' + data_root.mkdir() + blocked_root = evidence_dir / 'readonly' + blocked_root.mkdir() + results = {'guide': 'matched', 'empty_lmc': cli(executable, empty_library, data_root, 'INPUT_EMPTY')} + with deny_access(unreadable_library, ntsecuritycon.FILE_READ_DATA): + results['unreadable_lmc'] = cli(executable, unreadable_library, data_root, 'INPUT_PERMISSION') + with deny_access(blocked_root, ntsecuritycon.FILE_ADD_FILE | ntsecuritycon.FILE_ADD_SUBDIRECTORY): + results['cli_data_root'] = cli(executable, empty_library, blocked_root, 'DATA_ROOT_UNWRITABLE') + results['gui_data_root'] = startup_dialog(executable, blocked_root) + summary = json.dumps(results, ensure_ascii=False, indent=2) + (evidence_dir / 'result.json').write_text(summary + '\n', encoding='utf-8') + print(summary) + + +if __name__ == '__main__': + main() diff --git a/tests/test_application.py b/tests/test_application.py index 0ef069a..0c3b588 100644 --- a/tests/test_application.py +++ b/tests/test_application.py @@ -1,11 +1,94 @@ from pathlib import Path +import pytest + + +@pytest.mark.parametrize('filename, contents, code', [ + ('empty.lmc', b'', 'INPUT_EMPTY'), + ('missing.lmc', None, 'INPUT_MISSING'), + ('library.txt', b'library', 'INPUT_SUFFIX'), +]) +def test_explicit_cli_block_validates_lmc_before_dispatch(tmp_path, monkeypatch, capsys, filename, contents, code): + from cbb_refresh_verify import application, verify_runner + + path = tmp_path / filename + if contents is not None: + path.write_bytes(contents) + monkeypatch.setattr(verify_runner, 'run_batch', lambda *a, **kw: pytest.fail('invalid input dispatched')) + + assert application.main(['--batch-lmc', str(path), '--block', 'A', + '--data-root', str(tmp_path / 'data')]) == 1 + assert code in capsys.readouterr().err + + +def test_explicit_cli_block_reports_unreadable_lmc(tmp_path, monkeypatch, capsys): + from cbb_refresh_verify import application, verify_runner + + path = tmp_path / 'library.lmc' + path.write_bytes(b'library') + original_open = Path.open + + def open_path(candidate, *args, **kwargs): + if candidate == path: + raise PermissionError('denied') + return original_open(candidate, *args, **kwargs) + + monkeypatch.setattr(Path, 'open', open_path) + monkeypatch.setattr(verify_runner, 'run_batch', lambda *a, **kw: pytest.fail('unreadable input dispatched')) + assert application.main(['--batch-lmc', str(path), '--block', 'A', + '--data-root', str(tmp_path / 'data')]) == 1 + assert 'INPUT_PERMISSION' in capsys.readouterr().err + + +def test_cli_unwritable_data_root_returns_input_exit_code(tmp_path, capsys): + from cbb_refresh_verify import application + + path = tmp_path / 'data' + path.touch() + assert application.main(['--batch-lmc', str(tmp_path / 'library.lmc'), '--data-root', str(path)]) == 1 + error = capsys.readouterr().err + assert 'DATA_ROOT_UNWRITABLE' in error and str(path) in error + assert 'Traceback' not in error + + +def test_windowed_cli_can_write_to_redirected_windows_stderr(tmp_path): + import subprocess + import sys + + path = tmp_path / 'data' + path.touch() + command = ( + 'import sys; from cbb_refresh_verify.application import main; ' + 'sys.stderr = None; raise SystemExit(main(sys.argv[1:]))' + ) + result = subprocess.run([sys.executable, '-X', 'utf8', '-c', command, + '--batch-lmc', str(tmp_path / 'library.lmc'), '--data-root', str(path)], + capture_output=True, encoding='utf-8', timeout=15, + creationflags=subprocess.CREATE_NO_WINDOW) + assert result.returncode == 1 + assert 'DATA_ROOT_UNWRITABLE' in result.stderr and str(path) in result.stderr + + +def test_desktop_unwritable_data_root_shows_chinese_startup_error(tmp_path, monkeypatch): + import win32api + from cbb_refresh_verify import application + + path = tmp_path / 'data' + path.touch() + messages = [] + monkeypatch.setattr(win32api, 'MessageBox', lambda parent, detail, title, flags: messages.append((title, detail))) + + assert application.main(['--data-root', str(path)]) == 1 + assert len(messages) == 1 + assert '启动失败' in messages[0][0] + assert '无法写入数据目录' in messages[0][1] and str(path) in messages[0][1] + def test_cli_signal_requests_cooperative_batch_stop(tmp_path, monkeypatch): import signal from cbb_refresh_verify import application, verify_runner library = tmp_path/'center.lmc' - library.touch() + library.write_bytes(b'library') old = signal.getsignal(signal.SIGINT) def run(requests, *, stop): signal.getsignal(signal.SIGINT)(signal.SIGINT, None) @@ -65,6 +148,7 @@ def test_batch_cli_acquires_unc_lease_before_directory_scan(tmp_path, monkeypatc monkeypatch.setattr(application, 'configure', lambda *_args: type('C', (), { 'root': tmp_path, 'logger': type('L', (), {'info': lambda *a, **k: None, + 'warning': lambda *a, **k: None, 'exception': lambda *a, **k: None, 'handlers': ()})(), })()) diff --git a/tests/test_extended_safety.py b/tests/test_extended_safety.py index 1ec0be5..4b4e31c 100644 --- a/tests/test_extended_safety.py +++ b/tests/test_extended_safety.py @@ -166,6 +166,7 @@ def test_cli_unsafe_batch_preserves_created_drive(tmp_path, monkeypatch): from cbb_refresh_verify import application backend = FakeWNet() lease = LibraryPathLease.acquire(r'\\server\share\lib.lmc', backend=backend) + (tmp_path/'lib.lmc').write_bytes(b'library') monkeypatch.setattr(LibraryPathLease, 'acquire', lambda path: lease) monkeypatch.setattr('cbb_refresh_verify.network_path.select_library_file', lambda path: tmp_path/'lib.lmc') monkeypatch.setattr('cbb_refresh_verify.verify_runner.run_batch', lambda requests, **kw: [VerifyResult('FAIL', safe_to_continue=False)]) diff --git a/tests/test_packaging.py b/tests/test_packaging.py index 315c4b9..8a1ed1d 100644 --- a/tests/test_packaging.py +++ b/tests/test_packaging.py @@ -14,7 +14,20 @@ def test_spec_packages_adaptive_dialog_rules_and_uia_modules(): assert 'pywinauto' in text -def test_spec_analysis_includes_pywin32_timezone_dynamic_import(): +def test_spec_analysis_includes_pywin32_timezone_dynamic_import(tmp_path): + captured = _capture_spec_analysis(tmp_path) + assert 'win32timezone' in captured['hiddenimports'] + + +def test_spec_copies_quick_start_next_to_executable(tmp_path): + target = tmp_path / 'CbbRefreshVerify-Background' + target.mkdir() + _capture_spec_analysis(target) + guide = (target / '使用说明.txt').read_text(encoding='utf-8') + assert 'CbbRefreshVerify.exe' in guide and '--data-root' in guide + + +def _capture_spec_analysis(target): from types import SimpleNamespace captured = {} def analysis(*args, **kwargs): @@ -23,6 +36,6 @@ def test_spec_analysis_includes_pywin32_timezone_dynamic_import(): path = Path('packaging/CbbRefreshVerify.spec') namespace = {'SPECPATH': str(path.parent.resolve()), 'Analysis': analysis, 'PYZ': lambda *a, **k: None, 'EXE': lambda *a, **k: None, - 'COLLECT': lambda *a, **k: None} + 'COLLECT': lambda *a, **k: SimpleNamespace(name=str(target))} exec(compile(path.read_text(encoding='utf-8'), str(path), 'exec'), namespace) - assert 'win32timezone' in captured['hiddenimports'] + return captured diff --git a/tests/test_review345_ui_cli.py b/tests/test_review345_ui_cli.py index 6328bd7..f33e2dd 100644 --- a/tests/test_review345_ui_cli.py +++ b/tests/test_review345_ui_cli.py @@ -117,6 +117,7 @@ def batch_cli(tmp_path, monkeypatch): def __enter__(self): return self def __exit__(self, *_): pass def retain_for_recovery(self): retained.append(self.drive) + Lease.mentor_path.write_bytes(b'library') monkeypatch.setattr(network.LibraryPathLease, 'acquire', lambda _: Lease()) monkeypatch.setattr(network, 'select_library_file', lambda path: path) monkeypatch.setattr(reader, 'read_library_fast', lambda *a, **kw: LibraryReadResult((