test_remote_scripts.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. #!/usr/bin/env python3
  2. """Remote collector and package tests for the converged CPLD project."""
  3. from __future__ import annotations
  4. import json
  5. import shutil
  6. import subprocess
  7. import tempfile
  8. import unittest
  9. from pathlib import Path
  10. ROOT = Path(__file__).resolve().parents[2]
  11. class RemoteScriptTests(unittest.TestCase):
  12. def test_remote_tools_only_expose_latest_real_fan_ptc_collector(self) -> None:
  13. scripts = sorted(path.name for path in (ROOT / "tools" / "remote").glob("*.ps1"))
  14. self.assertEqual(scripts, ["collect-j6-host-sensor-real-fan-ptc.ps1"])
  15. self.assertFalse((ROOT / "tools" / "serial_debug_capture.py").exists())
  16. self.assertFalse((ROOT / "tools" / "windows_serial_validation.py").exists())
  17. def test_collect_j6_host_sensor_real_fan_ptc_is_static_allowlisted_host_writer_and_debug_reader(self) -> None:
  18. script = (ROOT / "tools" / "remote" / "collect-j6-host-sensor-real-fan-ptc.ps1").read_text(
  19. encoding="utf-8"
  20. )
  21. for marker in [
  22. "System.IO.Ports.SerialPort",
  23. "[ValidatePattern('^COM[0-9]+$')]",
  24. "HostPort",
  25. "DebugPort",
  26. 'if ($HostPort -eq $DebugPort)',
  27. 'if ($HostPort -ne "COM8")',
  28. 'if ($DebugPort -ne "COM7")',
  29. "BaudRate = 115200",
  30. "DebugBaud = 921600",
  31. "DtrEnable = $false",
  32. "RtsEnable = $false",
  33. "host-port-raw.bin",
  34. "host-port-escaped.txt",
  35. "debug-uart-raw.bin",
  36. "debug-uart-escaped.txt",
  37. "bmc-raw-replay.bin",
  38. "host-sensor-report.json",
  39. "debug-frame-stream.json",
  40. "host-command-transcript.json",
  41. "j6-host-sensor-real-fan-ptc-capture-manifest.json",
  42. "real-bmc-j6-host-sensor-real-fan-ptc-debug921-v1-receipt-draft.json",
  43. "real-bmc-j6-host-sensor-real-fan-ptc-debug921-v1",
  44. "J6CMD",
  45. "J6RAW",
  46. "J6EVT",
  47. "J6PWM",
  48. "J6MOD",
  49. "J6STAT",
  50. "J6MAP",
  51. "J6TEMP",
  52. "SENS",
  53. "DIMM",
  54. "PTCCH",
  55. "FANCH",
  56. "SET PTC 01 10",
  57. "SET PTC 24 20",
  58. "SET FAN 01 40",
  59. "SET FAN 04 30",
  60. "SET PID ENABLE",
  61. "GET STATUS",
  62. "GET MAP",
  63. "GET SENSOR",
  64. "SET PID DISABLE",
  65. "DISABLE",
  66. "host_port_writes_to_serial",
  67. "debug_port_writes_to_serial",
  68. "driver_install_attempted = $false",
  69. "enumerates_com_ports = $false",
  70. "opens_unknown_com_ports = $false",
  71. "AssumeManualSramProgrammed",
  72. "PROGRAM_SRAM",
  73. ]:
  74. self.assertIn(marker, script)
  75. self.assertIn("$hostSerial.Write", script)
  76. self.assertNotIn("$debugSerial.Write", script)
  77. for forbidden in [
  78. "SET PTC 00",
  79. "SET FAN 00",
  80. "SET FAN 05",
  81. "SET FAN 06",
  82. "GetPortNames",
  83. "Win32_SerialPort",
  84. "Get-CimInstance",
  85. "Get-WmiObject",
  86. "pip install",
  87. "pyserial",
  88. "python",
  89. "pnputil",
  90. "devcon",
  91. "install-driver",
  92. "add-windowsdriver",
  93. "driverquery",
  94. "PROGRAM_FLASH",
  95. "ERASE_FLASH",
  96. "PROGRAM_SPIBIN",
  97. "DIRECT_FLASH_WRITE",
  98. "blocked_edit_required",
  99. ]:
  100. self.assertNotIn(forbidden.lower(), script.lower())
  101. def test_collect_j6_host_sensor_real_fan_ptc_preserves_empty_raw_replay_byte_array(self) -> None:
  102. powershell = shutil.which("powershell")
  103. if powershell is None:
  104. self.skipTest("PowerShell is not available")
  105. script_path = ROOT / "tools" / "remote" / "collect-j6-host-sensor-real-fan-ptc.ps1"
  106. script = script_path.read_text(encoding="utf-8")
  107. helper_start = script.index("function Convert-HexToBytes")
  108. helper_end = script.index("$out =")
  109. helpers = script[helper_start:helper_end]
  110. with tempfile.TemporaryDirectory() as tmp:
  111. probe_path = Path(tmp) / "probe.ps1"
  112. out_path = Path(tmp) / "empty-replay.bin"
  113. probe_path.write_text(
  114. helpers
  115. + f"""
  116. $events = New-Object System.Collections.Generic.List[object]
  117. $rawReplayArray = New-BmcRawReplay $events
  118. if ($null -eq $rawReplayArray) {{
  119. throw "raw replay array was null"
  120. }}
  121. if ($rawReplayArray.GetType().FullName -ne "System.Byte[]") {{
  122. throw "raw replay array type was $($rawReplayArray.GetType().FullName)"
  123. }}
  124. if ($rawReplayArray.Length -ne 0) {{
  125. throw "raw replay array length was $($rawReplayArray.Length)"
  126. }}
  127. [System.IO.File]::WriteAllBytes("{out_path}", $rawReplayArray)
  128. """,
  129. encoding="utf-8",
  130. )
  131. result = subprocess.run(
  132. [powershell, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(probe_path)],
  133. cwd=ROOT,
  134. text=True,
  135. capture_output=True,
  136. check=False,
  137. )
  138. self.assertEqual(result.returncode, 0, result.stderr + result.stdout)
  139. self.assertTrue(out_path.exists())
  140. self.assertEqual(out_path.stat().st_size, 0)
  141. def test_collect_j6_host_sensor_real_fan_ptc_parses_two_digit_hex_fields_as_int64(self) -> None:
  142. powershell = shutil.which("powershell")
  143. if powershell is None:
  144. self.skipTest("PowerShell is not available")
  145. script_path = ROOT / "tools" / "remote" / "collect-j6-host-sensor-real-fan-ptc.ps1"
  146. script = script_path.read_text(encoding="utf-8")
  147. helper_start = script.index("function Convert-TokenValue")
  148. helper_end = script.index("function Convert-BytesToEscapedText")
  149. helpers = script[helper_start:helper_end]
  150. with tempfile.TemporaryDirectory() as tmp:
  151. probe_path = Path(tmp) / "probe.ps1"
  152. probe_path.write_text(
  153. helpers
  154. + """
  155. $events = New-Object System.Collections.Generic.List[object]
  156. $events.Add((Convert-FrameLine "J6PWM seq=0000000A src=hm pid=disabled timeout=1 ptc01=00 ptc24=00 fan01=1E fan04=1E" @("J6PWM"))) | Out-Null
  157. $events.Add((Convert-FrameLine "J6TEMP seq=00000003 status=valid valid=1E missing=00 fault=0 host_report_drop=00000000" @("J6TEMP"))) | Out-Null
  158. $events.Add((Convert-FrameLine "J6RAW seq=00000001 off=00000000 len=30 sum=00FF data=FFFFFFFF" @("J6RAW"))) | Out-Null
  159. foreach ($probe in @(
  160. @($events[0].fields.fan01, "fan01"),
  161. @($events[0].fields.timeout, "timeout"),
  162. @($events[1].fields.valid, "valid"),
  163. @($events[1].fields.missing, "missing"),
  164. @($events[2].fields.len, "len"),
  165. @($events[2].fields.sum, "sum")
  166. )) {
  167. if ($probe[0].GetType().FullName -ne "System.Int64") {
  168. throw "$($probe[1]) parsed as $($probe[0].GetType().FullName)"
  169. }
  170. }
  171. if ([int64]$events[0].fields.fan01 -ne 30) { throw "fan01 was $($events[0].fields.fan01)" }
  172. if ([int64]$events[0].fields.timeout -ne 1) { throw "timeout was $($events[0].fields.timeout)" }
  173. if ([int64]$events[1].fields.valid -ne 30) { throw "valid was $($events[1].fields.valid)" }
  174. if ([int64]$events[1].fields.missing -ne 0) { throw "missing was $($events[1].fields.missing)" }
  175. if ([int64]$events[2].fields.len -ne 48) { throw "len was $($events[2].fields.len)" }
  176. if ([int64]$events[2].fields.sum -ne 255) { throw "sum was $($events[2].fields.sum)" }
  177. """,
  178. encoding="utf-8",
  179. )
  180. result = subprocess.run(
  181. [powershell, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(probe_path)],
  182. cwd=ROOT,
  183. text=True,
  184. capture_output=True,
  185. check=False,
  186. )
  187. self.assertEqual(result.returncode, 0, result.stderr + result.stdout)
  188. def test_j6_host_sensor_real_fan_ptc_package_script_creates_two_executable_profile_packages(self) -> None:
  189. script = (ROOT / "tools" / "package_j6_host_sensor_real_fan_ptc_debug921.ps1").read_text(
  190. encoding="utf-8"
  191. )
  192. for marker in [
  193. "START-HERE.zh-CN.md",
  194. "tools\\remote\\collect-j6-host-sensor-real-fan-ptc.ps1",
  195. "bitstreams",
  196. "td-receipts",
  197. "commands",
  198. "pin_inventory.fcb_fpga_mcu0611.json",
  199. "sha256-inventory.json",
  200. "Compress-Archive",
  201. ".zip.sha256.txt",
  202. "temp-uart-ptc-remap",
  203. "formal-uart",
  204. "j6-host-sensor-real-fan-ptc-temp-uart-ptc-remap-debug921-v1",
  205. "j6-host-sensor-real-fan-ptc-formal-uart-debug921-v1",
  206. "SET PTC 01 10",
  207. "SET PTC 24 20",
  208. "SET FAN 01 40",
  209. "SET FAN 04 30",
  210. "-AssumeManualSramProgrammed $true",
  211. "excluded_self_referential_file",
  212. ]:
  213. self.assertIn(marker, script)
  214. for marker in [
  215. "blocked_pin_conflict_with_locked_debug_uart",
  216. "debug115",
  217. "swapped",
  218. "-ManualSramAttestation",
  219. "$att.status",
  220. "blocked_edit_required",
  221. "collect-com8-host-com7-debug.ps1",
  222. r"-Bitstream .\bitstreams\uart_rs232_j6_host_sensor_real_fan_ptc_debug921_primary.bit",
  223. "SET PTC 00",
  224. "SET FAN 00",
  225. "SET FAN 05",
  226. "SET FAN 06",
  227. "pip install",
  228. "pyserial",
  229. "python",
  230. ]:
  231. self.assertNotIn(marker.lower(), script.lower())
  232. def test_j6_host_sensor_real_fan_ptc_package_output_contains_executable_profile_artifacts(self) -> None:
  233. powershell = shutil.which("powershell")
  234. if powershell is None:
  235. self.skipTest("PowerShell is not available")
  236. with tempfile.TemporaryDirectory() as tmp:
  237. bitstream = Path(tmp) / "fake.bit"
  238. td_receipt = Path(tmp) / "td-receipt.json"
  239. bitstream.write_bytes(b"fake-sram-bitstream")
  240. td_receipt.write_text(
  241. json.dumps(
  242. {
  243. "schema": "td-build-receipt-v1",
  244. "status": "pass",
  245. "programming_mode": "SRAM-only",
  246. "bitstream": {"sha256": "0" * 64},
  247. }
  248. ),
  249. encoding="utf-8",
  250. )
  251. for profile, package_name in [
  252. ("temp-uart-ptc-remap", "j6-host-sensor-real-fan-ptc-temp-uart-ptc-remap-debug921-v1-test"),
  253. ("formal-uart", "j6-host-sensor-real-fan-ptc-formal-uart-debug921-v1-test"),
  254. ]:
  255. with self.subTest(profile=profile):
  256. result = subprocess.run(
  257. [
  258. powershell,
  259. "-NoProfile",
  260. "-ExecutionPolicy",
  261. "Bypass",
  262. "-File",
  263. str(ROOT / "tools" / "package_j6_host_sensor_real_fan_ptc_debug921.ps1"),
  264. "-OutputDir",
  265. tmp,
  266. "-PackageName",
  267. package_name,
  268. "-Profile",
  269. profile,
  270. "-Bitstream",
  271. str(bitstream),
  272. "-TdReceipt",
  273. str(td_receipt),
  274. ],
  275. cwd=ROOT,
  276. text=True,
  277. capture_output=True,
  278. check=False,
  279. )
  280. self.assertEqual(result.returncode, 0, result.stderr + result.stdout)
  281. stage = Path(tmp) / package_name
  282. self.assertTrue((stage / "START-HERE.zh-CN.md").is_file())
  283. self.assertTrue((stage / "collector" / "collect-j6-host-sensor-real-fan-ptc.ps1").is_file())
  284. self.assertTrue((stage / "commands" / "collect-template.ps1").is_file())
  285. self.assertTrue((stage / "bitstreams" / bitstream.name).is_file())
  286. self.assertTrue((stage / "td-receipts" / td_receipt.name).is_file())
  287. self.assertTrue((stage / "config" / "pin_inventory.fcb_fpga_mcu0611.json").is_file())
  288. self.assertTrue((stage / "schemas" / "real_bmc_j6_host_sensor_real_fan_ptc_debug921_v1_receipt.schema.json").is_file())
  289. self.assertFalse((stage / "blocked").exists())
  290. self.assertTrue((Path(tmp) / f"{package_name}.zip").is_file())
  291. self.assertTrue((Path(tmp) / f"{package_name}.zip.sha256.txt").is_file())
  292. manifest = json.loads((stage / "manifest.json").read_text(encoding="utf-8-sig"))
  293. self.assertEqual(manifest["status"], "pass")
  294. self.assertEqual(manifest["pin_profile"], profile)
  295. self.assertEqual(manifest["programming_mode"], "PROGRAM_SRAM")
  296. self.assertIn("host_control_commands", manifest)
  297. self.assertIn("pin_map", manifest)
  298. self.assertNotIn("pin_conflicts", manifest)
  299. inventory = json.loads((stage / "sha256-inventory.json").read_text(encoding="utf-8-sig"))
  300. self.assertEqual(inventory["self_hash_policy"], "excluded_self_referential_file")
  301. inventory_paths = {item["path"] for item in inventory["inventory"]}
  302. self.assertIn("manifest.json", inventory_paths)
  303. self.assertIn("START-HERE.zh-CN.md", inventory_paths)
  304. self.assertIn("collector/collect-j6-host-sensor-real-fan-ptc.ps1", inventory_paths)
  305. self.assertIn("commands/collect-template.ps1", inventory_paths)
  306. self.assertNotIn("sha256-inventory.json", inventory_paths)
  307. def test_j6_host_sensor_real_fan_ptc_runbook_is_chinese_copy_paste_ready_with_english_paths(self) -> None:
  308. runbook = (ROOT / "docs" / "j6-host-sensor-real-fan-ptc-debug921-runbook.zh-CN.md").read_text(
  309. encoding="utf-8"
  310. )
  311. for marker in [
  312. "J6 Host Sensor Real FAN PTC Debug921",
  313. "START-HERE.zh-CN.md",
  314. "COM8",
  315. "COM7",
  316. "blocked_pin_conflict_with_locked_debug_uart",
  317. "当前不要刷机",
  318. "锁定调试串口",
  319. "HEAT3",
  320. "HEAT4",
  321. "HEAT17",
  322. "HEAT18",
  323. "HEAT21",
  324. "HEAT22",
  325. "SET PTC 01 10",
  326. "SET PTC 24 20",
  327. "SET FAN 01 40",
  328. "SET FAN 04 30",
  329. "SET PID ENABLE",
  330. "GET SENSOR",
  331. "SET PID DISABLE",
  332. "DISABLE",
  333. "PTCCH",
  334. "FANCH",
  335. "1-based",
  336. "SENS",
  337. "DIMM",
  338. "J6TEMP",
  339. "J6RAW",
  340. "host-port-escaped.txt",
  341. "debug-uart-escaped.txt",
  342. "host-sensor-report.json",
  343. "bmc-raw-replay.bin",
  344. "不需要安装 Python",
  345. "不枚举 COM",
  346. "不写 DebugPort",
  347. ]:
  348. self.assertIn(marker, runbook)
  349. for forbidden in [
  350. "debug115",
  351. "Manual SRAM attestation status must be pass",
  352. "blocked_edit_required",
  353. "Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass -Force",
  354. r".\commands\collect-com8-host-com7-debug.ps1",
  355. r".\collector\collect-j6-host-sensor-real-fan-ptc.ps1 -HostPort COM8 -DebugPort COM7",
  356. "-AssumeManualSramProgrammed $true",
  357. r"bitstreams\uart_rs232_j6_host_sensor_real_fan_ptc_debug921_primary.bit",
  358. "collector/collect-j6-host-sensor-real-fan-ptc.ps1",
  359. "SET PTC 00",
  360. "SET FAN 00",
  361. "SET FAN 05",
  362. "SET FAN 06",
  363. r".\collector\采集",
  364. ]:
  365. self.assertNotIn(forbidden, runbook)
  366. def test_j6_host_sensor_real_fan_ptc_schema_requires_sensor_pwm_pid_pinmap_and_debug_artifacts(self) -> None:
  367. schema = json.loads(
  368. (ROOT / "schemas" / "real_bmc_j6_host_sensor_real_fan_ptc_debug921_v1_receipt.schema.json").read_text(
  369. encoding="utf-8"
  370. )
  371. )
  372. layers = schema["properties"]["layers"]["properties"]
  373. self.assertEqual(schema["properties"]["diagnostic_scope"], {"const": "host_sensor_real_fan_ptc_debug921"})
  374. for layer in [
  375. "host_command_sequence",
  376. "host_control_transcript",
  377. "host_sensor_reports",
  378. "debug_frame_capture",
  379. "bmc_raw_sampling",
  380. "pid_boundary",
  381. "timeout_evidence",
  382. "pin_map",
  383. "real_fan_ptc_hardware_status",
  384. "artifact_hashes",
  385. ]:
  386. self.assertIn(layer, layers)
  387. commands = layers["host_command_sequence"]["properties"]["commands"]["prefixItems"]
  388. self.assertEqual(commands[0], {"const": "SET PTC 01 10"})
  389. self.assertEqual(commands[1], {"const": "SET PTC 24 20"})
  390. self.assertEqual(commands[2], {"const": "SET FAN 01 40"})
  391. self.assertEqual(commands[3], {"const": "SET FAN 04 30"})
  392. self.assertIn("host_sensor_report", layers["host_sensor_reports"]["required"])
  393. self.assertIn("debug_frame_stream", layers["debug_frame_capture"]["required"])
  394. self.assertIn("raw_replay", layers["debug_frame_capture"]["required"])
  395. self.assertEqual(layers["pin_map"]["properties"]["ptc_count"], {"const": 24})
  396. self.assertEqual(layers["pin_map"]["properties"]["fan_count"], {"const": 4})
  397. if __name__ == "__main__":
  398. unittest.main()