import hashlib import importlib.util import io import tempfile import unittest from pathlib import Path from unittest.mock import patch PROJECT_ROOT = Path(__file__).resolve().parents[1] def load_prepare_vendor(): specification = importlib.util.spec_from_file_location( "snapform_prepare_vendor", PROJECT_ROOT / "prepare_vendor.py", ) module = importlib.util.module_from_spec(specification) specification.loader.exec_module(module) return module class PrepareVendorTest(unittest.TestCase): def test_downloads_and_verifies_artifact(self): prepare = load_prepare_vendor() content = b"locked artifact" artifact = { "filename": "artifact.tar.gz", "url": "https://example.invalid/artifact.tar.gz", "sha256": hashlib.sha256(content).hexdigest(), } with tempfile.TemporaryDirectory() as directory, patch.object( prepare.urllib.request, "urlopen", return_value=io.BytesIO(content), ): path = prepare.download_artifact(artifact, Path(directory)) self.assertEqual(path.read_bytes(), content) def test_rejects_hash_mismatch_without_leaving_partial_file(self): prepare = load_prepare_vendor() artifact = { "filename": "artifact.tar.gz", "url": "https://example.invalid/artifact.tar.gz", "sha256": hashlib.sha256(b"expected").hexdigest(), } with tempfile.TemporaryDirectory() as directory, patch.object( prepare.urllib.request, "urlopen", return_value=io.BytesIO(b"unexpected"), ): destination = Path(directory) with self.assertRaisesRegex(RuntimeError, "SHA-256 mismatch"): prepare.download_artifact(artifact, destination) self.assertFalse((destination / artifact["filename"]).exists()) self.assertFalse( (destination / f"{artifact['filename']}.part").exists() ) def test_rejects_unknown_platform(self): prepare = load_prepare_vendor() with self.assertRaisesRegex(ValueError, "Unsupported platform"): prepare.prepare(["windows-arm64"]) if __name__ == "__main__": unittest.main()