test_prod2u_programmer_runtime.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. #!/usr/bin/env python3
  2. """TDD coverage for the live-capable Prod2U PROGRAM_SRAM runner boundary."""
  3. from __future__ import annotations
  4. import hashlib
  5. import importlib.util
  6. import json
  7. import copy
  8. import subprocess
  9. import sys
  10. import tempfile
  11. import time
  12. import unittest
  13. import uuid
  14. from pathlib import Path
  15. import jsonschema
  16. ROOT = Path(__file__).resolve().parents[2]
  17. MODULE_PATH = ROOT / "tools" / "prod2u_programmer.py"
  18. FIXTURE = ROOT / "tests" / "fixtures" / "prod2u_programmer" / "gui_success_excerpt.log"
  19. CLI_FIXTURE = ROOT / "tests" / "fixtures" / "prod2u_programmer" / "cli_success_excerpt.log"
  20. BITSTREAM_BYTES = b"prod2u runtime fixture bitstream\n"
  21. def load_module():
  22. spec = importlib.util.spec_from_file_location("prod2u_programmer_runtime", MODULE_PATH)
  23. if spec is None or spec.loader is None:
  24. raise AssertionError("unable to load Prod2U programmer")
  25. module = importlib.util.module_from_spec(spec)
  26. spec.loader.exec_module(module)
  27. return module
  28. class FakeMutex:
  29. def __init__(self, acquired: bool = True) -> None:
  30. self.acquired = acquired
  31. self.entered = False
  32. def __enter__(self):
  33. self.entered = True
  34. if not self.acquired:
  35. raise TimeoutError("mutex busy")
  36. return self
  37. def __exit__(self, exc_type, exc, tb):
  38. return False
  39. class Prod2UProgrammerRuntimeTests(unittest.TestCase):
  40. def test_cleanup_targets_stale_bitwriter_cli_but_not_td_cli_or_hwserver(self) -> None:
  41. source = MODULE_PATH.read_text(encoding="utf-8")
  42. self.assertIn("'bw_commands_prompt'", source)
  43. allowed_line = next(line for line in source.splitlines() if "$allowed = @(" in line)
  44. self.assertNotIn("td_commands_prompt", allowed_line)
  45. self.assertNotIn("hwserver", allowed_line)
  46. def test_cleanup_td_root_match_requires_a_path_component_boundary(self) -> None:
  47. source = MODULE_PATH.read_text(encoding="utf-8")
  48. self.assertIn("$rootWithSeparator = $root + [System.IO.Path]::DirectorySeparatorChar", source)
  49. self.assertIn(".StartsWith($rootWithSeparator, [System.StringComparison]::OrdinalIgnoreCase)", source)
  50. self.assertNotIn(".StartsWith($root, [System.StringComparison]::OrdinalIgnoreCase)", source)
  51. def setUp(self) -> None:
  52. self.module = load_module()
  53. self.build_id = uuid.uuid4().hex[:8].upper()
  54. self.source_root = tempfile.TemporaryDirectory()
  55. self.output_root = tempfile.TemporaryDirectory()
  56. self.td_root = tempfile.TemporaryDirectory()
  57. self.source_bit = Path(self.source_root.name) / "source.bit"
  58. self.source_bit.write_bytes(BITSTREAM_BYTES)
  59. self.expected_sha256 = hashlib.sha256(BITSTREAM_BYTES).hexdigest()
  60. self.output_dir = Path(self.output_root.name)
  61. self.td_root_path = Path(self.td_root.name)
  62. self.td_bin = self.td_root_path / "bin"
  63. self.log_dir = self.td_bin / "log"
  64. self.log_dir.mkdir(parents=True)
  65. self.bw_exe = self.td_bin / "bw_commands_prompt.exe"
  66. self.bw_exe.write_bytes(b"fixture executable placeholder")
  67. def tearDown(self) -> None:
  68. staged = Path(self.module.staged_bitstream_path(self.build_id))
  69. if staged.is_file():
  70. staged.unlink()
  71. if staged.parent.is_dir():
  72. staged.parent.rmdir()
  73. self.source_root.cleanup()
  74. self.output_root.cleanup()
  75. self.td_root.cleanup()
  76. def success_log(self) -> str:
  77. staged_forward = self.module.staged_bitstream_path(self.build_id).replace("\\", "/")
  78. return FIXTURE.read_text(encoding="utf-8").replace(
  79. "C:/P2U/A1B2C3D4/fw.bit",
  80. staged_forward,
  81. )
  82. def cli_success_log(self) -> str:
  83. staged_forward = self.module.staged_bitstream_path(self.build_id).replace("\\", "/")
  84. return CLI_FIXTURE.read_text(encoding="utf-8").replace(
  85. "C:/P2U/A1B2C3D4/fw.bit",
  86. staged_forward,
  87. )
  88. def cleanup_result(self) -> dict:
  89. return {
  90. "td_root": str(self.td_root_path),
  91. "graceful_close_requested": ["bw.exe:101"],
  92. "forced_terminated": [],
  93. "wait_seconds": 5.0,
  94. "remaining": [],
  95. "status": "pass",
  96. }
  97. def test_runner_stages_hashes_executes_once_and_parses_only_new_log_bytes(self) -> None:
  98. old_log = self.log_dir / "bw_existing.log"
  99. old_log.write_text("PRG-8002 ERROR stale historical failure\n", encoding="utf-8")
  100. calls: list[dict] = []
  101. def fake_runner(command, *, cwd, timeout, capture_output, text, check):
  102. calls.append({"command": command, "cwd": cwd, "timeout": timeout})
  103. old_log.write_text(
  104. old_log.read_text(encoding="utf-8") + self.success_log(),
  105. encoding="utf-8",
  106. )
  107. return subprocess.CompletedProcess(command, 0, stdout="bw > ", stderr="")
  108. receipt = self.module.execute_program_sram(
  109. source_bitstream=self.source_bit,
  110. expected_bitstream_sha256=self.expected_sha256,
  111. build_id=self.build_id,
  112. output_dir=self.output_dir,
  113. td_root=self.td_root_path,
  114. run_id="runtime-pass",
  115. process_runner=fake_runner,
  116. cleanup_runner=lambda _td_root: self.cleanup_result(),
  117. mutex_factory=lambda: FakeMutex(),
  118. )
  119. staged = Path(self.module.staged_bitstream_path(self.build_id))
  120. self.assertEqual(staged.read_bytes(), BITSTREAM_BYTES)
  121. self.assertEqual(receipt["status"], "pass", receipt["parser"]["failures"])
  122. self.assertEqual(receipt["execution"]["attempt_count"], 1)
  123. self.assertEqual(receipt["execution"]["retry_count"], 0)
  124. self.assertEqual(receipt["execution"]["timeout_seconds"], 60)
  125. self.assertTrue(receipt["execution"]["command_execution_attempted"])
  126. self.assertTrue(receipt["mutex"]["acquired"])
  127. self.assertEqual(receipt["process_cleanup"]["wait_seconds"], 5.0)
  128. self.assertEqual(len(calls), 1)
  129. self.assertEqual(calls[0]["timeout"], 60)
  130. self.assertEqual(Path(calls[0]["command"][0]), self.bw_exe)
  131. self.assertEqual(Path(calls[0]["command"][1]), self.output_dir / "program-sram.tcl")
  132. self.assertEqual(
  133. calls[0]["command"][1],
  134. (self.output_dir / "program-sram.tcl").absolute().as_posix(),
  135. )
  136. self.assertNotIn("\\", calls[0]["command"][1])
  137. self.assertNotIn("stale historical failure", (self.output_dir / "bitwriter-log-delta.log").read_text(encoding="utf-8"))
  138. self.assertEqual(receipt["artifacts"]["tcl"]["sha256"], hashlib.sha256((self.output_dir / "program-sram.tcl").read_bytes()).hexdigest())
  139. self.assertEqual(receipt["artifacts"]["log_delta"]["sha256"], hashlib.sha256((self.output_dir / "bitwriter-log-delta.log").read_bytes()).hexdigest())
  140. schema = json.loads((ROOT / "schemas" / "prod2u_program_sram_receipt.schema.json").read_text(encoding="utf-8"))
  141. jsonschema.validate(receipt, schema)
  142. contradictions = (
  143. ("execution", "timed_out", True),
  144. ("execution", "command_execution_attempted", False),
  145. ("parser", "status", "fail"),
  146. ("staging", "matches_expected_path", False),
  147. ("safety", "flash_attempted", True),
  148. )
  149. for section, key, value in contradictions:
  150. with self.subTest(schema_contradiction=f"{section}.{key}"):
  151. invalid = copy.deepcopy(receipt)
  152. invalid[section][key] = value
  153. with self.assertRaises(jsonschema.ValidationError):
  154. jsonschema.validate(invalid, schema)
  155. def test_zero_exit_without_new_transaction_log_fails_closed(self) -> None:
  156. (self.log_dir / "bw_existing.log").write_text(self.success_log(), encoding="utf-8")
  157. receipt = self.module.execute_program_sram(
  158. source_bitstream=self.source_bit,
  159. expected_bitstream_sha256=self.expected_sha256,
  160. build_id=self.build_id,
  161. output_dir=self.output_dir,
  162. td_root=self.td_root_path,
  163. run_id="runtime-no-delta",
  164. process_runner=lambda command, **kwargs: subprocess.CompletedProcess(command, 0, stdout="bw > ", stderr=""),
  165. cleanup_runner=lambda _td_root: self.cleanup_result(),
  166. mutex_factory=lambda: FakeMutex(),
  167. )
  168. self.assertEqual(receipt["status"], "fail")
  169. self.assertIn("missing_bitwriter_log_delta", receipt["parser"]["failures"])
  170. self.assertFalse(receipt["parser"]["ordered_markers_complete"])
  171. def test_real_cli_stdout_mirror_and_connect_setup_are_accepted(self) -> None:
  172. cli_log = self.cli_success_log()
  173. def fake_runner(command, **kwargs):
  174. (self.log_dir / "bw_cli.log").write_text(cli_log, encoding="utf-8")
  175. return subprocess.CompletedProcess(command, 0, stdout=cli_log, stderr="")
  176. receipt = self.module.execute_program_sram(
  177. source_bitstream=self.source_bit,
  178. expected_bitstream_sha256=self.expected_sha256,
  179. build_id=self.build_id,
  180. output_dir=self.output_dir,
  181. td_root=self.td_root_path,
  182. run_id="runtime-cli-pass",
  183. process_runner=fake_runner,
  184. cleanup_runner=lambda _td_root: self.cleanup_result(),
  185. mutex_factory=lambda: FakeMutex(),
  186. )
  187. self.assertEqual(receipt["status"], "pass", receipt["parser"]["failures"])
  188. self.assertTrue(receipt["parser"]["stdout_transaction_mirror"])
  189. def test_tcl_script_load_failure_from_stdout_is_reported_explicitly(self) -> None:
  190. receipt = self.module.execute_program_sram(
  191. source_bitstream=self.source_bit,
  192. expected_bitstream_sha256=self.expected_sha256,
  193. build_id=self.build_id,
  194. output_dir=self.output_dir,
  195. td_root=self.td_root_path,
  196. run_id="runtime-tcl-load-failure",
  197. process_runner=lambda command, **kwargs: subprocess.CompletedProcess(
  198. command,
  199. 0,
  200. stdout='couldn\'t read file "C:broken\\program-sram.tcl": no such file or directory\nbw > ',
  201. stderr="",
  202. ),
  203. cleanup_runner=lambda _td_root: self.cleanup_result(),
  204. mutex_factory=lambda: FakeMutex(),
  205. )
  206. self.assertEqual(receipt["status"], "fail")
  207. self.assertIn("error_marker:couldn't read file", receipt["parser"]["failures"])
  208. def test_exit_zero_with_prg_error_or_multiple_transactions_fails(self) -> None:
  209. for name, delta, expected in (
  210. ("prg_error", "PRG-8002 ERROR Cannot open file\n", "error_marker:PRG-8002"),
  211. ("multiple", self.success_log() + self.success_log(), "transaction_count_not_one"),
  212. ):
  213. with self.subTest(name=name):
  214. output_dir = self.output_dir / name
  215. def fake_runner(command, **kwargs):
  216. (self.log_dir / f"bw_{name}.log").write_text(delta, encoding="utf-8")
  217. return subprocess.CompletedProcess(command, 0, stdout="bw > ", stderr="")
  218. receipt = self.module.execute_program_sram(
  219. source_bitstream=self.source_bit,
  220. expected_bitstream_sha256=self.expected_sha256,
  221. build_id=self.build_id,
  222. output_dir=output_dir,
  223. td_root=self.td_root_path,
  224. run_id=f"runtime-{name}",
  225. process_runner=fake_runner,
  226. cleanup_runner=lambda _td_root: self.cleanup_result(),
  227. mutex_factory=lambda: FakeMutex(),
  228. )
  229. self.assertNotEqual(receipt["status"], "pass")
  230. self.assertIn(expected, receipt["parser"]["failures"])
  231. def test_markers_cannot_be_joined_across_log_sources_or_stdout(self) -> None:
  232. success_lines = self.success_log().splitlines()
  233. cases = {
  234. "split_sources": (
  235. "\n".join(success_lines[:3]) + "\n",
  236. "\n".join(success_lines[3:]) + "\n",
  237. "",
  238. "ambiguous_bitwriter_log_sources",
  239. ),
  240. "stdout_supplement": (
  241. "\n".join(success_lines[:-1]) + "\n",
  242. "",
  243. success_lines[-1] + "\n",
  244. "missing_marker:download_finish",
  245. ),
  246. }
  247. for name, (first, second, stdout, expected) in cases.items():
  248. with self.subTest(name=name):
  249. output_dir = self.output_dir / name
  250. def fake_runner(command, **kwargs):
  251. (self.log_dir / f"bw_{name}_1.log").write_text(first, encoding="utf-8")
  252. if second:
  253. (self.log_dir / f"bw_{name}_2.log").write_text(second, encoding="utf-8")
  254. return subprocess.CompletedProcess(command, 0, stdout=stdout, stderr="")
  255. receipt = self.module.execute_program_sram(
  256. source_bitstream=self.source_bit,
  257. expected_bitstream_sha256=self.expected_sha256,
  258. build_id=self.build_id,
  259. output_dir=output_dir,
  260. td_root=self.td_root_path,
  261. run_id=f"runtime-{name}",
  262. process_runner=fake_runner,
  263. cleanup_runner=lambda _td_root: self.cleanup_result(),
  264. mutex_factory=lambda: FakeMutex(),
  265. )
  266. self.assertNotEqual(receipt["status"], "pass")
  267. self.assertIn(expected, receipt["parser"]["failures"])
  268. def test_partial_or_stderr_transaction_markers_outside_authoritative_log_fail(self) -> None:
  269. markers = {
  270. "run": 'RUN-1002 : start command "program -cable 0 -mode svf -spd 2 -p"\n',
  271. "chip": "PRG-2014 : Chip validation success: EF2L45\n",
  272. }
  273. for marker_name, marker in markers.items():
  274. for stream_name in ("stdout", "stderr"):
  275. with self.subTest(marker=marker_name, stream=stream_name):
  276. output_dir = self.output_dir / marker_name / stream_name
  277. def fake_runner(command, **kwargs):
  278. (self.log_dir / f"bw_{marker_name}_{stream_name}.log").write_text(
  279. self.success_log(), encoding="utf-8"
  280. )
  281. outputs = {"stdout": "bw > ", "stderr": ""}
  282. outputs[stream_name] = marker
  283. return subprocess.CompletedProcess(command, 0, **outputs)
  284. receipt = self.module.execute_program_sram(
  285. source_bitstream=self.source_bit,
  286. expected_bitstream_sha256=self.expected_sha256,
  287. build_id=self.build_id,
  288. output_dir=output_dir,
  289. td_root=self.td_root_path,
  290. run_id=f"runtime-marker-{marker_name}-{stream_name}",
  291. process_runner=fake_runner,
  292. cleanup_runner=lambda _td_root: self.cleanup_result(),
  293. mutex_factory=lambda: FakeMutex(),
  294. )
  295. self.assertEqual(receipt["status"], "fail")
  296. self.assertIn(
  297. f"transaction_marker_mismatch:{stream_name}",
  298. receipt["parser"]["failures"],
  299. )
  300. def test_replaced_log_file_is_not_treated_as_an_append_delta(self) -> None:
  301. existing = self.log_dir / "bw_existing.log"
  302. existing.write_text("historical\n", encoding="utf-8")
  303. def fake_runner(command, **kwargs):
  304. existing.unlink()
  305. existing.write_text(self.success_log(), encoding="utf-8")
  306. return subprocess.CompletedProcess(command, 0, stdout="", stderr="")
  307. receipt = self.module.execute_program_sram(
  308. source_bitstream=self.source_bit,
  309. expected_bitstream_sha256=self.expected_sha256,
  310. build_id=self.build_id,
  311. output_dir=self.output_dir / "replaced",
  312. td_root=self.td_root_path,
  313. run_id="runtime-replaced",
  314. process_runner=fake_runner,
  315. cleanup_runner=lambda _td_root: self.cleanup_result(),
  316. mutex_factory=lambda: FakeMutex(),
  317. )
  318. self.assertEqual(receipt["status"], "fail")
  319. self.assertIn("bitwriter_log_replaced_or_truncated", receipt["parser"]["failures"])
  320. def test_windows_job_runner_kills_spawned_process_tree_on_timeout(self) -> None:
  321. if sys.platform != "win32":
  322. self.skipTest("Windows Job Object coverage")
  323. with tempfile.TemporaryDirectory() as tmp:
  324. root = Path(tmp)
  325. child_pid_path = root / "child.pid"
  326. script = root / "parent.py"
  327. script.write_text(
  328. "import pathlib, subprocess, sys, time\n"
  329. "child = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(60)'])\n"
  330. "pathlib.Path(sys.argv[1]).write_text(str(child.pid), encoding='ascii')\n"
  331. "time.sleep(60)\n",
  332. encoding="ascii",
  333. )
  334. with self.assertRaises(subprocess.TimeoutExpired):
  335. self.module.run_process_in_job(
  336. [sys.executable, str(script), str(child_pid_path)],
  337. cwd=str(root),
  338. timeout=1.0,
  339. capture_output=True,
  340. text=True,
  341. check=False,
  342. )
  343. startup_deadline = time.monotonic() + 2.0
  344. while not child_pid_path.is_file() and time.monotonic() < startup_deadline:
  345. time.sleep(0.01)
  346. self.assertTrue(child_pid_path.is_file(), "parent did not report the spawned child PID")
  347. child_pid = int(child_pid_path.read_text(encoding="ascii"))
  348. termination_deadline = time.monotonic() + 2.0
  349. while (
  350. self.module.windows_process_is_running(child_pid)
  351. and time.monotonic() < termination_deadline
  352. ):
  353. time.sleep(0.01)
  354. self.assertFalse(
  355. self.module.windows_process_is_running(child_pid),
  356. "Job Object did not terminate the spawned child process",
  357. )
  358. def test_td_process_cleanup_accepts_a_normal_absolute_windows_path(self) -> None:
  359. if sys.platform != "win32":
  360. self.skipTest("Windows PowerShell process cleanup coverage")
  361. with tempfile.TemporaryDirectory() as tmp:
  362. td_root = Path(tmp) / "TD"
  363. td_root.mkdir()
  364. result = self.module.close_td_processes(td_root)
  365. self.assertEqual(result["status"], "pass", result)
  366. self.assertEqual(Path(result["td_root"]), td_root.resolve())
  367. self.assertEqual(result["remaining"], [])
  368. def test_hash_mismatch_and_busy_mutex_do_not_launch_bitwriter(self) -> None:
  369. calls: list[str] = []
  370. def fake_runner(command, **kwargs):
  371. calls.append("called")
  372. return subprocess.CompletedProcess(command, 0, stdout="", stderr="")
  373. with self.assertRaisesRegex(ValueError, "bitstream SHA256 mismatch"):
  374. self.module.execute_program_sram(
  375. source_bitstream=self.source_bit,
  376. expected_bitstream_sha256="0" * 64,
  377. build_id=self.build_id,
  378. output_dir=self.output_dir / "hash",
  379. td_root=self.td_root_path,
  380. run_id="runtime-hash",
  381. process_runner=fake_runner,
  382. cleanup_runner=lambda _td_root: self.cleanup_result(),
  383. mutex_factory=lambda: FakeMutex(),
  384. )
  385. self.assertEqual(calls, [])
  386. reused = self.output_dir / "reused"
  387. reused.mkdir()
  388. (reused / "existing.txt").write_text("do not overwrite", encoding="ascii")
  389. with self.assertRaisesRegex(FileExistsError, "output directory is not empty"):
  390. self.module.execute_program_sram(
  391. source_bitstream=self.source_bit,
  392. expected_bitstream_sha256=self.expected_sha256,
  393. build_id=self.build_id,
  394. output_dir=reused,
  395. td_root=self.td_root_path,
  396. run_id="runtime-reused",
  397. process_runner=fake_runner,
  398. cleanup_runner=lambda _td_root: self.cleanup_result(),
  399. mutex_factory=lambda: FakeMutex(),
  400. )
  401. self.assertEqual(calls, [])
  402. with self.assertRaisesRegex(TimeoutError, "mutex busy"):
  403. self.module.execute_program_sram(
  404. source_bitstream=self.source_bit,
  405. expected_bitstream_sha256=self.expected_sha256,
  406. build_id=self.build_id,
  407. output_dir=self.output_dir / "mutex",
  408. td_root=self.td_root_path,
  409. run_id="runtime-mutex",
  410. process_runner=fake_runner,
  411. cleanup_runner=lambda _td_root: self.cleanup_result(),
  412. mutex_factory=lambda: FakeMutex(acquired=False),
  413. )
  414. self.assertEqual(calls, [])
  415. if __name__ == "__main__":
  416. unittest.main()