test_current_targets.py 8.0 KB

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