Files
dxdesigner-part-replacement/tools/accept_random_packaged_ui.py

612 lines
33 KiB
Python

"""External UIA acceptance of a frozen EXE against disposable seeded projects.
Prepare projects/workbook with accept_random_cad.py first. Import never clicks
Execute and requires no CAD slot. Execute requires --run-native; it uses actual
UI save/confirmation/pause/resume controls. SQLite observations are read-only.
"""
from __future__ import annotations
import argparse
import ctypes
from ctypes import wintypes
import hashlib
import json
import os
import re
from pathlib import Path
import subprocess
import time
import traceback
from accept_packaged_ui import database, file_dialog, wait, verify_observation
from accept_random_cad import fingerprint, saved_uids, write
from packaged_window_driver import WindowDriver
from private_desktop_observer import PrivateDesktopObserver
def validate_fixture(root):
manifest = json.loads((root / 'manifest.json').read_text(encoding='utf-8'))
projects = (root / 'projects').resolve(strict=True)
source = Path(manifest['source']).resolve(strict=True)
if projects.is_relative_to(source.parent) or source.is_relative_to(root):
raise ValueError('Disposable fixture must be separate from original project')
if fingerprint(source.parent) != manifest['source_hashes']:
raise ValueError('Original source fingerprint changed')
paths = [Path(case['project']).resolve(strict=True) for case in manifest['cases']]
if not paths or len(paths) != len(set(paths)) or any(not p.is_relative_to(projects) for p in paths):
raise ValueError('Every case must name a distinct disposable project')
if not (root / 'random-bom.xlsx').is_file():
raise ValueError('Prepared random BOM workbook missing')
return manifest
def process_image(pid):
import win32api
process = win32api.OpenProcess(0x1000, False, pid)
try:
query = ctypes.windll.kernel32.QueryFullProcessImageNameW
query.argtypes = (wintypes.HANDLE, wintypes.DWORD, wintypes.LPWSTR, ctypes.POINTER(wintypes.DWORD))
query.restype = wintypes.BOOL
value, size = ctypes.create_unicode_buffer(32768), wintypes.DWORD(32768)
if not query(int(process), 0, value, ctypes.byref(size)):
raise ctypes.WinError()
return Path(value.value).resolve(strict=True)
finally:
process.Close()
def validate_session(root, pid, executable, sha256):
session = json.loads((root / 'ui-session.json').read_text(encoding='utf-8'))
if (session.get('pid') != pid or Path(session['executable']).resolve() != executable
or session.get('exe_sha256') != sha256):
raise ValueError('Attach requires the exact process/EXE hash recorded for this isolated root')
def queue_records(root):
return {p.name: json.loads(p.read_text(encoding='utf-8'))
for p in (root / 'data/task-queues').glob('*.json')}
def queue_bindings(queues):
return {name: {'task_ids': row['task_ids'], 'plan_hashes': row['plan_hashes']}
for name, row in queues.items()}
def pause_ready(queues):
# One actual queue must still have work beyond its currently running item.
# Never combine an old completed queue with a new single-item execution.
return any({'completed', 'running', 'pending'} <= {entry['state'] for entry in row['entries'].values()}
for row in queues.values())
def pause_evidence(root, task_ids):
"""Copy observations only; never create a worker control or acknowledgement."""
observations=[]
for task_id in task_ids:
work=root/'data/tasks'/task_id/'quick-run'
for path in [work/'worker-progress.json',*work.glob('startup-pause-*.json')]:
if path.exists():
data=path.read_bytes()
observations.append({'task_id':task_id,'path':str(path),
'sha256':hashlib.sha256(data).hexdigest(),'record':json.loads(data.decode('utf-8'))})
return observations
def resources_settled(root):
records = [(p, json.loads(p.read_text(encoding='utf-8')))
for pattern in ('*/supervisor.json', '*/session.json')
for p in (root / 'data/batch-resources').glob(pattern)]
for path, row in records:
if path.name == 'supervisor.json':
if row.get('state') != 'finished':
return False
else:
cleanup = row.get('cleanup') or {}
proof = row.get('release_proof') or {}
released = (cleanup.get('desktop_handle_closed') is True
and (cleanup.get('desktop_confirmation') or {}).get('released') is True
and not cleanup.get('errors'))
observed = (proof.get('generation') == row.get('generation')
and proof.get('processes_exited') is True and proof.get('desktop_released') is True)
if row.get('state') != 'released' or not (released or observed):
return False
return True
def control_enabled(driver, automation_id):
control = driver.find(automation_id=automation_id, optional=True)
return control is not None and control.is_enabled()
def confirm(driver, record, title='确认顺序执行本批任务'):
def confirmation():
acknowledge_error_modal(driver, record)
return next((w for w in driver.windows() if w.window_text() == title), None)
dialog = wait(confirmation, timeout=60)
text = [c.window_text() for c in dialog.descendants() if c.window_text()]
record('execution-confirmation', title=dialog.window_text(), text=text)
for label in ('Yes', '&Yes', '是(&Y)', '是'):
try:
yes = driver.find(label, kind='Button', window=dialog)
break
except LookupError:
pass
else:
raise LookupError('Expected explicit batch execution confirmation')
driver.click(yes)
def close_results(driver):
import win32con, win32gui
for dialog in driver.windows():
if '替换结果' in dialog.window_text():
win32gui.PostMessage(dialog.handle, win32con.WM_CLOSE, 0, 0)
def acknowledge_error_modal(driver, record, *, expected=()):
"""Capture and acknowledge only this process's disabled-owner error modal."""
import win32con, win32gui, win32process
for dialog in driver.windows():
title = dialog.window_text()
if title not in {'操作未完成', '错误', 'Error'}:
continue
owner = win32gui.GetWindow(dialog.handle, win32con.GW_OWNER)
# Qt UIA can report enabled=True while the native owner is disabled.
if (win32process.GetWindowThreadProcessId(dialog.handle)[1] != driver.pid
or not owner or owner != driver.main().handle
or win32process.GetWindowThreadProcessId(owner)[1] != driver.pid
or win32gui.IsWindowEnabled(owner)):
continue
text = [c.window_text() for c in dialog.descendants() if c.window_text()]
buttons = [c for c in dialog.descendants(control_type='Button')
if c.window_text() in {'OK', '&OK', '确定', '确定(&O)'} and c.is_enabled()]
if len(buttons) != 1:
raise AssertionError('Owned error modal has no unique OK; preserve it for inspection')
anticipated = any(message in '\n'.join(text) for message in expected)
# record() captures the actual owned window surfaces before acknowledging.
record('owned-error-modal', pid=driver.pid, hwnd=dialog.handle, title=title,
native_owner_hwnd=owner, native_owner_disabled=True,
text=text, expected_supplement=anticipated)
driver.click(buttons[0])
wait(lambda: not any(w.handle == dialog.handle for w in driver.windows()), timeout=15)
record('owned-error-modal-acknowledged', hwnd=dialog.handle, expected_supplement=anticipated)
if not anticipated:
raise AssertionError('Unexpected application error modal; stop UI writes, do not replay saved UIDs')
return True
return False
def wait_for_ui(driver, record, check, *, timeout):
def observed():
acknowledge_error_modal(driver,record)
return check()
return wait(observed,timeout=timeout)
def disable_automatic_intervention(driver,record):
acknowledge_error_modal(driver,record)
intervention=driver.find(automation_id='dshAutoIntervention')
if intervention.get_toggle_state():
driver.click(intervention)
wait_for_ui(driver,record,lambda:not driver.find(automation_id='dshAutoIntervention').get_toggle_state(),timeout=15)
record('automatic-intervention-disabled')
def add_rules(driver, root, manifest, record):
cases = [case for case in manifest['cases'] if case.get('target_cell') or case['kind'] == 'rule_mode']
if not cases:
return
assert len(manifest['cases']) == 1, 'Rule supplemental uses one standalone task'
driver.click(driver.find('本批料号规则', kind='TabItem'))
unique = {(r['old_part_number'], r['new_part_number']): r for r in cases[0]['requests']}
for request in unique.values():
driver.click(driver.find(automation_id='addMappingButton'))
dialog = wait_for_ui(driver,record,lambda: next((w for w in driver.windows() if w.window_text() == '替换规则'), None), timeout=20)
edits = sorted(dialog.descendants(control_type='Edit'), key=lambda c: c.rectangle().top)
assert len(edits) == 3, 'Unexpected real rule dialog layout; do not guess inputs'
driver.type_text(edits[0], request['old_part_number'])
driver.type_text(edits[1], request['new_part_number'])
cell = cases[0].get('target_cell', '')
if cell:
driver.click(driver.find(automation_id='loadTargetCells', window=dialog))
wait_for_ui(driver,record,lambda: driver.find(automation_id='loadTargetCells', window=dialog).is_enabled(), timeout=120)
combo = driver.find(automation_id='targetCellCombo', window=dialog)
combo.select(cell)
assert combo.selected_text() == cell
record('authentic-cell-selected', cell=cell, request=request)
if cases[0]['kind'] == 'rule_mode':
for label, expected in [('启用此规则', True), ('替换后写入自定义 Value', False),
('识别并同步原 Value 中的 /NC', True)]:
assert bool(driver.find(label, kind='CheckBox', window=dialog).get_toggle_state()) == expected
driver.click(driver.find('确定', kind='Button', window=dialog))
wait_for_ui(driver,record,lambda: any(row['old_part_number'] == request['old_part_number']
and row['new_part_number'] == request['new_part_number'] and row.get('target_cell', '') == cell
for row in database(root, 'select * from rules')), timeout=60)
if cases[0]['kind'] != 'rule_mode':
driver.click(driver.find('本批位号计划', kind='TabItem'))
def verify_rule_mode(root, case):
tasks = database(root, 'select * from tasks')
assert len(tasks) == 1 and not tasks[0]['target_plan_mode'], 'Rule task unexpectedly entered target-plan mode'
assert not tasks[0]['copy_part_number_to_value'], 'Rule task changed default preserve Value policy'
assert not database(root, 'select * from pending_bom') and not database(root, 'select * from target_plan')
request, = case['requests']
rule, = database(root, 'select * from rules')
assert rule['old_part_number'] == request['old_part_number'] and rule['new_part_number'] == request['new_part_number']
assert rule['enabled'] and rule['sync_nc'] and not rule['custom_value_enabled']
assert not rule['custom_value'] and not rule['target_cell']
assert request['value_mode'] == 'preserve' and request['sync_nc'] is True
return tasks
def verify_no_cad_fixture(root, manifest):
assert all(case['kind'] == 'already_target' for case in manifest['cases'])
observation = json.loads((root / 'desktop-observation.json').read_text(encoding='utf-8'))
assert not observation['sessions'], 'Already-target user validation unexpectedly started CAD'
assert not saved_uids(root), 'Already-target user validation unexpectedly saved a replacement'
entries = [entry for queue in queue_records(root).values() for entry in queue['entries'].values()]
assert entries and all(entry['state'] == 'skipped' for entry in entries)
projects = {Path(case['project']).resolve() for case in manifest['cases']}
inventories = [json.loads(path.read_text(encoding='utf-8')) for path in
(root / 'data/tasks').glob('*/quick-run-history/native-inventory-*/native-inventory.json')]
assert inventories, 'Already-target acceptance needs an actual native inventory read'
assert all(row['backend'] == 'native_cli' and row['state'] == 'ready' and row['source_hashes_unchanged']
and Path(row['project']).resolve() in projects and not Path(row['workspace']).exists()
and not row.get('cleanup', {}).get('errors') for row in inventories)
for row in inventories:
cleanup = row['cleanup']
assert cleanup['workers_closed'] is True and cleanup['desktop_created'] is False and cleanup['processes']
assert all(process['exit_code'] == 0 and process['job_active_processes'] == 0
and process['process_handle_closed'] is True and process['job_handle_closed'] is True
and process['unconfirmed_descendant_handles'] == 0 and not process['errors']
and not process['forced_termination'] for process in cleanup['processes'])
return {'outcome': 'already_target_no_op', 'replacement_performed': False,
'application_netlist_verification': 'not_required',
'inventory_reads': len(inventories), 'requested_projects': len(projects), 'saved_uid_count': 0}
def business_results(root):
return {str(path.relative_to(root)): hashlib.sha256(path.read_bytes()).hexdigest()
for path in (root / 'data/batch-resources').glob('*/business-result.json')}
class ExternalDesktopHold:
"""One independently owned reference; never close the application's handle."""
def __init__(self, root):
self.root, self.handle, self.name, self.session = root, None, None, None
def acquire(self):
if self.handle is not None:
return False
for path in (self.root / 'data/batch-resources').glob('*/session.json'):
row = json.loads(path.read_text(encoding='utf-8'))
if row.get('state') != 'ready' or not row.get('cad_pid'):
continue
name = row.get('desktop', '')
if (not re.fullmatch('dx-[0-9a-f]{32}', name)
or row.get('session_id') != path.parent.name):
raise ValueError('Resource fixture requires exact journal desktop namespace')
import win32service
self.handle = win32service.OpenDesktop(name, 0, False, 1)
self.name, self.session = name, path
return True
return False
def blocked(self):
if self.handle is None:
return False
row = json.loads(self.session.read_text(encoding='utf-8'))
cleanup = row.get('cleanup') or {}
result = self.session.with_name('business-result.json')
return (result.exists() and json.loads(result.read_text(encoding='utf-8')).get('payload', {}).get('business_succeeded') is True
and cleanup.get('desktop_handle_closed') is True
and (cleanup.get('desktop_confirmation') or {}).get('released') is False)
def release(self):
if self.handle is not None:
self.handle.CloseDesktop()
self.handle = None
def import_fixture(driver, root, manifest, record):
acknowledge_error_modal(driver,record)
if not database(root, 'select * from tasks'):
driver.click(driver.find(automation_id='newTaskButton'))
dialog = wait_for_ui(driver,record,lambda: next((w for w in driver.windows()
if w.window_text() == '从目录创建工程任务'), None), timeout=20)
driver.type_text(driver.find(automation_id='taskDirectory', window=dialog), str(root / 'projects'))
driver.click(driver.find(automation_id='readTaskProjects', window=dialog))
create = driver.find('创建任务', kind='Button', window=dialog)
wait_for_ui(driver,record,create.is_enabled, timeout=60)
record('directory-scanned', cases=len(manifest['cases']))
driver.click(create)
wait_for_ui(driver,record,lambda: len(database(root, 'select * from tasks')) == len(manifest['cases']), timeout=90)
observed = {Path(row['path']).resolve() for row in database(root, 'select path from projects')}
assert observed == {Path(c['project']).resolve() for c in manifest['cases']}
record('tasks-created', tasks=database(root, 'select * from tasks'))
if any(case['kind'] == 'rule_mode' for case in manifest['cases']):
assert len(manifest['cases']) == 1, 'Rule mode is a standalone supplemental'
if not database(root, 'select * from rules'):
add_rules(driver, root, manifest, record)
tasks = verify_rule_mode(root, manifest['cases'][0])
record('rule-mode-defaults-confirmed', tasks=tasks, rules=database(root, 'select * from rules'))
return
driver.click(driver.find('本批位号计划', kind='TabItem'))
button = driver.find(automation_id='importBomPlan')
wait_for_ui(driver,record,button.is_enabled, timeout=90)
existing = database(root, 'select * from pending_bom')
if existing or database(root, 'select * from target_plan'):
record('existing-ui-import-retained', drafts=existing)
return
add_rules(driver, root, manifest, record)
driver.click(button)
file_dialog(driver, root / 'random-bom.xlsx')
# Observe completed report through accessibility, never application objects.
wait_for_ui(driver,record,lambda: driver.find(automation_id='importBomPlan').is_enabled(), timeout=1200)
title = driver.find(automation_id='toggleBomReport').window_text()
record('excel-imported', report=title)
# Current candidates save source drafts immediately and defer native
# inventory until execution. Earlier candidates expose checked previews.
assert '待核验' in title or '未检查 0' in title, title
drafts = database(root, 'select * from pending_bom')
if drafts:
record('batch-source-drafts-saved-by-import', drafts=drafts)
return
record('before-batch-save', targets=database(root, 'select * from target_plan'))
driver.click(driver.find(automation_id='saveTargetPlan'))
wait_for_ui(driver,record,lambda: driver.find(automation_id='saveTargetPlan').is_enabled(), timeout=120)
drafts = database(root, 'select * from pending_bom')
targets = database(root, 'select * from target_plan')
assert drafts or targets, 'Real UI Save did not persist a plan'
record('batch-plan-saved', drafts=drafts, targets=targets)
def execute_fixture(driver, root, record, *, pause, fault=None, hold=None):
forced = recovered = False
def check_modal():
expected = []
if fault and forced and not recovered:
expected.append('操作已强制中断,结果待核验。')
if hold is not None and hold.name is not None:
expected.append('后台资源尚未确认释放,请使用“重新清理资源”后再开始下一批。')
acknowledge_error_modal(driver, record, expected=expected)
def ui_wait(check, *, timeout):
def observed():
check_modal()
return check()
return wait(observed, timeout=timeout)
check_modal()
intervention = driver.find(automation_id='dshAutoIntervention')
if intervention.get_toggle_state():
driver.click(intervention)
assert not intervention.get_toggle_state(), 'Automatic external intervention must be disabled'
record('automatic-intervention-disabled')
button = driver.find(automation_id='executeProjectTasks')
ui_wait(button.is_enabled, timeout=90)
previous = queue_records(root)
driver.click(button)
confirm(driver, record)
ui_wait(lambda: queue_records(root) != previous, timeout=120)
record('execution-started')
paused = resumed = False
before_resume = None
last = None
fault_seen = None
fault_binding = None
deadline = time.monotonic() + 14400
while time.monotonic() < deadline:
check_modal()
queues = queue_records(root)
if hold is not None:
if hold.acquire():
record('external-test-reference-opened', desktop=hold.name)
if hold.blocked():
before = business_results(root)
saved = saved_uids(root)
record('completed-business-desktop-still-present', desktop=hold.name, results=before)
hold.release()
close_results(driver)
cleanup = driver.find(automation_id='cleanupBatchResources')
ui_wait(cleanup.is_enabled, timeout=60)
driver.click(cleanup)
ui_wait(lambda: resources_settled(root)
and not control_enabled(driver, 'stopQueueButton'), timeout=180)
check_modal()
assert business_results(root) == before and saved_uids(root) == saved
record('resource-only-cleanup-confirmed-no-replay', results=before, queues=queue_records(root))
return
if fault and not forced:
frames = [json.loads(path.read_text(encoding='utf-8'))
for path in (root / 'data/tasks').glob('*/quick-run/worker-progress.json')
if time.time() - path.stat().st_mtime < 5]
active = [frame for frame in frames if frame.get('stage') == fault['stage']
and re.fullmatch('[0-9a-f]{32}', str(frame.get('token', '')))
and frame.get('job_id') and type(frame.get('sequence')) is int and frame['sequence'] > 0]
binding = [(frame['token'], frame['job_id']) for frame in active]
if not active:
fault_seen = fault_binding = None
elif fault_seen is None or binding != fault_binding:
fault_seen = time.monotonic()
fault_binding = binding
force = driver.find(automation_id='forceStopButton')
if (active and fault_seen is not None and time.monotonic() - fault_seen >= fault['delay_seconds']
and force.is_enabled()):
driver.click(force)
confirm(driver, record, '强制结束当前操作')
forced = True
record('real-ui-force-confirmed', frames=frames)
signature = json.dumps(queues, sort_keys=True)
if signature != last:
record('queue-state', queues=queues, tasks=database(root, 'select * from tasks'))
last = signature
running = any(entry['state'] == 'running' for q in queues.values() for entry in q['entries'].values())
stop = driver.find(automation_id='stopQueueButton', optional=True)
if pause and not paused and pause_ready(queues) and stop is not None and stop.is_enabled():
observed=pause_evidence(root,[task_id for q in queues.values() for task_id,entry in q['entries'].items()
if entry['state']=='running'])
driver.click(stop)
paused = True
record('pause-requested',observed_before_click=observed)
if not running and queues and resources_settled(root) and (stop is None or not stop.is_enabled()):
if fault and forced and not recovered:
close_results(driver)
recovery = driver.find(automation_id='recoverQuickRunButton')
ui_wait(recovery.is_enabled, timeout=60)
before = saved_uids(root)
before_supervisors = set((root / 'data/batch-resources').glob('*/supervisor.json'))
driver.click(recovery)
confirm(driver, record, '核验并恢复')
ui_wait(lambda: set((root / 'data/batch-resources').glob('*/supervisor.json')) != before_supervisors, timeout=60)
ui_wait(lambda: resources_settled(root) and not control_enabled(driver, 'stopQueueButton'), timeout=1200)
after = saved_uids(root)
assert all(after.get(key) == value for key, value in before.items())
recovered = True
record('real-ui-recovery-finished', saved_uids=after)
break
if any(entry['state']=='blocked' for q in queues.values() for entry in q['entries'].values()):
raise AssertionError('Queue stopped with blocked/uncertain entries; do not replay')
unfinished = any(entry['state'] in {'pending', 'paused'}
for q in queues.values() for entry in q['entries'].values())
if paused and not resumed and unfinished:
before_resume = saved_uids(root)
bindings = queue_bindings(queues)
paused_state = queue_records(root)
record('pause-settled-evidence',observations=pause_evidence(root,
[task_id for q in queues.values() for task_id in q['entries']]),saved_uids=before_resume)
# Close only result windows of this executable to expose resume.
close_results(driver)
ui_wait(lambda: driver.find(automation_id='executeProjectTasks').is_enabled(), timeout=60)
driver.click(driver.find(automation_id='executeProjectTasks'))
confirm(driver, record)
ui_wait(lambda: queue_records(root) != paused_state, timeout=120)
assert queue_bindings(queue_records(root)) == bindings, 'Resume changed queue/task/plan binding'
resumed = True
record('resume-confirmed', saved_uids=before_resume, queue_bindings=bindings)
time.sleep(1)
continue
if all(q.get('phase') == 'finished' for q in queues.values()):
break
if any(entry['state'] in {'blocked', 'paused'}
for q in queues.values() for entry in q['entries'].values()):
raise AssertionError('Queue stopped with blocked/uncertain entries; do not replay')
time.sleep(.5)
else:
raise TimeoutError('Execution deadline; preserve live owned application for inspection')
if pause:
assert paused and resumed, 'Pause/resume was not actually exercised'
if fault:
assert forced and recovered, 'Force/recovery was not actually exercised'
if hold is not None:
raise AssertionError('External resource reference did not reach the completed-business release boundary')
if before_resume is not None:
after = saved_uids(root)
assert all(after.get(key) == count for key, count in before_resume.items()), 'Saved UID replayed'
check_modal()
record('execution-finished', queues=queue_records(root), saved_uids=saved_uids(root))
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--exe', type=Path, required=True)
parser.add_argument('--expected-sha256', help='Reject a rebuilt or unintended candidate before launch')
parser.add_argument('--root', type=Path, required=True)
parser.add_argument('--pid', type=int, help='Attach only to this exact executable process')
parser.add_argument('--stage', choices=('import', 'execute'), default='import')
parser.add_argument('--run-native', action='store_true')
parser.add_argument('--no-pause', action='store_true')
parser.add_argument('--resource-hold', action='store_true', help='Hold one test-owned desktop reference through completed business')
args = parser.parse_args()
if args.stage == 'execute' and not args.run_native:
parser.error('Execution requires --run-native and exclusive CAD slot')
root, executable = args.root.resolve(strict=True), args.exe.resolve(strict=True)
manifest = validate_fixture(root)
fault = next((case.get('fault') for case in manifest['cases'] if case.get('fault')), None)
rule_mode = any(case['kind'] == 'rule_mode' for case in manifest['cases'])
if rule_mode and (len(manifest['cases']) != 1 or args.resource_hold or fault):
parser.error('Rule mode requires one standalone supplemental without force/resource injection')
if (args.resource_hold or fault) and len(manifest['cases']) != 1:
parser.error('Fault/resource supplemental must use one standalone disposable case')
if args.resource_hold and (args.stage != 'execute' or fault):
parser.error('Resource hold requires execute and cannot combine with force fault')
if executable.suffix.lower() != '.exe':
parser.error('A frozen Windows executable is required')
if not args.pid and (root / 'data').exists():
parser.error('New launch requires a fresh data root; use --pid to continue owned UI')
stamp = str(time.time_ns())
report = {'mode': 'frozen EXE external Windows UIA; no source UI or service calls',
'stage': args.stage, 'exe': str(executable), 'exe_sha256': hashlib.sha256(executable.read_bytes()).hexdigest(),
'root': str(root), 'seed': manifest['seed'], 'started_ns': time.time_ns(), 'passed': False, 'steps': []}
if args.expected_sha256 and report['exe_sha256'] != args.expected_sha256.lower():
parser.error('Executable SHA256 does not match the admitted candidate')
process = None
log = (root / ('exe-' + stamp + '.log')).open('w', encoding='utf-8')
try:
if args.pid:
pid = args.pid
validate_session(root, pid, executable, report['exe_sha256'])
else:
command = [str(executable), '--data-root', str(root / 'data')]
temporary = root / 'process-temp'
temporary.mkdir(exist_ok=True)
environment = dict(os.environ, TEMP=str(temporary), TMP=str(temporary))
process = subprocess.Popen(command, cwd=executable.parent, env=environment,
stdout=log, stderr=subprocess.STDOUT)
pid = process.pid
report['command'] = command
report['process_temp'] = str(temporary)
assert process_image(pid) == executable
report['pid'] = pid
write(root / 'ui-session.json', {'pid': pid, 'executable': str(executable), 'exe_sha256': report['exe_sha256']})
driver = WindowDriver(pid, root / 'packaged-recording' / stamp)
def record(step, **details):
driver.record(step)
report['steps'].append({'step': step, 'ns': time.time_ns(), **details})
write(root / 'packaged-ui-report.json', report)
print(json.dumps({'step': step, 'ns': report['steps'][-1]['ns']}, ensure_ascii=False), flush=True)
record('frozen-executable-opened')
disable_automatic_intervention(driver,record)
hold = ExternalDesktopHold(root) if args.resource_hold else None
with PrivateDesktopObserver(root):
try:
if args.stage == 'import':
import_fixture(driver, root, manifest, record)
else:
if not args.pid:
import_fixture(driver, root, manifest, record)
if rule_mode:
verify_rule_mode(root, manifest['cases'][0])
execute_fixture(driver, root, record, pause=not args.no_pause and len(manifest['cases']) > 1
and not fault and hold is None and not rule_mode,
fault=fault, hold=hold)
finally:
if hold is not None:
hold.release()
if args.stage == 'import':
observation = json.loads((root / 'desktop-observation.json').read_text(encoding='utf-8'))
assert not observation['sessions'], 'Import unexpectedly opened Mentor'
assert not queue_records(root), 'Import must not execute any queue'
else:
verify_observation(root / 'desktop-observation.json', require_sessions=not manifest.get('expected_no_cad', False))
if manifest.get('expected_no_cad'):
record('no-cad-user-validation-confirmed', **verify_no_cad_fixture(root, manifest))
assert fingerprint(Path(manifest['source']).parent) == manifest['source_hashes']
assert hashlib.sha256(executable.read_bytes()).hexdigest() == report['exe_sha256']
report['original_source_unchanged'] = report['executable_unchanged'] = True
report['passed'] = True
except BaseException:
report['failure'] = traceback.format_exc()
raise
finally:
report['finished_ns'] = time.time_ns()
write(root / ('packaged-ui-report-' + stamp + '.json'), report)
write(root / 'packaged-ui-report.json', report)
log.close()
# Keep the exact app available for review/continuation; never kill it.
if __name__ == '__main__':
main()