Import CBB refresh verify r4 stability baseline

Preserve tested Verify source, authoritative READY checks, bounded bridge retries, diagnostics and failure-only reporting. Include 336-test suite and packaging assets; exclude live Mentor samples, field logs, backups and distributions.
This commit is contained in:
阿白叔 committed 2026-09-29 15:05:20 +08:00
commit 11a2b2e46e
130 files changed
+19267

No files matched your search

+35
View File
@@ -0,0 +1,35 @@
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
$root = Split-Path $PSScriptRoot -Parent
Import-Module (Join-Path $root 'CBBRefresh.Core.psm1') -Force
function Assert-Equal {
param($Expected, $Actual, [string]$Message)
if ($Expected -ne $Actual) { throw "$Message (expected '$Expected', got '$Actual')" }
}
$before = Read-CbbRefreshStatus -Path (Join-Path $root 'examples\library-verify-before.json')
$next = Get-CbbRefreshNextAction -Status $before
Assert-Equal 'verify_result' $next.State 'yellow Verify state is selected first'
Assert-Equal 'run_cbb_verify' $next.Action 'Verify action is mapped'
if (Test-CbbRefreshAllGreen -Status $before) { throw 'before status must not be all green' }
$green = Read-CbbRefreshStatus -Path (Join-Path $root 'examples\library-verify-green.json')
if (-not (Test-CbbRefreshAllGreen -Status $green)) { throw 'green fixture must be all green' }
$verification = New-CbbRefreshVerification -Status $green -Observations @($green.observations)
Assert-Equal 'PASS' $verification.result 'all green status passes'
Assert-Equal $null $verification.nextAction 'all green status has no next action'
$importer = Get-CbbReuseBlockImporterPath -MentorBin $env:SDD_LM_BIN
if ([IO.Path]::GetFileName($importer) -ne 'ReuseBlockImporter.exe') {
throw 'ReuseBlockImporter path did not resolve to the expected executable.'
}
$threw = $false
try {
Invoke-CbbReuseBlockContentCheck -LmcFile (Join-Path $root 'fixtures\cloned-library\mentor_lib.lmc') `
-BlockName '1GPHY_RTL8211F_A' -LibSpec 'EE7.9' -DmsLoginConfig '' -MentorBin $env:SDD_LM_BIN
}
catch { $threw = $true }
if (-not $threw) { throw 'Empty DMS login configuration must be rejected before launching the checker.' }
Write-Output 'CBB refresh core tests passed.'
+83
View File
@@ -0,0 +1,83 @@
from pathlib import Path
def test_smoke_arguments_exit_zero_and_write_lifecycle_log(tmp_path: Path):
import subprocess, sys
result = subprocess.run([sys.executable, '-m', 'cbb_refresh_verify', '--smoke-test', '--data-root', str(tmp_path)], timeout=30)
assert result.returncode == 0
text = (tmp_path / "logs" / "application.log").read_text(encoding="utf-8")
assert "application_start" in text
assert "application_clean_shutdown" in text
assert "gui_smoke_window_created" in text
def test_module_entrypoint_propagates_main_exit_code():
import subprocess, sys
code = (
"import cbb_refresh_verify.application as a; a.main=lambda: 7; "
"import runpy; runpy.run_module('cbb_refresh_verify.__main__', run_name='__main__')"
)
result = subprocess.run([sys.executable, '-c', code], capture_output=True, text=True)
assert result.returncode == 7
def test_batch_cli_acquires_unc_lease_before_directory_scan(tmp_path, monkeypatch):
import cbb_refresh_verify.application as application
import cbb_refresh_verify.library_reader as library_reader
import cbb_refresh_verify.network_path as network_path
events = []
class Lease:
display_path = r'\\server\share\library'
mentor_path = tmp_path
drive = 'Z:'
remote_root = r'\\server\share'
created = True
def __enter__(self):
events.append('enter')
return self
def __exit__(self, *_args):
events.append('exit')
def close(self):
events.append('close')
class Library:
error = 'stop after path setup'
records = ()
monkeypatch.setattr(application, 'configure', lambda *_args: type('C', (), {
'root': tmp_path,
'logger': type('L', (), {'info': lambda *a, **k: None,
'exception': lambda *a, **k: None,
'handlers': ()})(),
})())
monkeypatch.setattr(network_path, 'LibraryPathLease', type('LP', (), {
'acquire': staticmethod(lambda path: (events.append(('acquire', path)) or Lease()))
}))
monkeypatch.setattr(network_path, 'select_library_file', lambda path: (
events.append(('select', path)) or path
))
# The command exits after the fake reader reports an empty/error library;
# ordering is the contract under test.
monkeypatch.setattr(library_reader, 'read_library_fast', lambda path, **kwargs: Library())
result = application.main(['--batch-lmc', r'\\server\share\library'])
assert result == 1
assert events[:3] == [('acquire', Path(r'\\server\share\library')), 'enter',
('select', tmp_path)]
def test_native_log_helper_mode_does_not_load_ui_or_mgcpcb(tmp_path, monkeypatch):
import json
import cbb_refresh_verify.application as application
request = tmp_path/'request.json'
pcb = tmp_path/'Work/PCB/test.pcb'
pcb.parent.mkdir(parents=True)
request.write_text(json.dumps({'root': str(tmp_path), 'pcb': str(pcb)}), encoding='utf-8')
monkeypatch.setattr(application, 'configure', lambda *_: (_ for _ in ()).throw(
AssertionError('log capture must not create a GUI/logger session')))
result = application.main(['--collect-failure-logs', str(request)])
assert result == 0
assert (tmp_path/'diagnostics/native-logs.json').is_file()
+61
View File
@@ -0,0 +1,61 @@
import pytest
from cbb_refresh_verify.pcb_bridge import AutomationLicenseError, validate_document
class FakeDocument:
def __init__(self):
self.validate_calls = []
def Validate(self, value):
self.validate_calls.append(value)
return 1234 if value == 0 else True
class FakeLicenseApp:
def __init__(self):
self.keys = []
def GetToken(self, key):
self.keys.append(key)
return 5678
def test_validate_uses_official_automation_token_without_logging_token():
document = FakeDocument()
license_app = FakeLicenseApp()
events = []
validate_document(document, lambda: license_app, emit=lambda **event: events.append(event))
assert document.validate_calls == [0, 5678]
assert license_app.keys == [1234]
assert [event['stage'] for event in events] == [
'license_key_requested', 'license_token_received', 'document_validated'
]
assert '5678' not in repr(events)
def test_unregistered_licensing_server_allows_ui_fallback():
class ComFailure(Exception):
hresult = -2147221164 # REGDB_E_CLASSNOTREG
with pytest.raises(AutomationLicenseError) as raised:
validate_document(FakeDocument(), lambda: (_ for _ in ()).throw(ComFailure('missing')))
assert raised.value.fallback_allowed is True
assert raised.value.error_code == 'AUTOMATION_LICENSE_UNAVAILABLE'
def test_rejected_license_token_is_fatal_not_ui_fallback():
class RejectingDocument(FakeDocument):
def Validate(self, value):
if value:
raise RuntimeError('token rejected')
return super().Validate(value)
with pytest.raises(AutomationLicenseError) as raised:
validate_document(RejectingDocument(), lambda: FakeLicenseApp())
assert raised.value.fallback_allowed is False
assert raised.value.error_code == 'AUTOMATION_LICENSE_REJECTED'
+174
View File
@@ -0,0 +1,174 @@
from pathlib import Path
from cbb_refresh_verify.batch_status import (BatchCheckpoint, BatchStatusSession,
fingerprint_library)
from cbb_refresh_verify.status_bridge import BridgeResponseError, BridgeResult
def test_fingerprint_changes_when_lmc_changes(tmp_path):
lmc = tmp_path / "mentor_lib.lmc"
lmc.write_bytes(b"one")
first = fingerprint_library(lmc)
lmc.write_bytes(b"two")
second = fingerprint_library(lmc)
assert first.sha256 != second.sha256
def test_fingerprint_preserves_mapped_drive_without_resolve(tmp_path, monkeypatch):
lmc = tmp_path / 'mentor_lib.lmc'
lmc.write_bytes(b'library')
monkeypatch.setattr(
Path,
'resolve',
lambda self: (_ for _ in ()).throw(AssertionError(f'resolve called: {self}')),
)
assert fingerprint_library(lmc).sha256
def test_fingerprint_changes_when_top_level_block_set_changes(tmp_path):
lmc = tmp_path / "mentor_lib.lmc"
lmc.write_bytes(b"library")
root = tmp_path / "ReusableBlocksLP"
(root / "CBB_A").mkdir(parents=True)
first = fingerprint_library(lmc)
(root / "CBB_B").mkdir()
second = fingerprint_library(lmc)
assert first.sha256 != second.sha256
def test_fingerprint_does_not_walk_cbb_descendants(tmp_path, monkeypatch):
import cbb_refresh_verify.batch_status as batch_status
lmc = tmp_path / "mentor_lib.lmc"
lmc.write_bytes(b"library")
root = tmp_path / "ReusableBlocksLP"
(root / "CBB_A" / "Work").mkdir(parents=True)
real_scandir = batch_status.os.scandir
def guarded_scandir(path):
if Path(path) != root:
raise AssertionError(f"descendant scan: {path}")
return real_scandir(path)
monkeypatch.setattr(batch_status.os, "scandir", guarded_scandir)
assert fingerprint_library(lmc).sha256
def test_checkpoint_ignores_truncated_json_line(tmp_path):
path = tmp_path / "scan.jsonl"
path.write_text('{"block_name":"A","status":"READY"}\n{"block_name":"B"', encoding="utf-8")
checkpoint = BatchCheckpoint.load(path)
assert checkpoint.completed_names == {"A"}
class FakeBridge:
def __init__(self, timeout_name=None):
self.requests = []
self.timeout_name = timeout_name
def query(self, lmc_file, block_name, *, block_type="RULP", timeout_seconds=10):
self.requests.append(block_name)
if block_name == self.timeout_name:
raise BridgeResponseError("状态桥响应超时")
return BridgeResult("READY" if block_name == "A" else "PENDING", "fake")
def test_scan_reuses_checkpoint_and_queries_only_missing(tmp_path):
lmc = tmp_path / "mentor_lib.lmc"
lmc.write_bytes(b"library")
checkpoint = tmp_path / "scan.jsonl"
fingerprint = fingerprint_library(lmc).sha256
checkpoint.write_text(
'{"block_name":"A","status":"READY","fingerprint":"' + fingerprint + '"}\n',
encoding="utf-8",
)
bridge = FakeBridge()
records = BatchStatusSession(bridge).scan(["A", "B"], lmc, checkpoint)
assert bridge.requests == ["B"]
assert {record.block_name for record in records} == {"A", "B"}
def test_timeout_isolated_and_later_item_continues(tmp_path):
lmc = tmp_path / "mentor_lib.lmc"
lmc.write_bytes(b"library")
bridge = FakeBridge(timeout_name="A")
records = BatchStatusSession(bridge, timeout_seconds=0.1).scan(
["A", "B"], lmc, tmp_path / "scan.jsonl")
assert records[0].status == "TIMEOUT"
assert records[1].status == "PENDING"
def test_protocol_path_mismatch_stops_repeating_same_global_failure(tmp_path):
class BrokenProtocolBridge:
def __init__(self):
self.requests = []
def query(self, lmc_file, block_name, **kwargs):
self.requests.append(block_name)
raise BridgeResponseError('状态桥中心库路径不匹配')
lmc = tmp_path / 'mentor_lib.lmc'
lmc.write_bytes(b'library')
bridge = BrokenProtocolBridge()
records = BatchStatusSession(bridge).scan(
['A', 'B', 'C'], lmc, tmp_path / 'scan.jsonl'
)
assert bridge.requests == ['A']
assert [record.status for record in records] == ['MALFORMED'] * 3
def test_authoritative_status_map_marks_missing_bridge_unavailable(tmp_path, monkeypatch):
import cbb_refresh_verify.batch_status as batch_status
from cbb_refresh_verify.status_bridge import BridgeUnavailable
class MissingBridge:
def __init__(self, *args, **kwargs):
pass
def start(self):
raise BridgeUnavailable(tmp_path / "missing.exe")
def restart(self):
raise BridgeUnavailable(tmp_path / "missing.exe")
def close(self):
pass
monkeypatch.setattr(batch_status, "StatusBridgeServer", MissingBridge)
lmc = tmp_path / "mentor_lib.lmc"
lmc.write_bytes(b"library")
result = batch_status.authoritative_status_map(
["A", "B"], lmc, tmp_path / "scan.jsonl")
assert result == {"A": "UNAVAILABLE", "B": "UNAVAILABLE"}
def test_authoritative_status_map_never_reuses_previous_scan_status(tmp_path, monkeypatch):
import cbb_refresh_verify.batch_status as batch_status
calls = []
class Bridge:
def __init__(self, *args, **kwargs):
pass
def start(self):
pass
def restart(self):
pass
def close(self):
pass
def query(self, lmc_file, block_name, **kwargs):
calls.append(block_name)
status = 'PENDING' if len(calls) == 1 else 'READY'
return BridgeResult(status, 'fake')
monkeypatch.setattr(batch_status, 'StatusBridgeServer', Bridge)
lmc = tmp_path / 'mentor_lib.lmc'
lmc.write_bytes(b'library')
checkpoint = tmp_path / 'scan.jsonl'
first = batch_status.authoritative_status_map(['A'], lmc, checkpoint)
second = batch_status.authoritative_status_map(['A'], lmc, checkpoint)
assert first == {'A': 'PENDING'}
assert second == {'A': 'READY'}
assert calls == ['A', 'A']
+86
View File
@@ -0,0 +1,86 @@
import json
import sys
import textwrap
from cbb_refresh_verify.batch_status import BatchStatusSession, fingerprint_library
from cbb_refresh_verify.status_bridge import StatusBridgeServer
def make_bridge_script(tmp_path, body):
script = tmp_path / "fault_bridge.py"
script.write_text(textwrap.dedent(body), encoding="utf-8")
return script
def test_malformed_response_does_not_stop_later_item(tmp_path):
script = make_bridge_script(tmp_path, '''
import json, sys
for line in sys.stdin:
item = json.loads(line)
if item["block_name"] == "BAD":
print("not-json", flush=True)
else:
print(json.dumps({"ok": True, "request_id": item["request_id"],
"block_name": item["block_name"], "lmc_file": item["lmc_file"],
"status": "PENDING", "source": "fake"}), flush=True)
''')
lmc = tmp_path / "x.lmc"; lmc.write_bytes(b"x")
bridge = StatusBridgeServer(script)
records = BatchStatusSession(bridge).scan(["BAD", "GOOD"], lmc, tmp_path / "scan.jsonl")
assert records[0].status == "ERROR"
assert records[1].status == "PENDING"
def test_bridge_exit_does_not_stop_later_item(tmp_path):
script = make_bridge_script(tmp_path, '''
import json, sys
for line in sys.stdin:
item = json.loads(line)
if item["block_name"] == "EXIT":
sys.exit(7)
print(json.dumps({"ok": True, "request_id": item["request_id"],
"block_name": item["block_name"], "lmc_file": item["lmc_file"],
"status": "READY", "source": "fake"}), flush=True)
''')
lmc = tmp_path / "x.lmc"; lmc.write_bytes(b"x")
records = BatchStatusSession(StatusBridgeServer(script)).scan(
["EXIT", "GOOD"], lmc, tmp_path / "scan.jsonl")
assert records[0].status == "ERROR"
assert records[1].status == "READY"
def test_timeout_on_item_seventeen_continues(tmp_path):
script = make_bridge_script(tmp_path, '''
import json, sys, time
for line in sys.stdin:
item = json.loads(line)
if item["block_name"] == "N17":
time.sleep(0.5)
print(json.dumps({"ok": True, "request_id": item["request_id"],
"block_name": item["block_name"], "lmc_file": item["lmc_file"],
"status": "PENDING", "source": "fake"}), flush=True)
''')
lmc = tmp_path / "x.lmc"; lmc.write_bytes(b"x")
names = [f"N{i}" for i in range(1, 18)] + ["N18"]
records = BatchStatusSession(StatusBridgeServer(script), timeout_seconds=0.1).scan(
names, lmc, tmp_path / "scan.jsonl")
assert records[16].status == "TIMEOUT"
assert records[17].status == "PENDING"
def test_fingerprint_change_does_not_reuse_checkpoint(tmp_path):
lmc = tmp_path / "x.lmc"; lmc.write_bytes(b"one")
checkpoint = tmp_path / "scan.jsonl"
first = fingerprint_library(lmc).sha256
checkpoint.write_text(json.dumps({"block_name": "A", "status": "READY",
"fingerprint": first}) + "\n", encoding="utf-8")
lmc.write_bytes(b"two")
class Bridge:
def __init__(self): self.requests = []
def query(self, lmc_file, block_name, **kwargs):
self.requests.append(block_name)
from cbb_refresh_verify.status_bridge import BridgeResult
return BridgeResult("PENDING", "fake")
bridge = Bridge()
BatchStatusSession(bridge).scan(["A"], lmc, checkpoint)
assert bridge.requests == ["A"]
+447
View File
@@ -0,0 +1,447 @@
import threading
from cbb_refresh_verify import application
from cbb_refresh_verify.dialog_agent import (
ActionResult,
DialogActionExecutor,
DialogAgentClient,
DialogAgentServer,
)
from cbb_refresh_verify.dialog_models import (
ControlSnapshot,
DialogPhase,
WindowSnapshot,
stable_fingerprint,
compatible_window_identity,
)
def snapshot(title="Prompt"):
return WindowSnapshot(
hwnd=10,
pid=20,
process_name="ExpeditionPCB.exe",
process_role="pcb",
window_class="GXWND",
title=title,
phase=DialogPhase.PCB_STARTING,
controls=(ControlSnapshot(11, 1, "Button", "OK", control_type="Button"),),
)
class FakeProbe:
def __init__(self, value):
self.value = value
def capture(self, phase):
return (self.value,) if self.value is not None else ()
def capture_one(self, hwnd, phase):
return self.value if self.value is not None and self.value.hwnd == hwnd else None
class FakeExecutor:
def __init__(self):
self.calls = []
def perform(self, snapshot_value, action):
self.calls.append((snapshot_value, action))
return ActionResult(channel="uia_invoke", accepted_controls=(1,))
def running_protocol(tmp_path, probe, executor=None):
client = DialogAgentClient.prepare(tmp_path, desktop_name="test", timeout_seconds=2)
server = DialogAgentServer.from_config(client.paths.config, probe=probe, executor=executor)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
return client, server, thread
def test_agent_correlates_observe_response_by_request_id(tmp_path):
client, server, thread = running_protocol(tmp_path, FakeProbe(snapshot()))
try:
reply = client.observe(DialogPhase.PCB_STARTING)
finally:
client.close()
thread.join(timeout=2)
assert reply[0].window_class == "GXWND"
assert server.requests[0]["request_id"] == server.responses[0]["request_id"]
assert server.responses[0]["sequence"] == 1
def test_agent_rejects_stale_action_fingerprint(tmp_path):
executor = FakeExecutor()
client, _server, thread = running_protocol(tmp_path, FakeProbe(snapshot("Changed")), executor)
try:
result = client.perform(
hwnd=10,
fingerprint=stable_fingerprint(snapshot("Old")),
action={"channels": ["uia_invoke"], "action": "confirm"},
phase=DialogPhase.PCB_STARTING,
)
finally:
client.close()
thread.join(timeout=2)
assert result.error_code == "STALE_DIALOG"
assert executor.calls == []
def test_agent_perform_uses_observed_snapshot_when_refresh_probe_blocks(tmp_path):
class BlockingRefreshProbe(FakeProbe):
def capture_one(self, hwnd, phase):
raise RuntimeError("refresh probe blocked by native license dialog")
executor = FakeExecutor()
value = snapshot()
client, server, thread = running_protocol(
tmp_path, BlockingRefreshProbe(value), executor
)
try:
observed = client.observe(DialogPhase.PCB_STARTING)
result = client.perform(
hwnd=value.hwnd,
fingerprint=stable_fingerprint(observed[0]),
action={"channels": ["uia_invoke"], "action": "confirm"},
phase=DialogPhase.PCB_STARTING,
)
finally:
client.close()
thread.join(timeout=2)
assert result.accepted_controls == (1,)
assert executor.calls == [(value, {"channels": ["uia_invoke"], "action": "confirm"})]
def test_window_identity_allows_control_tree_changes_during_initialization():
original = snapshot('')
changed = WindowSnapshot(
hwnd=original.hwnd,
pid=original.pid,
process_name=original.process_name,
process_role=original.process_role,
window_class=original.window_class,
title=original.title,
phase=original.phase,
controls=original.controls + (
ControlSnapshot(12, 2, 'Button', 'Cancel', control_type='Button'),
),
)
assert compatible_window_identity(original, changed)
def test_hidden_agent_route_runs_before_qt(monkeypatch, tmp_path):
called = []
monkeypatch.setattr(
"cbb_refresh_verify.dialog_agent.dialog_agent_main",
lambda path: called.append(path) or 17,
)
code = application.main(["--dialog-agent", str(tmp_path / "agent.json")])
assert code == 17
assert called == [tmp_path / "agent.json"]
def test_desktop_worker_companion_uses_same_desktop_and_job(monkeypatch):
import cbb_refresh_verify.desktop_worker as module
starts = []
assignments = []
class Startup:
lpDesktop = ""
class Handle:
def Close(self):
pass
monkeypatch.setattr(module.win32process, "STARTUPINFO", Startup)
monkeypatch.setattr(
module.win32process,
"CreateProcess",
lambda *args: starts.append(args) or (Handle(), Handle(), 321, 1),
)
monkeypatch.setattr(
module.win32job,
"AssignProcessToJobObject",
lambda job, handle: assignments.append((job, handle)),
)
worker = module.DesktopWorker.__new__(module.DesktopWorker)
worker.name = "PrivateDesk"
worker.job = object()
worker.job_bound = True
worker.companions = []
pid = worker.start_companion(["python", "--dialog-agent", "config.json"])
assert pid == 321
assert starts[0][-1].lpDesktop == "winsta0\\PrivateDesk"
assert assignments and len(worker.companions) == 1
def test_license_action_selects_unique_uia_license_before_ok():
selected = []
class Wrapper:
def select(self): selected.append('license')
controls = (
ControlSnapshot(11, 1522, 'GXWND', 'Product license', control_type='ListItem',
patterns=('SelectionItem',)),
ControlSnapshot(12, 1, 'Button', 'OK', control_type='Button', patterns=('Invoke',)),
)
value = snapshot()
value = WindowSnapshot(**{**value.__dict__, 'controls': controls})
executor = DialogActionExecutor(uia_wrapper=lambda _handle: Wrapper())
result = executor.perform(value, {
'action': 'accept_license',
'channels': ['uia_select', 'uia_invoke', 'win32_button_click'],
})
assert result.channel == 'uia_select'
assert result.accepted_controls == (1522,)
assert selected == ['license']
def test_license_action_invokes_ok_only_after_selection():
invoked = []
class Wrapper:
def invoke(self): invoked.append('ok')
controls = (
ControlSnapshot(11, 1522, 'GXWND', 'Product license', control_type='ListItem',
selected=True, patterns=('SelectionItem',)),
ControlSnapshot(12, 1, 'Button', 'OK', control_type='Button', patterns=('Invoke',)),
)
value = snapshot()
value = WindowSnapshot(**{**value.__dict__, 'controls': controls})
executor = DialogActionExecutor(uia_wrapper=lambda _handle: Wrapper())
result = executor.perform(value, {
'action': 'accept_license',
'channels': ['uia_select', 'uia_invoke', 'win32_button_click'],
})
assert result.channel == 'uia_invoke'
assert result.accepted_controls == (1,)
assert invoked == ['ok']
def test_license_selector_can_use_targeted_private_window_message():
messages = []
class Gui:
def PostMessage(self, hwnd, message, wparam, lparam):
messages.append((hwnd, message, wparam, lparam))
value = snapshot('')
controls = (
ControlSnapshot(11, 5225, 'Button', 'Select the desired product license',
control_type='Button'),
ControlSnapshot(12, 1, 'Button', 'OK', control_type='Button'),
)
value = WindowSnapshot(**{**value.__dict__, 'controls': controls})
executor = DialogActionExecutor(win32gui=Gui(), uia_wrapper=lambda _handle: (_ for _ in ()).throw(RuntimeError('uia unavailable')))
result = executor.perform(value, {
'action': 'accept_license',
'channels': ['win32_mouse_click'],
})
assert result.channel == 'win32_mouse_click'
assert result.accepted_controls == (1,)
assert [item[0] for item in messages] == [12, 12]
def test_license_selector_sends_center_click_and_parent_command_for_custom_button():
posted = []
sent = []
class Gui:
def GetWindowRect(self, hwnd):
assert hwnd == 12
return (100, 200, 180, 240)
def PostMessage(self, hwnd, message, wparam, lparam):
posted.append((hwnd, message, wparam, lparam))
def SendMessage(self, hwnd, message, wparam, lparam):
sent.append((hwnd, message, wparam, lparam))
value = snapshot('')
controls = (
ControlSnapshot(11, 5225, 'Button', 'Select the desired product license',
control_type='Button'),
ControlSnapshot(12, 1, 'Button', 'OK', control_type='Button'),
)
value = WindowSnapshot(**{**value.__dict__, 'hwnd': 99, 'controls': controls})
executor = DialogActionExecutor(win32gui=Gui(), uia_wrapper=lambda _handle: (_ for _ in ()).throw(RuntimeError('uia unavailable')))
result = executor.perform(value, {
'action': 'accept_license',
'channels': ['win32_mouse_click'],
})
assert result.channel == 'win32_mouse_click'
assert result.accepted_controls == (1,)
assert posted == []
assert sent == [(12, 0x0201, 1, (20 << 16) | 40),
(12, 0x0202, 0, (20 << 16) | 40),
(99, 0x0111, 1, 12)]
def test_license_action_targets_ok_when_license_pane_has_no_selectable_item():
controls = (
ControlSnapshot(11, 5225, 'Button', 'Select the desired product license',
control_type='Group'),
ControlSnapshot(12, 1522, 'GXWND', 'Select the desired product license',
control_type='Pane'),
ControlSnapshot(13, 1, 'Button', 'OK', control_type='Button'),
)
value = snapshot('')
value = WindowSnapshot(**{**value.__dict__, 'controls': controls})
executor = DialogActionExecutor(
win32gui=type('Gui', (), {'PostMessage': lambda *_args: None})(),
uia_wrapper=lambda _handle: (_ for _ in ()).throw(RuntimeError('uia unavailable')),
)
result = executor.perform(value, {
'action': 'accept_license',
'channels': ['win32_mouse_click'],
})
assert result.accepted_controls == (1,)
def test_license_ok_button_prefers_nonblocking_win32_button_click():
class Gui:
def __init__(self):
self.messages = []
def PostMessage(self, hwnd, message, wparam, lparam):
self.messages.append((hwnd, message, wparam, lparam))
value = snapshot('')
controls = (
ControlSnapshot(11, 5225, 'Button', 'Select the desired product license',
control_type='Button'),
ControlSnapshot(12, 1, 'Button', 'OK', control_type='Button'),
)
value = WindowSnapshot(**{**value.__dict__, 'controls': controls})
gui = Gui()
executor = DialogActionExecutor(
win32gui=gui,
uia_wrapper=lambda _handle: (_ for _ in ()).throw(RuntimeError('uia unavailable')),
)
result = executor.perform(value, {
'action': 'accept_license',
'channels': ['interface', 'uia_select', 'uia_invoke',
'win32_button_click', 'win32_mouse_click'],
})
assert result.channel == 'win32_button_click'
assert result.accepted_controls == (1,)
assert gui.messages and gui.messages[0][0] == 12
def test_database_restoration_selects_last_user_saved_before_ok():
selected = []
posted = []
class Wrapper:
def select(self):
selected.append('last-saved')
class Gui:
def PostMessage(self, hwnd, message, wparam, lparam):
posted.append((hwnd, message, wparam, lparam))
controls = (
ControlSnapshot(11, 6213, 'Button',
'Load the last user saved database dated 2026/9/24 22:52.',
control_type='RadioButton', patterns=('SelectionItem',)),
ControlSnapshot(12, 6206, 'Button',
'Load the autosave database dated 2026/9/24 22:52.',
control_type='RadioButton', selected=True,
patterns=('SelectionItem',)),
ControlSnapshot(13, 1, 'Button', 'OK', control_type='Button',
patterns=('Invoke',)),
)
value = snapshot('Database Restoration')
value = WindowSnapshot(**{**value.__dict__, 'controls': controls})
executor = DialogActionExecutor(win32gui=Gui(), uia_wrapper=lambda _handle: Wrapper())
result = executor.perform(value, {
'action': 'restore_last_saved',
'channels': ['uia_select', 'win32_button_click', 'uia_invoke'],
})
assert result.channel == 'win32_button_click'
assert result.accepted_controls == (6213,)
assert selected == []
assert posted and posted[0][0] == 11
def test_agent_polling_does_not_write_request_response_capture_files(tmp_path):
client, server, thread = running_protocol(tmp_path, FakeProbe(snapshot()))
try:
for _ in range(80):
assert client.observe(DialogPhase.PCB_STARTING)[0].hwnd == 10
assert not list(tmp_path.glob('*.jsonl'))
assert len(server.requests) <= 1
assert len(server.responses) <= 1
finally:
client.close()
thread.join(timeout=2)
assert not thread.is_alive()
def test_agent_start_failure_releases_listener(tmp_path):
import pytest
class FailedWorker:
name = 'test'
def start_companion(self, command):
raise RuntimeError('cannot create companion')
with pytest.raises(RuntimeError, match='cannot create companion'):
DialogAgentClient.start(FailedWorker(), tmp_path)
def test_memory_channel_timeout_is_bounded_and_partial_packets_survive():
import socket
import pytest
from cbb_refresh_verify.dialog_agent import JsonChannel
a, b = socket.socketpair()
channel = JsonChannel(a)
try:
b.sendall(b'{"value":')
with pytest.raises(TimeoutError):
channel.receive(.05)
b.sendall(b'17}\n')
assert channel.receive(.5) == {'value': 17}
b.close()
with pytest.raises(EOFError):
channel.receive(.5)
finally:
channel.close()
b.close()
def test_loopback_connection_rejects_wrong_agent_token(tmp_path):
import socket
import pytest
from cbb_refresh_verify.dialog_agent import JsonChannel, DialogAgentProtocolError
client = DialogAgentClient.prepare(tmp_path, desktop_name='test', timeout_seconds=.3)
wrong = JsonChannel(socket.create_connection(('127.0.0.1', client.paths.port), timeout=1))
try:
wrong.send({'token': 'not-the-agent'})
with pytest.raises(DialogAgentProtocolError, match='authentication failed'):
client.observe(DialogPhase.PCB_STARTING)
finally:
wrong.close()
client.close()
+53
View File
@@ -0,0 +1,53 @@
from cbb_refresh_verify.dialog_models import (
ControlSnapshot,
DialogPhase,
WindowSnapshot,
stable_fingerprint,
)
def snapshot(*, hwnd=10, pid=20, text="Elapsed time 11 C:\\A\\x.pcb",
control_types=("Button",)):
controls = tuple(
ControlSnapshot(
handle=100 + index,
control_id=index + 1,
class_name=control_type,
name=text if index == 0 else control_type,
control_type=control_type,
)
for index, control_type in enumerate(control_types)
)
return WindowSnapshot(
hwnd=hwnd,
pid=pid,
process_name="ExpeditionPCB.exe",
process_role="pcb",
window_class="#32770",
title="Expedition PCB",
phase=DialogPhase.PROJECT_INTEGRATION,
controls=controls,
)
def test_fingerprint_ignores_handle_pid_paths_and_elapsed_numbers():
first = snapshot(hwnd=10, pid=20, text="Elapsed time 11 C:\\A\\x.pcb")
second = snapshot(hwnd=99, pid=77, text="Elapsed time 42 D:\\B\\y.pcb")
assert stable_fingerprint(first) == stable_fingerprint(second)
def test_fingerprint_changes_for_control_shape():
assert stable_fingerprint(snapshot(control_types=("Button",))) != stable_fingerprint(
snapshot(control_types=("Button", "List"))
)
def test_snapshot_json_round_trip_preserves_original_evidence():
original = snapshot(text="数据库恢复 C:\\Work\\A.pcb")
restored = WindowSnapshot.from_record(original.to_record())
assert restored == original
assert restored.controls[0].name == "数据库恢复 C:\\Work\\A.pcb"
+169
View File
@@ -0,0 +1,169 @@
import pywintypes
from cbb_refresh_verify.dialog_models import DialogPhase
from cbb_refresh_verify.dialog_probe import WindowProbe
PHASE = DialogPhase.PCB_STARTING
class FakeDesktop:
def __init__(self, handles=()):
self.handles = tuple(handles)
def EnumDesktopWindows(self):
return self.handles
class FakeGui:
def __init__(self, windows, children=None, disappearing=()):
self.windows = windows
self.children = children or {}
self.disappearing = set(disappearing)
self.callback_results = []
def IsWindowVisible(self, hwnd):
return self.windows[hwnd].get("visible", True)
def GetClassName(self, hwnd):
return self.windows[hwnd].get("class_name", "")
def GetWindowText(self, hwnd):
if hwnd in self.disappearing:
raise pywintypes.error(1400, "GetWindowText", "invalid window")
return self.windows[hwnd].get("text", "")
def GetDlgCtrlID(self, hwnd):
return self.windows[hwnd].get("control_id", 0)
def IsWindowEnabled(self, hwnd):
return self.windows[hwnd].get("enabled", True)
def GetWindow(self, hwnd, _command):
return self.windows[hwnd].get("owner", 0)
def EnumChildWindows(self, hwnd, callback, context):
for child in self.children.get(hwnd, ()):
self.callback_results.append(callback(child, context))
def SendMessage(self, *_args):
return 0
class FakeProcess:
@staticmethod
def GetWindowThreadProcessId(hwnd):
return 1, 1000 + hwnd
class FakeUia:
def __init__(self, records=None, error=None):
self.records = records or {}
self.error = error
def controls(self, hwnd):
if self.error:
raise self.error
return self.records.get(hwnd, ())
def make_probe(gui, handles, uia=None):
return WindowProbe(
desktop=FakeDesktop(handles),
win32gui=gui,
win32process=FakeProcess(),
process_name_reader=lambda pid: f"proc-{pid}.exe",
uia=uia or FakeUia(),
)
def test_probe_keeps_visible_non_dialog_classes():
gui = FakeGui({10: {"class_name": "GXWND", "text": "License chooser"}})
snapshots = make_probe(gui, (10,)).capture(PHASE)
assert [item.window_class for item in snapshots] == ["GXWND"]
assert snapshots[0].process_name == "proc-1010.exe"
def test_disappearing_window_is_skipped_without_hiding_other_windows():
gui = FakeGui({
10: {"class_name": "GXWND", "text": "gone"},
20: {"class_name": "#32770", "text": "still here"},
}, disappearing=(10,))
snapshots = make_probe(gui, (10, 20)).capture(PHASE)
assert [item.hwnd for item in snapshots] == [20]
def test_uia_enrichment_records_patterns_and_automation_id():
gui = FakeGui({10: {"class_name": "GXWND", "text": "License chooser"}})
uia = FakeUia({10: ({
"handle": 101,
"control_id": 1522,
"class_name": "GXWND",
"name": "Product license",
"automation_id": "licenseList",
"control_type": "ListItem",
"enabled": True,
"selected": True,
"checked": False,
"patterns": ("SelectionItem",),
},)})
control = make_probe(gui, (10,), uia).capture(PHASE)[0].controls[0]
assert control.automation_id == "licenseList"
assert control.patterns == ("SelectionItem",)
assert control.selected is True
def test_uia_failure_keeps_win32_evidence_and_adds_diagnostic():
windows = {
10: {"class_name": "#32770", "text": "Prompt"},
11: {"class_name": "Button", "text": "OK", "control_id": 1},
}
gui = FakeGui(windows, children={10: (11,)})
snapshot = make_probe(gui, (10,), FakeUia(error=RuntimeError("uia down"))).capture(PHASE)[0]
assert snapshot.controls[0].name == "OK"
assert snapshot.diagnostics == ("UIA_ERROR: uia down",)
assert gui.callback_results == [True]
def test_empty_private_desktop_winerror_two_is_transient():
class EmptyDesktop:
@staticmethod
def EnumDesktopWindows():
raise pywintypes.error(2, "EnumDesktopWindows", "file not found")
probe = WindowProbe(
desktop=EmptyDesktop(), win32gui=object(), win32process=object(),
process_name_reader=lambda _pid: "", uia=FakeUia(),
)
assert probe.capture(PHASE) == ()
def test_probe_ignores_input_indicator_afx_and_hidden_ie_windows():
gui = FakeGui({
10: {"class_name": "UAC_InputIndicatorOverlayWnd", "text": ""},
20: {"class_name": "UAC Input Indicator", "text": ""},
30: {"class_name": "Afx:00400000:0:00010003:00000000:00000000", "text": ""},
35: {"class_name": "Internet Explorer_Hidden", "text": ""},
40: {"class_name": "#32770", "text": "real dialog"},
})
snapshots = make_probe(gui, (10, 20, 30, 35, 40)).capture(PHASE)
assert [item.hwnd for item in snapshots] == [40]
def test_probe_skips_project_integration_panel_during_com_phase():
gui = FakeGui({10: {"class_name": "#32770", "text": "Project Integration"}})
snapshots = make_probe(gui, (10,)).capture(DialogPhase.PROJECT_INTEGRATION)
assert snapshots == ()
+246
View File
@@ -0,0 +1,246 @@
import json
from pathlib import Path
import pytest
from cbb_refresh_verify.dialog_models import ControlSnapshot, DialogPhase, WindowSnapshot
from cbb_refresh_verify.dialog_rules import (
DialogRule,
RuleConfigError,
decide,
load_rules,
)
ASSETS = Path(__file__).resolve().parents[1] / "src" / "cbb_refresh_verify" / "assets"
def prompt(text, *, phase=DialogPhase.PCB_STARTING, window_class="#32770",
control_types=("Text", "Button")):
controls = tuple(
ControlSnapshot(
handle=100 + index,
control_id=index,
class_name=control_type,
name=text if index == 0 else "OK",
control_type=control_type,
patterns=("Invoke",) if control_type == "Button" else (),
)
for index, control_type in enumerate(control_types)
)
return WindowSnapshot(
hwnd=10,
pid=20,
process_name="ExpeditionPCB.exe",
process_role="pcb",
window_class=window_class,
title="Expedition PCB",
phase=phase,
controls=controls,
)
def matching_rule(rule_id, priority):
return DialogRule(
rule_id=rule_id,
priority=priority,
category="OBSERVE_PROGRESS",
phases=(DialogPhase.PROJECT_INTEGRATION,),
semantic_all=("task is being processed",),
)
def test_default_save_rule_is_out_of_phase_during_license_acquisition():
rules = load_rules(ASSETS / "dialog_rules.v1.json")
snapshot = prompt(
"Do you want to save the Reusable Block cell?",
phase=DialogPhase.LICENSE_ACQUISITION,
)
decision = decide(snapshot, rules)
assert decision.error_code == "DIALOG_OUT_OF_PHASE"
assert decision.rule_id == "reusable-block-save"
def test_license_selector_is_allowed_after_com_attach_wait():
rules = load_rules(ASSETS / "dialog_rules.v1.json")
snapshot = prompt(
"Select the desired product license",
phase=DialogPhase.DOCUMENT_ATTACH,
window_class="#32770",
control_types=("GXWND", "Button"),
)
decision = decide(snapshot, rules)
assert decision.rule_id == "license-selector"
assert decision.error_code == ""
def test_open_lock_confirmation_is_allowed_during_pcb_starting():
rules = load_rules(ASSETS / "dialog_rules.v1.json")
snapshot = prompt(
"Continue to open the design with read/write access permission?",
phase=DialogPhase.PCB_STARTING,
)
decision = decide(snapshot, rules)
assert decision.rule_id == "open-lock-confirm"
assert decision.error_code == ""
def test_forward_annotation_confirmation_is_accepted_during_document_attach():
rules = load_rules(ASSETS / "dialog_rules.v1.json")
snapshot = prompt(
"New changes are ready for Forward Annotation. Do you want to Forward Annotate now?",
phase=DialogPhase.DOCUMENT_ATTACH,
)
decision = decide(snapshot, rules)
assert decision.rule_id == "forward-annotation-confirm"
assert decision.action == "confirm_forward_annotation"
assert decision.error_code == ""
def test_forward_annotation_confirmation_is_accepted_during_pcb_starting():
rules = load_rules(ASSETS / "dialog_rules.v1.json")
snapshot = prompt(
"New changes are ready for Forward Annotation. Do you want to Forward Annotate now?",
phase=DialogPhase.PCB_STARTING,
)
decision = decide(snapshot, rules)
assert decision.rule_id == "forward-annotation-confirm"
assert decision.action == "confirm_forward_annotation"
assert decision.error_code == ""
def test_project_integration_panel_is_observation_only():
rules = load_rules(ASSETS / "dialog_rules.v1.json")
snapshot = prompt(
"&Project file and Design Forward Annotation Required, connectivity changed "
"No pending schematic CES changes to load into PCB",
phase=DialogPhase.PROJECT_INTEGRATION,
)
decision = decide(snapshot, rules)
assert decision.rule_id == "project-integration-panel"
assert decision.category == "OBSERVE_PROGRESS"
assert decision.action == ""
assert decision.error_code == ""
def test_license_selector_prefers_nonblocking_ok_click_before_uia_invoke():
rules = load_rules(ASSETS / "dialog_rules.v1.json")
snapshot = prompt(
"Select the desired product license",
phase=DialogPhase.DOCUMENT_ATTACH,
window_class="#32770",
control_types=("GXWND", "Button"),
)
decision = decide(snapshot, rules)
assert decision.channels.index("win32_button_click") < decision.channels.index("uia_invoke")
def test_tip_of_day_prefers_nonblocking_ok_click_before_uia_invoke():
rules = load_rules(ASSETS / "dialog_rules.v1.json")
decision = decide(prompt("Tip of the Day"), rules)
assert decision.rule_id == "tip-of-day"
assert decision.channels.index("win32_button_click") < decision.channels.index("uia_invoke")
def test_integration_progress_out_of_phase_remains_observation_only():
rules = load_rules(ASSETS / "dialog_rules.v1.json")
decision = decide(
prompt(
"Your task is being processed. Elapsed time 10 seconds",
phase=DialogPhase.SAVE,
),
rules,
)
assert decision.rule_id == "integration-progress"
assert decision.category == "OBSERVE_PROGRESS"
assert decision.error_code == "DIALOG_OUT_OF_PHASE"
def test_equal_priority_matches_are_rejected():
snapshot = prompt(
"Your task is being processed. Elapsed time 10 seconds",
phase=DialogPhase.PROJECT_INTEGRATION,
)
decision = decide(snapshot, (matching_rule("a", 10), matching_rule("b", 10)))
assert decision.error_code == "DIALOG_RULE_CONFLICT"
assert "a" in decision.detail and "b" in decision.detail
def test_override_replaces_rule_by_id(tmp_path):
override = tmp_path / "rules.json"
override.write_text(json.dumps({
"schema_version": 1,
"rules": [{"rule_id": "tip-of-day", "enabled": False}],
}), encoding="utf-8")
rules = load_rules(ASSETS / "dialog_rules.v1.json", override)
assert next(rule for rule in rules if rule.rule_id == "tip-of-day").enabled is False
def test_unknown_schema_is_rejected(tmp_path):
path = tmp_path / "rules.json"
path.write_text(json.dumps({"schema_version": 2, "rules": []}), encoding="utf-8")
with pytest.raises(RuleConfigError, match="schema_version"):
load_rules(path)
def test_negative_semantic_evidence_prevents_match():
rule = DialogRule(
rule_id="continue-not-cancel",
priority=1,
category="SAFE_CONFIRM",
phases=(DialogPhase.PCB_STARTING,),
semantic_any=("continue",),
semantic_none=("destructive",),
action="confirm",
)
decision = decide(prompt("Continue destructive recovery"), (rule,))
assert decision.error_code == "UNKNOWN_DIALOG"
def test_known_ime_language_bar_is_observation_only_not_an_unknown_dialog():
snapshot = WindowSnapshot(hwnd=100, pid=200, process_name='ExpeditionPCB.exe',
process_role='pcb', window_class='CiceroUIWndFrame', title='TF_FloatingLangBar_WndTitle',
phase=DialogPhase.PCB_STARTING, controls=(), owner_hwnd=99)
decision = decide(snapshot, load_rules(ASSETS/'dialog_rules.v1.json'))
assert decision.category == 'OBSERVE_PROGRESS'
assert decision.error_code == ''
assert decision.action == ''
def test_language_bar_filter_does_not_ignore_a_real_dialog_with_same_caption():
snapshot = prompt('TF_FloatingLangBar_WndTitle')
decision = decide(snapshot, load_rules(ASSETS/'dialog_rules.v1.json'))
assert decision.error_code == 'UNKNOWN_DIALOG'
def test_database_open_failure_is_classified_and_declines_log_view():
snapshot = prompt('Problem encountered while opening one of the database files. '
'See PCBLogFile.txt for details. Loading of the job has failed. '
'Do you wish to view the log file now?')
decision = decide(snapshot, load_rules(ASSETS/'dialog_rules.v1.json'))
assert decision.category == 'FATAL_ACK'
assert decision.error_code == 'MENTOR_DATABASE_LOAD_FAILED'
assert dict(decision.target)['control_id'] == 7 # IDNO, never launch another log viewer
+475
View File
@@ -0,0 +1,475 @@
from cbb_refresh_verify.dialog_supervisor import (
AgentDialogBackend,
DialogControl,
DialogObservationError,
DialogSnapshot,
DialogSupervisor,
Win32DialogBackend,
)
from cbb_refresh_verify.dialog_agent import ActionResult
from cbb_refresh_verify.dialog_models import (
ControlSnapshot as EvidenceControl,
DialogPhase,
WindowSnapshot,
)
from cbb_refresh_verify.dialog_rules import load_rules
from pathlib import Path
def dialog(text, *, title="Expedition PCB", hwnd=100, pid=200, buttons=("OK", "Cancel")):
controls = [DialogControl(1000, 0, "Static", text, True)]
controls.extend(
DialogControl(1100 + index, control_id, "Button", caption, True)
for index, (control_id, caption) in enumerate(zip((1, 2, 6, 7), buttons))
)
return DialogSnapshot(hwnd, pid, title, tuple(controls))
def license_dialog():
return dialog("Select the desired product license", title="", buttons=("OK", "Cancel"))
def save_error_dialog():
return dialog("Error saving the Reusable Block. See log file, ReusableBlock.txt.",
buttons=("OK",))
class FakeDialogs:
def __init__(self, observations):
self.observations = list(observations)
self.actions = []
def observe(self):
if not self.observations:
return ()
return tuple(self.observations.pop(0))
def perform(self, snapshot, action):
self.actions.append((snapshot.hwnd, action))
return (1,)
def test_click_is_not_resolved_until_dialog_disappears():
backend = FakeDialogs([[license_dialog()], [license_dialog()], []])
supervisor = DialogSupervisor(backend, retry_seconds=0, max_attempts=3)
first = supervisor.poll()
second = supervisor.poll()
third = supervisor.poll()
assert first.action_sent
assert not first.resolved
assert second.action_sent
assert not second.resolved
assert third.resolved
assert len(backend.actions) == 2
def test_stuck_dialog_fails_after_bounded_retries():
backend = FakeDialogs([[license_dialog()]] * 4)
supervisor = DialogSupervisor(backend, retry_seconds=0, max_attempts=2)
supervisor.poll()
supervisor.poll()
result = supervisor.poll()
assert result.error_code == "DIALOG_STUCK"
assert len(backend.actions) == 2
def test_unknown_dialog_is_recorded_but_not_clicked():
backend = FakeDialogs([[dialog("Unrecognized destructive prompt")]])
result = DialogSupervisor(backend).poll()
assert result.error_code == "UNKNOWN_DIALOG"
assert backend.actions == []
def test_save_error_is_fatal_even_with_ok_button():
backend = FakeDialogs([[save_error_dialog()]])
result = DialogSupervisor(backend).poll()
assert result.error_code == "SAVE_REUSABLE_BLOCK_FAILED"
assert backend.actions == [(100, "acknowledge_fatal")]
def test_changed_text_on_reused_handle_is_a_new_dialog_state():
backend = FakeDialogs([
[license_dialog()],
[dialog("Do you want to save the Reusable Block cell?", buttons=("Yes", "No"))],
])
supervisor = DialogSupervisor(backend, retry_seconds=60, max_attempts=3)
assert supervisor.poll().action_sent
result = supervisor.poll()
assert result.action_sent
assert backend.actions == [(100, "accept_license"), (100, "save_reusable_block")]
def test_progress_dialog_with_only_cancel_is_observed_not_clicked():
backend = FakeDialogs([[dialog("Your task is being processed. Elapsed time 10 seconds",
buttons=("Cancel",))]])
result = DialogSupervisor(backend).poll()
assert not result.action_sent
assert not result.error_code
assert backend.actions == []
def test_progress_dialog_text_change_counts_as_activity_without_clicking():
backend = FakeDialogs([
[dialog("Your task is being processed. Elapsed time 10 seconds", buttons=("Cancel",))],
[dialog("Your task is being processed. Elapsed time 11 seconds", buttons=("Cancel",))],
])
supervisor = DialogSupervisor(backend)
first = supervisor.poll()
second = supervisor.poll()
assert first.activity
assert second.activity
assert backend.actions == []
def test_win32_enumeration_callbacks_always_continue():
callback_results = []
class FakeGui:
def EnumWindows(self, callback, context):
callback_results.extend((callback(10, context), callback(20, context)))
def IsWindowVisible(self, hwnd):
return True
def GetClassName(self, hwnd):
return "#32770" if hwnd == 10 else "Other"
def EnumChildWindows(self, hwnd, callback, context):
callback_results.extend((callback(101, context), callback(102, context)))
def GetWindowText(self, hwnd):
return {10: "", 101: "Select the desired product license", 102: "OK"}.get(hwnd, "")
def GetDlgCtrlID(self, hwnd):
return 1 if hwnd == 102 else 0
def IsWindowEnabled(self, hwnd):
return True
def SendMessage(self, hwnd, message, wparam, lparam):
return 0
class FakeProcess:
@staticmethod
def GetWindowThreadProcessId(hwnd):
return 1, 200
snapshots = Win32DialogBackend(
{200}, win32gui=FakeGui(), win32process=FakeProcess(), win32con=object()
).observe()
assert callback_results == [True, True, True, True]
assert len(snapshots) == 1
assert snapshots[0].pid == 200
def test_database_restoration_selects_choice_before_confirming():
clicks = []
class Gui:
@staticmethod
def PostMessage(hwnd, *_args):
clicks.append(hwnd)
backend = Win32DialogBackend(
set(), win32gui=Gui(), win32process=object(), win32con=object()
)
choice = DialogControl(10, 6213, 'Button', 'Load the last user saved database', True)
ok = DialogControl(11, 1, 'Button', 'OK', True)
snapshot = DialogSnapshot(1, 2, 'Database Restoration', (choice, ok))
assert backend.perform(snapshot, 'restore_last_saved') == (6213,)
selected = DialogControl(10, 6213, 'Button', 'Load the last user saved database', True,
checked=True)
snapshot = DialogSnapshot(1, 2, 'Database Restoration', (selected, ok))
assert backend.perform(snapshot, 'restore_last_saved') == (1,)
assert clicks == [10, 11]
def test_license_waits_for_list_selection_before_clicking_ok():
clicks = []
class Gui:
@staticmethod
def PostMessage(hwnd, *_args):
clicks.append(hwnd)
backend = Win32DialogBackend(
set(), win32gui=Gui(), win32process=object(), win32con=object()
)
ok = DialogControl(11, 1, 'Button', 'OK', True)
unselected = DialogControl(12, 20, 'ComboBox', '', True, selected=False)
selected = DialogControl(12, 20, 'ComboBox', '', True, selected=True)
assert backend.perform(DialogSnapshot(1, 2, '', (unselected, ok)), 'accept_license') == ()
assert backend.perform(DialogSnapshot(1, 2, '', (selected, ok)), 'accept_license') == (1,)
assert clicks == [11]
def test_license_dialog_opens_product_selector_before_waiting_for_selection():
clicks = []
class Gui:
@staticmethod
def PostMessage(hwnd, *_args):
clicks.append(hwnd)
backend = Win32DialogBackend(
set(), win32gui=Gui(), win32process=object(), win32con=object()
)
selector = DialogControl(10, 5225, 'Button', 'Select the desired product license', True)
custom_list = DialogControl(11, 1522, 'GXWND', '', True)
ok = DialogControl(12, 1, 'Button', 'OK', True)
snapshot = DialogSnapshot(1, 2, '', (selector, custom_list, ok))
assert backend.perform(snapshot, 'accept_license') == (5225,)
assert clicks == [10]
def test_window_enumeration_failure_is_structured_not_silent():
class BrokenGui:
@staticmethod
def EnumWindows(_callback, _context):
raise RuntimeError('enum failed')
class Backend:
@staticmethod
def observe():
raise DialogObservationError('WINDOW_ENUM_ERROR', 'enum failed')
result = DialogSupervisor(Backend()).poll()
assert result.error_code == 'WINDOW_ENUM_ERROR'
backend = Win32DialogBackend(
set(), win32gui=BrokenGui(), win32process=object(), win32con=object()
)
result = DialogSupervisor(backend).poll()
assert result.error_code == 'WINDOW_ENUM_ERROR'
def test_private_desktop_without_windows_is_transient_not_fatal():
class EmptyDesktop:
@staticmethod
def EnumDesktopWindows():
import pywintypes
raise pywintypes.error(2, 'EnumDesktopWindows', 'file not found')
backend = Win32DialogBackend(
set(), desktop=EmptyDesktop(), win32gui=object(),
win32process=object(), win32con=object()
)
assert backend.observe() == ()
def test_private_desktop_access_failure_remains_structured():
class BrokenDesktop:
@staticmethod
def EnumDesktopWindows():
import pywintypes
raise pywintypes.error(5, 'EnumDesktopWindows', 'access denied')
backend = Win32DialogBackend(
set(), desktop=BrokenDesktop(), win32gui=object(),
win32process=object(), win32con=object()
)
result = DialogSupervisor(backend).poll()
assert result.error_code == 'WINDOW_ENUM_ERROR'
RULES = load_rules(
Path(__file__).resolve().parents[1] / 'src' / 'cbb_refresh_verify' / 'assets' /
'dialog_rules.v1.json'
)
def evidence_window(text, *, phase, window_class='#32770', selected=False):
return WindowSnapshot(
hwnd=500,
pid=600,
process_name='ExpeditionPCB.exe',
process_role='pcb',
window_class=window_class,
title='Expedition PCB',
phase=phase,
controls=(
EvidenceControl(501, 0, 'Static', text, control_type='Text'),
EvidenceControl(502, 1, 'Button', 'OK', control_type='Button',
enabled=True, selected=selected, patterns=('Invoke',)),
),
owner_hwnd=400,
)
class PhaseBackend:
def __init__(self, observations):
self.observations = list(observations)
self.actions = []
def observe(self, phase):
if not self.observations:
return ()
return tuple(self.observations.pop(0))
def perform(self, snapshot, action, phase):
self.actions.append((snapshot.hwnd, action, phase))
return ActionResult(channel='uia_invoke', accepted_controls=(1,))
def test_phase_aware_unknown_window_fails_without_action():
backend = PhaseBackend([[
evidence_window('Unrecognized destructive prompt', phase=DialogPhase.PCB_STARTING,
window_class='GXWND')
]])
result = DialogSupervisor(backend, rules=RULES).poll(DialogPhase.PCB_STARTING)
assert result.error_code == 'UNKNOWN_DIALOG'
assert backend.actions == []
def test_phase_aware_action_is_pending_until_window_disappears():
restore = evidence_window(
'Database Restoration - Load the last user saved database',
phase=DialogPhase.DATABASE_RECOVERY,
)
backend = PhaseBackend([[restore], []])
supervisor = DialogSupervisor(backend, rules=RULES, retry_seconds=60)
first = supervisor.poll(DialogPhase.DATABASE_RECOVERY)
second = supervisor.poll(DialogPhase.DATABASE_RECOVERY)
assert first.action_sent and not first.resolved
assert second.resolved
assert len(backend.actions) == 1
def test_phase_aware_changed_content_is_not_window_gone():
first = evidence_window(
'Database Restoration - Load the last user saved database',
phase=DialogPhase.DATABASE_RECOVERY,
)
changed = evidence_window(
'Database Restoration - Load the last user saved database - selected',
phase=DialogPhase.DATABASE_RECOVERY,
selected=True,
)
backend = PhaseBackend([[first], [changed]])
supervisor = DialogSupervisor(backend, rules=RULES, retry_seconds=60)
first_result = supervisor.poll(DialogPhase.DATABASE_RECOVERY)
second_result = supervisor.poll(DialogPhase.DATABASE_RECOVERY)
assert first_result.action_sent and not first_result.resolved
assert not second_result.resolved
def test_phase_aware_fatal_error_cannot_become_success():
fatal = evidence_window(
'There were errors during Project Integration',
phase=DialogPhase.PROJECT_INTEGRATION,
)
backend = PhaseBackend([[fatal]])
result = DialogSupervisor(backend, rules=RULES).poll(DialogPhase.PROJECT_INTEGRATION)
assert result.error_code == 'PROJECT_INTEGRATION_FAILED'
assert result.rule_id == 'integration-error'
assert backend.actions
def test_agent_backend_forwards_phase_fingerprint_and_action():
calls = []
class Client:
def observe(self, phase):
calls.append(('observe', phase))
return ()
def perform(self, **values):
calls.append(('perform', values))
return ActionResult(channel='uia_invoke', accepted_controls=(1,))
backend = AgentDialogBackend(Client())
window = evidence_window('Tip of the Day', phase=DialogPhase.PCB_STARTING)
backend.observe(DialogPhase.PCB_STARTING)
backend.perform(window, {'action': 'dismiss_tip'}, DialogPhase.PCB_STARTING)
assert calls[0] == ('observe', DialogPhase.PCB_STARTING)
assert calls[1][1]['hwnd'] == 500
assert calls[1][1]['fingerprint']
def native_database_open_error():
return DialogSnapshot(100, 200, 'Expedition PCB', (
DialogControl(1000, 0, 'Static',
'Problem encountered while opening one of the database files. '
'See PCBLogFile.txt for details. Loading of the job has failed. '
'Do you wish to view the log file now?', True),
DialogControl(1100, 6, 'Button', 'Yes', True),
DialogControl(1101, 7, 'Button', 'No', True),
))
def test_legacy_native_database_failure_is_classified_and_declines_log_viewer():
backend = FakeDialogs([[native_database_open_error()]])
result = DialogSupervisor(backend).poll()
assert result.error_code == 'MENTOR_DATABASE_LOAD_FAILED'
assert backend.actions == [(100, 'decline_database_log')]
def test_legacy_database_failure_clicks_idno_never_yes():
clicks = []
class Gui:
def PostMessage(self, handle, *args):
clicks.append(handle)
backend = Win32DialogBackend({200}, win32gui=Gui(), win32process=object(), win32con=object())
assert backend.perform(native_database_open_error(), 'decline_database_log') == (7,)
assert clicks == [1101]
only_yes = DialogSnapshot(100, 200, 'Expedition PCB', native_database_open_error().controls[:-1])
assert backend.perform(only_yes, 'decline_database_log') == ()
assert clicks == [1101]
def test_versioned_supervision_ignores_ime_and_still_handles_next_real_dialog():
phase = DialogPhase.PCB_STARTING
ime = WindowSnapshot(hwnd=800, pid=600, process_name='ExpeditionPCB.exe', process_role='pcb',
window_class='CiceroUIWndFrame', title='TF_FloatingLangBar_WndTitle', phase=phase,
owner_hwnd=400, controls=())
from dataclasses import replace
license_prompt = evidence_window('Select the desired product license', phase=phase)
license_prompt = replace(license_prompt, controls=(
replace(license_prompt.controls[0], class_name='GXWND'), license_prompt.controls[1]))
backend = PhaseBackend([[ime, license_prompt]])
result = DialogSupervisor(backend, rules=RULES).poll(phase)
assert not result.error_code
assert result.action_sent
assert len(backend.actions) == 1 and backend.actions[0][0] == license_prompt.hwnd
def test_versioned_database_open_failure_action_targets_no_button():
from dataclasses import replace
window = evidence_window(native_database_open_error().texts[0], phase=DialogPhase.DOCUMENT_ATTACH)
window = replace(window, controls=(window.controls[0],
EvidenceControl(502, 6, 'Button', 'Yes', control_type='Button'),
EvidenceControl(503, 7, 'Button', 'No', control_type='Button')))
backend = PhaseBackend([[window]])
result = DialogSupervisor(backend, rules=RULES).poll(window.phase)
assert result.error_code == 'MENTOR_DATABASE_LOAD_FAILED'
assert dict(backend.actions[0][1]['target']) == {'control_id': 7}
+56
View File
@@ -0,0 +1,56 @@
from pathlib import Path
def test_parse_icdb_server_address_extracts_port_and_hosts(tmp_path):
from cbb_refresh_verify.mentor_adapter import parse_icdb_server_address
address = tmp_path / "sAddress.adr"
address.write_text(
"guid\n127.0.0.1\n192.168.1.10\n10062\n1094\n"
"vt40T8RtWJOG2cE2Nlvc5A\n535943\n",
encoding="ascii",
)
assert parse_icdb_server_address(address) == {
"port": 10062,
"hosts": ["127.0.0.1", "192.168.1.10"],
}
def test_stale_icdb_address_is_moved_to_evidence(tmp_path, monkeypatch):
from cbb_refresh_verify import mentor_adapter
database = tmp_path / "database"
address = database / "cdbsvr" / "sAddress.adr"
address.parent.mkdir(parents=True)
address.write_text("guid\n127.0.0.1\n10062\n1094\n", encoding="ascii")
monkeypatch.setattr(mentor_adapter, "probe_icdb_server", lambda hosts, port: (False, "10062 unreachable"))
events = []
result = mentor_adapter.prepare_icdb_address(
database,
tmp_path / "evidence",
emit=lambda **event: events.append(event),
)
assert result["status"] == "STALE_MOVED"
assert not address.exists()
moved = list((tmp_path / "evidence" / "diagnostics" / "cdbsvr").glob("sAddress.adr.stale-*"))
assert len(moved) == 1
assert moved[0].read_text(encoding="ascii") == "guid\n127.0.0.1\n10062\n1094\n"
assert events[-1]["stage"] == "icdb_address_stale"
def test_live_icdb_address_is_left_in_place(tmp_path, monkeypatch):
from cbb_refresh_verify import mentor_adapter
database = tmp_path / "database"
address = database / "cdbsvr" / "sAddress.adr"
address.parent.mkdir(parents=True)
address.write_text("guid\n127.0.0.1\n10062\n1094\n", encoding="ascii")
monkeypatch.setattr(mentor_adapter, "probe_icdb_server", lambda hosts, port: (True, "127.0.0.1:10062"))
result = mentor_adapter.prepare_icdb_address(database, tmp_path / "evidence")
assert result["status"] == "LIVE"
assert address.is_file()
+570
View File
@@ -0,0 +1,570 @@
from pathlib import Path
import hashlib
import os
import pytest
from cbb_refresh_verify.integration import IntegrationError, refresh_integration
from cbb_refresh_verify.mentor_adapter import (pcb_log_reports_integration_error,
save_log_has_core_markers,
build_backup_command, best_effort_backup,
backup_timeout_seconds,
choose_dialog_action, cleanup_evidence_backup,
ActivityDeadline, cleanup_verify_processes,
ensure_pcb_central_library, is_network_backed_path)
from cbb_refresh_verify.library_manager_verify import (_fresh_library_pids, _menu_click_lparam,
_invoke_interactive_verify)
class FakeProjectIntegration:
ForwardAnnotationStatus = 1
SynchCESStatus = 2
LoadCESStatus = 2
BackAnnotationStatus = 2
IsForwardAnnotationAllowed = True
IsSynchCESAllowed = True
IsLoadCESAllowed = True
IsBackAnnotationAllowed = True
forward_calls = 0
def ForwardAnnotate(self):
self.forward_calls += 1
return True
def test_database_restoration_dialog_selects_last_saved_database():
action = choose_dialog_action(
'Database Restoration',
['Restore Database', 'Load the last user saved database dated 2026/9/3 19:32.',
'Load the autosave database dated 2026/9/3 19:32.', 'OK', 'Cancel'],
)
assert action == 'restore_last_saved'
def test_library_manager_fresh_pid_filter_rejects_stale_sessions():
assert _fresh_library_pids({10, 11}, {10, 11, 12, 13}, 12) == {12, 13}
def test_library_manager_menu_click_lparam_is_relative_to_popup_window():
assert _menu_click_lparam((50, 150, 300, 500), (140, 280, 260, 320)) == (150 << 16) | 150
def test_library_manager_menu_click_lparam_accepts_uia_rect_objects():
class Rect:
left = 140
top = 280
right = 260
bottom = 320
assert _menu_click_lparam((50, 150, 300, 500), Rect()) == (150 << 16) | 150
def test_interactive_verify_focuses_library_manager_before_real_right_click():
calls = []
class Target:
def set_focus(self):
calls.append('focus')
class Item:
def select(self):
calls.append('select')
def click_input(self, *, button):
calls.append(('click', button))
_invoke_interactive_verify(Target(), Item())
assert calls == ['focus', 'select', ('click', 'right')]
def test_cleanup_verify_processes_terminates_worker_parent_and_lm(monkeypatch):
from cbb_refresh_verify import mentor_adapter
terminated = []
monkeypatch.setattr(mentor_adapter, '_terminate_pid',
lambda pid, **_kwargs: terminated.append(int(pid)))
cleanup_verify_processes(101, 202, 303, emit=lambda **event: None)
assert terminated == [202, 303, 101]
def test_cleanup_verify_processes_discovers_unbound_target_pcb_processes(monkeypatch):
from cbb_refresh_verify import mentor_adapter
terminated = []
target = r'S:\Mentor_lib\ReusableBlocksLP\CBB\Work\CBB.pcb'
command = rf'"C:\Mentor\common\ExpeditionPCB.exe" "{target}" -ReusableCircuit'
monkeypatch.setattr(
mentor_adapter,
'_process_details',
lambda _name: [
(202, r'C:\Mentor\wg\ExpeditionPCB.exe', command, 303),
(303, r'C:\Mentor\common\ExpeditionPCB.exe', command, 101),
(204, r'C:\Mentor\wg\ExpeditionPCB.exe', command, 777),
(999, r'C:\Mentor\wg\ExpeditionPCB.exe', command, 0),
],
)
monkeypatch.setattr(mentor_adapter, '_terminate_pid',
lambda pid, **_kwargs: terminated.append(int(pid)))
mentor_adapter.cleanup_verify_processes(
101,
None,
None,
expected_pcb=target,
baseline_pids={999},
emit=lambda **event: None,
)
assert terminated == [202, 303, 204, 101]
def test_verify_cleanup_is_present_on_all_exit_paths():
from cbb_refresh_verify import mentor_adapter
import inspect
source = inspect.getsource(mentor_adapter.execute_job)
assert 'cleanup_verify_processes(' in source
assert 'expected_pcb=job.get(\'pcb\')' in source
def test_real_verify_execution_no_longer_calls_legacy_dialog_handler():
from cbb_refresh_verify import mentor_adapter
import inspect
source = inspect.getsource(mentor_adapter.execute_job)
assert 'handle_known_dialogs(' not in source
assert 'choose_dialog_action(' not in source
def test_real_verify_execution_uses_observed_reusable_circuit_route():
from cbb_refresh_verify import mentor_adapter
import inspect
source = inspect.getsource(mentor_adapter.execute_job)
assert 'native_lm_verify' in source
assert "job['lmc_file']" in source
assert 'build_pcb_launch_command' in source
assert 'launch_pcb_process' in source
def test_real_verify_keeps_licensing_in_32bit_save_helper():
from cbb_refresh_verify import mentor_adapter
import inspect
source = inspect.getsource(mentor_adapter.execute_job)
assert 'validate_document(' not in source
assert "save_verified_block.vbs" in source
def test_unknown_modal_prefers_safe_positive_action():
action = choose_dialog_action('Expedition PCB', ['Continue', 'Cancel'])
assert action == 'positive'
def test_unknown_modal_uses_fallback_action():
action = choose_dialog_action('Expedition PCB', ['Proceed with design recovery', 'Dismiss'])
assert action == 'fallback'
def test_evidence_backup_is_reclaimed(tmp_path):
backup = tmp_path/'backup'
(backup/'CBB'/'Cert').mkdir(parents=True)
(backup/'CBB'/'Cert'/'sample.prj').write_text('x', encoding='utf-8')
cleanup_evidence_backup(tmp_path)
assert not backup.exists()
def test_activity_deadline_is_extended_by_progress(monkeypatch):
now = [100.0]
monkeypatch.setattr('cbb_refresh_verify.mentor_adapter.time.monotonic', lambda: now[0])
deadline = ActivityDeadline(30)
assert not deadline.expired()
now[0] = 120.0
deadline.touch()
now[0] = 129.9
assert not deadline.expired()
assert deadline.remaining() == pytest.approx(20.1, abs=0.1)
now[0] = 149.9
assert not deadline.expired()
now[0] = 150.1
assert deadline.expired()
def test_refresh_integration_stops_on_new_pcb_error_before_action():
pi = FakeProjectIntegration()
with pytest.raises(IntegrationError, match='Job Preferences DB'):
refresh_integration(pi, error_reader=lambda: 'ERROR: Could not load Job Preferences DB')
assert pi.forward_calls == 0
class GreenProjectIntegration:
ForwardAnnotationStatus = 2
SynchCESStatus = 2
LoadCESStatus = 2
BackAnnotationStatus = 2
IsForwardAnnotationAllowed = True
IsSynchCESAllowed = True
IsLoadCESAllowed = True
IsBackAnnotationAllowed = True
def __init__(self):
self.actions = []
def ForwardAnnotate(self):
self.actions.append('ForwardAnnotate')
return True
def SynchCES(self):
self.actions.append('SynchCES')
return True
def LoadCES(self):
self.actions.append('LoadCES')
return True
def BackAnnotate(self):
self.actions.append('BackAnnotate')
return True
def test_refresh_integration_only_refreshes_first_action_when_already_green():
pi = GreenProjectIntegration()
events = []
assert refresh_integration(pi, settle_seconds=0, emit=lambda **e: events.append(e)) == {
'ForwardAnnotation': 2,
'SynchCES': 2,
'LoadCES': 2,
'BackAnnotation': 2,
}
assert pi.actions == ['ForwardAnnotate']
assert [e['action'] for e in events if e['stage'] == 'integration_action'] == pi.actions
def test_refresh_integration_waits_for_action_to_turn_green_before_next_action():
class PendingProjectIntegration(GreenProjectIntegration):
def ForwardAnnotate(self):
super().ForwardAnnotate()
self.ForwardAnnotationStatus = 1
return True
pi = PendingProjectIntegration()
waits = []
def complete_pending_action(_seconds):
assert pi.actions == ['ForwardAnnotate']
waits.append(True)
pi.ForwardAnnotationStatus = 2
refresh_integration(pi, settle_seconds=0, sleep=complete_pending_action)
assert waits
assert pi.actions == ['ForwardAnnotate']
@pytest.mark.parametrize('failure', ['not_allowed', 'returned_false', 'new_error'])
def test_refresh_integration_never_accepts_initial_green_when_refresh_fails(failure):
pi = GreenProjectIntegration()
if failure == 'not_allowed':
pi.ForwardAnnotationStatus = 1
pi.IsForwardAnnotationAllowed = False
elif failure == 'returned_false':
pi.ForwardAnnotate = lambda: False
with pytest.raises(IntegrationError):
refresh_integration(
pi, settle_seconds=0,
error_reader=lambda: 'refresh error' if failure == 'new_error' and pi.actions else '',
)
assert 'SynchCES' not in pi.actions
def test_refresh_integration_attempts_disabled_green_action_once():
pi = GreenProjectIntegration()
pi.IsForwardAnnotationAllowed = False
refresh_integration(pi, settle_seconds=0)
assert pi.actions == ['ForwardAnnotate']
def test_refresh_integration_never_counts_rejected_green_action_as_completed():
class VerifiedProjectIntegration(GreenProjectIntegration):
def _blocked(self, action):
self.actions.append(action)
raise RuntimeError(
f'{action} is not allowed on verified (or once verified) Reusable Blocks.')
def ForwardAnnotate(self): return self._blocked('ForwardAnnotate')
def SynchCES(self): return self._blocked('SynchCES')
def LoadCES(self): return self._blocked('LoadCES')
def BackAnnotate(self): return self._blocked('BackAnnotate')
pi = VerifiedProjectIntegration()
events = []
with pytest.raises(IntegrationError, match='not allowed on verified'):
refresh_integration(pi, settle_seconds=0, emit=lambda **e: events.append(e))
assert pi.actions == ['ForwardAnnotate']
assert not any(e['stage'] == 'integration_complete' for e in events)
def test_refresh_integration_does_not_retry_rejected_action_after_status_changes():
class VerifiedAfterFirstAction(GreenProjectIntegration):
def ForwardAnnotate(self):
self.actions.append('ForwardAnnotate')
self.BackAnnotationStatus = 1
return True
def BackAnnotate(self):
self.actions.append('BackAnnotate')
raise RuntimeError('Back Annotation is not allowed on verified (or once verified) Reusable Blocks.')
pi = VerifiedAfterFirstAction()
with pytest.raises(IntegrationError, match='not allowed on verified'):
refresh_integration(pi, settle_seconds=0, timeout_seconds=None)
assert pi.actions == ['ForwardAnnotate', 'BackAnnotate']
def test_refresh_integration_waits_for_real_state_change_without_internal_timeout():
class SlowProjectIntegration(GreenProjectIntegration):
SynchCESStatus = 2
LoadCESStatus = 2
BackAnnotationStatus = 2
IsForwardAnnotationAllowed = True
def __init__(self):
super().__init__()
self.reads = 0
self.forward_calls = 0
@property
def ForwardAnnotationStatus(self):
self.reads += 1
return 2 if self.reads >= 6 else 1
def ForwardAnnotate(self):
self.forward_calls += 1
return True
pi = SlowProjectIntegration()
result = refresh_integration(pi, settle_seconds=0, timeout_seconds=None,
sleep=lambda _seconds: None)
assert result['ForwardAnnotation'] == 2
assert pi.forward_calls == 1
def test_pcb_log_reports_only_new_integration_errors(tmp_path):
pcb = tmp_path / 'Work' / 'PCB' / 'sample.pcb'
log = pcb.parent / 'LogFiles' / 'ForwardAnnotation.txt'
log.parent.mkdir(parents=True)
log.write_text('No errors in Existing Schematic Packaging.\n', encoding='utf-8')
offset = log.stat().st_size
assert pcb_log_reports_integration_error(pcb, offsets={log: offset}) == ''
with log.open('a', encoding='utf-8') as stream:
stream.write('ERROR: Could not load Job Preferences DB\n')
stream.write('ERROR: Unable to create local Cell Library.\n')
stream.write('DataBase Load is being terminated with 2 errors and 0 warnings.\n')
detail = pcb_log_reports_integration_error(pcb, offsets={log: offset})
assert 'Job Preferences DB' in detail
assert 'local Cell Library' in detail
def test_pcb_log_ignores_nonfatal_packager_compatibility_warnings(tmp_path):
pcb = tmp_path / 'Work' / 'PCB' / 'sample.pcb'
log = pcb.parent / 'LogFiles' / 'PartPkg.log'
log.parent.mkdir(parents=True)
log.write_text(
'Unable to determine the Disable Repackage status.\n'
'Unable to successfully read the Property Definition Editor data.\n'
'No errors found. Proceeding with packaging...\n'
'Packager finished successfully.\n'
'!THE iCDB IS UP-TO-DATE!\n',
encoding='utf-8',
)
assert pcb_log_reports_integration_error(pcb, offsets={log: 0}) == ''
def test_pcb_log_reports_rewritten_same_size_log(tmp_path):
pcb = tmp_path / 'Work' / 'PCB' / 'sample.pcb'
log = pcb.parent / 'LogFiles' / 'ForwardAnnotation.txt'
log.parent.mkdir(parents=True)
old = 'No errors in Existing Schematic Packaging..\n'
log.write_text(old, encoding='utf-8')
baseline = {
'size': log.stat().st_size,
'mtime_ns': log.stat().st_mtime_ns,
'digest': hashlib.sha256(log.read_bytes()).hexdigest(),
}
new = 'ERROR: Unable to create local Cell Library.\n'
assert len(new.encode('utf-8')) == len(old.encode('utf-8'))
log.write_text(new, encoding='utf-8')
detail = pcb_log_reports_integration_error(pcb, offsets={log: baseline})
assert 'local Cell Library' in detail
def test_ensure_pcb_central_library_rewrites_stale_mapped_path(tmp_path):
pcb = tmp_path / 'Work' / 'PCB' / 'sample.pcb'
pcb.parent.mkdir(parents=True)
project = pcb.parent / 'pcb.prj'
project.write_text(
'KEY CentralLibrary "S:\\mentor_lib.lmc"\n'
'KEY CentralLibrary "S:\\mentor_lib.lmc"\n',
encoding='utf-8',
)
lmc = tmp_path / 'mentor_lib.lmc'
lmc.write_text('', encoding='utf-8')
evidence = tmp_path / 'evidence'
changed = ensure_pcb_central_library(pcb, lmc, evidence_dir=evidence)
assert changed is True
relative_lmc = os.path.relpath(lmc, project.parent).replace('/', '\\')
assert project.read_text(encoding='utf-8').count(relative_lmc) == 2
assert (evidence / 'pcb.prj.before-central-library').is_file()
def test_save_log_core_markers_allow_quit_recovery():
assert save_log_has_core_markers(
'LICENSE_OK\nSAVE_OK\nIS_SAVED\nPOST_SAVE_SYNCHRONIZED\nCLOSE_OK\n')
assert not save_log_has_core_markers('LICENSE_OK\nSAVE_OK\nIS_SAVED\n')
def test_backup_command_excludes_volatile_logs_and_databases(tmp_path):
command = build_backup_command(tmp_path/'source', tmp_path/'backup')
assert '/XD' in command and 'database' in command and 'logfiles' in command
assert '/XF' in command and '*.log' in command and '*.lck' in command
def test_backup_timeout_is_non_blocking_and_reported(tmp_path, monkeypatch):
source = tmp_path/'source'
source.mkdir()
terminated = []
class HangingProcess:
returncode = None
def wait(self, timeout):
raise __import__('subprocess').TimeoutExpired('robocopy', timeout)
import cbb_refresh_verify.mentor_adapter as adapter
monkeypatch.setattr(adapter.subprocess, 'Popen', lambda *args, **kwargs: HangingProcess())
monkeypatch.setattr(adapter, '_terminate', lambda process, **kwargs: terminated.append(process))
result = best_effort_backup(source, tmp_path/'backup', timeout_seconds=.1)
assert result['status'] == 'TIMEOUT'
assert terminated
def test_backup_timeout_scales_with_workload_and_is_independent_of_verify_timeout(tmp_path):
source = tmp_path/'source'
source.mkdir()
(source/'small.bin').write_bytes(b'x' * (1 * 1024 * 1024))
small = backup_timeout_seconds(source, verify_timeout_seconds=30)
large = tmp_path/'large'
large.mkdir()
for index in range(1200):
(large/f'{index:04d}.bin').write_bytes(b'x' * (64 * 1024))
large_budget = backup_timeout_seconds(large, verify_timeout_seconds=30)
assert small >= 3
assert large_budget > small
assert large_budget <= 30
assert backup_timeout_seconds(source, verify_timeout_seconds=1800) == small
def test_backup_timeout_falls_back_to_minimum_for_unreadable_source(tmp_path):
missing = tmp_path/'missing'
assert backup_timeout_seconds(missing, verify_timeout_seconds=30) == 3
def test_backup_timeout_ignores_volatile_directories_excluded_from_copy(tmp_path):
source = tmp_path/'source'
(source/'stable').mkdir(parents=True)
(source/'logfiles').mkdir()
(source/'stable'/'small.bin').write_bytes(b'x')
for index in range(1500):
(source/'logfiles'/f'{index:04d}.bin').write_bytes(b'x' * 1024)
budget = backup_timeout_seconds(source)
assert budget == pytest.approx(3.003)
def test_backup_timeout_uses_bounded_kill_budget(tmp_path, monkeypatch):
source = tmp_path/'source'
source.mkdir()
observed = {}
class HangingProcess:
returncode = None
def wait(self, timeout):
raise __import__('subprocess').TimeoutExpired('robocopy', timeout)
import cbb_refresh_verify.mentor_adapter as adapter
monkeypatch.setattr(adapter.subprocess, 'Popen', lambda *args, **kwargs: HangingProcess())
def terminate(process, **kwargs):
observed.update(kwargs)
monkeypatch.setattr(adapter, '_terminate', terminate)
result = best_effort_backup(source, tmp_path/'backup', timeout_seconds=3)
assert result['status'] == 'TIMEOUT'
assert observed['grace_seconds'] == 1
assert observed['kill_timeout_seconds'] <= 5
def test_network_backed_path_detects_unc_and_matching_mapped_drive(tmp_path):
assert is_network_backed_path(r'\\server\share\CBB', mapped_drive='Z:')
assert is_network_backed_path(r'Z:\CBB', mapped_drive='Z:')
assert not is_network_backed_path(tmp_path / 'CBB', mapped_drive='Z:')
def test_green_refresh_only_runs_newly_required_actions():
class NeedsBackAnnotation(GreenProjectIntegration):
def ForwardAnnotate(self):
super().ForwardAnnotate()
self.BackAnnotationStatus = 1
return True
def BackAnnotate(self):
super().BackAnnotate()
self.BackAnnotationStatus = 2
return True
pi = NeedsBackAnnotation()
result = refresh_integration(pi, settle_seconds=0)
assert pi.actions == ['ForwardAnnotate', 'BackAnnotate']
assert set(result.values()) == {2}
def test_initial_required_keeps_existing_full_sequence():
class Required(GreenProjectIntegration):
ForwardAnnotationStatus = 1
def ForwardAnnotate(self):
super().ForwardAnnotate()
self.ForwardAnnotationStatus = 2
return True
pi = Required()
refresh_integration(pi, settle_seconds=0)
assert pi.actions == ['ForwardAnnotate', 'SynchCES', 'LoadCES', 'BackAnnotate']
def test_integration_times_actual_call_and_completion_without_wall_clock():
now = [100.0]
events = []
class SlowForward(GreenProjectIntegration):
def ForwardAnnotate(self):
super().ForwardAnnotate()
now[0] += 341
return True
refresh_integration(SlowForward(), settle_seconds=0, clock=lambda: now[0],
emit=lambda **e: events.append(e))
complete = next(e for e in events if e['stage'] == 'integration_action_complete')
assert complete['elapsed_seconds'] == 341
assert complete['call_elapsed_seconds'] == 341
assert len([e for e in events if e['stage'] == 'integration_status']) == 1
+401
View File
@@ -0,0 +1,401 @@
from pathlib import Path
from cbb_refresh_verify.library_reader import read_library
class Obj:
def __init__(self, **kw): self.__dict__.update(kw)
def fake_dispatch(_):
class Collection:
def __init__(self, values): self.values=values; self.Count=len(values)
def Item(self, index): return self.values[index-1]
blocks = Collection([Obj(Name='Z_CBB', PartitionName='LP'), Obj(Name='A_CBB', PartitionName='LP')])
blocks2 = Collection([])
partitions = Collection([blocks, blocks2])
return Obj(OpenLibrary=lambda _: Obj(Partitions=lambda kind: partitions))
def test_reader_filters_and_sorts_records():
result = read_library(Path('fixture.lmc'), dispatch=fake_dispatch)
assert [item.name for item in result.records] == ['A_CBB', 'Z_CBB']
assert result.error is None
def test_reader_surfaces_com_error():
result = read_library(Path('fixture.lmc'), dispatch=lambda _: (_ for _ in ()).throw(RuntimeError('DMS')))
assert result.records == () and 'DMS' in result.error
def test_reader_accepts_com_collections_exposing_callable_count():
class Collection:
def __init__(self, values): self.values = values
def Count(self): return len(self.values)
def Item(self, index): return self.values[index - 1]
blocks = Collection([Obj(Name='CALLABLE_CBB', PartitionName='LP')])
partitions = Collection([blocks])
dispatch = lambda _: Obj(OpenLibrary=lambda _: Obj(Partitions=lambda kind: partitions))
result = read_library(Path('fixture.lmc'), dispatch=dispatch)
assert [record.name for record in result.records] == ['CALLABLE_CBB']
def test_reader_fast_scans_reusable_blocks_without_com(tmp_path):
lmc = tmp_path / 'center.lmc'
lmc.touch()
(tmp_path / 'ReusableBlocksLP' / 'B_CBB').mkdir(parents=True)
(tmp_path / 'ReusableBlocksLP' / 'A_CBB').mkdir()
from cbb_refresh_verify.library_reader import read_library_fast
result = read_library_fast(lmc)
assert [item.name for item in result.records] == ['A_CBB', 'B_CBB']
assert all(item.status == 'UNKNOWN' for item in result.records)
def test_reader_fast_applies_status_reader(tmp_path):
lmc = tmp_path / 'center.lmc'
lmc.touch()
(tmp_path / 'ReusableBlocksLP' / 'READY_CBB').mkdir(parents=True)
from cbb_refresh_verify.library_reader import read_library_fast
result = read_library_fast(lmc, status_reader=lambda name: 'READY' if name == 'READY_CBB' else 'PENDING')
assert result.records[0].status == 'READY'
def test_reader_fast_bulk_status_reader_is_called_once(tmp_path):
lmc = tmp_path / 'center.lmc'
lmc.touch()
(tmp_path / 'ReusableBlocksLP' / 'A_CBB').mkdir(parents=True)
(tmp_path / 'ReusableBlocksLP' / 'B_CBB').mkdir()
calls = []
from cbb_refresh_verify.library_reader import read_library_fast
def status_reader(path, names):
calls.append((path, names))
return {'A_CBB': 'READY', 'B_CBB': 'PENDING'}
result = read_library_fast(lmc, status_reader=status_reader)
assert len(calls) == 1
assert [record.status for record in result.records] == ['READY', 'PENDING']
def test_reader_fast_preserves_unavailable_bridge_status(tmp_path):
lmc = tmp_path / 'center.lmc'
lmc.touch()
(tmp_path / 'ReusableBlocksLP' / 'A_CBB').mkdir(parents=True)
from cbb_refresh_verify.library_reader import read_library_fast
result = read_library_fast(lmc, status_reader=lambda path, names: {'A_CBB': 'UNAVAILABLE'})
assert result.records[0].status == 'UNAVAILABLE'
def test_reader_fast_exposes_status_reader_failure_as_unavailable(tmp_path):
lmc = tmp_path / 'center.lmc'
lmc.touch()
(tmp_path / 'ReusableBlocksLP' / 'A_CBB').mkdir(parents=True)
from cbb_refresh_verify.library_reader import read_library_fast
result = read_library_fast(lmc, status_reader=lambda path, names: (_ for _ in ()).throw(RuntimeError('bridge down')))
assert result.records[0].status == 'UNAVAILABLE'
def test_filesystem_status_uses_complete_fresh_cert_artifacts(tmp_path):
lmc = tmp_path / 'center.lmc'
lmc.touch()
root = tmp_path / 'ReusableBlocksLP'
ready = root / 'READY_CBB' / 'Work'
pending = root / 'PENDING_CBB' / 'Work'
for work, name in ((ready, 'READY_CBB'), (pending, 'PENDING_CBB')):
(work / 'PCB' / 'Layout').mkdir(parents=True)
(work / f'{name}.prj').write_text('KEY PCBDesignPath "PCB\\actual.pcb"', encoding='utf-8')
(work / 'PCB' / 'actual.pcb').write_text('pcb', encoding='utf-8')
(work / 'PCB' / 'Layout' / 'LayoutDB.lyt').write_bytes(b'lyt')
cert = root / 'READY_CBB' / 'Cert'
(cert / 'PCB' / 'Layout').mkdir(parents=True)
(cert / 'READY_CBB.prj').write_text('cert', encoding='utf-8')
(cert / 'PCB' / 'actual.pcb').write_text('cert pcb', encoding='utf-8')
(cert / 'PCB' / 'Layout' / 'LayoutDB.lyt').write_bytes(b'cert lyt')
from cbb_refresh_verify.library_reader import read_library_fast, filesystem_status_map
statuses = filesystem_status_map(lmc, ('READY_CBB', 'PENDING_CBB'))
assert statuses == {'READY_CBB': 'READY', 'PENDING_CBB': 'PENDING'}
result = read_library_fast(lmc, status_reader=filesystem_status_map)
assert [record.status for record in result.records] == ['PENDING', 'READY']
def test_reconcile_statuses_uses_persisted_pending_when_tree_is_unavailable():
from cbb_refresh_verify.library_reader import reconcile_statuses
result = reconcile_statuses(
{'A': 'UNKNOWN', 'B': 'READY'},
{'A': 'PENDING', 'B': 'UNKNOWN'},
('A', 'B'),
)
assert result == {'A': 'PENDING', 'B': 'READY'}
def test_reconcile_statuses_prefers_calibrated_tree_sources_on_conflict():
from cbb_refresh_verify.library_reader import reconcile_statuses
result = reconcile_statuses(
{'A': 'READY', 'B': 'PENDING'},
{'A': 'PENDING', 'B': 'READY'},
('A', 'B'),
)
assert result == {'A': 'READY', 'B': 'PENDING'}
def test_reconcile_statuses_keeps_matching_sources():
from cbb_refresh_verify.library_reader import reconcile_statuses
assert reconcile_statuses({'A': 'READY'}, {'A': 'READY'}, ('A',)) == {'A': 'READY'}
def test_context_menu_status_parser_is_removed():
import cbb_refresh_verify.library_reader as reader
assert not hasattr(reader, 'status_from_context_menu')
def test_reconcile_uses_persisted_ready_when_tree_id_is_unavailable():
from cbb_refresh_verify.library_reader import reconcile_statuses
assert reconcile_statuses({'A': 'UNKNOWN'}, {'A': 'READY'}, ('A',)) == {'A': 'READY'}
assert reconcile_statuses({'A': 'READY'}, {'A': 'UNKNOWN'}, ('A',)) == {'A': 'READY'}
def test_reconcile_prefers_calibrated_tree_id_over_stale_persisted_status():
from cbb_refresh_verify.library_reader import reconcile_statuses
assert reconcile_statuses({'A': 'PENDING'}, {'A': 'READY'}, ('A',)) == {'A': 'PENDING'}
def test_tree_image_status_is_calibrated_from_filesystem_evidence():
from cbb_refresh_verify.library_reader import infer_tree_statuses
result = infer_tree_statuses(
{'A': 11, 'B': 11, 'C': 12},
{'A': 'PENDING', 'B': 'PENDING', 'C': 'READY'},
('A', 'B', 'C'),
)
assert result == {'A': 'PENDING', 'B': 'PENDING', 'C': 'READY'}
def test_image_status_map_is_derived_from_current_ids_not_fixed_indices():
from cbb_refresh_verify.library_reader import infer_image_status_map
assert infer_image_status_map(
{'A': 401, 'B': 902},
{'A': 'READY', 'B': 'PENDING'},
('A', 'B'),
) == {401: 'READY', 902: 'PENDING'}
assert infer_image_status_map(
{'A': 401, 'B': 401},
{'A': 'READY', 'B': 'PENDING'},
('A', 'B'),
) == {401: 'PENDING'}
def test_pending_id_overrides_stale_complete_cert_for_same_tree_icon():
from cbb_refresh_verify.library_reader import infer_tree_statuses, reconcile_statuses
tree = infer_tree_statuses(
{'PEF7071_PHY': 10, 'IP101GR': 10},
{'PEF7071_PHY': 'READY', 'IP101GR': 'PENDING'},
('PEF7071_PHY', 'IP101GR'),
)
assert tree == {'PEF7071_PHY': 'PENDING', 'IP101GR': 'PENDING'}
assert reconcile_statuses(tree, {'PEF7071_PHY': 'READY', 'IP101GR': 'PENDING'},
('PEF7071_PHY', 'IP101GR')) == {
'PEF7071_PHY': 'PENDING', 'IP101GR': 'PENDING'}
def test_unseen_tree_id_is_pending_when_ready_id_anchor_exists():
from cbb_refresh_verify.library_reader import infer_tree_statuses
assert infer_tree_statuses(
{'READY_CBB_1': 11, 'READY_CBB_2': 11, 'UNVERIFIED_CBB': 10},
{'READY_CBB_1': 'READY', 'READY_CBB_2': 'READY', 'UNVERIFIED_CBB': 'READY'},
('READY_CBB_1', 'READY_CBB_2', 'UNVERIFIED_CBB'),
) == {'READY_CBB_1': 'READY', 'READY_CBB_2': 'READY', 'UNVERIFIED_CBB': 'PENDING'}
def test_status_log_records_unseen_id_inference(caplog, monkeypatch, tmp_path):
import cbb_refresh_verify.library_reader as reader
caplog.set_level('INFO')
monkeypatch.setattr(reader, 'filesystem_evidence_map', lambda _library, names: {
name: {'status': 'READY', 'project_count': 1}
for name in names
})
result = reader.scan_open_library_status(
tmp_path / 'center.lmc',
('READY_CBB_1', 'READY_CBB_2', 'UNVERIFIED_CBB'),
tree_image_reader=lambda _library, _names: {'READY_CBB_1': 11, 'READY_CBB_2': 11, 'UNVERIFIED_CBB': 10},
)
assert result == {'READY_CBB_1': 'READY', 'READY_CBB_2': 'READY', 'UNVERIFIED_CBB': 'PENDING'}
assert 'unseen_tree_id_vs_ready_anchor' in caplog.text
def test_cached_ready_id_classifies_new_tree_id_as_pending(caplog, monkeypatch, tmp_path):
import json
import cbb_refresh_verify.library_reader as reader
caplog.set_level('INFO')
monkeypatch.setattr(reader, 'filesystem_evidence_map', lambda _library, names: {
name: {'status': 'READY', 'project_count': 1}
for name in names
})
store = tmp_path / 'image-map.json'
store.write_text(json.dumps({'schema_version': 2, 'image_status_map': {'11': 'READY'}}), encoding='utf-8')
result = reader.scan_open_library_status(
tmp_path / 'center.lmc',
('READY_CBB', 'UNVERIFIED_CBB'),
mapping_store=store,
tree_image_reader=lambda _library, _names: {'READY_CBB': 11, 'UNVERIFIED_CBB': 10},
)
assert result == {'READY_CBB': 'READY', 'UNVERIFIED_CBB': 'PENDING'}
assert 'cached_ready_anchor' in caplog.text
def test_cached_ready_id_is_not_downgraded_by_transient_pending_files(caplog, monkeypatch, tmp_path):
"""A post-Verify scan may see Cert files before they are fully written."""
import json
import cbb_refresh_verify.library_reader as reader
caplog.set_level('INFO')
monkeypatch.setattr(reader, 'filesystem_evidence_map', lambda _library, names: {
name: {'status': 'PENDING', 'project_count': 1}
for name in names
})
store = tmp_path / 'image-map.json'
store.write_text(json.dumps({'schema_version': 2, 'image_status_map': {'11': 'READY'}}), encoding='utf-8')
result = reader.scan_open_library_status(
tmp_path / 'center.lmc',
('VERIFIED_CBB',),
mapping_store=store,
tree_image_reader=lambda _library, _names: {'VERIFIED_CBB': 11},
)
assert result == {'VERIFIED_CBB': 'READY'}
assert 'cached_image_id_authoritative' in caplog.text
def test_verified_id_transition_uses_cached_ready_anchor(caplog, monkeypatch, tmp_path):
"""After Verify, a stale file snapshot must not downgrade the new ID."""
import json
import cbb_refresh_verify.library_reader as reader
caplog.set_level('INFO')
monkeypatch.setattr(reader, 'filesystem_evidence_map', lambda _library, names: {
name: {'status': 'PENDING', 'project_count': 1}
for name in names
})
store = tmp_path / 'image-map.json'
store.write_text(json.dumps({'schema_version': 2, 'image_status_map': {'10': 'PENDING', '11': 'READY'}}), encoding='utf-8')
result = reader.scan_open_library_status(
tmp_path / 'center.lmc',
('VERIFIED_CBB',),
mapping_store=store,
tree_image_reader=lambda _library, _names: {'VERIFIED_CBB': 11},
)
assert result == {'VERIFIED_CBB': 'READY'}
assert 'cached_image_id_authoritative' in caplog.text
def test_legacy_unversioned_image_cache_is_ignored(monkeypatch, tmp_path):
import json
import cbb_refresh_verify.library_reader as reader
monkeypatch.setattr(reader, 'filesystem_evidence_map', lambda _library, names: {
name: {'status': 'PENDING', 'project_count': 1}
for name in names
})
store = tmp_path / 'image-map.json'
store.write_text(json.dumps({'image_status_map': {'11': 'READY'}}), encoding='utf-8')
result = reader.scan_open_library_status(
tmp_path / 'center.lmc', ('CBB',), mapping_store=store,
tree_image_reader=lambda _library, _names: {'CBB': 11},
)
assert result == {'CBB': 'PENDING'}
def test_no_hardcoded_green_image_index_is_exposed():
import cbb_refresh_verify.library_reader as reader
import cbb_refresh_verify.mentor_adapter as adapter
assert not hasattr(reader, 'READY_IMAGE_INDEX')
assert not hasattr(adapter, 'GREEN_TREE_IMAGE_INDEX')
def test_unanchored_tree_image_is_unknown_instead_of_guessing():
from cbb_refresh_verify.library_reader import infer_tree_statuses
assert infer_tree_statuses({'A': 11}, {'A': 'UNKNOWN'}, ('A',)) == {'A': 'UNKNOWN'}
def test_unanchored_tree_image_is_not_calibrated_without_persisted_status():
from cbb_refresh_verify.library_reader import infer_tree_statuses
result = infer_tree_statuses(
{'A': 27, 'B': 27},
{'A': 'UNKNOWN', 'B': 'UNKNOWN'},
('A', 'B'),
)
assert result == {'A': 'UNKNOWN', 'B': 'UNKNOWN'}
def test_status_scan_logs_each_cbb_image_id(caplog, tmp_path):
from cbb_refresh_verify.library_reader import scan_open_library_status
caplog.set_level('INFO')
result = scan_open_library_status(
tmp_path / 'center.lmc',
('A', 'B'),
tree_image_reader=lambda _library, _names: {'A': 27, 'B': 28},
)
assert set(result) == {'A', 'B'}
assert 'name=A image_id=27' in caplog.text
assert 'name=B image_id=28' in caplog.text
def test_status_scan_keeps_only_missing_cert_or_project_items_pending(tmp_path):
lmc = tmp_path / 'center.lmc'
lmc.touch()
root = lmc.parent / 'ReusableBlocksLP'
ready = root / 'READY_CBB' / 'Work'
(ready / 'PCB' / 'Layout').mkdir(parents=True)
(ready / 'READY_CBB.prj').write_text('KEY PCBDesignPath "PCB\\actual.pcb"', encoding='utf-8')
(ready / 'PCB' / 'actual.pcb').write_text('pcb', encoding='utf-8')
(ready / 'PCB' / 'Layout' / 'LayoutDB.lyt').write_bytes(b'lyt')
cert = ready.parent / 'Cert'
(cert / 'PCB' / 'Layout').mkdir(parents=True)
(cert / 'READY_CBB.prj').write_text('cert', encoding='utf-8')
(cert / 'PCB' / 'actual.pcb').write_text('cert pcb', encoding='utf-8')
(cert / 'PCB' / 'Layout' / 'LayoutDB.lyt').write_bytes(b'cert lyt')
pending = root / 'IP101GR' / 'Work'
(pending / 'PCB' / 'Layout').mkdir(parents=True)
(pending / 'IP101GR.prj').write_text('KEY PCBDesignPath "PCB\\actual.pcb"', encoding='utf-8')
(pending / 'PCB' / 'actual.pcb').write_text('pcb', encoding='utf-8')
(pending / 'PCB' / 'Layout' / 'LayoutDB.lyt').write_bytes(b'lyt')
from cbb_refresh_verify.library_reader import scan_open_library_status
result = scan_open_library_status(
lmc,
('READY_CBB', 'IP101GR', 'MISSING_CBB'),
tree_image_reader=lambda _library, _names: {},
)
assert result == {'READY_CBB': 'READY', 'IP101GR': 'PENDING', 'MISSING_CBB': 'PENDING'}
def test_filesystem_evidence_exposes_multiple_persistent_dimensions(tmp_path):
lmc = tmp_path / 'center.lmc'
lmc.touch()
work = tmp_path / 'ReusableBlocksLP' / 'A_CBB' / 'Work'
(work / 'PCB' / 'Layout').mkdir(parents=True)
(work / 'A_CBB.prj').write_text('KEY PCBDesignPath "PCB\\actual.pcb"', encoding='utf-8')
(work / 'PCB' / 'actual.pcb').write_text('pcb', encoding='utf-8')
(work / 'PCB' / 'Layout' / 'LayoutDB.lyt').write_bytes(b'lyt')
cert = work.parent / 'Cert'
(cert / 'PCB' / 'Layout').mkdir(parents=True)
(cert / 'A_CBB.prj').write_text('cert', encoding='utf-8')
(cert / 'PCB' / 'actual.pcb').write_text('cert pcb', encoding='utf-8')
(cert / 'PCB' / 'Layout' / 'LayoutDB.lyt').write_bytes(b'cert lyt')
from cbb_refresh_verify.library_reader import filesystem_evidence_map
evidence = filesystem_evidence_map(lmc, ('A_CBB',))['A_CBB']
assert evidence['status'] == 'READY'
assert all(evidence[key] for key in (
'work_project', 'work_pcb', 'work_layout',
'cert_project', 'cert_pcb', 'cert_layout'))
def test_filesystem_evidence_preserves_mapped_drive_paths(tmp_path, monkeypatch):
"""Legacy evidence scanning must not resolve a mapped drive back to UNC."""
lmc = tmp_path / 'center.lmc'
lmc.touch()
work = tmp_path / 'ReusableBlocksLP' / 'A_CBB' / 'Work'
(work / 'PCB' / 'Layout').mkdir(parents=True)
(work / 'A_CBB.prj').write_text('KEY PCBDesignPath "PCB\\actual.pcb"', encoding='utf-8')
(work / 'PCB' / 'actual.pcb').write_text('pcb', encoding='utf-8')
(work / 'PCB' / 'Layout' / 'LayoutDB.lyt').write_bytes(b'lyt')
cert = work.parent / 'Cert'
(cert / 'PCB' / 'Layout').mkdir(parents=True)
(cert / 'A_CBB.prj').write_text('cert', encoding='utf-8')
(cert / 'PCB' / 'actual.pcb').write_text('cert pcb', encoding='utf-8')
(cert / 'PCB' / 'Layout' / 'LayoutDB.lyt').write_bytes(b'cert lyt')
monkeypatch.setattr(Path, 'resolve', lambda self: pytest.fail('mapped path was resolved'))
from cbb_refresh_verify.library_reader import filesystem_evidence_map
assert filesystem_evidence_map(lmc, ('A_CBB',))['A_CBB']['status'] == 'READY'
def test_missing_work_project_is_a_pending_calibration_anchor(tmp_path):
lmc = tmp_path / 'center.lmc'
lmc.touch()
(tmp_path / 'ReusableBlocksLP' / 'IMPORTED_CBB').mkdir(parents=True)
from cbb_refresh_verify.library_reader import filesystem_evidence_map
evidence = filesystem_evidence_map(lmc, ('IMPORTED_CBB',))['IMPORTED_CBB']
assert evidence['project_count'] == 0
assert evidence['status'] == 'PENDING'
+36
View File
@@ -0,0 +1,36 @@
from pathlib import Path
from cbb_refresh_verify.mentor_paths import discover_sdd_home
def _install(root: Path):
sdd = root / 'Mentor' / '7.9.5EE' / 'SDD_HOME'
for relative in (
'lm/win32/bin/LibraryManager.exe',
'lm/win32/bin/ReuseBlockImporter.exe',
'common/win32/bin/ExpeditionPCB.exe',
):
path = sdd / relative
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(b'fixture')
return sdd
def test_discover_sdd_home_finds_common_mentor_layout(tmp_path):
expected = _install(tmp_path)
assert discover_sdd_home(environ={}, search_roots=(tmp_path,)) == expected
def test_discover_sdd_home_prefers_explicit_installation(tmp_path):
expected = _install(tmp_path / 'explicit')
_install(tmp_path / 'other')
assert discover_sdd_home(str(expected / 'lm' / 'win32' / 'bin'), environ={},
search_roots=(tmp_path / 'other', tmp_path / 'explicit')) == expected
def test_discover_sdd_home_returns_none_without_known_mentor_binaries(tmp_path):
(tmp_path / 'Mentor' / '7.9.5EE' / 'SDD_HOME').mkdir(parents=True)
assert discover_sdd_home(environ={}, search_roots=(tmp_path,)) is None
+146
View File
@@ -0,0 +1,146 @@
from pathlib import Path
import pytest
from cbb_refresh_verify.network_path import (
LibraryPathLease,
NetworkPathError,
ensure_mapped_drive_visible,
select_library_file,
)
class FakeWNet:
def __init__(self, *, existing=None, used=None):
self.existing = dict(existing or {})
self.used = set(used or self.existing)
self.added = []
self.cancelled = []
def mappings(self):
return dict(self.existing)
def used_drives(self):
return set(self.used)
def add_mapping(self, drive, remote):
self.added.append((drive, remote))
self.existing[drive] = remote
self.used.add(drive)
def cancel_mapping(self, drive):
self.cancelled.append(drive)
self.existing.pop(drive, None)
self.used.discard(drive)
def test_unc_uses_existing_mapping_without_releasing_it():
backend = FakeWNet(existing={"Y:": r"\\server\share"})
with LibraryPathLease.acquire(
r"\\server\share\lib\mentor_lib.lmc", backend=backend
) as lease:
assert lease.mentor_path == Path(r"Y:\lib\mentor_lib.lmc")
assert lease.created is False
assert backend.added == []
assert backend.cancelled == []
def test_created_mapping_is_released():
backend = FakeWNet(used={"Z:"})
lease = LibraryPathLease.acquire(
r"\\server\share\lib\mentor_lib.lmc", backend=backend
)
assert lease.drive == "Y:"
assert backend.added == [("Y:", r"\\server\share")]
lease.close()
assert backend.cancelled == ["Y:"]
def test_created_mapping_is_not_removed_after_external_retarget():
backend = FakeWNet()
lease = LibraryPathLease.acquire(
r"\\server\share\lib\mentor_lib.lmc", backend=backend
)
backend.existing[lease.drive] = r"\\other\share"
lease.close()
assert backend.cancelled == []
def test_local_path_does_not_touch_wnet(tmp_path):
backend = FakeWNet()
lmc = tmp_path / "mentor_lib.lmc"
with LibraryPathLease.acquire(lmc, backend=backend) as lease:
assert lease.mentor_path == lmc
assert backend.added == []
assert backend.cancelled == []
def test_mapped_drive_records_remote_root_without_rebinding(tmp_path):
backend = FakeWNet(existing={"S:": r"\\server\share"})
lease = LibraryPathLease.acquire(
Path(r"S:\mentor_lib.lmc"), backend=backend
)
assert lease.drive == "S:"
assert lease.remote_root == r"\\server\share"
assert lease.created is False
assert backend.added == []
def test_worker_mapping_is_recreated_when_child_cannot_see_drive():
backend = FakeWNet()
result = ensure_mapped_drive_visible(
"S:", r"\\server\share", backend=backend
)
assert result == {"drive": "S:", "remote_root": r"\\server\share", "created": True}
assert backend.added == [("S:", r"\\server\share")]
def test_worker_mapping_rejects_conflicting_drive():
backend = FakeWNet(existing={"S:": r"\\other\share"})
with pytest.raises(NetworkPathError, match="映射冲突"):
ensure_mapped_drive_visible("S:", r"\\server\share", backend=backend)
def test_forward_slash_unc_is_normalized_and_mapped():
backend = FakeWNet()
lease = LibraryPathLease.acquire(
'//server/share/lib/mentor_lib.lmc', backend=backend
)
assert lease.remote_root == r'\\server\share'
assert lease.mentor_path == Path(r'Z:\lib\mentor_lib.lmc')
lease.close()
def test_single_leading_backslash_is_rejected_as_malformed_unc():
with pytest.raises(NetworkPathError, match='两个反斜杠'):
LibraryPathLease.acquire(r'\192.168.0.252\eda\mentor_lib.lmc', backend=FakeWNet())
def test_library_directory_selects_its_only_lmc(tmp_path):
lmc = tmp_path / 'mentor_lib.lmc'
lmc.touch()
assert select_library_file(tmp_path) == lmc
def test_library_directory_rejects_ambiguous_lmc_files(tmp_path):
(tmp_path / 'one.lmc').touch()
(tmp_path / 'two.lmc').touch()
with pytest.raises(NetworkPathError, match='唯一'):
select_library_file(tmp_path)
+14
View File
@@ -0,0 +1,14 @@
from pathlib import Path
def test_spec_uses_onedir_collect_and_product_name():
text=Path('packaging/CbbRefreshVerify.spec').read_text(encoding='utf-8')
assert 'COLLECT(' in text and 'CbbRefreshVerify' in text
def test_build_script_validates_executable():
text=Path('packaging/Build-CbbRefreshVerify.ps1').read_text(encoding='utf-8')
assert 'CbbRefreshVerify.exe' in text
def test_spec_packages_adaptive_dialog_rules_and_uia_modules():
text = Path('packaging/CbbRefreshVerify.spec').read_text(encoding='utf-8')
assert 'dialog_rules.v1.json' in text
assert 'pywinauto' in text
+77
View File
@@ -0,0 +1,77 @@
from pathlib import Path
import json
import subprocess
from cbb_refresh_verify.status_bridge import default_bridge_path
def test_packaged_layout_contains_status_bridge_asset():
spec = Path("packaging/CbbRefreshVerify.spec").read_text(encoding="utf-8")
assert "tools/status_bridge/bin" in spec
assert Path("tools/status_bridge/bin/CbbStatusBridge32.exe").is_file()
def test_packaged_layout_contains_read_only_verify_probe_asset():
spec = Path("packaging/CbbRefreshVerify.spec").read_text(encoding="utf-8")
assert "VerifyProbe32.exe" in spec
assert Path("tools/status_bridge/bin/VerifyProbe32.exe").is_file()
def test_frozen_bridge_lookup_includes_internal_onedir_root():
text = Path("src/cbb_refresh_verify/status_bridge.py").read_text(encoding="utf-8")
assert "_MEIPASS" in text
def test_default_bridge_path_does_not_claim_ready_without_bridge(tmp_path, monkeypatch):
monkeypatch.setenv("CBB_STATUS_BRIDGE", str(tmp_path / "missing.exe"))
path = default_bridge_path()
assert not path.exists()
def test_main_window_default_worker_count_is_one():
text = Path("src/cbb_refresh_verify/ui/main_window.py").read_text(encoding="utf-8")
assert "setMaxThreadCount(1)" in text
def test_main_window_defaults_to_authoritative_bridge_status():
text = Path("src/cbb_refresh_verify/ui/main_window.py").read_text(encoding="utf-8")
assert "authoritative_status=True" in text
def test_spec_keeps_dynamic_main_window_import_in_frozen_package():
spec = Path("packaging/CbbRefreshVerify.spec").read_text(encoding="utf-8")
assert "cbb_refresh_verify.ui.main_window" in spec
def test_main_window_module_imports_without_optional_replacement_package():
import os
import subprocess
import sys
env = os.environ.copy()
env["PYTHONPATH"] = str(Path("src").resolve())
result = subprocess.run(
[sys.executable, "-c", "import cbb_refresh_verify.ui.main_window"],
env=env, capture_output=True, text=True, timeout=15,
)
assert result.returncode == 0, result.stderr
def test_compiled_bridge_json_codec_round_trips_unc_path():
bridge = Path('tools/status_bridge/bin/CbbStatusBridge32.exe').resolve()
request = {
'request_id': 'codec-1',
'lmc_file': r'\\192.168.0.252\eda\Mentor_lib\mentor_lib.lmc',
'block_name': 'CBB_TEST',
}
result = subprocess.run(
[str(bridge), '--codec-test'],
input=json.dumps(request, ensure_ascii=False) + '\n',
capture_output=True,
text=True,
encoding='utf-8',
timeout=10,
)
assert result.returncode == 0, result.stdout + result.stderr
assert json.loads(result.stdout) == request
+91
View File
@@ -0,0 +1,91 @@
import pytest
from cbb_refresh_verify.pcb_bridge import (
PcbBridgeError,
execution_outcome,
require_document_identity,
wait_for_target_document,
)
class ProjectIntegration:
def __init__(self, project):
self.ProjectFile = str(project)
class Document:
def __init__(self, name, project):
self.Name = name
self.ProjectIntegration = ProjectIntegration(project)
class Application:
def __init__(self, document):
self.ActiveDocument = document
def job(tmp_path):
return {
'project': str(tmp_path / 'Work' / 'CBB.prj'),
'pcb': str(tmp_path / 'Work' / 'PCB' / 'CBB.pcb'),
}
def test_bridge_rejects_wrong_document_before_actions(tmp_path):
current = Document('OTHER.pcb', tmp_path / 'Work' / 'OTHER.prj')
with pytest.raises(PcbBridgeError, match='身份不符') as raised:
require_document_identity(current, job(tmp_path))
assert raised.value.error_code == 'PCB_IDENTITY_MISMATCH'
def test_bridge_attaches_through_com_without_window_title_gate(tmp_path):
expected = Document('CBB.pcb', tmp_path / 'Work' / 'CBB.prj')
attempts = iter((RuntimeError('not ready'), Application(expected)))
events = []
def provider():
value = next(attempts)
if isinstance(value, Exception):
raise value
return value
app, document, integration = wait_for_target_document(
job(tmp_path), provider, process_alive=lambda: True,
emit=lambda **event: events.append(event), sleep=lambda _seconds: None,
)
assert app.ActiveDocument is document
assert integration.ProjectFile.endswith('CBB.prj')
assert not any(event['stage'] == 'com_wait' for event in events)
assert events[-1]['stage'] == 'identity_verified'
def test_bridge_stops_if_pcb_exits_before_com_is_ready(tmp_path):
alive = iter((True, False))
with pytest.raises(PcbBridgeError) as raised:
wait_for_target_document(
job(tmp_path), lambda: (_ for _ in ()).throw(RuntimeError('not ready')),
process_alive=lambda: next(alive), sleep=lambda _seconds: None,
)
assert raised.value.error_code == 'PCB_EXITED_BEFORE_COM'
def test_fatal_dialog_overrides_successful_save_markers():
result = execution_outcome(
save_complete=True,
pcb_exited=True,
fatal_error='SAVE_REUSABLE_BLOCK_FAILED: Error saving the Reusable Block',
)
assert result['status'] == 'FAIL'
assert result['error_code'] == 'SAVE_REUSABLE_BLOCK_FAILED'
def test_success_requires_save_and_pcb_exit():
assert execution_outcome(save_complete=True, pcb_exited=True)['status'] == 'PASS'
assert execution_outcome(save_complete=False, pcb_exited=True)['status'] == 'FAIL'
assert execution_outcome(save_complete=True, pcb_exited=False)['status'] == 'FAIL'
+52
View File
@@ -0,0 +1,52 @@
from cbb_refresh_verify.post_verify_diagnostics import build_snapshot, invoke_with_evidence
def test_invoke_evidence_distinguishes_entering_from_returning():
events = []
def invoke():
assert events == [{'stage': 'verify_invoke', 'lm_pid': 100}]
invoke_with_evidence(invoke, events.append, {'lm_pid': 100})
assert events == [
{'stage': 'verify_invoke', 'lm_pid': 100},
{'stage': 'verify_invoke_returned', 'lm_pid': 100},
]
def test_invoke_failure_does_not_claim_returned():
events = []
def invoke():
raise RuntimeError('COM invocation failed')
try:
invoke_with_evidence(invoke, events.append, {'lm_pid': 100})
except RuntimeError:
pass
assert events == [{'stage': 'verify_invoke', 'lm_pid': 100}]
def test_snapshot_records_preexisting_and_rejected_pcb_processes():
processes = [
(20, 'ExpeditionPCB.exe', r'D:\Mentor\wg\ExpeditionPCB.exe',
r'D:\Mentor\wg\ExpeditionPCB.exe "F:\library\target.pcb" -ReusableCircuit'),
(21, 'exppcb.exe', r'D:\Mentor\wg\exppcb.exe',
r'D:\Mentor\wg\exppcb.exe "F:\library\target.pcb"'),
(22, 'ExpeditionPCB.exe', r'D:\Mentor\wg\ExpeditionPCB.exe',
r'D:\Mentor\wg\ExpeditionPCB.exe "F:\library\target.pcb" -ReusableCircuit'),
]
snapshot = build_snapshot(processes, [], r'F:\library\target.pcb', {20})
assert [(p['pid'], p['preexisting'], p['matches_current_filter'])
for p in snapshot['processes']] == [
(20, True, True), (21, False, False), (22, False, True),
]
def test_snapshot_keeps_lm_modal_details_without_changing_windows():
modal = {'pid': 100, 'hwnd': 9, 'class_name': '#32770',
'title': 'Confirm Verify', 'texts': ['OK', 'Cancel']}
snapshot = build_snapshot([], [modal], r'F:\library\target.pcb', set())
assert snapshot['windows'] == [modal]
+79
View File
@@ -0,0 +1,79 @@
import pytest
from cbb_refresh_verify.runtime_timing import RunTimings, parse_save_progress
def test_phase_duration_uses_worker_monotonic_time_not_delayed_poll_time():
now = [900.0]
timer = RunTimings(clock=lambda: now[0])
timer.record({'stage': 'pcb_launch', 'monotonic_seconds': 1000.0})
now[0] = 1600
timer.record({'stage': 'identity_verified', 'monotonic_seconds': 1132.0})
assert timer.snapshot()[0]['pcb_startup'] == 132.0
def test_action_and_save_subtimings_accumulate_real_durations():
timer = RunTimings(clock=lambda: 1000.0)
timer.record({'stage': 'integration_action_complete', 'action': 'ForwardAnnotate',
'elapsed_seconds': 341, 'call_elapsed_seconds': 336})
timer.record({'stage': 'integration_action_complete', 'action': 'BackAnnotate',
'elapsed_seconds': 4, 'call_elapsed_seconds': 3})
timer.record({'stage': 'save_progress', 'timings_seconds': {'save': 246, 'close': 3}})
durations, unfinished = timer.snapshot()
assert durations['forward_annotation'] == 341
assert durations['forward_annotation_call'] == 336
assert durations['back_annotation'] == 4
assert durations['save'] == 246
assert durations['close'] == 3
assert 'synch_ces' not in durations # skipped is not a zero-time measurement
def test_timeout_reports_unfinished_phase_without_fabricating_completion():
now = [10.0]
timer = RunTimings(clock=lambda: now[0])
timer.record({'stage': 'save_start', 'monotonic_seconds': 15})
now[0] = 45
durations, unfinished = timer.snapshot()
assert durations['save_close'] == 30
assert unfinished == ('save_close',)
assert 'save' not in durations
assert durations['total'] == 35
def test_save_helper_timing_parser_keeps_completion_markers():
result = parse_save_progress('SAVE_START\nTIMING|save|246.250\nSAVE_OK\nTIMING|close|3.125\nCLOSE_OK\n')
assert result == {'markers': ['SAVE_START', 'SAVE_OK', 'CLOSE_OK'],
'timings_seconds': {'save': 246.25, 'close': 3.125}}
@pytest.mark.parametrize('invalid', ['TIMING|save|NaN', 'TIMING|save|-1', 'TIMING|save|bad'])
def test_invalid_helper_timing_never_poison_result(invalid):
assert parse_save_progress(invalid)['timings_seconds'] == {}
def test_returned_but_rejected_save_is_not_reported_as_still_in_call():
now = [10.0]
timer = RunTimings(clock=lambda: now[0])
timer.record({'stage': 'save_progress', 'markers': ['SAVE_START'], 'monotonic_seconds': 12})
now[0] = 30
timer.record({'stage': 'save_progress', 'markers': ['SAVE_START'],
'timings_seconds': {'save': 5}})
durations, unfinished = timer.snapshot()
assert durations['save'] == 5
assert 'save' not in unfinished
def test_repeat_action_and_repeated_save_snapshot_do_not_double_count():
timer = RunTimings(clock=lambda: 1000.0)
for _ in range(2):
timer.record({'stage': 'integration_action_complete', 'action': 'ForwardAnnotate',
'elapsed_seconds': 10, 'call_elapsed_seconds': 8})
event = {'stage': 'save_progress', 'markers': ['SAVE_START', 'SAVE_OK'],
'timings_seconds': {'save': 30}}
timer.record(event)
timer.record(event)
values, unfinished = timer.snapshot()
assert values['forward_annotation'] == 20
assert values['forward_annotation_call'] == 16
assert values['save'] == 30
assert unfinished == ()
+112
View File
@@ -0,0 +1,112 @@
"""Production safeguards: no input injection, no desktop switching, no menu driving.
These asserts encode the operating rules for this tool: the user's mouse,
keyboard and desktop are never touched. Dialogs that belong to a process this
run started are answered with a posted BM_CLICK, which is a message to that
dialog and not user input.
"""
from pathlib import Path
SOURCE_ROOT = Path(__file__).resolve().parents[1]/'src'/'cbb_refresh_verify'
# Anything that moves the cursor, injects input, switches desktops, or drives
# the Library Manager menu/keyboard must never appear in production code.
FORBIDDEN_APIS = (
'mouse_event',
'SendInput',
'SetCursorPos',
'SwitchDesktop',
'click_input',
'SendKeys',
'keybd_event',
'SetForegroundWindow',
'SetActiveWindow',
'AttachThreadInput',
'WM_MOUSEMOVE',
'WM_CONTEXTMENU',
'WM_COMMAND',
'VK_APPS',
'TVM_SELECTITEM',
'EndMenu',
)
def production_sources():
return sorted(path for path in SOURCE_ROOT.rglob('*.py') if '__pycache__' not in path.parts)
def test_no_input_injection_or_desktop_switching_in_production_code():
offenders = []
for path in production_sources():
text = path.read_text(encoding='utf-8')
for api in FORBIDDEN_APIS:
if path.name == 'library_manager_verify.py' and api in {'WM_MOUSEMOVE', 'TVM_SELECTITEM'}:
continue
if path.name == 'library_manager_verify.py' and api == 'click_input':
# The only permitted real-input route is the explicit
# interactive compatibility mode; the default worker remains
# isolated and never reaches this branch.
continue
if api in text:
offenders.append(f'{path.name}: {api}')
assert offenders == [], f'输入注入/桌面切换/菜单驱动 API 不得出现在生产代码: {offenders}'
def test_library_manager_verify_route_is_private_and_semantic():
text = (SOURCE_ROOT/'library_manager_verify.py').read_text(encoding='utf-8')
assert 'launch_library_verify' in text
assert 'invoke_with_evidence(' in text and 'verify_action.invoke,' in text
# WM_COMMAND dispatch was experimentally disproved on EE7.9 and must not
# return to the production path. The only fallback is a message posted to
# the private popup menu itself, after semantic Verify resolution.
assert '_post_lmc_menu_command' not in text
assert 'verify_command_posted' not in text
assert '_post_menu_item_click' in text
assert 'WM_RBUTTONDOWN' in text and 'WM_RBUTTONUP' in text
assert 'SetCursorPos' not in text
assert 'SendInput' not in text
assert 'SetForegroundWindow' not in text
def test_real_input_is_guarded_by_explicit_interactive_mode():
text = (SOURCE_ROOT/'library_manager_verify.py').read_text(encoding='utf-8')
assert 'if interactive_input:' in text
assert 'item.click_input(button=\'right\')' in text
assert 'if menu_handle and not interactive_input:' in text
def test_batch_execution_uses_observed_reusable_circuit_route():
import inspect
from cbb_refresh_verify import mentor_adapter
text = inspect.getsource(mentor_adapter.execute_job)
assert 'native_lm_verify' in text
assert "job['lmc_file']" in text
assert 'launch_pcb_process' in text
def test_dialog_handling_only_posts_button_clicks():
text = (SOURCE_ROOT/'mentor_adapter.py').read_text(encoding='utf-8')
assert 'BM_CLICK' in text
# The only posted messages are the documented dialog button clicks.
assert text.count('PostMessage') == 1
def test_desktop_worker_close_kills_unbound_worker_tree():
text = (SOURCE_ROOT/'desktop_worker.py').read_text(encoding='utf-8')
assert 'if self.poll() is None:' in text
assert 'self.kill()' in text
def test_verification_never_deletes_or_moves_library_files():
for path in production_sources():
text = path.read_text(encoding='utf-8')
for operation in ('os.remove', '.unlink('):
assert operation not in text, f'{path.name} 不得删除/移动中心库文件'
adapter = (SOURCE_ROOT/'mentor_adapter.py').read_text(encoding='utf-8')
assert "Path(root) / 'backup'" in adapter
assert 'shutil.rmtree(backup)' in adapter
# The only library-side mutation is quarantining the volatile, unreachable
# cdbsvr address advertisement; stable CBB content remains untouched.
assert adapter.count('shutil.move') == 1
assert "sAddress.adr" in adapter
+77
View File
@@ -0,0 +1,77 @@
import os
from pathlib import Path
import subprocess
import pytest
from cbb_refresh_verify.runtime_timing import parse_save_progress
@pytest.mark.parametrize('save_ok', [True, False])
def test_packaged_vbs_measures_real_save_call_and_preserves_failure_gate(tmp_path, save_ok):
# Execute the real helper in its target 32-bit host. Only external COM
# object creation is replaced; Save/Validate/Close order and timers are real.
script = Path(__file__).parents[1] / 'src/cbb_refresh_verify/save_verified_block.vbs'
source = script.read_text(encoding='utf-8')
classes = r'''
Class FakePi
Public ProjectFile, ForwardAnnotationStatus, SynchCESStatus, LoadCESStatus, BackAnnotationStatus
Private Sub Class_Initialize
ProjectFile = WScript.Arguments(0)
ForwardAnnotationStatus = 2
SynchCESStatus = 2
LoadCESStatus = 2
BackAnnotationStatus = 2
End Sub
End Class
Class FakeDoc
Public Property Get ProjectIntegration
Set ProjectIntegration = New FakePi
End Property
Public Function Validate(token)
Validate = 17
End Function
Public Function Save()
WScript.Sleep 120
Save = SAVE_RETURN
End Function
Public Function IsSaved()
IsSaved = True
End Function
Public Function Close(saveChanges)
Close = True
End Function
End Class
Class FakeApp
Public Property Get ActiveDocument
Set ActiveDocument = New FakeDoc
End Property
Public Sub Quit()
End Sub
End Class
Class FakeLic
Public Function GetToken(value)
GetToken = value
End Function
End Class
'''
source = source.replace('Option Explicit', 'Option Explicit\n' + classes.replace('SAVE_RETURN', str(save_ok)))
source = source.replace('GetObject(, "MGCPCB.Application")', 'New FakeApp')
source = source.replace('CreateObject("MGCPCBAutomationLicensing.Application")', 'New FakeLic')
harness = tmp_path/'save_harness.vbs'
harness.write_text(source, encoding='ascii')
cscript = Path(os.environ['WINDIR'])/'SysWOW64/cscript.exe'
completed = subprocess.run([str(cscript), '//nologo', str(harness), 'expected.prj'],
capture_output=True, text=True, timeout=10)
parsed = parse_save_progress(completed.stdout)
assert parsed['timings_seconds']['save'] >= .08
if save_ok:
assert completed.returncode == 0, completed.stderr
assert 'SAVE_OK' in parsed['markers']
assert 'CLOSE_OK' in parsed['markers']
assert parsed['timings_seconds']['post_save_check'] >= 0
assert parsed['timings_seconds']['close'] >= 0
else:
assert completed.returncode == 4, completed.stderr
assert 'SAVE_OK' not in parsed['markers']
assert 'CLOSE_OK' not in parsed['markers']
+140
View File
@@ -0,0 +1,140 @@
from pathlib import Path
from cbb_refresh_verify.status_bridge import (
BridgeResult,
BridgeUnavailable,
BridgeResponseError,
parse_bridge_response,
StatusBridgeClient,
)
import pytest
def test_parse_ready_response_preserves_raw_evidence():
result = parse_bridge_response(
'{"ok":true,"status":"READY","source":"IsVerifiedReuseBlock","raw_status":2}'
)
assert result.status == "READY"
assert result.source == "IsVerifiedReuseBlock"
assert result.raw_status == 2
def test_parse_rejects_success_without_authoritative_status():
try:
parse_bridge_response('{"ok":true,"status":"UNKNOWN"}')
except BridgeResponseError as error:
assert "authoritative" in str(error)
else:
raise AssertionError("missing authoritative status must be rejected")
def test_unavailable_bridge_has_actionable_diagnostic(tmp_path):
missing = tmp_path / "CbbStatusBridge32.exe"
try:
raise BridgeUnavailable(missing)
except BridgeUnavailable as error:
assert str(missing) in str(error)
assert "32-bit" in str(error)
def test_bridge_rejects_mismatched_response_identity():
line = ('{"ok":true,"request_id":"request-2","block_name":"OTHER",'
'"lmc_file":"C:/lib/other.lmc","status":"READY",'
'"source":"IsVerifiedReuseBlock","raw_status":1}')
with pytest.raises(BridgeResponseError, match='请求标识'):
parse_bridge_response(line, expected_request_id='request-1',
expected_block='TARGET', expected_lmc='C:/lib/mentor_lib.lmc')
def test_bridge_accepts_correlated_response():
line = ('{"ok":true,"request_id":"request-1","block_name":"TARGET",'
'"lmc_file":"C:/lib/mentor_lib.lmc","status":"READY",'
'"source":"IsVerifiedReuseBlock","raw_status":1}')
result = parse_bridge_response(line, expected_request_id='request-1',
expected_block='TARGET', expected_lmc='C:/lib/mentor_lib.lmc')
assert result == BridgeResult(
'READY', 'IsVerifiedReuseBlock', 1, '', result.response,
request_id='request-1', block_name='TARGET', lmc_file='C:/lib/mentor_lib.lmc')
def test_bridge_accepts_legacy_response_with_redundant_unc_separators():
line = ('{"ok":true,"request_id":"request-1","block_name":"TARGET",'
'"lmc_file":"\\\\\\\\\\\\\\\\192.168.0.252\\\\\\\\eda\\\\\\\\lib\\\\\\\\mentor_lib.lmc",'
'"status":"READY","source":"IsVerifiedReuseBlock","raw_status":1}')
result = parse_bridge_response(
line,
expected_request_id='request-1',
expected_block='TARGET',
expected_lmc=r'\\192.168.0.252\eda\lib\mentor_lib.lmc',
)
assert result.status == 'READY'
def test_one_shot_client_preserves_mapped_drive_in_request(tmp_path, monkeypatch):
executable = tmp_path / 'CbbStatusBridge32.exe'
executable.touch()
captured = {}
class Process:
returncode = 0
def communicate(self, request_line, timeout):
import json
request = json.loads(request_line)
captured.update(request)
return json.dumps({
'ok': True,
'request_id': request['request_id'],
'block_name': request['block_name'],
'lmc_file': request['lmc_file'],
'status': 'READY',
'source': 'IsVerifiedReuseBlock',
}), ''
monkeypatch.setattr(
'cbb_refresh_verify.status_bridge.subprocess.Popen',
lambda *args, **kwargs: Process(),
)
StatusBridgeClient(executable).query(Path(r'Y:\library\mentor_lib.lmc'), 'TARGET')
assert captured['lmc_file'] == r'Y:\library\mentor_lib.lmc'
def test_one_shot_client_passes_private_read_opt_in_to_bridge(tmp_path, monkeypatch):
executable = tmp_path / 'CbbStatusBridge32.exe'
executable.touch()
captured = {}
class Process:
returncode = 0
def communicate(self, request_line, timeout):
import json
request = json.loads(request_line)
response = {
'ok': True,
'request_id': request['request_id'],
'block_name': request['block_name'],
'lmc_file': request['lmc_file'],
'status': 'READY',
'source': 'IsVerifiedReuseBlock',
'raw_status': 1,
}
return json.dumps(response), ''
def popen(*args, **kwargs):
captured.update(kwargs.get('env') or {})
return Process()
monkeypatch.setattr('cbb_refresh_verify.status_bridge.subprocess.Popen', popen)
result = StatusBridgeClient(
executable, env={'CBB_STATUS_BRIDGE_ALLOW_PRIVATE': '1'}
).query(tmp_path / 'mentor_lib.lmc', 'TARGET')
assert result.status == 'READY'
assert captured['CBB_STATUS_BRIDGE_ALLOW_PRIVATE'] == '1'
+46
View File
@@ -0,0 +1,46 @@
import json
import subprocess
import sys
from pathlib import Path
def run_server_client(fake_server, names):
process = subprocess.Popen(
[sys.executable, str(fake_server)],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
text=True,
)
requests = []
for name in names:
requests.append(json.dumps({"op": "is_verified", "lmc_file": "x.lmc",
"block_name": name, "block_type": "RULP"}) + "\n")
stdout, _ = process.communicate("".join(requests), timeout=5)
return [json.loads(line) for line in stdout.splitlines() if line.strip()]
def test_server_response_is_one_line_per_request(tmp_path):
fake = tmp_path / "fake_server.py"
fake.write_text(
"import json,sys\n"
"for line in sys.stdin:\n"
" p=json.loads(line); print(json.dumps({'ok':True,'block_name':p['block_name'],'status':'READY','source':'fake'}), flush=True)\n",
encoding="utf-8",
)
result = run_server_client(fake, ["A", "B"])
assert [item["block_name"] for item in result] == ["A", "B"]
def test_one_bad_request_does_not_stop_following_request(tmp_path):
fake = tmp_path / "fake_server.py"
fake.write_text(
"import json,sys\n"
"for line in sys.stdin:\n"
" p=json.loads(line)\n"
" if p.get('block_name') == 'BAD': print(json.dumps({'ok':False,'error':'bad'}), flush=True)\n"
" else: print(json.dumps({'ok':True,'block_name':p['block_name'],'status':'PENDING','source':'fake'}), flush=True)\n",
encoding="utf-8",
)
result = run_server_client(fake, ["BAD", "GOOD"])
assert result[0]["ok"] is False
assert result[1]["ok"] is True
+267
View File
@@ -0,0 +1,267 @@
import os
from pathlib import Path
os.environ.setdefault('QT_QPA_PLATFORM','offscreen')
from cbb_refresh_verify.models import CbbRecord, LibraryReadResult
from cbb_refresh_verify.ui.main_window import MainWindow
from cbb_refresh_verify.verify_runner import VerifyResult
from threading import Event
from PySide6.QtCore import Qt
from PySide6.QtGui import QPalette
def test_application_palette_keeps_table_text_readable(qtbot):
from PySide6.QtWidgets import QApplication
from cbb_refresh_verify.application import configure_qt_application
app = QApplication.instance()
configure_qt_application(app)
text = app.palette().color(QPalette.ColorRole.Text)
base = app.palette().color(QPalette.ColorRole.Base)
assert text.value() < 100
assert base.value() > 180
def fake_reader(_): return LibraryReadResult((CbbRecord('CBB1','Reusable Blocks'),))
def test_verify_requires_loaded_library_and_invalidates_on_path_change(qtbot):
window=MainWindow(reader=fake_reader, verifier=lambda _: VerifyResult('PASS')); qtbot.addWidget(window)
assert not window.batch_button.isEnabled()
window.lmc_edit.setText('lib.lmc'); window.load_library()
qtbot.waitUntil(lambda: window.batch_button.isEnabled())
# LibSpec / DMS config are optional: they only add the contents check.
assert hasattr(window, 'libspec_edit') and hasattr(window, 'dms_edit')
window.lmc_edit.setText('different.lmc')
assert not window.batch_button.isEnabled()
assert window.cbb_table.rowCount() == 0
def test_ui_removes_current_cbb_controls_and_hides_advanced_settings(qtbot):
window = MainWindow(reader=fake_reader, verifier=lambda _: VerifyResult('PASS'))
qtbot.addWidget(window)
assert not hasattr(window, 'cbb_combo')
assert not hasattr(window, 'verify_button')
assert window.advanced_panel.isHidden()
window.advanced_toggle.click()
assert not window.advanced_panel.isHidden()
def test_window_title_and_action_buttons_are_polished(qtbot):
window = MainWindow(reader=fake_reader, verifier=lambda _: VerifyResult('PASS'))
qtbot.addWidget(window)
assert '后台串行' not in window.windowTitle()
assert not window.windowIcon().isNull()
for button in (window.load_button, window.browse_button, window.selected_batch_button,
window.batch_button, window.stop_button, window.logs_button):
assert not button.icon().isNull()
def test_import_incomplete_rows_are_skipped_and_disabled(qtbot, tmp_path):
lmc = tmp_path / 'center.lmc'
lmc.touch()
broken = tmp_path / 'ReusableBlocksLP' / 'BROKEN_CBB' / 'Work'
broken.mkdir(parents=True)
valid = tmp_path / 'ReusableBlocksLP' / 'VALID_CBB' / 'Work'
(valid / 'PCB' / 'Layout').mkdir(parents=True)
(valid / 'VALID_CBB.prj').write_text('KEY PCBDesignPath "PCB\\actual.pcb"', encoding='utf-8')
(valid / 'PCB' / 'actual.pcb').write_text('pcb', encoding='utf-8')
(valid / 'PCB' / 'Layout' / 'LayoutDB.lyt').write_bytes(b'lyt')
calls = []
def reader(_):
return LibraryReadResult((CbbRecord('BROKEN_CBB', 'LP'), CbbRecord('VALID_CBB', 'LP')))
window = MainWindow(reader=reader,
verifier=lambda req: (calls.append(req.block_name) or VerifyResult('PASS')),
data_root=tmp_path)
qtbot.addWidget(window)
window.lmc_edit.setText(str(lmc))
window.load_library()
qtbot.waitUntil(lambda: window.batch_button.isEnabled())
assert window.cbb_table.item(0, 2).text().startswith('跳过:')
assert not (window.cbb_table.item(0, 0).flags() & Qt.ItemIsUserCheckable)
window.verify_all()
qtbot.waitUntil(lambda: not window.busy)
assert calls == ['VALID_CBB']
def test_batch_does_not_block_ui_and_stop_skips_next_item(qtbot,tmp_path):
entered, release = Event(), Event()
calls=[]
def verify(req):
calls.append(req.block_name); entered.set()
release.wait(3)
return VerifyResult('PASS')
def reader(_): return LibraryReadResult((CbbRecord('A','LP'),CbbRecord('B','LP')))
window=MainWindow(reader=reader,verifier=verify,data_root=tmp_path)
qtbot.addWidget(window); window.lmc_edit.setText('lib.lmc');window.load_library()
qtbot.waitUntil(lambda: window.batch_button.isEnabled())
window.verify_all()
try:
qtbot.waitUntil(entered.is_set)
assert window.stop_button.isEnabled()
window.stop_button.click()
finally:
release.set()
qtbot.waitUntil(lambda: not window.busy)
assert calls == ['A']
assert list((tmp_path/'reports').glob('*.log'))
def test_loaded_library_shows_selectable_rows_and_selected_batch_action(qtbot, tmp_path):
def reader(_): return LibraryReadResult((CbbRecord('A', 'LP'), CbbRecord('B', 'LP')))
window = MainWindow(reader=reader, verifier=lambda _: VerifyResult('PASS'), data_root=tmp_path)
qtbot.addWidget(window)
window.lmc_edit.setText('lib.lmc')
window.load_library()
qtbot.waitUntil(lambda: window.batch_button.isEnabled())
assert window.cbb_table.rowCount() == 2
assert not window.selected_batch_button.isEnabled()
window.cbb_table.item(0, 0).setCheckState(Qt.Checked)
window.selected_batch_button.click()
qtbot.waitUntil(lambda: not window.busy)
assert (tmp_path / 'reports').exists()
assert window.cbb_table.item(0, 2).text() == '绿色 / Ready'
assert window.cbb_table.item(0, 3).text() == 'PASS'
def test_large_library_load_does_not_update_controls_for_every_table_cell(qtbot, tmp_path):
records = tuple(CbbRecord(f'CBB_{index:04d}', 'LP') for index in range(300))
window = MainWindow(reader=lambda _: LibraryReadResult(records), data_root=tmp_path)
qtbot.addWidget(window)
calls = []
original_update = window._update
window._update = lambda: (calls.append(window.cbb_table.rowCount()), original_update())[1]
window.lmc_edit.setText(str(tmp_path / 'center.lmc'))
window.load_library()
qtbot.waitUntil(lambda: not window.busy)
assert window.cbb_table.rowCount() == 300
assert window._row_by_name['CBB_0299'] == 299
assert len(calls) < 20
def test_ready_rows_show_status_and_cannot_be_selected_or_verified(qtbot, tmp_path):
def reader(_):
return LibraryReadResult((CbbRecord('READY_CBB', 'LP', status='READY'), CbbRecord('PENDING_CBB', 'LP', status='PENDING')))
calls = []
window = MainWindow(reader=reader, verifier=lambda req: (calls.append(req.block_name) or VerifyResult('PASS')), data_root=tmp_path)
qtbot.addWidget(window)
window.lmc_edit.setText('lib.lmc')
window.load_library()
qtbot.waitUntil(lambda: window.batch_button.isEnabled())
assert window.cbb_table.columnCount() == 4
assert window.cbb_table.item(0, 2).text() == '绿色 / Ready'
assert not (window.cbb_table.item(0, 0).flags() & Qt.ItemIsUserCheckable)
assert window.cbb_table.item(0, 0).background().color().name().lower() == '#e8f5e9'
window.cbb_table.item(0, 0).setCheckState(Qt.Checked)
assert 'READY_CBB' not in window._selected_names()
window.verify_all()
qtbot.waitUntil(lambda: not window.busy)
assert calls == ['PENDING_CBB']
assert window.cbb_table.item(1, 0).checkState() == Qt.Unchecked
assert not (window.cbb_table.item(1, 0).flags() & Qt.ItemIsUserCheckable)
assert window.cbb_table.item(1, 0).background().color().name().lower() == '#e8f5e9'
def test_unc_library_uses_mentor_path_for_read_and_verify_and_releases_on_close(qtbot, tmp_path):
calls = []
class FakeLease:
display_path = Path(r'\\server\share\mentor_lib.lmc')
mentor_path = Path(r'Y:\mentor_lib.lmc')
closed = False
def close(self):
self.closed = True
lease = FakeLease()
def lease_factory(path):
assert str(path) == str(lease.display_path)
return lease
def reader(path):
calls.append(path)
return LibraryReadResult((CbbRecord('CBB1', 'LP', status='PENDING'),))
window = MainWindow(reader=reader, data_root=tmp_path, path_lease_factory=lease_factory)
qtbot.addWidget(window)
window.lmc_edit.setText(str(lease.display_path))
window.load_library()
qtbot.waitUntil(lambda: not window.busy)
assert calls == [lease.mentor_path]
assert window._request('CBB1').lmc_file == lease.mentor_path
window.close()
assert lease.closed
def test_advanced_options_are_copied_to_verify_request(qtbot, tmp_path):
window = MainWindow(reader=fake_reader, data_root=tmp_path)
qtbot.addWidget(window)
window.loaded_path = 'display.lmc'
window.mentor_lmc_path = Path(r'Y:\lib\mentor_lib.lmc')
window.libspec_edit.setText('EE7.9_CUSTOM')
window.dms_edit.setText(r'Y:\config\login.conf')
window.mentor_bin_edit.setText(r'D:\Mentor\bin')
window.timeout_spin.setValue(45)
request = window._request('CBB1')
assert request.lmc_file == Path(r'Y:\lib\mentor_lib.lmc')
assert request.libspec == 'EE7.9_CUSTOM'
assert request.dms_login_config == r'Y:\config\login.conf'
assert request.mentor_bin == r'D:\Mentor\bin'
assert request.timeout_seconds == 45
def test_ui_request_keeps_background_trigger_mode(qtbot, tmp_path):
window = MainWindow(reader=fake_reader, data_root=tmp_path)
qtbot.addWidget(window)
window.loaded_path = 'display.lmc'
window.mentor_lmc_path = Path(r'Y:\lib\mentor_lib.lmc')
assert window._request('CBB1').interactive_input is False
def test_ui_request_exposes_native_lm_verify_compatibility_switch(qtbot, tmp_path):
window = MainWindow(reader=fake_reader, data_root=tmp_path)
qtbot.addWidget(window)
window.loaded_path = 'display.lmc'
window.mentor_lmc_path = Path(r'Y:\lib\mentor_lib.lmc')
assert window._request('CBB1').native_lm_verify is False
window.native_lm_verify_check.setChecked(True)
assert window._request('CBB1').native_lm_verify is True
def test_library_directory_input_uses_its_only_lmc(qtbot, tmp_path):
lmc = tmp_path / 'mentor_lib.lmc'
lmc.touch()
calls = []
window = MainWindow(
reader=lambda path: (
calls.append(path) or LibraryReadResult((CbbRecord('CBB1', 'LP'),))
),
data_root=tmp_path / 'data',
)
qtbot.addWidget(window)
window.lmc_edit.setText(str(tmp_path))
window.load_library()
qtbot.waitUntil(lambda: not window.busy)
assert calls == [lmc]
assert window._request('CBB1').lmc_file == lmc
def test_ui_default_timeout_matches_request_and_labels_inactivity(qtbot):
from cbb_refresh_verify.verify_runner import VerifyRequest
window = MainWindow(reader=fake_reader)
qtbot.addWidget(window)
assert window.timeout_spin.value() == 600
assert window.timeout_spin.value() == VerifyRequest(Path('lib.lmc'), 'CBB1', Path('data')).timeout_seconds
assert '无进展' in window.timeout_spin.suffix()
def test_batch_summary_exposes_failures_only_report(qtbot, tmp_path):
window = MainWindow(reader=fake_reader, data_root=tmp_path)
qtbot.addWidget(window)
report=tmp_path/'reports/batch-20260929-test.log'
window._batch_done(([VerifyResult('FAIL',stderr='Mentor error')],report))
assert '仅失败日志' in window.summary.text()
assert str(report.with_name('failures-20260929-test.log')) in window.summary.text()
+150
View File
@@ -0,0 +1,150 @@
from pathlib import Path
import json
import pytest
from cbb_refresh_verify import verify_diagnostics as diagnostics
def pcb_fixture(tmp_path):
pcb = tmp_path / 'CBB' / 'Work' / 'PCB' / 'CBB.pcb'
pcb.parent.mkdir(parents=True)
pcb.write_bytes(b'PCB')
return pcb
def test_missing_generated_jobprefs_is_warning_not_a_failure(tmp_path):
pcb = pcb_fixture(tmp_path)
record = diagnostics.collect_preflight_diagnostics(pcb, tmp_path / 'evidence')
assert record['non_blocking'] is True
assert record['directory_writable'] is True
assert len(record['paths']) == 4
assert any(item['path'].endswith(str(Path('Work/Layout_Temp/JobPrefsDB.jpf')))
for item in record['paths'])
assert len(record['warnings']) == 3
assert list(pcb.parent.iterdir()) == [pcb] # no fake dirs, lock or prefs files
assert json.loads((tmp_path/'evidence/diagnostics/preflight.json').read_text('utf-8')) == record
def test_jobprefs_readable_probe_reads_only_one_byte_and_closes_handle(tmp_path, monkeypatch):
pcb = pcb_fixture(tmp_path)
prefs = pcb.parent/'Layout/JobPrefsDB.jpf'
prefs.parent.mkdir()
prefs.write_bytes(b'real database data')
record = diagnostics.collect_preflight_diagnostics(pcb, tmp_path/'evidence')
entry = next(item for item in record['paths'] if item['path'] == str(prefs))
assert entry['readable'] is True
assert entry['size_bytes'] == len(b'real database data')
prefs.rename(prefs.with_suffix('.moved')) # would fail on Windows if handle leaked
def test_unreadable_jobprefs_does_not_prevent_verify(tmp_path, monkeypatch):
pcb = pcb_fixture(tmp_path)
prefs = pcb.parent/'Layout/JobPrefsDB.jpf'
prefs.parent.mkdir()
prefs.touch()
original = Path.open
def deny(path, *args, **kwargs):
if path == prefs:
raise PermissionError('simulated network share permission')
return original(path, *args, **kwargs)
monkeypatch.setattr(Path, 'open', deny)
record = diagnostics.collect_preflight_diagnostics(pcb, tmp_path/'evidence')
assert record['non_blocking'] is True
assert 'simulated network share permission' in str(record)
def test_writability_failure_is_diagnostic_only(tmp_path, monkeypatch):
pcb = pcb_fixture(tmp_path)
def deny(**kwargs):
raise PermissionError('no create permission')
monkeypatch.setattr(diagnostics.tempfile, 'NamedTemporaryFile', deny)
record = diagnostics.collect_preflight_diagnostics(pcb, tmp_path/'evidence')
assert record['directory_writable'] is False
assert record['non_blocking'] is True
assert 'no create permission' in str(record)
assert pcb.read_bytes() == b'PCB'
def test_native_log_tail_is_bounded_and_preserves_multiline_detail(tmp_path):
pcb = pcb_fixture(tmp_path)
source = pcb.parent/'LogFiles/ForwardAnnotation.txt'
source.parent.mkdir()
raw = b'x' * 10000 + b'\nERROR: Symbol $1I1\n pin mapping explanation\r\n'
source.write_bytes(raw)
record = diagnostics.collect_native_failure_logs(pcb, tmp_path/'evidence', max_bytes=1024)
item = next(item for item in record['files'] if item['source'] == str(source))
target = Path(item['evidence'])
assert item['truncated'] is True
assert item['original_size_bytes'] == len(raw)
assert target.read_bytes() == raw[-1024:]
assert source.read_bytes() == raw
source.rename(source.with_suffix('.moved'))
assert (tmp_path/'evidence/diagnostics/native-logs.json').is_file()
def test_native_logs_include_known_root_and_logfiles_paths_without_recursing(tmp_path, monkeypatch):
pcb = pcb_fixture(tmp_path)
sources = [pcb.parent/'LogFiles/PCBLogFile.txt', pcb.parent/'ReusableBlock.txt',
pcb.parent.parent/'ReusableBlock.txt']
for source in sources:
source.parent.mkdir(exist_ok=True)
source.write_text('native message', encoding='utf-8')
def unexpected(*args, **kwargs):
pytest.fail('diagnostics must not recursively enumerate a network CBB')
monkeypatch.setattr(Path, 'rglob', unexpected)
monkeypatch.setattr(Path, 'glob', unexpected)
record = diagnostics.collect_native_failure_logs(pcb, tmp_path/'evidence')
copied = [item for item in record['files'] if item.get('evidence')]
assert {item['source'] for item in copied} == {str(source) for source in sources}
assert len({item['evidence'] for item in copied}) == 3
def test_log_access_error_is_recorded_not_raised(tmp_path, monkeypatch):
pcb = pcb_fixture(tmp_path)
source = pcb.parent/'LogFiles/PCBLogFile.txt'
source.parent.mkdir()
source.touch()
original = Path.open
def deny(path, *args, **kwargs):
if path == source:
raise PermissionError('native log is locked')
return original(path, *args, **kwargs)
monkeypatch.setattr(Path, 'open', deny)
record = diagnostics.collect_native_failure_logs(pcb, tmp_path/'evidence')
assert 'native log is locked' in str(record)
assert record['non_blocking'] is True
def test_local_evidence_write_error_does_not_mask_original_failure(tmp_path, monkeypatch):
pcb = pcb_fixture(tmp_path)
original = Path.mkdir
def deny(path, *args, **kwargs):
if 'evidence' in path.parts:
raise PermissionError('evidence unavailable')
return original(path, *args, **kwargs)
monkeypatch.setattr(Path, 'mkdir', deny)
record = diagnostics.collect_native_failure_logs(pcb, tmp_path/'evidence')
assert 'evidence unavailable' in str(record)
assert record['non_blocking'] is True
def test_failure_log_helper_has_hard_timeout_and_never_launches_mentor(tmp_path, monkeypatch):
import subprocess
pcb = pcb_fixture(tmp_path)
root = tmp_path/'evidence'
root.mkdir()
job_path = root/'request.json'
job_path.write_text(json.dumps({'root': str(root), 'pcb': str(pcb)}), encoding='utf-8')
calls = []
def timed_out(command, **kwargs):
calls.append((command, kwargs))
raise subprocess.TimeoutExpired(command, kwargs['timeout'])
monkeypatch.setattr(diagnostics.subprocess, 'run', timed_out)
result = diagnostics.capture_failure_logs_with_timeout(job_path, timeout_seconds=2)
assert result['status'] == 'TIMEOUT'
assert len(calls) == 1
assert '--collect-failure-logs' in calls[0][0]
assert '--verify-worker' not in calls[0][0]
assert calls[0][1]['timeout'] == 2
assert (root/'diagnostics/native-log-capture.json').is_file()
+44
View File
@@ -0,0 +1,44 @@
import json
import pytest
def test_parse_export_probe_requires_all_known_exports():
from cbb_refresh_verify.verify_probe import parse_export_probe
payload = {
"ok": True,
"probe": "exports",
"dll_path": r"D:\Mentor\LMCDLL70.dll",
"architecture": "x86",
"exports": {
"IsVerifiedReuseBlock": {"found": True, "address": "0x100544e0"},
"GetStatusRBInContextOfCL": {"found": True, "address": "0x1006ddc0"},
"VerifyReuseBlock": {"found": True, "address": "0x10057840"},
"UnVerifyReuseBlock": {"found": True, "address": "0x10061b40"},
"GetReusableCircuitVerificationStatus": {"found": True, "address": "0x20019c30"},
},
"write_call": {"enabled": False, "reason": "CFilename ABI not reconstructed"},
}
result = parse_export_probe(json.dumps(payload))
assert result.architecture == "x86"
assert result.export("VerifyReuseBlock").found is True
assert result.write_enabled is False
def test_parse_export_probe_rejects_write_enabled_payload():
from cbb_refresh_verify.verify_probe import ProbeResponseError, parse_export_probe
payload = {
"ok": True,
"probe": "exports",
"dll_path": "LMCDLL70.dll",
"architecture": "x86",
"exports": {},
"write_call": {"enabled": True, "reason": "unsafe"},
}
with pytest.raises(ProbeResponseError, match="写接口探测桥不能启用写调用"):
parse_export_probe(json.dumps(payload))
File diff suppressed because it is too large. Load diff
+107
View File
@@ -0,0 +1,107 @@
from pathlib import Path
from types import SimpleNamespace
import subprocess
import pytest
from cbb_refresh_verify import mentor_adapter as adapter
def exercise_worker(tmp_path, monkeypatch, *, integration_error=None):
work = tmp_path/'ReusableBlocksLP/CBB/Work'
pcb = work/'PCB/CBB.pcb'
pcb.parent.mkdir(parents=True)
pcb.touch()
project = work/'CBB.prj'
project.touch()
evidence = tmp_path/'evidence'
evidence.mkdir()
events = []
monkeypatch.setattr(adapter, 'backup_timeout_seconds', lambda _: .1)
monkeypatch.setattr(adapter, 'best_effort_backup', lambda *a, **kw: {'status':'SKIPPED'})
monkeypatch.setattr(adapter, 'prepare_icdb_address', lambda *a, **kw: {'status':'ABSENT'})
monkeypatch.setattr(adapter, 'ensure_pcb_central_library', lambda *a, **kw: False)
monkeypatch.setattr(adapter, 'pcb_processes', lambda: ())
monkeypatch.setattr(adapter, 'build_pcb_launch_command', lambda *a: ('ExpeditionPCB.exe',))
monkeypatch.setattr(adapter, 'launch_pcb_process', lambda *a: SimpleNamespace(pid=1))
monkeypatch.setattr(adapter, '_process_details', lambda _: ())
monkeypatch.setattr(adapter, 'select_reusable_circuit_worker', lambda *a, **kw: (2,'pcb','command',1))
monkeypatch.setattr(adapter, 'cleanup_verify_processes', lambda *a, **kw: None)
monkeypatch.setattr('cbb_refresh_verify.pcb_bridge.wait_for_target_document',
lambda *a, **kw: (None, None, object()))
def integration(*args, **kwargs):
if integration_error:
raise RuntimeError(integration_error)
monkeypatch.setattr('cbb_refresh_verify.integration.refresh_integration', integration)
# The x86 helper finished; the pre-existing Save/Close gates remain exercised.
def save_helper(command, **kw):
kw['stdout'].write('LICENSE_OK\nSAVE_OK\nIS_SAVED\nPOST_SAVE_SYNCHRONIZED\nCLOSE_OK\nQUIT_OK\n')
kw['stdout'].flush()
return SimpleNamespace(pid=3, poll=lambda: 0, returncode=0)
monkeypatch.setattr(adapter.subprocess, 'Popen', save_helper)
job = {'root':str(evidence),'project':str(project),'pcb':str(pcb),
'lmc_file':str(tmp_path/'lib.lmc'),'block_name':'CBB','timeout':600}
return job, events, lambda: adapter.execute_job(job, lambda **e: events.append(e))
def test_missing_cert_cannot_block_saved_and_closed_worker(tmp_path, monkeypatch):
job, events, execute = exercise_worker(tmp_path, monkeypatch)
result = execute()
work = Path(job['project']).parent
assert result['status'] == 'PASS' # execution only; parent must still ask bridge
assert not (work.parent/'Cert').exists()
assert any(e['stage'] == 'saved_and_closed' for e in events)
assert any(e['stage'] == 'cert_diagnostics' and e['non_blocking'] for e in events)
def test_cert_diagnostic_io_failure_is_nonblocking(tmp_path, monkeypatch):
from cbb_refresh_verify.mentor_adapter import collect_cert_evidence
original = Path.stat
def deny(path, *args, **kwargs):
if 'Cert' in path.parts:
raise PermissionError('simulated SMB error on Cert')
return original(path,*args,**kwargs)
monkeypatch.setattr(Path,'stat',deny)
result = collect_cert_evidence(tmp_path, tmp_path/'Cert/CBB.prj', tmp_path/'Cert/PCB/CBB.pcb', probe_files=True)
assert result['non_blocking'] is True
assert 'simulated SMB error' in str(result)
def test_worker_records_diagnostics_once_before_pcb_launch(tmp_path, monkeypatch):
import json
job, events, execute = exercise_worker(tmp_path, monkeypatch)
assert execute()['status'] == 'PASS'
stages = [event['stage'] for event in events]
assert stages.count('preflight_diagnostics') == 1
assert stages.index('preflight_diagnostics') < stages.index('pcb_launch')
record = json.loads((Path(job['root'])/'diagnostics/preflight.json').read_text('utf-8'))
assert record['non_blocking'] is True
assert record['directory_writable'] is True
assert not (Path(job['root'])/'diagnostics/native-logs.json').exists()
def test_worker_failure_preserves_native_multiline_logs_and_original_error(tmp_path, monkeypatch):
job, events, execute = exercise_worker(tmp_path, monkeypatch,
integration_error='Project Integration error: symbol $1I1')
source = Path(job['pcb']).parent/'LogFiles/ForwardAnnotation.txt'
source.parent.mkdir()
source.write_bytes(b'ERROR: symbol $1I1\n pin mapping detail\n')
with pytest.raises(RuntimeError, match='Project Integration error: symbol'):
execute()
target = Path(job['root'])/'diagnostics/native-logs/pcb-logfiles-ForwardAnnotation.txt'
assert target.read_bytes() == source.read_bytes()
assert any(event['stage'] == 'native_failure_logs' for event in events)
def test_default_cert_diagnostics_never_stat_network_files(tmp_path, monkeypatch):
original = Path.stat
def unexpected(path, *args, **kwargs):
if 'Cert' in path.parts:
pytest.fail('Cert stat must not delay successful Save/Close on SMB')
return original(path,*args,**kwargs)
monkeypatch.setattr(Path,'stat',unexpected)
result=adapter.collect_cert_evidence(tmp_path,tmp_path/'Cert/CBB.prj',tmp_path/'Cert/PCB/CBB.pcb')
assert result['non_blocking'] is True
assert result['probed'] is False
assert result['project_exists'] is None