mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-21 13:55:58 +00:00
Merge upstream main and close diagnostic publication races
This commit is contained in:
473 files changed
+36063
-3507
No files matched your search
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,95 @@
|
||||
import itertools
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shlex
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
import yaml
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
class CiChecksTest(unittest.TestCase):
|
||||
def test_pr_cache_writes_and_source_timestamp_policy(self):
|
||||
jobs = yaml.safe_load((ROOT / '.github/workflows/build.yml').read_text())['jobs']
|
||||
cache = next(step for step in jobs['build']['steps']
|
||||
if step.get('uses') == 'gradle/actions/setup-gradle@v4')['with']
|
||||
self.assertEqual(cache['cache-read-only'],
|
||||
"${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository }}")
|
||||
gradle = (ROOT / 'app/build.gradle').read_text()
|
||||
self.assertIn("gitValue(['show', '-s', '--format=%ct', '--end-of-options', sourceCommit])", gradle)
|
||||
|
||||
def test_report_comment_lookup_ignores_human_marker(self):
|
||||
if not shutil.which('jq'):
|
||||
self.skipTest('jq required to execute comment selection')
|
||||
script = (ROOT / 'tools/release/report-build.sh').read_text()
|
||||
line = next(line for line in script.splitlines() if line.startswith('ID='))
|
||||
arguments = shlex.split(line[len('ID=$('):].split(' | head', 1)[0])
|
||||
query = arguments[arguments.index('--jq') + 1].replace('$MARK', '<!-- build -->')
|
||||
comments = [dict(id=1, user=dict(login='someone'), body='<!-- build --> forged'),
|
||||
dict(id=2, user=dict(login='github-actions[bot]'), body='<!-- build --> result')]
|
||||
result = subprocess.check_output(['jq', '-r', query], input=json.dumps(comments), text=True)
|
||||
self.assertEqual(result.strip(), '2')
|
||||
|
||||
def test_build_and_tests_use_identical_generated_metadata(self):
|
||||
jobs = yaml.safe_load((ROOT / '.github/workflows/build.yml').read_text())['jobs']
|
||||
steps = {step.get('id'): step for step in jobs['build']['steps']}
|
||||
self.assertEqual(steps['build']['env'], steps['unit-tests']['env'])
|
||||
self.assertIn('DROIDDECK_BUILD_LABEL', steps['unit-tests']['env'])
|
||||
self.assertIn('SGDB_API_KEY', steps['unit-tests']['env'])
|
||||
gradle = (ROOT / 'app/build.gradle').read_text()
|
||||
self.assertIn("outputs.doNotCacheIf('CI executes the test suite on every run') { true }", gradle)
|
||||
self.assertIn('outputs.upToDateWhen { false }', gradle)
|
||||
|
||||
def test_independent_jobs_wait_only_for_the_pinned_source(self):
|
||||
jobs = yaml.safe_load((ROOT / '.github/workflows/build.yml').read_text())['jobs']
|
||||
for name in ('xbox', 'components', 'python-tests'):
|
||||
self.assertEqual(jobs[name]['needs'], 'source')
|
||||
self.assertEqual(set(jobs['build']['needs']), {'source', 'components', 'xbox'})
|
||||
|
||||
def test_dependency_update_errors_block_installation(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
sudo = root / 'sudo'
|
||||
sudo.write_text('#!/bin/bash\nprintf "%s\\n" "$*" >> "$APT_LOG"\nexit "${APT_RESULT:-0}"\n')
|
||||
sudo.chmod(0o755)
|
||||
query = root / 'dpkg-query'
|
||||
query.write_text('#!/bin/sh\nexit 1\n')
|
||||
query.chmod(0o755)
|
||||
log = root / 'apt.log'
|
||||
env = dict(os.environ, PATH=str(root) + os.pathsep + os.environ['PATH'], APT_LOG=str(log))
|
||||
installer = ROOT / 'tools/ci/install-ubuntu-packages.sh'
|
||||
result = subprocess.run(['bash', str(installer), 'qemu-user'], env=dict(env, APT_RESULT='17'))
|
||||
self.assertEqual(result.returncode, 17)
|
||||
self.assertEqual(len(log.read_text().splitlines()), 2)
|
||||
log.unlink()
|
||||
subprocess.run(['bash', str(installer), 'qemu-user'], env=env, check=True)
|
||||
update, install = log.read_text().splitlines()
|
||||
for command in (update, install):
|
||||
self.assertIn('Dir::Etc::sourceparts=-', command)
|
||||
self.assertIn('Acquire::https::Timeout=15', command)
|
||||
self.assertIn('Acquire::Retries=1', command)
|
||||
self.assertIn('APT::Update::Error-Mode=any', update)
|
||||
self.assertIn('install -y -q --no-install-recommends qemu-user', install)
|
||||
|
||||
def test_required_status_rejects_failed_cancelled_or_skipped_test_jobs(self):
|
||||
jobs = yaml.safe_load((ROOT / '.github/workflows/build.yml').read_text())['jobs']
|
||||
gate = jobs['checks']
|
||||
self.assertEqual(gate['name'], 'Compile and test APK')
|
||||
self.assertEqual(set(gate['needs']), {'build', 'python-tests'})
|
||||
self.assertIn('always()', gate['if'])
|
||||
for build, python in itertools.product(('success', 'failure', 'cancelled', 'skipped'), repeat=2):
|
||||
with self.subTest(build=build, python=python):
|
||||
result = subprocess.run(
|
||||
['bash', '-c', gate['steps'][0]['run']],
|
||||
env=dict(os.environ, BUILD_RESULT=build, PYTHON_RESULT=python),
|
||||
capture_output=True)
|
||||
self.assertEqual(result.returncode == 0, build == python == 'success')
|
||||
for publisher in ('sign', 'packs'):
|
||||
self.assertIn('checks', jobs[publisher]['needs'])
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
class CiNdkTest(unittest.TestCase):
|
||||
def test_installed_ndk_must_match_the_declared_version(self):
|
||||
version = (ROOT / 'tools/ci/toolchains.env').read_text().strip().split('=', 1)[1]
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
ndk = root / 'ndk' / version
|
||||
ndk.mkdir(parents=True)
|
||||
properties = ndk / 'source.properties'
|
||||
properties.write_text('Pkg.Revision = ' + version + '\n')
|
||||
output = root / 'environment'
|
||||
env = dict(os.environ, ANDROID_HOME=str(root), GITHUB_ENV=str(output))
|
||||
script = ROOT / 'tools/ci/resolve-ndk.sh'
|
||||
subprocess.run(['bash', str(script)], env=env, check=True)
|
||||
self.assertIn('NDK_VERSION=' + version, output.read_text())
|
||||
self.assertIn('ANDROID_NDK_HOME=' + str(ndk), output.read_text())
|
||||
properties.write_text('Pkg.Revision = unexpected\n')
|
||||
self.assertNotEqual(subprocess.run(['bash', str(script)], env=env).returncode, 0)
|
||||
@@ -0,0 +1,106 @@
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tarfile
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
SPEC = importlib.util.spec_from_file_location('component_prepare', Path(__file__).resolve().parents[1] / 'components/prepare.py')
|
||||
components = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(components)
|
||||
|
||||
|
||||
class ComponentPrepareTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
directory = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(directory.cleanup)
|
||||
self.root = Path(directory.name)
|
||||
self.fixture(self.root)
|
||||
|
||||
def fixture(self, root):
|
||||
for name in components.TREES:
|
||||
(root / name).mkdir(parents=True)
|
||||
(root / 'tools/components/recipes').mkdir(parents=True)
|
||||
(root / 'input.h').write_text('#define VALUE 1\n')
|
||||
(root / 'tools/components/recipes/fake.sh').write_text('printf binary > app/src/main/assets/linuxfs/demo.so\n')
|
||||
spec = dict(script='tools/components/recipes/fake.sh', inputs=['input.h', 'tools/components/recipes/fake.sh'],
|
||||
outputs=['app/src/main/assets/linuxfs/demo.so'])
|
||||
(root / components.REGISTRY).write_text(json.dumps(dict(fake=spec)))
|
||||
for name in components.LIBRARIES:
|
||||
(root / name).parent.mkdir(parents=True, exist_ok=True)
|
||||
(root / name).write_bytes(b'library')
|
||||
subprocess.run(['git', 'init', '-q', str(root)], check=True)
|
||||
subprocess.run(['git', '-C', str(root), 'config', 'core.autocrlf', 'false'], check=True)
|
||||
subprocess.run(['git', '-C', str(root), 'add', '.'], check=True)
|
||||
subprocess.run(['git', '-C', str(root), '-c', 'user.name=Test Developer', '-c', 'user.email=test@example.test',
|
||||
'commit', '-qm', 'baseline'], check=True)
|
||||
|
||||
def test_recipe_failure_or_missing_output_does_not_succeed(self):
|
||||
script = self.root / 'tools/components/recipes/fake.sh'
|
||||
script.write_text('exit 7\n')
|
||||
with self.assertRaises(subprocess.CalledProcessError):
|
||||
components.prepare('fake', self.root)
|
||||
script.write_text('exit 0\n')
|
||||
with self.assertRaisesRegex(ValueError, 'required outputs'):
|
||||
components.prepare('fake', self.root)
|
||||
|
||||
def test_identity_covers_source_and_recipe_changes(self):
|
||||
original = components.identity('fake', self.root)
|
||||
(self.root / 'input.h').write_text('#define VALUE 2\n')
|
||||
changed = components.identity('fake', self.root)
|
||||
self.assertNotEqual(original, changed)
|
||||
script = self.root / 'tools/components/recipes/fake.sh'
|
||||
script.write_text(script.read_text() + '\nprintf changed\n')
|
||||
self.assertNotEqual(changed, components.identity('fake', self.root))
|
||||
|
||||
def test_tool_requirements_are_installed_in_one_union(self):
|
||||
definitions = dict(one=dict(packages=['gcc', 'cmake']), two=dict(packages=['gcc', 'qemu-user']))
|
||||
with patch.object(components, 'registry', return_value=definitions), patch.object(components.subprocess, 'run') as run:
|
||||
components.prepare_tools(['one', 'two'], self.root)
|
||||
run.assert_called_once_with(['bash', 'tools/ci/install-ubuntu-packages.sh', 'cmake', 'gcc', 'qemu-user'],
|
||||
cwd=self.root, check=True)
|
||||
|
||||
def test_prepared_handoff_verifies_every_file_and_source_tree(self):
|
||||
components.prepare('fake', self.root)
|
||||
archive = self.root / 'prepared.tar.gz'
|
||||
components.pack(archive, self.root)
|
||||
tree = subprocess.check_output(['git', 'rev-parse', 'HEAD^{tree}'], cwd=self.root, text=True).strip()
|
||||
target = self.root / 'target'
|
||||
self.fixture(target)
|
||||
components.unpack(archive, tree, target)
|
||||
self.assertEqual((target / 'app/src/main/assets/linuxfs/demo.so').read_bytes(), b'binary')
|
||||
with self.assertRaisesRegex(ValueError, 'pinned source'):
|
||||
components.unpack(archive, 'wrong-tree', target)
|
||||
|
||||
def test_tampered_component_bytes_fail_handoff_verification(self):
|
||||
components.prepare('fake', self.root)
|
||||
archive = self.root / 'prepared.tar.gz'
|
||||
components.pack(archive, self.root)
|
||||
corrupt = self.root / 'corrupt.tar.gz'
|
||||
with tarfile.open(archive) as original, tarfile.open(corrupt, 'w:gz') as output:
|
||||
for entry in original:
|
||||
content = original.extractfile(entry).read()
|
||||
if entry.name.endswith('demo.so'):
|
||||
content = b'tampered'
|
||||
entry.size = len(content)
|
||||
output.addfile(entry, io.BytesIO(content))
|
||||
target = self.root / 'target'
|
||||
self.fixture(target)
|
||||
tree = subprocess.check_output(['git', 'rev-parse', 'HEAD^{tree}'], cwd=self.root, text=True).strip()
|
||||
with self.assertRaisesRegex(ValueError, 'file hashes'):
|
||||
components.unpack(corrupt, tree, target)
|
||||
|
||||
def test_archive_cannot_overwrite_source_through_traversal(self):
|
||||
archive = self.root / 'bad.tar.gz'
|
||||
with tarfile.open(archive, mode='w:gz') as tar:
|
||||
name = 'app/src/main/assets/linuxfs/../../../../../input.h'
|
||||
entry = tarfile.TarInfo(name)
|
||||
entry.size = 3
|
||||
tar.addfile(entry, io.BytesIO(b'bad'))
|
||||
with self.assertRaisesRegex(ValueError, 'Unsafe'):
|
||||
components.unpack(archive, 'tree', self.root)
|
||||
self.assertEqual((self.root / 'input.h').read_text(), '#define VALUE 1\n')
|
||||
@@ -456,6 +456,15 @@ class ProtonRunTest(Temp):
|
||||
("0", "0", str(appid << 32 | 0x02000000), "1"))
|
||||
self.assertEqual(env["STEAM_COMPAT_DATA_PATH"], str(self.root / ("steamapps/compatdata/%d" % appid)))
|
||||
|
||||
def test_a_window_draws_with_the_desktops_software_gl(self):
|
||||
target = RUN["Target"]("2596113170", "/c", "/i", str(self.root), "fixed")
|
||||
session = {"MESA_LOADER_DRIVER_OVERRIDE": "zink", "GALLIUM_DRIVER": "zink", "LIBGL_KOPPER_DRI2": "true"}
|
||||
env = RUN["environment"](session, target, "/tool", str(self.root), window=True)
|
||||
self.assertEqual((env["LIBGL_ALWAYS_SOFTWARE"], env["GALLIUM_DRIVER"]), ("1", "llvmpipe"))
|
||||
self.assertNotIn("MESA_LOADER_DRIVER_OVERRIDE", env)
|
||||
self.assertNotIn("LIBGL_KOPPER_DRI2", env)
|
||||
self.assertEqual(RUN["environment"](session, target, "/tool", str(self.root))["GALLIUM_DRIVER"], "zink")
|
||||
|
||||
def test_a_steam_game_keeps_its_own_id(self):
|
||||
target = RUN["Target"]("413150", "/c", "/i", str(self.root), "steam")
|
||||
env = RUN["environment"]({"PROTON_USE_WINED3D": "0"}, target, "/tool", str(self.root), window=True)
|
||||
@@ -465,6 +474,13 @@ class ProtonRunTest(Temp):
|
||||
self.assertEqual(RUN["arguments"]("/root/x/setup.msi", ["/qn"]), ["msiexec", "/i", "Z:\\root\\x\\setup.msi", "/qn"])
|
||||
self.assertEqual(RUN["arguments"]("/root/x/a.exe", ["-w"]), ["/root/x/a.exe", "-w"])
|
||||
|
||||
def test_a_virtual_desktop_runs_the_program_by_its_windows_path(self):
|
||||
pfx = "/root/Steam/steamapps/compatdata/2596113170"
|
||||
self.assertEqual(RUN["arguments"](pfx + "/pfx/drive_c/Program Files (x86)/Battle.net/Battle.net Launcher.exe", [], "1280x720", pfx),
|
||||
["explorer.exe", "/desktop=droiddeck,1280x720", "C:\\Program Files (x86)\\Battle.net\\Battle.net Launcher.exe"])
|
||||
self.assertEqual(RUN["arguments"]("/root/.cache/setup.exe", ["--lang=enUS"], "1920x1080", pfx),
|
||||
["explorer.exe", "/desktop=droiddeck,1920x1080", "Z:\\root\\.cache\\setup.exe", "--lang=enUS"])
|
||||
|
||||
def test_a_games_own_program_is_left_to_steam(self):
|
||||
self.write("Steam/appcache/appinfo.vdf", appinfo({413150: STARDEW}))
|
||||
self.assertEqual(RUN["compat"]()["launch_programs"](STARDEW["config"]),
|
||||
@@ -554,6 +570,50 @@ class ProtonRunTest(Temp):
|
||||
self.game("70", "Linux Game", "run.sh")
|
||||
self.assertEqual(self.run_main(["--app", "70"])[0], 2)
|
||||
|
||||
def test_without_steam_a_shortcut_reuses_a_signed_prefix_folder(self):
|
||||
bat = self.write("Games/Epic/Game/.droiddeck-launch.bat", b"@echo off")
|
||||
start = self.tmp / "Games/Epic/Game/Binaries"
|
||||
start.mkdir()
|
||||
signed = self.root / "steamapps/compatdata/-1561598272"
|
||||
signed.mkdir(parents=True)
|
||||
code, calls, dirs = self.run_main(["--app", "2733369024", "--dir", str(start), "--", str(bat)])
|
||||
self.assertIsNone(code)
|
||||
env = calls[0][2]
|
||||
self.assertEqual(env["STEAM_COMPAT_DATA_PATH"], str(signed))
|
||||
self.assertFalse((self.root / "steamapps/compatdata/2733369024").exists())
|
||||
|
||||
def test_prefix_folder_prefers_initialized_unsigned_over_empty_signed(self):
|
||||
signed = self.root / "steamapps/compatdata/-1561598272"
|
||||
signed.mkdir(parents=True)
|
||||
initialized = self.root / "steamapps/compatdata/2733369024/pfx"
|
||||
initialized.mkdir(parents=True)
|
||||
|
||||
self.assertEqual(RUN["prefix_folder"](str(self.root), 2733369024), str(initialized.parent))
|
||||
|
||||
def test_prefix_folder_prefers_initialized_signed_over_empty_unsigned(self):
|
||||
unsigned = self.root / "steamapps/compatdata/2733369024"
|
||||
unsigned.mkdir(parents=True)
|
||||
initialized = self.root / "steamapps/compatdata/-1561598272/pfx"
|
||||
initialized.mkdir(parents=True)
|
||||
|
||||
self.assertEqual(RUN["prefix_folder"](str(self.root), 2733369024), str(initialized.parent))
|
||||
|
||||
def test_prefix_folder_prefers_unsigned_when_initialization_ties(self):
|
||||
unsigned = self.root / "steamapps/compatdata/2733369024/pfx"
|
||||
unsigned.mkdir(parents=True)
|
||||
signed = self.root / "steamapps/compatdata/-1561598272/pfx"
|
||||
signed.mkdir(parents=True)
|
||||
|
||||
self.assertEqual(RUN["prefix_folder"](str(self.root), 2733369024), str(unsigned.parent))
|
||||
|
||||
def test_prefix_folder_skips_numeric_names_too_long_to_convert(self):
|
||||
from unittest.mock import patch
|
||||
folder = self.root / "steamapps/compatdata"
|
||||
folder.mkdir(parents=True)
|
||||
with patch.object(RUN["os"], "listdir", return_value=["9" * 5000]):
|
||||
self.assertEqual(RUN["prefix_folder"](str(self.root), 2733369024),
|
||||
str(folder / "2733369024"))
|
||||
|
||||
def test_without_steam_a_shortcut_keeps_its_prefix_folder_and_launch_options(self):
|
||||
bat = self.write("Games/Epic/Game/.droiddeck-launch.bat", b"@echo off")
|
||||
start = self.tmp / "Games/Epic/Game/Binaries"
|
||||
@@ -568,6 +628,43 @@ class ProtonRunTest(Temp):
|
||||
self.assertTrue((self.root / "steamapps/compatdata/2733369024").is_dir())
|
||||
self.assertEqual(dirs, [str(start)])
|
||||
|
||||
def write_account(self):
|
||||
self.write("Steam/config/loginusers.vdf",
|
||||
'"users"\n{\n\t"76561198352563669"\n\t{\n\t\t"MostRecent"\t\t"1"\n\t}\n}\n')
|
||||
return "Steam/userdata/392297941/config/"
|
||||
|
||||
def test_without_steam_and_options_a_game_takes_its_steam_launch_options(self):
|
||||
config = self.write_account()
|
||||
self.write(config + "localconfig.vdf", '"UserLocalConfigStore"\n{\n\t"Software"\n\t{\n\t\t"Valve"\n\t\t{\n'
|
||||
'\t\t\t"Steam"\n\t\t\t{\n\t\t\t\t"apps"\n\t\t\t\t{\n\t\t\t\t\t"413150"\n\t\t\t\t\t{\n'
|
||||
'\t\t\t\t\t\t"cloud"\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t"LaunchOptions"\t\t"-wrong"\n\t\t\t\t\t\t}\n'
|
||||
'\t\t\t\t\t\t"LaunchOptions"\t\t"DXVK_HUD=1 %command% -d3d9 \\"-name=Two Words\\""\n'
|
||||
'\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n')
|
||||
shortcuts = runpy.run_path(str(BIN / "droiddeck-steam-shortcuts"))
|
||||
self.write(config + "shortcuts.vdf", shortcuts["write"]({"shortcuts": {
|
||||
"0": {"appid": -1561598272, "AppName": "Batman", "LaunchOptions": "-d3d9"},
|
||||
"1": {"appid": -1, "AppName": "Other", "LaunchOptions": "-x"},
|
||||
}}))
|
||||
root = str(self.root)
|
||||
self.assertEqual(RUN["steam_options"]("413150", root), 'DXVK_HUD=1 %command% -d3d9 "-name=Two Words"')
|
||||
self.assertEqual(RUN["steam_options"]("2733369024", root), "-d3d9")
|
||||
self.assertEqual(RUN["steam_options"]("70", root), "")
|
||||
self.assertEqual(RUN["steam_options"]("2733369025", root), "")
|
||||
info = {"common": {"type": "Game"}, "config": {"launch": {
|
||||
"0": {"executable": "Game.exe", "type": "default", "config": {"oslist": "windows"}}}}}
|
||||
self.write("Steam/appcache/appinfo.vdf", appinfo({413150: info}))
|
||||
program = self.game("413150", "Some Game", "Game.exe")
|
||||
code, calls, _ = self.run_main(["--app", "413150"])
|
||||
self.assertIsNone(code)
|
||||
_, argv, env = calls[0]
|
||||
self.assertEqual(argv[1:], ["waitforexitandrun", str(program), "-d3d9", "-name=Two Words"])
|
||||
self.assertEqual(env["DXVK_HUD"], "1")
|
||||
bat = self.write("Games/GOG/Batman/Batman.exe", b"MZ")
|
||||
code, calls, _ = self.run_main(["--app", "2733369024", "--", str(bat)])
|
||||
self.assertEqual(calls[0][1][1:], ["waitforexitandrun", str(bat), "-d3d9"])
|
||||
code, calls, _ = self.run_main(["--app", "2733369024", "--options", "", "--", str(bat)])
|
||||
self.assertEqual(calls[0][1][1:], ["waitforexitandrun", str(bat)])
|
||||
|
||||
def test_launch_options_split_like_steam_does(self):
|
||||
split = RUN["split_options"]
|
||||
self.assertEqual(split(""), ({}, []))
|
||||
|
||||
@@ -196,6 +196,63 @@ class AgentTest(unittest.TestCase):
|
||||
answer = self.ask({"kind": "vr", "action": "status"})
|
||||
self.assertEqual("UNAVAILABLE", answer["error"]["code"])
|
||||
|
||||
def fake_proc(self, pid, parent, comm, env):
|
||||
root = self.dir / "proc" / str(pid)
|
||||
root.mkdir(parents=True)
|
||||
(root / "comm").write_text(comm + "\n")
|
||||
(root / "stat").write_text("%d (%s) S %d 0 0" % (pid, comm, parent))
|
||||
(root / "environ").write_bytes(b"\0".join(b"%s=%s" % (k.encode(), v.encode()) for k, v in env.items()) + b"\0")
|
||||
|
||||
def tag(self, wins, arch="arm64"):
|
||||
snap = {"displays": {":0": [], ":1": wins}}
|
||||
with patch.dict(os.environ, {"DISPLAY": ":0", "BL_STEAM_CLIENT_ARCH": arch}), \
|
||||
patch.object(agent.subprocess, "run") as run, patch.object(agent, "log"):
|
||||
run.return_value.returncode = 0
|
||||
tagged = agent.tag_game_windows(snap, proc=self.dir / "proc")
|
||||
return tagged, [call.args[0][-1] for call in run.call_args_list]
|
||||
|
||||
def test_a_sandboxed_flatpak_window_is_tagged_with_its_shortcut(self):
|
||||
self.fake_proc(40, 1, "gjs", {"FLATPAK_ID": "com.github.tchx84.Flatseal", "SteamAppId": "2166984148"})
|
||||
win = {"window": 7, "map": "viewable", "class": "com.github.tchx84.Flatseal", "pid": None}
|
||||
self.assertEqual(self.tag([win]), (True, ["2166984148"]))
|
||||
|
||||
def test_a_flatpak_window_named_after_the_app_is_matched(self):
|
||||
self.fake_proc(40, 1, "vacuumtube", {"FLATPAK_ID": "rocks.shy.VacuumTube", "SteamAppId": "3000000001"})
|
||||
win = {"window": 7, "map": "viewable", "class": "VacuumTube", "pid": None}
|
||||
self.assertEqual(self.tag([win]), (True, ["3000000001"]))
|
||||
|
||||
def test_a_window_whose_process_has_no_app_id_falls_back_to_its_flatpak(self):
|
||||
self.fake_proc(40, 1, "bwrap", {"FLATPAK_ID": "com.github.tchx84.Flatseal", "SteamAppId": "2166984148"})
|
||||
self.fake_proc(41, 1, "gjs", {})
|
||||
win = {"window": 7, "map": "viewable", "class": "com.github.tchx84.Flatseal", "pid": 41}
|
||||
self.assertEqual(self.tag([win]), (True, ["2166984148"]))
|
||||
|
||||
def test_a_flatpak_shared_by_two_shortcuts_is_not_guessed(self):
|
||||
self.fake_proc(40, 1, "gjs", {"FLATPAK_ID": "com.github.tchx84.Flatseal", "SteamAppId": "2166984148"})
|
||||
self.fake_proc(42, 1, "gjs", {"FLATPAK_ID": "com.github.tchx84.Flatseal", "SteamAppId": "3000000003"})
|
||||
win = {"window": 7, "map": "viewable", "class": "com.github.tchx84.Flatseal", "pid": None}
|
||||
self.assertEqual(self.tag([win]), (False, []))
|
||||
|
||||
def test_a_window_outside_the_reaper_takes_its_process_app_id(self):
|
||||
self.fake_proc(30, 1, "proot", {})
|
||||
self.fake_proc(31, 30, "electron", {"SteamAppId": "3000000002"})
|
||||
win = {"window": 8, "map": "viewable", "class": "electron", "pid": 31}
|
||||
self.assertEqual(self.tag([win]), (True, ["3000000002"]))
|
||||
|
||||
def test_windows_gamescope_already_resolves_are_left_alone(self):
|
||||
self.fake_proc(20, 1, "reaper", {})
|
||||
self.fake_proc(21, 20, "game", {"SteamAppId": "413150"})
|
||||
wins = [{"window": 9, "map": "viewable", "class": "game", "pid": 21},
|
||||
{"window": 10, "map": "viewable", "class": "tagged", "pid": None, "appId": 5},
|
||||
{"window": 11, "map": "viewable", "class": "other", "pid": None},
|
||||
{"window": 12, "map": "unmapped", "class": "game", "pid": 21},
|
||||
{"window": 13, "map": "viewable", "class": "steam_app_550", "pid": None}]
|
||||
self.assertEqual(self.tag(wins), (False, []))
|
||||
|
||||
def test_the_x86_client_still_tags_its_game_classes(self):
|
||||
win = {"window": 13, "map": "viewable", "class": "steam_app_550", "pid": None}
|
||||
self.assertEqual(self.tag([win], arch="x86_64"), (True, ["550"]))
|
||||
|
||||
def test_exec_output_and_status(self):
|
||||
answer = self.ask({"kind": "exec", "argv": ["sh", "-c", "echo out; echo err >&2; exit 3"], "env": {"X": "1"}})
|
||||
self.assertTrue(answer["ok"])
|
||||
|
||||
@@ -549,11 +549,12 @@ class LaunchTest(FexTestCase):
|
||||
def test_the_guest_environment(self):
|
||||
arm = self.write(self.tmp / "arm.so", elf(183))
|
||||
x86 = self.write(self.tmp / "x86.so", elf(62))
|
||||
env = {"LD_PRELOAD": "%s:%s %s" % (arm, x86, self.tmp / "gone.so"),
|
||||
env = {"LD_PRELOAD": "%s:%s %s libMelonLoader.Bootstrap.so" % (arm, x86, self.tmp / "gone.so"),
|
||||
"LD_LIBRARY_PATH": "/steam/steamrtarm64:/usr/lib/aarch64-linux-gnu:/game/lib:/steam/linuxarm64",
|
||||
"FEX_ROOTFS": "/usr/share/guestos/fex-mesa", "FEX_TSOENABLED": "1"}
|
||||
guest = FEX["guest_environment"]({"portable": True}, env)
|
||||
self.assertEqual((guest["LD_PRELOAD"], guest["LD_LIBRARY_PATH"], guest["FEX_PORTABLE"]), (str(x86), "/game/lib", "1"))
|
||||
self.assertEqual((guest["LD_PRELOAD"], guest["LD_LIBRARY_PATH"], guest["FEX_PORTABLE"]),
|
||||
("%s:libMelonLoader.Bootstrap.so" % x86, "/game/lib", "1"))
|
||||
self.assertNotIn("FEX_ROOTFS", guest)
|
||||
self.assertEqual(guest["FEX_TSOENABLED"], "1")
|
||||
self.assertTrue(guest["FEX_APP_CONFIG_LOCATION"].endswith("/config/"))
|
||||
@@ -690,6 +691,32 @@ class LaunchTest(FexTestCase):
|
||||
command, env, mode = G["launch"].call_args[0]
|
||||
self.assertEqual((command, mode), (["/game/run.sh", "-a"], "auto"))
|
||||
|
||||
def test_steam_games_get_their_settings_and_linux_unity_keeps_tso(self):
|
||||
config = self.home / ".config/droiddeck/game-environment.json"
|
||||
unity = self.write(self.tmp / "Megabonk/Megabonk.x86_64", elf(62), 0o755)
|
||||
self.write(self.tmp / "Megabonk/UnityPlayer.so", elf(62))
|
||||
self.write(self.tmp / "Megabonk/GameAssembly.so", elf(62))
|
||||
other = self.write(self.tmp / "Other/game.x86_64", elf(62), 0o755)
|
||||
self.write(config, json.dumps({"version": 1, "shared": {"FEX_TSOENABLED": "0", "FEX_MULTIBLOCK": "1"},
|
||||
"games": {"20": {"FEX_TSOENABLED": "0"}}}))
|
||||
|
||||
def started(program, app):
|
||||
with mock.patch.dict(G, {"launch": mock.Mock(return_value=0), "GAME_ENVIRONMENT": str(config)}), \
|
||||
mock.patch.dict(os.environ, {"SteamAppId": app}, clear=True):
|
||||
_, said = self.quiet(FEX["main"], ["steam", "waitforexitandrun", str(program), "-arg"])
|
||||
command, env, _ = G["launch"].call_args[0]
|
||||
self.assertEqual(command, [str(program), "-arg"])
|
||||
return env.get("FEX_TSOENABLED"), env.get("FEX_MULTIBLOCK"), said
|
||||
|
||||
tso, multiblock, said = started(unity, "10")
|
||||
self.assertEqual((tso, multiblock), ("1", "1"))
|
||||
self.assertIn("Unity: FEX with TSO", said)
|
||||
self.assertEqual(started(other, "10")[:2], ("0", "1"))
|
||||
self.assertEqual(started(unity, "20")[:2], ("0", "1"))
|
||||
config.unlink()
|
||||
self.assertEqual(started(unity, "10")[:2], ("1", None))
|
||||
self.assertEqual(started(other, "10")[:2], (None, None))
|
||||
|
||||
|
||||
class AppInfoTest(unittest.TestCase):
|
||||
COMPAT = runpy.run_path(str(BIN / "steam-compatibility"))
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import json
|
||||
import runpy
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
|
||||
COMPAT = runpy.run_path(str(BIN / "steam-compatibility"))
|
||||
TOOL = COMPAT["TOOL"]
|
||||
OLD = {"name": "DroidDeck-Proton-11-11.2", "display": "DroidDeck-Proton 11-11.2", "dir": "DroidDeck-Proton 11-11.2", "valve": False}
|
||||
NEW = {"name": "DroidDeck-Proton-11-11.4", "display": "DroidDeck-Proton 11-11.4", "dir": "DroidDeck-Proton 11-11.4", "valve": False}
|
||||
VALVE = {"name": TOOL, "display": "Proton Experimental ARM64", "dir": "Proton - Experimental (ARM64)", "valve": True}
|
||||
GE = {"name": "GE-Proton11-7", "display": "GE-Proton11-7", "dir": "GE-Proton11-7", "valve": False}
|
||||
|
||||
|
||||
def config_text(entries):
|
||||
mapping = "".join('"%s" { "name" "%s" "config" "" "priority" "%s" }' % (app, name, "75" if app == "0" else "250") for app, name in entries)
|
||||
return '"InstallConfigStore" { "Software" { "Valve" { "Steam" { "CompatToolMapping" { %s } } } } }' % mapping
|
||||
|
||||
|
||||
class DroidDeckProtonDefaultTest(unittest.TestCase):
|
||||
def run_default(self, state, mapping, catalog, apps=(), request=None, settle=True):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
directory = Path(tmp)
|
||||
(directory / "state.json").write_text(json.dumps(state))
|
||||
if request is not None:
|
||||
(directory / "request.json").write_text(json.dumps(request))
|
||||
config = directory / "config.vdf"
|
||||
config.write_text(config_text(mapping))
|
||||
default = COMPAT["register_default"](str(config), list(apps), catalog=catalog, directory=str(directory), settle=settle)
|
||||
return default, COMPAT["read_config_mapping"](str(config)), json.loads((directory / "state.json").read_text())
|
||||
|
||||
def test_a_replacement_seen_while_steam_runs_still_moves_the_default_later(self):
|
||||
_, mapping, state = self.run_default(
|
||||
{"default": OLD["name"], "own_proton": True, "tools": [VALVE, OLD]}, [("0", OLD["name"])], [VALVE, NEW], settle=False)
|
||||
self.assertEqual(state["tools"], [VALVE, NEW])
|
||||
self.assertIn(OLD["name"], state["own_builds"])
|
||||
default, mapping, state = self.run_default(state, [("0", OLD["name"])], [VALVE, NEW])
|
||||
self.assertEqual(default, NEW["name"])
|
||||
self.assertEqual(mapping, {"0": NEW["name"]})
|
||||
|
||||
def test_a_valve_default_picked_in_steam_after_a_replacement_is_kept(self):
|
||||
default, mapping, _ = self.run_default(
|
||||
{"default": OLD["name"], "own_proton": True, "tools": [VALVE, OLD]}, [("0", TOOL)], [VALVE, NEW])
|
||||
self.assertEqual(default, TOOL)
|
||||
self.assertEqual(mapping, {"0": TOOL})
|
||||
|
||||
def test_the_first_start_with_droiddeck_proton_makes_it_the_default_for_following_titles(self):
|
||||
default, mapping, state = self.run_default(
|
||||
{"default": TOOL, "auto": {"42": TOOL}}, [("0", TOOL), ("42", TOOL), ("43", TOOL)], [VALVE, NEW], ["42", "43"])
|
||||
self.assertEqual(default, NEW["name"])
|
||||
self.assertEqual(mapping, {"0": NEW["name"], "42": NEW["name"], "43": TOOL})
|
||||
self.assertEqual(state["default"], NEW["name"])
|
||||
self.assertTrue(state["own_proton"])
|
||||
|
||||
def test_a_default_picked_after_the_switch_is_kept(self):
|
||||
default, mapping, state = self.run_default(
|
||||
{"default": NEW["name"], "own_proton": True, "applied": 1, "tools": [VALVE, NEW]},
|
||||
[("0", NEW["name"])], [VALVE, NEW], request={"seq": 2, "valve": True, "dir": VALVE["dir"]})
|
||||
self.assertEqual(default, TOOL)
|
||||
self.assertEqual(mapping, {"0": TOOL})
|
||||
default, mapping, state = self.run_default(
|
||||
{"default": TOOL, "own_proton": True, "tools": [VALVE, NEW]}, [("0", TOOL)], [VALVE, NEW])
|
||||
self.assertEqual(default, TOOL)
|
||||
self.assertEqual(mapping, {"0": TOOL})
|
||||
|
||||
def test_a_replaced_build_moves_its_default_and_titles_to_the_newest(self):
|
||||
default, mapping, state = self.run_default(
|
||||
{"default": OLD["name"], "own_proton": True, "auto": {"42": OLD["name"]}, "tools": [VALVE, OLD, GE]},
|
||||
[("0", OLD["name"]), ("42", OLD["name"]), ("43", OLD["name"]), ("44", GE["name"]), ("45", TOOL)],
|
||||
[VALVE, NEW, GE], ["42", "43", "44", "45"])
|
||||
self.assertEqual(default, NEW["name"])
|
||||
self.assertEqual(mapping, {"0": NEW["name"], "42": NEW["name"], "43": NEW["name"], "44": GE["name"], "45": TOOL})
|
||||
self.assertEqual(state["auto"], {"42": NEW["name"]})
|
||||
|
||||
def test_a_replaced_build_does_not_override_a_valve_default(self):
|
||||
default, mapping, _ = self.run_default(
|
||||
{"default": TOOL, "own_proton": True, "tools": [VALVE, OLD]}, [("0", TOOL), ("43", OLD["name"])], [VALVE, NEW], ["43"])
|
||||
self.assertEqual(default, TOOL)
|
||||
self.assertEqual(mapping, {"0": TOOL, "43": NEW["name"]})
|
||||
|
||||
def test_nothing_changes_without_droiddeck_proton(self):
|
||||
default, mapping, state = self.run_default({"default": TOOL}, [("0", TOOL)], [VALVE, GE])
|
||||
self.assertEqual(default, TOOL)
|
||||
self.assertEqual(mapping, {"0": TOOL})
|
||||
self.assertNotIn("own_proton", state)
|
||||
|
||||
def test_the_newest_build_is_found_by_version(self):
|
||||
newest, gone = COMPAT["own_proton_moves"]({"tools": [OLD]}, [dict(NEW, name="a", dir="DroidDeck-Proton 11-9.10"), dict(NEW, name="b", dir="DroidDeck-Proton 11-11.1")])
|
||||
self.assertEqual(newest, "b")
|
||||
self.assertEqual(gone, {OLD["name"]})
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -413,6 +413,21 @@ class DroiddeckctlTest(FakeAdbTest):
|
||||
self.assertEqual("Awake", out["wakefulness"])
|
||||
self.assertIn(["shell", "input", "keyevent", "KEYCODE_WAKEUP"], [c["args"] for c in self.calls()])
|
||||
|
||||
def test_proot_profile_queues_only_the_next_session(self):
|
||||
self.configure({"env": {"ok": True}})
|
||||
code, out = self.run_ctl("proot-profile", "enable", "--slow-us", "250")
|
||||
self.assertEqual(0, code, out)
|
||||
self.assertEqual({"op": "set", "lines": ["PROOT_PROFILE=1", "PROOT_PROFILE_SLOW_US=250"], "persistent": False},
|
||||
self.calls("env")[0]["request"])
|
||||
|
||||
def test_proot_profile_report_needs_no_adb_or_device(self):
|
||||
path = self.dir / "session.log"
|
||||
path.write_text('ordinary log')
|
||||
with unittest.mock.patch.object(ctl, "adb_path", side_effect=AssertionError("must stay offline")):
|
||||
code, out = self.run_ctl("proot-profile", "report", str(path))
|
||||
self.assertEqual(0, code, out)
|
||||
self.assertFalse(out["hasCounters"])
|
||||
|
||||
def test_override_pushes_to_the_inbox_first(self):
|
||||
self.configure({
|
||||
"access": {"ok": True, "commands": True, "inbox": "/sdcard/Android/data/x/files/agent-inbox"},
|
||||
|
||||
@@ -1160,8 +1160,12 @@ class BundleTest(unittest.TestCase):
|
||||
except ImportError:
|
||||
self.skipTest("PyYAML is not installed")
|
||||
apk = yaml.safe_load((self.ROOT / ".github/workflows/build.yml").read_text())
|
||||
steps = {step.get("name"): step for step in apk["jobs"]["build"]["steps"]}
|
||||
bundle = steps["Bundle the droiddeck-esync packs"]
|
||||
steps = {step.get("name"): step for step in apk["jobs"]["components"]["steps"]}
|
||||
import json
|
||||
recipes = json.loads((self.ROOT / "tools/components/recipes.json").read_text())
|
||||
bundle = dict(steps["Bundle the droiddeck-esync packs"])
|
||||
self.assertIn("prepare.py esync", bundle["run"])
|
||||
bundle["run"] = (self.ROOT / recipes["esync"]["script"]).read_text()
|
||||
self.assertNotIn("if", bundle)
|
||||
self.assertIn("tools/droiddeck-esync/release.env", bundle["run"])
|
||||
self.assertIn('release_url="https://github.com/${SYNC_BUNDLE_REPO}/releases/download/${SYNC_BUNDLE_TAG}"', bundle["run"])
|
||||
@@ -1169,7 +1173,7 @@ class BundleTest(unittest.TestCase):
|
||||
self.assertIn('curl -fsSL --retry 3 -o sync-index.json "$release_url/index.json"', bundle["run"])
|
||||
self.assertIn("sha256sum -c -", bundle["run"])
|
||||
self.assertNotIn("revoked.txt", bundle["run"])
|
||||
stage = next(step for step in apk["jobs"]["build"]["steps"] if "overlay/usr/local/bin/droiddeck-*" in step.get("run", ""))
|
||||
stage = {"run": (self.ROOT / recipes["runtime"]["script"]).read_text()}
|
||||
self.assertIn("tools/linuxfs/overlay/usr/local/bin/droiddeck-* ", stage["run"])
|
||||
local = (self.ROOT / "tools/build_local.sh").read_text()
|
||||
self.assertIn("tools/linuxfs/overlay/usr/local/bin/droiddeck-* ", local)
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-flatpak-setup"
|
||||
|
||||
|
||||
class FlatpakSetupTest(unittest.TestCase):
|
||||
def run_setup(self, uid, pacman):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
bin_dir = root / "bin"
|
||||
bin_dir.mkdir()
|
||||
stubs = {"id": "echo %d" % uid, "curl": "exit 7", "pacman": pacman, "pacman-key": "exit 0"}
|
||||
for name, body in stubs.items():
|
||||
(bin_dir / name).write_text("#!/bin/sh\n%s\n" % body)
|
||||
(bin_dir / name).chmod(0o755)
|
||||
script = root / "setup"
|
||||
script.write_text(SCRIPT.read_text().replace("WORK=/var/cache/droiddeck-flatpak", "WORK=%s/work" % root)
|
||||
.replace("/etc/pacman.d/gnupg/pubring.gpg", str(root / "pubring.gpg"))
|
||||
.replace(" /etc/pacman.conf >", " %s >" % (root / "pacman.conf")))
|
||||
(root / "pacman.conf").write_text("[options]\n[core]\nInclude = /etc/pacman.d/mirrorlist\n")
|
||||
(root / "pubring.gpg").write_text("")
|
||||
env = dict(os.environ, PATH="%s:%s" % (bin_dir, os.environ["PATH"]))
|
||||
result = subprocess.run(["bash", str(script)], env=env, capture_output=True, text=True, timeout=30)
|
||||
return result.returncode, result.stdout
|
||||
|
||||
def test_a_manual_run_without_root_says_so(self):
|
||||
code, out = self.run_setup(1000, "exit 0")
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn("== FAIL needs root", out)
|
||||
self.assertNotIn("Reading the package lists", out)
|
||||
|
||||
def test_an_unreachable_mirror_reports_pacmans_error(self):
|
||||
code, out = self.run_setup(0, "echo \"error: failed retrieving file 'core.db' : Could not resolve host\" >&2; exit 1")
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn("== FAIL could not reach the Arch Linux ARM mirrors (error: failed retrieving file 'core.db' : "
|
||||
"Could not resolve host)", out)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -8,6 +8,7 @@ import shlex
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from unittest import mock
|
||||
import unittest
|
||||
|
||||
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
|
||||
@@ -295,6 +296,14 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
self.assertEqual(MODULE["apply_config"](env, config, "42")["TU_DEBUG"], "sysmem")
|
||||
self.assertNotIn("TU_DEBUG", MODULE["apply_config"](env, config, "43"))
|
||||
|
||||
def test_the_vram_cap_comes_before_the_games_own_dxvk_settings(self):
|
||||
cap = MODULE["vram_cap"]
|
||||
self.assertEqual(cap({"BL_VRAM_MB": "4096"})["DXVK_CONFIG"], "dxgi.maxDeviceMemory = 4096")
|
||||
self.assertEqual(cap({"BL_VRAM_MB": "2048", "DXVK_CONFIG": "dxvk.maxFrameRate = 60;"})["DXVK_CONFIG"],
|
||||
"dxgi.maxDeviceMemory = 2048; dxvk.maxFrameRate = 60")
|
||||
for off in ({}, {"BL_VRAM_MB": "0"}, {"BL_VRAM_MB": "lots"}, {"BL_VRAM_MB": "²"}, {"BL_VRAM_MB": "-1"}):
|
||||
self.assertNotIn("DXVK_CONFIG", cap(off))
|
||||
|
||||
def test_a_games_wine_sync_choice_also_reaches_its_setup_runs(self):
|
||||
env = {"BL_SYNC": "1", "BL_SYNC_FALLBACK": "1", "BL_FSYNC_FIRST": "0", "OTHER": "kept"}
|
||||
config = {"version": 1, "games": {"42": {"BL_SYNC": "0", "BL_FSYNC_FIRST": "1", "PROTON_NO_ESYNC": "1", "FEX_TSOENABLED": "1"}}}
|
||||
@@ -472,6 +481,90 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
(asylum / name).touch()
|
||||
self.assertEqual(MODULE["engine_fixes"](str(asylum / "BmLauncher.exe"), []), ({}, [], []))
|
||||
|
||||
def test_black_ops_iii_and_dark_souls_remastered_skip_protonfixes(self):
|
||||
for exe in ("/game/Call of Duty Black Ops III/BlackOps3.exe", "/game/DARK SOULS REMASTERED/DarkSoulsRemastered.exe"):
|
||||
env, extra, notes = MODULE["engine_fixes"](exe, [])
|
||||
self.assertEqual((env, extra), ({"PROTONFIXES_DISABLE": "1"}, []))
|
||||
self.assertTrue(notes)
|
||||
self.assertEqual(MODULE["engine_fixes"]("/game/Game/DarkSoulsII.exe", []), ({}, [], []))
|
||||
|
||||
def test_game_cores_are_parsed_from_lists_and_ranges(self):
|
||||
parse = MODULE["parse_cores"]
|
||||
self.assertEqual(parse("0-3,6"), {0, 1, 2, 3, 6})
|
||||
self.assertEqual(parse(" 4, 5 "), {4, 5})
|
||||
for bad in ("", "a", "3-1", "1,,2", "-1", "1-"):
|
||||
self.assertIsNone(parse(bad), bad)
|
||||
|
||||
def test_a_profiles_game_cores_pin_the_game_within_the_online_cores(self):
|
||||
calls = []
|
||||
os_mod = MODULE["os"]
|
||||
with mock.patch.dict(MODULE["game_cores"].__globals__, {"online_cores": lambda: {0, 1, 2, 3, 4, 5, 6, 7}}), \
|
||||
mock.patch.object(os_mod, "sched_setaffinity", side_effect=lambda pid, cores: calls.append(set(cores)), create=True):
|
||||
MODULE["game_cores"]({"DROIDDECK_GAME_CORES": "0-2,9"})
|
||||
MODULE["game_cores"]({"DROIDDECK_GAME_CORES": "junk"})
|
||||
MODULE["game_cores"]({"DROIDDECK_GAME_CORES": "12-13"})
|
||||
MODULE["game_cores"]({})
|
||||
self.assertEqual(calls, [{0, 1, 2}])
|
||||
self.assertEqual(MODULE["parse_cores"]("0,2-7"), {0, 2, 3, 4, 5, 6, 7})
|
||||
|
||||
def test_caravan_sandwitch_robocop_and_cyberpunk_run_at_feature_level_12_1(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
caravan = Path(tmp) / "Caravan SandWitch"
|
||||
shipping = caravan / "CaravanSandWitch/Binaries/Win64"
|
||||
shipping.mkdir(parents=True)
|
||||
for name in ("CaravanSandWitch.exe", ".droiddeck-launch.bat"):
|
||||
(caravan / name).touch()
|
||||
(shipping / "CaravanSandWitch-Win64-Shipping.exe").touch()
|
||||
cyberpunk = Path(tmp) / "Cyberpunk 2077"
|
||||
(cyberpunk / "bin/x64").mkdir(parents=True)
|
||||
for name in ("REDprelauncher.exe", "bin/x64/Cyberpunk2077.exe"):
|
||||
(cyberpunk / name).touch()
|
||||
robocop = Path(tmp) / "RoboCop Rogue City"
|
||||
(robocop / "RoboCop/Binaries/Win64").mkdir(parents=True)
|
||||
for name in ("RoboCop.exe", "RoboCop/Binaries/Win64/RoboCop-Win64-Shipping.exe"):
|
||||
(robocop / name).touch()
|
||||
games = [caravan / "CaravanSandWitch.exe", caravan / ".droiddeck-launch.bat",
|
||||
shipping / "CaravanSandWitch-Win64-Shipping.exe",
|
||||
robocop / "RoboCop.exe", robocop / "RoboCop/Binaries/Win64/RoboCop-Win64-Shipping.exe",
|
||||
cyberpunk / "REDprelauncher.exe", cyberpunk / "bin/x64/Cyberpunk2077.exe"]
|
||||
for exe in games:
|
||||
env, extra, notes = MODULE["engine_fixes"](str(exe), [])
|
||||
self.assertEqual((env, extra), ({"VKD3D_FEATURE_LEVEL": "12_1"}, []), exe)
|
||||
self.assertTrue(notes)
|
||||
config = {"version": 1, "shared": {"VKD3D_FEATURE_LEVEL": "12_2"}}
|
||||
self.assertEqual(MODULE["apply_config"]({}, config, "1582650", env)["VKD3D_FEATURE_LEVEL"], "12_1")
|
||||
config["games"] = {"1582650": {"VKD3D_FEATURE_LEVEL": "12_2"}}
|
||||
self.assertEqual(MODULE["apply_config"]({}, config, "1582650", env)["VKD3D_FEATURE_LEVEL"], "12_2")
|
||||
other = Path(tmp) / "Other/Binaries/Win64"
|
||||
other.mkdir(parents=True)
|
||||
(other / "Other-Win64-Shipping.exe").touch()
|
||||
self.assertEqual(MODULE["engine_fixes"](str(other / "Other-Win64-Shipping.exe"), []), ({}, [], []))
|
||||
witcher = Path(tmp) / "The Witcher 3"
|
||||
witcher.mkdir()
|
||||
(witcher / "REDprelauncher.exe").touch()
|
||||
self.assertNotIn("VKD3D_FEATURE_LEVEL", MODULE["engine_fixes"](str(witcher / "REDprelauncher.exe"), [])[0])
|
||||
|
||||
def test_unity_players_keep_tso_over_the_preset(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
def game(*names):
|
||||
for name in names:
|
||||
(Path(tmp) / name).parent.mkdir(parents=True, exist_ok=True)
|
||||
(Path(tmp) / name).touch()
|
||||
return str(Path(tmp) / names[0])
|
||||
|
||||
il2cpp = game("Megabonk/Megabonk.x86_64", "Megabonk/UnityPlayer.so", "Megabonk/GameAssembly.so")
|
||||
mono = game("Mono/Game.x86_64", "Mono/UnityPlayer.so")
|
||||
windows = game("Crab Game/Crab Game.exe", "Crab Game/UnityPlayer.dll", "Crab Game/GameAssembly.dll")
|
||||
windows_mono = game("RoR2/Risk of Rain 2.exe", "RoR2/UnityPlayer.dll", "RoR2/MonoBleedingEdge/mono-2.0-bdwgc.dll")
|
||||
for exe in (il2cpp, mono, windows, windows_mono):
|
||||
env, extra, notes = MODULE["engine_fixes"](exe, [])
|
||||
self.assertEqual((env, extra, notes), ({"FEX_TSOENABLED": "1"}, [], ["Unity: FEX with TSO"]))
|
||||
performance = {"version": 1, "shared": {"FEX_TSOENABLED": "0", "FEX_VECTORTSOENABLED": "0"}}
|
||||
result = MODULE["apply_config"]({}, performance, "3405340", env)
|
||||
self.assertEqual((result["FEX_TSOENABLED"], result["FEX_VECTORTSOENABLED"]), ("1", "0"))
|
||||
performance["games"] = {"3405340": {"FEX_TSOENABLED": "0"}}
|
||||
self.assertEqual(MODULE["apply_config"]({}, performance, "3405340", env)["FEX_TSOENABLED"], "0")
|
||||
|
||||
def test_a_new_fix_only_needs_registering(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
(Path(tmp) / "Game.exe").touch()
|
||||
@@ -1278,6 +1371,52 @@ class DirectAudioPrefixTest(unittest.TestCase):
|
||||
self.assertIsNone(self.link("system32"))
|
||||
|
||||
|
||||
class UbisoftOverlayTest(unittest.TestCase):
|
||||
SETTINGS = (
|
||||
"language:\n code: en-US\n"
|
||||
"overlay:\n enabled: true\n forceunhookgame: false\n fps_enabled: false\n warning_enabled: true\n"
|
||||
"patchTrigger:\n source: USER_RESTART\n"
|
||||
)
|
||||
|
||||
def test_the_overlay_and_its_prompt_are_turned_off_and_the_rest_is_kept(self):
|
||||
got = MODULE["overlay_off"](self.SETTINGS)
|
||||
self.assertEqual(got, self.SETTINGS.replace("enabled: true", "enabled: false"))
|
||||
self.assertEqual(MODULE["overlay_off"](got), got)
|
||||
|
||||
def test_missing_keys_or_section_are_added(self):
|
||||
self.assertEqual(MODULE["overlay_off"]("overlay:\n fps_enabled: true\nmisc:\n a: 1\n"),
|
||||
"overlay:\n fps_enabled: true\n enabled: false\n warning_enabled: false\nmisc:\n a: 1\n")
|
||||
self.assertEqual(MODULE["overlay_off"](""), "overlay:\n enabled: false\n warning_enabled: false\n")
|
||||
|
||||
def test_blank_lines_inside_the_overlay_section_do_not_end_it(self):
|
||||
text = "overlay:\n enabled: true\n\n warning_enabled: true\n\nmisc:\n a: 1\n"
|
||||
self.assertEqual(MODULE["overlay_off"](text), text.replace("true", "false"))
|
||||
self.assertEqual(MODULE["overlay_off"]("overlay:\n fps_enabled: true\n\nmisc:\n a: 1\n"),
|
||||
"overlay:\n fps_enabled: true\n enabled: false\n warning_enabled: false\n\nmisc:\n a: 1\n")
|
||||
|
||||
def test_an_annotated_overlay_header_is_the_same_section(self):
|
||||
self.assertEqual(MODULE["overlay_off"]("overlay: # in-game\n enabled: true\n"),
|
||||
"overlay: # in-game\n enabled: false\n warning_enabled: false\n")
|
||||
|
||||
def test_only_prefixes_with_ubisoft_connect_are_touched(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
prefix = Path(tmp) / "447040/pfx"
|
||||
env = {"STEAM_COMPAT_DATA_PATH": str(prefix.parent)}
|
||||
settings = prefix / MODULE["UBISOFT_SETTINGS"]
|
||||
prefix.mkdir(parents=True)
|
||||
MODULE["ubisoft_overlay_off"](env)
|
||||
self.assertFalse(settings.exists())
|
||||
(prefix / MODULE["UBISOFT_LAUNCHER"]).mkdir(parents=True)
|
||||
MODULE["ubisoft_overlay_off"](env)
|
||||
self.assertEqual(settings.read_text(), "overlay:\n enabled: false\n warning_enabled: false\n")
|
||||
settings.write_text(self.SETTINGS)
|
||||
settings.chmod(0o644)
|
||||
MODULE["ubisoft_overlay_off"](env)
|
||||
self.assertEqual(settings.read_text(), self.SETTINGS.replace("enabled: true", "enabled: false"))
|
||||
self.assertEqual(settings.stat().st_mode & 0o777, 0o644)
|
||||
self.assertEqual(sorted(p.name for p in settings.parent.iterdir()), ["settings.yaml"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
#include <assert.h>
|
||||
#include <errno.h>
|
||||
#include <pthread.h>
|
||||
#include <stdarg.h>
|
||||
#include <stdatomic.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <sys/mman.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "../../app/src/main/cpp/adrenotools/src/hook/kgsl.h"
|
||||
#include "../../app/src/main/cpp/waylandcomp/src/gpu_clock_pin.h"
|
||||
|
||||
enum { NONE, OPEN, DEVICE, CONTEXT, CONSTRAINT, MEMORY, MAP, SYNC, SUBMIT, THREAD, WAIT };
|
||||
static atomic_int failure, descriptors, contexts, memories, mappings, submissions, waits;
|
||||
static atomic_bool timeout_wait;
|
||||
static bool legacy_core;
|
||||
static uint32_t commands[1024];
|
||||
|
||||
int __android_log_print(int priority, const char *tag, const char *format, ...) {
|
||||
(void)priority; (void)tag; (void)format;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int __wrap_open(const char *path, int flags, ...) {
|
||||
(void)flags;
|
||||
assert(!strcmp(path, "/dev/kgsl-3d0"));
|
||||
if (atomic_load(&failure) == OPEN) { errno = EACCES; return -1; }
|
||||
assert(atomic_fetch_add(&descriptors, 1) == 0);
|
||||
return 91;
|
||||
}
|
||||
|
||||
int __wrap_close(int fd) {
|
||||
assert(fd == 91);
|
||||
assert(atomic_fetch_sub(&descriptors, 1) == 1);
|
||||
errno = EBADF;
|
||||
return 0;
|
||||
}
|
||||
|
||||
void *__wrap_mmap(void *address, size_t size, int protection, int flags, int fd, off_t offset) {
|
||||
(void)address; (void)protection; (void)flags;
|
||||
assert(fd == 91 && size == sizeof(commands) && offset == (23 << 12));
|
||||
if (atomic_load(&failure) == MAP) { errno = EACCES; return MAP_FAILED; }
|
||||
assert(atomic_fetch_add(&mappings, 1) == 0);
|
||||
return commands;
|
||||
}
|
||||
|
||||
int __wrap_munmap(void *address, size_t size) {
|
||||
assert(address == commands && size == sizeof(commands));
|
||||
assert(atomic_fetch_sub(&mappings, 1) == 1);
|
||||
return 0;
|
||||
}
|
||||
|
||||
#ifdef __ANDROID__
|
||||
int __wrap_ioctl(int fd, int request, ...) {
|
||||
#else
|
||||
int __wrap_ioctl(int fd, unsigned long request, ...) {
|
||||
#endif
|
||||
assert(fd == 91);
|
||||
va_list args;
|
||||
va_start(args, request);
|
||||
void *arg = va_arg(args, void *);
|
||||
va_end(args);
|
||||
int step = NONE;
|
||||
switch ((unsigned int)request) {
|
||||
case IOCTL_KGSL_DEVICE_GETPROPERTY: step = DEVICE; break;
|
||||
case IOCTL_KGSL_DRAWCTXT_CREATE: step = CONTEXT; break;
|
||||
case IOCTL_KGSL_SETPROPERTY: step = CONSTRAINT; break;
|
||||
case IOCTL_KGSL_GPUMEM_ALLOC_ID: step = MEMORY; break;
|
||||
case IOCTL_KGSL_GPUMEM_SYNC_CACHE: step = SYNC; break;
|
||||
case IOCTL_KGSL_GPU_COMMAND: step = SUBMIT; break;
|
||||
case IOCTL_KGSL_DEVICE_WAITTIMESTAMP_CTXTID: step = WAIT; break;
|
||||
}
|
||||
if (step && atomic_load(&failure) == step) { errno = EACCES; return -1; }
|
||||
switch ((unsigned int)request) {
|
||||
case IOCTL_KGSL_DEVICE_GETPROPERTY: {
|
||||
struct kgsl_device_getproperty *property = arg;
|
||||
assert(property->type == KGSL_PROP_DEVICE_INFO);
|
||||
((struct kgsl_devinfo *)property->value)->chip_id = legacy_core ? 0x04030000 : 0x07030000;
|
||||
break;
|
||||
}
|
||||
case IOCTL_KGSL_DRAWCTXT_CREATE: {
|
||||
struct kgsl_drawctxt_create *context = arg;
|
||||
assert(context->flags & KGSL_CONTEXT_PWR_CONSTRAINT);
|
||||
context->drawctxt_id = 17;
|
||||
atomic_fetch_add(&contexts, 1);
|
||||
break;
|
||||
}
|
||||
case IOCTL_KGSL_SETPROPERTY: {
|
||||
struct kgsl_device_getproperty *property = arg;
|
||||
assert(property->type == KGSL_PROP_PWR_CONSTRAINT);
|
||||
struct kgsl_device_constraint *constraint = property->value;
|
||||
assert(constraint->context_id == 17 && constraint->type == KGSL_CONSTRAINT_PWRLEVEL);
|
||||
assert(((struct kgsl_device_constraint_pwrlevel *)constraint->data)->level == KGSL_CONSTRAINT_PWR_MAX);
|
||||
break;
|
||||
}
|
||||
case IOCTL_KGSL_GPUMEM_ALLOC_ID: {
|
||||
struct kgsl_gpumem_alloc_id *memory = arg;
|
||||
memory->id = 23; memory->gpuaddr = 0x100000; memory->mmapsize = sizeof(commands);
|
||||
atomic_fetch_add(&memories, 1);
|
||||
break;
|
||||
}
|
||||
case IOCTL_KGSL_GPUMEM_SYNC_CACHE:
|
||||
assert(((struct kgsl_gpumem_sync_cache *)arg)->op == KGSL_GPUMEM_CACHE_CLEAN);
|
||||
break;
|
||||
case IOCTL_KGSL_GPU_COMMAND: {
|
||||
struct kgsl_gpu_command *command = arg;
|
||||
struct kgsl_command_object *object = (void *)(uintptr_t)command->cmdlist;
|
||||
assert(command->context_id == 17 && command->numcmds == 1);
|
||||
assert(command->flags & KGSL_CMDBATCH_PWR_CONSTRAINT);
|
||||
assert(object->id == 23 && object->gpuaddr == 0x100000 && object->size == 8);
|
||||
assert(commands[0] == (legacy_core ? 0xc0001000 : 0x70100001) && commands[1] == 0);
|
||||
command->timestamp = atomic_fetch_add(&submissions, 1) + 1;
|
||||
break;
|
||||
}
|
||||
case IOCTL_KGSL_DEVICE_WAITTIMESTAMP_CTXTID:
|
||||
atomic_fetch_add(&waits, 1);
|
||||
if (atomic_load(&timeout_wait)) { errno = ETIMEDOUT; return -1; }
|
||||
break;
|
||||
case IOCTL_KGSL_DRAWCTXT_DESTROY:
|
||||
assert(atomic_fetch_sub(&contexts, 1) == 1);
|
||||
break;
|
||||
case IOCTL_KGSL_GPUMEM_FREE_ID:
|
||||
assert(atomic_fetch_sub(&memories, 1) == 1);
|
||||
break;
|
||||
default: assert(!"unexpected ioctl");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int __real_pthread_create(pthread_t *, const pthread_attr_t *, void *(*)(void *), void *);
|
||||
int __wrap_pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start)(void *), void *arg) {
|
||||
if (atomic_load(&failure) == THREAD) return EAGAIN;
|
||||
return __real_pthread_create(thread, attr, start, arg);
|
||||
}
|
||||
|
||||
static void assert_released(void) {
|
||||
assert(!atomic_load(&descriptors) && !atomic_load(&contexts));
|
||||
assert(!atomic_load(&memories) && !atomic_load(&mappings));
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
assert(gpu_clock_pin_set(false));
|
||||
assert_released();
|
||||
legacy_core = true;
|
||||
assert(gpu_clock_pin_set(true));
|
||||
assert(gpu_clock_pin_set(false));
|
||||
assert_released();
|
||||
legacy_core = false;
|
||||
for (int step = OPEN; step <= THREAD; ++step) {
|
||||
atomic_store(&failure, step);
|
||||
assert(!gpu_clock_pin_set(true));
|
||||
assert(errno == (step == THREAD ? EAGAIN : EACCES));
|
||||
assert_released();
|
||||
}
|
||||
atomic_store(&failure, NONE);
|
||||
atomic_store(&submissions, 0);
|
||||
assert(gpu_clock_pin_set(true));
|
||||
assert(gpu_clock_pin_set(true));
|
||||
for (int i = 0; i < 100 && atomic_load(&submissions) < 2; ++i) usleep(10000);
|
||||
assert(atomic_load(&submissions) > 1);
|
||||
assert(gpu_clock_pin_set(false));
|
||||
assert(gpu_clock_pin_set(false));
|
||||
assert_released();
|
||||
|
||||
atomic_store(&timeout_wait, true);
|
||||
atomic_store(&submissions, 0);
|
||||
atomic_store(&waits, 0);
|
||||
assert(gpu_clock_pin_set(true));
|
||||
for (int i = 0; i < 100 && atomic_load(&waits) < 2; ++i) usleep(10000);
|
||||
assert(atomic_load(&waits) >= 2);
|
||||
assert(atomic_load(&submissions) == 1);
|
||||
assert(gpu_clock_pin_set(false));
|
||||
assert_released();
|
||||
atomic_store(&timeout_wait, false);
|
||||
|
||||
atomic_store(&failure, WAIT);
|
||||
assert(gpu_clock_pin_set(true));
|
||||
for (int i = 0; i < 100 && atomic_load(&descriptors); ++i) usleep(10000);
|
||||
assert_released();
|
||||
atomic_store(&failure, NONE);
|
||||
assert(gpu_clock_pin_set(true));
|
||||
assert(gpu_clock_pin_set(false));
|
||||
assert_released();
|
||||
puts("gpu clock pin: failure cleanup, renewal, bounded queue and restart passed");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import pathlib
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
class GpuClockPinTest(unittest.TestCase):
|
||||
@unittest.skipUnless(sys.platform.startswith('linux') and shutil.which('cc'), 'requires a Linux C compiler')
|
||||
def test_constraint_lifecycle(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
directory = pathlib.Path(tmp)
|
||||
(directory / 'android').mkdir()
|
||||
(directory / 'android/log.h').write_text(
|
||||
'#define ANDROID_LOG_WARN 5\n'
|
||||
'int __android_log_print(int, const char *, const char *, ...);\n')
|
||||
binary = directory / 'gpu-clock-pin-test'
|
||||
subprocess.run([
|
||||
'cc', '-std=c11', '-D_DEFAULT_SOURCE', '-D__user=', '-Wall', '-Wextra', '-Werror',
|
||||
'-I', str(directory), '-pthread',
|
||||
str(ROOT / 'tools/tests/test_gpu_clock_pin.c'),
|
||||
str(ROOT / 'app/src/main/cpp/waylandcomp/src/gpu_clock_pin.c'),
|
||||
'-Wl,--wrap=open,--wrap=close,--wrap=mmap,--wrap=munmap,--wrap=ioctl,--wrap=pthread_create',
|
||||
'-o', str(binary),
|
||||
], check=True)
|
||||
subprocess.run([str(binary)], check=True, timeout=10)
|
||||
@@ -0,0 +1,580 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
|
||||
|
||||
NTDLL = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <signal.h>
|
||||
#include <string.h>
|
||||
|
||||
int install_handler(int sig, void (*fn)(int, siginfo_t *, void *), void **seen) {
|
||||
struct sigaction sa, old;
|
||||
memset(&sa, 0, sizeof(sa));
|
||||
sa.sa_sigaction = fn;
|
||||
sa.sa_flags = SA_SIGINFO | SA_RESTART;
|
||||
sigemptyset(&sa.sa_mask);
|
||||
if (sigaction(sig, &sa, NULL) != 0) return -1;
|
||||
if (sigaction(sig, NULL, &old) != 0) return -1;
|
||||
*seen = (void *)old.sa_sigaction;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int install_oneshot(int sig, void (*fn)(int, siginfo_t *, void *)) {
|
||||
struct sigaction sa;
|
||||
memset(&sa, 0, sizeof(sa));
|
||||
sa.sa_sigaction = fn;
|
||||
sa.sa_flags = SA_SIGINFO | SA_RESTART | SA_RESETHAND;
|
||||
sigemptyset(&sa.sa_mask);
|
||||
return sigaction(sig, &sa, NULL);
|
||||
}
|
||||
"""
|
||||
|
||||
PROGRAM = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <linux/ioctl.h>
|
||||
#include <pthread.h>
|
||||
#include <semaphore.h>
|
||||
#include <signal.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/wait.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
struct sem_args { uint32_t count, max; };
|
||||
struct mutex_args { uint32_t owner, count; };
|
||||
struct event_args { uint32_t manual, signaled; };
|
||||
struct wait_args { uint64_t timeout, objs; uint32_t count, index, flags, owner, alert, pad; };
|
||||
#define NT_CREATE_SEM _IOW('N', 0x80, struct sem_args)
|
||||
#define NT_SEM_RELEASE _IOWR('N', 0x81, uint32_t)
|
||||
#define NT_WAIT_ANY _IOWR('N', 0x82, struct wait_args)
|
||||
#define NT_WAIT_ALL _IOWR('N', 0x83, struct wait_args)
|
||||
#define NT_CREATE_MUTEX _IOW('N', 0x84, struct mutex_args)
|
||||
#define NT_MUTEX_UNLOCK _IOWR('N', 0x85, struct mutex_args)
|
||||
#define NT_MUTEX_KILL _IOW('N', 0x86, uint32_t)
|
||||
#define NT_CREATE_EVENT _IOW('N', 0x87, struct event_args)
|
||||
#define NT_EVENT_SET _IOR('N', 0x88, uint32_t)
|
||||
#define NT_EVENT_RESET _IOR('N', 0x89, uint32_t)
|
||||
#define NT_EVENT_PULSE _IOR('N', 0x8a, uint32_t)
|
||||
#define NT_SEM_READ _IOR('N', 0x8b, struct sem_args)
|
||||
#define NT_MUTEX_READ _IOR('N', 0x8c, struct mutex_args)
|
||||
#define NT_EVENT_READ _IOR('N', 0x8d, struct event_args)
|
||||
|
||||
int install_handler(int sig, void (*fn)(int, siginfo_t *, void *), void **seen);
|
||||
int install_oneshot(int sig, void (*fn)(int, siginfo_t *, void *));
|
||||
|
||||
static int dev, fails;
|
||||
#define CHECK(name, cond) do { if (!(cond)) { printf("FAIL %s line %d errno %d\n", name, __LINE__, errno); fails++; } } while (0)
|
||||
|
||||
static uint64_t mono_ns(int64_t delta_ms) {
|
||||
struct timespec t;
|
||||
clock_gettime(CLOCK_MONOTONIC, &t);
|
||||
return (uint64_t)t.tv_sec * 1000000000ull + (uint64_t)t.tv_nsec + (uint64_t)(delta_ms * 1000000);
|
||||
}
|
||||
|
||||
static int wait_on(unsigned long req, const int *objs, uint32_t count, uint32_t owner, int alert, uint64_t timeout, uint32_t *index) {
|
||||
struct wait_args w = {timeout, (uintptr_t)objs, count, 0xdead, 0, owner, (uint32_t)alert, 0};
|
||||
int r = ioctl(dev, req, &w);
|
||||
if (index) *index = w.index;
|
||||
return r < 0 ? errno : 0;
|
||||
}
|
||||
|
||||
static int event(int manual, int signaled) {
|
||||
struct event_args a = {(uint32_t)manual, (uint32_t)signaled};
|
||||
return ioctl(dev, NT_CREATE_EVENT, &a);
|
||||
}
|
||||
|
||||
static int sem(uint32_t count, uint32_t max) {
|
||||
struct sem_args a = {count, max};
|
||||
return ioctl(dev, NT_CREATE_SEM, &a);
|
||||
}
|
||||
|
||||
static int mutex(uint32_t owner, uint32_t count) {
|
||||
struct mutex_args a = {owner, count};
|
||||
return ioctl(dev, NT_CREATE_MUTEX, &a);
|
||||
}
|
||||
|
||||
static uint32_t prev_of(int fd, unsigned long req, uint32_t in) {
|
||||
uint32_t v = in;
|
||||
if (ioctl(fd, req, &v) < 0) return 0xffffffff;
|
||||
return v;
|
||||
}
|
||||
|
||||
static void semaphores(void) {
|
||||
struct sem_args bad = {3, 2}, r;
|
||||
CHECK("sem_create_invalid", ioctl(dev, NT_CREATE_SEM, &bad) < 0 && errno == EINVAL);
|
||||
int s = sem(2, 2);
|
||||
CHECK("sem_create", s >= 0);
|
||||
uint32_t idx;
|
||||
CHECK("sem_wait1", wait_on(NT_WAIT_ANY, &s, 1, 1, 0, 0, &idx) == 0 && idx == 0);
|
||||
CHECK("sem_wait2", wait_on(NT_WAIT_ANY, &s, 1, 1, 0, 0, &idx) == 0);
|
||||
CHECK("sem_empty", wait_on(NT_WAIT_ANY, &s, 1, 1, 0, 0, NULL) == ETIMEDOUT);
|
||||
CHECK("sem_release_prev", prev_of(s, NT_SEM_RELEASE, 1) == 0);
|
||||
CHECK("sem_overflow", prev_of(s, NT_SEM_RELEASE, 2) == 0xffffffff && errno == EOVERFLOW);
|
||||
CHECK("sem_read", ioctl(s, NT_SEM_READ, &r) == 0 && r.count == 1 && r.max == 2);
|
||||
close(s);
|
||||
}
|
||||
|
||||
static void mutexes(void) {
|
||||
struct mutex_args bad = {0, 1}, r, u;
|
||||
CHECK("mutex_create_invalid", ioctl(dev, NT_CREATE_MUTEX, &bad) < 0 && errno == EINVAL);
|
||||
int m = mutex(0, 0);
|
||||
uint32_t idx;
|
||||
CHECK("mutex_owner_zero", wait_on(NT_WAIT_ANY, &m, 1, 0, 0, 0, NULL) == EINVAL);
|
||||
CHECK("mutex_take", wait_on(NT_WAIT_ANY, &m, 1, 7, 0, 0, &idx) == 0 && idx == 0);
|
||||
CHECK("mutex_recurse", wait_on(NT_WAIT_ANY, &m, 1, 7, 0, 0, NULL) == 0);
|
||||
CHECK("mutex_other", wait_on(NT_WAIT_ANY, &m, 1, 8, 0, 0, NULL) == ETIMEDOUT);
|
||||
CHECK("mutex_read", ioctl(m, NT_MUTEX_READ, &r) == 0 && r.owner == 7 && r.count == 2);
|
||||
u = (struct mutex_args){8, 0};
|
||||
CHECK("mutex_unlock_eperm", ioctl(m, NT_MUTEX_UNLOCK, &u) < 0 && errno == EPERM);
|
||||
u = (struct mutex_args){0, 0};
|
||||
CHECK("mutex_unlock_einval", ioctl(m, NT_MUTEX_UNLOCK, &u) < 0 && errno == EINVAL);
|
||||
u = (struct mutex_args){7, 0};
|
||||
CHECK("mutex_unlock_prev", ioctl(m, NT_MUTEX_UNLOCK, &u) == 0 && u.count == 2);
|
||||
uint32_t who = 8;
|
||||
CHECK("mutex_kill_eperm", ioctl(m, NT_MUTEX_KILL, &who) < 0 && errno == EPERM);
|
||||
who = 7;
|
||||
CHECK("mutex_kill", ioctl(m, NT_MUTEX_KILL, &who) == 0);
|
||||
CHECK("mutex_read_dead", ioctl(m, NT_MUTEX_READ, &r) < 0 && errno == EOWNERDEAD && r.owner == 0 && r.count == 0);
|
||||
CHECK("mutex_abandoned", wait_on(NT_WAIT_ANY, &m, 1, 9, 0, 0, &idx) == EOWNERDEAD && idx == 0);
|
||||
CHECK("mutex_after_abandon", ioctl(m, NT_MUTEX_READ, &r) == 0 && r.owner == 9 && r.count == 1);
|
||||
close(m);
|
||||
}
|
||||
|
||||
static void events(void) {
|
||||
int a = event(0, 1), m = event(1, 0);
|
||||
struct event_args r;
|
||||
CHECK("auto_take", wait_on(NT_WAIT_ANY, &a, 1, 1, 0, 0, NULL) == 0);
|
||||
CHECK("auto_consumed", wait_on(NT_WAIT_ANY, &a, 1, 1, 0, 0, NULL) == ETIMEDOUT);
|
||||
CHECK("set_prev0", prev_of(m, NT_EVENT_SET, 0) == 0);
|
||||
CHECK("set_prev1", prev_of(m, NT_EVENT_SET, 0) == 1);
|
||||
CHECK("manual_kept", wait_on(NT_WAIT_ANY, &m, 1, 1, 0, 0, NULL) == 0 && wait_on(NT_WAIT_ANY, &m, 1, 1, 0, 0, NULL) == 0);
|
||||
CHECK("reset_prev", prev_of(m, NT_EVENT_RESET, 0) == 1);
|
||||
CHECK("pulse_prev", prev_of(m, NT_EVENT_PULSE, 0) == 0);
|
||||
CHECK("pulse_leaves_unsignaled", ioctl(m, NT_EVENT_READ, &r) == 0 && r.manual == 1 && r.signaled == 0);
|
||||
close(a);
|
||||
close(m);
|
||||
}
|
||||
|
||||
static void any_order(void) {
|
||||
int o[4] = {event(1, 0), sem(1, 5), event(1, 1), sem(0, 5)};
|
||||
int alert = event(0, 1);
|
||||
uint32_t idx;
|
||||
CHECK("any_lowest", wait_on(NT_WAIT_ANY, o, 4, 1, alert, 0, &idx) == 0 && idx == 1);
|
||||
CHECK("any_next", wait_on(NT_WAIT_ANY, o, 4, 1, alert, 0, &idx) == 0 && idx == 2);
|
||||
prev_of(o[2], NT_EVENT_RESET, 0);
|
||||
CHECK("any_alert", wait_on(NT_WAIT_ANY, o, 4, 1, alert, 0, &idx) == 0 && idx == 4);
|
||||
CHECK("any_alert_consumed", wait_on(NT_WAIT_ANY, o, 4, 1, alert, 0, NULL) == ETIMEDOUT);
|
||||
int dup[3] = {o[3], o[0], o[3]};
|
||||
prev_of(o[3], NT_SEM_RELEASE, 1);
|
||||
CHECK("any_duplicate_lowest", wait_on(NT_WAIT_ANY, dup, 3, 1, 0, 0, &idx) == 0 && idx == 0);
|
||||
int many[65];
|
||||
for (int i = 0; i < 65; i++) many[i] = o[0];
|
||||
CHECK("any_too_many", wait_on(NT_WAIT_ANY, many, 65, 1, 0, 0, NULL) == EINVAL);
|
||||
int badfd = 0;
|
||||
CHECK("any_invalid_fd", wait_on(NT_WAIT_ANY, &badfd, 1, 1, 0, 0, NULL) == EINVAL);
|
||||
CHECK("any_timeout", wait_on(NT_WAIT_ANY, o, 1, 1, 0, mono_ns(30), NULL) == ETIMEDOUT);
|
||||
for (int i = 0; i < 4; i++) close(o[i]);
|
||||
close(alert);
|
||||
}
|
||||
|
||||
static void all_semantics(void) {
|
||||
int s = sem(1, 5), e = event(0, 0), m = mutex(0, 0);
|
||||
int o[3] = {s, e, m};
|
||||
struct sem_args sr;
|
||||
uint32_t idx;
|
||||
CHECK("all_not_ready", wait_on(NT_WAIT_ALL, o, 3, 4, 0, 0, NULL) == ETIMEDOUT);
|
||||
CHECK("all_untouched", ioctl(s, NT_SEM_READ, &sr) == 0 && sr.count == 1);
|
||||
prev_of(e, NT_EVENT_SET, 0);
|
||||
CHECK("all_ready", wait_on(NT_WAIT_ALL, o, 3, 4, 0, 0, &idx) == 0 && idx == 0);
|
||||
CHECK("all_took_sem", ioctl(s, NT_SEM_READ, &sr) == 0 && sr.count == 0);
|
||||
int dup[2] = {s, s};
|
||||
CHECK("all_duplicate", wait_on(NT_WAIT_ALL, dup, 2, 4, 0, 0, NULL) == EINVAL);
|
||||
int alert = event(1, 1);
|
||||
CHECK("all_alert", wait_on(NT_WAIT_ALL, o, 3, 4, alert, 0, &idx) == 0 && idx == 3);
|
||||
close(s);
|
||||
close(e);
|
||||
close(m);
|
||||
close(alert);
|
||||
}
|
||||
|
||||
static int wake_obj;
|
||||
static uint32_t wake_index;
|
||||
static int wake_ret;
|
||||
static void *waiter(void *p) {
|
||||
int all = (int)(intptr_t)p;
|
||||
int objs[2] = {wake_obj, wake_obj + 0};
|
||||
wake_ret = wait_on(all ? NT_WAIT_ALL : NT_WAIT_ANY, objs, 1, 3, 0, UINT64_MAX, &wake_index);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static void cross_thread(void) {
|
||||
wake_obj = event(0, 0);
|
||||
pthread_t t;
|
||||
pthread_create(&t, NULL, waiter, NULL);
|
||||
usleep(30000);
|
||||
prev_of(wake_obj, NT_EVENT_SET, 0);
|
||||
pthread_join(t, NULL);
|
||||
CHECK("thread_wake", wake_ret == 0 && wake_index == 0);
|
||||
struct event_args r;
|
||||
CHECK("thread_auto_reset", ioctl(wake_obj, NT_EVENT_READ, &r) == 0 && r.signaled == 0);
|
||||
close(wake_obj);
|
||||
int s = sem(0, 10);
|
||||
wake_obj = s;
|
||||
pthread_t ts[3];
|
||||
for (int i = 0; i < 3; i++) pthread_create(&ts[i], NULL, waiter, NULL);
|
||||
usleep(30000);
|
||||
CHECK("sem_release_three", prev_of(s, NT_SEM_RELEASE, 3) == 0);
|
||||
for (int i = 0; i < 3; i++) pthread_join(ts[i], NULL);
|
||||
struct sem_args sr;
|
||||
CHECK("sem_all_taken", ioctl(s, NT_SEM_READ, &sr) == 0 && sr.count == 0);
|
||||
close(s);
|
||||
}
|
||||
|
||||
static void cross_process(void) {
|
||||
int sv[2];
|
||||
CHECK("socketpair", socketpair(AF_UNIX, SOCK_STREAM, 0, sv) == 0);
|
||||
int inherited = event(0, 0);
|
||||
pid_t pid = fork();
|
||||
if (pid == 0) {
|
||||
uint32_t idx;
|
||||
int r1 = wait_on(NT_WAIT_ANY, &inherited, 1, 5, 0, mono_ns(5000), &idx);
|
||||
char c;
|
||||
struct iovec io = {&c, 1};
|
||||
char cbuf[CMSG_SPACE(sizeof(int))];
|
||||
struct msghdr msg = {0};
|
||||
msg.msg_iov = &io;
|
||||
msg.msg_iovlen = 1;
|
||||
msg.msg_control = cbuf;
|
||||
msg.msg_controllen = sizeof(cbuf);
|
||||
int got = -1;
|
||||
if (recvmsg(sv[1], &msg, 0) == 1) memcpy(&got, CMSG_DATA(CMSG_FIRSTHDR(&msg)), sizeof(int));
|
||||
int r2 = wait_on(NT_WAIT_ANY, &got, 1, 5, 0, mono_ns(5000), NULL);
|
||||
_exit(r1 == 0 && r2 == 0 ? 0 : 1);
|
||||
}
|
||||
usleep(30000);
|
||||
prev_of(inherited, NT_EVENT_SET, 0);
|
||||
int sent = sem(0, 1);
|
||||
char c = 'x';
|
||||
struct iovec io = {&c, 1};
|
||||
char cbuf[CMSG_SPACE(sizeof(int))];
|
||||
struct msghdr msg = {0};
|
||||
msg.msg_iov = &io;
|
||||
msg.msg_iovlen = 1;
|
||||
msg.msg_control = cbuf;
|
||||
msg.msg_controllen = sizeof(cbuf);
|
||||
struct cmsghdr *cm = CMSG_FIRSTHDR(&msg);
|
||||
cm->cmsg_level = SOL_SOCKET;
|
||||
cm->cmsg_type = SCM_RIGHTS;
|
||||
cm->cmsg_len = CMSG_LEN(sizeof(int));
|
||||
memcpy(CMSG_DATA(cm), &sent, sizeof(int));
|
||||
sendmsg(sv[0], &msg, 0);
|
||||
usleep(30000);
|
||||
prev_of(sent, NT_SEM_RELEASE, 1);
|
||||
int status = 0;
|
||||
waitpid(pid, &status, 0);
|
||||
CHECK("process_wake", WIFEXITED(status) && WEXITSTATUS(status) == 0);
|
||||
close(inherited);
|
||||
close(sent);
|
||||
close(sv[0]);
|
||||
close(sv[1]);
|
||||
}
|
||||
|
||||
static int ping_obj, pong_obj, stress_sem;
|
||||
static void *stress_ponger(void *p) {
|
||||
long n = (long)p;
|
||||
uint32_t v;
|
||||
for (long i = 0; i < n; i++) {
|
||||
if (wait_on(NT_WAIT_ANY, &ping_obj, 1, 21, 0, UINT64_MAX, NULL) != 0) return (void *)1;
|
||||
ioctl(pong_obj, NT_EVENT_SET, &v);
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
static void *stress_hammer(void *p) {
|
||||
long n = (long)p;
|
||||
for (long i = 0; i < n; i++) {
|
||||
if (wait_on(NT_WAIT_ANY, &stress_sem, 1, 22, 0, UINT64_MAX, NULL) != 0) return (void *)1;
|
||||
uint32_t c = 1;
|
||||
ioctl(stress_sem, NT_SEM_RELEASE, &c);
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static void stress(void) {
|
||||
long rounds = 20000;
|
||||
ping_obj = event(0, 0);
|
||||
pong_obj = event(0, 0);
|
||||
pthread_t t;
|
||||
void *bad = NULL;
|
||||
pthread_create(&t, NULL, stress_ponger, (void *)rounds);
|
||||
uint32_t v;
|
||||
int ok = 1;
|
||||
for (long i = 0; i < rounds && ok; i++) {
|
||||
ioctl(ping_obj, NT_EVENT_SET, &v);
|
||||
ok = wait_on(NT_WAIT_ANY, &pong_obj, 1, 20, 0, UINT64_MAX, NULL) == 0;
|
||||
}
|
||||
pthread_join(t, &bad);
|
||||
CHECK("stress_pingpong", ok && bad == NULL);
|
||||
stress_sem = sem(1, 1);
|
||||
pthread_t th[4];
|
||||
for (int i = 0; i < 4; i++) pthread_create(&th[i], NULL, stress_hammer, (void *)5000L);
|
||||
int hammer_ok = 1;
|
||||
for (int i = 0; i < 4; i++) {
|
||||
pthread_join(th[i], &bad);
|
||||
hammer_ok &= bad == NULL;
|
||||
}
|
||||
struct sem_args sr;
|
||||
CHECK("stress_contended", hammer_ok && ioctl(stress_sem, NT_SEM_READ, &sr) == 0 && sr.count == 1);
|
||||
close(ping_obj);
|
||||
close(pong_obj);
|
||||
close(stress_sem);
|
||||
}
|
||||
|
||||
static int busy_obj;
|
||||
static volatile int handled, stop_worker;
|
||||
static sem_t parked, unpark;
|
||||
static void reentrant(int sig, siginfo_t *si, void *uc) {
|
||||
(void)sig; (void)si; (void)uc;
|
||||
uint32_t v = 0;
|
||||
ioctl(busy_obj, NT_EVENT_SET, &v);
|
||||
handled++;
|
||||
}
|
||||
static void suspending(int sig, siginfo_t *si, void *uc) {
|
||||
(void)sig; (void)si; (void)uc;
|
||||
sem_post(&parked);
|
||||
while (sem_wait(&unpark) != 0) {}
|
||||
handled++;
|
||||
}
|
||||
static void *worker(void *p) {
|
||||
(void)p;
|
||||
uint32_t v;
|
||||
while (!stop_worker) {
|
||||
ioctl(busy_obj, NT_EVENT_SET, &v);
|
||||
wait_on(NT_WAIT_ANY, &busy_obj, 1, 11, 0, 0, NULL);
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static void signals(void) {
|
||||
void *seen = NULL;
|
||||
busy_obj = event(0, 0);
|
||||
CHECK("install_reentrant", install_handler(SIGUSR1, reentrant, &seen) == 0);
|
||||
CHECK("query_original", seen == (void *)reentrant);
|
||||
pthread_t w;
|
||||
stop_worker = 0;
|
||||
handled = 0;
|
||||
pthread_create(&w, NULL, worker, NULL);
|
||||
for (int i = 0; i < 2000; i++) {
|
||||
pthread_kill(w, SIGUSR1);
|
||||
if (i % 64 == 0) usleep(100);
|
||||
}
|
||||
usleep(20000);
|
||||
stop_worker = 1;
|
||||
pthread_join(w, NULL);
|
||||
CHECK("reentrant_ran", handled > 0);
|
||||
sem_init(&parked, 0, 0);
|
||||
sem_init(&unpark, 0, 0);
|
||||
CHECK("install_suspending", install_handler(SIGUSR1, suspending, &seen) == 0);
|
||||
stop_worker = 0;
|
||||
handled = 0;
|
||||
pthread_create(&w, NULL, worker, NULL);
|
||||
uint32_t v;
|
||||
for (int i = 0; i < 300; i++) {
|
||||
pthread_kill(w, SIGUSR1);
|
||||
while (sem_wait(&parked) != 0) {}
|
||||
ioctl(busy_obj, NT_EVENT_SET, &v);
|
||||
wait_on(NT_WAIT_ANY, &busy_obj, 1, 12, 0, 0, NULL);
|
||||
sem_post(&unpark);
|
||||
}
|
||||
stop_worker = 1;
|
||||
pthread_join(w, NULL);
|
||||
CHECK("suspend_ran", handled == 300);
|
||||
close(busy_obj);
|
||||
}
|
||||
|
||||
static volatile int burst_count;
|
||||
static void bursting(int sig, siginfo_t *si, void *uc) {
|
||||
(void)sig; (void)si; (void)uc;
|
||||
uint32_t v = 0;
|
||||
ioctl(busy_obj, NT_EVENT_SET, &v);
|
||||
__atomic_add_fetch(&burst_count, 1, __ATOMIC_RELAXED);
|
||||
}
|
||||
|
||||
static void bursts(void) {
|
||||
void *seen = NULL;
|
||||
busy_obj = event(0, 0);
|
||||
for (int s = 0; s < 8; s++) CHECK("install_burst", install_handler(SIGRTMIN + s, bursting, &seen) == 0);
|
||||
pthread_t w;
|
||||
stop_worker = 0;
|
||||
burst_count = 0;
|
||||
pthread_create(&w, NULL, worker, NULL);
|
||||
union sigval val = {0};
|
||||
int sent = 0;
|
||||
for (int i = 0; i < 400; i++) {
|
||||
for (int s = 0; s < 8; s++)
|
||||
if (pthread_sigqueue(w, SIGRTMIN + s, val) == 0) sent++;
|
||||
usleep(200);
|
||||
}
|
||||
for (int i = 0; i < 2000 && __atomic_load_n(&burst_count, __ATOMIC_RELAXED) < sent; i++) usleep(1000);
|
||||
stop_worker = 1;
|
||||
pthread_join(w, NULL);
|
||||
CHECK("burst_all_handled", burst_count == sent && sent > 0);
|
||||
close(busy_obj);
|
||||
}
|
||||
|
||||
static volatile int oneshot_count;
|
||||
static void oneshot(int sig, siginfo_t *si, void *uc) {
|
||||
(void)sig; (void)si; (void)uc;
|
||||
__atomic_add_fetch(&oneshot_count, 1, __ATOMIC_RELAXED);
|
||||
}
|
||||
|
||||
static void oneshots(void) {
|
||||
busy_obj = event(0, 0);
|
||||
pthread_t w;
|
||||
stop_worker = 0;
|
||||
oneshot_count = 0;
|
||||
pthread_create(&w, NULL, worker, NULL);
|
||||
int fired = 0;
|
||||
for (int i = 0; i < 300; i++) {
|
||||
if (install_oneshot(SIGWINCH, oneshot) != 0) break;
|
||||
int before = __atomic_load_n(&oneshot_count, __ATOMIC_RELAXED);
|
||||
pthread_kill(w, SIGWINCH);
|
||||
fired++;
|
||||
for (int j = 0; j < 2000 && __atomic_load_n(&oneshot_count, __ATOMIC_RELAXED) == before; j++) usleep(50);
|
||||
}
|
||||
stop_worker = 1;
|
||||
pthread_join(w, NULL);
|
||||
CHECK("oneshot_handlers_run", oneshot_count == fired && fired == 300);
|
||||
close(busy_obj);
|
||||
}
|
||||
|
||||
static int outer_obj, inner_obj, other_dev, other_obj;
|
||||
static volatile int nested_ok, nested_done, outer_done;
|
||||
static void nesting(int sig, siginfo_t *si, void *uc) {
|
||||
(void)sig; (void)si; (void)uc;
|
||||
uint32_t idx = 99;
|
||||
int ok = wait_on(NT_WAIT_ANY, &inner_obj, 1, 21, 0, mono_ns(50), &idx) == 0 && idx == 0;
|
||||
struct wait_args w = {mono_ns(2), (uintptr_t)&other_obj, 1, 0xdead, 0, 22, 0, 0};
|
||||
ok = ok && ioctl(other_dev, NT_WAIT_ANY, &w) < 0 && errno == ETIMEDOUT;
|
||||
nested_ok += ok;
|
||||
__atomic_store_n(&nested_done, 1, __ATOMIC_RELEASE);
|
||||
}
|
||||
static void *outer_waiter(void *p) {
|
||||
struct wait_args w = {mono_ns(3000), (uintptr_t)&outer_obj, 1, 99, 0, 23, 0, 0};
|
||||
int r;
|
||||
do { r = ioctl(dev, NT_WAIT_ANY, &w); } while (r < 0 && errno == EINTR);
|
||||
*(int *)p = r == 0 && w.index == 0;
|
||||
__atomic_store_n(&outer_done, 1, __ATOMIC_RELEASE);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static void nested_waits(void) {
|
||||
void *seen = NULL;
|
||||
other_dev = open("/dev/ntsync", O_RDWR | O_CLOEXEC);
|
||||
CHECK("second_device", other_dev >= 0);
|
||||
struct event_args ea = {0, 0};
|
||||
other_obj = ioctl(other_dev, NT_CREATE_EVENT, &ea);
|
||||
inner_obj = event(1, 1);
|
||||
CHECK("install_nesting", install_handler(SIGUSR2, nesting, &seen) == 0);
|
||||
int good = 0, early = 0;
|
||||
nested_ok = 0;
|
||||
for (int i = 0; i < 40; i++) {
|
||||
outer_obj = event(0, 0);
|
||||
int result = 0;
|
||||
pthread_t t;
|
||||
nested_done = outer_done = 0;
|
||||
pthread_create(&t, NULL, outer_waiter, &result);
|
||||
usleep(5000);
|
||||
pthread_kill(t, SIGUSR2);
|
||||
while (!__atomic_load_n(&nested_done, __ATOMIC_ACQUIRE)) usleep(200);
|
||||
usleep(5000);
|
||||
early += __atomic_load_n(&outer_done, __ATOMIC_ACQUIRE);
|
||||
uint32_t v = 0;
|
||||
ioctl(outer_obj, NT_EVENT_SET, &v);
|
||||
pthread_join(t, NULL);
|
||||
good += result;
|
||||
close(outer_obj);
|
||||
}
|
||||
CHECK("outer_wait_not_woken_by_nested_wait", early == 0);
|
||||
CHECK("outer_wait_survives_nested_waits", good == 40);
|
||||
CHECK("nested_waits_complete", nested_ok == 40);
|
||||
close(inner_obj);
|
||||
close(other_obj);
|
||||
close(other_dev);
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
alarm(60);
|
||||
dev = open("/dev/ntsync", O_RDWR | O_CLOEXEC);
|
||||
if (dev < 0) {
|
||||
printf("no device %d\n", errno);
|
||||
return 1;
|
||||
}
|
||||
semaphores();
|
||||
mutexes();
|
||||
events();
|
||||
any_order();
|
||||
all_semantics();
|
||||
cross_thread();
|
||||
cross_process();
|
||||
stress();
|
||||
signals();
|
||||
bursts();
|
||||
oneshots();
|
||||
nested_waits();
|
||||
printf("done fails=%d\n", fails);
|
||||
return fails != 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
class NtsyncPreloadTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
if not shutil.which("cc"):
|
||||
raise unittest.SkipTest("no compiler")
|
||||
cls.tmp = tempfile.TemporaryDirectory()
|
||||
tmp = Path(cls.tmp.name)
|
||||
(tmp / "ntdll.c").write_text(NTDLL)
|
||||
(tmp / "prog.c").write_text(PROGRAM)
|
||||
sources = sorted(str(p) for p in PRELOAD.glob("*.c"))
|
||||
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-Wall", "-pthread", "-o", str(tmp / "libblsession.so"), *sources, "-ldl"],
|
||||
check=True)
|
||||
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-o", str(tmp / "ntdll.so"), str(tmp / "ntdll.c")], check=True)
|
||||
subprocess.run(["cc", "-O1", "-pthread", "-o", str(tmp / "prog"), str(tmp / "prog.c"), str(tmp / "ntdll.so"),
|
||||
"-Wl,-rpath," + str(tmp)], check=True)
|
||||
cls.program = tmp / "prog"
|
||||
cls.preload = tmp / "libblsession.so"
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.tmp.cleanup()
|
||||
|
||||
def run_program(self):
|
||||
env = dict(os.environ, LD_PRELOAD=str(self.preload), BL_SYNC="1")
|
||||
return subprocess.run([str(self.program)], env=env, capture_output=True, text=True, timeout=90)
|
||||
|
||||
def test_emulation_matches_the_ntsync_driver(self):
|
||||
out = self.run_program()
|
||||
self.assertEqual(out.returncode, 0, out.stdout + out.stderr)
|
||||
self.assertIn("done fails=0", out.stdout)
|
||||
|
||||
def test_repeated_runs_stay_consistent(self):
|
||||
for _ in range(3):
|
||||
out = self.run_program()
|
||||
self.assertEqual(out.returncode, 0, out.stdout + out.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -66,6 +66,8 @@ static void send_toplevel_configure(struct surface *s) { (void)s; resizes++; }
|
||||
#define pointer_button(...) ((void)0)
|
||||
#define scroll_event(...) ((void)0)
|
||||
#define axis_event(...) ((void)0)
|
||||
#define stream_take(...) ((void)0)
|
||||
#define stream_forget_all(...) ((void)0)
|
||||
#define pointer_delta(...) ((void)0)
|
||||
#define deliver_touch(m) ((void)0)
|
||||
#define deliver_pointer(m) (pointers++)
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
import hashlib
|
||||
import http.server
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import socket
|
||||
import subprocess
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
FETCH = ROOT / 'tools/packs/fetch-verified.sh'
|
||||
|
||||
|
||||
class PackDownloadsTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
directory = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(directory.cleanup)
|
||||
self.root = Path(directory.name)
|
||||
self.cache = self.root / 'cache'
|
||||
self.cache.mkdir()
|
||||
self.destination = self.root / 'download'
|
||||
self.remote = self.root / 'remote'
|
||||
self.remote.write_bytes(b'verified input')
|
||||
self.checksum = hashlib.sha256(self.remote.read_bytes()).hexdigest()
|
||||
self.log = self.root / 'curl.log'
|
||||
tool = self.root / 'bin/curl'
|
||||
tool.parent.mkdir()
|
||||
tool.write_text('#!/usr/bin/env python3\nimport json,os,shutil,sys\n'
|
||||
'args=sys.argv[1:]\n'
|
||||
'with open(os.environ["CURL_LOG"],"a") as f: f.write(json.dumps(args)+"\\n")\n'
|
||||
'shutil.copyfile(os.environ["REMOTE"],args[args.index("-o")+1])\n')
|
||||
tool.chmod(0o755)
|
||||
self.env = dict(os.environ, DROIDDECK_PACK_CACHE=str(self.cache), CURL_LOG=str(self.log),
|
||||
REMOTE=str(self.remote), PATH=str(tool.parent) + os.pathsep + os.environ['PATH'])
|
||||
|
||||
def fetch(self, checksum=None, url='https://example.test/pinned', env=None):
|
||||
return subprocess.run(['bash', str(FETCH), url, checksum or self.checksum, str(self.destination)],
|
||||
env=env or self.env, capture_output=True, text=True)
|
||||
|
||||
def test_cold_download_then_warm_reuse_and_corruption_repair(self):
|
||||
self.assertEqual(self.fetch().returncode, 0)
|
||||
self.assertEqual(self.fetch().returncode, 0)
|
||||
self.assertEqual(len(self.log.read_text().splitlines()), 1)
|
||||
self.assertEqual(self.destination.read_bytes(), b'verified input')
|
||||
(self.cache / self.checksum).write_bytes(b'corrupt')
|
||||
self.assertEqual(self.fetch().returncode, 0)
|
||||
self.assertEqual(len(self.log.read_text().splitlines()), 2)
|
||||
self.assertEqual((self.cache / self.checksum).read_bytes(), b'verified input')
|
||||
|
||||
def test_directory_cache_entry_is_replaced_only_after_verification(self):
|
||||
entry = self.cache / self.checksum
|
||||
entry.mkdir()
|
||||
sentinel = entry / 'old-entry'
|
||||
sentinel.write_bytes(b'preserve until verified')
|
||||
self.remote.write_bytes(b'tampered download')
|
||||
self.assertNotEqual(self.fetch().returncode, 0)
|
||||
self.assertEqual(sentinel.read_bytes(), b'preserve until verified')
|
||||
self.assertFalse(self.destination.exists())
|
||||
self.remote.write_bytes(b'verified input')
|
||||
result = self.fetch()
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertTrue(entry.is_file())
|
||||
self.assertEqual(entry.read_bytes(), b'verified input')
|
||||
self.assertEqual(self.destination.read_bytes(), b'verified input')
|
||||
self.assertEqual(list(self.cache.iterdir()), [entry])
|
||||
self.assertEqual(self.fetch().returncode, 0)
|
||||
self.assertEqual(len(self.log.read_text().splitlines()), 2)
|
||||
|
||||
def test_changed_pin_cannot_reuse_old_bytes(self):
|
||||
self.assertEqual(self.fetch().returncode, 0)
|
||||
self.remote.write_bytes(b'new approved input')
|
||||
updated = hashlib.sha256(self.remote.read_bytes()).hexdigest()
|
||||
self.assertEqual(self.fetch(updated).returncode, 0)
|
||||
self.assertEqual(len(self.log.read_text().splitlines()), 2)
|
||||
self.assertEqual(self.destination.read_bytes(), b'new approved input')
|
||||
|
||||
def test_bad_download_is_not_cached_or_written(self):
|
||||
self.remote.write_bytes(b'tampered download')
|
||||
self.assertNotEqual(self.fetch().returncode, 0)
|
||||
self.assertFalse((self.cache / self.checksum).exists())
|
||||
self.assertFalse(self.destination.exists())
|
||||
self.assertEqual(list(self.cache.iterdir()), [])
|
||||
arguments = json.loads(self.log.read_text())
|
||||
self.assertIn('--retry-all-errors', arguments)
|
||||
self.assertIn('--max-time', arguments)
|
||||
self.assertIn('--retry-max-time', arguments)
|
||||
|
||||
def test_connection_reset_retries_then_verifies_real_download(self):
|
||||
if not shutil.which('curl'):
|
||||
self.skipTest('curl required for transport test')
|
||||
content = self.remote.read_bytes()
|
||||
attempts = []
|
||||
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
attempts.append(True)
|
||||
if len(attempts) == 1:
|
||||
self.connection.shutdown(socket.SHUT_RDWR)
|
||||
self.connection.close()
|
||||
return
|
||||
self.send_response(200)
|
||||
self.send_header('Content-Length', str(len(content)))
|
||||
self.end_headers()
|
||||
self.wfile.write(content)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
server = http.server.ThreadingHTTPServer(('127.0.0.1', 0), Handler)
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
try:
|
||||
env = dict(self.env, PATH=os.environ['PATH'])
|
||||
result = self.fetch(url=f'http://127.0.0.1:{server.server_port}/input', env=env)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertGreaterEqual(len(attempts), 2)
|
||||
self.assertEqual(self.destination.read_bytes(), content)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
thread.join()
|
||||
@@ -0,0 +1,187 @@
|
||||
import copy
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tarfile
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
SPEC = importlib.util.spec_from_file_location('preload_snapshots', Path(__file__).resolve().parents[1] / 'components/preloads.py')
|
||||
snapshots = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(snapshots)
|
||||
|
||||
|
||||
def archive(files):
|
||||
stream = io.BytesIO()
|
||||
with tarfile.open(fileobj=stream, mode='w:gz') as tar:
|
||||
for name, content in files.items():
|
||||
entry = tarfile.TarInfo(name)
|
||||
entry.size = len(content)
|
||||
tar.addfile(entry, io.BytesIO(content))
|
||||
return stream.getvalue()
|
||||
|
||||
|
||||
class PreloadSnapshotTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
directory = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(directory.cleanup)
|
||||
self.root = Path(directory.name)
|
||||
# Real repository inputs exercise the transitive include walker and build recipe.
|
||||
for group in snapshots.INPUTS:
|
||||
for name in snapshots.source_files(group):
|
||||
if name.startswith('@'):
|
||||
continue
|
||||
target = self.root / name
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_bytes((snapshots.ROOT / name).read_bytes())
|
||||
recipe = 'tools/components/build-arm64-preloads.sh'
|
||||
(self.root / recipe).parent.mkdir(parents=True, exist_ok=True)
|
||||
(self.root / recipe).write_text((snapshots.ROOT / recipe).read_text())
|
||||
x86 = 'tools/components/recipes/x86-preloads.sh'
|
||||
(self.root / x86).parent.mkdir(parents=True, exist_ok=True)
|
||||
(self.root / x86).write_text((snapshots.ROOT / x86).read_text())
|
||||
(self.root / '.github/workflows').mkdir(parents=True)
|
||||
(self.root / '.github/workflows/build.yml').write_text((snapshots.ROOT / '.github/workflows/build.yml').read_text())
|
||||
self.git('init', '-q')
|
||||
self.git('config', 'core.autocrlf', 'false')
|
||||
self.git('config', 'user.name', 'Test Developer')
|
||||
self.git('config', 'user.email', 'test@example.test')
|
||||
self.git('add', '.')
|
||||
self.binaries = {name: ('verified-' + name).encode() for name in snapshots.FILES}
|
||||
self.content = archive(self.binaries)
|
||||
self.data = dict(version=1, origin=dict(run=123, commit='abc', artifact=456, artifact_sha256='0' * 64),
|
||||
groups={g: snapshots.source_files(g, self.root) for g in snapshots.INPUTS},
|
||||
arm64_recipe=snapshots.recipe(self.root), x86_recipe=snapshots.x86_recipe(self.root),
|
||||
archive_sha256=snapshots.sha(self.content),
|
||||
outputs={name: snapshots.sha(value) for name, value in self.binaries.items()})
|
||||
(self.root / snapshots.LOCK).write_text(json.dumps(self.data))
|
||||
self.git('add', '.')
|
||||
self.git('commit', '-qm', 'Approved baseline')
|
||||
self.base = self.git('rev-parse', 'HEAD').strip()
|
||||
|
||||
def git(self, *args):
|
||||
return subprocess.check_output(['git', *args], cwd=self.root, text=True)
|
||||
|
||||
def restore(self, base=None):
|
||||
with patch.dict(os.environ, COMPONENT_TRUSTED_BASE=base or self.base, FORCE_PRELOAD_REBUILD='false'), \
|
||||
patch.object(snapshots.urllib.request, 'urlopen', return_value=io.BytesIO(self.content)) as fetch, \
|
||||
patch.object(snapshots, 'prove_origin') as prove:
|
||||
result = snapshots.restore(self.root)
|
||||
return result, fetch, prove
|
||||
|
||||
def test_reviewed_unchanged_binaries_reused_and_written(self):
|
||||
result, fetch, prove = self.restore()
|
||||
self.assertEqual(result, dict(arm64=True, x86=True))
|
||||
prove.assert_not_called()
|
||||
fetch.assert_called_once()
|
||||
for name, value in self.binaries.items():
|
||||
self.assertEqual((self.root / 'app/src/main/assets/linuxfs' / name).read_bytes(), value)
|
||||
|
||||
def test_changed_common_source_requires_both_rebuilds(self):
|
||||
path = self.root / snapshots.COMMON[0]
|
||||
path.write_text(path.read_text() + '\n// Changed source\n')
|
||||
result, fetch, prove = self.restore()
|
||||
self.assertEqual(result, dict(arm64=False, x86=False))
|
||||
fetch.assert_not_called()
|
||||
prove.assert_not_called()
|
||||
|
||||
def test_new_transitive_header_is_an_input(self):
|
||||
source = self.root / snapshots.COMMON[0]
|
||||
source.write_text(source.read_text() + '\n#include "new-header.h"\n')
|
||||
header = source.with_name('new-header.h')
|
||||
header.write_text('#define VALUE 1\n')
|
||||
before = snapshots.source_files('arm64', self.root)
|
||||
header.write_text('#define VALUE 2\n')
|
||||
self.assertNotEqual(before, snapshots.source_files('arm64', self.root))
|
||||
|
||||
def test_changed_recipe_rebuilds_arm64_only(self):
|
||||
script = self.root / 'tools/components/build-arm64-preloads.sh'
|
||||
script.write_text(script.read_text().replace('-O2', '-O3'))
|
||||
result, _, _ = self.restore()
|
||||
self.assertEqual(result, dict(arm64=False, x86=True))
|
||||
|
||||
def test_shell_newline_changes_invalidate_the_recipe(self):
|
||||
script = self.root / 'tools/components/build-arm64-preloads.sh'
|
||||
original = snapshots.recipe(self.root)
|
||||
text = script.read_text()
|
||||
script.write_text(text.replace('-ldl\n', '-ldl ', 1))
|
||||
self.assertNotEqual(original, snapshots.recipe(self.root))
|
||||
|
||||
def test_x86_container_recipe_changes_rebuild_x86_only(self):
|
||||
script = self.root / 'tools/components/recipes/x86-preloads.sh'
|
||||
script.write_text(script.read_text().replace('debian:bullseye', 'debian:bookworm'))
|
||||
result, _, _ = self.restore()
|
||||
self.assertEqual(result, dict(arm64=True, x86=False))
|
||||
|
||||
def test_new_manifest_requires_main_build_proof(self):
|
||||
result, _, prove = self.restore('HEAD~1')
|
||||
self.assertTrue(all(result.values()))
|
||||
prove.assert_called_once()
|
||||
|
||||
def test_forged_binary_hash_cannot_prove_main_origin(self):
|
||||
data = copy.deepcopy(self.data)
|
||||
data['outputs']['libblsession.so'] = 'f' * 64
|
||||
with patch.object(snapshots, 'artifact_bytes', return_value=self.binaries):
|
||||
with self.assertRaisesRegex(ValueError, 'original main APK'):
|
||||
snapshots.prove_origin(data, self.root / 'cache', self.root)
|
||||
|
||||
def test_modified_input_policy_cannot_omit_producer_dependencies(self):
|
||||
data = copy.deepcopy(self.data)
|
||||
data['origin']['commit'] = self.base
|
||||
omitted = snapshots.COMMON[0]
|
||||
del data['groups']['arm64'][omitted]
|
||||
with patch.object(snapshots, 'artifact_bytes', return_value=self.binaries), \
|
||||
patch.object(snapshots, 'run', return_value=b''), \
|
||||
patch.object(snapshots, 'source_files', side_effect=lambda group, *args: data['groups'][group]), \
|
||||
patch.object(snapshots, 'producer_sources', return_value={omitted: self.data['groups']['arm64'][omitted]}):
|
||||
with self.assertRaisesRegex(ValueError, 'producing build dependency'):
|
||||
snapshots.prove_origin(data, self.root / 'cache', self.root)
|
||||
|
||||
def test_non_main_or_unsuccessful_run_cannot_prove_origin(self):
|
||||
build = dict(event='pull_request', head_branch='main', conclusion='success', head_sha='abc',
|
||||
path='.github/workflows/build.yml', repository=dict(full_name=snapshots.REPO))
|
||||
for field, value in [('event', 'pull_request'), ('head_branch', 'feature'), ('conclusion', 'failure')]:
|
||||
candidate = dict(build, event='push')
|
||||
candidate[field] = value
|
||||
with self.subTest(field=field), patch.object(snapshots, 'api', return_value=candidate):
|
||||
with self.assertRaisesRegex(ValueError, 'successful main'):
|
||||
snapshots.artifact_bytes(self.data['origin'], self.root / 'cache')
|
||||
|
||||
def test_corrupt_archive_is_rejected(self):
|
||||
with self.assertRaisesRegex(ValueError, 'checksum'):
|
||||
snapshots.unpack(self.content + b'tampered', self.data)
|
||||
|
||||
def test_missing_duplicate_or_traversal_entries_are_rejected(self):
|
||||
for files in ({}, {'../escaped': b'bad'}, {'libblsession.so': b'wrong'}):
|
||||
content = archive(files)
|
||||
data = dict(self.data, archive_sha256=snapshots.sha(content))
|
||||
with self.subTest(names=list(files)), self.assertRaises(ValueError):
|
||||
snapshots.unpack(content, data)
|
||||
|
||||
def test_missing_release_rebuilds_without_accepting_unverified_bytes(self):
|
||||
error = snapshots.urllib.error.HTTPError('https://example.test', 404, 'missing', {}, None)
|
||||
with patch.dict(os.environ, COMPONENT_TRUSTED_BASE=self.base), \
|
||||
patch.object(snapshots.urllib.request, 'urlopen', side_effect=error):
|
||||
self.assertEqual(snapshots.restore(self.root), dict(arm64=False, x86=False))
|
||||
|
||||
def test_transient_download_failure_rebuilds_but_integrity_errors_fail(self):
|
||||
errors = [TimeoutError('network'), snapshots.http.client.IncompleteRead(b'partial'),
|
||||
snapshots.urllib.error.HTTPError('https://example.test', 503, 'unavailable', {}, None)]
|
||||
for error in errors:
|
||||
with self.subTest(error=type(error).__name__), patch.dict(os.environ, COMPONENT_TRUSTED_BASE=self.base), \
|
||||
patch.object(snapshots.urllib.request, 'urlopen', side_effect=error):
|
||||
self.assertEqual(snapshots.restore(self.root), dict(arm64=False, x86=False))
|
||||
with patch.dict(os.environ, COMPONENT_TRUSTED_BASE=self.base), \
|
||||
patch.object(snapshots.urllib.request, 'urlopen', return_value=io.BytesIO(b'corrupt')):
|
||||
with self.assertRaisesRegex(ValueError, 'checksum'):
|
||||
snapshots.restore(self.root)
|
||||
|
||||
def test_manual_rebuild_does_not_download_snapshot(self):
|
||||
with patch.dict(os.environ, FORCE_PRELOAD_REBUILD='true'), \
|
||||
patch.object(snapshots.urllib.request, 'urlopen') as fetch:
|
||||
self.assertEqual(snapshots.restore(self.root), dict(arm64=False, x86=False))
|
||||
fetch.assert_not_called()
|
||||
@@ -0,0 +1,91 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
TOOLS = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(TOOLS))
|
||||
from proot_profile import report
|
||||
|
||||
PROGRAM = r'''
|
||||
#define _POSIX_C_SOURCE 200809L
|
||||
#define PR_NB_SYSNUM 2
|
||||
#define PR_void 0
|
||||
static const char *stringify_sysnum(unsigned nr) { return nr ? "openat" : "void"; }
|
||||
#include "profile.h"
|
||||
int main(void) {
|
||||
errno = EBUSY;
|
||||
if (!dd_profile_enabled()) return errno != EBUSY;
|
||||
if (errno != EBUSY) return 1;
|
||||
for (int i = 0; i < 40; i++) {
|
||||
uint64_t wall = dd_profile_clock(CLOCK_MONOTONIC);
|
||||
uint64_t cpu = dd_profile_clock(CLOCK_THREAD_CPUTIME_ID);
|
||||
struct timespec wait = {0, 2000000};
|
||||
nanosleep(&wait, 0);
|
||||
errno = ENOENT;
|
||||
dd_profile_record(1, 1, 123, wall, cpu);
|
||||
if (errno != ENOENT) return 2;
|
||||
if (i == 9) dd_profile_flush();
|
||||
}
|
||||
dd_profile_next = 0;
|
||||
uint64_t wall = dd_profile_clock(CLOCK_MONOTONIC);
|
||||
uint64_t cpu = dd_profile_clock(CLOCK_THREAD_CPUTIME_ID);
|
||||
struct timespec wait = {0, 2000000};
|
||||
nanosleep(&wait, 0);
|
||||
dd_profile_record(1, 0, 123, wall, cpu);
|
||||
return 0;
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
class ProotProfileTest(unittest.TestCase):
|
||||
def test_snapshots_replace_instead_of_adding_and_tracers_remain_separate(self):
|
||||
with tempfile.TemporaryDirectory() as work:
|
||||
path = Path(work) / 'session.log'
|
||||
records = [dict(type='total', tracer=1, id=2, syscall='statx', stage='enter',
|
||||
calls=n, wall_ns=n * 100, cpu_ns=n * 10, max_ns=100) for n in (3, 8)]
|
||||
records.append(dict(records[-1], tracer=2, calls=2))
|
||||
records += [dict(type='total', tracer=1, id=3, syscall='openat', stage='enter',
|
||||
calls=1, wall_ns=1000, cpu_ns=1000, max_ns=1000)]
|
||||
path.write_text('unrelated log\n' + ''.join('prefix proot-profile ' + json.dumps(r) + '\n' for r in records)
|
||||
+ 'proot-profile {truncated\n' + 'proot-profile []\n')
|
||||
result = report(path)
|
||||
self.assertEqual(11, result['handlerCalls'])
|
||||
self.assertEqual(3, result['tracers'])
|
||||
self.assertEqual(2, result['malformedRecords'])
|
||||
self.assertEqual('statx', result['totals'][0]['syscall'])
|
||||
self.assertEqual('openat', report(path, 'cpu')['totals'][0]['syscall'])
|
||||
|
||||
def test_empty_logs_do_not_claim_profiling_ran(self):
|
||||
with tempfile.TemporaryDirectory() as work:
|
||||
path = Path(work) / 'session.log'
|
||||
path.write_text('ordinary log\n')
|
||||
self.assertFalse(report(path)['hasCounters'])
|
||||
|
||||
@unittest.skipUnless(shutil.which('cc'), 'C compiler required')
|
||||
def test_real_clocks_bounded_samples_errno_and_periodic_counters(self):
|
||||
with tempfile.TemporaryDirectory() as work:
|
||||
source = Path(work) / 'profile.c'
|
||||
binary = Path(work) / 'profile'
|
||||
source.write_text(PROGRAM)
|
||||
subprocess.run(['cc', '-Wall', '-Wextra', '-Werror', '-std=c99', '-I', str(TOOLS / 'proot'),
|
||||
str(source), '-o', str(binary)], check=True)
|
||||
for setting in ('0', ''):
|
||||
result = subprocess.run([binary], env=dict(os.environ, PROOT_PROFILE=setting), capture_output=True, check=True)
|
||||
self.assertEqual(b'', result.stderr)
|
||||
result = subprocess.run([binary], env=dict(os.environ, PROOT_PROFILE='1', PROOT_PROFILE_SLOW_US='1'),
|
||||
capture_output=True, check=True)
|
||||
rows = [json.loads(line.split(b'proot-profile ', 1)[1]) for line in result.stderr.splitlines()]
|
||||
self.assertEqual(33, sum(row['type'] == 'slow' for row in rows))
|
||||
self.assertEqual(32, sum(row['type'] == 'slow' and row['stage'] == 'enter' for row in rows))
|
||||
self.assertGreater(sum(row['type'] == 'total' for row in rows), 2)
|
||||
log = Path(work) / 'session.log'
|
||||
log.write_bytes(result.stderr)
|
||||
counters = report(log)
|
||||
self.assertEqual(41, counters['handlerCalls'])
|
||||
self.assertGreater(counters['handlerWallNs'], counters['handlerCpuNs'])
|
||||
self.assertEqual(40, counters['totals'][0]['calls'])
|
||||
@@ -45,6 +45,26 @@ VULKAN_SCRIPT = r'''"InstallScript"
|
||||
'''
|
||||
|
||||
|
||||
UBISOFT_SCRIPT = r'''"installscript"
|
||||
{
|
||||
"Run Process"
|
||||
{
|
||||
"Ubisoft Connect PC Client"
|
||||
{
|
||||
"process 1" "%INSTALLDIR%\\UbisoftConnectInstaller.exe"
|
||||
"command 1" "/S"
|
||||
}
|
||||
"easyanticheat"
|
||||
{
|
||||
"HasRunKey" "HKEY_CURRENT_USER\\SOFTWARE\\Ubisoft\\WatchDogs2EAC"
|
||||
"process 1" "%INSTALLDIR%\\EasyAntiCheat\\InstallWD2EAC.cmd"
|
||||
"command 1" ""
|
||||
}
|
||||
}
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
class SeedRedistsTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = Path(tempfile.mkdtemp())
|
||||
@@ -353,5 +373,33 @@ class SeedRedistsTest(unittest.TestCase):
|
||||
self.assertEqual(self.reg.read_text().count('"Vulkan111080"'), 2)
|
||||
|
||||
|
||||
def ubisoft(self):
|
||||
script = self.tmp / "legacycompat/evaluatorscript_447040.vdf"
|
||||
script.parent.mkdir(parents=True)
|
||||
script.write_text('"evaluatorscript"\n{\n\t"appid"\t\t"447040"\n\t"1"\n'
|
||||
+ "\n".join("\t" + line for line in UBISOFT_SCRIPT.splitlines()) + "\n}\n")
|
||||
env = dict(os.environ, DROIDDECK_LIBRARIES="", DROIDDECK_SEED_SCRIPTS=str(script))
|
||||
return subprocess.run(["bash", str(SCRIPT), str(self.steam)], env=env, capture_output=True, text=True, check=True)
|
||||
|
||||
def test_the_ubisoft_connect_installer_is_left_to_run(self):
|
||||
self.ubisoft()
|
||||
self.assertIn('"easyanticheat"=dword:00000001', self.user.read_text())
|
||||
self.assertNotIn("Ubisoft Connect PC Client", self.reg.read_text())
|
||||
self.assertNotIn("Ubisoft Connect PC Client", (self.reg.parent / ".droiddeck-redists").read_text())
|
||||
|
||||
def test_a_ubisoft_connect_marker_an_earlier_seeding_wrote_comes_out(self):
|
||||
marker = "HKEY_LOCAL_MACHINE\\\\Software\\\\Valve\\\\Steam\\\\Apps\\\\447040\tUbisoft Connect PC Client"
|
||||
self.reg.write_text(
|
||||
"WINE REGISTRY Version 2\n"
|
||||
"\n[Software\\\\Valve\\\\Steam\\\\Apps\\\\447040] 1791729070\n"
|
||||
'"Ubisoft Connect PC Client"=dword:00000001\n'
|
||||
"\n[Software\\\\Wow6432Node\\\\Valve\\\\Steam\\\\Apps\\\\447040] 1791729070\n"
|
||||
'"Ubisoft Connect PC Client"=dword:00000001\n')
|
||||
(self.reg.parent / ".droiddeck-redists").write_text(marker + "\n")
|
||||
result = self.ubisoft()
|
||||
self.assertNotIn("Ubisoft Connect PC Client", self.reg.read_text())
|
||||
self.assertNotIn("Ubisoft Connect PC Client", (self.reg.parent / ".droiddeck-redists").read_text())
|
||||
self.assertIn("Ubisoft Connect markers out", result.stdout)
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,4 +1,4 @@
|
||||
"""The XTest cursor path is enabled only for Steam sessions."""
|
||||
"""Gamescope composites the cursor only when a Steam session asks for it."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
@@ -8,29 +8,37 @@ import unittest
|
||||
SESSION = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-session'
|
||||
SOURCE = SESSION.read_text()
|
||||
MATCH = re.search(
|
||||
r'^ if \[ "\$mode" = steam \]; then\n.*?^ fi\n', SOURCE, re.M | re.S)
|
||||
r'^ if \[ "\$mode" = steam \] && \[ "\$\{BL_CURSOR_COMPOSITE:-0\}" = 1 \]; then\n.*?^ fi\n',
|
||||
SOURCE, re.M | re.S)
|
||||
assert MATCH is not None
|
||||
CURSOR_SETUP = MATCH.group(0)
|
||||
|
||||
|
||||
class SessionCursorRoutingTest(unittest.TestCase):
|
||||
def run_setup(self, mode, initial=None):
|
||||
def run_setup(self, mode, initial=None, composite=None):
|
||||
env = dict(os.environ, mode=mode)
|
||||
if initial is not None:
|
||||
env['gamescope_cursor_composite'] = initial
|
||||
else:
|
||||
env.pop('gamescope_cursor_composite', None)
|
||||
if composite is not None:
|
||||
env['BL_CURSOR_COMPOSITE'] = composite
|
||||
else:
|
||||
env.pop('BL_CURSOR_COMPOSITE', None)
|
||||
result = subprocess.run(
|
||||
['bash', '-c', CURSOR_SETUP + 'printf "%s\n" "${gamescope_cursor_composite-}"'],
|
||||
env=env, text=True, capture_output=True, check=True)
|
||||
return result.stdout.strip()
|
||||
|
||||
def test_steam_enables_manual_composition_for_the_nested_cursor(self):
|
||||
self.assertEqual('2', self.run_setup('steam'))
|
||||
def test_steam_leaves_the_cursor_with_the_host_unless_asked(self):
|
||||
self.assertEqual('', self.run_setup('steam'))
|
||||
|
||||
def test_steam_composites_the_cursor_when_the_setting_is_on(self):
|
||||
self.assertEqual('2', self.run_setup('steam', composite='1'))
|
||||
|
||||
def test_other_sessions_keep_their_existing_cursor_composition(self):
|
||||
self.assertEqual('', self.run_setup('desktop'))
|
||||
self.assertEqual('1', self.run_setup('run', '1'))
|
||||
self.assertEqual('', self.run_setup('desktop', composite='1'))
|
||||
self.assertEqual('1', self.run_setup('run', '1', composite='1'))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -22,7 +22,7 @@ PACKAGES = [line.split()[1] for line in VARIANTS.read_text().splitlines()
|
||||
def guest_prefix(package):
|
||||
source = SERVICE.read_text()
|
||||
before_environment = source.split("val guest = ArrayList<String>()", 1)[1].split(
|
||||
"addClientEnvironment(guest, steamHere)", 1)[0]
|
||||
"addClientEnvironment(guest,", 1)[0]
|
||||
environment = source.split("private fun addClientEnvironment(", 1)[1].split(
|
||||
'guest.add("HOME=/root")', 1)[0]
|
||||
prefix = []
|
||||
|
||||
@@ -45,6 +45,68 @@ class SteamCompatEnvironmentTest(unittest.TestCase):
|
||||
client_path += ':' + inherited['LD_LIBRARY_PATH']
|
||||
self.assertEqual(result.stdout.splitlines(), ['1', client_path])
|
||||
|
||||
def test_session_exit_stops_the_library_helper(self):
|
||||
source = (BIN / 'droiddeck-session').read_text()
|
||||
launch = next(line for line in source.splitlines()
|
||||
if 'droiddeck-steam-compat "$steam_root"' in line)
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
pid = root / 'pid'
|
||||
helper = root / 'droiddeck-steam-compat'
|
||||
helper.write_text('#!/bin/sh\necho $$ > "$PID_FILE"\nexec sleep 30\n')
|
||||
helper.chmod(0o755)
|
||||
env = dict(os.environ, PATH=str(root) + os.pathsep + os.environ['PATH'],
|
||||
PID_FILE=str(pid), steam_root='/steam', steam_x64='0')
|
||||
subprocess.run(['bash', '-c', '_bl_compat_env=(env)\n' + launch + '\n'
|
||||
'until [ -s "$PID_FILE" ]; do sleep 0.05; done\n'
|
||||
'kill $(jobs -p)\nwait'],
|
||||
env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=10)
|
||||
helper_pid = int(pid.read_text())
|
||||
try:
|
||||
os.kill(helper_pid, 0)
|
||||
except ProcessLookupError:
|
||||
return
|
||||
os.kill(helper_pid, 9)
|
||||
self.fail('droiddeck-steam-compat outlived the session')
|
||||
|
||||
def test_the_x86_64_client_gets_only_the_file_dialog_bridge(self):
|
||||
source = (BIN / 'droiddeck-session').read_text()
|
||||
start = source.index(' if [ "$steam_x64" = 1 ]; then\n { droiddeck-steam-compat --files-only')
|
||||
block = source[start:source.index(' fi\n', start) + len(' fi\n')]
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
helper = root / 'droiddeck-steam-compat'
|
||||
helper.write_text('#!/bin/sh\necho "$@" >> "$ARGS_FILE"\n')
|
||||
helper.chmod(0o755)
|
||||
for x64, expected in (('1', '--files-only /steam'), ('0', '/steam')):
|
||||
with self.subTest(x64=x64):
|
||||
args = root / ('args-' + x64)
|
||||
env = dict(os.environ, PATH=str(root) + os.pathsep + os.environ['PATH'],
|
||||
ARGS_FILE=str(args), steam_root='/steam', steam_x64=x64)
|
||||
subprocess.run(['bash', '-c', '_bl_compat_env=(env)\n' + block + 'wait\n'], env=env, timeout=10, check=True)
|
||||
self.assertEqual(args.read_text().split('\n')[0], expected)
|
||||
|
||||
def test_files_only_mode_installs_only_the_file_dialog_hook(self):
|
||||
import runpy
|
||||
compat = runpy.run_path(str(BIN / 'droiddeck-steam-compat'))
|
||||
calls = []
|
||||
|
||||
class Page:
|
||||
def __init__(self, port, path):
|
||||
self.ws = None
|
||||
def evaluate(self, expression):
|
||||
calls.append(('evaluate', expression[:40]))
|
||||
return True
|
||||
def call(self, method, params):
|
||||
calls.append((method, params['name']))
|
||||
|
||||
helper = compat['Helper']('/steam', 1234, files_only=True)
|
||||
helper.attach.__globals__.update(shared_context=lambda port: '/devtools/page/1', Page=Page)
|
||||
self.assertTrue(helper.attach())
|
||||
bindings = [name for method, name in calls if method == 'Runtime.addBinding']
|
||||
self.assertEqual(bindings, [compat['FILE_BINDING']])
|
||||
self.assertIn(('evaluate', compat['FILE_JS'][:40]), calls)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -641,6 +641,114 @@ class ReconcileTest(unittest.TestCase):
|
||||
self.assertEqual(page.mapping["10"], "GE-Proton9-1")
|
||||
self.assertEqual(state["auto"], {"11": TOOL})
|
||||
|
||||
def games(self):
|
||||
return json.loads((self.state / "games.json").read_text())["games"]
|
||||
|
||||
def write_games(self, games):
|
||||
(self.state / "games.json").write_text(json.dumps({"version": 1, "games": games}))
|
||||
|
||||
def test_a_steam_pick_after_the_app_choice_is_kept_live(self):
|
||||
page = FakePage({"0": TOOL, "10": TOOL, "11": TOOL}, [TOOL, TOOL_11, COMPAT["FEX_TOOL"]])
|
||||
self.write_games({"10": {"valve": True, "dir": "Proton 11.0 (ARM64)"}})
|
||||
state = self.reconcile(page)
|
||||
self.assertEqual(page.sets, [("10", TOOL_11)])
|
||||
self.assertEqual(state["games_applied"], {"10": {"valve": True, "dir": "Proton 11.0 (ARM64)"}})
|
||||
|
||||
page.sets.clear()
|
||||
page.mapping["10"] = COMPAT["FEX_TOOL"]
|
||||
state = self.reconcile(page)
|
||||
self.assertEqual(page.sets, [])
|
||||
self.assertEqual(page.mapping["10"], COMPAT["FEX_TOOL"])
|
||||
self.assertEqual(self.games(), {})
|
||||
self.assertEqual(state["games_applied"], {})
|
||||
|
||||
self.write_games({"10": {"valve": True, "dir": "Proton 11.0 (ARM64)"}})
|
||||
self.reconcile(page)
|
||||
self.assertEqual(page.sets, [("10", TOOL_11)])
|
||||
|
||||
def test_a_steam_pick_of_our_proton_becomes_the_app_choice_live(self):
|
||||
page = FakePage({"0": TOOL, "10": TOOL, "11": TOOL}, [TOOL, TOOL_11])
|
||||
self.write_games({"10": {"valve": True, "dir": "Proton 11.0 (ARM64)"}})
|
||||
self.reconcile(page)
|
||||
page.sets.clear()
|
||||
page.mapping["10"] = TOOL
|
||||
state = self.reconcile(page)
|
||||
self.assertEqual(page.sets, [])
|
||||
self.assertEqual(self.games(), {"10": {"valve": True, "dir": "Proton Experimental (ARM64)"}})
|
||||
self.assertEqual(state["games_applied"], self.games())
|
||||
|
||||
def test_use_the_default_applies_once_then_steam_picks_stand_live(self):
|
||||
page = FakePage({"0": TOOL, "10": TOOL_11, "11": TOOL}, [TOOL, TOOL_11, COMPAT["FEX_TOOL"]])
|
||||
self.write_games({"10": None})
|
||||
self.reconcile(page)
|
||||
self.assertEqual(page.sets, [("10", TOOL)])
|
||||
|
||||
page.sets.clear()
|
||||
self.reconcile(page)
|
||||
self.assertEqual(self.games(), {})
|
||||
page.mapping["10"] = COMPAT["FEX_TOOL"]
|
||||
self.reconcile(page)
|
||||
self.assertEqual(page.sets, [])
|
||||
self.assertEqual(page.mapping["10"], COMPAT["FEX_TOOL"])
|
||||
|
||||
def test_choices_an_earlier_build_applied_give_way_to_steam_picks_live(self):
|
||||
(self.state / "state.json").write_text(json.dumps({"default": TOOL, "auto": {"11": TOOL}, "tools": []}))
|
||||
self.write_games({"10": None, "11": {"valve": True, "dir": "Proton 11.0 (ARM64)"}})
|
||||
page = FakePage({"0": TOOL, "10": COMPAT["FEX_TOOL"], "11": "steamlinuxruntime_sniper"},
|
||||
[TOOL, TOOL_11, COMPAT["FEX_TOOL"]])
|
||||
self.reconcile(page)
|
||||
self.assertEqual(page.sets, [])
|
||||
self.assertEqual(self.games(), {})
|
||||
|
||||
def test_an_app_choice_written_during_a_sync_is_not_overwritten(self):
|
||||
self.write_games({"10": {"valve": True, "dir": "Proton 11.0 (ARM64)"}})
|
||||
requests, text = COMPAT["read_game_requests"]()
|
||||
self.write_games({"10": {"valve": True, "dir": "Proton Experimental (ARM64)"}})
|
||||
self.assertFalse(COMPAT["write_game_requests"]({}, text))
|
||||
self.assertEqual(self.games(), {"10": {"valve": True, "dir": "Proton Experimental (ARM64)"}})
|
||||
|
||||
def test_an_app_the_client_briefly_refuses_keeps_its_applied_choice_live(self):
|
||||
page = FakePage({"0": TOOL, "10": TOOL, "11": TOOL}, [TOOL, TOOL_11, COMPAT["FEX_TOOL"]])
|
||||
self.write_games({"10": {"valve": True, "dir": "Proton 11.0 (ARM64)"}})
|
||||
self.reconcile(page)
|
||||
page.refused = {"10"}
|
||||
state = self.reconcile(page)
|
||||
self.assertEqual(state["games_applied"], {"10": {"valve": True, "dir": "Proton 11.0 (ARM64)"}})
|
||||
page.refused = set()
|
||||
page.sets.clear()
|
||||
page.mapping["10"] = COMPAT["FEX_TOOL"]
|
||||
self.reconcile(page)
|
||||
self.assertEqual(page.sets, [])
|
||||
self.assertEqual(page.mapping["10"], COMPAT["FEX_TOOL"])
|
||||
|
||||
def test_an_app_rewriting_its_choices_during_both_tries_applies_none_of_them_live(self):
|
||||
page = FakePage({"0": TOOL, "10": TOOL, "11": TOOL}, [TOOL, TOOL_11, COMPAT["FEX_TOOL"]])
|
||||
self.write_games({"10": {"valve": True, "dir": "Proton 11.0 (ARM64)"}})
|
||||
self.reconcile(page)
|
||||
page.sets.clear()
|
||||
page.mapping["10"] = COMPAT["FEX_TOOL"]
|
||||
self.write_games({"10": {"valve": True, "dir": "Proton 11.0 (ARM64)"}, "11": None})
|
||||
with mock.patch.dict(COMPAT["settled_game_requests"].__globals__, write_game_requests=lambda *_: False):
|
||||
state = self.reconcile(page)
|
||||
self.assertEqual(page.sets, [])
|
||||
self.assertEqual(state["games_applied"], {"10": {"valve": True, "dir": "Proton 11.0 (ARM64)"}})
|
||||
|
||||
def test_a_steam_pick_is_kept_at_the_next_start(self):
|
||||
config = self.steam / "config/config.vdf"
|
||||
config.parent.mkdir(parents=True)
|
||||
vdf = '"InstallConfigStore" { "Software" { "Valve" { "Steam" { "CompatToolMapping" { %s } } } } }'
|
||||
entry = '"%s" { "name" "%s" "config" "" "priority" "250" }'
|
||||
catalog = COMPAT["tool_catalog"](str(self.steam))
|
||||
self.write_games({"10": {"valve": True, "dir": "Proton 11.0 (ARM64)"}})
|
||||
config.write_text(vdf % (entry % ("0", TOOL) + entry % ("10", TOOL)))
|
||||
with mock.patch.dict(COMPAT["register_default"].__globals__, steam_running=lambda: False):
|
||||
COMPAT["register_default"](str(config), ["10"], catalog=catalog, directory=str(self.state), settle=True)
|
||||
self.assertIn(entry % ("10", TOOL_11), " ".join(config.read_text().split()))
|
||||
config.write_text(vdf % (entry % ("0", TOOL) + entry % ("10", COMPAT["FEX_TOOL"])))
|
||||
COMPAT["register_default"](str(config), ["10"], catalog=catalog, directory=str(self.state), settle=True)
|
||||
self.assertIn(entry % ("10", COMPAT["FEX_TOOL"]), " ".join(config.read_text().split()))
|
||||
self.assertEqual(self.games(), {})
|
||||
|
||||
def test_file_mode_defers_to_the_live_helper(self):
|
||||
(self.state / "live.pid").write_text("%d\n" % os.getpid())
|
||||
self.assertTrue(COMPAT["live_helper_running"]())
|
||||
|
||||
@@ -42,6 +42,15 @@ class DesktopSteamLaunchTest(unittest.TestCase):
|
||||
self.assertEqual(result.stdout.splitlines(), ['1', 'desktop', ':7', 'steam', 'steam://open/library'])
|
||||
self.assertFalse((self.session / 'steam-launch').exists())
|
||||
|
||||
def test_desktop_games_present_without_dri3(self):
|
||||
(self.root / 'supervisor').write_text('#!/bin/bash\nprintf "%s\\n" "$MESA_VK_WSI_DEBUG"\n')
|
||||
self.env.pop('MESA_VK_WSI_DEBUG', None)
|
||||
self.assertEqual(self.launch('desktop', '945360').stdout.splitlines(), ['sw'])
|
||||
self.env['MESA_VK_WSI_DEBUG'] = 'noshm'
|
||||
self.assertEqual(self.launch('desktop', '945360').stdout.splitlines(), ['noshm,sw'])
|
||||
self.env['MESA_VK_WSI_DEBUG'] = 'sw,noshm'
|
||||
self.assertEqual(self.launch('desktop', '945360').stdout.splitlines(), ['sw,noshm'])
|
||||
|
||||
def test_desktop_game_url_goes_to_client(self):
|
||||
result = self.launch('desktop', '501590')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import runpy
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
|
||||
LIVE = runpy.run_path(str(BIN / "droiddeck-steam-compat"))
|
||||
|
||||
HARNESS = r"""
|
||||
const assert = require('assert');
|
||||
globalThis.window = globalThis;
|
||||
const native = () => Promise.reject({ result: 2, message: '' });
|
||||
const popupCallbacks = [];
|
||||
const popup = { window: { SteamClient: { System: { OpenFileDialog: native } } } };
|
||||
const later = { window: { SteamClient: { System: { OpenFileDialog: native } } } };
|
||||
globalThis.SteamClient = { System: { OpenFileDialog: native } };
|
||||
window.g_PopupManager = { GetPopups: () => [popup], AddPopupCreatedCallback: cb => popupCallbacks.push(cb) };
|
||||
const asked = [];
|
||||
window.droiddeckOpenFileDialog = payload => asked.push(JSON.parse(payload));
|
||||
const script = require('fs').readFileSync(process.argv[2], 'utf8');
|
||||
(async () => {
|
||||
assert.strictEqual(eval(script), 'installed');
|
||||
const orphan = SteamClient.System.OpenFileDialog({ strTitle: 'Before reconnect' });
|
||||
assert.strictEqual(eval(script), 'present');
|
||||
await assert.rejects(orphan, e => e.result === 2);
|
||||
assert.strictEqual(window.__droiddeckFiles.done(1, '/late'), false);
|
||||
asked.length = 0;
|
||||
assert.notStrictEqual(SteamClient.System.OpenFileDialog, native);
|
||||
assert.strictEqual(popup.window.SteamClient.System.OpenFileDialog, SteamClient.System.OpenFileDialog);
|
||||
popupCallbacks.forEach(cb => cb(later));
|
||||
assert.strictEqual(later.window.SteamClient.System.OpenFileDialog, SteamClient.System.OpenFileDialog);
|
||||
const options = { strTitle: 'Pick', bChooseDirectory: true };
|
||||
const chosen = SteamClient.System.OpenFileDialog(options);
|
||||
const cancelled = later.window.SteamClient.System.OpenFileDialog({ strTitle: 'Other' });
|
||||
assert.deepStrictEqual(asked, [{ id: 2, options }, { id: 3, options: { strTitle: 'Other' } }]);
|
||||
assert.strictEqual(window.__droiddeckFiles.done(2, '/root/Storage/Games'), true);
|
||||
assert.strictEqual(window.__droiddeckFiles.done(2, '/again'), false);
|
||||
assert.strictEqual(await chosen, '/root/Storage/Games');
|
||||
window.__droiddeckFiles.done(3, null);
|
||||
await assert.rejects(cancelled, e => e.result === 2);
|
||||
delete window.droiddeckOpenFileDialog;
|
||||
await assert.rejects(SteamClient.System.OpenFileDialog({}), e => e.result === 2);
|
||||
})().catch(e => { console.error(e); process.exit(1); });
|
||||
"""
|
||||
|
||||
|
||||
def bound(payload):
|
||||
return {"method": "Runtime.bindingCalled", "params": {"name": LIVE["FILE_BINDING"], "payload": payload}}
|
||||
|
||||
|
||||
class FileDialogScriptTest(unittest.TestCase):
|
||||
def test_every_window_asks_the_bridge_and_gets_the_path_or_a_cancel(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
script = Path(tmp) / "files.js"
|
||||
script.write_text(LIVE["FILE_JS"])
|
||||
harness = Path(tmp) / "harness.js"
|
||||
harness.write_text(HARNESS)
|
||||
result = subprocess.run(["node", str(harness), str(script)], capture_output=True, text=True, timeout=20)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
|
||||
|
||||
class FileDialogBridgeTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.globals = LIVE["Helper"].attach.__globals__
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.root = Path(self.tmp.name)
|
||||
self.helper = LIVE["Helper"](str(self.root), 1)
|
||||
self.helper.page = mock.Mock()
|
||||
|
||||
def answer(self):
|
||||
return self.helper.page.evaluate.call_args.args[0]
|
||||
|
||||
def test_the_chooser_runs_under_a_steam_reaper_with_the_options_on_stdin(self):
|
||||
reaper = self.root / "steamrtarm64/reaper"
|
||||
reaper.parent.mkdir()
|
||||
reaper.write_text("#!/bin/sh\n")
|
||||
reaper.chmod(0o755)
|
||||
proc = mock.Mock(stdin=io.BytesIO())
|
||||
proc.stdin.close = lambda: None
|
||||
with mock.patch.object(self.globals["subprocess"], "Popen", return_value=proc) as popen:
|
||||
self.helper.page.drain.return_value = [bound(json.dumps({"id": 3, "options": {"strTitle": "Pick"}}))]
|
||||
self.helper.drain()
|
||||
command = popen.call_args.args[0]
|
||||
self.assertEqual(command[:4], [str(reaper), "SteamLaunch", "AppId=769", "--"])
|
||||
self.assertEqual(command[-1], "--choose-file")
|
||||
self.assertEqual(json.loads(proc.stdin.getvalue()), {"strTitle": "Pick"})
|
||||
self.assertEqual(self.helper.chooser, (3, proc))
|
||||
|
||||
def test_a_second_request_while_one_is_open_is_cancelled(self):
|
||||
first = mock.Mock()
|
||||
self.helper.chooser = (1, first)
|
||||
self.helper.open_chooser(json.dumps({"id": 2, "options": {}}))
|
||||
self.assertEqual(self.answer(), "window.__droiddeckFiles?.done(2, null)")
|
||||
self.assertEqual(self.helper.chooser, (1, first))
|
||||
|
||||
def test_the_chosen_path_or_a_cancel_goes_back_to_the_page(self):
|
||||
for code, out, expected in ((0, b'"/root/Storage/My Game/game.sh"\n', '"/root/Storage/My Game/game.sh"'),
|
||||
(0, b'" spaced name "\n', '" spaced name "'),
|
||||
(1, b"", "null"), (2, b"", "null"), (0, b"\n", "null"), (0, b"not json\n", "null")):
|
||||
proc = mock.Mock(stdout=io.BytesIO(out), returncode=code)
|
||||
self.helper.chooser = (7, proc)
|
||||
self.helper.chooser_done()
|
||||
self.assertEqual(self.answer(), "window.__droiddeckFiles?.done(7, %s)" % expected)
|
||||
self.assertIsNone(self.helper.chooser)
|
||||
|
||||
def test_bad_requests_are_ignored(self):
|
||||
with mock.patch.object(self.globals["subprocess"], "Popen") as popen:
|
||||
for payload in ("not json", json.dumps({"options": {}}), json.dumps({"id": 1, "options": []})):
|
||||
self.helper.open_chooser(payload)
|
||||
popen.assert_not_called()
|
||||
self.helper.page.evaluate.assert_not_called()
|
||||
|
||||
def test_choose_file_mode_prints_the_path_and_fails_on_cancel(self):
|
||||
for chooser, code, printed in ((mock.Mock(return_value="/root/Storage/a.exe "), 0, '"/root/Storage/a.exe "\n'),
|
||||
(mock.Mock(return_value=None), 1, ""),
|
||||
(mock.Mock(side_effect=ValueError("Namespace Gtk not available for version 3.0")), 2, ""),
|
||||
(mock.Mock(side_effect=ImportError("No module named 'gi'")), 2, "")):
|
||||
with mock.patch.dict(LIVE["chooser_main"].__globals__, {"choose_file": chooser}), \
|
||||
mock.patch.object(sys, "stdin", io.StringIO('{"strTitle": "Pick"}')), \
|
||||
mock.patch.object(sys, "stdout", io.StringIO()) as out:
|
||||
self.assertEqual(LIVE["chooser_main"](), code)
|
||||
self.assertEqual(out.getvalue(), printed)
|
||||
|
||||
def test_attach_installs_the_file_dialog_bridge(self):
|
||||
page = mock.Mock()
|
||||
page.evaluate.return_value = True
|
||||
with mock.patch.dict(self.globals, {"shared_context": lambda port: "/devtools/page/1",
|
||||
"Page": mock.Mock(return_value=page)}):
|
||||
self.helper.attach()
|
||||
page.call.assert_any_call("Runtime.addBinding", {"name": LIVE["FILE_BINDING"]})
|
||||
page.evaluate.assert_any_call(LIVE["FILE_JS"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -26,25 +26,48 @@ class SteamInstallTest(unittest.TestCase):
|
||||
self.bin = self.root / 'bin'
|
||||
self.bin.mkdir()
|
||||
curl = self.bin / 'curl'
|
||||
curl.write_text('''#!/bin/bash
|
||||
set -eu
|
||||
url=""
|
||||
out=""
|
||||
while [ $# -gt 0 ]; do
|
||||
case $1 in
|
||||
-o) out=$2; shift 2 ;;
|
||||
--connect-timeout|--max-time|--speed-limit|--speed-time|--retry|--retry-delay) shift 2 ;;
|
||||
-*) shift ;;
|
||||
*) url=$1; shift ;;
|
||||
esac
|
||||
done
|
||||
printf '%s\\n' "$url" >> "$TEST_REQUESTS"
|
||||
if [ -n "${TEST_FAIL_HOST:-}" ]; then
|
||||
case $url in *"$TEST_FAIL_HOST"*) exit 22 ;; esac
|
||||
fi
|
||||
cp "$TEST_CDN/${url##*/}" "$out"
|
||||
curl.write_text('''#!/usr/bin/env python3
|
||||
import os, sys
|
||||
args = sys.argv[1:]
|
||||
url = next(a for a in args if a.startswith('https://'))
|
||||
out = args[args.index('-o') + 1]
|
||||
name = url.rsplit('/', 1)[1]
|
||||
offset = os.path.getsize(out) if '-C' in args and os.path.exists(out) else 0
|
||||
with open(os.environ['TEST_REQUESTS'], 'a') as log:
|
||||
log.write(url + '\\n')
|
||||
with open(os.environ['TEST_REQUESTS'] + '.offsets', 'a') as log:
|
||||
log.write(f'{name} {offset}\\n')
|
||||
def done(status, code='200'):
|
||||
if '-w' in args:
|
||||
sys.stdout.write(code)
|
||||
sys.exit(status)
|
||||
host_fail = os.environ.get('TEST_FAIL_HOST')
|
||||
if host_fail and host_fail in url:
|
||||
done(22, '000')
|
||||
action = []
|
||||
plan = os.environ.get('TEST_PLAN')
|
||||
if plan and os.path.exists(plan):
|
||||
lines = open(plan).read().splitlines()
|
||||
for n, line in enumerate(lines):
|
||||
if line.split()[0] == name:
|
||||
action = line.split()[1:]
|
||||
del lines[n]
|
||||
open(plan, 'w').write(''.join(l + '\\n' for l in lines))
|
||||
break
|
||||
if action[:1] == ['fail']:
|
||||
done(int(action[1]), '000')
|
||||
if action[:1] == ['http']:
|
||||
done(22, action[1])
|
||||
if action[:1] == ['norange'] and offset:
|
||||
done(33)
|
||||
data = open(os.path.join(os.environ['TEST_CDN'], name), 'rb').read()
|
||||
end = int(action[1]) if action[:1] == ['cut'] else len(data)
|
||||
with open(out, 'ab' if offset else 'wb') as target:
|
||||
target.write(data[offset:end])
|
||||
done(28 if end < len(data) else 0)
|
||||
''')
|
||||
curl.chmod(0o755)
|
||||
self.plan = self.root / 'plan'
|
||||
if shutil.which('sha256sum') is None:
|
||||
sha = self.bin / 'sha256sum'
|
||||
sha.write_text('#!/bin/bash\nexec shasum -a 256 "$@"\n')
|
||||
@@ -55,8 +78,9 @@ cp "$TEST_CDN/${url##*/}" "$out"
|
||||
sha1.chmod(0o755)
|
||||
self.env = dict(os.environ, HOME=str(self.home), XDG_DATA_HOME=str(self.data),
|
||||
PATH=str(self.bin) + os.pathsep + os.environ['PATH'],
|
||||
TEST_CDN=str(self.cdn), TEST_REQUESTS=str(self.requests))
|
||||
for channel in ('steamdeck_publicbeta',):
|
||||
TEST_CDN=str(self.cdn), TEST_REQUESTS=str(self.requests),
|
||||
TEST_PLAN=str(self.plan), BL_STEAM_RETRY_DELAYS='0 0 0')
|
||||
for channel in ('steamdeck_publicbeta', 'steamdeck_stable'):
|
||||
archive = self.cdn / (channel + '.zip')
|
||||
with zipfile.ZipFile(archive, 'w') as package:
|
||||
package.writestr('steamrtarm64/steam', channel)
|
||||
@@ -68,12 +92,17 @@ cp "$TEST_CDN/${url##*/}" "$out"
|
||||
f'\t\t"file" "{archive.name}"\n\t\t"sha2" "{digest}"\n'
|
||||
'\t}\n}\n')
|
||||
|
||||
def install(self, fail_host=None):
|
||||
def install(self, fail_host=None, *args, **extra):
|
||||
env = self.env if fail_host is None else dict(self.env, TEST_FAIL_HOST=fail_host)
|
||||
return subprocess.run(['bash', str(SCRIPT)], env=env, text=True, capture_output=True)
|
||||
return subprocess.run(['bash', str(SCRIPT), *args], env=dict(env, **extra), text=True, capture_output=True)
|
||||
|
||||
def assert_installed(self, channel='steamdeck_publicbeta', fail_host=None, expected=None):
|
||||
result = self.install(fail_host)
|
||||
def channel(self, **extra):
|
||||
result = self.install(None, '--channel', **extra)
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
return result.stdout.strip()
|
||||
|
||||
def assert_installed(self, channel='steamdeck_publicbeta', fail_host=None, expected=None, **extra):
|
||||
result = self.install(fail_host, **extra)
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
self.assertEqual(channel + '\n', (self.steam / 'package/beta').read_text())
|
||||
self.assertEqual('123456\n', (self.steam / 'package/droiddeck-installed').read_text())
|
||||
@@ -87,6 +116,7 @@ cp "$TEST_CDN/${url##*/}" "$out"
|
||||
'https://client-update.steamstatic.com/' + channel + '.zip',
|
||||
]
|
||||
self.assertEqual(expected, self.requests.read_text().splitlines())
|
||||
return result
|
||||
|
||||
def test_downloads_the_deck_beta_client(self):
|
||||
self.assert_installed()
|
||||
@@ -155,8 +185,80 @@ cp "$TEST_CDN/${url##*/}" "$out"
|
||||
self.requests.unlink()
|
||||
with (package / 'droiddeck-unconfirmed').open('a') as marker:
|
||||
marker.write('start\nstart\nstart\n')
|
||||
self.assertEqual(0, self.install(BL_STEAM_CHANNEL='beta').returncode)
|
||||
self.assertFalse(self.requests.exists())
|
||||
|
||||
def test_the_default_channel_is_the_deck_beta(self):
|
||||
self.assertEqual('steamdeck_publicbeta', self.channel())
|
||||
|
||||
def stable_requests(self, beta_manifest=True):
|
||||
stable = [
|
||||
'https://client-update.steamstatic.com/steam_client_steamdeck_stable_linuxarm64',
|
||||
'https://client-update.steamstatic.com/steamdeck_stable.zip',
|
||||
]
|
||||
if beta_manifest:
|
||||
stable.insert(0, 'https://client-update.steamstatic.com/steam_client_steamdeck_publicbeta_linuxarm64')
|
||||
return stable
|
||||
|
||||
def test_a_repaired_beta_client_that_still_shows_nothing_falls_back_to_stable(self):
|
||||
package = self.break_client(2)
|
||||
self.assertEqual(0, self.install().returncode)
|
||||
self.requests.unlink()
|
||||
with (package / 'droiddeck-unconfirmed').open('a') as marker:
|
||||
marker.write('start\nstart\n')
|
||||
result = self.assert_installed('steamdeck_stable', expected=self.stable_requests(False))
|
||||
self.assertIn("falling back to Valve's steamdeck_stable Steam client", result.stdout)
|
||||
self.assertEqual('steamdeck_stable\n', (package / 'droiddeck-channel').read_text())
|
||||
self.assertEqual('repaired\n', (package / 'droiddeck-unconfirmed').read_text())
|
||||
self.assertEqual('steamdeck_stable', self.channel())
|
||||
|
||||
def test_the_stable_fallback_is_not_repeated(self):
|
||||
self.test_a_repaired_beta_client_that_still_shows_nothing_falls_back_to_stable()
|
||||
self.requests.unlink()
|
||||
with (self.steam / 'package/droiddeck-unconfirmed').open('a') as marker:
|
||||
marker.write('start\nstart\nstart\n')
|
||||
self.assertEqual(0, self.install().returncode)
|
||||
self.assertFalse(self.requests.exists())
|
||||
self.assertEqual('steamdeck_stable\n', (self.steam / 'package/beta').read_text())
|
||||
|
||||
def test_a_pinned_beta_channel_never_falls_back(self):
|
||||
package = self.break_client(2)
|
||||
self.assertEqual(0, self.install().returncode)
|
||||
with (package / 'droiddeck-unconfirmed').open('a') as marker:
|
||||
marker.write('start\nstart\n')
|
||||
self.assertEqual('steamdeck_publicbeta', self.channel(BL_STEAM_CHANNEL='beta'))
|
||||
self.assertEqual(0, self.install(BL_STEAM_CHANNEL='beta').returncode)
|
||||
self.assertFalse((package / 'droiddeck-channel').exists())
|
||||
|
||||
def test_the_channel_setting_selects_stable(self):
|
||||
setting = self.home / '.config/droiddeck/steam-channel'
|
||||
setting.parent.mkdir(parents=True)
|
||||
setting.write_text('stable\n')
|
||||
self.assertEqual('steamdeck_stable', self.channel())
|
||||
self.assert_installed('steamdeck_stable', expected=self.stable_requests(False))
|
||||
self.assertFalse((self.steam / 'package/droiddeck-channel').exists())
|
||||
|
||||
def empty_beta_manifest(self):
|
||||
(self.cdn / 'steam_client_steamdeck_publicbeta_linuxarm64').write_text(
|
||||
'"linuxarm64"\n{\n\t"version" "123457"\n'
|
||||
'\t"client_steamrtarm64_linuxarm64"\n\t{\n'
|
||||
'\t\t"file" "client.zip"\n\t\t"sha2" "00"\n'
|
||||
'\t}\n}\n')
|
||||
|
||||
def test_a_beta_manifest_without_an_arm64_client_falls_back_to_stable(self):
|
||||
self.empty_beta_manifest()
|
||||
result = self.assert_installed('steamdeck_stable', expected=self.stable_requests())
|
||||
self.assertIn('no client components in steam_client_steamdeck_publicbeta_linuxarm64', result.stderr)
|
||||
self.assertIn('client_steamrtarm64_linuxarm64', result.stderr)
|
||||
self.assertEqual('steamdeck_stable\n', (self.steam / 'package/droiddeck-channel').read_text())
|
||||
self.assertEqual('steamdeck_stable', self.channel())
|
||||
|
||||
def test_a_pinned_beta_manifest_without_an_arm64_client_fails_and_names_its_blocks(self):
|
||||
self.empty_beta_manifest()
|
||||
result = self.install(BL_STEAM_CHANNEL='beta')
|
||||
self.assertNotEqual(0, result.returncode)
|
||||
self.assertIn('client_steamrtarm64_linuxarm64', result.stderr)
|
||||
self.assertFalse((self.steam / 'package/droiddeck-installed').exists())
|
||||
|
||||
def test_requested_repair_runs_once_and_is_retried_until_it_completes(self):
|
||||
package = self.break_client(0)
|
||||
@@ -177,6 +279,143 @@ cp "$TEST_CDN/${url##*/}" "$out"
|
||||
self.assertEqual(0, self.install().returncode)
|
||||
self.assertFalse(self.requests.exists())
|
||||
|
||||
def publish(self, **parts):
|
||||
"""The CDN's client as these parts (block name -> byte count of incompressible content),
|
||||
listed with sizes as Valve's manifest lists them."""
|
||||
files = {}
|
||||
blocks = ''
|
||||
for block, length in parts.items():
|
||||
archive = self.cdn / f'{block}.zip.{hashlib.sha1(block.encode()).hexdigest()}'
|
||||
with zipfile.ZipFile(archive, 'w', zipfile.ZIP_STORED) as package:
|
||||
package.writestr(f'parts/{block}', os.urandom(length))
|
||||
if block.endswith('_linuxarm64_linuxarm64'):
|
||||
package.writestr('steamrtarm64/steam', 'steamdeck_publicbeta')
|
||||
data = archive.read_bytes()
|
||||
files[block] = archive.name
|
||||
blocks += (f'\t"{block}"\n\t{{\n\t\t"file"\t\t"{archive.name}"\n\t\t"size"\t\t"{len(data)}"\n'
|
||||
f'\t\t"sha2"\t\t"{hashlib.sha256(data).hexdigest()}"\n\t}}\n')
|
||||
(self.cdn / 'steam_client_steamdeck_publicbeta_linuxarm64').write_text(
|
||||
'"linuxarm64"\n{\n\t"version"\t\t"123456"\n' + blocks + '}\n')
|
||||
return files
|
||||
|
||||
def two_parts(self):
|
||||
return self.publish(a_all=1_200_000, client_linuxarm64_linuxarm64=1_300_000)
|
||||
|
||||
def plan_for(self, name, *actions):
|
||||
with self.plan.open('a') as plan:
|
||||
plan.writelines(f'{name} {action}\n' for action in actions)
|
||||
|
||||
def offsets(self, name):
|
||||
log = Path(str(self.requests) + '.offsets')
|
||||
return [int(line.split()[1]) for line in log.read_text().splitlines() if line.split()[0] == name]
|
||||
|
||||
def requested(self):
|
||||
return [line.rsplit('/', 1)[1] for line in self.requests.read_text().splitlines()]
|
||||
|
||||
@property
|
||||
def download(self):
|
||||
return self.steam / 'package/droiddeck-download'
|
||||
|
||||
def test_progress_is_counted_in_megabytes_across_parts(self):
|
||||
self.two_parts()
|
||||
result = self.install()
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
self.assertIn('downloading Steam: a_all (1/2), 0 of 2 MB\n', result.stdout)
|
||||
self.assertIn('downloading Steam: client_linuxarm64_linuxarm64 (2/2), 1 of 2 MB\n', result.stdout)
|
||||
self.assertTrue((self.steam / 'parts/a_all').is_file())
|
||||
self.assertFalse(self.download.exists())
|
||||
|
||||
def test_a_dropped_connection_resumes_from_what_arrived(self):
|
||||
files = self.two_parts()
|
||||
client = files['client_linuxarm64_linuxarm64']
|
||||
self.plan_for(client, 'cut 500000')
|
||||
result = self.install()
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
self.assertEqual([0, 500000], self.offsets(client))
|
||||
self.assertIn('interrupted (curl exit 28), trying again in 0 s', result.stdout)
|
||||
self.assertEqual('123456\n', (self.steam / 'package/droiddeck-installed').read_text())
|
||||
|
||||
def test_a_failed_session_keeps_what_it_finished_and_fetched(self):
|
||||
files = self.two_parts()
|
||||
client = files['client_linuxarm64_linuxarm64']
|
||||
self.plan_for(client, 'cut 400000', *['fail 6'] * 12)
|
||||
result = self.install()
|
||||
self.assertNotEqual(0, result.returncode)
|
||||
self.assertIn('could not download client_linuxarm64_linuxarm64 (curl exit 6)', result.stderr)
|
||||
self.assertFalse((self.steam / 'package/droiddeck-installed').exists())
|
||||
self.assertTrue((self.download / (files['a_all'] + '.unpacked')).is_file())
|
||||
self.assertFalse((self.download / files['a_all']).exists())
|
||||
self.assertEqual(400000, (self.download / client).stat().st_size)
|
||||
self.requests.unlink()
|
||||
Path(str(self.requests) + '.offsets').unlink()
|
||||
self.assertEqual(0, self.install().returncode)
|
||||
self.assertEqual(['steam_client_steamdeck_publicbeta_linuxarm64', client], self.requested())
|
||||
self.assertEqual([400000], self.offsets(client))
|
||||
self.assertFalse(self.download.exists())
|
||||
|
||||
def test_a_server_that_will_not_resume_starts_the_part_over(self):
|
||||
files = self.two_parts()
|
||||
client = files['client_linuxarm64_linuxarm64']
|
||||
self.plan_for(client, 'cut 400000', 'norange')
|
||||
result = self.install()
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
self.assertEqual([0, 400000, 0], self.offsets(client))
|
||||
|
||||
def test_a_missing_part_hands_over_to_the_next_cdn_at_once(self):
|
||||
files = self.two_parts()
|
||||
client = files['client_linuxarm64_linuxarm64']
|
||||
self.plan_for(client, 'http 404')
|
||||
result = self.install()
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
self.assertEqual(['https://client-update.steamstatic.com/' + client,
|
||||
'https://client-update.akamai.steamstatic.com/' + client],
|
||||
[line for line in self.requests.read_text().splitlines() if line.endswith(client)])
|
||||
self.assertIn('HTTP 404 from https://client-update.steamstatic.com', result.stderr)
|
||||
self.assertNotIn('trying again', result.stdout)
|
||||
|
||||
def test_a_server_error_is_retried_on_the_same_cdn(self):
|
||||
files = self.two_parts()
|
||||
client = files['client_linuxarm64_linuxarm64']
|
||||
self.plan_for(client, 'http 503')
|
||||
result = self.install()
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
self.assertEqual(['https://client-update.steamstatic.com/' + client] * 2,
|
||||
[line for line in self.requests.read_text().splitlines() if line.endswith(client)])
|
||||
self.assertIn('interrupted (curl exit 22), trying again in 0 s', result.stdout)
|
||||
|
||||
def test_bytes_that_do_not_check_out_are_fetched_again(self):
|
||||
files = self.two_parts()
|
||||
client = files['client_linuxarm64_linuxarm64']
|
||||
self.download.mkdir(parents=True)
|
||||
(self.download / client).write_bytes(b'x' * (self.cdn / client).stat().st_size)
|
||||
result = self.install()
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
self.assertEqual([0], self.offsets(client))
|
||||
|
||||
def test_parts_left_for_another_client_version_are_dropped(self):
|
||||
files = self.two_parts()
|
||||
self.download.mkdir(parents=True)
|
||||
(self.download / 'a_all.zip.0123').write_bytes(b'older')
|
||||
(self.download / 'b_all.zip.4567.unpacked').write_bytes(b'')
|
||||
self.plan_for(files['client_linuxarm64_linuxarm64'], *['fail 7'] * 12)
|
||||
self.assertNotEqual(0, self.install().returncode)
|
||||
self.assertEqual([files['a_all'] + '.unpacked'], sorted(p.name for p in self.download.iterdir()))
|
||||
|
||||
def test_a_repair_unpacks_every_part_again_once(self):
|
||||
files = self.two_parts()
|
||||
self.assertEqual(0, self.install().returncode)
|
||||
(self.home / '.bl-steam-repair').write_text('1\n')
|
||||
self.requests.unlink()
|
||||
self.plan_for(files['client_linuxarm64_linuxarm64'], *['fail 7'] * 12)
|
||||
self.assertNotEqual(0, self.install().returncode)
|
||||
self.assertIn(files['a_all'], self.requested())
|
||||
self.requests.unlink()
|
||||
self.assertEqual(0, self.install().returncode)
|
||||
self.assertEqual(['steam_client_steamdeck_publicbeta_linuxarm64', files['client_linuxarm64_linuxarm64']],
|
||||
self.requested())
|
||||
self.assertFalse((self.home / '.bl-steam-repair').exists())
|
||||
self.assertFalse(self.download.exists())
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -153,6 +153,8 @@ class DesktopGamesTest(unittest.TestCase):
|
||||
steam = root / "Steam"
|
||||
manifest(steam / "steamapps", 40, name="Game")
|
||||
manifest(steam / "steamapps", 1628350, name="Steam Linux Runtime 3.0 (sniper)", installdir="SteamLinuxRuntime_sniper")
|
||||
manifest(steam / "steamapps", 1826330, name="Proton EasyAntiCheat Runtime", installdir="Proton EasyAntiCheat Runtime")
|
||||
manifest(steam / "steamapps", 1161040, name="Proton BattlEye Runtime", installdir="Proton BattlEye Runtime")
|
||||
manifest(steam / "steamapps", 5000, name="Some Proton", installdir="Some Proton")
|
||||
(steam / "steamapps/common/Some Proton").mkdir(parents=True)
|
||||
(steam / "steamapps/common/Some Proton/toolmanifest.vdf").write_text('"manifest"\n{\n}\n')
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
from pathlib import Path
|
||||
import runpy
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
BIN = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin'
|
||||
MODULE = runpy.run_path(str(BIN / 'droiddeck-steam-shaders'))
|
||||
apply = MODULE['apply']
|
||||
set_text = MODULE['set_text']
|
||||
parse = runpy.run_path(str(BIN / 'droiddeck-steam-ui-scale'))['parse']
|
||||
|
||||
THOR = '''"InstallConfigStore"
|
||||
{
|
||||
\t"Software"
|
||||
\t{
|
||||
\t\t"Valve"
|
||||
\t\t{
|
||||
\t\t\t"Steam"
|
||||
\t\t\t{
|
||||
\t\t\t\t"ShaderCacheManager"
|
||||
\t\t\t\t{
|
||||
\t\t\t\t\t"HasCurrentBucket"\t\t"1"
|
||||
\t\t\t\t\t"ProcessingQueue"\t\t"207140;848350;"
|
||||
\t\t\t\t\t"App"
|
||||
\t\t\t\t\t{
|
||||
\t\t\t\t\t}
|
||||
\t\t\t\t}
|
||||
\t\t\t}
|
||||
\t\t}
|
||||
\t}
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
def disabled(text):
|
||||
steam = parse(text).get('InstallConfigStore').get('Software').get('Valve').get('Steam')
|
||||
return steam.get('ShaderCacheManager').get('DisableShaderCache')
|
||||
|
||||
|
||||
class SteamShadersTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.root = Path(self.temp.name)
|
||||
self.config = self.root / 'config/config.vdf'
|
||||
self.config.parent.mkdir()
|
||||
|
||||
def test_off_adds_the_key_the_client_writes(self):
|
||||
text, changed = set_text(THOR, False)
|
||||
self.assertTrue(changed)
|
||||
self.assertEqual('1', disabled(text))
|
||||
self.assertIn('\t\t\t\t\t"DisableShaderCache"\t\t"1"\n\t\t\t\t}', text)
|
||||
self.assertIn('"ProcessingQueue"\t\t"207140;848350;"', text)
|
||||
|
||||
def test_existing_value_is_replaced_in_place(self):
|
||||
off, _ = set_text(THOR, False)
|
||||
on, changed = set_text(off, True)
|
||||
self.assertTrue(changed)
|
||||
self.assertEqual('0', disabled(on))
|
||||
self.assertEqual(off.replace('"DisableShaderCache"\t\t"1"', '"DisableShaderCache"\t\t"0"'), on)
|
||||
|
||||
def test_matching_value_leaves_the_file_alone(self):
|
||||
off, _ = set_text(THOR, False)
|
||||
self.assertEqual((off, False), set_text(off, False))
|
||||
|
||||
def test_missing_sections_are_created(self):
|
||||
text, changed = set_text('"InstallConfigStore"\n{\n}\n', False)
|
||||
self.assertTrue(changed)
|
||||
self.assertEqual('1', disabled(text))
|
||||
|
||||
def test_apply_writes_config_and_creates_a_fresh_one(self):
|
||||
self.config.write_text(THOR)
|
||||
self.assertTrue(apply(self.root, False))
|
||||
self.assertEqual('1', disabled(self.config.read_text()))
|
||||
self.assertFalse(apply(self.root, False))
|
||||
fresh = Path(self.temp.name) / 'fresh'
|
||||
fresh.mkdir()
|
||||
self.assertTrue(apply(fresh, True))
|
||||
self.assertEqual('0', disabled((fresh / 'config/config.vdf').read_text()))
|
||||
|
||||
def test_invalid_config_is_rejected(self):
|
||||
with self.assertRaises(ValueError):
|
||||
set_text('"InstallConfigStore" {', False)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,167 @@
|
||||
from pathlib import Path
|
||||
import contextlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import runpy
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
SCRIPT = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-steam-share'
|
||||
SHARE = runpy.run_path(str(SCRIPT))
|
||||
|
||||
CONFIG = ('"InstallConfigStore"\n{\n\t"Software"\n\t{\n\t\t"Valve"\n\t\t{\n\t\t\t"Steam"\n\t\t\t{\n'
|
||||
'\t\t\t\t"CompatToolMapping"\n\t\t\t\t{\n%s\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n')
|
||||
|
||||
|
||||
def mapping(**tools):
|
||||
return ''.join('\t\t\t\t\t"%s"\n\t\t\t\t\t{\n\t\t\t\t\t\t"name"\t\t"%s"\n\t\t\t\t\t\t"config"\t\t""\n'
|
||||
'\t\t\t\t\t\t"priority"\t\t"250"\n\t\t\t\t\t}\n' % (app.lstrip('_'), name)
|
||||
for app, name in tools.items())
|
||||
|
||||
|
||||
def manifest(app, folder, updated=100, flags=4):
|
||||
return ('"AppState"\n{\n\t"appid"\t\t"%s"\n\t"name"\t\t"%s"\n\t"StateFlags"\t\t"%d"\n'
|
||||
'\t"installdir"\t\t"%s"\n\t"LastUpdated"\t\t"%d"\n}\n' % (app, folder, flags, folder, updated))
|
||||
|
||||
|
||||
class SteamShareTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
home = Path(self.temp.name)
|
||||
self.arm = home / 'arm/Steam'
|
||||
self.x64 = home / 'x64/Steam'
|
||||
self.card = home / 'card'
|
||||
self.shared = home / 'x64/shared'
|
||||
for root, tool in ((self.arm, 'droiddeck-proton-arm64'), (self.x64, 'droiddeck-proton-a64')):
|
||||
(root / 'steamapps/common').mkdir(parents=True)
|
||||
(root / 'config').mkdir()
|
||||
(root / 'compatibilitytools.d/proton').mkdir(parents=True)
|
||||
(root / 'compatibilitytools.d/proton/compatibilitytool.vdf').write_text(
|
||||
'"compatibilitytools"\n{\n\t"compat_tools"\n\t{\n\t\t"%s"\n\t\t{\n\t\t}\n\t}\n}\n' % tool)
|
||||
(self.arm / 'config/config.vdf').write_text(CONFIG % mapping(_0='droiddeck-proton-arm64', _413150='droiddeck-fex'))
|
||||
(self.x64 / 'config/config.vdf').write_text(CONFIG % '')
|
||||
self.install(self.arm, '413150', 'Stardew Valley')
|
||||
self.install(self.arm, '13210', 'Unreal Tournament 3')
|
||||
self.install(self.arm, '1493710', 'Proton - Experimental')
|
||||
|
||||
def install(self, root, app, folder, updated=100):
|
||||
(root / 'steamapps/common' / folder).mkdir(parents=True, exist_ok=True)
|
||||
(root / 'steamapps/common' / folder / 'game.bin').write_text('x')
|
||||
(root / ('steamapps/appmanifest_%s.acf' % app)).write_text(manifest(app, folder, updated))
|
||||
|
||||
def run_share(self, here):
|
||||
with contextlib.redirect_stdout(io.StringIO()):
|
||||
return SHARE['main']([here, str(self.arm), str(self.x64), str(self.card), str(self.shared)])
|
||||
|
||||
def view(self, *parts):
|
||||
return self.shared.joinpath('arm64', 'steamapps', *parts)
|
||||
|
||||
def test_x64_client_sees_arm64_games_in_place(self):
|
||||
self.assertEqual(self.run_share('x86-64'), 0)
|
||||
self.assertEqual(os.readlink(self.view('common/Stardew Valley')), str(self.arm / 'steamapps/common/Stardew Valley'))
|
||||
self.assertTrue(self.view('appmanifest_413150.acf').is_file())
|
||||
self.assertTrue(self.view('appmanifest_13210.acf').is_file())
|
||||
self.assertFalse(self.view('appmanifest_1493710.acf').exists())
|
||||
folders = (self.x64 / 'steamapps/libraryfolders.vdf').read_text()
|
||||
self.assertIn(str(self.shared / 'arm64'), folders)
|
||||
self.assertIn('ARM64 client games', folders)
|
||||
|
||||
def test_tools_follow_the_other_client(self):
|
||||
self.run_share('x86-64')
|
||||
tools = SHARE['entries']((self.x64 / 'config/config.vdf').read_text())
|
||||
self.assertEqual(tools['413150'], 'droiddeck-direct')
|
||||
self.assertEqual(tools['13210'], 'droiddeck-proton-a64')
|
||||
|
||||
def test_a_proton_pick_stays_when_the_other_client_uses_another_proton(self):
|
||||
(self.x64 / 'config/config.vdf').write_text(CONFIG % mapping(_13210='droiddeck-proton-11-a64'))
|
||||
self.run_share('x86-64')
|
||||
self.assertEqual(SHARE['entries']((self.x64 / 'config/config.vdf').read_text())['13210'], 'droiddeck-proton-11-a64')
|
||||
|
||||
def test_an_automatic_proton_gives_way_to_the_installed_linux_build(self):
|
||||
self.install(self.x64, '550', 'Left 4 Dead 2')
|
||||
(self.x64 / 'config/config.vdf').write_text(CONFIG % mapping(_550='droiddeck-direct'))
|
||||
(self.arm / 'config/config.vdf').write_text(CONFIG % mapping(_0='droiddeck-proton-arm64', _550='droiddeck-proton-arm64'))
|
||||
self.run_share('arm64')
|
||||
self.assertEqual(SHARE['entries']((self.arm / 'config/config.vdf').read_text())['550'], 'droiddeck-fex')
|
||||
|
||||
def test_an_x64_proton_pick_reaches_the_arm64_client(self):
|
||||
self.install(self.x64, '550', 'Left 4 Dead 2')
|
||||
(self.x64 / 'config/config.vdf').write_text(CONFIG % mapping(_550='droiddeck-proton-a64'))
|
||||
self.run_share('arm64')
|
||||
self.assertEqual(SHARE['entries']((self.arm / 'config/config.vdf').read_text())['550'], 'droiddeck-proton-arm64')
|
||||
|
||||
def test_a_tool_the_user_chose_is_kept(self):
|
||||
(self.x64 / 'config/config.vdf').write_text(CONFIG % mapping(_13210='my-proton'))
|
||||
self.run_share('x86-64')
|
||||
self.assertEqual(SHARE['entries']((self.x64 / 'config/config.vdf').read_text())['13210'], 'my-proton')
|
||||
|
||||
def test_own_install_wins(self):
|
||||
self.install(self.x64, '413150', 'Stardew Valley')
|
||||
self.run_share('x86-64')
|
||||
self.assertFalse(self.view('appmanifest_413150.acf').exists())
|
||||
self.assertFalse(os.path.lexists(self.view('common/Stardew Valley')))
|
||||
|
||||
def test_newer_update_goes_back_to_the_source(self):
|
||||
self.run_share('x86-64')
|
||||
self.view('appmanifest_413150.acf').write_text(manifest('413150', 'Stardew Valley', 200))
|
||||
self.run_share('x86-64')
|
||||
self.assertIn('"LastUpdated"\t\t"200"', (self.arm / 'steamapps/appmanifest_413150.acf').read_text())
|
||||
|
||||
def test_uninstall_from_the_view_hides_until_reinstalled(self):
|
||||
self.run_share('x86-64')
|
||||
self.view('appmanifest_13210.acf').unlink()
|
||||
self.run_share('x86-64')
|
||||
self.assertFalse(os.path.lexists(self.view('common/Unreal Tournament 3')))
|
||||
self.assertTrue((self.arm / 'steamapps/common/Unreal Tournament 3/game.bin').is_file())
|
||||
self.run_share('x86-64')
|
||||
self.assertFalse(self.view('appmanifest_13210.acf').exists())
|
||||
self.install(self.arm, '13210', 'Unreal Tournament 3', 300)
|
||||
self.run_share('x86-64')
|
||||
self.assertTrue(self.view('appmanifest_13210.acf').is_file())
|
||||
|
||||
def test_files_deleted_through_the_view_drop_the_source_manifest(self):
|
||||
self.run_share('x86-64')
|
||||
(self.arm / 'steamapps/common/Unreal Tournament 3/game.bin').unlink()
|
||||
self.view('appmanifest_13210.acf').unlink()
|
||||
self.run_share('x86-64')
|
||||
self.assertFalse((self.arm / 'steamapps/appmanifest_13210.acf').exists())
|
||||
|
||||
def test_removed_source_leaves_the_view(self):
|
||||
self.run_share('x86-64')
|
||||
(self.arm / 'steamapps/appmanifest_413150.acf').unlink()
|
||||
self.run_share('x86-64')
|
||||
self.assertFalse(self.view('appmanifest_413150.acf').exists())
|
||||
self.assertFalse(os.path.lexists(self.view('common/Stardew Valley')))
|
||||
state = json.loads((self.shared / 'arm64/.droiddeck-shared.json').read_text())
|
||||
self.assertNotIn('413150', state['shared'])
|
||||
|
||||
def test_arm64_client_sees_x64_games(self):
|
||||
self.install(self.x64, '550', 'Left 4 Dead 2')
|
||||
(self.x64 / 'config/config.vdf').write_text(CONFIG % mapping(_550='droiddeck-direct'))
|
||||
self.run_share('arm64')
|
||||
self.assertTrue(self.shared.joinpath('x86-64/steamapps/appmanifest_550.acf').is_file())
|
||||
self.assertEqual(SHARE['entries']((self.arm / 'config/config.vdf').read_text())['550'], 'droiddeck-fex')
|
||||
self.assertIn('x86-64 client games', (self.arm / 'steamapps/libraryfolders.vdf').read_text())
|
||||
|
||||
def test_an_empty_view_is_not_offered(self):
|
||||
self.run_share('x86-64')
|
||||
for app in ('413150', '13210', '1493710'):
|
||||
(self.arm / ('steamapps/appmanifest_%s.acf' % app)).unlink()
|
||||
self.run_share('x86-64')
|
||||
self.assertNotIn(str(self.shared / 'arm64'), (self.x64 / 'steamapps/libraryfolders.vdf').read_text())
|
||||
|
||||
def test_unfinished_installs_are_not_shared(self):
|
||||
(self.arm / 'steamapps/appmanifest_413150.acf').write_text(manifest('413150', 'Stardew Valley', flags=1026))
|
||||
self.run_share('x86-64')
|
||||
self.assertFalse(self.view('appmanifest_413150.acf').exists())
|
||||
|
||||
def test_bad_arguments(self):
|
||||
with contextlib.redirect_stdout(io.StringIO()):
|
||||
self.assertEqual(SHARE['main'](['mips']), 2)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -203,6 +203,30 @@ class ShortcutsTest(unittest.TestCase):
|
||||
self.assertEqual('-vulkan', steam['LaunchOptions'])
|
||||
self.assertEqual('Mine', steam['AppName'])
|
||||
|
||||
def users(self, *blocks):
|
||||
body = ''.join('\t"%d"\n\t{\n%s\t}\n' % (76561197960265728 + acct, ''.join('\t\t"%s"\t\t"%s"\n' % kv for kv in keys.items()))
|
||||
for acct, keys in blocks)
|
||||
(self.steam / 'config').mkdir(exist_ok=True)
|
||||
(self.steam / 'config/loginusers.vdf').write_text('"users"\n{\n%s}\n' % body)
|
||||
(self.steam / 'userdata/456/config').mkdir(parents=True, exist_ok=True)
|
||||
|
||||
def test_the_account_marked_most_recent_is_used(self):
|
||||
self.users((123, dict(MostRecent='1', AutoLogin='0', timestamp='100')), (456, dict(MostRecent='0', AutoLogin='1', timestamp='200')))
|
||||
self.assertEqual(str(self.steam / 'userdata/123'), shortcuts.account_dir(str(self.steam)))
|
||||
|
||||
def test_without_most_recent_the_account_that_signs_in_is_used(self):
|
||||
self.users((123, dict(AutoLogin='1', timestamp='100')), (456, dict(AutoLogin='0', timestamp='200')))
|
||||
self.assertEqual(str(self.steam / 'userdata/123'), shortcuts.account_dir(str(self.steam)))
|
||||
self.assertIn(APPID, self.run_writer(self.game()))
|
||||
|
||||
def test_without_either_mark_the_account_used_last_is_used(self):
|
||||
self.users((456, dict(AutoLogin='0', timestamp='100')), (123, dict(AutoLogin='0', timestamp='200')))
|
||||
self.assertEqual(str(self.steam / 'userdata/123'), shortcuts.account_dir(str(self.steam)))
|
||||
|
||||
def test_two_accounts_without_any_mark_write_nothing(self):
|
||||
self.users((123, dict(AccountName='a')), (456, dict(AccountName='b')))
|
||||
self.assertIsNone(shortcuts.account_dir(str(self.steam)))
|
||||
|
||||
def test_an_older_record_without_launch_options_still_takes_the_apps(self):
|
||||
self.run_writer(self.game())
|
||||
record = self.record()
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
BIN = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin'
|
||||
SHIM = BIN / 'droiddeck-steamrt-shim'
|
||||
SESSION = (BIN / 'droiddeck-session').read_text()
|
||||
X64 = (BIN / 'droiddeck-steam-x64').read_text()
|
||||
|
||||
|
||||
class SteamrtShimTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.root = Path(self.temp.name)
|
||||
self.client = self.root / 'steamrtarm64'
|
||||
self.client.mkdir()
|
||||
self.shim = self.root / 'shim'
|
||||
|
||||
def runtime(self, path):
|
||||
runtime = self.client / path
|
||||
(runtime / 'bin').mkdir(parents=True)
|
||||
(runtime / 'bin/steam-runtime-check-requirements').write_text('#!/bin/sh\nexit 1\n')
|
||||
(runtime / 'bin/steam-runtime-system-info').write_text('#!/bin/sh\necho info\n')
|
||||
(runtime / 'files').mkdir()
|
||||
(runtime / 'files/marker').write_text('runtime files')
|
||||
return runtime
|
||||
|
||||
def build(self):
|
||||
return subprocess.run(['bash', str(SHIM), str(self.client), str(self.shim)],
|
||||
capture_output=True, text=True, timeout=30)
|
||||
|
||||
def sh(self, *args):
|
||||
return subprocess.run(['sh', *map(str, args)], capture_output=True, text=True, timeout=30)
|
||||
|
||||
def assert_shim(self):
|
||||
result = self.build()
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
self.assertEqual(0, self.sh(self.shim / 'bin/steam-runtime-check-requirements').returncode)
|
||||
self.assertEqual('info\n', self.sh(self.shim / 'bin/steam-runtime-system-info').stdout)
|
||||
self.assertEqual('runtime files', (self.shim / 'files/marker').read_text())
|
||||
launched = self.sh(self.shim / 'bin/steam-runtime-launch-client', '--env=BL_SHIM_TEST=yes',
|
||||
f'--directory={self.root}', '--', 'sh', '-c', 'echo "$BL_SHIM_TEST $(basename "$PWD")"')
|
||||
self.assertEqual(f'yes {self.root.name}\n', launched.stdout)
|
||||
launched = self.sh(self.shim / 'bin/steam-runtime-launch-client', '--env', 'BL_SHIM_TEST=split',
|
||||
'--directory', self.root, '--', 'sh', '-c', 'echo "$BL_SHIM_TEST $(basename "$PWD")"')
|
||||
self.assertEqual(f'split {self.root.name}\n', launched.stdout)
|
||||
missing = self.sh(self.shim / 'bin/steam-runtime-launch-client', '--directory', self.root / 'missing',
|
||||
'--', 'true')
|
||||
self.assertEqual(127, missing.returncode)
|
||||
|
||||
def test_a_client_without_a_container_gets_no_shim(self):
|
||||
self.shim.mkdir()
|
||||
self.assertEqual(1, self.build().returncode)
|
||||
self.assertFalse(self.shim.exists())
|
||||
|
||||
def test_the_pressure_vessel_runtime_is_shimmed(self):
|
||||
self.runtime('pv-runtime/steam-runtime-steamrt')
|
||||
self.assert_shim()
|
||||
|
||||
def test_a_requirements_probe_elsewhere_is_shimmed(self):
|
||||
self.runtime('steam-runtime')
|
||||
self.assert_shim()
|
||||
|
||||
def test_the_arm64_session_starts_a_containerized_client_through_the_shim(self):
|
||||
block = re.search(r'\n( +steam_client=\("\$steam_root/steamrtarm64/steam"\)\n.*?\n fi\n)', SESSION, re.S).group(1)
|
||||
stub = self.root / 'droiddeck-steamrt-shim'
|
||||
for status, shimmed in ((1, False), (0, True)):
|
||||
stub.write_text(f'#!/bin/bash\nexit {status}\n')
|
||||
stub.chmod(0o755)
|
||||
script = 'if :; then\n' + block + 'printf "%s\\n" "${steam_client[@]}"\n'
|
||||
env = dict(os.environ, HOME=str(self.root), steam_root='/steam',
|
||||
PATH=str(self.root) + os.pathsep + os.environ['PATH'])
|
||||
result = subprocess.run(['bash', '-c', script], env=env, capture_output=True, text=True, timeout=30)
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
lines = result.stdout.splitlines()
|
||||
self.assertEqual('/steam/steamrtarm64/steam', lines[-1])
|
||||
self.assertEqual(shimmed, 'Valve containerized the arm64 Steam client' in result.stdout)
|
||||
self.assertEqual(shimmed, any(line.startswith('STEAM_RUNTIME_STEAMRT=') and
|
||||
line.endswith('/.droiddeck-steamrt-shim') for line in lines))
|
||||
|
||||
def test_both_clients_are_told_they_already_run_inside_the_container(self):
|
||||
guard = SESSION.index('export STEAM_STEAMRT_RECURSION_GUARD=1')
|
||||
self.assertLess(guard, SESSION.index('"${steam_client[@]}" "${_bl_ui[@]}"'))
|
||||
self.assertIn('-u STEAM_STEAMRT_RECURSION_GUARD', SESSION[:guard])
|
||||
self.assertIn('export STEAM_STEAMRT_RECURSION_GUARD=1', X64)
|
||||
self.assertIn('droiddeck-steamrt-shim "$STEAM_X64/steamrt64" "$X64_HOME/steamrt-shim" || rm -rf "$X64_HOME/steamrt-shim"', X64)
|
||||
|
||||
|
||||
class SessionChannelTest(unittest.TestCase):
|
||||
BLOCK = re.search(r'\n( +steam_channel=steamdeck_publicbeta\n.*?\n +fi\n)', SESSION, re.S).group(1)
|
||||
|
||||
def channel(self, x64, installer):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
stub = Path(temp) / 'droiddeck-steam-install'
|
||||
stub.write_text('#!/bin/bash\n' + installer + '\n')
|
||||
stub.chmod(0o755)
|
||||
env = dict(os.environ, steam_x64=x64, PATH=temp + os.pathsep + os.environ['PATH'])
|
||||
result = subprocess.run(['bash', '-c', self.BLOCK + 'echo "$steam_channel"\n'], env=env,
|
||||
capture_output=True, text=True, timeout=30)
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
return result.stdout.strip()
|
||||
|
||||
def test_the_arm64_client_follows_the_installed_channel(self):
|
||||
self.assertEqual('steamdeck_stable', self.channel('0', '[ "$1" = --channel ] && echo steamdeck_stable'))
|
||||
|
||||
def test_an_installer_without_an_answer_keeps_the_deck_beta(self):
|
||||
self.assertEqual('steamdeck_publicbeta', self.channel('0', 'exit 1'))
|
||||
|
||||
def test_the_x86_client_keeps_its_own_channel(self):
|
||||
self.assertEqual('steamdeck_publicbeta', self.channel('1', 'echo steamdeck_stable'))
|
||||
|
||||
def test_the_client_branch_on_disk_and_clientbeta_use_the_same_channel(self):
|
||||
self.assertIn('-clientbeta "$steam_channel"', SESSION)
|
||||
self.assertIn('echo "$steam_channel" > "$steam_beta"', SESSION)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -277,11 +277,40 @@ class CloudHooks(unittest.TestCase):
|
||||
for sh in (compat.LAUNCHER_SH, compat.EXTRA_WRAPPER_SH):
|
||||
self.assertIn('bl_run ${BL_TASKSET:-} /usr/local/bin/droiddeck-game-env', sh)
|
||||
self.assertNotIn('exec ${BL_TASKSET:-} /usr/local/bin/droiddeck-game-env', sh)
|
||||
self.assertIn('[ $? -eq 10 ] && BL_STORE_EXIT=1', compat.BL_STORE_SETUP)
|
||||
self.assertIn('[ $rc -eq 10 ] && BL_STORE_EXIT=1', compat.BL_STORE_SETUP)
|
||||
self.assertIn('droiddeck-store-launch --exited --code "$rc" "${BL_STORE_ARGS[@]}"', compat.BL_STORE_SETUP)
|
||||
self.assertIn('exec "$@"', compat.BL_STORE_SETUP)
|
||||
|
||||
|
||||
BNET_EXE = '/root/.local/share/Steam/steamapps/compatdata/2596113170/pfx/drive_c/Program Files (x86)/Battle.net/Battle.net.exe'
|
||||
|
||||
|
||||
class BattleNet(unittest.TestCase):
|
||||
def test_a_games_shortcut_is_handed_to_droiddeck_battlenet(self):
|
||||
self.assertEqual([store.BATTLENET, 'launch', 'Fen'], store.battlenet(['waitforexitandrun', BNET_EXE, '--exec=launch Fen'], env={}))
|
||||
self.assertEqual([store.BATTLENET, 'launch', 'OSI'], store.battlenet(['"%s"' % BNET_EXE, '--exec="launch OSI"'], env={}))
|
||||
self.assertEqual([store.BATTLENET, 'open'], store.battlenet([BNET_EXE], env={}))
|
||||
|
||||
def test_anything_else_and_its_own_starts_are_left_alone(self):
|
||||
other = BNET_EXE.replace('2596113170', '123')
|
||||
self.assertIsNone(store.battlenet([other, '--exec=launch Fen'], env={}))
|
||||
self.assertIsNone(store.battlenet(['/x/Diablo IV/Diablo IV.exe'], env={}))
|
||||
self.assertIsNone(store.battlenet([BNET_EXE, '--exec=launch Fen'], env={'BL_BATTLENET': '1'}))
|
||||
self.assertEqual([store.BATTLENET, 'open'], store.battlenet([BNET_EXE, '--exec=launch Fen;rm'], env={}))
|
||||
|
||||
def test_the_launch_runs_there_and_the_wrapper_ends_with_it(self):
|
||||
with patch.dict(os.environ, {}, clear=False), patch.object(store.subprocess, 'call', return_value=0) as call:
|
||||
os.environ.pop('BL_BATTLENET', None)
|
||||
self.assertEqual(store.RAN, store.main([BNET_EXE, '--exec=launch Pro']))
|
||||
call.assert_called_once_with([store.BATTLENET, 'launch', 'Pro'])
|
||||
with patch.dict(os.environ, {}, clear=False), patch.object(store.subprocess, 'call', return_value=1):
|
||||
os.environ.pop('BL_BATTLENET', None)
|
||||
self.assertEqual(store.RAN_FAILED, store.main([BNET_EXE, '--exec=launch Pro']))
|
||||
self.assertIn('[ $rc -eq 11 ] && exit 0', compat.BL_STORE_SETUP)
|
||||
self.assertIn('[ $rc -eq 12 ] && exit 1', compat.BL_STORE_SETUP)
|
||||
self.assertLess(compat.BL_STORE_SETUP.index('droiddeck-store-launch "$@"'), compat.BL_STORE_SETUP.index('[ $rc -eq 11 ] && exit 0'))
|
||||
|
||||
|
||||
class Launchers(unittest.TestCase):
|
||||
def test_both_proton_launchers_ask_before_proton_starts(self):
|
||||
sh = compat.LAUNCHER_SH
|
||||
|
||||
@@ -223,5 +223,35 @@ class VencEmulatorTest(unittest.TestCase):
|
||||
self.assertEqual(server.touches, [(0, 65535, 32767), (1, 32767, 0), (2, 32767, 0)])
|
||||
|
||||
|
||||
def test_xtest_calls_from_a_locally_loaded_library_still_reach_libxtst(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
tmp = Path(tmp)
|
||||
(tmp / 'xtst.c').write_text(
|
||||
'int XTestFakeButtonEvent(void *d, unsigned b, int p, unsigned long t) { return 7; }\n'
|
||||
'int XTestFakeMotionEvent(void *d, int s, int x, int y, unsigned long t) { return 7; }\n')
|
||||
(tmp / 'ui.c').write_text(
|
||||
'int XTestFakeButtonEvent(void *, unsigned, int, unsigned long);\n'
|
||||
'int XTestFakeMotionEvent(void *, int, int, int, unsigned long);\n'
|
||||
'int ui_click(void) { return XTestFakeButtonEvent(0, 1, 1, 0) + XTestFakeButtonEvent(0, 3, 0, 0); }\n'
|
||||
'int ui_move(void) { return XTestFakeMotionEvent(0, 0, 10, 20, 0); }\n')
|
||||
(tmp / 'main.c').write_text(
|
||||
'#include <dlfcn.h>\n#include <stdio.h>\n'
|
||||
'int main(int argc, char **argv) {\n'
|
||||
' void *ui = dlopen(argv[1], RTLD_NOW | RTLD_LOCAL);\n'
|
||||
' if (!ui) return 2;\n'
|
||||
' int (*click)(void) = dlsym(ui, "ui_click"), (*move)(void) = dlsym(ui, "ui_move");\n'
|
||||
' printf("%d %d\\n", click(), move());\n'
|
||||
' return click() == 14 && move() == 7 ? 0 : 1;\n'
|
||||
'}\n')
|
||||
run = lambda *a: subprocess.run(['cc', *a], check=True, cwd=tmp)
|
||||
run('-shared', '-fPIC', '-Wl,-soname,libXtst.so.6', '-o', 'libXtst.so.6', 'xtst.c')
|
||||
run('-shared', '-fPIC', '-o', 'libui.so', 'ui.c', '-L.', '-l:libXtst.so.6', "-Wl,-rpath,$ORIGIN")
|
||||
run('-shared', '-fPIC', '-pthread', '-o', 'libhook.so', str(VENC), str(TOUCH), '-ldl')
|
||||
run('-o', 'main', 'main.c', '-ldl')
|
||||
done = subprocess.run([str(tmp / 'main'), str(tmp / 'libui.so')],
|
||||
env=dict(os.environ, LD_PRELOAD=str(tmp / 'libhook.so')),
|
||||
capture_output=True, text=True, timeout=20)
|
||||
self.assertEqual(done.returncode, 0, done.stdout + done.stderr)
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -31,14 +31,14 @@ class XboxBuildSourceTest(unittest.TestCase):
|
||||
git('switch', '-q', 'main')
|
||||
(root / 'backend').write_text('merged backend')
|
||||
git('commit', '-qam', 'backend changed after branch')
|
||||
for name in ('xbox', 'apk'):
|
||||
for name in ('source', 'xbox', 'components', 'apk', 'tests', 'dispatch'):
|
||||
git('clone', '-q', str(root), str(root / name))
|
||||
git('checkout', '-q', head, cwd=root / name)
|
||||
output = root / 'output'
|
||||
env['GITHUB_OUTPUT'] = str(output)
|
||||
subprocess.run(['bash', '-c', step('xbox', 'Pin and merge the APK source')], cwd=root / 'xbox', env=env, check=True, capture_output=True)
|
||||
subprocess.run(['bash', '-c', step('source', 'Pin and merge the APK source')], cwd=root / 'source', env=env, check=True, capture_output=True)
|
||||
base = output.read_text().strip().split('=', 1)[1]
|
||||
tree = git('rev-parse', 'HEAD^{tree}', cwd=root / 'xbox')
|
||||
tree = git('rev-parse', 'HEAD^{tree}', cwd=root / 'source')
|
||||
(root / 'backend').write_text('newer main, after backend build')
|
||||
git('commit', '-qam', 'main advanced again')
|
||||
env.update(BUILD_BASE_SHA=base, XBOX_SOURCE_TREE=tree)
|
||||
@@ -46,3 +46,19 @@ class XboxBuildSourceTest(unittest.TestCase):
|
||||
subprocess.run(['bash', '-c', step('build', 'Verify backend and APK source match')], cwd=root / 'apk', env=env, check=True, capture_output=True)
|
||||
self.assertEqual((root / 'apk/backend').read_text(), 'merged backend')
|
||||
self.assertEqual(git('rev-parse', 'HEAD^{tree}', cwd=root / 'apk'), tree)
|
||||
|
||||
subprocess.run(['bash', '-c', step('python-tests', 'Merge the pinned APK base')], cwd=root / 'tests', env=env, check=True, capture_output=True)
|
||||
subprocess.run(['bash', '-c', step('python-tests', 'Verify backend and test source match')], cwd=root / 'tests', env=env, check=True, capture_output=True)
|
||||
self.assertEqual(git('rev-parse', 'HEAD^{tree}', cwd=root / 'tests'), tree)
|
||||
|
||||
env['SOURCE_TREE'] = tree
|
||||
for job in ('xbox', 'components'):
|
||||
subprocess.run(['bash', '-c', step(job, 'Merge the pinned APK base')], cwd=root / job, env=env, check=True, capture_output=True)
|
||||
subprocess.run(['bash', '-c', step(job, 'Verify pinned source tree')], cwd=root / job, env=env, check=True, capture_output=True)
|
||||
self.assertEqual(git('rev-parse', 'HEAD^{tree}', cwd=root / job), tree)
|
||||
|
||||
trusted = root / 'trusted-output'
|
||||
env['GITHUB_OUTPUT'] = str(trusted)
|
||||
subprocess.run(['bash', '-c', step('source', 'Resolve trusted manifest base')], cwd=root / 'dispatch', env=env, check=True, capture_output=True)
|
||||
self.assertEqual(trusted.read_text().strip(), 'base-sha=' + git('rev-parse', 'main'))
|
||||
self.assertNotEqual(git('rev-parse', 'HEAD', cwd=root / 'dispatch'), git('rev-parse', 'main'))
|
||||
@@ -1,8 +1,10 @@
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import runpy
|
||||
import socket
|
||||
import subprocess
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
@@ -54,11 +56,13 @@ class XboxLaunchTest(unittest.TestCase):
|
||||
patch.dict(xbox['launch'].__globals__, wine=unittest.mock.Mock(return_value=7)):
|
||||
launch = xbox['launch']
|
||||
self.assertEqual(launch(['/proton', 'waitforexitandrun', '/encrypted/Game.exe'],
|
||||
{'BL_LAUNCH_DIR': '/launch', 'DROIDDECK_XBOX_CREDENTIAL_SOCKET': 'stale'}), 7)
|
||||
{'BL_LAUNCH_DIR': '/launch', 'DROIDDECK_XBOX_CREDENTIAL_SOCKET': 'stale',
|
||||
'DROIDDECK_XBOX_CREDENTIAL_PORT': '4100', 'DROIDDECK_XBOX_CREDENTIAL_KEY': 'stale-key'}), 7)
|
||||
wine = launch.__globals__['wine']
|
||||
self.assertEqual(wine.call_args.args[0], ['/private/Game.exe'])
|
||||
env = wine.call_args.args[1]
|
||||
self.assertNotIn('DROIDDECK_XBOX_CREDENTIAL_SOCKET', env)
|
||||
for name in ('DROIDDECK_XBOX_CREDENTIAL_SOCKET', 'DROIDDECK_XBOX_CREDENTIAL_PORT', 'DROIDDECK_XBOX_CREDENTIAL_KEY'):
|
||||
self.assertNotIn(name, env)
|
||||
self.assertEqual(env['XODUS_XSTS_PLAYFAB'], 'game-token')
|
||||
close.assert_called_once()
|
||||
self.assertEqual(store['ask'].call_args.args[1], {'op': 'xbox-released', 'lease': 'lease-1'})
|
||||
@@ -115,7 +119,8 @@ class XboxLaunchTest(unittest.TestCase):
|
||||
command = root / 'command.json'
|
||||
command.write_text(json.dumps(['/selected/proton', 'waitforexitandrun', '/encrypted/Game.exe', '--custom', 'two words']))
|
||||
env = {'STEAM_COMPAT_DATA_PATH': str(prefix.parent), 'DROIDDECK_XBOX_COMMAND_FILE': str(command),
|
||||
'DROIDDECK_XBOX_CREDENTIAL_SOCKET': 'private-account-channel', 'XODUS_BRIDGE_KEY': 'runtime-key'}
|
||||
'DROIDDECK_XBOX_CREDENTIAL_SOCKET': 'private-account-channel', 'DROIDDECK_XBOX_CREDENTIAL_PORT': '4100',
|
||||
'DROIDDECK_XBOX_CREDENTIAL_KEY': 'private-key', 'XODUS_BRIDGE_KEY': 'runtime-key'}
|
||||
with patch.dict(os.environ, env), patch.dict(xbox['wine'].__globals__, RUNTIME=runtime.parent), patch('subprocess.run') as initialize, patch('subprocess.call', return_value=7) as call:
|
||||
initialize.return_value.returncode = 0
|
||||
self.assertEqual(xbox['wine'](['/private-view/Game.exe']), 7)
|
||||
@@ -126,6 +131,43 @@ class XboxLaunchTest(unittest.TestCase):
|
||||
initialize.assert_called_once()
|
||||
for child in (initialize, call):
|
||||
child_env = child.call_args.kwargs['env']
|
||||
self.assertNotIn('DROIDDECK_XBOX_CREDENTIAL_SOCKET', child_env)
|
||||
for name in ('DROIDDECK_XBOX_CREDENTIAL_SOCKET', 'DROIDDECK_XBOX_CREDENTIAL_PORT', 'DROIDDECK_XBOX_CREDENTIAL_KEY'):
|
||||
self.assertNotIn(name, child_env)
|
||||
self.assertNotIn('DROIDDECK_XBOX_COMMAND_FILE', child_env)
|
||||
self.assertEqual(child_env['XODUS_BRIDGE_KEY'], 'runtime-key')
|
||||
|
||||
def test_missing_runtime_classes_are_registered_once(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
prefix = Path(root)
|
||||
key = xbox['CLASS_KEY'].replace('\\', '\\\\')
|
||||
present = [name for names in xbox['CLASSES'].values() for name in names
|
||||
if name != 'Windows.ApplicationModel.DataTransfer.DataTransferManager']
|
||||
(prefix / 'system.reg').write_text(''.join('[%s%s] 1\n"DllPath"="x"\n\n' % (key, name) for name in present))
|
||||
imported = []
|
||||
def run(argv, **kwargs):
|
||||
imported.append(Path(argv[4][2:].replace('\\', '/')).read_bytes()[2:].decode('utf-16-le'))
|
||||
return subprocess.CompletedProcess(argv, 0)
|
||||
with patch('subprocess.run', side_effect=run) as child:
|
||||
xbox['register_classes']('/selected/proton', prefix, {'A': '1'})
|
||||
self.assertEqual(child.call_args.args[0][:4], ['/selected/proton', 'run', 'reg.exe', 'import'])
|
||||
self.assertEqual(child.call_args.kwargs['env'], {'A': '1'})
|
||||
self.assertEqual(imported, ['Windows Registry Editor Version 5.00\r\n\r\n[HKEY_LOCAL_MACHINE\\Software\\Microsoft\\WindowsRuntime'
|
||||
'\\ActivatableClassId\\Windows.ApplicationModel.DataTransfer.DataTransferManager]\r\n'
|
||||
'"DllPath"="C:\\\\windows\\\\system32\\\\twinapi.appcore.dll"\r\n\r\n'])
|
||||
with (prefix / 'system.reg').open('a') as file:
|
||||
file.write('[%sWindows.ApplicationModel.DataTransfer.DataTransferManager] 1\n' % key)
|
||||
with patch('subprocess.run') as child:
|
||||
xbox['register_classes']('/selected/proton', prefix, {})
|
||||
(prefix / 'system.reg').unlink()
|
||||
xbox['register_classes']('/selected/proton', prefix, {})
|
||||
child.assert_not_called()
|
||||
|
||||
def test_failed_class_registration_is_reported_and_launch_continues(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
prefix = Path(root)
|
||||
(prefix / 'system.reg').write_text('')
|
||||
for outcome in ({'return_value': subprocess.CompletedProcess([], 1)},
|
||||
{'side_effect': subprocess.TimeoutExpired('reg.exe', 90)}):
|
||||
with patch('subprocess.run', **outcome), patch('sys.stderr', new_callable=io.StringIO) as err:
|
||||
self.assertIsNone(xbox['register_classes']('/selected/proton', prefix, {}))
|
||||
self.assertIn('registration failed', err.getvalue())
|
||||
Reference in new issue
Block a user