Cotton code
84 lines · 4.5 KB · PythonRaw
"""Guards for bounded, resumable preparation of shared packages."""import hashlibfrom pathlib import Pathimport tempfileimport unittestfrom unittest.mock import patchimport packagesclass CachePreparation(unittest.TestCase):    def test_interrupted_prepare_resumes_verified_prefix_across_invocations(self):        # RULE: Preparation retains completed ranges across failures but publishes only the complete pinned package, so an aborted relay download never poisons a cut.        with tempfile.TemporaryDirectory() as tmp, patch.object(packages, 'CHUNK_BYTES', 3):            root = Path(tmp)            dest = root / 'places.sqlite'            digest = hashlib.sha256(b'abcdef').hexdigest()            starts = []            def interrupted(repo, url, chunk, start, end, timeout):                starts.append(start)                if start:                    raise OSError('synthetic interrupted relay')                chunk.write_bytes(b'abc')                return 6            with self.assertRaisesRegex(RuntimeError, 'range attempts failed'):                packages.acquire(root, '/asset', dest, digest, fetch=interrupted)            self.assertFalse(dest.exists())            self.assertEqual(dest.with_suffix('.sqlite.part').read_bytes(), b'abc')            self.assertEqual(starts, [0, 3, 3, 3])            def resumed(repo, url, chunk, start, end, timeout):                self.assertEqual(start, 3)                self.assertLessEqual(timeout, 45)                chunk.write_bytes(b'def')                return 6            packages.acquire(root, '/asset', dest, digest, fetch=resumed)            self.assertEqual(dest.read_bytes(), b'abcdef')            self.assertFalse(dest.with_suffix('.sqlite.part').exists())    def test_changed_bytes_and_exhausted_deadline_never_publish(self):        # RULE: Cache preparation is bounded in time and size and refuses wrong bytes; a cache filename alone cannot authenticate a release asset.        with tempfile.TemporaryDirectory() as tmp:            root = Path(tmp)            dest = root / 'places.sqlite'            digest = hashlib.sha256(b'good').hexdigest()            def changed(repo, url, chunk, start, end, timeout):                chunk.write_bytes(b'evil')                return 4            with self.assertRaisesRegex(RuntimeError, 'SHA-256'):                packages.acquire(root, '/asset', dest, digest, fetch=changed)            self.assertFalse(dest.exists())            self.assertFalse(dest.with_suffix('.sqlite.part').exists())            with self.assertRaises(TimeoutError):                packages.acquire(root, '/asset', dest, digest, fetch=changed, deadline=0)            self.assertFalse(dest.exists())    def test_prepare_imports_verified_existing_packages_and_reuses_the_shared_cache(self):        # RULE: A package already held locally fills the shared SHA cache without fetching; later cuts and preparation jobs reuse the same authenticated bytes.        with tempfile.TemporaryDirectory() as tmp:            root = Path(tmp)            local = root / 'local'            local.mkdir()            (local / 'places.sqlite').write_bytes(b'good')            digest = hashlib.sha256(b'good').hexdigest()            pins = {'places': {'package_sha256': digest}}            with patch.object(packages, 'acquire', side_effect=AssertionError('no host')):                packages.prepare(root, root / 'shared', ['places'], pins, local)                (local / 'places.sqlite').unlink()                packages.prepare(root, root / 'shared', ['places'], pins, local)            self.assertEqual(packages.asset_path(root / 'shared', 'places', pins['places']).read_bytes(), b'good')    def test_explicit_preparation_refuses_corrupt_cached_bytes(self):        # RULE: Explicit preparation cannot replace an existing package whose SHA disagrees with its namespace, so corruption is always visible.        with tempfile.TemporaryDirectory() as tmp:            root = Path(tmp)            digest = hashlib.sha256(b'good').hexdigest()            pins = {'places': {'package_sha256': digest}}            cache = root / 'shared'            asset = packages.asset_path(cache, 'places', pins['places'])            asset.parent.mkdir(parents=True)            asset.write_bytes(b'bad')            with patch.object(packages, 'acquire', side_effect=AssertionError('no fetch')):                with self.assertRaisesRegex(ValueError, 'SHA-256 mismatch'):                    packages.prepare(root, cache, ['places'], pins, root / 'local')            self.assertEqual(asset.read_bytes(), b'bad')