116 lines
5.0 KiB
Python
116 lines
5.0 KiB
Python
"""Verify the packaged native listener against the restored PDF test copy."""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
|
|
from pypdf import PdfReader
|
|
|
|
|
|
def wait_for(predicate, seconds=60):
|
|
deadline = time.monotonic() + seconds
|
|
while time.monotonic() < deadline:
|
|
result = predicate()
|
|
if result:
|
|
return result
|
|
time.sleep(0.25)
|
|
raise TimeoutError("Packaged listener did not produce the expected evidence")
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument("executable", type=Path)
|
|
parser.add_argument("--name", default="pdf-frozen")
|
|
options = parser.parse_args()
|
|
base = Path(os.environ["LOCALAPPDATA"]) / "DxProductivity/acceptance/native-20261010"
|
|
settings = base / f"{options.name}-settings.json"
|
|
if settings.exists():
|
|
raise SystemExit("Frozen acceptance already exists; retain previous evidence")
|
|
data = json.loads((base / "pdf-native-auto.json").read_text(encoding="utf-8"))
|
|
data.update(auto_export=True, output_dir=str(base / f"{options.name}-output"))
|
|
settings.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
environment = os.environ.copy()
|
|
# The portable Python runtime is self-contained; sch2pdf still needs the
|
|
# DLL folders belonging to the installed Mentor engine.
|
|
native_paths = [part for part in os.environ.get("PATH", "").split(";") if "mentor" in part.casefold()]
|
|
environment["PATH"] = ";".join([*native_paths, r"C:\Windows\System32", r"C:\Windows"])
|
|
environment.pop("PYTHONPATH", None)
|
|
environment.pop("PYTHONHOME", None)
|
|
command = [str(options.executable.resolve()), "pdf-export-listen", "--settings", str(settings)]
|
|
process = subprocess.Popen(command, env=environment, cwd=options.executable.parent)
|
|
state = settings.with_name(settings.name + ".listener-state.json")
|
|
log = settings.with_name(settings.name + ".listener.log")
|
|
|
|
def events():
|
|
if not log.exists():
|
|
return []
|
|
return [json.loads(line) for line in log.read_text(encoding="utf-8").splitlines() if line]
|
|
|
|
def listening():
|
|
if process.poll() is not None:
|
|
raise RuntimeError(f"Listener exited {process.returncode}: {events()}")
|
|
if state.exists():
|
|
return json.loads(state.read_text(encoding="utf-8")).get("state") == "listening"
|
|
|
|
def completed(count):
|
|
records = [item for item in events() if item["event"] == "export-completed"]
|
|
if len(records) >= count:
|
|
if records[-1]["returncode"] != 0:
|
|
raise RuntimeError(f"Frozen export failed: {events()}")
|
|
return records
|
|
return False
|
|
|
|
helper = Path(__file__).with_name("run_dx_script.py")
|
|
|
|
def run(script):
|
|
subprocess.run([sys.executable, str(helper), "--project", data["project_path"], str(script)], check=True, timeout=30)
|
|
|
|
changed = False
|
|
try:
|
|
wait_for(listening, 30)
|
|
print(f"FROZEN_LISTENING pid={process.pid}", flush=True)
|
|
change = base / "pdf-frozen-change-value.vbs"
|
|
restore = base / "pdf-frozen-restore-value.vbs"
|
|
for source, target in (("pdf-native-change-value.vbs", change), ("pdf-native-restore-value.vbs", restore)):
|
|
text = (base / source).read_text(encoding="ascii")
|
|
text = text.replace("pdf-native-old-value.txt", "pdf-frozen-old-value.txt").replace("_PDF_NATIVE_ON", "_PDF_FROZEN_ON")
|
|
target.write_text(text, encoding="ascii")
|
|
run(change)
|
|
changed = True
|
|
wait_for(lambda: completed(1))
|
|
pdfs = tuple(Path(data["output_dir"]).glob("*.pdf"))
|
|
assert len(pdfs) == 1, pdfs
|
|
pdf = PdfReader(pdfs[0])
|
|
assert len(pdf.pages) == 1
|
|
assert "IC/D2128_PDF_FROZEN_ON" in pdf.pages[0].extract_text()
|
|
shutil.copy2(pdfs[0], base / "pdf-frozen-enabled-value.pdf")
|
|
print("FROZEN_PDF_CHANGED_VALUE_CONFIRMED", flush=True)
|
|
run(restore)
|
|
changed = False
|
|
wait_for(lambda: completed(2))
|
|
assert "_PDF_FROZEN_ON" not in PdfReader(pdfs[0]).pages[0].extract_text()
|
|
result = {"executable": str(options.executable.resolve()), "listener_pid": process.pid,
|
|
"state": "passed", "native_binding": json.loads(state.read_text(encoding="utf-8")),
|
|
"pages": 1, "changed_value_in_pdf": True, "restored_value_confirmed": True,
|
|
"completed": completed(2), "python_on_path": False}
|
|
finally:
|
|
if changed:
|
|
run(restore)
|
|
data["auto_export"] = False
|
|
settings.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
process.wait(timeout=15)
|
|
result["listener_exit_code"] = process.returncode
|
|
assert process.returncode == 0
|
|
(base / f"{options.name}-acceptance.json").write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
print("PASS FROZEN PDF NATIVE ACCEPTANCE", flush=True)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|