test: verify Part Label copying through live UI replacement and independent readback
This commit is contained in:
1 parent
65a72c6a3a
commit
2fdbe3acb3
3 files changed
+290
No files matched your search
@@ -0,0 +1,246 @@
|
||||
"""Verify the UI Part Label option and saved attributes on a disposable CAD copy."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import sys
|
||||
import time
|
||||
import traceback
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'src'))
|
||||
|
||||
|
||||
def inspect_native(project, schematic, sheet, destination):
|
||||
import pythoncom
|
||||
import win32com.client
|
||||
from dx_productivity.trial_task_center.cad_identity import project_file_path, verify_application
|
||||
from dx_productivity.trial_task_center.native_helper import attach, attribute_value, components_on_sheet
|
||||
pythoncom.CoInitialize()
|
||||
try:
|
||||
app = win32com.client.GetActiveObject('Viewdraw.Application')
|
||||
verify_application(app, require_view=False)
|
||||
assert not project_file_path(app), 'independent reader cannot take over an open project'
|
||||
assert app.OpenProject(str(project))
|
||||
assert Path(project_file_path(app)).resolve() == project.resolve()
|
||||
document = app.SchematicSheetDocuments().Open(schematic, sheet)
|
||||
document.Activate()
|
||||
app, api = attach() # Certify the active view's owned PID before reading.
|
||||
rows = []
|
||||
for component in components_on_sheet(app, api):
|
||||
if str(component.Refdes) not in {'RV05', 'RV11'}:
|
||||
continue
|
||||
rows.append(dict(uid=str(component.UID), refdes=str(component.Refdes),
|
||||
part_number=attribute_value(component, 'Part Number'),
|
||||
part_label=attribute_value(component, 'Part Label'),
|
||||
value=attribute_value(component, 'Value')))
|
||||
assert len(rows) == 2
|
||||
document.Close(False, '')
|
||||
app.CloseProject()
|
||||
assert not project_file_path(app)
|
||||
destination.write_text(json.dumps(rows, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
finally:
|
||||
pythoncom.CoUninitialize()
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--source', type=Path)
|
||||
parser.add_argument('--library', type=Path)
|
||||
parser.add_argument('--output', type=Path, required=True)
|
||||
parser.add_argument('--inspect-project', type=Path)
|
||||
parser.add_argument('--schematic')
|
||||
parser.add_argument('--sheet')
|
||||
parser.add_argument('--resume', action='store_true')
|
||||
args = parser.parse_args()
|
||||
if args.inspect_project:
|
||||
inspect_native(args.inspect_project, args.schematic, args.sheet, args.output)
|
||||
return 0
|
||||
if not args.source or not args.library:
|
||||
parser.error('--source and --library are required for the live UI probe')
|
||||
os.environ.setdefault('QT_QPA_PLATFORM', 'offscreen')
|
||||
from openpyxl import load_workbook
|
||||
from PySide6.QtCore import QPoint, QThreadPool, Qt
|
||||
from PySide6.QtGui import QFont, QFontDatabase
|
||||
from PySide6.QtTest import QTest
|
||||
from PySide6.QtWidgets import QApplication, QCheckBox, QFileDialog
|
||||
from dx_productivity.trial_task_center.isolated_cad import IsolatedCadSession
|
||||
from dx_productivity.trial_task_center.legacy_paths import cleanup_worker_aliases
|
||||
from dx_productivity.trial_task_center.logging_setup import configure_logging
|
||||
from dx_productivity.trial_task_center.models import TaskStatus
|
||||
from dx_productivity.trial_task_center.service import TaskCenterService
|
||||
from dx_productivity.trial_task_center.store import TaskStore
|
||||
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
|
||||
from private_desktop_observer import PrivateDesktopObserver
|
||||
from probe_bom_live_roundtrip import export_measurements, hashes
|
||||
|
||||
output, source = args.output.resolve(), args.source.resolve(strict=True)
|
||||
assert not output.is_relative_to(source.parent)
|
||||
output.mkdir(parents=True, exist_ok=args.resume)
|
||||
source_hashes = hashes(source)
|
||||
if not args.resume:
|
||||
shutil.copytree(source.parent, output / 'project')
|
||||
project = output / 'project' / source.name
|
||||
text, count = re.subn(r'(?m)^KEY CentralLibrary .*$',
|
||||
lambda _: f'KEY CentralLibrary "{args.library.resolve(strict=True).as_posix()}"',
|
||||
project.read_text(encoding='utf-8-sig'))
|
||||
assert count == 1
|
||||
if not args.resume:
|
||||
project.write_text(text, encoding='utf-8')
|
||||
store = TaskStore(output / 'tasks.db')
|
||||
service = TaskCenterService(store, configure_logging(output / 'data'))
|
||||
app = QApplication.instance() or QApplication([])
|
||||
font_id = QFontDatabase.addApplicationFont(str(Path(os.environ['WINDIR']) / 'Fonts/msyh.ttc'))
|
||||
families = QFontDatabase.applicationFontFamilies(font_id)
|
||||
if families:
|
||||
app.setFont(QFont(families[0], 10))
|
||||
window = TrialTaskCenterWindow(service, quick_run_confirmer=lambda *_: True,
|
||||
close_plan_confirmer=lambda: 'discard')
|
||||
report = (json.loads((output / 'report.json').read_text(encoding='utf-8')) if args.resume else
|
||||
{'source': str(source), 'project': str(project), 'steps': [], 'errors': []})
|
||||
report.pop('error', None)
|
||||
report.pop('verified', None)
|
||||
def record(stage, started=None, **details):
|
||||
entry = {'stage': stage, **details}
|
||||
if started is not None:
|
||||
entry['seconds'] = time.perf_counter() - started
|
||||
report['steps'].append(entry)
|
||||
(output / 'report.json').write_text(json.dumps(report, ensure_ascii=False, indent=2, default=str), encoding='utf-8')
|
||||
print(json.dumps(entry, ensure_ascii=False, default=str), flush=True)
|
||||
def idle():
|
||||
deadline = time.monotonic() + 900
|
||||
while (window._workers or window._loading or window._task_query.busy or window._context_query.busy
|
||||
or window._log_presenter.query.busy or window._feedback_query.busy):
|
||||
if time.monotonic() > deadline:
|
||||
raise TimeoutError('live Part Label UI probe deadline exceeded')
|
||||
app.processEvents()
|
||||
time.sleep(.02)
|
||||
app.processEvents()
|
||||
def click(button):
|
||||
assert button.isEnabled(), button.objectName()
|
||||
if isinstance(button, QCheckBox):
|
||||
QTest.mouseClick(button, Qt.MouseButton.LeftButton, pos=QPoint(8, button.height() // 2))
|
||||
else:
|
||||
QTest.mouseClick(button, Qt.MouseButton.LeftButton)
|
||||
original_error = window._show_error
|
||||
def error_received(error, **options):
|
||||
report['errors'].append(str(error))
|
||||
original_error(error, **options)
|
||||
window._show_error = error_received
|
||||
template, filled = output / 'default-template.xlsx', output / 'part-label-bom.xlsx'
|
||||
original_open, original_save = QFileDialog.getOpenFileName, QFileDialog.getSaveFileName
|
||||
QFileDialog.getSaveFileName = lambda *_a, **_k: (str(template), 'Excel (*.xlsx)')
|
||||
QFileDialog.getOpenFileName = lambda *_a, **_k: (str(filled), 'Excel (*.xlsx)')
|
||||
try:
|
||||
window.show()
|
||||
idle()
|
||||
task = service.tasks()[0] if args.resume else service.create_project_tasks(project.parent)[0]
|
||||
report['task_id'] = task.task_id
|
||||
window.open_task(task.task_id)
|
||||
idle()
|
||||
window.mapping_tabs.setCurrentIndex(1)
|
||||
if not args.resume:
|
||||
click(window.plan_panel.export_bom_button)
|
||||
idle()
|
||||
book = load_workbook(template)
|
||||
worksheet = book.active
|
||||
headers = [cell.value for cell in worksheet[1]]
|
||||
scaffold = dict(zip(headers, next(worksheet.iter_rows(min_row=2, values_only=True))))
|
||||
worksheet.delete_rows(2, worksheet.max_row)
|
||||
row = scaffold | dict(old_part_number='4100-CA0000-T7', new_part_number='4100-CA0000-T0',
|
||||
refdes='RV05', enabled=True, sync_nc=True)
|
||||
worksheet.append([row.get(header, '') for header in headers])
|
||||
book.save(filled)
|
||||
book.close()
|
||||
with PrivateDesktopObserver(output):
|
||||
if not service.target_plan(task.task_id):
|
||||
started = time.perf_counter()
|
||||
click(window.plan_panel.import_bom_button)
|
||||
idle()
|
||||
result = window.plan_panel.last_bom_report
|
||||
assert result and result.preview and result.passed_rows == 1 and not result.failed_rows, report['errors']
|
||||
record('import_bom', started, passed=result.passed_rows, failed=result.failed_rows)
|
||||
click(window.plan_panel.save_button)
|
||||
idle()
|
||||
before = service.target_plan(task.task_id)
|
||||
assert {row.target.refdes for row in before} == {'RV05', 'RV11'}
|
||||
assert sum(row.enabled for row in before) == 1
|
||||
if not window.run_panel.copy_value_check.isChecked():
|
||||
click(window.run_panel.copy_value_check)
|
||||
idle()
|
||||
assert window.run_panel.copy_value_check.isChecked()
|
||||
assert service.get_task(task.task_id).copy_part_number_to_value
|
||||
record('ui_part_label_copy_enabled')
|
||||
window.grab().save(str(output / '01-part-label-enabled.png'))
|
||||
started = time.perf_counter()
|
||||
did_execute = service.get_task(task.task_id).status is not TaskStatus.COMPLETED
|
||||
if did_execute:
|
||||
click(window.run_panel.quick_run_button)
|
||||
idle()
|
||||
assert service.get_task(task.task_id).status is TaskStatus.COMPLETED, report['errors']
|
||||
if did_execute:
|
||||
record('native_replacement_saved_and_reopened', started)
|
||||
else:
|
||||
record('reuse_completed_task_for_readback')
|
||||
window.grab().save(str(output / '02-part-label-completed.png'))
|
||||
facade = service.for_project_task(task.task_id)
|
||||
command = facade._quick_run_preparer.data_root / 'quick-run/command.tsv'
|
||||
fields = command.read_text(encoding='utf-8-sig').splitlines()
|
||||
job = dict(zip(fields[0].split('\t'), fields[1].split('\t')))
|
||||
assert job['value_mode'] == 'part_label'
|
||||
selected = next(row.target for row in before if row.enabled)
|
||||
reader = facade._quick_run_preparer.data_root / 'quick-run-history/sheet-discovery-partlabel-independent'
|
||||
reader.mkdir(parents=True, exist_ok=True)
|
||||
destination = output / 'independent-attributes.json'
|
||||
started = time.perf_counter()
|
||||
with IsolatedCadSession(reader) as session:
|
||||
process = session.start_worker((sys.executable, str(Path(__file__).resolve()),
|
||||
'--inspect-project', str(project), '--schematic', selected.schematic_name,
|
||||
'--sheet', selected.sheet_number, '--output', str(destination)), stdout=-1, stderr=-1)
|
||||
deadline = time.monotonic() + 150
|
||||
while process.poll() is None and time.monotonic() < deadline:
|
||||
time.sleep(.1)
|
||||
if process.poll() is None:
|
||||
raise TimeoutError('independent Part Label read did not finish')
|
||||
stdout, stderr = process.stdout.read(), process.stderr.read()
|
||||
(reader / 'worker-output.txt').write_bytes(stdout + b'\n' + stderr)
|
||||
assert process.poll() == 0, stderr.decode('utf-8', errors='replace')
|
||||
actual = json.loads(destination.read_text(encoding='utf-8'))
|
||||
targets = {row['refdes']: row for row in actual}
|
||||
copied = targets['RV05']
|
||||
assert copied['part_number'] == '4100-CA0000-T0'
|
||||
assert copied['part_label'] and copied['value'] == copied['part_label']
|
||||
for row in before:
|
||||
after = targets[row.target.refdes]
|
||||
assert after['uid'] == row.target.uid
|
||||
if not row.enabled:
|
||||
assert after['part_number'] == row.target.old_part_number and after['value'] == row.target.old_value
|
||||
record('independent_saved_attributes', started, components=actual)
|
||||
observation = json.loads((output / 'desktop-observation.json').read_text(encoding='utf-8'))
|
||||
assert not observation['observer_errors']
|
||||
assert observation['input_desktop_before'] == observation['input_desktop_after']
|
||||
assert not observation['owned_cad_became_foreground'] and not observation['owned_cad_on_input_desktop']
|
||||
assert all(observation['cad_exit_confirmed'].values()) and all(observation['desktop_absent'].values())
|
||||
report['verified'] = True
|
||||
except Exception as error:
|
||||
report['error'] = str(error)
|
||||
traceback.print_exc()
|
||||
finally:
|
||||
idle()
|
||||
report['source_project_unchanged'] = hashes(source) == source_hashes
|
||||
QFileDialog.getOpenFileName, QFileDialog.getSaveFileName = original_open, original_save
|
||||
window.close()
|
||||
QThreadPool.globalInstance().waitForDone()
|
||||
store.close()
|
||||
report['alias_cleanup_errors'] = [str(error) for error in cleanup_worker_aliases()]
|
||||
report['measurements'] = str(export_measurements(output))
|
||||
(output / 'report.json').write_text(json.dumps(report, ensure_ascii=False, indent=2, default=str), encoding='utf-8')
|
||||
print(json.dumps({key: report[key] for key in ('verified', 'error', 'source_project_unchanged') if key in report}), flush=True)
|
||||
return 0 if report.get('verified') and report['source_project_unchanged'] and not report['alias_cleanup_errors'] else 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
Reference in new issue
Block a user