test_package_for_agent_analysis.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  1. #!/usr/bin/env python3
  2. """Tests for the root-level complete agent analysis packager."""
  3. from __future__ import annotations
  4. import importlib.util
  5. import hashlib
  6. import json
  7. import random
  8. import shutil
  9. import subprocess
  10. import sys
  11. import tempfile
  12. import unittest
  13. import zipfile
  14. from pathlib import Path
  15. from types import ModuleType
  16. from unittest import mock
  17. import jsonschema
  18. ROOT = Path(__file__).resolve().parents[2]
  19. MODULE_PATH = ROOT / "package_for_agent_analysis.py"
  20. def write_file(root: Path, relative: str, data: bytes = b"fixture\n") -> Path:
  21. path = root / Path(relative)
  22. path.parent.mkdir(parents=True, exist_ok=True)
  23. path.write_bytes(data)
  24. return path
  25. def load_analyzer(testcase: unittest.TestCase) -> ModuleType:
  26. testcase.assertTrue(MODULE_PATH.is_file(), "root analysis packager is missing")
  27. spec = importlib.util.spec_from_file_location("package_for_agent_analysis", MODULE_PATH)
  28. testcase.assertIsNotNone(spec)
  29. testcase.assertIsNotNone(spec.loader)
  30. module = importlib.util.module_from_spec(spec)
  31. spec.loader.exec_module(module)
  32. return module
  33. class PackageForAgentAnalysisTests(unittest.TestCase):
  34. maxDiff = None
  35. def test_config_expands_source_roots_and_rejects_positive_include_rules(self) -> None:
  36. analyzer = load_analyzer(self)
  37. with tempfile.TemporaryDirectory() as tmp:
  38. temp = Path(tmp)
  39. config_path = temp / "sources.json"
  40. config_path.write_text(
  41. json.dumps(
  42. {
  43. "schema": "cpld-agent-analysis-sources-v1",
  44. "max_zip_bytes": 380_000_000,
  45. "target_zip_bytes": 350_000_000,
  46. "external_sources": [
  47. {
  48. "id": "board-viewer",
  49. "category": "hardware",
  50. "kind": "directory",
  51. "path_candidates": ["{user_profile}/board-viewer"],
  52. "archive_policy": "inspect",
  53. }
  54. ],
  55. "extra_exclusions": [],
  56. }
  57. ),
  58. encoding="utf-8",
  59. )
  60. config = analyzer.load_config(
  61. config_path,
  62. repo_root=temp / "repo",
  63. user_profile=temp / "user",
  64. )
  65. self.assertEqual(config.max_zip_bytes, 380_000_000)
  66. self.assertEqual(config.target_zip_bytes, 350_000_000)
  67. self.assertEqual(
  68. config.external_sources[0].path_candidates,
  69. (temp / "user" / "board-viewer",),
  70. )
  71. payload = json.loads(config_path.read_text(encoding="utf-8"))
  72. payload["external_sources"][0]["include_globs"] = ["*.brd"]
  73. config_path.write_text(json.dumps(payload), encoding="utf-8")
  74. with self.assertRaisesRegex(analyzer.PackagingError, "include"):
  75. analyzer.load_config(
  76. config_path,
  77. repo_root=temp / "repo",
  78. user_profile=temp / "user",
  79. )
  80. del payload["external_sources"][0]["include_globs"]
  81. payload["extra_exclusions"] = [
  82. {
  83. "path": "generated/cache",
  84. "reason": "known_rebuildable_cache",
  85. "include_globs": ["*.brd"],
  86. }
  87. ]
  88. config_path.write_text(json.dumps(payload), encoding="utf-8")
  89. with self.assertRaisesRegex(analyzer.PackagingError, "include"):
  90. analyzer.load_config(
  91. config_path,
  92. repo_root=temp / "repo",
  93. user_profile=temp / "user",
  94. )
  95. def test_default_config_and_output_index_match_versioned_schemas(self) -> None:
  96. analyzer = load_analyzer(self)
  97. config_path = ROOT / "config" / "agent_analysis_handoff_sources.json"
  98. config_schema_path = ROOT / "schemas" / "agent_analysis_handoff_sources.schema.json"
  99. index_schema_path = ROOT / "schemas" / "agent_analysis_handoff_index.schema.json"
  100. config_payload = json.loads(config_path.read_text(encoding="utf-8"))
  101. config_schema = json.loads(config_schema_path.read_text(encoding="utf-8"))
  102. jsonschema.validate(config_payload, config_schema)
  103. self.assertEqual(
  104. {item["id"] for item in config_payload["external_sources"]},
  105. {"td-docs", "board-viewer", "p4-review-worktree", "codegraph"},
  106. )
  107. self.assertIn(
  108. {"path": ".codegraph", "reason": "declared_external_reparse_alias"},
  109. config_payload["extra_exclusions"],
  110. )
  111. with tempfile.TemporaryDirectory() as tmp:
  112. temp = Path(tmp)
  113. source = temp / "source"
  114. item = write_file(source, "data/file.bin", b"fixture")
  115. collection = analyzer.AnalysisCollection(
  116. status="pass",
  117. items=(
  118. analyzer.make_package_item(
  119. item,
  120. relative="workspace-current/data/file.bin",
  121. category="core",
  122. source_id="workspace-current",
  123. ),
  124. ),
  125. excluded=(),
  126. warnings=(),
  127. sources=({"id": "workspace-current", "status": "pass"},),
  128. git=(),
  129. )
  130. result = analyzer.create_analysis_package(
  131. collection=collection,
  132. output_root=temp / "output",
  133. package_name="schema-fixture",
  134. max_zip_bytes=1_000_000,
  135. target_zip_bytes=800_000,
  136. force=False,
  137. )
  138. index = json.loads(
  139. (Path(result["output_dir"]) / "HANDOFF-INDEX.json").read_text(encoding="utf-8")
  140. )
  141. index_schema = json.loads(index_schema_path.read_text(encoding="utf-8"))
  142. jsonschema.validate(index, index_schema)
  143. def test_analysis_scan_keeps_unknown_and_generated_files(self) -> None:
  144. analyzer = load_analyzer(self)
  145. with tempfile.TemporaryDirectory() as tmp:
  146. root = Path(tmp)
  147. write_file(root, "src/rtl/core.v")
  148. write_file(root, "reference/original/board/main.brd", b"board")
  149. write_file(root, "td/build/current/design.bit", b"bitstream")
  150. write_file(root, ".codegraph/codegraph.db", b"graph")
  151. write_file(root, "tmp/formal/result.vvp", b"simulation")
  152. write_file(root, "unknown/evidence.bin", b"unknown")
  153. write_file(root, ".venv/Scripts/python.exe", b"venv")
  154. write_file(root, "pkg/__pycache__/cache.pyc", b"cache")
  155. write_file(root, "reference/original/local_archives/Anlogic.lic", b"license")
  156. write_file(root, "tmp/sysinternals-handle-test/handle.exe", b"tool")
  157. candidates, excluded, _ = analyzer.scan_analysis_root(root)
  158. included = {item.relative for item in candidates}
  159. self.assertIn("src/rtl/core.v", included)
  160. self.assertIn("reference/original/board/main.brd", included)
  161. self.assertIn("td/build/current/design.bit", included)
  162. self.assertIn(".codegraph/codegraph.db", included)
  163. self.assertIn("tmp/formal/result.vvp", included)
  164. self.assertIn("unknown/evidence.bin", included)
  165. excluded_by_path = {item["path"]: item["rule"] for item in excluded}
  166. self.assertEqual(excluded_by_path[".venv"], "virtual_environment")
  167. self.assertEqual(excluded_by_path["pkg/__pycache__"], "python_bytecode_cache")
  168. self.assertEqual(
  169. excluded_by_path["reference/original/local_archives/Anlogic.lic"],
  170. "credential_or_license_file",
  171. )
  172. self.assertEqual(
  173. excluded_by_path["tmp/sysinternals-handle-test"],
  174. "external_tool_cache",
  175. )
  176. def test_missing_external_sources_are_warnings(self) -> None:
  177. analyzer = load_analyzer(self)
  178. with tempfile.TemporaryDirectory() as tmp:
  179. temp = Path(tmp)
  180. existing = temp / "existing"
  181. write_file(existing, "board.xml", b"board")
  182. source_type = analyzer.ExternalSource
  183. sources = (
  184. source_type(
  185. id="existing",
  186. category="hardware",
  187. kind="directory",
  188. path_candidates=(existing,),
  189. archive_policy="inspect",
  190. ),
  191. source_type(
  192. id="missing",
  193. category="td-docs",
  194. kind="directory",
  195. path_candidates=(temp / "missing",),
  196. archive_policy="inspect",
  197. ),
  198. )
  199. resolved, warnings = analyzer.resolve_external_sources(sources)
  200. self.assertEqual([item.id for item in resolved], ["existing"])
  201. self.assertEqual(len(warnings), 1)
  202. self.assertEqual(warnings[0]["code"], "missing_external_source")
  203. self.assertEqual(warnings[0]["source_id"], "missing")
  204. def test_collect_analysis_inputs_rebases_sources_and_creates_git_bundles(self) -> None:
  205. git = shutil.which("git")
  206. if not git:
  207. self.skipTest("Git is required")
  208. analyzer = load_analyzer(self)
  209. with tempfile.TemporaryDirectory() as tmp:
  210. temp = Path(tmp)
  211. repo = temp / "repo"
  212. review = temp / "review"
  213. for root, tracked_name in ((repo, "main.txt"), (review, "review.txt")):
  214. root.mkdir()
  215. subprocess.run([git, "init", "-q", str(root)], check=True)
  216. subprocess.run([git, "-C", str(root), "config", "user.name", "Test"], check=True)
  217. subprocess.run(
  218. [git, "-C", str(root), "config", "user.email", "test@example.invalid"],
  219. check=True,
  220. )
  221. write_file(root, tracked_name, tracked_name.encode("ascii"))
  222. subprocess.run([git, "-C", str(root), "add", tracked_name], check=True)
  223. subprocess.run([git, "-C", str(root), "commit", "-q", "-m", "fixture"], check=True)
  224. write_file(repo, "td/build/current/design.bit", b"bitstream")
  225. write_file(review, "notes/untracked.txt", b"review notes")
  226. config = analyzer.HandoffConfig(
  227. max_zip_bytes=380_000_000,
  228. target_zip_bytes=350_000_000,
  229. external_sources=(
  230. analyzer.ExternalSource(
  231. id="review-worktree",
  232. category="core",
  233. kind="git_worktree",
  234. path_candidates=(review,),
  235. archive_policy="inspect",
  236. ),
  237. analyzer.ExternalSource(
  238. id="missing-docs",
  239. category="td-docs",
  240. kind="directory",
  241. path_candidates=(temp / "missing",),
  242. archive_policy="inspect",
  243. ),
  244. ),
  245. extra_exclusions=(),
  246. )
  247. collection = analyzer.collect_analysis_inputs(
  248. repo_root=repo,
  249. config=config,
  250. temp_root=temp / "run",
  251. )
  252. item_paths = {item.candidate.relative for item in collection.items}
  253. self.assertIn("workspace-current/td/build/current/design.bit", item_paths)
  254. self.assertIn("external/review-worktree/notes/untracked.txt", item_paths)
  255. self.assertIn("git-history/workspace-current.bundle", item_paths)
  256. self.assertIn("git-history/review-worktree.bundle", item_paths)
  257. self.assertEqual(collection.status, "pass_with_warnings")
  258. self.assertEqual(collection.warnings[0]["source_id"], "missing-docs")
  259. sources_by_id = {item["id"]: item for item in collection.sources}
  260. self.assertEqual(Path(sources_by_id["workspace-current"]["path"]), repo.resolve())
  261. self.assertEqual(Path(sources_by_id["review-worktree"]["path"]), review.resolve())
  262. for item in collection.items:
  263. if item.candidate.relative.startswith("git-history/"):
  264. result = subprocess.run(
  265. [git, "bundle", "verify", str(item.candidate.absolute)],
  266. capture_output=True,
  267. text=True,
  268. check=False,
  269. )
  270. self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
  271. def test_existing_invalid_external_git_worktree_fails_instead_of_warning(self) -> None:
  272. git = shutil.which("git")
  273. if not git:
  274. self.skipTest("Git is required")
  275. analyzer = load_analyzer(self)
  276. with tempfile.TemporaryDirectory() as tmp:
  277. temp = Path(tmp)
  278. repo = temp / "repo"
  279. repo.mkdir()
  280. subprocess.run([git, "init", "-q", str(repo)], check=True)
  281. subprocess.run([git, "-C", str(repo), "config", "user.name", "Test"], check=True)
  282. subprocess.run(
  283. [git, "-C", str(repo), "config", "user.email", "test@example.invalid"],
  284. check=True,
  285. )
  286. write_file(repo, "tracked.txt", b"tracked")
  287. subprocess.run([git, "-C", str(repo), "add", "tracked.txt"], check=True)
  288. subprocess.run([git, "-C", str(repo), "commit", "-q", "-m", "fixture"], check=True)
  289. invalid = temp / "invalid-worktree"
  290. write_file(invalid, "notes.txt", b"not a Git repository")
  291. config = analyzer.HandoffConfig(
  292. max_zip_bytes=380_000_000,
  293. target_zip_bytes=350_000_000,
  294. external_sources=(
  295. analyzer.ExternalSource(
  296. id="invalid-worktree",
  297. category="core",
  298. kind="git_worktree",
  299. path_candidates=(invalid,),
  300. archive_policy="inspect",
  301. ),
  302. ),
  303. extra_exclusions=(),
  304. )
  305. with self.assertRaisesRegex(analyzer.PackagingError, "Git command failed"):
  306. analyzer.collect_analysis_inputs(
  307. repo_root=repo,
  308. config=config,
  309. temp_root=temp / "run",
  310. )
  311. def test_unsupported_archive_keeps_safe_raw_and_sanitizes_license_archive(self) -> None:
  312. analyzer = load_analyzer(self)
  313. seven_zip = analyzer.find_7z()
  314. if seven_zip is None:
  315. self.skipTest("7-Zip is required")
  316. with tempfile.TemporaryDirectory() as tmp:
  317. temp = Path(tmp)
  318. def make_archive(name: str, entries: dict[str, bytes]) -> Path:
  319. source = temp / f"{name}-source"
  320. for relative, data in entries.items():
  321. write_file(source, relative, data)
  322. archive = temp / f"{name}.7z"
  323. result = subprocess.run(
  324. [str(seven_zip), "a", "-t7z", str(archive), ".\\*"],
  325. cwd=source,
  326. capture_output=True,
  327. text=True,
  328. check=False,
  329. )
  330. self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
  331. return archive
  332. safe_archive = make_archive("safe", {"docs/readme.txt": b"safe\n"})
  333. sensitive_archive = make_archive(
  334. "sensitive",
  335. {
  336. "docs/readme.txt": b"safe\n",
  337. "private/Anlogic.lic": b"license\n",
  338. },
  339. )
  340. items = (
  341. analyzer.make_package_item(
  342. safe_archive,
  343. relative="external/hardware/safe.7z",
  344. category="hardware",
  345. source_id="hardware",
  346. ),
  347. analyzer.make_package_item(
  348. sensitive_archive,
  349. relative="external/hardware/sensitive.7z",
  350. category="hardware",
  351. source_id="hardware",
  352. ),
  353. )
  354. prepared = analyzer.prepare_unsupported_archives(
  355. items,
  356. temp_root=temp / "expanded",
  357. seven_zip=seven_zip,
  358. extra_exclusions=(),
  359. )
  360. paths = {item.candidate.relative for item in prepared.items}
  361. self.assertIn("external/hardware/safe.7z", paths)
  362. self.assertIn("external/hardware/safe.7z.expanded/docs/readme.txt", paths)
  363. self.assertNotIn("external/hardware/sensitive.7z", paths)
  364. self.assertIn("external/hardware/sensitive.7z.expanded/docs/readme.txt", paths)
  365. self.assertNotIn("external/hardware/sensitive.7z.expanded/private/Anlogic.lic", paths)
  366. self.assertTrue(
  367. any(
  368. item["path"] == "external/hardware/sensitive.7z"
  369. and item["rule"] == "unsupported_archive_contains_sensitive_content"
  370. for item in prepared.excluded
  371. )
  372. )
  373. raw_safe = next(
  374. item for item in prepared.items if item.candidate.relative == "external/hardware/safe.7z"
  375. )
  376. self.assertFalse(raw_safe.scan_archive)
  377. def test_supported_archive_rejects_license_member_by_path(self) -> None:
  378. analyzer = load_analyzer(self)
  379. with tempfile.TemporaryDirectory() as tmp:
  380. temp = Path(tmp)
  381. archive_path = temp / "vendor.zip"
  382. with zipfile.ZipFile(archive_path, "w") as archive:
  383. archive.writestr("docs/readme.txt", b"safe\n")
  384. archive.writestr("private/Anlogic.lic", b"opaque vendor license\n")
  385. item = analyzer.make_package_item(
  386. archive_path,
  387. relative="external/vendor/vendor.zip",
  388. category="hardware",
  389. source_id="vendor",
  390. )
  391. with self.assertRaisesRegex(analyzer.PackagingError, "license|credential"):
  392. analyzer._audit_package_items((item,))
  393. def test_cli_explain_reports_inclusion_and_fixed_exclusion(self) -> None:
  394. with tempfile.TemporaryDirectory() as tmp:
  395. temp = Path(tmp)
  396. external = temp / "board-viewer"
  397. board = write_file(external, "board.cad", b"board")
  398. cached = write_file(external, ".venv/cache.bin", b"cache")
  399. config_path = temp / "sources.json"
  400. config_path.write_text(
  401. json.dumps(
  402. {
  403. "schema": "cpld-agent-analysis-sources-v1",
  404. "max_zip_bytes": 380_000_000,
  405. "target_zip_bytes": 350_000_000,
  406. "external_sources": [
  407. {
  408. "id": "board-viewer",
  409. "category": "hardware",
  410. "kind": "directory",
  411. "path_candidates": [str(external)],
  412. "archive_policy": "inspect",
  413. }
  414. ],
  415. "extra_exclusions": [],
  416. }
  417. ),
  418. encoding="utf-8",
  419. )
  420. help_result = subprocess.run(
  421. [sys.executable, str(MODULE_PATH), "--help"],
  422. capture_output=True,
  423. text=True,
  424. check=False,
  425. )
  426. self.assertEqual(help_result.returncode, 0, help_result.stderr)
  427. for option in (
  428. "--audit-only",
  429. "--explain",
  430. "--config",
  431. "--output-dir",
  432. "--package-name",
  433. "--force-overwrite",
  434. ):
  435. self.assertIn(option, help_result.stdout)
  436. included_result = subprocess.run(
  437. [
  438. sys.executable,
  439. str(MODULE_PATH),
  440. "--config",
  441. str(config_path),
  442. "--explain",
  443. str(board),
  444. ],
  445. capture_output=True,
  446. text=True,
  447. check=False,
  448. )
  449. self.assertEqual(included_result.returncode, 0, included_result.stderr)
  450. included = json.loads(included_result.stdout)
  451. self.assertEqual(included["decision"], "include")
  452. self.assertEqual(included["source_id"], "board-viewer")
  453. excluded_result = subprocess.run(
  454. [
  455. sys.executable,
  456. str(MODULE_PATH),
  457. "--config",
  458. str(config_path),
  459. "--explain",
  460. str(cached),
  461. ],
  462. capture_output=True,
  463. text=True,
  464. check=False,
  465. )
  466. self.assertEqual(excluded_result.returncode, 0, excluded_result.stderr)
  467. excluded = json.loads(excluded_result.stdout)
  468. self.assertEqual(excluded["decision"], "exclude")
  469. self.assertEqual(excluded["reason"], "virtual_environment")
  470. def test_create_analysis_package_writes_single_verified_zip_and_index(self) -> None:
  471. analyzer = load_analyzer(self)
  472. with tempfile.TemporaryDirectory() as tmp:
  473. temp = Path(tmp)
  474. source = temp / "source"
  475. first = write_file(source, "src/core.v", b"module core; endmodule\n")
  476. second = write_file(source, "reference/original/main.brd", b"board\n")
  477. collection = analyzer.AnalysisCollection(
  478. status="pass_with_warnings",
  479. items=(
  480. analyzer.make_package_item(
  481. first,
  482. relative="workspace-current/src/core.v",
  483. category="core",
  484. source_id="workspace-current",
  485. ),
  486. analyzer.make_package_item(
  487. second,
  488. relative="workspace-current/reference/original/main.brd",
  489. category="hardware",
  490. source_id="workspace-current",
  491. ),
  492. ),
  493. excluded=(),
  494. warnings=(
  495. {
  496. "code": "missing_external_source",
  497. "source_id": "td-docs",
  498. "message": "missing",
  499. },
  500. ),
  501. sources=({"id": "workspace-current", "status": "pass"},),
  502. git=(),
  503. )
  504. result = analyzer.create_analysis_package(
  505. collection=collection,
  506. output_root=temp / "output",
  507. package_name="single-fixture",
  508. max_zip_bytes=1_000_000,
  509. target_zip_bytes=800_000,
  510. force=False,
  511. )
  512. package_dir = Path(result["output_dir"])
  513. self.assertEqual(result["status"], "pass_with_warnings")
  514. self.assertEqual(len(result["volumes"]), 1)
  515. volume = package_dir / result["volumes"][0]["file"]
  516. self.assertLess(volume.stat().st_size, 1_000_000)
  517. self.assertTrue((package_dir / "HANDOFF-INDEX.json").is_file())
  518. self.assertTrue((package_dir / "START-HERE.zh-CN.md").is_file())
  519. self.assertTrue((package_dir / "SHA256SUMS.txt").is_file())
  520. with zipfile.ZipFile(volume) as archive:
  521. self.assertIsNone(archive.testzip())
  522. self.assertIn("CPLD/workspace-current/src/core.v", archive.namelist())
  523. self.assertIn("CPLD/workspace-current/reference/original/main.brd", archive.namelist())
  524. self.assertIn("CPLD/HANDOFF-METADATA/VOLUME-MANIFEST.json", archive.namelist())
  525. index = json.loads((package_dir / "HANDOFF-INDEX.json").read_text(encoding="utf-8"))
  526. self.assertEqual(index["status"], "pass_with_warnings")
  527. self.assertEqual(index["volumes"][0]["sha256"], hashlib.sha256(volume.read_bytes()).hexdigest())
  528. def test_create_analysis_package_splits_into_independent_zip_volumes(self) -> None:
  529. analyzer = load_analyzer(self)
  530. with tempfile.TemporaryDirectory() as tmp:
  531. temp = Path(tmp)
  532. source = temp / "source"
  533. randomizer = random.Random(7)
  534. items = []
  535. for index, category in enumerate(("core", "core", "hardware", "evidence"), start=1):
  536. path = write_file(source, f"data/file-{index}.bin", randomizer.randbytes(12_000))
  537. items.append(
  538. analyzer.make_package_item(
  539. path,
  540. relative=f"workspace-current/data/file-{index}.bin",
  541. category=category,
  542. source_id="workspace-current",
  543. )
  544. )
  545. collection = analyzer.AnalysisCollection(
  546. status="pass",
  547. items=tuple(items),
  548. excluded=(),
  549. warnings=(),
  550. sources=({"id": "workspace-current", "status": "pass"},),
  551. git=(),
  552. )
  553. result = analyzer.create_analysis_package(
  554. collection=collection,
  555. output_root=temp / "output",
  556. package_name="multi-fixture",
  557. max_zip_bytes=30_000,
  558. target_zip_bytes=20_000,
  559. force=False,
  560. )
  561. package_dir = Path(result["output_dir"])
  562. self.assertGreaterEqual(len(result["volumes"]), 2)
  563. seen_entries: set[str] = set()
  564. for volume_info in result["volumes"]:
  565. volume = package_dir / volume_info["file"]
  566. self.assertLess(volume.stat().st_size, 30_000)
  567. with zipfile.ZipFile(volume) as archive:
  568. self.assertIsNone(archive.testzip())
  569. self.assertIn("CPLD/HANDOFF-METADATA/VOLUME-MANIFEST.json", archive.namelist())
  570. seen_entries.update(
  571. name for name in archive.namelist() if name.startswith("CPLD/workspace-current/data/")
  572. )
  573. self.assertEqual(len(seen_entries), 4)
  574. def test_create_analysis_package_chunks_and_reassembles_single_large_file(self) -> None:
  575. analyzer = load_analyzer(self)
  576. with tempfile.TemporaryDirectory() as tmp:
  577. temp = Path(tmp)
  578. source = temp / "source"
  579. payload = random.Random(19).randbytes(55_000)
  580. large = write_file(source, "data/large.db", payload)
  581. collection = analyzer.AnalysisCollection(
  582. status="pass",
  583. items=(
  584. analyzer.make_package_item(
  585. large,
  586. relative="workspace-current/data/large.db",
  587. category="evidence",
  588. source_id="workspace-current",
  589. ),
  590. ),
  591. excluded=(),
  592. warnings=(),
  593. sources=({"id": "workspace-current", "status": "pass"},),
  594. git=(),
  595. )
  596. result = analyzer.create_analysis_package(
  597. collection=collection,
  598. output_root=temp / "output",
  599. package_name="large-fixture",
  600. max_zip_bytes=30_000,
  601. target_zip_bytes=20_000,
  602. force=False,
  603. )
  604. package_dir = Path(result["output_dir"])
  605. for volume_info in result["volumes"]:
  606. self.assertLess((package_dir / volume_info["file"]).stat().st_size, 30_000)
  607. index = json.loads((package_dir / "HANDOFF-INDEX.json").read_text(encoding="utf-8"))
  608. self.assertEqual(len(index["large_files"]), 1)
  609. large_info = index["large_files"][0]
  610. self.assertEqual(large_info["path"], "workspace-current/data/large.db")
  611. self.assertEqual(large_info["sha256"], hashlib.sha256(payload).hexdigest())
  612. self.assertGreaterEqual(len(large_info["chunks"]), 2)
  613. reassembler = package_dir / "reassemble_large_files.py"
  614. self.assertTrue(reassembler.is_file())
  615. reconstructed = temp / "reconstructed"
  616. completed = subprocess.run(
  617. [
  618. sys.executable,
  619. str(reassembler),
  620. "--package-dir",
  621. str(package_dir),
  622. "--output-dir",
  623. str(reconstructed),
  624. ],
  625. capture_output=True,
  626. text=True,
  627. check=False,
  628. )
  629. self.assertEqual(completed.returncode, 0, completed.stdout + completed.stderr)
  630. rebuilt = reconstructed / "workspace-current" / "data" / "large.db"
  631. self.assertEqual(rebuilt.read_bytes(), payload)
  632. def test_create_analysis_package_restores_previous_directory_when_publication_fails(self) -> None:
  633. analyzer = load_analyzer(self)
  634. with tempfile.TemporaryDirectory() as tmp:
  635. temp = Path(tmp)
  636. source = temp / "source"
  637. item = write_file(source, "data/file.bin", b"replacement")
  638. output_root = temp / "output"
  639. final_dir = output_root / "atomic-fixture"
  640. final_dir.mkdir(parents=True)
  641. marker = write_file(final_dir, "old-marker.txt", b"old package")
  642. collection = analyzer.AnalysisCollection(
  643. status="pass",
  644. items=(
  645. analyzer.make_package_item(
  646. item,
  647. relative="workspace-current/data/file.bin",
  648. category="core",
  649. source_id="workspace-current",
  650. ),
  651. ),
  652. excluded=(),
  653. warnings=(),
  654. sources=({"id": "workspace-current", "status": "pass"},),
  655. git=(),
  656. )
  657. real_replace = analyzer.os.replace
  658. def fail_new_directory(source_path: object, target_path: object) -> None:
  659. source_name = Path(source_path).name
  660. if (
  661. source_name != "atomic-fixture"
  662. and not source_name.endswith(".backup")
  663. and Path(target_path).name == "atomic-fixture"
  664. ):
  665. raise OSError("injected publication failure")
  666. real_replace(source_path, target_path)
  667. with mock.patch.object(analyzer.os, "replace", side_effect=fail_new_directory):
  668. with self.assertRaisesRegex(analyzer.PackagingError, "publish"):
  669. analyzer.create_analysis_package(
  670. collection=collection,
  671. output_root=output_root,
  672. package_name="atomic-fixture",
  673. max_zip_bytes=1_000_000,
  674. target_zip_bytes=800_000,
  675. force=True,
  676. )
  677. self.assertEqual(marker.read_bytes(), b"old package")
  678. self.assertEqual(
  679. [path.name for path in output_root.iterdir()],
  680. ["atomic-fixture"],
  681. )
  682. def test_create_analysis_package_keeps_previous_directory_when_backup_move_fails(self) -> None:
  683. analyzer = load_analyzer(self)
  684. with tempfile.TemporaryDirectory() as tmp:
  685. temp = Path(tmp)
  686. source = temp / "source"
  687. item = write_file(source, "data/file.bin", b"replacement")
  688. output_root = temp / "output"
  689. final_dir = output_root / "backup-failure-fixture"
  690. final_dir.mkdir(parents=True)
  691. marker = write_file(final_dir, "old-marker.txt", b"old package")
  692. collection = analyzer.AnalysisCollection(
  693. status="pass",
  694. items=(
  695. analyzer.make_package_item(
  696. item,
  697. relative="workspace-current/data/file.bin",
  698. category="core",
  699. source_id="workspace-current",
  700. ),
  701. ),
  702. excluded=(),
  703. warnings=(),
  704. sources=({"id": "workspace-current", "status": "pass"},),
  705. git=(),
  706. )
  707. real_replace = analyzer.os.replace
  708. def fail_backup_move(source_path: object, target_path: object) -> None:
  709. if Path(source_path).name == "backup-failure-fixture":
  710. raise OSError("injected backup move failure")
  711. real_replace(source_path, target_path)
  712. with mock.patch.object(analyzer.os, "replace", side_effect=fail_backup_move):
  713. with self.assertRaisesRegex(analyzer.PackagingError, "publish"):
  714. analyzer.create_analysis_package(
  715. collection=collection,
  716. output_root=output_root,
  717. package_name="backup-failure-fixture",
  718. max_zip_bytes=1_000_000,
  719. target_zip_bytes=800_000,
  720. force=True,
  721. )
  722. self.assertEqual(marker.read_bytes(), b"old package")
  723. self.assertEqual(
  724. [path.name for path in output_root.iterdir()],
  725. ["backup-failure-fixture"],
  726. )
  727. if __name__ == "__main__":
  728. unittest.main()