| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787 |
- #!/usr/bin/env python3
- """Tests for the root-level complete agent analysis packager."""
- from __future__ import annotations
- import importlib.util
- import hashlib
- import json
- import random
- import shutil
- import subprocess
- import sys
- import tempfile
- import unittest
- import zipfile
- from pathlib import Path
- from types import ModuleType
- from unittest import mock
- import jsonschema
- ROOT = Path(__file__).resolve().parents[2]
- MODULE_PATH = ROOT / "package_for_agent_analysis.py"
- def write_file(root: Path, relative: str, data: bytes = b"fixture\n") -> Path:
- path = root / Path(relative)
- path.parent.mkdir(parents=True, exist_ok=True)
- path.write_bytes(data)
- return path
- def load_analyzer(testcase: unittest.TestCase) -> ModuleType:
- testcase.assertTrue(MODULE_PATH.is_file(), "root analysis packager is missing")
- spec = importlib.util.spec_from_file_location("package_for_agent_analysis", MODULE_PATH)
- testcase.assertIsNotNone(spec)
- testcase.assertIsNotNone(spec.loader)
- module = importlib.util.module_from_spec(spec)
- spec.loader.exec_module(module)
- return module
- class PackageForAgentAnalysisTests(unittest.TestCase):
- maxDiff = None
- def test_config_expands_source_roots_and_rejects_positive_include_rules(self) -> None:
- analyzer = load_analyzer(self)
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- config_path = temp / "sources.json"
- config_path.write_text(
- json.dumps(
- {
- "schema": "cpld-agent-analysis-sources-v1",
- "max_zip_bytes": 380_000_000,
- "target_zip_bytes": 350_000_000,
- "external_sources": [
- {
- "id": "board-viewer",
- "category": "hardware",
- "kind": "directory",
- "path_candidates": ["{user_profile}/board-viewer"],
- "archive_policy": "inspect",
- }
- ],
- "extra_exclusions": [],
- }
- ),
- encoding="utf-8",
- )
- config = analyzer.load_config(
- config_path,
- repo_root=temp / "repo",
- user_profile=temp / "user",
- )
- self.assertEqual(config.max_zip_bytes, 380_000_000)
- self.assertEqual(config.target_zip_bytes, 350_000_000)
- self.assertEqual(
- config.external_sources[0].path_candidates,
- (temp / "user" / "board-viewer",),
- )
- payload = json.loads(config_path.read_text(encoding="utf-8"))
- payload["external_sources"][0]["include_globs"] = ["*.brd"]
- config_path.write_text(json.dumps(payload), encoding="utf-8")
- with self.assertRaisesRegex(analyzer.PackagingError, "include"):
- analyzer.load_config(
- config_path,
- repo_root=temp / "repo",
- user_profile=temp / "user",
- )
- del payload["external_sources"][0]["include_globs"]
- payload["extra_exclusions"] = [
- {
- "path": "generated/cache",
- "reason": "known_rebuildable_cache",
- "include_globs": ["*.brd"],
- }
- ]
- config_path.write_text(json.dumps(payload), encoding="utf-8")
- with self.assertRaisesRegex(analyzer.PackagingError, "include"):
- analyzer.load_config(
- config_path,
- repo_root=temp / "repo",
- user_profile=temp / "user",
- )
- def test_default_config_and_output_index_match_versioned_schemas(self) -> None:
- analyzer = load_analyzer(self)
- config_path = ROOT / "config" / "agent_analysis_handoff_sources.json"
- config_schema_path = ROOT / "schemas" / "agent_analysis_handoff_sources.schema.json"
- index_schema_path = ROOT / "schemas" / "agent_analysis_handoff_index.schema.json"
- config_payload = json.loads(config_path.read_text(encoding="utf-8"))
- config_schema = json.loads(config_schema_path.read_text(encoding="utf-8"))
- jsonschema.validate(config_payload, config_schema)
- self.assertEqual(
- {item["id"] for item in config_payload["external_sources"]},
- {"td-docs", "board-viewer", "p4-review-worktree", "codegraph"},
- )
- self.assertIn(
- {"path": ".codegraph", "reason": "declared_external_reparse_alias"},
- config_payload["extra_exclusions"],
- )
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- source = temp / "source"
- item = write_file(source, "data/file.bin", b"fixture")
- collection = analyzer.AnalysisCollection(
- status="pass",
- items=(
- analyzer.make_package_item(
- item,
- relative="workspace-current/data/file.bin",
- category="core",
- source_id="workspace-current",
- ),
- ),
- excluded=(),
- warnings=(),
- sources=({"id": "workspace-current", "status": "pass"},),
- git=(),
- )
- result = analyzer.create_analysis_package(
- collection=collection,
- output_root=temp / "output",
- package_name="schema-fixture",
- max_zip_bytes=1_000_000,
- target_zip_bytes=800_000,
- force=False,
- )
- index = json.loads(
- (Path(result["output_dir"]) / "HANDOFF-INDEX.json").read_text(encoding="utf-8")
- )
- index_schema = json.loads(index_schema_path.read_text(encoding="utf-8"))
- jsonschema.validate(index, index_schema)
- def test_analysis_scan_keeps_unknown_and_generated_files(self) -> None:
- analyzer = load_analyzer(self)
- with tempfile.TemporaryDirectory() as tmp:
- root = Path(tmp)
- write_file(root, "src/rtl/core.v")
- write_file(root, "reference/original/board/main.brd", b"board")
- write_file(root, "td/build/current/design.bit", b"bitstream")
- write_file(root, ".codegraph/codegraph.db", b"graph")
- write_file(root, "tmp/formal/result.vvp", b"simulation")
- write_file(root, "unknown/evidence.bin", b"unknown")
- write_file(root, ".venv/Scripts/python.exe", b"venv")
- write_file(root, "pkg/__pycache__/cache.pyc", b"cache")
- write_file(root, "reference/original/local_archives/Anlogic.lic", b"license")
- write_file(root, "tmp/sysinternals-handle-test/handle.exe", b"tool")
- candidates, excluded, _ = analyzer.scan_analysis_root(root)
- included = {item.relative for item in candidates}
- self.assertIn("src/rtl/core.v", included)
- self.assertIn("reference/original/board/main.brd", included)
- self.assertIn("td/build/current/design.bit", included)
- self.assertIn(".codegraph/codegraph.db", included)
- self.assertIn("tmp/formal/result.vvp", included)
- self.assertIn("unknown/evidence.bin", included)
- excluded_by_path = {item["path"]: item["rule"] for item in excluded}
- self.assertEqual(excluded_by_path[".venv"], "virtual_environment")
- self.assertEqual(excluded_by_path["pkg/__pycache__"], "python_bytecode_cache")
- self.assertEqual(
- excluded_by_path["reference/original/local_archives/Anlogic.lic"],
- "credential_or_license_file",
- )
- self.assertEqual(
- excluded_by_path["tmp/sysinternals-handle-test"],
- "external_tool_cache",
- )
- def test_missing_external_sources_are_warnings(self) -> None:
- analyzer = load_analyzer(self)
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- existing = temp / "existing"
- write_file(existing, "board.xml", b"board")
- source_type = analyzer.ExternalSource
- sources = (
- source_type(
- id="existing",
- category="hardware",
- kind="directory",
- path_candidates=(existing,),
- archive_policy="inspect",
- ),
- source_type(
- id="missing",
- category="td-docs",
- kind="directory",
- path_candidates=(temp / "missing",),
- archive_policy="inspect",
- ),
- )
- resolved, warnings = analyzer.resolve_external_sources(sources)
- self.assertEqual([item.id for item in resolved], ["existing"])
- self.assertEqual(len(warnings), 1)
- self.assertEqual(warnings[0]["code"], "missing_external_source")
- self.assertEqual(warnings[0]["source_id"], "missing")
- def test_collect_analysis_inputs_rebases_sources_and_creates_git_bundles(self) -> None:
- git = shutil.which("git")
- if not git:
- self.skipTest("Git is required")
- analyzer = load_analyzer(self)
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- repo = temp / "repo"
- review = temp / "review"
- for root, tracked_name in ((repo, "main.txt"), (review, "review.txt")):
- root.mkdir()
- subprocess.run([git, "init", "-q", str(root)], check=True)
- subprocess.run([git, "-C", str(root), "config", "user.name", "Test"], check=True)
- subprocess.run(
- [git, "-C", str(root), "config", "user.email", "test@example.invalid"],
- check=True,
- )
- write_file(root, tracked_name, tracked_name.encode("ascii"))
- subprocess.run([git, "-C", str(root), "add", tracked_name], check=True)
- subprocess.run([git, "-C", str(root), "commit", "-q", "-m", "fixture"], check=True)
- write_file(repo, "td/build/current/design.bit", b"bitstream")
- write_file(review, "notes/untracked.txt", b"review notes")
- config = analyzer.HandoffConfig(
- max_zip_bytes=380_000_000,
- target_zip_bytes=350_000_000,
- external_sources=(
- analyzer.ExternalSource(
- id="review-worktree",
- category="core",
- kind="git_worktree",
- path_candidates=(review,),
- archive_policy="inspect",
- ),
- analyzer.ExternalSource(
- id="missing-docs",
- category="td-docs",
- kind="directory",
- path_candidates=(temp / "missing",),
- archive_policy="inspect",
- ),
- ),
- extra_exclusions=(),
- )
- collection = analyzer.collect_analysis_inputs(
- repo_root=repo,
- config=config,
- temp_root=temp / "run",
- )
- item_paths = {item.candidate.relative for item in collection.items}
- self.assertIn("workspace-current/td/build/current/design.bit", item_paths)
- self.assertIn("external/review-worktree/notes/untracked.txt", item_paths)
- self.assertIn("git-history/workspace-current.bundle", item_paths)
- self.assertIn("git-history/review-worktree.bundle", item_paths)
- self.assertEqual(collection.status, "pass_with_warnings")
- self.assertEqual(collection.warnings[0]["source_id"], "missing-docs")
- sources_by_id = {item["id"]: item for item in collection.sources}
- self.assertEqual(Path(sources_by_id["workspace-current"]["path"]), repo.resolve())
- self.assertEqual(Path(sources_by_id["review-worktree"]["path"]), review.resolve())
- for item in collection.items:
- if item.candidate.relative.startswith("git-history/"):
- result = subprocess.run(
- [git, "bundle", "verify", str(item.candidate.absolute)],
- capture_output=True,
- text=True,
- check=False,
- )
- self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
- def test_existing_invalid_external_git_worktree_fails_instead_of_warning(self) -> None:
- git = shutil.which("git")
- if not git:
- self.skipTest("Git is required")
- analyzer = load_analyzer(self)
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- repo = temp / "repo"
- repo.mkdir()
- subprocess.run([git, "init", "-q", str(repo)], check=True)
- subprocess.run([git, "-C", str(repo), "config", "user.name", "Test"], check=True)
- subprocess.run(
- [git, "-C", str(repo), "config", "user.email", "test@example.invalid"],
- check=True,
- )
- write_file(repo, "tracked.txt", b"tracked")
- subprocess.run([git, "-C", str(repo), "add", "tracked.txt"], check=True)
- subprocess.run([git, "-C", str(repo), "commit", "-q", "-m", "fixture"], check=True)
- invalid = temp / "invalid-worktree"
- write_file(invalid, "notes.txt", b"not a Git repository")
- config = analyzer.HandoffConfig(
- max_zip_bytes=380_000_000,
- target_zip_bytes=350_000_000,
- external_sources=(
- analyzer.ExternalSource(
- id="invalid-worktree",
- category="core",
- kind="git_worktree",
- path_candidates=(invalid,),
- archive_policy="inspect",
- ),
- ),
- extra_exclusions=(),
- )
- with self.assertRaisesRegex(analyzer.PackagingError, "Git command failed"):
- analyzer.collect_analysis_inputs(
- repo_root=repo,
- config=config,
- temp_root=temp / "run",
- )
- def test_unsupported_archive_keeps_safe_raw_and_sanitizes_license_archive(self) -> None:
- analyzer = load_analyzer(self)
- seven_zip = analyzer.find_7z()
- if seven_zip is None:
- self.skipTest("7-Zip is required")
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- def make_archive(name: str, entries: dict[str, bytes]) -> Path:
- source = temp / f"{name}-source"
- for relative, data in entries.items():
- write_file(source, relative, data)
- archive = temp / f"{name}.7z"
- result = subprocess.run(
- [str(seven_zip), "a", "-t7z", str(archive), ".\\*"],
- cwd=source,
- capture_output=True,
- text=True,
- check=False,
- )
- self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
- return archive
- safe_archive = make_archive("safe", {"docs/readme.txt": b"safe\n"})
- sensitive_archive = make_archive(
- "sensitive",
- {
- "docs/readme.txt": b"safe\n",
- "private/Anlogic.lic": b"license\n",
- },
- )
- items = (
- analyzer.make_package_item(
- safe_archive,
- relative="external/hardware/safe.7z",
- category="hardware",
- source_id="hardware",
- ),
- analyzer.make_package_item(
- sensitive_archive,
- relative="external/hardware/sensitive.7z",
- category="hardware",
- source_id="hardware",
- ),
- )
- prepared = analyzer.prepare_unsupported_archives(
- items,
- temp_root=temp / "expanded",
- seven_zip=seven_zip,
- extra_exclusions=(),
- )
- paths = {item.candidate.relative for item in prepared.items}
- self.assertIn("external/hardware/safe.7z", paths)
- self.assertIn("external/hardware/safe.7z.expanded/docs/readme.txt", paths)
- self.assertNotIn("external/hardware/sensitive.7z", paths)
- self.assertIn("external/hardware/sensitive.7z.expanded/docs/readme.txt", paths)
- self.assertNotIn("external/hardware/sensitive.7z.expanded/private/Anlogic.lic", paths)
- self.assertTrue(
- any(
- item["path"] == "external/hardware/sensitive.7z"
- and item["rule"] == "unsupported_archive_contains_sensitive_content"
- for item in prepared.excluded
- )
- )
- raw_safe = next(
- item for item in prepared.items if item.candidate.relative == "external/hardware/safe.7z"
- )
- self.assertFalse(raw_safe.scan_archive)
- def test_supported_archive_rejects_license_member_by_path(self) -> None:
- analyzer = load_analyzer(self)
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- archive_path = temp / "vendor.zip"
- with zipfile.ZipFile(archive_path, "w") as archive:
- archive.writestr("docs/readme.txt", b"safe\n")
- archive.writestr("private/Anlogic.lic", b"opaque vendor license\n")
- item = analyzer.make_package_item(
- archive_path,
- relative="external/vendor/vendor.zip",
- category="hardware",
- source_id="vendor",
- )
- with self.assertRaisesRegex(analyzer.PackagingError, "license|credential"):
- analyzer._audit_package_items((item,))
- def test_cli_explain_reports_inclusion_and_fixed_exclusion(self) -> None:
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- external = temp / "board-viewer"
- board = write_file(external, "board.cad", b"board")
- cached = write_file(external, ".venv/cache.bin", b"cache")
- config_path = temp / "sources.json"
- config_path.write_text(
- json.dumps(
- {
- "schema": "cpld-agent-analysis-sources-v1",
- "max_zip_bytes": 380_000_000,
- "target_zip_bytes": 350_000_000,
- "external_sources": [
- {
- "id": "board-viewer",
- "category": "hardware",
- "kind": "directory",
- "path_candidates": [str(external)],
- "archive_policy": "inspect",
- }
- ],
- "extra_exclusions": [],
- }
- ),
- encoding="utf-8",
- )
- help_result = subprocess.run(
- [sys.executable, str(MODULE_PATH), "--help"],
- capture_output=True,
- text=True,
- check=False,
- )
- self.assertEqual(help_result.returncode, 0, help_result.stderr)
- for option in (
- "--audit-only",
- "--explain",
- "--config",
- "--output-dir",
- "--package-name",
- "--force-overwrite",
- ):
- self.assertIn(option, help_result.stdout)
- included_result = subprocess.run(
- [
- sys.executable,
- str(MODULE_PATH),
- "--config",
- str(config_path),
- "--explain",
- str(board),
- ],
- capture_output=True,
- text=True,
- check=False,
- )
- self.assertEqual(included_result.returncode, 0, included_result.stderr)
- included = json.loads(included_result.stdout)
- self.assertEqual(included["decision"], "include")
- self.assertEqual(included["source_id"], "board-viewer")
- excluded_result = subprocess.run(
- [
- sys.executable,
- str(MODULE_PATH),
- "--config",
- str(config_path),
- "--explain",
- str(cached),
- ],
- capture_output=True,
- text=True,
- check=False,
- )
- self.assertEqual(excluded_result.returncode, 0, excluded_result.stderr)
- excluded = json.loads(excluded_result.stdout)
- self.assertEqual(excluded["decision"], "exclude")
- self.assertEqual(excluded["reason"], "virtual_environment")
- def test_create_analysis_package_writes_single_verified_zip_and_index(self) -> None:
- analyzer = load_analyzer(self)
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- source = temp / "source"
- first = write_file(source, "src/core.v", b"module core; endmodule\n")
- second = write_file(source, "reference/original/main.brd", b"board\n")
- collection = analyzer.AnalysisCollection(
- status="pass_with_warnings",
- items=(
- analyzer.make_package_item(
- first,
- relative="workspace-current/src/core.v",
- category="core",
- source_id="workspace-current",
- ),
- analyzer.make_package_item(
- second,
- relative="workspace-current/reference/original/main.brd",
- category="hardware",
- source_id="workspace-current",
- ),
- ),
- excluded=(),
- warnings=(
- {
- "code": "missing_external_source",
- "source_id": "td-docs",
- "message": "missing",
- },
- ),
- sources=({"id": "workspace-current", "status": "pass"},),
- git=(),
- )
- result = analyzer.create_analysis_package(
- collection=collection,
- output_root=temp / "output",
- package_name="single-fixture",
- max_zip_bytes=1_000_000,
- target_zip_bytes=800_000,
- force=False,
- )
- package_dir = Path(result["output_dir"])
- self.assertEqual(result["status"], "pass_with_warnings")
- self.assertEqual(len(result["volumes"]), 1)
- volume = package_dir / result["volumes"][0]["file"]
- self.assertLess(volume.stat().st_size, 1_000_000)
- self.assertTrue((package_dir / "HANDOFF-INDEX.json").is_file())
- self.assertTrue((package_dir / "START-HERE.zh-CN.md").is_file())
- self.assertTrue((package_dir / "SHA256SUMS.txt").is_file())
- with zipfile.ZipFile(volume) as archive:
- self.assertIsNone(archive.testzip())
- self.assertIn("CPLD/workspace-current/src/core.v", archive.namelist())
- self.assertIn("CPLD/workspace-current/reference/original/main.brd", archive.namelist())
- self.assertIn("CPLD/HANDOFF-METADATA/VOLUME-MANIFEST.json", archive.namelist())
- index = json.loads((package_dir / "HANDOFF-INDEX.json").read_text(encoding="utf-8"))
- self.assertEqual(index["status"], "pass_with_warnings")
- self.assertEqual(index["volumes"][0]["sha256"], hashlib.sha256(volume.read_bytes()).hexdigest())
- def test_create_analysis_package_splits_into_independent_zip_volumes(self) -> None:
- analyzer = load_analyzer(self)
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- source = temp / "source"
- randomizer = random.Random(7)
- items = []
- for index, category in enumerate(("core", "core", "hardware", "evidence"), start=1):
- path = write_file(source, f"data/file-{index}.bin", randomizer.randbytes(12_000))
- items.append(
- analyzer.make_package_item(
- path,
- relative=f"workspace-current/data/file-{index}.bin",
- category=category,
- source_id="workspace-current",
- )
- )
- collection = analyzer.AnalysisCollection(
- status="pass",
- items=tuple(items),
- excluded=(),
- warnings=(),
- sources=({"id": "workspace-current", "status": "pass"},),
- git=(),
- )
- result = analyzer.create_analysis_package(
- collection=collection,
- output_root=temp / "output",
- package_name="multi-fixture",
- max_zip_bytes=30_000,
- target_zip_bytes=20_000,
- force=False,
- )
- package_dir = Path(result["output_dir"])
- self.assertGreaterEqual(len(result["volumes"]), 2)
- seen_entries: set[str] = set()
- for volume_info in result["volumes"]:
- volume = package_dir / volume_info["file"]
- self.assertLess(volume.stat().st_size, 30_000)
- with zipfile.ZipFile(volume) as archive:
- self.assertIsNone(archive.testzip())
- self.assertIn("CPLD/HANDOFF-METADATA/VOLUME-MANIFEST.json", archive.namelist())
- seen_entries.update(
- name for name in archive.namelist() if name.startswith("CPLD/workspace-current/data/")
- )
- self.assertEqual(len(seen_entries), 4)
- def test_create_analysis_package_chunks_and_reassembles_single_large_file(self) -> None:
- analyzer = load_analyzer(self)
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- source = temp / "source"
- payload = random.Random(19).randbytes(55_000)
- large = write_file(source, "data/large.db", payload)
- collection = analyzer.AnalysisCollection(
- status="pass",
- items=(
- analyzer.make_package_item(
- large,
- relative="workspace-current/data/large.db",
- category="evidence",
- source_id="workspace-current",
- ),
- ),
- excluded=(),
- warnings=(),
- sources=({"id": "workspace-current", "status": "pass"},),
- git=(),
- )
- result = analyzer.create_analysis_package(
- collection=collection,
- output_root=temp / "output",
- package_name="large-fixture",
- max_zip_bytes=30_000,
- target_zip_bytes=20_000,
- force=False,
- )
- package_dir = Path(result["output_dir"])
- for volume_info in result["volumes"]:
- self.assertLess((package_dir / volume_info["file"]).stat().st_size, 30_000)
- index = json.loads((package_dir / "HANDOFF-INDEX.json").read_text(encoding="utf-8"))
- self.assertEqual(len(index["large_files"]), 1)
- large_info = index["large_files"][0]
- self.assertEqual(large_info["path"], "workspace-current/data/large.db")
- self.assertEqual(large_info["sha256"], hashlib.sha256(payload).hexdigest())
- self.assertGreaterEqual(len(large_info["chunks"]), 2)
- reassembler = package_dir / "reassemble_large_files.py"
- self.assertTrue(reassembler.is_file())
- reconstructed = temp / "reconstructed"
- completed = subprocess.run(
- [
- sys.executable,
- str(reassembler),
- "--package-dir",
- str(package_dir),
- "--output-dir",
- str(reconstructed),
- ],
- capture_output=True,
- text=True,
- check=False,
- )
- self.assertEqual(completed.returncode, 0, completed.stdout + completed.stderr)
- rebuilt = reconstructed / "workspace-current" / "data" / "large.db"
- self.assertEqual(rebuilt.read_bytes(), payload)
- def test_create_analysis_package_restores_previous_directory_when_publication_fails(self) -> None:
- analyzer = load_analyzer(self)
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- source = temp / "source"
- item = write_file(source, "data/file.bin", b"replacement")
- output_root = temp / "output"
- final_dir = output_root / "atomic-fixture"
- final_dir.mkdir(parents=True)
- marker = write_file(final_dir, "old-marker.txt", b"old package")
- collection = analyzer.AnalysisCollection(
- status="pass",
- items=(
- analyzer.make_package_item(
- item,
- relative="workspace-current/data/file.bin",
- category="core",
- source_id="workspace-current",
- ),
- ),
- excluded=(),
- warnings=(),
- sources=({"id": "workspace-current", "status": "pass"},),
- git=(),
- )
- real_replace = analyzer.os.replace
- def fail_new_directory(source_path: object, target_path: object) -> None:
- source_name = Path(source_path).name
- if (
- source_name != "atomic-fixture"
- and not source_name.endswith(".backup")
- and Path(target_path).name == "atomic-fixture"
- ):
- raise OSError("injected publication failure")
- real_replace(source_path, target_path)
- with mock.patch.object(analyzer.os, "replace", side_effect=fail_new_directory):
- with self.assertRaisesRegex(analyzer.PackagingError, "publish"):
- analyzer.create_analysis_package(
- collection=collection,
- output_root=output_root,
- package_name="atomic-fixture",
- max_zip_bytes=1_000_000,
- target_zip_bytes=800_000,
- force=True,
- )
- self.assertEqual(marker.read_bytes(), b"old package")
- self.assertEqual(
- [path.name for path in output_root.iterdir()],
- ["atomic-fixture"],
- )
- def test_create_analysis_package_keeps_previous_directory_when_backup_move_fails(self) -> None:
- analyzer = load_analyzer(self)
- with tempfile.TemporaryDirectory() as tmp:
- temp = Path(tmp)
- source = temp / "source"
- item = write_file(source, "data/file.bin", b"replacement")
- output_root = temp / "output"
- final_dir = output_root / "backup-failure-fixture"
- final_dir.mkdir(parents=True)
- marker = write_file(final_dir, "old-marker.txt", b"old package")
- collection = analyzer.AnalysisCollection(
- status="pass",
- items=(
- analyzer.make_package_item(
- item,
- relative="workspace-current/data/file.bin",
- category="core",
- source_id="workspace-current",
- ),
- ),
- excluded=(),
- warnings=(),
- sources=({"id": "workspace-current", "status": "pass"},),
- git=(),
- )
- real_replace = analyzer.os.replace
- def fail_backup_move(source_path: object, target_path: object) -> None:
- if Path(source_path).name == "backup-failure-fixture":
- raise OSError("injected backup move failure")
- real_replace(source_path, target_path)
- with mock.patch.object(analyzer.os, "replace", side_effect=fail_backup_move):
- with self.assertRaisesRegex(analyzer.PackagingError, "publish"):
- analyzer.create_analysis_package(
- collection=collection,
- output_root=output_root,
- package_name="backup-failure-fixture",
- max_zip_bytes=1_000_000,
- target_zip_bytes=800_000,
- force=True,
- )
- self.assertEqual(marker.read_bytes(), b"old package")
- self.assertEqual(
- [path.name for path in output_root.iterdir()],
- ["backup-failure-fixture"],
- )
- if __name__ == "__main__":
- unittest.main()
|