test_current_targets.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. from pathlib import Path
  2. from unittest import mock
  3. import argparse,hashlib,json,re,shutil
  4. import pytest
  5. from tools import fw_cli,fw_targets,target_registry
  6. from tools.generate_target import generate_named_target
  7. from tools.source_identity import source_identity
  8. ROOT=Path(__file__).resolve().parents[2]
  9. @pytest.fixture
  10. def exported_files(tmp_path):
  11. for folder in ('contracts','config','projects','products'):
  12. shutil.copytree(ROOT/folder,tmp_path/folder)
  13. for entry in fw_targets.load_registry(ROOT)['targets'].values():
  14. closure=json.loads((ROOT/entry['source_closure']).read_text(encoding='utf-8'))
  15. for relative in closure['sources']:
  16. if relative.startswith('generated/'):continue
  17. destination=tmp_path/relative;destination.parent.mkdir(parents=True,exist_ok=True)
  18. shutil.copy2(ROOT/relative,destination)
  19. return tmp_path
  20. def snapshot(root):
  21. return {p.relative_to(root).as_posix():(hashlib.sha256(p.read_bytes()).hexdigest(),p.stat().st_mtime_ns)
  22. for p in root.rglob('*') if p.is_file()}
  23. @pytest.mark.parametrize('name,canonical,product',[
  24. ('6400','6400','6400-front-rear'),('6400-front-rear','6400','6400-front-rear'),
  25. ('prod2u-6400-front-back','6400','6400-front-rear'),('mrdimm','mrdimm','mrdimm-chamber'),
  26. ('mrdimm-chamber','mrdimm','mrdimm-chamber'),(' MRDIMM ','mrdimm','mrdimm-chamber')])
  27. def test_both_registry_adapters_resolve_current_product(name,canonical,product):
  28. one=fw_targets.resolve_target(name,ROOT);two=target_registry.resolve_target(name)
  29. assert one['alias']==two.alias==canonical
  30. assert one['project_id']==two.project_id==product
  31. for key in ('requirements','source_closure','params_header','host_contract','adc','sdc','td_project','verification_targets'):
  32. assert (ROOT/one[key]).is_file(),key
  33. assert 'p4_normal' not in one['top_module']
  34. def test_registry_has_only_two_current_products():
  35. assert set(fw_targets.list_aliases(ROOT))==set(target_registry.list_target_aliases())=={'6400','mrdimm'}
  36. for resolver in (fw_targets.resolve_target,target_registry.resolve_target):
  37. with pytest.raises(ValueError):resolver('prod2u-door-temp')
  38. assert 'Full acceptance pending' in fw_targets.target_status_line('mrdimm')
  39. def test_ambiguous_alias_is_rejected_by_both_adapters(tmp_path):
  40. data=fw_targets.load_registry(ROOT)
  41. data['targets']['mrdimm']['aliases'].append('6400-front-rear')
  42. path=tmp_path/'registry.json';path.write_text(json.dumps(data))
  43. with pytest.raises(ValueError):fw_targets.resolve_target('6400',ROOT,path)
  44. with pytest.raises(ValueError):target_registry.resolve_target('6400',registry_path=path)
  45. def test_fresh_generation_isolated_deterministic_and_readonly_check(exported_files):
  46. root=exported_files
  47. assert not (root/'generated').exists()
  48. for name in ('6400','mrdimm'):
  49. generate_named_target(name,repo=root)
  50. original=snapshot(root)
  51. for name in ('mrdimm-chamber','6400-front-rear'):
  52. generate_named_target(name,repo=root)
  53. generate_named_target(name,repo=root,check=True)
  54. assert snapshot(root)==original
  55. assert re.search(r'FB_SNAPSHOT_LENGTH\s+199\b',(root/'generated/6400/prod2u_6400_v1_params.vh').read_text())
  56. assert json.loads((root/'generated/mrdimm/snapshot-layout.json').read_text())['length']==352
  57. assert not (root/'src/generated').exists()
  58. path=root/'generated/mrdimm/snapshot-layout.json';path.write_bytes(path.read_bytes()+b' ')
  59. drifted=snapshot(root)
  60. with pytest.raises(ValueError,match='generated drift'):generate_named_target('mrdimm',repo=root,check=True)
  61. assert snapshot(root)==drifted
  62. generate_named_target('mrdimm',repo=root)
  63. assert {k:v[0] for k,v in snapshot(root).items()}=={k:v[0] for k,v in original.items()}
  64. def test_closure_uses_selected_repository(exported_files):
  65. root=exported_files
  66. for name in ('6400','mrdimm'):
  67. generate_named_target(name,repo=root)
  68. target=target_registry.resolve_target(name,repo=root)
  69. sources=target_registry.load_source_closure(target)
  70. assert all((root/p).is_file() for p in sources)
  71. assert not any('/legacy/' in p or 'door_percent' in p for p in sources)
  72. missing=root/'src/motor/motor_engine.v';missing.unlink()
  73. with pytest.raises(ValueError,match='missing files'):
  74. target_registry.load_source_closure(target_registry.resolve_target('mrdimm',repo=root))
  75. @pytest.mark.parametrize('name,profile',[('6400','6400-front-rear'),('mrdimm-chamber','mrdimm-chamber')])
  76. def test_build_dispatches_current_td_profile(name,profile,tmp_path):
  77. with mock.patch.object(fw_cli.sys,'platform','linux'),mock.patch.object(fw_cli,'_generate_one') as gen,\
  78. mock.patch.object(fw_cli.subprocess,'call',return_value=7) as run:
  79. assert fw_cli.main(['build',name,'--run-root',str(tmp_path/'run')])==7
  80. assert run.call_args.args[0][-4:]==['--profile',profile,'--run-root',str(tmp_path/'run')]
  81. gen.assert_called_once_with('6400' if profile.startswith('6400') else 'mrdimm',check=True)
  82. def test_package_is_a_thin_canonical_forwarder():
  83. with mock.patch('tools.package_prod2u.main',return_value=3) as package:
  84. assert fw_cli.main(['package','verify','example.zip'])==3
  85. package.assert_called_once_with(['verify','example.zip'])
  86. def test_exported_identity_is_not_fake_git_clean(tmp_path):
  87. with pytest.raises(ValueError,match='neither'):source_identity(tmp_path)
  88. data={'schema':'prod2u-workspace-snapshot-v1','snapshot_id':'fixture','repos':[
  89. {'name':'cpld-temperature-control','commit':'a'*40,'tree':'b'*40}]}
  90. path=tmp_path/'WORKSPACE-SNAPSHOT.json';path.write_text(json.dumps(data))
  91. identity=source_identity(tmp_path)
  92. assert identity['source_kind']=='exported' and identity['clean'] is None and identity['branch'] is None
  93. assert identity['commit']=='a'*40 and identity['tree']=='b'*40
  94. data['repos'].append(data['repos'][0]);path.write_text(json.dumps(data))
  95. with pytest.raises(ValueError,match='ambiguous'):source_identity(tmp_path)
  96. @pytest.mark.parametrize('counts',[None,(0,0),(1,1)])
  97. def test_success_exit_without_executed_unit_tests_fails(tmp_path,counts):
  98. def start(command,**kwargs):
  99. if counts is not None:
  100. xml=Path(next(x.split('=',1)[1] for x in command if x.startswith('--junitxml=')))
  101. xml.write_text(f'<testsuites><testsuite tests="{counts[0]}" skipped="{counts[1]}" failures="0" errors="0"/></testsuites>')
  102. process=mock.Mock();process.wait.return_value=0;return process
  103. with mock.patch.object(fw_cli.sys,'platform','linux'),mock.patch.object(fw_cli,'_generate_one'),\
  104. mock.patch.object(fw_cli.subprocess,'Popen',side_effect=start),\
  105. mock.patch.object(fw_cli,'source_identity',return_value={'source_kind':'fixture'}),\
  106. mock.patch.object(fw_cli,'cmd_diagnose',return_value=0):
  107. assert fw_cli.main(['test','mrdimm','--run-root',str(tmp_path/'run')])==1
  108. report=json.loads((tmp_path/'run/RESULT.json').read_text())
  109. assert report['status']=='FAIL'