ruen-ui/tests/test_installers.py

217 lines
12 KiB
Python
Raw Normal View History

"""Offline installer transactions. Set RUEN_PWSH to also exercise PowerShell.
These fixtures do not establish native Windows GUI/PowerShell 5.1 compatibility.
Run: PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s tests -v
"""
import hashlib
import importlib.machinery
import importlib.util
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
import types
import unittest
from unittest.mock import patch
import zipfile
sys.dont_write_bytecode = True
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'Tools'))
sys.path.insert(0, str(ROOT / 'scripts'))
import ruen_dependencies as deps
import build_release
def load_setup(bundle):
loader = importlib.machinery.SourceFileLoader('ruen_setup', str(bundle / 'Ruen-Setup'))
spec = importlib.util.spec_from_loader(loader.name, loader)
module = importlib.util.module_from_spec(spec); loader.exec_module(module)
module.closed = lambda root: None # Fake install must not interact with running games.
module.CONFIG = bundle.parent / 'install.json'
return module
def fingerprint(root):
return {p.relative_to(root).as_posix(): deps.digest(p) for p in root.rglob('*') if p.is_file()
and 'Ruen-UI-Backups' not in p.parts and p.name != '.ruen-install.lock'}
class InstallerTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory(prefix='ruen-release-test-')
self.base = Path(self.temp.name); self.bundle = self.base / 'bundle'
self.game = self.base / 'game/_forever_'; self.game.mkdir(parents=True)
(self.game / 'Wow.exe').write_bytes(b'fixture')
self.cache = self.base / 'cache'; self.cache.mkdir()
for name, data in build_release.payload().items():
p = self.bundle / name; p.parent.mkdir(parents=True, exist_ok=True); p.write_bytes(data)
lock = json.loads((self.bundle / 'dependencies.lock.json').read_text())
for package in lock['packages']:
archive = self.base / 'fixture.zip'
with zipfile.ZipFile(archive, 'w') as z:
for name in package['folders']:
z.writestr(name + '/' + name + '.toc', '## Interface: 16001\n')
z.writestr(name + '/fixture.lua', '-- upstream fixture\n')
package['sha256'] = deps.digest(archive); package['bytes'] = archive.stat().st_size
package['max_unpacked_bytes'] = 10000
package['url'] = 'https://127.0.0.1:1/not-a-real-download'
shutil.copy2(archive, self.cache / (package['id'] + '-' + package['sha256'][:12] + '.zip'))
(self.bundle / 'dependencies.lock.json').write_text(json.dumps(lock))
self.seal()
self.account = self.game / 'WTF/Account/TEST'
self.character = self.account / 'Realm/Character'; self.character.mkdir(parents=True)
for p, text in [(self.account / 'bindings-cache.wtf', 'bind F1 ORIGINAL\n'),
(self.character / 'AddOns.txt', 'Unrelated: enabled\nRuenUI: disabled\n'),
(self.account / 'SavedVariables/Spoken.lua', 'custom = "keep me"\n')]:
p.parent.mkdir(parents=True, exist_ok=True); p.write_text(text)
unrelated = self.game / 'Interface/AddOns/Unrelated/hello.lua'
unrelated.parent.mkdir(parents=True); unrelated.write_text('-- untouched')
self.original = fingerprint(self.game)
self.setup = load_setup(self.bundle)
self.args = types.SimpleNamespace(cache=str(self.cache), voice_packs='none', language='auto')
def tearDown(self): self.temp.cleanup()
def seal(self):
data = {p.relative_to(self.bundle).as_posix(): p.read_bytes() for p in self.bundle.rglob('*') if p.is_file() and p.name != 'manifest.json'}
(self.bundle / 'manifest.json').write_bytes(build_release.manifest(data))
def test_linux_install_repeat_preserve_and_restore(self):
self.setup.verify(self.bundle); self.setup.install(self.game, self.args)
self.assertEqual((self.account / 'SavedVariables/Spoken.lua').read_text(), 'custom = "keep me"\n')
backups = list((self.game / 'Ruen-UI-Backups').iterdir()); self.assertEqual(len(backups), 1)
report = self.game / 'Interface/AddOns/RuenUI/HardwareProfile.lua'
report.write_text('-- this laptop only\n')
self.setup.install(self.game, self.args)
self.assertEqual(len(list((self.game / 'Ruen-UI-Backups').iterdir())), 1)
self.assertEqual(report.read_text(), '-- this laptop only\n')
(self.account / 'bindings-cache.wtf').write_text('bind F1 NEW\n')
self.setup.restore(self.game, backups[0])
self.assertEqual(fingerprint(self.game), self.original)
def test_linux_reject_missing_backup_before_mutation(self):
self.setup.install(self.game, self.args)
backup = next((self.game / 'Ruen-UI-Backups').iterdir())
(backup / 'original/WTF/Account/TEST/bindings-cache.wtf').unlink()
before = fingerprint(self.game)
with self.assertRaises(ValueError): self.setup.restore(self.game, backup)
self.assertEqual(fingerprint(self.game), before)
def test_tampered_package(self):
(self.bundle / 'RuenUI/Core.lua').write_text('-- corrupted')
with self.assertRaises(ValueError): self.setup.verify(self.bundle)
self.assertEqual(fingerprint(self.game), self.original)
def test_incompatible_dependency(self):
folder = self.game / 'Interface/AddOns/Spoken'; folder.mkdir()
(folder / 'Spoken.toc').write_text('## Interface: 120000\n')
before = fingerprint(self.game)
with self.assertRaises(ValueError): self.setup.install(self.game, self.args)
self.assertEqual(fingerprint(self.game), before)
def test_download_failure_has_no_game_changes(self):
for path in self.cache.glob('*.zip'): path.unlink()
with self.assertRaises(Exception): self.setup.install(self.game, self.args)
self.assertEqual(fingerprint(self.game), self.original)
self.assertFalse(list(self.cache.glob('*.part')))
def test_partial_install_rolls_back(self):
original_copy = self.setup.copy
failed = False
def fail_once(src, dst):
nonlocal failed
if Path(dst) == self.game / 'Interface/AddOns/Spoken' and not failed:
failed = True
Path(dst).mkdir(); (Path(dst) / 'partial.lua').write_text('partial')
raise OSError('simulated disk write failure')
return original_copy(src, dst)
with patch.object(self.setup, 'copy', side_effect=fail_once), self.assertRaises(OSError):
self.setup.install(self.game, self.args)
self.assertTrue(failed)
self.assertEqual(fingerprint(self.game), self.original)
def test_parallel_install_lock(self):
with self.setup.locked(self.cache / '.install.lock'):
with self.assertRaises(RuntimeError): self.setup.install(self.game, self.args)
self.assertEqual(fingerprint(self.game), self.original)
def test_dependency_links_are_rejected(self):
(self.game / 'Interface/AddOns/Spoken').symlink_to(self.base / 'outside', target_is_directory=True)
with self.assertRaises(ValueError): self.setup.install(self.game, self.args)
def test_legacy_migration_and_restore(self):
old = self.account / 'SavedVariables/BradStockUI.lua.bak'; old.write_text('BradStockUIDB = {}\n')
before = fingerprint(self.game)
self.setup.install(self.game, self.args)
self.assertFalse(old.exists())
self.assertIn('RuenUIDB', (old.parent / 'RuenUI.lua.bak').read_text())
self.setup.restore(self.game, next((self.game / 'Ruen-UI-Backups').iterdir()))
self.assertEqual(fingerprint(self.game), before)
@unittest.skipUnless(os.environ.get('RUEN_PWSH'), 'Set RUEN_PWSH for PowerShell fixture tests')
def test_powershell_install_repeat_restore_and_integrity(self):
def run(*args, success=True):
r = subprocess.run([os.environ['RUEN_PWSH'], '-NoLogo', '-NoProfile', '-File', str(self.bundle / 'Install-Ruen-UI.ps1'), '-NonInteractive', *args], capture_output=True, text=True)
self.assertEqual(r.returncode == 0, success, r.stdout + r.stderr)
return r
install_args = ('-WoWPath', str(self.game), '-VoicePacks', 'none', '-CachePath', str(self.cache))
run(*install_args)
self.assertEqual((self.account / 'SavedVariables/Spoken.lua').read_text(), 'custom = "keep me"\n')
backups = list((self.game / 'Ruen-UI-Backups').iterdir()); self.assertEqual(len(backups), 1)
report = self.game / 'Interface/AddOns/RuenUI/HardwareProfile.lua'; report.write_text('-- retain report\n')
run(*install_args)
self.assertEqual(len(list((self.game / 'Ruen-UI-Backups').iterdir())), 1)
(self.account / 'bindings-cache.wtf').write_text('changed')
run('-Restore', '-BackupPath', str(backups[0]))
self.assertEqual(fingerprint(self.game), self.original)
(self.bundle / 'RuenUI/Core.lua').write_text('-- corrupt')
run(*install_args, success=False)
self.assertEqual(fingerprint(self.game), self.original)
@unittest.skipUnless(os.environ.get('RUEN_PWSH'), 'Set RUEN_PWSH for PowerShell fixture tests')
def test_powershell_failed_download_and_incomplete_restore(self):
def run(*args):
return subprocess.run([os.environ['RUEN_PWSH'], '-NoLogo', '-NoProfile', '-File', str(self.bundle / 'Install-Ruen-UI.ps1'), '-NonInteractive', *args], capture_output=True, text=True)
args = ('-WoWPath', str(self.game), '-VoicePacks', 'none', '-CachePath', str(self.cache))
missing = next(self.cache.glob('Leatrix_Plus-*.zip')); archive = missing.read_bytes(); missing.unlink()
r = run(*args); self.assertNotEqual(r.returncode, 0, r.stdout + r.stderr)
self.assertEqual(fingerprint(self.game), self.original)
missing.write_bytes(archive)
r = run(*args); self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
backup = next((self.game / 'Ruen-UI-Backups').iterdir())
(backup / 'original/WTF/Account/TEST/bindings-cache.wtf').unlink()
before = fingerprint(self.game)
r = run('-Restore', '-BackupPath', str(backup)); self.assertNotEqual(r.returncode, 0)
self.assertEqual(fingerprint(self.game), before)
@unittest.skipUnless(os.environ.get('RUEN_PWSH'), 'Set RUEN_PWSH for PowerShell fixture tests')
def test_powershell_archive_path_checks(self):
# Dot-source the helper only; each invalid path must fail without touching disk.
script = ". '" + str(self.bundle / 'Tools/Resolve-RuenDependencies.ps1') + "'; "
script += "foreach ($p in @('../escape','/absolute','C:/file','a/../b','a\\b','NUL.txt','a:stream','a./file','a//b')) { $caught=$false; try { Get-RuenArchivePath $p > $null } catch { $caught=$true }; if (-not $caught) { throw ('Accepted: '+$p) } }; Write-Output 'PASS'"
r = subprocess.run([os.environ['RUEN_PWSH'], '-NoProfile', '-Command', script], capture_output=True, text=True)
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
class ArchiveTests(unittest.TestCase):
def test_unsafe_paths(self):
for name in ('../escape', '/absolute', 'C:/file', 'a/../b', 'a\\b', 'NUL.txt', 'a:stream', 'a./file', 'a//b'):
with self.subTest(name=name), self.assertRaises(ValueError): deps.safe_relative(name)
def test_archive_case_collision_and_traversal(self):
with tempfile.TemporaryDirectory() as d:
root = Path(d); archive = root / 'fixture.zip'; stage = root / 'stage'; stage.mkdir()
p = {'folders': ['Spoken'], 'max_unpacked_bytes': 1000}
for entries in [('Spoken/a', 'Spoken/A'), ('Spoken/a', '../escape')]:
with zipfile.ZipFile(archive, 'w') as z:
for entry in entries: z.writestr(entry, 'x')
with self.assertRaises(ValueError): deps.extract(p, archive, stage)
self.assertFalse(list(stage.rglob('*')))
if __name__ == '__main__': unittest.main()