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

231 lines
12 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 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')