Files
cutdex/tool/windows/test_native_cache_unit.py
T
lingjhf 8d1cfb5560
Gitea CI / Check code and tests (pull_request) Successful in 8m8s
Gitea CI / Build Windows x64 app (pull_request) Successful in 2m9s
Gitea CI / Audit and package Windows x64 (pull_request) Successful in 1m5s
Gitea CI / Build Android APK (pull_request) Successful in 3m4s
Gitea CI / Assemble and validate CI artifacts (pull_request) Successful in 51s
Gitea CI / Gitea CI passed (pull_request) Successful in 2s
perf(ci): cache verified Velopack native archives
2026-10-07 00:20:44 +08:00

214 lines
11 KiB
Python

from concurrent.futures import ThreadPoolExecutor
import hashlib
import io
from pathlib import Path
import tempfile
import threading
import subprocess
import sys
import time
import unittest
from unittest.mock import patch
from urllib.error import HTTPError, URLError
import native_cache as cache
class NativeCacheTests(unittest.TestCase):
def setUp(self):
self.temporary = tempfile.TemporaryDirectory()
self.addCleanup(self.temporary.cleanup)
self.root = Path(self.temporary.name)
self.payload = b'Velopack archive bytes'
self.archive = cache.Archive('1.2.161', hashlib.sha256(self.payload).hexdigest())
def download(self, url, destination):
self.assertEqual(url, self.archive.url)
destination.write_bytes(self.payload)
def test_cold_fill_and_warm_hit_do_not_repeat_download(self):
with patch.object(cache, 'download_archive', side_effect=self.download) as download:
path = cache.ensure_archive(self.archive, self.root)
self.assertEqual(cache.ensure_archive(self.archive, self.root), path)
self.assertEqual(download.call_count, 1)
self.assertEqual(path.read_bytes(), self.payload)
self.assertFalse(list(self.root.glob('*.part')))
def test_every_hit_is_checked_and_tampered_bytes_are_replaced(self):
with patch.object(cache, 'download_archive', side_effect=self.download) as download:
path = cache.ensure_archive(self.archive, self.root)
path.write_bytes(b'corrupt')
cache.ensure_archive(self.archive, self.root)
self.assertEqual(download.call_count, 2)
self.assertEqual(path.read_bytes(), self.payload)
def test_failed_integrity_check_never_publishes_or_removes_existing_file(self):
destination = self.root / self.archive.name
destination.write_bytes(b'old corrupt file')
def invalid_download(url, temporary):
temporary.write_bytes(b'wrong payload')
self.assertEqual(destination.read_bytes(), b'old corrupt file')
with patch.object(cache, 'download_archive', side_effect=invalid_download):
with self.assertRaisesRegex(ValueError, 'SHA256 differs'):
cache.ensure_archive(self.archive, self.root)
self.assertEqual(destination.read_bytes(), b'old corrupt file')
self.assertFalse(list(self.root.glob('*.part')))
def test_download_failure_cleans_its_partial_file(self):
def failed_download(url, temporary):
temporary.write_bytes(b'partial')
raise RuntimeError('network failure')
with patch.object(cache, 'download_archive', side_effect=failed_download):
with self.assertRaisesRegex(RuntimeError, 'network failure'):
cache.ensure_archive(self.archive, self.root)
self.assertFalse((self.root / self.archive.name).exists())
self.assertFalse(list(self.root.glob('*.part')))
def test_cancelled_run_partial_files_cannot_be_cache_hits(self):
stale = self.root / (self.archive.name + '.cancelled.part')
stale.write_bytes(b'incomplete')
with patch.object(cache, 'download_archive', side_effect=self.download) as download:
cache.ensure_archive(self.archive, self.root)
download.assert_called_once()
self.assertEqual(stale.read_bytes(), b'incomplete')
def test_version_and_digest_both_isolate_cache_entries(self):
upgraded = cache.Archive('1.2.162', self.archive.sha256)
republished = cache.Archive('1.2.161', 'a' * 64)
self.assertEqual(len({self.archive.name, upgraded.name, republished.name}), 3)
def test_parallel_fills_share_one_verified_download(self):
entered, release = threading.Event(), threading.Event()
def slow_download(url, temporary):
entered.set()
if not release.wait(5):
raise RuntimeError('test download was not released')
self.download(url, temporary)
with patch.object(cache, 'download_archive', side_effect=slow_download) as download:
with ThreadPoolExecutor(max_workers=2) as workers:
first = workers.submit(cache.ensure_archive, self.archive, self.root)
self.assertTrue(entered.wait(5))
second = workers.submit(cache.ensure_archive, self.archive, self.root)
release.set()
self.assertEqual(first.result(timeout=5), second.result(timeout=5))
self.assertEqual(download.call_count, 1)
def test_lock_timeout_and_exception_release(self):
lock = self.root / 'archive.lock'
with cache.archive_lock(lock):
with self.assertRaisesRegex(RuntimeError, 'cache lock'):
with cache.archive_lock(lock, timeout=0):
self.fail('acquired an already held lock')
with self.assertRaisesRegex(ValueError, 'abort'):
with cache.archive_lock(lock):
raise ValueError('abort')
with cache.archive_lock(lock, timeout=0):
pass
def test_offline_archive_is_verified_and_populates_persistent_cache(self):
source = self.root / 'offline.zip'
source.write_bytes(self.payload)
with patch.object(cache, 'download_archive') as download:
result = cache.ensure_archive(self.archive, self.root / 'persistent', source)
download.assert_not_called()
self.assertNotEqual(result, source)
self.assertEqual(result.read_bytes(), self.payload)
def test_cancelled_process_releases_the_cache_lock(self):
lock, marker = self.root / 'archive.lock', self.root / 'locked'
program = ('import native_cache, sys; from pathlib import Path; '
'\nwith native_cache.archive_lock(Path(sys.argv[1])):'
'\n Path(sys.argv[2]).write_text("locked")'
'\n sys.stdin.read()')
process = subprocess.Popen([sys.executable, '-c', program, str(lock), str(marker)],
cwd=Path(__file__).parent, stdin=subprocess.PIPE,
stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
try:
deadline = time.monotonic() + 5
while not marker.exists() and process.poll() is None and time.monotonic() < deadline:
time.sleep(0.01)
self.assertTrue(marker.exists(), 'test process failed to acquire its lock')
process.terminate()
process.wait(timeout=5)
with cache.archive_lock(lock, timeout=0):
pass
finally:
if process.poll() is None:
process.terminate()
process.communicate(timeout=5)
def test_bad_explicit_archive_cannot_be_hidden_by_a_good_cache_hit(self):
(self.root / self.archive.name).write_bytes(self.payload)
source = self.root / 'bad.zip'
source.write_bytes(b'bad')
with patch.object(cache, 'download_archive') as download:
with self.assertRaisesRegex(ValueError, 'DESKUP_VELOPACK_ARCHIVE'):
cache.ensure_archive(self.archive, self.root, source)
download.assert_not_called()
def test_manifest_is_read_from_resolved_sdk_without_a_second_version_pin(self):
windows = self.root / 'windows'
windows.mkdir()
manifest = windows / 'velopack.cmake'
manifest.write_text('set(DESKUP_VELOPACK_VERSION "1.2.162")\n'
f'URL_HASH SHA256={self.archive.sha256.upper()}\n'
'file(TO_CMAKE_PATH "$ENV{DESKUP_VELOPACK_ARCHIVE}" local)\n')
self.assertEqual(cache.resolved_archive(self.root), cache.Archive('1.2.162', self.archive.sha256))
for text in ('set(DESKUP_VELOPACK_VERSION "../unsafe")', 'URL_HASH SHA256=bad', ''):
manifest.write_text(text)
with self.assertRaisesRegex(ValueError, 'must pin'):
cache.resolved_archive(self.root)
def test_temporary_network_errors_retry_with_a_fresh_download_file(self):
destination = self.root / 'download.part'
destination.write_bytes(b'previous attempt')
with patch.object(cache, 'urlopen', side_effect=[URLError('temporary'), io.BytesIO(self.payload)]) as request:
with patch.object(cache.time, 'sleep'):
cache.download_archive(self.archive.url, destination)
self.assertEqual(request.call_count, 2)
self.assertEqual(destination.read_bytes(), self.payload)
def test_network_retries_are_bounded_and_permanent_errors_fail_immediately(self):
for error, count in [(URLError('unavailable'), 3),
(HTTPError(self.archive.url, 404, 'missing', {}, None), 1),
(HTTPError(self.archive.url, 503, 'busy', {}, None), 3)]:
with self.subTest(count=count):
with patch.object(cache, 'urlopen', side_effect=error) as request:
with patch.object(cache.time, 'sleep'), self.assertRaises(RuntimeError):
cache.download_archive(self.archive.url, self.root / 'download.part')
self.assertEqual(request.call_count, count)
def test_interrupted_response_is_retried_without_preserving_partial_bytes(self):
class Interrupted(io.BytesIO):
def read(self, size=-1):
if self.tell():
raise TimeoutError('interrupted response')
return super().read(size)
destination = self.root / 'download.part'
with patch.object(cache, 'urlopen', side_effect=[Interrupted(b'partial'), io.BytesIO(self.payload)]):
with patch.object(cache.time, 'sleep'):
cache.download_archive(self.archive.url, destination)
self.assertEqual(destination.read_bytes(), self.payload)
def test_exports_only_a_verified_archive_for_subsequent_ci_steps(self):
output = self.root / 'github-env'
output.write_text('EXISTING=value\n')
environment = {'GITHUB_ENV': str(output), 'LOCALAPPDATA': str(self.root)}
with patch.object(cache, 'resolved_archive', return_value=self.archive):
with patch.object(cache, 'download_archive', side_effect=self.download):
archive = cache.prepare(environment=environment)
self.assertEqual(output.read_text(), f'EXISTING=value\nDESKUP_VELOPACK_ARCHIVE={archive.as_posix()}\n')
self.assertEqual(archive.parent, self.root / 'Cutdex/ci-tools/native')
def test_failed_verification_cannot_export_an_archive(self):
output = self.root / 'github-env'
with patch.object(cache, 'resolved_archive', return_value=self.archive):
with patch.object(cache, 'download_archive', side_effect=lambda url, path: path.write_bytes(b'wrong')):
with self.assertRaises(ValueError):
cache.prepare(self.root, {'GITHUB_ENV': str(output)})
self.assertFalse(output.exists())
if __name__ == '__main__':
unittest.main()