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

556 lines
29 KiB
Python

"""Native export and asset identity boundaries; never launch native tools."""
from pathlib import Path
import pytest
def ascii_report(date=b'Tue Nov 03 11:19:39 2026', directory=b'C:\\copy\\database'):
return (b'iCDB Ascii Report Generation Date: '+date+b'\r\n\r\n\r\n\tReport Criteria:\r\n'
b'\t iCDB directory: '+directory+b'\r\n\t DATE: '+date+b'\r\n\r\n'
b'\t REPORT FORMAT: FREEFORM\r\n\t MODE: HIER AND FLAT BLOCKS\r\n'
b'\t CONNECTION LISTS: ON\r\n\t TEXT LISTS: ON\r\n\r\n'
b'Block Top \tRoot\r\n\tPort A\r\nConfig default\tview none\r\n\tPin A\r\n')
def test_ascii_only_normalizes_three_validated_header_values():
from cbb_refresh_verify.native_engineering_identity import normalize_ascii
first = ascii_report()
changed = ascii_report(b'Wed Nov 04 12:00:00 2026', b'D:\\other\\database')
assert normalize_ascii(first, 'Top') == normalize_ascii(changed, 'Top')
assert normalize_ascii(first, 'Top') != normalize_ascii(first.replace(b'Port A', b'Port B'), 'Top')
body = b'\tiCDB Ascii Report Generation Date: design property\r\n'
assert normalize_ascii(first+body, 'Top') != normalize_ascii(first+body.replace(b'property', b'value'), 'Top')
@pytest.mark.parametrize('change', ['empty', 'wrong_root', 'missing_config', 'header_duplicate', 'wrong_mode'])
def test_ascii_rejects_missing_or_unrecognized_structure(change):
from cbb_refresh_verify.native_engineering_identity import normalize_ascii
data = ascii_report()
data = {'empty': b'', 'wrong_root': data.replace(b'Block Top ', b'Block Other '),
'missing_config': data.replace(b'Config default', b'Partial default'),
'header_duplicate': data.replace(b'\tReport Criteria:', b'\t DATE: extra'),
'wrong_mode': data.replace(b'HIER AND FLAT BLOCKS', b'FLAT ONLY')}[change]
with pytest.raises(ValueError): normalize_ascii(data, 'Top')
def test_inf_only_normalizes_unique_timestamp_column():
from cbb_refresh_verify.native_engineering_identity import normalize_inf, INF_HEADER
row = [b'identity', b'Design Capture', b'VB99.0', b'11/03/26 11:21:34']+[b'value']*12
first = INF_HEADER+b'\r\n'+b'\t'.join(row)+b'\r\n'
assert normalize_inf(first) == normalize_inf(first.replace(b'11:21:34', b'11:21:37'))
assert normalize_inf(first) != normalize_inf(first.replace(b'value', b'changed', 1))
with pytest.raises(ValueError): normalize_inf(first.replace(b'System_Date', b'Unknown'))
with pytest.raises(ValueError): normalize_inf(first+b'extra row\r\n')
@pytest.fixture
def project(tmp_path):
from test_management import project
source = project(tmp_path/'project', name='Source')
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.write_bytes(b'library')
for path in (source, source.parent/'PCB/pcb.prj'):
with path.open('a', encoding='utf-8') as stream:
stream.write(f'KEY CentralLibrary "{library}"\n')
return source, library
def test_assets_require_correct_library_references_and_unknown_bytes(project):
from cbb_refresh_verify.native_engineering_identity import asset_identity
source, library = project
before = asset_identity(source, library)
runtime = source.parent/'database/cdbsvr/events/events.dat'
runtime.parent.mkdir(parents=True); runtime.write_bytes(b'runtime')
(source.parent/'database/icdb.dat').write_bytes(b'native normalized database')
assert asset_identity(source, library) == before
unknown = source.parent/'unknown-engineering.bin'; unknown.write_bytes(b'engineering')
assert asset_identity(source, library) != before
unknown.unlink()
(source.parent/'PCB/Layout/LayoutDB.lyt').write_bytes(b'changed physical design')
assert asset_identity(source, library) != before
text = (source.parent/'PCB/pcb.prj').read_text()
(source.parent/'PCB/pcb.prj').write_text(text.replace(str(library), 'missing.lmc'))
with pytest.raises(ValueError, match='CentralLibrary'):
asset_identity(source, library)
def test_linked_legacy_identity_preserves_template_bytes_and_aligns_only_active_project(project, tmp_path):
from cbb_refresh_verify.native_engineering_identity import asset_identity, project_library
from cbb_refresh_verify.backup_recovery import _align_library
source, library = project
template = source.parent/'PCB/template.prj'
(source.parent/'PCB/pcb.prj').rename(template)
original = template.read_bytes()
before = asset_identity(source, library)
assert 'PCB/template.prj' in before['assets']
other = tmp_path/'other.lmc'; other.write_bytes(b'other library')
_align_library(source, next((source.parent/'PCB').glob('*.pcb')), other)
assert template.read_bytes() == original
assert project_library(source) == other
assert asset_identity(source, other) == before
template.write_bytes(original+b'unknown engineering change')
assert asset_identity(source, other) != before
@pytest.mark.parametrize('relative', ['database/cdbsvr/persistent.dat',
'database/cdbsvr/new-engineering/config.bin', 'database/cdbsvr/events/custom.dat',
'database/cdbsvr/plog/unknown-engineering.bin'])
def test_unknown_cdbsvr_assets_remain_part_of_identity(project, relative):
from cbb_refresh_verify.native_engineering_identity import asset_identity
source, library = project
baseline = asset_identity(source, library)
unknown = source.parent/relative; unknown.parent.mkdir(parents=True, exist_ok=True)
unknown.write_bytes(b'first engineering content')
added = asset_identity(source, library)
assert added != baseline
unknown.write_bytes(b'changed engineering content')
assert asset_identity(source, library) != added
unknown.unlink()
assert asset_identity(source, library) == baseline
def test_observed_guid_and_events_runtime_does_not_change_identity(project):
from cbb_refresh_verify.native_engineering_identity import asset_identity
source, library = project
baseline = asset_identity(source, library)
for relative in ['database/cdbsvr/plog/2026.11.03.guid.48432.txt',
'database/cdbsvr/events/events.dat', 'database/cdbsvr/events/events.idx']:
path = source.parent/relative; path.parent.mkdir(parents=True, exist_ok=True); path.write_bytes(b'runtime')
assert asset_identity(source, library) == baseline
@pytest.mark.parametrize('failure', ['empty', 'missing_completion', 'error', 'exit'])
def test_export_evidence_requires_successful_complete_native_output(tmp_path, failure):
from cbb_refresh_verify.native_engineering_identity import validate_export_output
report = tmp_path/'design.rpt'; report.write_bytes(b'report')
log = tmp_path/'native.log'
log.write_text(f'Report generation complete, report file is {report}\n')
code = 0
if failure == 'empty': report.write_bytes(b'')
if failure == 'missing_completion': log.write_text('partial report\n')
if failure == 'error':
with log.open('a') as stream: stream.write('ERROR: database corrupt\n')
if failure == 'exit': code = 2
with pytest.raises(ValueError): validate_export_output('ascii', code, report, log)
def test_capture_only_exports_fresh_copy_and_leaves_source_unchanged(project, tmp_path, monkeypatch):
import cbb_refresh_verify.native_engineering_identity as identity
from cbb_refresh_verify.library_lock import LibraryLock
from cbb_refresh_verify.scoped_manifest import build_manifest
source, library = project
original = build_manifest(source.parent)
monkeypatch.setattr(identity, 'check_exporters', lambda _: None)
monkeypatch.setattr(identity, '_process_snapshot', lambda: [])
def exports(clone, root, *_):
assert clone.parent == root/'project' and clone != source
(clone.parent/'database/icdb.dat').write_bytes(b'export changed disposable copy')
(root/'design.rpt').write_bytes(ascii_report())
(root/'design.edf').write_bytes(edif_report())
(root/'export-launch.json').write_text('{"started": false}')
return {'success': True, 'safe_to_continue': True, 'detail': ''}
monkeypatch.setattr(identity, '_run_exports', exports)
monkeypatch.setattr(identity, 'csv_identity', lambda _: {'work/identity': 'csv proof'})
with LibraryLock(library):
result = identity.capture_identity(source, tmp_path/'analysis', expected_library=library,
owner_library=library, mentor_home=tmp_path)
assert result.identity['policy'] == identity.POLICY and result.safe_to_continue
assert build_manifest(source.parent) == original
def test_capture_unreleased_exporter_retains_caller_lease(project, tmp_path, monkeypatch):
import cbb_refresh_verify.native_engineering_identity as identity
from cbb_refresh_verify.library_lock import LibraryLock, LibraryBusy, blocker_path, _owners, _guard
source, library = project
monkeypatch.setattr(identity, 'check_exporters', lambda _: None)
monkeypatch.setattr(identity, '_run_exports', lambda *a: {
'success': False, 'safe_to_continue': False, 'detail': 'TIMEOUT: native exporter retained'})
lease = LibraryLock(library)
try:
with lease:
result = identity.capture_identity(source, tmp_path/'analysis', expected_library=library,
owner_library=library, mentor_home=tmp_path)
assert result.identity is None and not result.safe_to_continue
with pytest.raises(LibraryBusy):
with LibraryLock(library): pass
finally:
with _guard:
owner = _owners.pop(lease.key, None)
if owner: owner['handle'].Close()
blocker_path(library).unlink(missing_ok=True)
def test_export_timeout_retains_process_without_kill(project, tmp_path, monkeypatch):
import cbb_refresh_verify.native_engineering_identity as identity
source, _ = project
root = tmp_path/'exports'; root.mkdir()
seen = []
class Running:
pid = 987654
def __init__(self, command, **kwargs): seen.append(command)
def poll(self): return None
def kill(self): pytest.fail('native owner cannot be killed')
def terminate(self): pytest.fail('native owner cannot be terminated')
monkeypatch.setattr(identity, '_retained_exports', [])
monkeypatch.setattr(identity.subprocess, 'Popen', Running)
monkeypatch.setattr(identity, '_process_snapshot', lambda: [])
monkeypatch.setattr(identity, '_database_released', lambda _: True)
result = identity._run_exports(source, root, tmp_path, 0)
assert not result['safe_to_continue'] and 'TIMEOUT' in result['detail']
assert len(identity._retained_exports) == 1
assert seen[0][-5:] == ['-f', '-h', '-c', '-t', '-nostrip']
assert (root/'ascii-process.json').is_file()
def test_export_does_not_adopt_unrelated_existing_native_owner(project, tmp_path, monkeypatch):
import cbb_refresh_verify.native_engineering_identity as identity
source, _ = project
root = tmp_path/'exports'; root.mkdir()
unrelated = {'pid': 888888, 'parent': 0, 'name': 'iCDBNetServer.exe',
'executable': 'native', 'command': 'iCDBNetServer.exe C:\\other\\database'}
monkeypatch.setattr(identity, '_process_snapshot', lambda: [unrelated])
monkeypatch.setattr(identity, '_database_released', lambda _: True)
monkeypatch.setattr(identity, 'validate_export_output', lambda *_: None)
started = []
class Finished:
pid = 987654
returncode = 0
def __init__(self, command, **kwargs): started.append(command)
def poll(self): return 0
monkeypatch.setattr(identity.subprocess, 'Popen', Finished)
result = identity._run_exports(source, root, tmp_path, 1)
assert result['success'] and result['safe_to_continue']
assert len(started) == 3
def test_export_does_not_adopt_existing_child_of_reused_parent_pid(project, tmp_path, monkeypatch):
import cbb_refresh_verify.native_engineering_identity as identity
import win32api
source, _ = project
root = tmp_path/'exports'; root.mkdir()
# This process predates the exporter; its historical parent PID has been reused.
unrelated = dict(pid=888888, parent=987654, name='python.exe', executable='python.exe',
command='python other-tool.py', created='20261111120000.000000+480')
monkeypatch.setattr(identity, '_process_snapshot', lambda: [unrelated])
monkeypatch.setattr(identity, '_database_released', lambda _: True)
monkeypatch.setattr(identity, 'validate_export_output', lambda *_: None)
monkeypatch.setattr(win32api, 'OpenProcess', lambda *a: pytest.fail('adopted another tool'))
class Finished:
pid = 987654
returncode = 0
def __init__(self, *a, **k): pass
def poll(self): return 0
monkeypatch.setattr(identity.subprocess, 'Popen', Finished)
result = identity._run_exports(source, root, tmp_path, 1)
assert result['success'] and result['safe_to_continue']
def test_export_lineage_rejects_reused_owner_and_its_new_children():
from cbb_refresh_verify.native_engineering_identity import _export_descendants, _process_birth
old = '20261112120000.000000+480'
new = '20261112120100.000000+480'
tracked = {10: _process_birth(old), 20: _process_birth(old)}
rows = [dict(pid=20, parent=10, created=new), dict(pid=30, parent=20, created=new)]
assert _export_descendants(rows, tracked, set()) == []
assert 30 not in tracked
# An orphaned real child can outlive its exact original parent.
rows = [dict(pid=40, parent=10, created=new)]
assert _export_descendants(rows, tracked, set()) == rows
def test_export_lineage_rejects_child_older_than_native_handle_birth():
from cbb_refresh_verify.native_engineering_identity import _export_descendants, _process_birth
tracked = {10: _process_birth('20261112120000.000000+480')}
rows = [dict(pid=20, parent=10, created='20261111120000.000000+480')]
assert _export_descendants(rows, tracked, set()) == []
@pytest.mark.parametrize('remains_alive,database_busy', [(False, False), (True, False), (False, True)])
def test_export_reobserves_access_denied_child_before_deciding_release(
project, tmp_path, monkeypatch, remains_alive, database_busy):
import json
import pywintypes
import win32api
from cbb_refresh_verify import native_engineering_identity as identity
source, _ = project
root = tmp_path/'exports'; root.mkdir()
launched, seen = [], {}
class Finished:
returncode = 0
def __init__(self, *args, **kwargs):
self.pid = 980000+len(launched)*2
launched.append(self)
def poll(self): return 0
def kill(self): pytest.fail('native owner must not be killed')
def snapshot():
if not launched: return []
pid = launched[-1].pid
seen[pid] = seen.get(pid, 0)+1
if seen[pid] == 1 or remains_alive:
return [{'pid': pid+1, 'parent': pid, 'name': 'conhost.exe',
'command': '', 'executable': '', 'created': 'creation-identity'}]
return []
def denied(*args): raise pywintypes.error(5, 'OpenProcess', 'Access is denied')
ticks = iter(i/100 for i in range(1000))
monkeypatch.setattr(identity.time, 'monotonic', lambda: next(ticks))
monkeypatch.setattr(identity.time, 'sleep', lambda _: None)
monkeypatch.setattr(identity.subprocess, 'Popen', Finished)
monkeypatch.setattr(identity, '_process_snapshot', snapshot)
monkeypatch.setattr(identity, '_database_released', lambda _: not launched or not database_busy)
monkeypatch.setattr(identity, 'validate_export_output', lambda *_: None)
monkeypatch.setattr(identity, '_retained_exports', [])
monkeypatch.setattr(win32api, 'OpenProcess', denied)
result = identity._run_exports(source, root, tmp_path, .045)
expected = not remains_alive and not database_busy
assert result['success'] is expected
assert result['safe_to_continue'] is expected
record = json.loads((root/'ascii-process.json').read_text('utf-8'))
assert record['process_identities'][0]['pid'] == launched[0].pid+1
assert record['process_observation_errors'][str(launched[0].pid+1)]['winerror'] == 5
if expected:
assert len(launched) == 3 and not identity._retained_exports
else:
assert 'TIMEOUT' in result['detail'] and identity._retained_exports
def test_export_spawn_failure_does_not_manufacture_native_ownership(project, tmp_path, monkeypatch):
import cbb_refresh_verify.native_engineering_identity as identity
source, _ = project
root = tmp_path/'exports'; root.mkdir()
monkeypatch.setattr(identity, '_process_snapshot', lambda: [])
monkeypatch.setattr(identity, '_database_released', lambda _: True)
def fail(*a, **k): raise FileNotFoundError('missing exporter')
monkeypatch.setattr(identity.subprocess, 'Popen', fail)
result = identity._run_exports(source, root, tmp_path, 1)
assert not result['success'] and result['safe_to_continue']
assert 'missing exporter' in result['detail']
def test_unconfirmed_export_constructor_failure_retains_ownership(project, tmp_path, monkeypatch):
import cbb_refresh_verify.native_engineering_identity as identity
source, _ = project
root = tmp_path/'exports'; root.mkdir()
monkeypatch.setattr(identity, '_process_snapshot', lambda: [])
monkeypatch.setattr(identity, '_database_released', lambda _: True)
def fail(*a, **k): raise RuntimeError('uncertain partially-created process')
monkeypatch.setattr(identity.subprocess, 'Popen', fail)
result = identity._run_exports(source, root, tmp_path, 1)
assert not result['success'] and not result['safe_to_continue']
@pytest.mark.parametrize('summary', ['native-outcome.json', 'identity.json'])
def test_export_summary_write_failure_preserves_confirmed_release(project, tmp_path, monkeypatch, summary):
import cbb_refresh_verify.native_engineering_identity as identity
from cbb_refresh_verify.library_lock import LibraryLock, blocker_path
import win32event
from uuid import uuid4
create_mutex = win32event.CreateMutex
monkeypatch.setattr(win32event, 'CreateMutex', lambda security, owned, name:
create_mutex(security, owned, name+'-test-'+uuid4().hex))
source, library = project
monkeypatch.setattr(identity, 'check_exporters', lambda _: None)
monkeypatch.setattr(identity, '_process_snapshot', lambda: [])
def exports(clone, root, *_):
(root/'export-launch.json').write_text('{"started": false}')
return {'success': False, 'safe_to_continue': True, 'detail': 'export rejected before start'}
monkeypatch.setattr(identity, '_run_exports', exports)
original_write = identity._write_json
def write(path, record):
if path.name == summary: raise OSError('summary unavailable')
return original_write(path, record)
monkeypatch.setattr(identity, '_write_json', write)
with LibraryLock(library):
result = identity.capture_identity(source, tmp_path/'analysis', expected_library=library,
owner_library=library, mentor_home=tmp_path)
assert result.identity is None and result.safe_to_continue
assert 'summary unavailable' in result.detail
assert not blocker_path(library).exists()
def test_export_snapshot_uses_bounded_read_only_helper(monkeypatch):
from cbb_refresh_verify import native_engineering_identity as identity, owner_probe
rows = [{'pid': 42, 'parent': 10, 'name': 'unknown-child.exe'}]
calls = []
def query(**kwargs):
calls.append(kwargs)
return rows
monkeypatch.setattr(owner_probe, 'query_process_snapshot', query)
assert identity._process_snapshot() == rows
assert calls == [{'timeout_seconds': 10}]
@pytest.mark.parametrize('after_launch', [False, True])
def test_export_snapshot_timeout_preserves_launch_extent(project, tmp_path, monkeypatch, after_launch):
from cbb_refresh_verify import native_engineering_identity as identity
source, _ = project
root = tmp_path/'exports'; root.mkdir()
calls = []
def snapshot():
calls.append('snapshot')
if after_launch and len(calls) == 1: return []
raise RuntimeError('OWNER_QUERY_TIMEOUT: WMI timed out')
monkeypatch.setattr(identity, '_process_snapshot', snapshot)
monkeypatch.setattr(identity, '_database_released', lambda _: True)
monkeypatch.setattr(identity, '_retained_exports', [])
launched = []
class Running:
pid = 987654
def __init__(self, *a, **k): launched.append(self)
def poll(self): return None
monkeypatch.setattr(identity.subprocess, 'Popen', Running)
result = identity._run_exports(source, root, tmp_path, 1)
assert not result['success']
assert result['safe_to_continue'] is (not after_launch)
assert result['native_started'] is after_launch
assert 'OWNER_QUERY_TIMEOUT' in result['detail']
assert bool(launched) is after_launch
assert bool(identity._retained_exports) is after_launch
def test_prelaunch_snapshot_timeout_releases_only_own_unstarted_guard(project, tmp_path, monkeypatch):
from cbb_refresh_verify import native_engineering_identity as identity
from cbb_refresh_verify.library_lock import LibraryLock, blocker_path
import win32event
from uuid import uuid4
source, library = project
create_mutex = win32event.CreateMutex
monkeypatch.setattr(win32event, 'CreateMutex', lambda security, owned, name:
create_mutex(security, owned, name+'-test-'+uuid4().hex))
monkeypatch.setattr(identity, 'check_exporters', lambda _: None)
calls = []
def snapshot():
calls.append('query')
raise RuntimeError('OWNER_QUERY_TIMEOUT: process tree unavailable')
monkeypatch.setattr(identity, '_process_snapshot', snapshot)
with LibraryLock(library):
result = identity.capture_identity(source, tmp_path/'analysis', expected_library=library,
owner_library=library, mentor_home=tmp_path)
assert result.identity is None and result.safe_to_continue
assert 'OWNER_QUERY_TIMEOUT' in result.detail
assert calls == ['query']
assert not blocker_path(library).exists()
@pytest.mark.parametrize('failure', ['source', 'lease', 'scope', 'exporters', 'directory', 'mutex'])
def test_capture_prevalidation_failure_explicitly_reports_no_native_session(project, tmp_path, monkeypatch, failure):
from cbb_refresh_verify import native_engineering_identity as identity, library_lock
import win32event
source, library = project
root = tmp_path/'analysis'
def reject(*args, **kwargs): raise OSError(f'prevalidation {failure} unavailable')
monkeypatch.setattr(library_lock, 'owned_snapshot', lambda _: b'owned lease')
monkeypatch.setattr(identity, 'check_exporters', lambda _: None)
monkeypatch.setattr(identity, '_run_exports', lambda *a, **k: pytest.fail('native export must not start'))
if failure == 'source': monkeypatch.setattr(identity, 'source_project', reject)
if failure == 'lease': monkeypatch.setattr(library_lock, 'owned_snapshot', lambda _: None)
if failure == 'scope': root = source.parent/'analysis'
if failure == 'exporters': monkeypatch.setattr(identity, 'check_exporters', reject)
if failure == 'directory':
mkdir = Path.mkdir
def create(path, *args, **kwargs):
if path == root: return reject()
return mkdir(path, *args, **kwargs)
monkeypatch.setattr(Path, 'mkdir', create)
if failure == 'mutex': monkeypatch.setattr(win32event, 'CreateMutex', reject)
result = identity.capture_identity(source, root, expected_library=library,
owner_library=library, mentor_home=tmp_path)
assert result.identity is None and result.safe_to_continue
assert result.detail
@pytest.mark.parametrize('failure', ['initial_launch_record', 'final_process_record'])
def test_export_record_io_preserves_known_launch_extent(project, tmp_path, monkeypatch, failure):
from cbb_refresh_verify import native_engineering_identity as identity, library_lock
import win32event
from uuid import uuid4
source, library = project
create_mutex = win32event.CreateMutex
monkeypatch.setattr(win32event, 'CreateMutex', lambda security, owned, name:
create_mutex(security, owned, name+'-test-'+uuid4().hex))
monkeypatch.setattr(identity, 'check_exporters', lambda _: None)
monkeypatch.setattr(identity, '_process_snapshot', lambda: [])
monkeypatch.setattr(identity, '_database_released', lambda _: True)
monkeypatch.setattr(library_lock, '_supervisor_alive', lambda _: False)
launched = []
class Finished:
pid = 987654
returncode = 0
def __init__(self, *args, **kwargs): launched.append(self)
def poll(self): return 0
monkeypatch.setattr(identity.subprocess, 'Popen', Finished)
def content_failure(*args): raise ValueError('native export content rejected')
monkeypatch.setattr(identity, 'validate_export_output', content_failure)
write = identity._write_json
process_writes = []
def fail(path, record):
if path.name == 'export-launch.json' and failure == 'initial_launch_record':
raise OSError('launch metadata unavailable')
if path.name == 'ascii-process.json':
process_writes.append(record.copy())
if failure == 'final_process_record' and len(process_writes) == 2:
raise OSError('final process metadata unavailable')
return write(path, record)
monkeypatch.setattr(identity, '_write_json', fail)
with library_lock.LibraryLock(library):
result = identity.capture_identity(source, tmp_path/'analysis', expected_library=library,
owner_library=library, mentor_home=tmp_path)
assert result.identity is None and result.safe_to_continue
assert 'metadata unavailable' in result.detail
assert bool(launched) is (failure == 'final_process_record')
assert not library_lock.blocker_path(library).exists()
with library_lock.LibraryLock(library): pass
def test_successful_export_keeps_release_when_final_diagnostic_write_fails(project, tmp_path, monkeypatch):
from cbb_refresh_verify import native_engineering_identity as identity
source, _ = project
root = tmp_path/'exports'; root.mkdir()
monkeypatch.setattr(identity, '_process_snapshot', lambda: [])
monkeypatch.setattr(identity, '_database_released', lambda _: True)
monkeypatch.setattr(identity, 'validate_export_output', lambda *_: None)
class Finished:
pid = 987654
returncode = 0
def __init__(self, *args, **kwargs): pass
def poll(self): return 0
monkeypatch.setattr(identity.subprocess, 'Popen', Finished)
write = identity._write_json
counts = {}
def fail(path, record):
if path.name.endswith('-process.json'):
counts[path] = counts.get(path, 0)+1
if counts[path] == 2: raise OSError('final metadata unavailable')
return write(path, record)
monkeypatch.setattr(identity, '_write_json', fail)
result = identity._run_exports(source, root, tmp_path, 1)
assert result['success'] and result['safe_to_continue']
assert 'final metadata unavailable' in result['detail']
def edif_report(timestamp=b'2026 11 3 11 40 56'):
return (b'(edif DxD (edifVersion 2 0 0) (status (written (timestamp '+timestamp+b')'
b' (program "DxDesigner Edif Exporter"))) (library Board1 (cell Top'
b' (view SCHEMATIC_VIEW (viewType SCHEMATIC) (page sheet1 (figure LINE (pt 1 2)))'
b' (property timestamp (string "2026 11 3 11 40 56")))))'
b' (design Board1 (cellRef Top (libraryRef Board1))))')
def test_edif_only_normalizes_root_written_timestamp_preserving_geometry_and_properties():
from cbb_refresh_verify.native_engineering_identity import normalize_edif
first = edif_report()
assert normalize_edif(first, 'Top') == normalize_edif(edif_report(b'2026 11 3 11 40 59'), 'Top')
assert normalize_edif(first, 'Top') != normalize_edif(first.replace(b'(pt 1 2)', b'(pt 1 3)'), 'Top')
assert normalize_edif(first, 'Top') != normalize_edif(first.replace(b'"2026 11 3 11 40 56"', b'"changed"'), 'Top')
for bad in [first[:-1], first.replace(b'(edifVersion 2 0 0)', b'(edifVersion 1 0 0)'),
first.replace(b'(cellRef Top', b'(cellRef Other'), first.replace(b'(pt 1 2)', b'')]:
with pytest.raises(ValueError): normalize_edif(bad, 'Top')
def test_edif_binds_native_escaped_digit_initial_root_without_changing_design_bytes():
from cbb_refresh_verify.native_engineering_identity import normalize_edif
report = edif_report().replace(b'cell Top', b'cell &1GPHY_8212').replace(b'cellRef Top', b'cellRef &1GPHY_8212')
normalized = normalize_edif(report, '1GPHY_8212')
assert b'(cell &1GPHY_8212' in normalized and b'(cellRef &1GPHY_8212' in normalized
for wrong in ('1GPHY_8211', '&1GPHY_8212'):
with pytest.raises(ValueError): normalize_edif(report, wrong)
with pytest.raises(ValueError):
normalize_edif(report.replace(b'&1GPHY_8212', b'1GPHY_8212'), '1GPHY_8212')