修复:Windows 离线启动误校验 Python 可再生缓存,提供原地修复工具

This commit is contained in:
2026-11-05 11:05:37 +08:00
parent 7357c309dd
commit c2410c4ce1
5 changed files with 276 additions and 1 deletions
+119
View File
@@ -0,0 +1,119 @@
import hashlib
import json
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
from unittest.mock import patch
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import control
import repair_windows_cache as fix
from build_bundle import strip_runtime_bytecode
class WindowsCacheRepairTest(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory(prefix='quality cache repair ')
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name) / '中文 QualityCenter & files'
self.root.mkdir()
self.source = 'runtimes/python/Lib/__future__.py'
self.cache = 'runtimes/python/Lib/__pycache__/__future__.cpython-311.pyc'
self.program = {
self.source: b'"""Original Python standard library source."""\n',
self.cache: b'original-bytecode',
'app/backend.jar': b'original-program',
'deploy/bootstrap/windows-start.ps1': b'original-bootstrap',
'migration/database.sql.gz': b'original-business-migration',
}
for name, data in self.program.items():
path = self.root / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(data)
self.manifest = {'platform': 'windows', 'updateVersion': '2026.11.04.1',
'runtimes': [{'name': 'python', 'sha256': 'original-runtime'}],
'files': [{'path': name, 'sha256': hashlib.sha256(data).hexdigest()} for name, data in self.program.items()]}
self.manifest_path = self.root / 'manifest.json'
self.manifest_path.write_text(json.dumps(self.manifest), encoding='utf-8')
self.data = {'.runtime/deployment.json': b'local-private-configuration',
'.runtime/migration-progress.json': b'original-migration-progress',
'runtimedata/mysql/business-file': b'windows-existing-data'}
for name, data in self.data.items():
path = self.root / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(data)
def verify(self):
with patch.object(control, 'ROOT', self.root), patch.object(control, 'IS_WINDOWS', True), \
patch.object(control.platform, 'machine', return_value='AMD64'), \
patch.object(control, 'configuration', return_value={}), \
patch.object(control, 'environment', return_value={'QUALITY_ASSISTANT_PACKAGE': str(self.root / 'fake-native')}), \
patch.object(control.subprocess, 'run', return_value=subprocess.CompletedProcess([], 0)):
control.verify()
def test_actual_startup_hash_check_fails_on_regenerated_cache_then_passes_after_repair(self):
(self.root / self.cache).write_bytes(b'new-bytecode-created-on-windows')
with self.assertRaisesRegex(RuntimeError, '__future__.*pyc'):
self.verify()
result = fix.repair(self.root)
self.assertEqual(result['cacheEntriesRemoved'], 1)
self.verify()
after = json.loads(self.manifest_path.read_text(encoding='utf-8'))
self.assertEqual(after, {**self.manifest, 'files': [item for item in self.manifest['files'] if item['path'] != self.cache]})
self.assertEqual(json.loads((self.root / result['manifestBackup']).read_text()), self.manifest)
for name, data in {**self.program, **self.data}.items():
if name != self.cache:
self.assertEqual((self.root / name).read_bytes(), data, name)
self.assertTrue(fix.repair(self.root)['alreadyRepaired'])
(self.root / 'app/backend.jar').write_bytes(b'corrupted-program')
with self.assertRaisesRegex(RuntimeError, 'backend.jar'):
self.verify()
def test_real_source_damage_is_not_converted_into_a_successful_repair(self):
(self.root / self.source).write_bytes(b'changed-source')
original = self.manifest_path.read_bytes()
with self.assertRaisesRegex(RuntimeError, '对应源码'):
fix.repair(self.root)
self.assertEqual(original, self.manifest_path.read_bytes())
self.assertTrue((self.root / self.cache).is_file())
self.assertFalse((self.root / '.runtime/cache-repair-backups').exists())
def test_missing_cache_is_regenerable_but_source_is_still_required(self):
(self.root / self.cache).unlink()
self.assertEqual(fix.repair(self.root)['cacheFilesRemoved'], 0)
self.verify()
def test_single_click_file_executes_the_same_repair_with_only_bundled_python_stdlib(self):
command = self.root / '修复缓存校验并启动.cmd'
command.write_bytes(fix.command_file())
content = command.read_text(encoding='utf-8')
code = content.split(' -c "', 1)[1].split('" "%~f0"', 1)[0]
result = subprocess.run([sys.executable, '-I', '-S', '-B', '-X', 'utf8', '-c', code, str(command)], capture_output=True, text=True)
self.assertEqual(result.returncode, 0, result.stderr)
self.verify()
self.assertIn('set "PYTHONDONTWRITEBYTECODE=1"', content)
self.assertIn('deploy\\bootstrap\\windows-start.ps1', content)
def test_only_regenerable_runtime_caches_are_eligible(self):
self.assertEqual(fix.cache_source(self.cache), self.source)
self.assertEqual(fix.cache_source(self.cache.replace('.pyc', '.opt-1.pyc')), self.source)
for name in ['runtimedata/__pycache__/data.cpython-311.pyc', 'scripts/code.py',
'runtimes/python/../data/__pycache__/x.cpython-311.pyc',
'runtimes/python/Lib/__pycache__/unknown.pyc']:
self.assertIsNone(fix.cache_source(name), name)
def test_future_bundles_exclude_bytecode_and_keep_source(self):
strip_runtime_bytecode(self.root)
self.assertFalse((self.root / self.cache).exists())
self.assertEqual((self.root / self.source).read_bytes(), self.program[self.source])
(self.root / self.cache).write_bytes(b'bytecode')
(self.root / self.source).unlink()
with self.assertRaisesRegex(RuntimeError, '缺少对应源码'):
strip_runtime_bytecode(self.root)
if __name__ == '__main__':
unittest.main()