Files
yiyezhqiu-refactored/tools/acceptance/packaged_menu.py
T

168 lines
8.1 KiB
Python

"""Exercise generated menu actions on the dedicated native feature copy."""
from __future__ import annotations
import argparse
import json
import os
from pathlib import Path
import subprocess
import sys
import time
from types import SimpleNamespace
import win32gui
import win32process
from pywinauto import Application
import win32com.client
BASE = Path(os.environ["LOCALAPPDATA"]) / "DxProductivity/acceptance/native-20261010"
PROJECT = BASE / "1GPHY_RTL8211F/1GPHY_RTL8211F.prj"
HOST_PID = 81576
def wait_for(predicate, seconds=30):
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
result = predicate()
if result:
return result
time.sleep(0.2)
raise TimeoutError("Menu action did not produce the expected native result")
def owned_dialogs():
result = []
def callback(handle, _):
if win32process.GetWindowThreadProcessId(handle)[1] == HOST_PID and win32gui.GetClassName(handle) == "#32770" and win32gui.IsWindowVisible(handle):
texts = []
win32gui.EnumChildWindows(handle, lambda child, _: texts.append(win32gui.GetWindowText(child)), None)
result.append((handle, texts))
win32gui.EnumWindows(callback, None)
return result
def close_completion_dialog(handle):
buttons = []
win32gui.EnumChildWindows(handle, lambda child, _: buttons.append(child) if
win32gui.GetClassName(child) == "Button" and win32gui.GetWindowText(child) in {"确定", "OK"} else None, None)
assert len(buttons) == 1, "Expected one confirmation button on owned completion dialog"
# DxDesigner uses control ID 2 for its localized confirmation button.
win32gui.PostMessage(handle, 0x111, win32gui.GetDlgCtrlID(buttons[0]), buttons[0])
def tools_running():
service = win32com.client.GetObject("winmgmts:")
return [SimpleNamespace(pid=int(p.ProcessId), executable=str(p.ExecutablePath), command_line=str(p.CommandLine))
for p in service.ExecQuery("SELECT ProcessId, ExecutablePath, CommandLine FROM Win32_Process WHERE Name='DxDesignerTools.exe'")]
def main():
parser = argparse.ArgumentParser()
parser.add_argument("executable", type=Path)
parser.add_argument("--features")
options = parser.parse_args()
root = options.executable.resolve().parent
helper = Path(__file__).with_name("run_dx_script.py")
install = Path(os.environ["LOCALAPPDATA"]) / "DxProductivity/startup-refactored/MenuAdd.vbs"
subprocess.run([sys.executable, str(helper), "--project", str(PROJECT), str(install)], timeout=30, check=True)
cases = [(1, "refdes", "自动位号"), (2, "property-change", "属性批改"),
(3, "property-visibility", "属性显示"), (4, "inspection", "设计检查"),
(5, "bom", "BOM 工具"), (6, "pdf-export", "PDF 导出"), (7, "compatibility", ""), (8, "guide", "")]
if options.features:
cases = [case for case in cases if case[1] in options.features.split(",")]
results = []
for index, feature, expected in cases:
script = BASE / f"packaged-menu-{feature}.vbs"
marker = BASE / f"packaged-menu-{feature}.txt"
marker.unlink(missing_ok=True)
script.write_text(f'''
Dim mBar, mItem, mAction, mIndex, mStream
If LCase(Application.GetProjectData().GetProjectFilePath()) <> LCase("{PROJECT}") Then Err.Raise 513, "Acceptance", "Wrong test project"
Set mBar = CommandBars("Sheet Menu Bar")
For mIndex = 1 To mBar.Controls.Count
Set mItem = mBar.Controls.Item(mIndex)
If mItem.Caption = "Dx " & ChrW(&H6548) & ChrW(&H7387) & ChrW(&H5DE5) & ChrW(&H5177) Then
mAction = mItem.Controls.Item({index}).OnAction
Set mStream = CreateObject("Scripting.FileSystemObject").CreateTextFile("{marker}", True, True)
mStream.WriteLine mAction
mStream.Close
Application.ExecuteCommand mAction
Set mStream = CreateObject("Scripting.FileSystemObject").OpenTextFile("{marker}", 8, False, -1)
mStream.WriteLine "DONE"
mStream.Close
Exit For
End If
Next
''', encoding="ascii")
before = {p.pid for p in tools_running()}
if feature == "compatibility":
for handle, texts in owned_dialogs():
if any("compatibility.json" in text for text in texts):
close_completion_dialog(handle)
time.sleep(0.3)
started_at = time.time()
child = subprocess.Popen([sys.executable, str(helper), "--project", str(PROJECT), str(script)])
if expected:
def new_tool():
for p in tools_running():
if p.pid not in before and "--request" in p.command_line and Path(p.executable).resolve() == options.executable.resolve():
return p
tool = wait_for(new_tool)
app = Application(backend="uia").connect(process=tool.pid, timeout=15)
window = app.window(title="一叶知秋_重构版")
window.wait("visible", timeout=15)
texts = [x.window_text() for x in window.descendants(control_type="Text")]
selected = [x.window_text() for x in window.descendants(control_type="ListItem") if x.is_selected()]
assert selected == [expected], (feature, selected)
assert "桥接已连接" in texts and PROJECT.name in texts, texts
results.append({"feature": feature, "pid": tool.pid, "selected_page": selected[0], "bridge": "connected", "project": PROJECT.name, "executable": tool.executable})
window.close()
elif feature == "compatibility":
def close_completion():
probe = BASE.parent.parent / "compatibility.json"
if not probe.exists() or probe.stat().st_mtime < started_at:
return None
try:
payload = json.loads(probe.read_text(encoding="utf-8"))
except (OSError, ValueError):
return None
if "retained_reference" not in payload or not payload.get("yield_method"):
return None
for handle, texts in owned_dialogs():
if any("compatibility.json" in text for text in texts):
close_completion_dialog(handle)
return texts
if any("VBScript" in text or "Microsoft" in text for text in texts):
raise RuntimeError(f"Native compatibility dialog: {texts}")
texts = wait_for(close_completion)
probe = BASE.parent.parent / "compatibility.json"
assert probe.stat().st_mtime >= started_at
data = json.loads(probe.read_text(encoding="utf-8"))
for key in ("portable_root_valid", "full_design_enumeration", "refdes_readable", "uid_readable", "attributes_readable", "sheet_number_readable", "retained_reference"):
assert data[key] is True, (key, data)
assert data["full_design_count"] == 114 and data["position_method"] and data["yield_method"]
results.append({"feature": feature, "probe": data})
else:
guide = root / "docs/DxDesigner_7.9.5_自动位号工具使用说明.docx"
def open_guide():
try:
word = win32com.client.GetActiveObject("Word.Application")
for doc in word.Documents:
if Path(doc.FullName).resolve() == guide.resolve():
return doc
except Exception:
return None
doc = wait_for(open_guide)
results.append({"feature": feature, "document": str(guide), "pages": doc.ComputeStatistics(2)})
doc.Close(SaveChanges=0)
assert child.wait(timeout=15) == 0
assert "DONE" in marker.read_text(encoding="utf-16")
print(f"PASS MENU {feature}", flush=True)
(BASE / "packaged-menu-acceptance.json").write_text(json.dumps(results, ensure_ascii=False, indent=2), encoding="utf-8")
(BASE / "packaged-menu-acceptance.json").write_text(json.dumps(results, ensure_ascii=False, indent=2), encoding="utf-8")
if __name__ == "__main__":
main()