Download tools/test_inventory_binding.py from maxwellinked/time-lapse-artifacts: direct link, hf CLI and curl.
- Browser
- Download file 13.8 kB
-
https://huggingface.co/datasets/maxwellinked/time-lapse-artifacts/resolve/main/tools/test_inventory_binding.py
- Command line
-
hf download hf://datasets/maxwellinked/time-lapse-artifacts/tools/test_inventory_binding.py
-
curl -L -o test_inventory_binding.py https://huggingface.co/datasets/maxwellinked/time-lapse-artifacts/resolve/main/tools/test_inventory_binding.py
13.8 kB
| #!/usr/bin/env python3 | |
| """Self-contained tests for exact-revision validation-file binding.""" | |
| from __future__ import annotations | |
| import csv | |
| import hashlib | |
| import importlib.util | |
| import json | |
| import subprocess | |
| import sys | |
| import tempfile | |
| import threading | |
| import unittest | |
| from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer | |
| from pathlib import Path | |
| from types import ModuleType | |
| TOOLS = Path(__file__).resolve().parent | |
| REVISION = "a" * 40 | |
| OTHER_REVISION = "b" * 40 | |
| PAYLOAD = b"file_name,record_id\nexample.mp4,tla-0123456789abcdef\n" | |
| def load_module(name: str, path: Path) -> ModuleType: | |
| spec = importlib.util.spec_from_file_location(name, path) | |
| if spec is None or spec.loader is None: | |
| raise RuntimeError(f"unable to load {path}") | |
| module = importlib.util.module_from_spec(spec) | |
| spec.loader.exec_module(module) | |
| return module | |
| capture = load_module("capture_hub_inventory", TOOLS / "capture_hub_inventory.py") | |
| relationships = load_module( | |
| "validate_fragment_relationships", | |
| TOOLS / "validate_fragment_relationships.py", | |
| ) | |
| class FixtureHandler(BaseHTTPRequestHandler): | |
| protocol_version = "HTTP/1.1" | |
| def do_GET(self) -> None: # noqa: N802 | |
| if self.headers.get("Accept-Encoding") != "identity": | |
| self.send_error(400, "identity content encoding required") | |
| return | |
| if self.path == "/resolve": | |
| self.send_response(302) | |
| self.send_header("Location", f"http://127.0.0.1:{self.server.server_port}/payload") | |
| self.send_header("X-Repo-Commit", REVISION) | |
| self.send_header("Content-Length", "0") | |
| self.end_headers() | |
| return | |
| if self.path == "/wrong-commit": | |
| self.send_response(200) | |
| self.send_header("X-Repo-Commit", OTHER_REVISION) | |
| self.send_header("Content-Length", str(len(PAYLOAD))) | |
| self.end_headers() | |
| self.wfile.write(PAYLOAD) | |
| return | |
| if self.path == "/payload": | |
| self.send_response(200) | |
| self.send_header("Content-Encoding", "identity") | |
| self.send_header("Content-Length", str(len(PAYLOAD))) | |
| self.end_headers() | |
| self.wfile.write(PAYLOAD) | |
| return | |
| self.send_error(404) | |
| def log_message(self, format: str, *args: object) -> None: | |
| del format, args | |
| class InventoryBindingTests(unittest.TestCase): | |
| def setUpClass(cls) -> None: | |
| cls.server = ThreadingHTTPServer(("127.0.0.1", 0), FixtureHandler) | |
| cls.thread = threading.Thread(target=cls.server.serve_forever, daemon=True) | |
| cls.thread.start() | |
| cls.base_url = f"http://127.0.0.1:{cls.server.server_port}" | |
| def tearDownClass(cls) -> None: | |
| cls.server.shutdown() | |
| cls.server.server_close() | |
| cls.thread.join(timeout=5) | |
| def test_capture_records_exact_byte_receipt_across_redirect(self) -> None: | |
| receipt = capture.read_validation_file( | |
| f"{self.base_url}/resolve", | |
| REVISION, | |
| timeout=5, | |
| retries=0, | |
| max_bytes=1024, | |
| ) | |
| self.assertEqual(set(receipt), {"sha256", "size", "repoCommit"}) | |
| self.assertEqual(receipt["size"], len(PAYLOAD)) | |
| self.assertEqual(receipt["repoCommit"], REVISION) | |
| def test_capture_rejects_wrong_commit_and_oversize_body(self) -> None: | |
| with self.assertRaises(RuntimeError): | |
| capture.read_validation_file( | |
| f"{self.base_url}/wrong-commit", | |
| REVISION, | |
| timeout=5, | |
| retries=0, | |
| max_bytes=1024, | |
| ) | |
| with self.assertRaises(RuntimeError): | |
| capture.read_validation_file( | |
| f"{self.base_url}/resolve", | |
| REVISION, | |
| timeout=5, | |
| retries=0, | |
| max_bytes=len(PAYLOAD) - 1, | |
| ) | |
| def test_validator_requires_matching_hash_size_and_commit(self) -> None: | |
| receipt = capture.read_validation_file( | |
| f"{self.base_url}/resolve", | |
| REVISION, | |
| timeout=5, | |
| retries=0, | |
| max_bytes=1024, | |
| ) | |
| inventory = {"validationFiles": {"metadata.csv": receipt}} | |
| with tempfile.TemporaryDirectory(prefix="tla-binding-test-") as temp_dir: | |
| metadata = Path(temp_dir) / "metadata.csv" | |
| metadata.write_bytes(PAYLOAD) | |
| errors: list[str] = [] | |
| relationships.validate_pinned_metadata( | |
| inventory, | |
| metadata, | |
| REVISION, | |
| errors, | |
| ) | |
| self.assertEqual(errors, []) | |
| metadata.write_bytes(PAYLOAD + b"tampered") | |
| errors = [] | |
| relationships.validate_pinned_metadata( | |
| inventory, | |
| metadata, | |
| REVISION, | |
| errors, | |
| ) | |
| self.assertTrue(any("differs" in error for error in errors)) | |
| errors = [] | |
| relationships.validate_pinned_metadata( | |
| inventory, | |
| metadata, | |
| OTHER_REVISION, | |
| errors, | |
| ) | |
| self.assertTrue(any("source_hub_revision" in error for error in errors)) | |
| def test_validator_requires_top_level_inventory_revision(self) -> None: | |
| errors: list[str] = [] | |
| relationships.validate_inventory_revision( | |
| {"sha": REVISION}, | |
| REVISION, | |
| errors, | |
| ) | |
| self.assertEqual(errors, []) | |
| relationships.validate_inventory_revision( | |
| {"sha": OTHER_REVISION}, | |
| REVISION, | |
| errors, | |
| ) | |
| self.assertTrue(any("inventory commit" in error for error in errors)) | |
| def test_full_relationship_validator_accepts_only_bound_metadata(self) -> None: | |
| metadata_fields = ["file_name", "record_id", "hub_xet_hash"] | |
| metadata_rows: list[dict[str, str]] = [] | |
| relationship_rows: list[dict[str, str]] = [] | |
| canonical_by_set: dict[str, list[str]] = {} | |
| record_counter = 1 | |
| for group_index, cardinality in enumerate((2, 2, 2, 6, 10), start=1): | |
| set_label = ( | |
| f"2026-08-{20 + group_index:02d}.000{group_index}." | |
| "BallpointPen.Ink.Paper.9x12" | |
| ) | |
| canonical_by_set[set_label] = [] | |
| for position in range(1, cardinality + 1): | |
| record_id = f"tla-{record_counter:016x}" | |
| record_counter += 1 | |
| file_path = ( | |
| f"Standard_Time_Lapses/{set_label}.Rec{position:02d}.mp4" | |
| ) | |
| xet_hash = hashlib.sha256( | |
| f"fixture-xet:{file_path}".encode("utf-8") | |
| ).hexdigest() | |
| metadata_rows.append( | |
| { | |
| "file_name": file_path, | |
| "record_id": record_id, | |
| "hub_xet_hash": xet_hash, | |
| } | |
| ) | |
| canonical_by_set[set_label].append(record_id) | |
| relationship_rows.append( | |
| { | |
| "fragment_set_label": set_label, | |
| "object_role": "canonical_fragment", | |
| "record_id": record_id, | |
| "file_path": file_path, | |
| "sha256": hashlib.sha256( | |
| f"fixture-sha:{file_path}".encode("utf-8") | |
| ).hexdigest(), | |
| "hub_xet_hash": xet_hash, | |
| "size_bytes": str(1000 + record_counter), | |
| "sequence_position": str(position), | |
| "sequence_count": str(cardinality), | |
| "sequence_completeness": "owner_confirmed_complete", | |
| "source_record_ids": "", | |
| "derivative_coverage": "", | |
| "evidence_state": ( | |
| "owner-confirmed; boundary-frame-verified; " | |
| "checksum-computed; media-probed; demux-verified; " | |
| "sampled-decode-verified" | |
| ), | |
| "source_hub_revision": REVISION, | |
| "notes": "", | |
| } | |
| ) | |
| set_labels = list(canonical_by_set) | |
| derivative_specs = [ | |
| (set_labels[0], canonical_by_set[set_labels[0]], "complete_sequence"), | |
| (set_labels[1], canonical_by_set[set_labels[1]], "complete_sequence"), | |
| (set_labels[2], canonical_by_set[set_labels[2]][1:2], "partial_sequence"), | |
| (set_labels[2], canonical_by_set[set_labels[2]][1:2], "partial_sequence"), | |
| (set_labels[1], canonical_by_set[set_labels[1]], "complete_sequence"), | |
| ] | |
| for derivative_index, (set_label, source_ids, coverage) in enumerate( | |
| derivative_specs, | |
| start=1, | |
| ): | |
| file_path = ( | |
| "Standard_Time_Lapses/Provenance/2026-08-27/InShot/" | |
| f"fixture-{derivative_index}.mp4" | |
| ) | |
| relationship_rows.append( | |
| { | |
| "fragment_set_label": set_label, | |
| "object_role": "noncanonical_inshot_derivative", | |
| "record_id": "", | |
| "file_path": file_path, | |
| "sha256": hashlib.sha256( | |
| f"fixture-sha:{file_path}".encode("utf-8") | |
| ).hexdigest(), | |
| "hub_xet_hash": hashlib.sha256( | |
| f"fixture-xet:{file_path}".encode("utf-8") | |
| ).hexdigest(), | |
| "size_bytes": str(2000 + derivative_index), | |
| "sequence_position": "", | |
| "sequence_count": str(len(canonical_by_set[set_label])), | |
| "sequence_completeness": "owner_confirmed_complete", | |
| "source_record_ids": ";".join(source_ids), | |
| "derivative_coverage": coverage, | |
| "evidence_state": ( | |
| "sampled-frame-verified; duration-arithmetic-verified; " | |
| "checksum-computed; media-probed; demux-verified; " | |
| "sampled-decode-verified" | |
| ), | |
| "source_hub_revision": REVISION, | |
| "notes": "", | |
| } | |
| ) | |
| self.assertEqual(len(metadata_rows), 22) | |
| self.assertEqual(len(relationship_rows), 27) | |
| with tempfile.TemporaryDirectory(prefix="tla-validator-test-") as temp_dir: | |
| temp = Path(temp_dir) | |
| metadata_path = temp / "metadata.csv" | |
| relationships_path = temp / "relationships.csv" | |
| inventory_path = temp / "inventory.json" | |
| with metadata_path.open("w", encoding="utf-8", newline="") as handle: | |
| writer = csv.DictWriter( | |
| handle, | |
| fieldnames=metadata_fields, | |
| lineterminator="\n", | |
| ) | |
| writer.writeheader() | |
| writer.writerows(metadata_rows) | |
| with relationships_path.open("w", encoding="utf-8", newline="") as handle: | |
| writer = csv.DictWriter( | |
| handle, | |
| fieldnames=relationships.FIELDS, | |
| lineterminator="\n", | |
| ) | |
| writer.writeheader() | |
| writer.writerows(relationship_rows) | |
| metadata_bytes = metadata_path.read_bytes() | |
| inventory = { | |
| "sha": REVISION, | |
| "siblings": [ | |
| { | |
| "rfilename": row["file_path"], | |
| "size": int(row["size_bytes"]), | |
| "lfs": { | |
| "size": int(row["size_bytes"]), | |
| "sha256": row["sha256"], | |
| }, | |
| "xetHash": row["hub_xet_hash"], | |
| "repoCommit": REVISION, | |
| } | |
| for row in relationship_rows | |
| ], | |
| "validationFiles": { | |
| "metadata.csv": { | |
| "sha256": hashlib.sha256(metadata_bytes).hexdigest(), | |
| "size": len(metadata_bytes), | |
| "repoCommit": REVISION, | |
| } | |
| }, | |
| } | |
| inventory_path.write_text( | |
| json.dumps(inventory), | |
| encoding="utf-8", | |
| ) | |
| command = [ | |
| sys.executable, | |
| str(TOOLS / "validate_fragment_relationships.py"), | |
| "--relationships", | |
| str(relationships_path), | |
| "--metadata", | |
| str(metadata_path), | |
| "--repo-inventory-json", | |
| str(inventory_path), | |
| ] | |
| completed = subprocess.run( | |
| command, | |
| check=False, | |
| capture_output=True, | |
| text=True, | |
| encoding="utf-8", | |
| ) | |
| self.assertEqual(completed.returncode, 0, completed.stdout + completed.stderr) | |
| metadata_path.write_bytes(metadata_bytes + b"\n") | |
| completed = subprocess.run( | |
| command, | |
| check=False, | |
| capture_output=True, | |
| text=True, | |
| encoding="utf-8", | |
| ) | |
| self.assertNotEqual(completed.returncode, 0) | |
| self.assertIn("differs from the pinned repository", completed.stdout) | |
| if __name__ == "__main__": | |
| unittest.main() | |