from pathlib import Path from unittest import mock import argparse,hashlib,json,re,shutil import pytest from tools import fw_cli,fw_targets,target_registry from tools.generate_target import generate_named_target from tools.source_identity import source_identity ROOT=Path(__file__).resolve().parents[2] @pytest.fixture def exported_files(tmp_path): for folder in ('contracts','config','projects','products'): shutil.copytree(ROOT/folder,tmp_path/folder) for entry in fw_targets.load_registry(ROOT)['targets'].values(): closure=json.loads((ROOT/entry['source_closure']).read_text(encoding='utf-8')) for relative in closure['sources']: if relative.startswith('generated/'):continue destination=tmp_path/relative;destination.parent.mkdir(parents=True,exist_ok=True) shutil.copy2(ROOT/relative,destination) return tmp_path def snapshot(root): return {p.relative_to(root).as_posix():(hashlib.sha256(p.read_bytes()).hexdigest(),p.stat().st_mtime_ns) for p in root.rglob('*') if p.is_file()} @pytest.mark.parametrize('name,canonical,product',[ ('6400','6400','6400-front-rear'),('6400-front-rear','6400','6400-front-rear'), ('prod2u-6400-front-back','6400','6400-front-rear'),('mrdimm','mrdimm','mrdimm-chamber'), ('mrdimm-chamber','mrdimm','mrdimm-chamber'),(' MRDIMM ','mrdimm','mrdimm-chamber')]) def test_both_registry_adapters_resolve_current_product(name,canonical,product): one=fw_targets.resolve_target(name,ROOT);two=target_registry.resolve_target(name) assert one['alias']==two.alias==canonical assert one['project_id']==two.project_id==product for key in ('requirements','source_closure','params_header','host_contract','adc','sdc','td_project','verification_targets'): assert (ROOT/one[key]).is_file(),key assert 'p4_normal' not in one['top_module'] def test_registry_has_only_two_current_products(): assert set(fw_targets.list_aliases(ROOT))==set(target_registry.list_target_aliases())=={'6400','mrdimm'} for resolver in (fw_targets.resolve_target,target_registry.resolve_target): with pytest.raises(ValueError):resolver('prod2u-door-temp') assert 'Full acceptance pending' in fw_targets.target_status_line('mrdimm') def test_ambiguous_alias_is_rejected_by_both_adapters(tmp_path): data=fw_targets.load_registry(ROOT) data['targets']['mrdimm']['aliases'].append('6400-front-rear') path=tmp_path/'registry.json';path.write_text(json.dumps(data)) with pytest.raises(ValueError):fw_targets.resolve_target('6400',ROOT,path) with pytest.raises(ValueError):target_registry.resolve_target('6400',registry_path=path) def test_fresh_generation_isolated_deterministic_and_readonly_check(exported_files): root=exported_files assert not (root/'generated').exists() for name in ('6400','mrdimm'): generate_named_target(name,repo=root) original=snapshot(root) for name in ('mrdimm-chamber','6400-front-rear'): generate_named_target(name,repo=root) generate_named_target(name,repo=root,check=True) assert snapshot(root)==original assert re.search(r'FB_SNAPSHOT_LENGTH\s+199\b',(root/'generated/6400/prod2u_6400_v1_params.vh').read_text()) assert json.loads((root/'generated/mrdimm/snapshot-layout.json').read_text())['length']==352 assert not (root/'src/generated').exists() path=root/'generated/mrdimm/snapshot-layout.json';path.write_bytes(path.read_bytes()+b' ') drifted=snapshot(root) with pytest.raises(ValueError,match='generated drift'):generate_named_target('mrdimm',repo=root,check=True) assert snapshot(root)==drifted generate_named_target('mrdimm',repo=root) assert {k:v[0] for k,v in snapshot(root).items()}=={k:v[0] for k,v in original.items()} def test_closure_uses_selected_repository(exported_files): root=exported_files for name in ('6400','mrdimm'): generate_named_target(name,repo=root) target=target_registry.resolve_target(name,repo=root) sources=target_registry.load_source_closure(target) assert all((root/p).is_file() for p in sources) assert not any('/legacy/' in p or 'door_percent' in p for p in sources) missing=root/'src/motor/motor_engine.v';missing.unlink() with pytest.raises(ValueError,match='missing files'): target_registry.load_source_closure(target_registry.resolve_target('mrdimm',repo=root)) @pytest.mark.parametrize('name,profile',[('6400','6400-front-rear'),('mrdimm-chamber','mrdimm-chamber')]) def test_build_dispatches_current_td_profile(name,profile,tmp_path): with mock.patch.object(fw_cli.sys,'platform','linux'),mock.patch.object(fw_cli,'_generate_one') as gen,\ mock.patch.object(fw_cli.subprocess,'call',return_value=7) as run: assert fw_cli.main(['build',name,'--run-root',str(tmp_path/'run')])==7 assert run.call_args.args[0][-4:]==['--profile',profile,'--run-root',str(tmp_path/'run')] gen.assert_called_once_with('6400' if profile.startswith('6400') else 'mrdimm',check=True) def test_package_is_a_thin_canonical_forwarder(): with mock.patch('tools.package_prod2u.main',return_value=3) as package: assert fw_cli.main(['package','verify','example.zip'])==3 package.assert_called_once_with(['verify','example.zip']) def test_exported_identity_is_not_fake_git_clean(tmp_path): with pytest.raises(ValueError,match='neither'):source_identity(tmp_path) data={'schema':'prod2u-workspace-snapshot-v1','snapshot_id':'fixture','repos':[ {'name':'cpld-temperature-control','commit':'a'*40,'tree':'b'*40}]} path=tmp_path/'WORKSPACE-SNAPSHOT.json';path.write_text(json.dumps(data)) identity=source_identity(tmp_path) assert identity['source_kind']=='exported' and identity['clean'] is None and identity['branch'] is None assert identity['commit']=='a'*40 and identity['tree']=='b'*40 data['repos'].append(data['repos'][0]);path.write_text(json.dumps(data)) with pytest.raises(ValueError,match='ambiguous'):source_identity(tmp_path) @pytest.mark.parametrize('counts',[None,(0,0),(1,1)]) def test_success_exit_without_executed_unit_tests_fails(tmp_path,counts): def start(command,**kwargs): if counts is not None: xml=Path(next(x.split('=',1)[1] for x in command if x.startswith('--junitxml='))) xml.write_text(f'') process=mock.Mock();process.wait.return_value=0;return process with mock.patch.object(fw_cli.sys,'platform','linux'),mock.patch.object(fw_cli,'_generate_one'),\ mock.patch.object(fw_cli.subprocess,'Popen',side_effect=start),\ mock.patch.object(fw_cli,'source_identity',return_value={'source_kind':'fixture'}),\ mock.patch.object(fw_cli,'cmd_diagnose',return_value=0): assert fw_cli.main(['test','mrdimm','--run-root',str(tmp_path/'run')])==1 report=json.loads((tmp_path/'run/RESULT.json').read_text()) assert report['status']=='FAIL'