test: accept frozen BOM workflow and add window-only GIF tutorial

This commit is contained in:
阿白叔 committed 2026-10-15 23:35:57 +08:00
1 parent a16914bc72
commit 6b5f79b412
9 files changed
+805 -6

No files matched your search

+358
View File
@@ -0,0 +1,358 @@
"""Operate an extracted candidate through Windows UI, preserving real evidence.
Workbook edits are test fixtures based on the application's exported template.
No application Python modules, simulated workers or invented log events are used.
"""
from __future__ import annotations
import argparse
import ctypes
from ctypes import wintypes
import json
from pathlib import Path
import sqlite3
import time
import traceback
from openpyxl import load_workbook
import win32con
import win32api
import win32gui
from packaged_window_driver import WindowDriver
from private_desktop_observer import PrivateDesktopObserver
def wait(check, *, timeout=900):
deadline, last = time.monotonic() + timeout, None
while time.monotonic() < deadline:
try:
value = check()
except LookupError:
value = None # Qt can replace its accessible children during refresh.
if value:
return value
if int(time.monotonic()) // 30 != last:
last = int(time.monotonic()) // 30
print('Waiting for UI operation; evidence remains on disk.', flush=True)
time.sleep(.3)
raise TimeoutError('Candidate UI operation did not complete')
def database(root, sql):
with sqlite3.connect((root / 'data/task-center.db').as_uri() + '?mode=ro', uri=True) as db:
db.row_factory = sqlite3.Row
return [dict(row) for row in db.execute(sql)]
def verify_identity(root, session):
import hashlib
executable = (root / 'extracted/DxPartReplace/DxPartReplace.exe').resolve(strict=True)
assert Path(session['executable']).resolve(strict=True) == executable
process = win32api.OpenProcess(0x1000, False, session['pid'])
try:
query = ctypes.windll.kernel32.QueryFullProcessImageNameW
query.argtypes = (wintypes.HANDLE, wintypes.DWORD, wintypes.LPWSTR, ctypes.POINTER(wintypes.DWORD))
query.restype = wintypes.BOOL
buffer, size = ctypes.create_unicode_buffer(32768), wintypes.DWORD(32768)
assert query(int(process), 0, buffer, ctypes.byref(size))
assert Path(buffer.value).resolve(strict=True) == executable
finally:
process.Close()
manifest = json.loads((root / 'candidate-manifest.json').read_text(encoding='utf-8'))
assert hashlib.sha256(executable.read_bytes()).hexdigest() == manifest['exe_sha256']
def verify_disposable_projects(root):
inputs = json.loads((root / 'inputs.json').read_text(encoding='utf-8'))
expected = {Path(p).resolve(strict=True) for p in inputs['projects']}
originals = {Path(p).resolve(strict=True) for p in inputs['sources']}
assert len(expected) == 2
assert all(p.is_relative_to(root / 'projects') and p not in originals for p in expected)
projects = database(root, 'select path from projects')
if projects:
assert {Path(p['path']).resolve(strict=True) for p in projects} == expected
for row in database(root, 'select * from target_plan'):
assert Path(row['project_path']).resolve(strict=True) in expected
assert row['old_part_number'] == '4100-CA0000-T7'
assert bool(row['enabled']) == (row['refdes'] == 'RV05')
if row['enabled']:
assert row['new_part_number'] == '4100-CA0000-T0'
else:
assert row['refdes'] == 'RV11' and row['old_value'] == '0R'
def verify_observation(path):
observation = json.loads(path.read_text(encoding='utf-8'))
assert not observation['observer_errors'], observation['observer_errors']
assert observation['sessions']
assert all(observation['cad_exit_confirmed'].values())
assert all(observation['desktop_absent'].values())
assert not observation['owned_cad_became_foreground']
assert not observation['owned_cad_on_input_desktop']
assert observation['input_desktop_before'] == observation['input_desktop_after']
assert observation['file_read_samples'] == observation['samples']
def verified_events(root):
records = []
for task in database(root, 'select task_id from tasks'):
path = root / 'data/tasks' / task['task_id'] / 'events.jsonl'
events = [json.loads(line) for line in path.read_text(encoding='utf-8').splitlines()]
saved = [e for e in events if e['operation'] == 'quick_run_executed'
and e.get('details', {}).get('state') == 'saved_ok']
assert len(saved) == 1, f'Expected one genuinely saved step: {task}'
assert 'RV05 4100-CA0000-T7 -> 4100-CA0000-T0' in saved[0]['message']
records.append(dict(task_id=task['task_id'], event=saved[0]))
return records
def file_dialog(driver, path, *, save=False):
dialog = wait(lambda: next((w for w in driver.windows()
if win32gui.GetClassName(w.handle) == '#32770'), None), timeout=15)
# Native Windows Common Item Dialog FileNameControlHost has edit ID 1001.
edits = dialog.descendants(control_type='Edit')
target = next((c for c in edits if c.element_info.automation_id in ('1001', '1148')), None)
if target is None:
target = next(c for c in edits if 'FileName' in c.element_info.automation_id)
target.set_edit_text(str(path))
button = next(c for c in dialog.descendants(control_type='Button')
if c.element_info.automation_id == '1')
# Native buttons own HWNDs, unlike Qt's lightweight children.
win32gui.PostMessage(button.handle, win32con.BM_CLICK, 0, 0)
wait(lambda: not win32gui.IsWindow(dialog.handle), timeout=20)
def fill_template(template, path, *, invalid=False):
workbook = load_workbook(template)
sheet = workbook.active
headers = [c.value for c in sheet[1]]
assert len(headers) == 11
for number in range(2, sheet.max_row + 1):
row = dict(zip(headers, (c.value for c in sheet[number])))
row.update(old_part_number='4100-CA0000-T7', new_part_number='4100-CA0000-T0',
refdes='RV05', enabled=True, sync_nc=True)
for column, header in enumerate(headers, 1):
sheet.cell(number, column).value = row.get(header)
if invalid:
row['refdes'] = 'R_DOES_NOT_EXIST'
sheet.append([row.get(h) for h in headers])
workbook.save(path)
workbook.close()
def bom(driver, root, report):
tasks = database(root, 'select * from tasks')
assert not any(t['status'] == 'completed' for t in tasks), 'Do not overwrite an executed acceptance run'
if not tasks:
dialogs = [w for w in driver.windows() if w.window_text() == '从目录创建工程任务']
if not dialogs:
driver.click(driver.find(automation_id='newTaskButton'))
dialog = wait(lambda: next((w for w in driver.windows() if w.window_text() == '从目录创建工程任务'), None))
driver.type_text(driver.find(automation_id='taskDirectory', window=dialog), str(root / 'projects'))
driver.record('02 填写工程根目录,点击“读取工程”',
highlight=driver.find(automation_id='readTaskProjects', window=dialog))
driver.click(driver.find(automation_id='readTaskProjects', window=dialog))
create = driver.find('创建任务', kind='Button', window=dialog)
wait(create.is_enabled, timeout=20)
driver.record('03 勾选工程:每个工程创建一个任务', highlight=create)
driver.click(create)
wait(lambda: len(database(root, 'select * from tasks')) == 2, timeout=20)
driver.click(driver.find('本批位号计划', kind='TabItem'))
wait(lambda: driver.find(automation_id='exportBomTemplate').is_enabled(), timeout=20)
driver.record('04 已创建两个任务;先导出本批默认 BOM 模板',
highlight=driver.find(automation_id='exportBomTemplate'))
template = root / '默认BOM模板.xlsx'
if not template.exists():
driver.click(driver.find(automation_id='exportBomTemplate'))
file_dialog(driver, template, save=True)
wait(template.is_file, timeout=20)
valid, invalid = root / 'BOM-替换RV05.xlsx', root / 'BOM-含错误位号.xlsx'
fill_template(template, valid)
fill_template(template, invalid, invalid=True)
report['template_columns'] = 11
report['template'] = str(template)
# Invalid and valid import both use the candidate's real CAD inventory reader.
for path, expected_failed, caption in (
(invalid, True, '05 导入含错误位号的 BOM:先检查报告,不会部分保存'),
(valid, False, '07 修正后重新导入:两工程各替换 RV05,RV11 保留'),
):
driver.record(caption, highlight=driver.find(automation_id='importBomPlan'))
started = time.monotonic()
if not any(win32gui.GetClassName(w.handle) == '#32770' for w in driver.windows()):
driver.click(driver.find(automation_id='importBomPlan'))
file_dialog(driver, path)
wait(lambda: driver.find(automation_id='importBomPlan').is_enabled(), timeout=1200)
toggle = driver.find(automation_id='toggleBomReport')
title = toggle.window_text()
assert '通过 2' in title and '未检查 0' in title, title
assert ('失败 1' in title) if expected_failed else ('失败 0' in title), title
assert not database(root, 'select * from target_plan'), 'Import must not persist before Save'
report.setdefault('imports', []).append(dict(file=path.name, seconds=time.monotonic() - started, title=title))
driver.click(toggle)
detail = wait(lambda: next((w for w in driver.windows() if w.window_text() == '本批 BOM 导入校验详情'), None))
text = driver.find(automation_id='bomImportReport', window=detail).window_text()
if expected_failed:
assert 'R_DOES_NOT_EXIST' in text or 'Excel 第 4 行' in text, text
driver.record('06 校验报告:通过 2 行 / 失败 1 行,错误定位到 Excel 行号' if expected_failed
else '08 校验全部通过;当前是预览,点击保存才写入计划', duration=2500)
win32gui.PostMessage(detail.handle, win32con.WM_CLOSE, 0, 0)
wait(lambda: not win32gui.IsWindow(detail.handle), timeout=10)
driver.click(driver.find(automation_id='saveTargetPlan'))
wait(lambda: len(database(root, 'select * from target_plan')) == 4, timeout=20)
rows = database(root, 'select * from target_plan')
assert sum(r['enabled'] for r in rows) == 2
assert all(bool(r['enabled']) == (r['refdes'] == 'RV05') for r in rows)
report['saved_targets'] = rows
driver.record('09 保存本批计划:仅 RV05 替换,同料号 RV11 保持原样', duration=2300)
# Search affects display only; it must not change batch execution membership.
search = driver.find(automation_id='taskSearch')
driver.type_text(search, 'T605A')
assert len(driver.find(automation_id='taskList').children()) == 1
driver.record('10 左侧搜索只过滤显示,不改变同批执行范围', highlight=search)
driver.type_text(search, '')
assert len(driver.find(automation_id='taskList').children()) == 2
report['search_preserves_tasks'] = True
def execute(driver, root, report):
verify_disposable_projects(root)
tasks = database(root, 'select * from tasks')
assert len(tasks) == 2 and all(t['status'] in ('draft', 'ready') for t in tasks)
rows = database(root, 'select * from target_plan')
assert len(rows) == 4 and sum(r['enabled'] for r in rows) == 2
for task in tasks:
item = next(c for c in driver.find(automation_id='taskList').children() if task['name'] in c.window_text())
driver.click(item)
wait(lambda: Path(task['name']).name in driver.find(automation_id='boundProjectPath').window_text(), timeout=20)
copy = driver.find(automation_id='copyPartNumberToValue')
wait(copy.is_enabled, timeout=20)
if not copy.get_toggle_state():
driver.click(copy)
wait(lambda: next(t for t in database(root, 'select * from tasks')
if t['task_id'] == task['task_id'])['copy_part_number_to_value'], timeout=15)
driver.record('11 开启 Part Label → Value;确认计划已保存', highlight=copy)
driver.click(driver.find(automation_id='executeProjectTasks'))
confirmation = wait(lambda: next((w for w in driver.windows() if w.window_text() == '确认顺序执行本批任务'), None))
driver.record('12 核对执行范围与保存回读说明,再确认执行', duration=2500)
yes = None
for text in ('Yes', '&Yes', '是(&Y)', '是'):
try:
yes = driver.find(text, kind='Button', window=confirmation)
break
except LookupError:
pass
assert yes is not None, 'Cannot identify native execution confirmation button'
started = time.monotonic()
driver.click(yes)
driver.record('13 后台按工程顺序执行;等待段已压缩', duration=2000)
last_status = None
def finished():
nonlocal last_status
states = database(root, 'select name,status,error_id from tasks order by group_position')
if states != last_status:
print(json.dumps(states, ensure_ascii=False), flush=True)
driver.record('执行中:按工程顺序替换、保存并重新打开核验', duration=1000)
last_status = states
if any(t['status'] == 'failed' for t in states):
raise AssertionError(f'Native execution failed; do not auto-retry: {states}')
return all(t['status'] == 'completed' for t in states)
wait(finished, timeout=1800)
wait(lambda: driver.find(automation_id='startNewRoundButton').is_enabled(), timeout=20)
report['execution_seconds'] = time.monotonic() - started
report['completed_tasks'] = database(root, 'select * from tasks')
report['saved_readback_events'] = verified_events(root)
driver.record('14 本批执行结束:查看真实替换结果与回读状态', duration=2500)
def details(driver, root, report):
dialogs = [w for w in driver.windows() if w.window_text() == '当前任务 · 替换结果与执行日志']
if not dialogs:
driver.click(driver.find(automation_id='toggleLogButton'))
dialog = wait(lambda: next((w for w in driver.windows() if w.window_text() == '当前任务 · 替换结果与执行日志'), None))
table = driver.find(automation_id='executionResults', window=dialog)
# The result table is populated from actual saved/reopened readback events.
time.sleep(1)
cells = [c.window_text() for c in table.children()]
assert any('RV05' in text for text in cells), cells
assert any('4100-CA0000-T0' in text for text in cells), cells
assert any('已保存并核验' in text for text in cells), cells
report['result_accessibility_cells'] = cells
driver.record('15 位号替换结果:图页、位号、旧料号、回读料号、核验状态', duration=2700)
driver.click(driver.find('完整日志', kind='TabItem', window=dialog))
driver.record('16 完整日志查看各阶段;可翻页查看历史记录', duration=2500)
win32gui.PostMessage(dialog.handle, win32con.WM_CLOSE, 0, 0)
wait(lambda: not win32gui.IsWindow(dialog.handle), timeout=10)
driver.click(driver.find(automation_id='toggleLogButton'))
reopened = wait(lambda: next((w for w in driver.windows()
if w.window_text() == '当前任务 · 替换结果与执行日志'), None), timeout=10)
assert reopened.handle != dialog.handle
wait(lambda: any('RV05' in c.window_text() for c in driver.find(
automation_id='executionResults', window=reopened).children()), timeout=15)
driver.record('17 日志窗口关闭后可重新打开,结果仍可查看', duration=2000)
detail = next(w for w in driver.windows() if w.window_text() == '当前任务 · 替换结果与执行日志')
win32gui.PostMessage(detail.handle, win32con.WM_CLOSE, 0, 0)
driver.record('18 已完成任务可“开始新一轮”;旧轮次证据保留',
highlight=driver.find(automation_id='startNewRoundButton'), duration=2500)
report['detail_reopened'] = True
def new_round(driver, root, report):
assert json.loads((root / 'independent-report.json').read_text(encoding='utf-8'))['passed']
tasks = database(root, 'select * from tasks')
assert len(tasks) == 2 and all(t['status'] == 'completed' for t in tasks)
driver.click(driver.find(automation_id='startNewRoundButton'))
dialog = wait(lambda: next((w for w in driver.windows() if w.window_text() == '开始新一轮'), None), timeout=15)
driver.record('19 开始新一轮前确认:旧计划与执行证据会归档保留', duration=2500)
yes = None
for text in ('Yes', '&Yes', '是(&Y)', '是'):
try:
yes = driver.find(text, kind='Button', window=dialog)
break
except LookupError:
pass
assert yes is not None
driver.click(yes)
wait(lambda: all(t['status'] == 'draft' for t in database(root, 'select * from tasks')), timeout=20)
assert not database(root, 'select * from target_plan')
archives = list((root / 'data/tasks').glob('*/rounds/*/plan.json'))
assert len(archives) == 2
driver.record('20 两任务已恢复待配置;按当前料号重新填 BOM 后可再执行', duration=3000)
report['new_round_archives'] = [str(path) for path in archives]
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--root', type=Path, required=True)
parser.add_argument('--stage', choices=('bom', 'execute', 'details', 'new_round'), required=True)
parser.add_argument('--run-native', action='store_true')
args = parser.parse_args()
if not args.run_native:
parser.error('All stages require --run-native to acknowledge disposable CAD operations')
root = args.root.resolve(strict=True)
session = json.loads((root / 'ui-session.json').read_text(encoding='utf-8'))
verify_identity(root, session)
verify_disposable_projects(root)
driver = WindowDriver(session['pid'], root / 'recording')
report_path = root / 'ui-acceptance.json'
report = json.loads(report_path.read_text(encoding='utf-8')) if report_path.exists() else {}
report.pop(args.stage + '_passed', None)
try:
if args.stage in ('bom', 'execute'):
with PrivateDesktopObserver(root):
globals()[args.stage](driver, root, report)
(root / f'desktop-observation-{args.stage}.json').write_bytes((root / 'desktop-observation.json').read_bytes())
verify_observation(root / f'desktop-observation-{args.stage}.json')
else:
globals()[args.stage](driver, root, report)
report[args.stage + '_passed'] = True
except Exception:
report.setdefault('failures', []).append(dict(stage=args.stage, traceback=traceback.format_exc()))
raise
finally:
report_path.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
driver.save_gif(root / '窗口操作教程.gif')
if __name__ == '__main__':
main()
+55
View File
@@ -0,0 +1,55 @@
"""Assemble numbered PrintWindow operation frames; shorten only idle waits."""
import argparse
import json
from pathlib import Path
from PIL import Image
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--root', type=Path, required=True)
parser.add_argument('--output', type=Path, required=True)
args = parser.parse_args()
root = args.root.resolve(strict=True)
events = json.loads((root / 'recording/frames.json').read_text(encoding='utf-8'))
by_number = {}
for entry in events:
first = entry['caption'].split(maxsplit=1)[0]
if not first.isdigit():
continue
number = int(first)
# Early driver setup retries are not part of the instructional sequence.
if number not in by_number or number in (1, 2):
by_number[number] = entry
assert set(by_number) == set(range(1, 21)), sorted(by_number)
selected = [by_number[n] for n in range(1, 21)]
images = [Image.open(root / f'recording/frame-{e["frame"]:03d}.png').convert('RGB') for e in selected]
assert {image.size for image in images} == {(1280, 980)}
# A shared palette samples every real state, including error and success colors.
contact = Image.new('RGB', (1024, 980), '#f3f5f8')
for n, image in enumerate(images):
thumb = image.resize((256, 196), Image.Resampling.LANCZOS)
contact.paste(thumb, ((n % 4) * 256, (n // 4) * 196))
palette = contact.quantize(colors=192)
frames = [image.quantize(palette=palette, dither=Image.Dither.NONE) for image in images]
args.output.parent.mkdir(parents=True, exist_ok=True)
durations = [max(e['duration_ms'], 2200) for e in selected]
frames[0].save(args.output, save_all=True, append_images=frames[1:],
duration=durations, loop=0, optimize=True, disposal=2)
contact.save(root / 'tutorial-contact-sheet.png')
with Image.open(args.output) as exported:
assert exported.n_frames == 20 and exported.size == (1280, 980)
for number in (0, 5, 14, 19):
exported.seek(number)
exported.convert('RGB').save(root / f'tutorial-gif-check-{number:02d}.png')
report = dict(gif=str(args.output.resolve()), bytes=args.output.stat().st_size,
frames=20, duration_seconds=sum(durations) / 1000,
capture='PrintWindow surfaces of the candidate process only',
waits_shortened=True, steps=selected)
(root / 'tutorial-report.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
print(json.dumps({k: v for k, v in report.items() if k != 'steps'}, ensure_ascii=False, indent=2))
if __name__ == '__main__':
main()
+163
View File
@@ -0,0 +1,163 @@
"""External Windows UI driver and PrintWindow-only instructional capture.
This utility cannot import application internals or fabricate task state. It
operates the executable through Windows accessibility and records only windows
owned by that executable. Workbook edits and acceptance assertions belong to
the calling scenario.
"""
from __future__ import annotations
import ctypes
from ctypes import wintypes
import json
from pathlib import Path
import time
from PIL import Image, ImageDraw, ImageFont
from pywinauto import Application
import win32con
import win32gui
import win32process
import win32ui
def window_image(hwnd):
"""Read this HWND's drawing surface, never the desktop framebuffer."""
left, top, right, bottom = win32gui.GetWindowRect(hwnd)
width, height = right - left, bottom - top
dc = win32gui.GetWindowDC(hwnd)
source = win32ui.CreateDCFromHandle(dc)
target = source.CreateCompatibleDC()
bitmap = win32ui.CreateBitmap()
bitmap.CreateCompatibleBitmap(source, width, height)
target.SelectObject(bitmap)
try:
print_window = ctypes.windll.user32.PrintWindow
print_window.argtypes = (wintypes.HWND, wintypes.HDC, wintypes.UINT)
print_window.restype = wintypes.BOOL
if not print_window(hwnd, target.GetSafeHdc(), 2):
raise RuntimeError(f'PrintWindow failed for {hwnd}')
return Image.frombuffer('RGB', (width, height), bitmap.GetBitmapBits(True), 'raw', 'BGRX', 0, 1).copy()
finally:
win32gui.DeleteObject(bitmap.GetHandle())
target.DeleteDC()
source.DeleteDC()
win32gui.ReleaseDC(hwnd, dc)
class WindowDriver:
def __init__(self, pid, output):
self.pid, self.output = pid, Path(output)
self.output.mkdir(parents=True, exist_ok=True)
self.app = Application(backend='uia').connect(process=pid, timeout=15)
self.frames, self.durations, self.steps = [], [], []
self.font = ImageFont.truetype('C:/Windows/Fonts/msyh.ttc', 22)
if (self.output / 'frames.json').exists():
self.steps = json.loads((self.output / 'frames.json').read_text(encoding='utf-8'))
self.frames = [Image.open(self.output / f'frame-{s["frame"]:03d}.png').convert('RGB') for s in self.steps]
self.durations = [s['duration_ms'] for s in self.steps]
def windows(self):
handles = []
def collect(handle, _):
if win32gui.IsWindowVisible(handle) and win32process.GetWindowThreadProcessId(handle)[1] == self.pid:
left, top, right, bottom = win32gui.GetWindowRect(handle)
if right - left > 100 and bottom - top > 80:
handles.append(handle)
win32gui.EnumWindows(collect, None)
return [self.app.window(handle=handle).wrapper_object() for handle in handles]
def main(self):
deadline = time.monotonic() + 15
while time.monotonic() < deadline:
for window in self.windows():
if window.window_text().startswith('DxDesigner '):
return window
time.sleep(.2)
raise TimeoutError('Application main window not found')
def find(self, text=None, *, kind=None, automation_id=None, window=None):
root = window or self.main()
# Do not recursively enumerate virtual Qt table cells through UIA.
def walk(parent, depth=0):
if depth > 12:
return
for child in parent.children():
yield child
if child.element_info.control_type not in {
'Table', 'DataGrid', 'List', 'ScrollBar', 'Header', 'Edit',
'Button', 'Text', 'CheckBox', 'ComboBox', 'TitleBar', 'MenuBar', 'MenuItem'}:
yield from walk(child, depth + 1)
controls = walk(root)
matches = [c for c in controls if (kind is None or c.element_info.control_type == kind)
and (text is None or c.window_text() == text)
and (automation_id is None or c.element_info.automation_id == automation_id
or c.element_info.automation_id.endswith('.' + automation_id))
and c.is_visible()]
if len(matches) != 1:
raise LookupError(f'Expected one {text!r}/{automation_id!r}, got {len(matches)}')
return matches[0]
def click(self, control):
# Posted window mouse events allow modal dialogs without blocking the driver.
self.point(control)
def point(self, control, *, dx=None, dy=None, double=False):
rect = control.rectangle()
if dx is None and control.element_info.control_type in ('ListItem', 'DataItem'):
dx = 20 # Qt may expose the full elided text width beyond its viewport.
root = control
while not root.handle or not win32gui.IsWindow(root.handle):
root = root.parent()
x = rect.left + (dx if dx is not None else rect.width() // 2)
y = rect.top + (dy if dy is not None else rect.height() // 2)
x, y = win32gui.ScreenToClient(root.handle, (x, y))
value = (y << 16) | (x & 0xFFFF)
for _ in range(2 if double else 1):
win32gui.PostMessage(root.handle, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, value)
win32gui.PostMessage(root.handle, win32con.WM_LBUTTONUP, 0, value)
time.sleep(.2)
def type_text(self, control, text):
control.set_edit_text(text)
time.sleep(.2)
def record(self, caption, *, highlight=None, duration=1600):
main = self.main()
image = window_image(main.handle)
left, top, _, _ = win32gui.GetWindowRect(main.handle)
# Owned modal/detail windows are composited from their own surfaces.
for other in reversed(self.windows()):
if other.handle == main.handle:
continue
other_left, other_top, _, _ = win32gui.GetWindowRect(other.handle)
image.paste(window_image(other.handle), (other_left - left, other_top - top))
draw = ImageDraw.Draw(image)
if highlight is not None:
rect = highlight.rectangle()
box = (rect.left - left - 3, rect.top - top - 3,
rect.right - left + 3, rect.bottom - top + 3)
draw.rounded_rectangle(box, radius=5, outline='#e35d30', width=4)
# Fixed canvas dimensions allow window resizing without desktop capture.
image.thumbnail((1280, 900), Image.Resampling.LANCZOS)
canvas = Image.new('RGB', (1280, 980), '#f3f5f8')
canvas.paste(image, ((1280 - image.width) // 2, 0))
draw = ImageDraw.Draw(canvas)
draw.rectangle((0, 900, 1280, 980), fill='#172b45')
draw.text((24, 914), caption, font=self.font, fill='white')
draw.text((24, 946), '窗口操作实录 · 等待过程已压缩 · 工程副本验收',
font=ImageFont.truetype('C:/Windows/Fonts/msyh.ttc', 16), fill='#bdcfdf')
index = len(self.frames)
canvas.save(self.output / f'frame-{index:03d}.png')
self.frames.append(canvas)
self.durations.append(duration)
self.steps.append(dict(frame=index, caption=caption, duration_ms=duration, wall_time=time.time()))
(self.output / 'frames.json').write_text(json.dumps(self.steps, ensure_ascii=False, indent=2), encoding='utf-8')
def save_gif(self, path):
if not self.frames:
raise RuntimeError('No window frames captured')
palette = self.frames[0].quantize(colors=160)
images = [frame.quantize(palette=palette, dither=Image.Dither.NONE) for frame in self.frames]
images[0].save(path, save_all=True, append_images=images[1:],
duration=self.durations, loop=0, optimize=True, disposal=2)
+76
View File
@@ -0,0 +1,76 @@
"""Create task data with the real 1.1.1 EXE, then open its copy in the candidate."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import sqlite3
import subprocess
import time
import win32con
import win32gui
from accept_packaged_ui import wait
from packaged_window_driver import WindowDriver
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--root', type=Path, required=True)
args = parser.parse_args()
root = args.root.resolve(strict=True)
repository = Path(__file__).resolve().parents[1]
legacy = repository / 'dist/DxPartReplace-1.1.1/DxPartReplace/DxPartReplace.exe'
release = json.loads((repository / 'docs/releases/v1.1.1-build.json').read_text(encoding='utf-8'))
assert hashlib.sha256(legacy.read_bytes()).hexdigest() == release['artifacts']['exe_sha256']
old_data, new_data = root / 'v111-created-data', root / 'v111-upgraded-copy'
old_data.mkdir(exist_ok=False)
projects = root / 'upgrade-fixture-projects'
for name in ('Legacy-A', 'Legacy-B'):
path = projects / name / 'board.prj'
path.parent.mkdir(parents=True)
path.write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n', encoding='utf-8')
env = dict(os.environ, TEMP=str(repository / 'build/test-temp-remediation'),
TMP=str(repository / 'build/test-temp-remediation'), LOCALAPPDATA=str(root / 'profile'))
for key in ('PYTHONPATH', 'PYTHONHOME', 'DX_TASK_CENTER_HOME', 'QT_QPA_PLATFORM'):
env.pop(key, None)
process = subprocess.Popen([str(legacy), '--data-root', str(old_data)], env=env,
creationflags=subprocess.CREATE_NO_WINDOW)
driver = WindowDriver(process.pid, root / 'upgrade-recording')
window = driver.main()
try:
driver.click(driver.find(automation_id='newTaskButton'))
dialog = wait(lambda: next((w for w in driver.windows() if w.window_text() == '从目录创建工程任务'), None), timeout=15)
driver.type_text(driver.find(automation_id='taskDirectory', window=dialog), str(projects))
driver.click(driver.find(automation_id='readTaskProjects', window=dialog))
create = driver.find('创建任务', kind='Button', window=dialog)
wait(create.is_enabled, timeout=20)
driver.click(create)
def read_tasks(path):
with sqlite3.connect(path) as db:
return db.execute('select task_id,name from tasks order by task_id').fetchall()
original = wait(lambda: (rows if len(rows := read_tasks(old_data / 'task-center.db')) == 2 else None), timeout=20)
time.sleep(.5)
finally:
win32gui.PostMessage(window.handle, win32con.WM_CLOSE, 0, 0)
process.wait(timeout=30)
before = hashlib.sha256((old_data / 'task-center.db').read_bytes()).hexdigest()
new_data.mkdir()
with sqlite3.connect((old_data / 'task-center.db').as_uri() + '?mode=ro', uri=True) as src, sqlite3.connect(new_data / 'task-center.db') as dst:
src.backup(dst)
env['QT_QPA_PLATFORM'] = 'offscreen'
candidate = root / 'extracted/DxPartReplace/DxPartReplace.exe'
result = subprocess.run([str(candidate), '--smoke-test', '--data-root', str(new_data)],
env=env, capture_output=True, timeout=90)
report = dict(legacy_version='1.1.1', task_count=len(original), candidate_exit_code=result.returncode,
task_identities_preserved=read_tasks(new_data / 'task-center.db') == original,
legacy_source_unchanged=hashlib.sha256((old_data / 'task-center.db').read_bytes()).hexdigest() == before,
fixture_is_metadata_only=True, cad_launched=False)
assert result.returncode == 0 and report['task_identities_preserved'] and report['legacy_source_unchanged'], report
(root / 'v111-upgrade-report.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
print(json.dumps(report, ensure_ascii=False, indent=2))
if __name__ == '__main__':
main()
+79
View File
@@ -0,0 +1,79 @@
"""Independently read saved disposable projects after frozen-EXE execution."""
import argparse
import json
from pathlib import Path
import sys
import time
import win32api
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'src'))
from dx_productivity.trial_task_center import isolated_cad
from accept_packaged_ui import database, verify_disposable_projects, verify_observation
from private_desktop_observer import PrivateDesktopObserver
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--root', type=Path, required=True)
parser.add_argument('--run-native', action='store_true', required=True)
args = parser.parse_args()
root = args.root.resolve(strict=True)
verify_disposable_projects(root)
tasks = database(root, 'select task_id,status from tasks')
assert len(tasks) == 2 and all(t['status'] == 'completed' for t in tasks)
candidate = root / 'extracted/DxPartReplace/DxPartReplace.exe'
original = isolated_cad._helper_command
def helper(action, evidence, pid):
return (str(candidate), '--private-cad-action', action,
'--private-cad-evidence', str(evidence), '--private-cad-pid', str(pid))
isolated_cad._helper_command = helper
report = dict(reader='independent source attribute reader in fresh private CAD; frozen probe/quit helpers', projects=[])
try:
with PrivateDesktopObserver(root):
for task in tasks:
rows = database(root, "select * from target_plan where task_id='" + task['task_id'] + "'")
selected = next(row for row in rows if row['enabled'])
project = Path(selected['project_path']).resolve(strict=True)
assert project.is_relative_to(root / 'projects')
reader = root / 'data/tasks' / task['task_id'] / 'quick-run-history/sheet-discovery-acceptance-independent'
reader.mkdir(exist_ok=False)
destination = root / ('independent-attributes-' + task['task_id'] + '.json')
started = time.monotonic()
with isolated_cad.IsolatedCadSession(reader) as session:
process = session.start_worker((sys.executable,
str(Path(__file__).with_name('probe_part_label_live.py')),
'--inspect-project', win32api.GetShortPathName(str(project)),
'--schematic', selected['schematic_name'], '--sheet', selected['sheet_number'],
'--output', str(destination)), stdout=-1, stderr=-1)
try:
if process.wait(timeout=150):
raise AssertionError(process.stderr.read().decode('utf-8', errors='replace'))
finally:
process.close()
actual = json.loads(destination.read_text(encoding='utf-8'))
by_ref = {r['refdes']: r for r in actual}
assert set(by_ref) == {'RV05', 'RV11'}
assert by_ref['RV05']['part_number'] == '4100-CA0000-T0'
assert by_ref['RV05']['part_label'] == by_ref['RV05']['value'] == '0R'
for before in rows:
after = by_ref[before['refdes']]
assert before['uid'] == after['uid']
if not before['enabled']:
assert after['part_number'] == before['old_part_number']
assert after['value'] == before['old_value']
entry = dict(task_id=task['task_id'], project=str(project), components=actual,
seconds=time.monotonic() - started)
report['projects'].append(entry)
print(json.dumps(entry, ensure_ascii=False), flush=True)
observation = root / 'desktop-observation-independent.json'
observation.write_bytes((root / 'desktop-observation.json').read_bytes())
verify_observation(observation)
report['passed'] = True
finally:
isolated_cad._helper_command = original
(root / 'independent-report.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
if __name__ == '__main__':
main()