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 repair_windows_update_check as fix ORIGINAL_SHA = fix.OLD_SHA class UpdateCheckRepairTest(unittest.TestCase): def setUp(self): self.temp = tempfile.TemporaryDirectory(prefix='quality source path repair ') self.addCleanup(self.temp.cleanup) self.root = Path(self.temp.name) / '中文 QualityCenter & files' self.root.mkdir() self.original = b'original source fixture\n' self.old_sha = hashlib.sha256(self.original).hexdigest() self.guard = patch.object(fix, 'OLD_SHA', self.old_sha) self.guard.start() self.addCleanup(self.guard.stop) for name, value in {fix.SCRIPT: self.original, 'deploy/bootstrap/windows-start.ps1': b'original bootstrap', 'migration/database.sql.gz': b'existing migration payload', '.runtime/deployment.json': b'original private configuration', 'runtimedata/mysql/retained-database': b'imported database data'}.items(): target = self.root / name target.parent.mkdir(parents=True, exist_ok=True) target.write_bytes(value) self.manifest = {'platform': 'windows', 'updateVersion': '2026.11.04.1', 'updateSequence': 1, 'runtimeFingerprint': 'unchanged', 'otherMetadata': {'keep': True}, 'files': [{'path': fix.SCRIPT, 'sha256': self.old_sha}, {'path': 'deploy/bootstrap/windows-start.ps1', 'sha256': 'unchanged'}]} self.manifest_path = self.root / 'manifest.json' self.manifest_path.write_text(json.dumps(self.manifest), encoding='utf-8') def test_backup_manifest_and_script_only_preserving_database_and_configuration(self): private = {name: (self.root / name).read_bytes() for name in ['migration/database.sql.gz', '.runtime/deployment.json', 'runtimedata/mysql/retained-database']} result = fix.repair(self.root) self.assertTrue(result['updateCheckRepaired']) self.assertEqual((self.root / fix.SCRIPT).read_bytes(), fix.PATCHED_SCRIPT) expected = json.loads(json.dumps(self.manifest)) expected['files'][0]['sha256'] = fix.NEW_SHA self.assertEqual(json.loads(self.manifest_path.read_text()), expected) backup = self.root / result['backup'] self.assertEqual((backup / 'update_manager.py').read_bytes(), self.original) self.assertEqual(json.loads((backup / 'manifest.json').read_text()), self.manifest) for name, value in private.items(): self.assertEqual((self.root / name).read_bytes(), value) self.assertTrue(fix.repair(self.root)['alreadyRepaired']) def test_modified_script_or_manifest_is_not_approved_as_a_repair(self): before = self.manifest_path.read_bytes() (self.root / fix.SCRIPT).write_bytes(b'unrecognized source') with self.assertRaisesRegex(RuntimeError, '版本'): fix.repair(self.root) self.assertEqual(self.manifest_path.read_bytes(), before) def test_failed_second_write_restores_original_program_and_manifest(self): before = self.manifest_path.read_bytes() original_atomic = fix.atomic calls = [] def failing(path, data): calls.append(path) if len(calls) == 2: raise OSError('simulated manifest write failure') original_atomic(path, data) with patch.object(fix, 'atomic', side_effect=failing), self.assertRaises(OSError): fix.repair(self.root) self.assertEqual((self.root / fix.SCRIPT).read_bytes(), self.original) self.assertEqual(self.manifest_path.read_bytes(), before) def test_retry_completes_an_interrupted_script_manifest_pair(self): (self.root / fix.SCRIPT).write_bytes(fix.PATCHED_SCRIPT) fix.repair(self.root) self.assertEqual(json.loads(self.manifest_path.read_text())['files'][0]['sha256'], fix.NEW_SHA) def test_cmd_payload_runs_with_bundled_standard_library_without_service_restart(self): # 真实原包脚本由交付包集成验证;此单元测试使用受控旧源码摘要。 command = self.root / '修复更新检查.cmd' body = fix.command_file().decode('utf-8').replace(ORIGINAL_SHA, self.old_sha) command.write_bytes(body.encode('utf-8')) code = body.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.assertEqual((self.root / fix.SCRIPT).read_bytes(), fix.PATCHED_SCRIPT) self.assertNotIn('powershell.exe', body) self.assertIn('无需停止服务或重新导入数据库', body) def test_active_update_lock_blocks_patching(self): before = self.manifest_path.read_bytes() with fix.update_lock(self.root), self.assertRaisesRegex(RuntimeError, '仍在运行'): fix.repair(self.root) self.assertEqual(self.manifest_path.read_bytes(), before) def test_worker_or_unfinished_journal_blocks_repair(self): for name, data in [('worker.json', {}), ('journal.json', {'phase': 'installing'})]: path = self.root / '.runtime/update' / name path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(data)) with self.assertRaises(RuntimeError): fix.repair(self.root) self.assertEqual((self.root / fix.SCRIPT).read_bytes(), self.original) path.unlink() def test_previous_check_repair_version_can_upgrade_without_losing_manifest_fields(self): prior = b'previous optimized checker fixture' digest = hashlib.sha256(prior).hexdigest() (self.root / fix.SCRIPT).write_bytes(prior) value = json.loads(self.manifest_path.read_text()) value['files'][0]['sha256'] = digest self.manifest_path.write_text(json.dumps(value)) with patch.object(fix, 'PREVIOUS_SHA', digest): self.assertTrue(fix.repair(self.root)['updateCheckRepaired']) self.assertEqual(fix.PATCHED_SCRIPT, (self.root / fix.SCRIPT).read_bytes()) def test_embedded_program_matches_reviewed_source(self): self.assertEqual(fix.PATCHED_SCRIPT, (HERE / 'update_manager.py').read_bytes()) if __name__ == '__main__': unittest.main()