139 lines
9.5 KiB
Python
139 lines
9.5 KiB
Python
"""One real replacement on a NEW disposable copy, then the packaged verification loop."""
|
|
import argparse
|
|
from contextlib import closing
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
import shutil
|
|
import sqlite3
|
|
import subprocess
|
|
import sys
|
|
|
|
ROOT=Path(__file__).resolve().parents[1]
|
|
sys.path[:0]=[str(ROOT),str(ROOT/'src'),str(ROOT/'tools')]
|
|
from dx_productivity.trial_task_center.native_netlist import capture_project,export_netlist,_hash
|
|
from dx_productivity.trial_task_center.store import TaskStore
|
|
from dx_productivity.trial_task_center.service import TaskCenterService
|
|
from dx_productivity.trial_task_center.logging_setup import configure_logging
|
|
from dx_productivity.trial_task_center.bom_plan import write_bom_template
|
|
from verification_closed_loop import require
|
|
|
|
|
|
def main(argv=None):
|
|
parser=argparse.ArgumentParser(description=__doc__)
|
|
for name in ('source','library','exe','output'):parser.add_argument('--'+name,type=Path,required=True)
|
|
args=parser.parse_args(argv)
|
|
source,library,exe=(p.resolve(strict=True) for p in (args.source,args.library,args.exe))
|
|
output=args.output.resolve()
|
|
require(not output.exists() and not output.is_relative_to(source.parent) and not output.is_relative_to(library.parent), 'Use a new external disposable output directory')
|
|
output.mkdir(parents=True)
|
|
original={str(p):_hash(p) for p in source.parent.rglob('*') if p.is_file()}
|
|
original[str(library)]=_hash(library)
|
|
report={'scenario':'actual-saved-replacement-handoff','source':str(source),'library':str(library),
|
|
'executable':str(exe),'executable_sha256':_hash(exe), 'expected':{'refdes':'RV05','old':'4100-CA0000-T7','new':'4100-CA0000-T0','keep':'RV11'}}
|
|
process=driver=window=None
|
|
def rows(query):
|
|
with sqlite3.connect(output/'data/task-center.db') as db:
|
|
db.row_factory=sqlite3.Row
|
|
return [dict(row) for row in db.execute(query)]
|
|
try:
|
|
project_root=output/'projects'/'sample';shutil.copytree(source.parent,project_root)
|
|
project=project_root/source.name
|
|
body,count=re.subn(r'(?m)^KEY CentralLibrary "[^"\r\n]*"',lambda _:f'KEY CentralLibrary "{library.as_posix()}"',project.read_text(encoding='utf-8-sig'))
|
|
require(count==1,'Expected one explicit central library in the sample')
|
|
project.write_text(body,encoding='utf-8')
|
|
before=export_netlist(capture_project(project,output/'baseline-capture'),output/'baseline-export')
|
|
require(before['status']=='success' and before['complete'],'Baseline native export failed')
|
|
components=before['graph']['components']
|
|
target=[c for c in components.values() if c['refdes']=='RV05'];keep=[c for c in components.values() if c['refdes']=='RV11']
|
|
require(len(target)==len(keep)==1 and target[0]['attributes']['Part Number']=='4100-CA0000-T7'
|
|
and keep[0]['attributes']['Part Number']=='4100-CA0000-T7','Sample does not match fixed RV05/RV11 prerequisites')
|
|
store=TaskStore(output/'data/task-center.db')
|
|
try:
|
|
service=TaskCenterService(store,configure_logging(output/'data'),supervised=True)
|
|
task,=service.create_project_tasks(output/'projects',selected_paths=(project,))
|
|
book=write_bom_template(output/'rv05.xlsx',({'project_path':str(project),'old_part_number':'4100-CA0000-T7',
|
|
'new_part_number':'4100-CA0000-T0','refdes':'RV05','enabled':True,'sync_nc':True},))
|
|
imported=service.import_bom_drafts(task.task_id,(book,))
|
|
require(imported.deferred and imported.failed_rows==0,'Pending BOM was not accepted')
|
|
require(not rows('SELECT * FROM execution_operations'),'Preparation unexpectedly executed a replacement')
|
|
finally:store.close()
|
|
(output/'predeclared.json').write_text(json.dumps(dict(report,original_sha256=original),ensure_ascii=False,indent=2),encoding='utf-8')
|
|
import win32gui,win32con
|
|
from packaged_window_driver import WindowDriver,window_image
|
|
from accept_packaged_ui import wait
|
|
env=dict(os.environ)
|
|
for key in ('PYTHONPATH','PYTHONHOME','DX_TASK_CENTER_HOME','QT_QPA_PLATFORM'):env.pop(key,None)
|
|
process=subprocess.Popen([str(exe),'--data-root',str(output/'data')],cwd=exe.parent,env=env,
|
|
stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,creationflags=subprocess.CREATE_NO_WINDOW)
|
|
driver=WindowDriver(process.pid,output)
|
|
def ready():
|
|
try:return driver.main()
|
|
except TimeoutError:return None
|
|
window=wait(ready,timeout=90)
|
|
task_list=wait(lambda:driver.find(automation_id='taskList'),timeout=30)
|
|
candidate=wait(lambda:next((c for c in task_list.children() if task.name in c.window_text()),None),timeout=30)
|
|
driver.click(candidate)
|
|
wait(lambda:source.name in driver.find(automation_id='boundProjectPath').window_text(),timeout=30)
|
|
button=wait(lambda:driver.find(automation_id='executeProjectTasks'),timeout=30)
|
|
wait(button.is_enabled,timeout=30);driver.click(button)
|
|
confirmation=wait(lambda:next((w for w in driver.windows() if w.window_text()=='确认顺序执行本批任务'),None),timeout=30)
|
|
yes=next(b for b in confirmation.descendants(control_type='Button') if b.window_text().replace('&','') in ('Yes','是(Y)','是'))
|
|
window_image(confirmation.handle).save(output/'execution-confirmation.png');driver.click(yes)
|
|
def execution_done():
|
|
tasks=rows('SELECT status,error_id FROM tasks')
|
|
if any(t['status']=='failed' for t in tasks):raise ValueError('Replacement failed; no automatic replay: '+str(tasks))
|
|
return tasks and all(t['status']=='completed' for t in tasks)
|
|
wait(execution_done,timeout=1200)
|
|
require(rows('SELECT COUNT(*) n FROM execution_operations')[0]['n']==1,'Expected exactly one RV05 replacement operation')
|
|
operation=rows('SELECT * FROM execution_operations')[0]
|
|
require(operation['state']=='verified','Replacement was not saved and verified')
|
|
driver.click(driver.find(automation_id='verification_navigation'))
|
|
wait(lambda:len(rows('SELECT item_id FROM verification_items'))==1,timeout=30)
|
|
item=rows('SELECT * FROM verification_items')[0]
|
|
with closing(TaskStore(output/'data/task-center.db')) as store:
|
|
from dx_productivity.trial_task_center.verification.service import VerificationService
|
|
verification=VerificationService(store,output/'data')
|
|
payload=verification.repo.revision(item['item_id'],1)['payload']
|
|
require(payload['input_state']=='ready' and payload['expectation_ref'] is not None,'Real receipt did not deliver frozen before/after/expectations')
|
|
window_image(window.handle).save(output/'automatic-handoff.png')
|
|
win32gui.PostMessage(window.handle,win32con.WM_CLOSE,0,0);require(process.wait(45)==0,'Replacement window did not close normally')
|
|
after=export_netlist(capture_project(project,output/'saved-capture'),output/'saved-export')
|
|
require(after['status']=='success' and after['complete'],'Saved readback native export failed')
|
|
actual={c['refdes']:c for c in after['graph']['components'].values() if c['refdes'] in ('RV05','RV11')}
|
|
require(actual['RV05']['attributes']['Part Number']=='4100-CA0000-T0','RV05 was not replaced')
|
|
require(actual['RV11']==keep[0],'Non-target RV11 changed')
|
|
# Freeze the saved replacement journal; the verification subprocess must leave it intact.
|
|
prior=rows('SELECT * FROM execution_operations')
|
|
command=[sys.executable,'-X','utf8',str(ROOT/'tools/accept_verification_closed_loop.py'),
|
|
'--exe',str(exe),'--before-root',str(output/'projects'),'--after-root',str(output/'projects'),
|
|
'--expected-items',item['display_name'],'--expect-verdict','WARNING','--handoff-data',str(output/'data'),
|
|
'--output',str(output/'verification-loop')]
|
|
completed=subprocess.run(command,cwd=ROOT,timeout=1200,capture_output=True)
|
|
(output/'loop-output.txt').write_bytes(completed.stdout+b'\n'+completed.stderr)
|
|
require(completed.returncode==0,'Packaged handoff loop failed; inspect loop-output.txt')
|
|
require(rows('SELECT * FROM execution_operations')==prior,'Verification changed the replacement journal')
|
|
require(len(rows('SELECT * FROM verification_items'))==1,'Repeated delivery duplicated the project')
|
|
report.update(passed=True,item_id=item['item_id'],replacement_operations=1,verification_replacement_delta=0,
|
|
rv05_replaced=True,rv11_unchanged=True,loop=str(output/'verification-loop/acceptance.json'))
|
|
except Exception as error:
|
|
report.update(passed=False,error=type(error).__name__,reason=str(error))
|
|
if driver:
|
|
for n,w in enumerate(driver.windows()):
|
|
try:window_image(w.handle).save(output/f'failure-{n}.png')
|
|
except Exception:pass
|
|
if process and process.poll() is None and window:
|
|
try:
|
|
win32gui.PostMessage(window.handle,win32con.WM_CLOSE,0,0);process.wait(45)
|
|
except Exception:report['process_left_running']=process.pid
|
|
finally:
|
|
report['originals_unchanged']=all(_hash(Path(p))==sha for p,sha in original.items())
|
|
if not report['originals_unchanged']:report['passed']=False
|
|
(output/'acceptance.json').write_text(json.dumps(report,ensure_ascii=False,indent=2),encoding='utf-8')
|
|
print(json.dumps(report,ensure_ascii=False))
|
|
return 0 if report.get('passed') else 1
|
|
|
|
|
|
if __name__=='__main__':raise SystemExit(main())
|