Files
cbb-refresh-verify-795/tests/test_management_diagnostics.py

143 lines
7.6 KiB
Python

import json
from pathlib import Path
from types import ModuleType, SimpleNamespace
import pytest
def test_raw_dispatch_diagnostics_preserve_hresult_and_known_member_ids(tmp_path):
from cbb_refresh_verify.native_management import _dispatch_diagnostics
class Error(RuntimeError):
hresult = -2147221008
class Raw:
def GetIDsOfNames(self, name):
if name == 'Quit': raise Error('COM apartment unavailable')
return 17 if name == 'Close' else 21
obj = SimpleNamespace(_oleobj_=Raw())
_dispatch_diagnostics(tmp_path, 'before-import', obj, obj)
record = json.loads((tmp_path/'dispatch-diagnostics.jsonl').read_text(encoding='utf-8'))
assert record['members']['application.OnReusableBlocksEditor']['dispid'] == 21
assert record['members']['library.Close']['dispid'] == 17
error = record['members']['application.Quit']['error']
assert error['hresult'] == -2147221008 and error['args'] == ['COM apartment unavailable']
assert error['type'].endswith('Error')
def test_probe_records_dispatch_before_after_import_and_after_source_alignment(tmp_path, monkeypatch):
import cbb_refresh_verify.native_management as native
import sys, os
source = tmp_path/'source/Block.prj'
source.parent.mkdir()
source.write_text('KEY RootBlock "Block"\nKEY PCBDesignPath "PCB/Block.pcb"\n'
'KEY iCDBDir "database"\nKEY CentralLibrary "old.lmc"\n')
(source.parent/'database').mkdir(); (source.parent/'database/icdb.dat').write_bytes(b'fixture')
pcb = source.parent/'PCB/Block.pcb'; (pcb.parent/'Layout').mkdir(parents=True)
pcb.write_text('KEY ProjectFile "../Block.prj"\n')
(pcb.parent/'pcb.prj').write_text('KEY CentralLibrary "old.lmc"\n')
(pcb.parent/'Layout/LayoutDB.lyt').write_bytes(b'fixture')
root = tmp_path/'native-add'; root.mkdir()
library = root/'fixture/mentor_lib.lmc'; library.parent.mkdir(); library.touch()
phase = ['before']
class Raw:
def GetIDsOfNames(self, name): return 1 if phase[0] == 'before' else 2
class App:
_oleobj_ = Raw()
def OnReusableBlocksEditor(self): raise RuntimeError('stop before native UI')
class Uia(ModuleType):
def __getattr__(self, name):
if name == 'Desktop':
phase[0] = 'after'
return None
raise AttributeError(name)
monkeypatch.setitem(sys.modules, 'pywinauto', Uia('pywinauto'))
job = {'operation': 'probe_create_add', 'source': str(source), 'library': str(library),
'name': 'Block', 'timeout_seconds': 0, 'supervisor_pid': os.getpid()}
with pytest.raises(RuntimeError, match='stop before native UI'):
native._probe_add_dialog_impl(App(), job, None, set(), root, library=SimpleNamespace(_oleobj_=Raw()))
records = [json.loads(line) for line in (root/'dispatch-diagnostics.jsonl').read_text(encoding='utf-8').splitlines()]
assert [r['stage'] for r in records] == ['before-pywinauto-import', 'after-pywinauto-import', 'after-source-alignment']
assert records[0]['members']['application.Quit']['dispid'] == 1
assert records[1]['members']['application.Quit']['dispid'] == 2
assert records[2]['paths'] == {'source': str(source), 'pcb': str(pcb), 'library_argument': str(library)}
assert 'old.lmc' not in source.read_text()
@pytest.mark.parametrize('operation', ['probe_create_add', 'probe_readd', 'catalog'])
def test_probe_preloads_uia_before_com_proxy_creation_but_catalog_stays_read_only(tmp_path, monkeypatch, operation):
import sys, win32com.client
import cbb_refresh_verify.native_management as native
import cbb_refresh_verify.mentor_adapter as mentor
root = tmp_path/'job'; root.mkdir()
library_path = tmp_path/'fixture.lmc'; library_path.touch()
events, running = [], [False]
class Uia(ModuleType):
def __getattr__(self, name):
if name == 'Desktop':
events.append('uia-loaded')
return object
raise AttributeError(name)
monkeypatch.setitem(sys.modules, 'pywinauto', Uia('pywinauto'))
library = SimpleNamespace(FullName=str(library_path), FlowType=1,
Partitions=lambda kind: SimpleNamespace(Count=0), Close=lambda: events.append('library-close'))
class App:
def OpenLibrary(self, path): return library
def CreateLibrary(self, path, flow): return library
def Quit(self): events.append('quit'); running[0] = False
def dispatch(progid):
events.append('dispatch'); running[0] = True
return App()
monkeypatch.setattr(win32com.client, 'DispatchEx', dispatch)
monkeypatch.setattr(native, '_current_desktop', lambda:
(SimpleNamespace(EnumDesktopWindows=lambda: []), 'CbbManagement_test'))
monkeypatch.setattr(mentor, '_process_details', lambda name:
[(123, str(tmp_path/'lm/win32/bin/LibraryManager.exe'), '', 0)] if running[0] else [])
monkeypatch.setattr(native, 'prepare_probe_library', lambda *a: library_path)
monkeypatch.setattr(native, 'validate_probe_readd', lambda *a: library_path)
class Disconnected(RuntimeError):
hresult = -2147220995
def editor(*a, **k): raise Disconnected('controlled native failure')
monkeypatch.setattr(native, '_probe_add_dialog', editor)
monkeypatch.setattr(native, '_wait_native_exit', lambda pids: True)
result = native._catalog_native({'operation': operation, 'desktop': 'CbbManagement_test',
'library': str(library_path), 'mentor_home': str(tmp_path), 'probe_token': 'fixture',
'supervisor_pid': __import__('os').getpid()}, root)
assert events[:2] == (['dispatch', 'library-close'] if operation == 'catalog' else ['uia-loaded', 'dispatch'])
if operation == 'catalog':
assert result['success'] and 'uia-loaded' not in events
else:
assert result['exception']['hresult'] == -2147220995
assert result['exception']['args'] == ['controlled native failure']
def test_probe_converts_desktop_pyhandle_before_uia_boundary(tmp_path, monkeypatch):
import sys, win32gui, win32process
import cbb_refresh_verify.native_management as native
import cbb_refresh_verify.management as management
import cbb_refresh_verify.backup_recovery as recovery
source = tmp_path/'source/Block.prj'
source.parent.mkdir()
source.write_bytes(b'file-only UIA boundary fixture')
pcb = source.parent/'PCB/Block.pcb'
root = tmp_path/'native-add'; root.mkdir()
class Handle:
def __int__(self): return 200
handle = Handle()
desktop = SimpleNamespace(EnumDesktopWindows=lambda: [handle])
monkeypatch.setattr(win32process, 'GetWindowThreadProcessId', lambda hwnd: (1, 9))
monkeypatch.setattr(win32gui, 'IsWindowVisible', lambda hwnd: True)
monkeypatch.setattr(win32gui, 'GetWindowText', lambda hwnd: 'Reusable Blocks')
monkeypatch.setattr(management, 'source_project', lambda *a: (source, pcb, 'Block'))
monkeypatch.setattr(recovery, '_align_library', lambda *a: None)
class Desktop:
def __init__(self, **kwargs): pass
def window(self, *, handle):
assert type(handle) is int and handle == 200
raise RuntimeError('integer UIA boundary reached')
monkeypatch.setitem(sys.modules, 'pywinauto', SimpleNamespace(Desktop=Desktop))
app = SimpleNamespace(OnReusableBlocksEditor=lambda: None)
import os
job = {'operation': 'probe_create_add', 'source': str(source), 'name': 'Block', 'supervisor_pid': os.getpid(),
'library': str(root/'fixture/mentor_lib.lmc'), 'timeout_seconds': 5}
with pytest.raises(RuntimeError, match='integer UIA boundary reached'):
native._probe_add_dialog_impl(app, job, desktop, {9}, root)