feat: add safe native Mentor PDF exporter and tested portable UI
This commit is contained in:
1 parent
10a87d2cee
commit
d4928af5b6
33 files changed
+2267
-13
No files matched your search
@@ -0,0 +1,14 @@
|
||||
from pathlib import Path
|
||||
import pytest
|
||||
|
||||
@pytest.fixture
|
||||
def project_factory(tmp_path):
|
||||
def make(relative="board", name="board", schematic=True):
|
||||
root = tmp_path / relative
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
project = root / f"{name}.prj"
|
||||
project.write_text('SECTION DesignInfo\nKEY FrontEndSnapshot "DxD"\nENDSECTION\nSECTION Board1\nKEY RootBlock "ROOT"\nENDSECTION\nSECTION iCDB\nKEY iCDBDir ".\\database"\nENDSECTION\n' if schematic else 'SECTION PCB\nKEY ConfigType "PCB"\nENDSECTION\n')
|
||||
(root / "database").mkdir(exist_ok=True)
|
||||
(root / "database" / "icdb.dat").write_bytes(b"sample database")
|
||||
return project
|
||||
return make
|
||||
@@ -0,0 +1,72 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
from mentor_pdf_export.cli import main
|
||||
|
||||
|
||||
def test_self_check_writes_machine_readable_report(tmp_path):
|
||||
report=tmp_path / "check.json"
|
||||
assert main(["--self-check","--report",str(report)]) == 0
|
||||
data=json.loads(report.read_text(encoding="utf-8"))
|
||||
assert data["version"] == "0.1.0"
|
||||
assert "engine_available" in data
|
||||
|
||||
|
||||
def test_invalid_cli_export_returns_nonzero(tmp_path):
|
||||
assert main(["--export",str(tmp_path / "missing.prj"),"--output",str(tmp_path / "pdf")]) != 0
|
||||
|
||||
|
||||
def test_report_never_overwrites_project_even_for_self_check(project_factory):
|
||||
project=project_factory()
|
||||
before=project.read_bytes()
|
||||
assert main(["--self-check","--report",str(project)]) == 2
|
||||
assert project.read_bytes()==before
|
||||
|
||||
|
||||
def test_report_inside_source_is_rejected_before_export(project_factory,tmp_path,monkeypatch):
|
||||
from mentor_pdf_export import cli
|
||||
from mentor_pdf_export.exporter import Exporter
|
||||
from pypdf import PdfWriter
|
||||
project=project_factory()
|
||||
protected=project.parent/"settings.json";protected.write_text("original")
|
||||
engine=tmp_path/"sch2pdf.exe";engine.write_bytes(b"fake")
|
||||
def runner(args,*rest):
|
||||
writer=PdfWriter();writer.add_blank_page(width=500,height=400)
|
||||
with Path(args[args.index("-a")+1]).open("wb") as out:writer.write(out)
|
||||
return 0
|
||||
monkeypatch.setattr(cli,"Exporter",lambda engine,runs:Exporter(engine,runs,runner=runner))
|
||||
rc=main(["--export",str(project),"--engine",str(engine),"--output",str(tmp_path/"pdfs"),"--runs-root",str(tmp_path/"runs"),"--report",str(protected)])
|
||||
assert rc==2
|
||||
assert protected.read_text()=="original"
|
||||
assert not (tmp_path/"pdfs").exists()
|
||||
|
||||
|
||||
def test_queue_destinations_protect_every_source_before_first_export(project_factory,tmp_path,monkeypatch):
|
||||
from mentor_pdf_export import cli
|
||||
from mentor_pdf_export.exporter import Exporter
|
||||
from mentor_pdf_export.workspace import fingerprint
|
||||
from pypdf import PdfWriter
|
||||
a=project_factory("a");b=project_factory("b")
|
||||
engine=tmp_path/"sch2pdf.exe";engine.write_bytes(b"fake")
|
||||
before=fingerprint(b.parent)
|
||||
def runner(args,*rest):
|
||||
writer=PdfWriter();writer.add_blank_page(width=500,height=400)
|
||||
with Path(args[args.index("-a")+1]).open("wb") as out:writer.write(out)
|
||||
return 0
|
||||
monkeypatch.setattr(cli,"Exporter",lambda engine,runs:Exporter(engine,runs,runner=runner))
|
||||
rc=main(["--export",str(a),str(b),"--engine",str(engine),"--output",str(b.parent/"database"),"--runs-root",str(tmp_path/"runs")])
|
||||
assert rc==2
|
||||
assert fingerprint(b.parent)==before
|
||||
assert not (tmp_path/"runs").exists()
|
||||
|
||||
|
||||
def test_self_check_cannot_overwrite_unowned_json(tmp_path):
|
||||
report=tmp_path/"critical.json";report.write_text('{"user_setting":123}')
|
||||
before=report.read_bytes()
|
||||
assert main(["--self-check","--report",str(report)]) == 2
|
||||
assert report.read_bytes()==before
|
||||
|
||||
|
||||
def test_self_check_can_refresh_its_own_report(tmp_path):
|
||||
report=tmp_path/"self-check.json"
|
||||
assert main(["--self-check","--report",str(report)]) == 0
|
||||
assert main(["--self-check","--report",str(report)]) == 0
|
||||
@@ -0,0 +1,325 @@
|
||||
import sys
|
||||
import threading
|
||||
from pathlib import Path
|
||||
import pytest
|
||||
from mentor_pdf_export.engine import run_engine, discover_engine
|
||||
|
||||
|
||||
def test_capture_exit_and_logs(tmp_path):
|
||||
rc = run_engine([sys.executable, "-c", "import sys; print('hello'); print('bad',file=sys.stderr); sys.exit(3)"], tmp_path, tmp_path / "log", threading.Event(), 10)
|
||||
assert rc == 3
|
||||
assert b"hello" in (tmp_path / "log/stdout.log").read_bytes()
|
||||
assert b"bad" in (tmp_path / "log/stderr.log").read_bytes()
|
||||
|
||||
|
||||
def test_engine_timeout(tmp_path):
|
||||
with pytest.raises(TimeoutError):
|
||||
run_engine([sys.executable, "-c", "import time; time.sleep(20)"], tmp_path, tmp_path / "logs", threading.Event(), .3)
|
||||
|
||||
|
||||
def test_pre_cancel_does_not_launch(tmp_path):
|
||||
cancel = threading.Event(); cancel.set()
|
||||
with pytest.raises(InterruptedError):
|
||||
run_engine(["must-not-run.exe"], tmp_path, tmp_path / "logs", cancel, 10)
|
||||
|
||||
|
||||
def test_cancel_running_process(tmp_path):
|
||||
cancel = threading.Event()
|
||||
timer = threading.Timer(.3, cancel.set); timer.start()
|
||||
try:
|
||||
with pytest.raises(InterruptedError):
|
||||
run_engine([sys.executable, "-c", "import time; time.sleep(20)"], tmp_path, tmp_path / "logs", cancel, 10)
|
||||
finally:
|
||||
timer.cancel()
|
||||
|
||||
|
||||
def test_explicit_invalid_engine_never_falls_back(tmp_path):
|
||||
with pytest.raises(FileNotFoundError):
|
||||
discover_engine(tmp_path / "missing.exe")
|
||||
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def owned_process_handles():
|
||||
"""Retain handles, not recyclable PIDs; clean even assertion failures."""
|
||||
import os
|
||||
if os.name != "nt":
|
||||
pytest.skip("Windows Job Object test")
|
||||
import win32api
|
||||
import win32con
|
||||
import win32event
|
||||
handles = []
|
||||
|
||||
def capture(pid):
|
||||
handle = win32api.OpenProcess(
|
||||
win32con.SYNCHRONIZE | win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_TERMINATE,
|
||||
False, pid,
|
||||
)
|
||||
handles.append(handle)
|
||||
return handle
|
||||
|
||||
yield capture
|
||||
for handle in reversed(handles):
|
||||
try:
|
||||
if win32event.WaitForSingleObject(handle, 0) == win32event.WAIT_TIMEOUT:
|
||||
win32api.TerminateProcess(handle, 1)
|
||||
assert win32event.WaitForSingleObject(handle, 5000) == win32event.WAIT_OBJECT_0
|
||||
finally:
|
||||
handle.Close()
|
||||
|
||||
|
||||
def child_tree_command(pid_file):
|
||||
child = "import time; time.sleep(30)"
|
||||
code = (
|
||||
"import subprocess,time,pathlib; "
|
||||
f"p=subprocess.Popen([{sys.executable!r},'-B','-c',{child!r}],"
|
||||
"stdin=subprocess.DEVNULL,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL); "
|
||||
f"pathlib.Path({str(pid_file)!r}).write_text(str(p.pid)); time.sleep(30)"
|
||||
)
|
||||
return [sys.executable, "-B", "-c", code]
|
||||
|
||||
|
||||
def capture_child(pid_file, capture):
|
||||
import time
|
||||
deadline = time.monotonic() + 5
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
return capture(int(pid_file.read_text()))
|
||||
except (FileNotFoundError, ValueError):
|
||||
time.sleep(.01)
|
||||
pytest.fail("Synthetic parent did not publish its child PID")
|
||||
|
||||
|
||||
def test_timeout_terminates_owned_child_tree(tmp_path, monkeypatch, owned_process_handles):
|
||||
import win32event
|
||||
from mentor_pdf_export import engine
|
||||
original = engine._create_job
|
||||
child_handles = []
|
||||
pid_file = tmp_path / "child.pid"
|
||||
|
||||
def assign(process):
|
||||
owned_process_handles(process.pid)
|
||||
return original(process)
|
||||
|
||||
def started(message):
|
||||
if "PID=" in message:
|
||||
child_handles.append(capture_child(pid_file, owned_process_handles))
|
||||
|
||||
monkeypatch.setattr(engine, "_create_job", assign)
|
||||
with pytest.raises(TimeoutError):
|
||||
run_engine(child_tree_command(pid_file), tmp_path, tmp_path / "logs", threading.Event(), 1.2, started)
|
||||
assert len(child_handles) == 1
|
||||
assert win32event.WaitForSingleObject(child_handles[0], 5000) == win32event.WAIT_OBJECT_0
|
||||
|
||||
|
||||
@pytest.mark.parametrize("stop", ["timeout", "cancel"])
|
||||
def test_delayed_job_binding_cannot_allow_early_child_escape(tmp_path, monkeypatch, owned_process_handles, stop):
|
||||
import time
|
||||
import win32event
|
||||
from mentor_pdf_export import engine
|
||||
original = engine._create_job
|
||||
pid_file = tmp_path / "early-child.pid"
|
||||
ran_before_binding = []
|
||||
child_handles = []
|
||||
cancel = threading.Event()
|
||||
|
||||
def delayed_assign(process):
|
||||
owned_process_handles(process.pid)
|
||||
# Old launch is running: wait for its early child. Fixed launch must
|
||||
# remain suspended for the entire delay, without executing user code.
|
||||
deadline = time.monotonic() + .8
|
||||
while not pid_file.exists() and time.monotonic() < deadline:
|
||||
time.sleep(.01)
|
||||
ran_before_binding.append(pid_file.exists())
|
||||
return original(process)
|
||||
|
||||
def started(message):
|
||||
if "PID=" in message:
|
||||
child_handles.append(capture_child(pid_file, owned_process_handles))
|
||||
if stop == "cancel":
|
||||
cancel.set()
|
||||
|
||||
monkeypatch.setattr(engine, "_create_job", delayed_assign)
|
||||
expected = TimeoutError if stop == "timeout" else InterruptedError
|
||||
with pytest.raises(expected):
|
||||
run_engine(child_tree_command(pid_file), tmp_path, tmp_path / "logs", cancel, 2.2, started)
|
||||
assert len(child_handles) == 1
|
||||
child_stopped = win32event.WaitForSingleObject(child_handles[0], 1000) == win32event.WAIT_OBJECT_0
|
||||
assert (ran_before_binding, child_stopped) == ([False], True), "Engine ran before Job binding or its early child survived stop"
|
||||
|
||||
|
||||
|
||||
def test_windows_native_launch_streams_flags_and_handle_allowlist(tmp_path, monkeypatch, owned_process_handles):
|
||||
import _winapi
|
||||
import win32api
|
||||
import win32con
|
||||
import win32event
|
||||
from mentor_pdf_export import engine
|
||||
original = _winapi.CreateProcess
|
||||
launches = []
|
||||
extra = win32event.CreateEvent(None, True, False, None)
|
||||
win32api.SetHandleInformation(extra, win32con.HANDLE_FLAG_INHERIT, win32con.HANDLE_FLAG_INHERIT)
|
||||
|
||||
def create(*args):
|
||||
flags, info = args[5], args[8]
|
||||
inherited = info.lpAttributeList.get("handle_list", []) if info.lpAttributeList else []
|
||||
launches.append((flags, set(inherited), {info.hStdInput, info.hStdOutput, info.hStdError}))
|
||||
return original(*args)
|
||||
|
||||
monkeypatch.setattr(_winapi, "CreateProcess", create)
|
||||
cwd = tmp_path / "working folder"
|
||||
cwd.mkdir()
|
||||
event_code = f"try:\n win32event.SetEvent({int(extra)})\nexcept pywintypes.error:\n pass"
|
||||
code = (
|
||||
"import os,sys,win32event,pywintypes; "
|
||||
"assert sys.stdin.buffer.read()==b''; "
|
||||
"print(os.getcwd()); print('stdout marker'); print('stderr marker',file=sys.stderr); "
|
||||
f"exec({event_code!r}); "
|
||||
"sys.exit(7)"
|
||||
)
|
||||
try:
|
||||
assert engine.run_engine([sys.executable, "-B", "-c", code], cwd, tmp_path / "logs", threading.Event(), 10) == 7
|
||||
assert len(launches) == 1
|
||||
flags, inherited, standard = launches[0]
|
||||
assert flags & 0x00000004, "CREATE_SUSPENDED is required"
|
||||
assert flags & _winapi.CREATE_NO_WINDOW
|
||||
assert len(inherited) == 3 and inherited == standard
|
||||
assert win32event.WaitForSingleObject(extra, 0) == win32event.WAIT_TIMEOUT
|
||||
assert str(cwd).encode() in (tmp_path / "logs/stdout.log").read_bytes()
|
||||
assert b"stdout marker" in (tmp_path / "logs/stdout.log").read_bytes()
|
||||
assert b"stderr marker" in (tmp_path / "logs/stderr.log").read_bytes()
|
||||
finally:
|
||||
extra.Close()
|
||||
|
||||
|
||||
def process_handle_count():
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
kernel = ctypes.WinDLL("kernel32", use_last_error=True)
|
||||
kernel.GetCurrentProcess.restype = wintypes.HANDLE
|
||||
kernel.GetProcessHandleCount.argtypes = [wintypes.HANDLE, ctypes.POINTER(wintypes.DWORD)]
|
||||
kernel.GetProcessHandleCount.restype = wintypes.BOOL
|
||||
count = wintypes.DWORD()
|
||||
assert kernel.GetProcessHandleCount(kernel.GetCurrentProcess(), ctypes.byref(count))
|
||||
return count.value
|
||||
|
||||
|
||||
@pytest.mark.parametrize("failure", ["create", "job_create", "job_configure", "assign", "resume", "cancel"])
|
||||
def test_windows_startup_failures_do_not_execute_or_leak(tmp_path, monkeypatch, owned_process_handles, failure):
|
||||
import gc
|
||||
import _winapi
|
||||
import msvcrt
|
||||
import win32job
|
||||
import win32process
|
||||
import win32event
|
||||
import mentor_pdf_export.workspace
|
||||
from mentor_pdf_export import engine
|
||||
original_create = _winapi.CreateProcess
|
||||
original_assign = win32job.AssignProcessToJobObject
|
||||
cancel = threading.Event()
|
||||
parents = []
|
||||
marker = tmp_path / "must-not-execute.txt"
|
||||
|
||||
def create(*args):
|
||||
if failure == "create":
|
||||
raise OSError("injected create failure")
|
||||
result = original_create(*args)
|
||||
parents.append(owned_process_handles(result[2]))
|
||||
return result
|
||||
|
||||
def assign(*args):
|
||||
if failure == "assign":
|
||||
raise OSError("injected assignment failure")
|
||||
result = original_assign(*args)
|
||||
if failure == "cancel":
|
||||
cancel.set()
|
||||
return result
|
||||
|
||||
def resume(*args):
|
||||
raise OSError("injected resume failure")
|
||||
|
||||
monkeypatch.setattr(_winapi, "CreateProcess", create)
|
||||
monkeypatch.setattr(win32job, "AssignProcessToJobObject", assign)
|
||||
if failure == "resume":
|
||||
monkeypatch.setattr(win32process, "ResumeThread", resume)
|
||||
if failure in {"job_create", "job_configure"}:
|
||||
def fail_job(*args):
|
||||
raise OSError("injected job setup failure")
|
||||
target = "CreateJobObject" if failure == "job_create" else "SetInformationJobObject"
|
||||
monkeypatch.setattr(win32job, target, fail_job)
|
||||
gc.collect()
|
||||
baseline = process_handle_count()
|
||||
expected = InterruptedError if failure == "cancel" else OSError
|
||||
with pytest.raises(expected):
|
||||
run_engine([sys.executable, "-B", "-c", f"from pathlib import Path; Path({str(marker)!r}).write_text('unsafe')"], tmp_path, tmp_path / "logs", cancel, 10)
|
||||
assert not marker.exists(), "Suspended process must not execute on setup failure/cancellation"
|
||||
for handle in parents:
|
||||
assert win32event.WaitForSingleObject(handle, 5000) == win32event.WAIT_OBJECT_0
|
||||
gc.collect()
|
||||
assert process_handle_count() == baseline + len(parents), "Leaked process/thread/job/stdio handle"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("fail_at", [1, 2, 3])
|
||||
def test_windows_partial_stdio_setup_closes_handles(tmp_path, monkeypatch, owned_process_handles, fail_at):
|
||||
import _winapi
|
||||
import msvcrt
|
||||
import mentor_pdf_export.workspace
|
||||
from mentor_pdf_export import engine
|
||||
original = _winapi.DuplicateHandle
|
||||
calls = []
|
||||
|
||||
def duplicate(*args):
|
||||
calls.append(args)
|
||||
if len(calls) == fail_at:
|
||||
raise OSError("injected stdio duplication failure")
|
||||
return original(*args)
|
||||
|
||||
def must_not_launch(*args):
|
||||
pytest.fail("Incomplete stdio must not create a process")
|
||||
|
||||
monkeypatch.setattr(_winapi, "DuplicateHandle", duplicate)
|
||||
monkeypatch.setattr(_winapi, "CreateProcess", must_not_launch)
|
||||
baseline = process_handle_count()
|
||||
with pytest.raises(OSError, match="stdio duplication"):
|
||||
engine.run_engine([sys.executable, "-B", "-c", "pass"], tmp_path, tmp_path / "logs", threading.Event(), 10)
|
||||
assert process_handle_count() == baseline
|
||||
|
||||
|
||||
def test_windows_exit_code_259_is_not_mistaken_for_running(tmp_path, owned_process_handles):
|
||||
assert run_engine([sys.executable, "-B", "-c", "import sys; sys.exit(259)"], tmp_path, tmp_path / "logs", threading.Event(), 10) == 259
|
||||
|
||||
|
||||
def test_callback_error_stops_owned_tree_but_not_other_process(tmp_path, monkeypatch, owned_process_handles):
|
||||
import subprocess
|
||||
import win32event
|
||||
from mentor_pdf_export import engine
|
||||
original = engine._create_job
|
||||
pid_file = tmp_path / "callback-child.pid"
|
||||
children = []
|
||||
other = subprocess.Popen(
|
||||
[sys.executable, "-B", "-c", "import time; time.sleep(30)"],
|
||||
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
||||
creationflags=subprocess.CREATE_NO_WINDOW,
|
||||
)
|
||||
try:
|
||||
other_handle = owned_process_handles(other.pid)
|
||||
|
||||
def assign(process):
|
||||
owned_process_handles(process.pid)
|
||||
return original(process)
|
||||
|
||||
def started(message):
|
||||
if "PID=" in message:
|
||||
children.append(capture_child(pid_file, owned_process_handles))
|
||||
raise RuntimeError("injected event callback failure")
|
||||
|
||||
monkeypatch.setattr(engine, "_create_job", assign)
|
||||
with pytest.raises(RuntimeError, match="event callback failure"):
|
||||
run_engine(child_tree_command(pid_file), tmp_path, tmp_path / "logs", threading.Event(), 10, started)
|
||||
assert len(children) == 1
|
||||
assert win32event.WaitForSingleObject(children[0], 5000) == win32event.WAIT_OBJECT_0
|
||||
assert win32event.WaitForSingleObject(other_handle, 0) == win32event.WAIT_TIMEOUT
|
||||
finally:
|
||||
if other.poll() is None:
|
||||
other.kill()
|
||||
other.wait(timeout=10)
|
||||
@@ -0,0 +1,164 @@
|
||||
from pathlib import Path
|
||||
import threading
|
||||
import pytest
|
||||
from pypdf import PdfWriter
|
||||
from mentor_pdf_export.models import ExportOptions
|
||||
from mentor_pdf_export.scanner import read_project
|
||||
from mentor_pdf_export.validation import validate_pdf
|
||||
from mentor_pdf_export.exporter import Exporter, output_path
|
||||
|
||||
|
||||
def pdf(path):
|
||||
writer = PdfWriter()
|
||||
writer.add_blank_page(width=500, height=400)
|
||||
with Path(path).open("wb") as f:
|
||||
writer.write(f)
|
||||
|
||||
|
||||
def fake_runner(args, cwd, log_dir, cancel, timeout, on_event=None):
|
||||
pdf(args[args.index("-a") + 1])
|
||||
return 0
|
||||
|
||||
|
||||
def test_validate_pdf(tmp_path):
|
||||
file = tmp_path / "a.pdf"; pdf(file)
|
||||
assert validate_pdf(file).pages == 1
|
||||
file.write_bytes(b"not a pdf")
|
||||
with pytest.raises(ValueError):
|
||||
validate_pdf(file)
|
||||
|
||||
|
||||
def test_invalid_zero_page_pdf(tmp_path):
|
||||
file = tmp_path / "empty.pdf"
|
||||
with file.open("wb") as f:
|
||||
PdfWriter().write(f)
|
||||
with pytest.raises(ValueError, match="页"):
|
||||
validate_pdf(file)
|
||||
|
||||
|
||||
def test_success_and_json_report(project_factory, tmp_path):
|
||||
info = read_project(project_factory())
|
||||
exporter = Exporter(Path("fake.exe"), tmp_path / "runs", runner=fake_runner)
|
||||
result = exporter.export(info, tmp_path / "pdfs", ExportOptions(), threading.Event())
|
||||
assert result.status == "success" and result.pages == 1
|
||||
assert Path(result.output).is_file()
|
||||
assert (Path(result.run_dir) / "result.json").is_file()
|
||||
|
||||
|
||||
def test_old_output_preserved_on_failed_export(project_factory, tmp_path):
|
||||
info = read_project(project_factory())
|
||||
output = output_path(info, tmp_path / "pdfs"); output.parent.mkdir(); output.write_bytes(b"previous")
|
||||
def failure(*args):
|
||||
return 2
|
||||
result = Exporter(Path("fake.exe"), tmp_path / "runs", runner=failure).export(info, output.parent, ExportOptions(overwrite=True), threading.Event())
|
||||
assert result.status == "failed"
|
||||
assert output.read_bytes() == b"previous"
|
||||
|
||||
|
||||
def test_existing_output_needs_explicit_overwrite(project_factory, tmp_path):
|
||||
info = read_project(project_factory())
|
||||
output = output_path(info, tmp_path / "pdfs"); output.parent.mkdir(); output.write_bytes(b"previous")
|
||||
result = Exporter(Path("fake.exe"), tmp_path / "runs", runner=fake_runner).export(info, output.parent, ExportOptions(), threading.Event())
|
||||
assert result.status == "skipped"
|
||||
assert output.read_bytes() == b"previous"
|
||||
|
||||
|
||||
def test_failure_not_published_even_when_file_exists(project_factory, tmp_path):
|
||||
info = read_project(project_factory())
|
||||
def bad(args, *rest):
|
||||
pdf(args[args.index("-a") + 1]); return 9
|
||||
result = Exporter(Path("fake.exe"), tmp_path / "runs", runner=bad).export(info, tmp_path / "pdfs", ExportOptions(), threading.Event())
|
||||
assert result.status == "failed"
|
||||
assert not output_path(info, tmp_path / "pdfs").exists()
|
||||
|
||||
|
||||
def test_source_change_never_claims_success(project_factory, tmp_path):
|
||||
project = project_factory(); info = read_project(project)
|
||||
def changing(args, *rest):
|
||||
pdf(args[args.index("-a") + 1])
|
||||
(project.parent / "database/icdb.dat").write_bytes(b"edited elsewhere")
|
||||
return 0
|
||||
result = Exporter(Path("fake.exe"), tmp_path / "runs", runner=changing).export(info, tmp_path / "pdfs", ExportOptions(), threading.Event())
|
||||
assert result.status == "uncertain"
|
||||
assert not output_path(info, tmp_path / "pdfs").exists()
|
||||
|
||||
|
||||
def test_duplicate_project_names_have_distinct_outputs(project_factory, tmp_path):
|
||||
a = read_project(project_factory("a", "same")); b = read_project(project_factory("b", "same"))
|
||||
assert output_path(a, tmp_path / "out") != output_path(b, tmp_path / "out")
|
||||
|
||||
|
||||
def test_cannot_output_inside_source(project_factory, tmp_path):
|
||||
info = read_project(project_factory())
|
||||
result = Exporter(Path("fake.exe"), tmp_path / "runs", runner=fake_runner).export(info, info.path.parent / "pdf", ExportOptions(), threading.Event())
|
||||
assert result.status == "failed"
|
||||
|
||||
|
||||
def test_pre_cancel_returns_cancelled(project_factory, tmp_path):
|
||||
info = read_project(project_factory())
|
||||
cancel = threading.Event(); cancel.set()
|
||||
result = Exporter(Path("fake.exe"), tmp_path / "runs", runner=fake_runner).export(info, tmp_path / "pdfs", ExportOptions(), cancel)
|
||||
assert result.status == "cancelled"
|
||||
|
||||
|
||||
def test_final_source_check_is_before_publish(project_factory,tmp_path,monkeypatch):
|
||||
import mentor_pdf_export.exporter as module
|
||||
info=read_project(project_factory())
|
||||
output=output_path(info,tmp_path/"pdfs");output.parent.mkdir();output.write_bytes(b"previous")
|
||||
original=module.fingerprint
|
||||
count=0
|
||||
def checked(*args):
|
||||
nonlocal count
|
||||
count+=1
|
||||
assert output.read_bytes()==b"previous", "final source validation happened after publication"
|
||||
return original(*args)
|
||||
monkeypatch.setattr(module,"fingerprint",checked)
|
||||
result=Exporter(Path("fake.exe"),tmp_path/"runs",runner=fake_runner).export(info,output.parent,ExportOptions(overwrite=True),threading.Event())
|
||||
assert result.status=="success"
|
||||
|
||||
|
||||
def test_result_record_failure_never_overwrites_old_pdf(project_factory,tmp_path,monkeypatch):
|
||||
import mentor_pdf_export.exporter as module
|
||||
info=read_project(project_factory())
|
||||
output=output_path(info,tmp_path/"pdfs");output.parent.mkdir();output.write_bytes(b"previous")
|
||||
original=module.write_json
|
||||
def fail_result(path,data):
|
||||
if Path(path).name=="result.json":raise OSError("disk full")
|
||||
return original(path,data)
|
||||
monkeypatch.setattr(module,"write_json",fail_result)
|
||||
result=Exporter(Path("fake.exe"),tmp_path/"runs",runner=fake_runner).export(info,output.parent,ExportOptions(overwrite=True),threading.Event())
|
||||
assert result.status in {"failed","uncertain"}
|
||||
assert output.read_bytes()==b"previous"
|
||||
|
||||
|
||||
def test_post_publish_record_failure_returns_traceable_uncertain_result(project_factory,tmp_path,monkeypatch):
|
||||
import mentor_pdf_export.exporter as module
|
||||
info=read_project(project_factory())
|
||||
original=module.write_json
|
||||
count=0
|
||||
def fail_final(path,data):
|
||||
nonlocal count
|
||||
if Path(path).name=="result.json":
|
||||
count+=1
|
||||
if count>=2:raise OSError("disk full after publish")
|
||||
return original(path,data)
|
||||
monkeypatch.setattr(module,"write_json",fail_final)
|
||||
result=Exporter(Path("fake.exe"),tmp_path/"runs",runner=fake_runner).export(info,tmp_path/"pdfs",ExportOptions(),threading.Event())
|
||||
assert result.status=="uncertain"
|
||||
assert Path(result.output).is_file()
|
||||
assert (Path(result.run_dir)/"result.json").is_file()
|
||||
|
||||
|
||||
def test_staging_stat_failure_still_returns_and_records_result(project_factory,tmp_path,monkeypatch):
|
||||
info=read_project(project_factory())
|
||||
original=Path.exists
|
||||
def denied(path):
|
||||
if path.name.endswith(".partial.pdf"):raise OSError("staging stat denied")
|
||||
return original(path)
|
||||
monkeypatch.setattr(Path,"exists",denied)
|
||||
def failure(args,*rest):
|
||||
pdf(args[args.index("-a")+1]);return 2
|
||||
result=Exporter(Path("fake.exe"),tmp_path/"runs",runner=failure).export(info,tmp_path/"pdfs",ExportOptions(),threading.Event())
|
||||
assert result.status=="failed"
|
||||
assert (Path(result.run_dir)/"result.json").is_file()
|
||||
assert "暂存" in result.message
|
||||
@@ -0,0 +1,16 @@
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def test_bundle_excludes_foreign_icu_but_keeps_qt_and_crt():
|
||||
file=Path(__file__).parents[1]/"packaging/bundle_policy.py"
|
||||
spec=importlib.util.spec_from_file_location("bundle_policy",file)
|
||||
module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module)
|
||||
entries=[
|
||||
("icuuc.dll",r"C:\tools\poppler\icuuc.dll","BINARY"),
|
||||
("icudt78.dll",r"C:\tools\poppler\icudt78.dll","BINARY"),
|
||||
(r"PySide6\Qt6Core.dll",r"C:\python\PySide6\Qt6Core.dll","BINARY"),
|
||||
("VCRUNTIME140.dll",r"C:\python\VCRUNTIME140.dll","BINARY"),
|
||||
]
|
||||
filtered=module.filter_binaries(entries)
|
||||
assert filtered == entries[2:]
|
||||
@@ -0,0 +1,33 @@
|
||||
from pathlib import Path
|
||||
from mentor_pdf_export.models import ExportOptions
|
||||
from mentor_pdf_export.profiles import write_profile, build_command
|
||||
|
||||
def test_profile_clears_url_and_preserves_fonts(tmp_path):
|
||||
ini = tmp_path / "dxpdf.ini"
|
||||
ini.write_text("Color 1\nUrlProperties Value\nStartAcrobat 1\nFont_1 Courier-Bold\n")
|
||||
write_profile(ini, ExportOptions())
|
||||
lines = ini.read_text().splitlines()
|
||||
assert "Color 4" in lines
|
||||
assert "UrlProperties " in lines
|
||||
assert "StartAcrobat 0" in lines
|
||||
assert "Font_1 Courier-Bold" in lines
|
||||
assert "ChangeIct2Sch 1" in lines
|
||||
assert "VisibleHLs 0" in lines
|
||||
|
||||
def test_command_is_argument_list_not_shell():
|
||||
args = build_command(Path("engine.exe"), Path("工程 x.prj"), Path("x.pdf"), ExportOptions(schematic="ROOT"))
|
||||
assert args[:3] == ["engine.exe", "-project", "工程 x.prj"]
|
||||
assert args[args.index("-c") + 1] == "4"
|
||||
assert args[args.index("-schematic") + 1] == "ROOT"
|
||||
assert "-p" in args and "-e" in args and "-i2s" in args
|
||||
assert "-s" not in args and "-v" not in args and "-i" not in args
|
||||
|
||||
def test_disabled_flags_not_enabled():
|
||||
args = build_command(Path("engine.exe"), Path("a.prj"), Path("a.pdf"), ExportOptions(popup=False, use_exclusion=False, change_ict=False))
|
||||
assert "-p" not in args and "-e" not in args and "-i2s" not in args
|
||||
|
||||
|
||||
def test_stroke_mode_uses_native_verified_attached_switch():
|
||||
args=build_command(Path("engine.exe"),Path("a.prj"),Path("a.pdf"),ExportOptions(stroke_fonts=True))
|
||||
assert "-uAll" in args
|
||||
assert "-u" not in args and "-udx" not in args
|
||||
@@ -0,0 +1,23 @@
|
||||
from mentor_pdf_export.scanner import scan_projects
|
||||
|
||||
def test_scans_children_even_when_root_contains_project(project_factory, tmp_path):
|
||||
root = project_factory(".", "top")
|
||||
child = project_factory("nested", "child")
|
||||
assert {p.path for p in scan_projects(tmp_path)} == {root.resolve(), child.resolve()}
|
||||
|
||||
def test_prunes_pcb_backups_and_output(project_factory, tmp_path):
|
||||
good = project_factory("good")
|
||||
project_factory("good/PCB", "fake")
|
||||
project_factory("ProjectBackup/old", "old")
|
||||
project_factory("output", "export_copy")
|
||||
project_factory("layout", "layout", schematic=False)
|
||||
assert [p.path for p in scan_projects(tmp_path)] == [good.resolve()]
|
||||
|
||||
def test_explicit_excluded_root(project_factory, tmp_path):
|
||||
good = project_factory("good")
|
||||
project_factory("other")
|
||||
assert [p.path for p in scan_projects(tmp_path, excluded_roots=(tmp_path / "other",))] == [good.resolve()]
|
||||
|
||||
def test_reads_actual_root_block(project_factory, tmp_path):
|
||||
project_factory()
|
||||
assert scan_projects(tmp_path)[0].root_blocks == ("ROOT",)
|
||||
@@ -0,0 +1,103 @@
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from pypdf import PdfWriter
|
||||
from PySide6.QtCore import Qt
|
||||
from mentor_pdf_export.ui import MainWindow
|
||||
from mentor_pdf_export.exporter import Exporter
|
||||
|
||||
|
||||
def runner(args, cwd, log_dir, cancel, timeout, on_event=None):
|
||||
writer = PdfWriter(); writer.add_blank_page(width=500,height=400)
|
||||
with Path(args[args.index("-a")+1]).open("wb") as f:
|
||||
writer.write(f)
|
||||
return 0
|
||||
|
||||
|
||||
def make_window(qtbot, tmp_path, factory=None):
|
||||
window = MainWindow(root=str(tmp_path), output=str(tmp_path / "pdfs"), runs_root=tmp_path.parent / (tmp_path.name + "-runs"), exporter_factory=factory)
|
||||
qtbot.addWidget(window); window.show()
|
||||
return window
|
||||
|
||||
|
||||
def test_scan_and_toggle_does_not_reset_table(qtbot, project_factory, tmp_path):
|
||||
project_factory()
|
||||
window = make_window(qtbot,tmp_path)
|
||||
qtbot.mouseClick(window.scan_button, Qt.LeftButton)
|
||||
qtbot.waitUntil(lambda: window.table.rowCount() == 1, timeout=10000)
|
||||
qtbot.waitUntil(lambda: not window.busy)
|
||||
item = window.table.item(0,0)
|
||||
assert item.checkState() == Qt.Checked
|
||||
item.setCheckState(Qt.Unchecked)
|
||||
assert window.table.item(0,0) is item
|
||||
assert window.selected_count() == 0
|
||||
window.select_all()
|
||||
assert window.selected_count() == 1
|
||||
|
||||
|
||||
def test_export_worker_result_and_buttons(qtbot, project_factory, tmp_path):
|
||||
project_factory()
|
||||
def factory(engine, runs):
|
||||
return Exporter(engine,runs,runner=runner)
|
||||
window = make_window(qtbot,tmp_path,factory)
|
||||
engine=tmp_path/"sch2pdf.exe";engine.write_bytes(b"fake")
|
||||
window.engine_edit.setText(str(engine))
|
||||
window.scan_projects()
|
||||
qtbot.waitUntil(lambda: window.table.rowCount()==1 and not window.busy,timeout=10000)
|
||||
window.start_export()
|
||||
assert window.busy
|
||||
assert not window.start_button.isEnabled()
|
||||
assert not window.options_group.isEnabled()
|
||||
qtbot.waitUntil(lambda: not window.busy,timeout=10000)
|
||||
assert window.table.item(0,3).text()=="成功"
|
||||
assert window.start_button.isEnabled()
|
||||
assert not window.stop_button.isEnabled()
|
||||
assert window.progress.value()==1
|
||||
assert "1 页" in window.table.item(0,4).text()
|
||||
|
||||
|
||||
def test_cancel_signal_is_requested(qtbot, project_factory, tmp_path):
|
||||
project_factory()
|
||||
started=threading.Event()
|
||||
def waiting(args,cwd,log_dir,cancel,timeout,on_event=None):
|
||||
started.set()
|
||||
assert cancel.wait(5)
|
||||
raise InterruptedError("任务已停止")
|
||||
window = make_window(qtbot,tmp_path,lambda engine,runs:Exporter(engine,runs,runner=waiting))
|
||||
engine=tmp_path/"sch2pdf.exe";engine.write_bytes(b"fake")
|
||||
window.engine_edit.setText(str(engine))
|
||||
window.scan_projects()
|
||||
qtbot.waitUntil(lambda: window.table.rowCount()==1 and not window.busy,timeout=10000)
|
||||
window.start_export()
|
||||
qtbot.waitUntil(started.is_set,timeout=10000)
|
||||
window.stop_export()
|
||||
qtbot.waitUntil(lambda:not window.busy,timeout=10000)
|
||||
assert window.table.item(0,3).text()=="已停止"
|
||||
|
||||
|
||||
def test_failed_only_selection(qtbot, project_factory, tmp_path):
|
||||
project_factory("one");project_factory("two")
|
||||
window = make_window(qtbot,tmp_path)
|
||||
window.scan_projects()
|
||||
qtbot.waitUntil(lambda:window.table.rowCount()==2 and not window.busy,timeout=10000)
|
||||
window.table.item(0,3).setText("失败")
|
||||
window.table.item(1,3).setText("成功")
|
||||
window.select_failed()
|
||||
assert window.table.item(0,0).checkState()==Qt.Checked
|
||||
assert window.table.item(1,0).checkState()==Qt.Unchecked
|
||||
|
||||
|
||||
def test_ui_preflights_all_source_paths_before_queue(qtbot,project_factory,tmp_path):
|
||||
project_factory("a");b=project_factory("b")
|
||||
window=make_window(qtbot,tmp_path,lambda engine,runs:Exporter(engine,runs,runner=runner))
|
||||
engine=tmp_path/"sch2pdf.exe";engine.write_bytes(b"fake")
|
||||
window.engine_edit.setText(str(engine));window.scan_projects()
|
||||
qtbot.waitUntil(lambda:window.table.rowCount()==2 and not window.busy,timeout=10000)
|
||||
window.output_edit.setText(str(b.parent/"database"))
|
||||
window.start_export()
|
||||
# A must not start and write into B while the second source is unprotected.
|
||||
unexpectedly_started=window.busy
|
||||
if window.busy:
|
||||
window.stop_export()
|
||||
qtbot.waitUntil(lambda:not window.busy,timeout=10000)
|
||||
assert not unexpectedly_started
|
||||
assert window.worker is None
|
||||
@@ -0,0 +1,42 @@
|
||||
from pathlib import Path
|
||||
from pypdf import PdfWriter
|
||||
from mentor_pdf_export.models import ExportOptions
|
||||
from mentor_pdf_export.scanner import read_project
|
||||
from mentor_pdf_export.exporter import Exporter
|
||||
from mentor_pdf_export.workers import BatchWorker
|
||||
|
||||
|
||||
def test_batch_pre_record_failure_stops_before_engine(qapp,project_factory,tmp_path,monkeypatch):
|
||||
from mentor_pdf_export import workers
|
||||
called=[]
|
||||
def runner(*args):called.append(True);return 0
|
||||
def full(*args):raise OSError("disk full")
|
||||
monkeypatch.setattr(workers,"write_json",full)
|
||||
info=read_project(project_factory())
|
||||
worker=BatchWorker([(0,info)],tmp_path/"pdfs",ExportOptions(),Exporter(Path("fake.exe"),tmp_path/"runs",runner=runner))
|
||||
worker.run()
|
||||
assert not called
|
||||
assert not worker.results
|
||||
|
||||
|
||||
def test_late_batch_record_failure_keeps_result_and_pre_record(qapp,project_factory,tmp_path,monkeypatch):
|
||||
from mentor_pdf_export import workers
|
||||
original=workers.write_json
|
||||
count=0
|
||||
def fail_later(path,data):
|
||||
nonlocal count
|
||||
count+=1
|
||||
if count>1:raise OSError("disk full later")
|
||||
original(path,data)
|
||||
monkeypatch.setattr(workers,"write_json",fail_later)
|
||||
def runner(args,*rest):
|
||||
writer=PdfWriter();writer.add_blank_page(width=500,height=400)
|
||||
with Path(args[args.index("-a")+1]).open("wb") as out:writer.write(out)
|
||||
return 0
|
||||
info=read_project(project_factory())
|
||||
worker=BatchWorker([(0,info)],tmp_path/"pdfs",ExportOptions(),Exporter(Path("fake.exe"),tmp_path/"runs",runner=runner))
|
||||
texts=[];worker.completed.connect(texts.append)
|
||||
worker.run()
|
||||
assert len(worker.results)==1 and worker.results[0].status=="success"
|
||||
assert Path(worker.summary_path).exists()
|
||||
assert "成功 1" in texts[-1] and "记录" in texts[-1]
|
||||
@@ -0,0 +1,52 @@
|
||||
import pytest
|
||||
from mentor_pdf_export.models import ExportOptions
|
||||
from mentor_pdf_export.workspace import prepare_workspace, fingerprint
|
||||
|
||||
def test_copy_changes_profile_not_original(project_factory, tmp_path):
|
||||
source = project_factory()
|
||||
(source.parent / "dxpdf.ini").write_text("Color 1\nUrlProperties Value\n")
|
||||
(source.parent / "PCB").mkdir()
|
||||
(source.parent / "PCB" / "private.bin").write_bytes(b"pcb")
|
||||
before = fingerprint(source.parent)
|
||||
copied = prepare_workspace(source, tmp_path / "runs" / "one", ExportOptions())
|
||||
assert copied.is_file()
|
||||
assert not (copied.parent / "PCB").exists()
|
||||
assert "Color 4" in (copied.parent / "dxpdf.ini").read_text()
|
||||
assert before == fingerprint(source.parent)
|
||||
|
||||
def test_rejects_database_outside_project(project_factory, tmp_path):
|
||||
project = project_factory()
|
||||
project.write_text(project.read_text().replace('.\\database', '..\\other'))
|
||||
with pytest.raises(ValueError, match="数据库|database"):
|
||||
prepare_workspace(project, tmp_path / "run", ExportOptions())
|
||||
|
||||
def test_rejects_workspace_inside_source(project_factory):
|
||||
source = project_factory()
|
||||
with pytest.raises(ValueError, match="副本|workspace"):
|
||||
prepare_workspace(source, source.parent / "run", ExportOptions())
|
||||
|
||||
|
||||
def test_library_override_only_changes_copy(project_factory, tmp_path):
|
||||
source = project_factory()
|
||||
source.write_text(source.read_text() + 'KEY CentralLibrary "\\\\oldserver\\lib\\mentor.lmc"\n')
|
||||
library = tmp_path / "library.lmc";library.write_bytes(b"sample library")
|
||||
before = fingerprint(source.parent)
|
||||
copied = prepare_workspace(source, tmp_path / "run", ExportOptions(library_override=str(library)))
|
||||
assert str(library).replace("\\", "/") in copied.read_text().replace("\\", "/")
|
||||
assert fingerprint(source.parent) == before
|
||||
assert library.read_bytes() == b"sample library"
|
||||
|
||||
|
||||
def test_missing_library_override_rejected(project_factory, tmp_path):
|
||||
source = project_factory()
|
||||
with pytest.raises(ValueError, match="中心库"):
|
||||
prepare_workspace(source, tmp_path / "run", ExportOptions(library_override=str(tmp_path / "missing.lmc")))
|
||||
|
||||
|
||||
def test_library_override_preserves_next_project_line(project_factory, tmp_path):
|
||||
source = project_factory()
|
||||
source.write_text(source.read_text() + 'KEY CentralLibrary "\\\\oldserver\\lib\\mentor.lmc"\nKEY DxD_Version "7.9.4"\n')
|
||||
library=tmp_path/"local.lmc";library.write_bytes(b"lib")
|
||||
copied=prepare_workspace(source,tmp_path/"run",ExportOptions(library_override=str(library)))
|
||||
lines=copied.read_text().splitlines()
|
||||
assert 'KEY DxD_Version "7.9.4"' in lines
|
||||
Reference in new issue
Block a user