test_current_targets.py 8.5 KB

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