Merge DroidDeck 0.5.0 into the non-Adreno test branch

Conflicts kept both sides: the 0.5.0 GPU drivers redesign (Auto / pair / mix modes, rollback of
a pair that never starts a session) with the test branch's Mali, PowerVR and Xclipse rules (Mali
display on the phone's own driver, bridge and system-Vulkan fallbacks, 1-hour list refresh for the
open drivers); the test branch's Update button for rebuilt open pairs moved into 0.5.0's new GPU
drivers panel; Venus GL probing, the Mali compatibility layer and oom_score_adj redirect kept with
0.5.0's x86-64 Steam client, VAC diagnostics and caller-aware preload hooks.
This commit is contained in:
The412Banner committed 2026-10-19 08:51:42 +00:00
commit bab999038f
616 files changed
+83918 -2233

No files matched your search

+83
View File
@@ -0,0 +1,83 @@
const assert = require('assert');
const vm = require('vm');
const source = require('fs').readFileSync(process.argv[2], 'utf8');
const calls = [], requests = [], errors = [], timers = new Set();
let changed;
const apps = { RunGame(...args) { calls.push({receiver: this, args}); return 'native'; } };
const openvr = {
RegisterForVRModeChange(callback) { changed = callback; callback(false); return {unregister() {}}; },
StartVR(...args) { return args; },
};
const overview = new Map([
['611670', {vr_only: true}],
['620980', {vr_supported: true}],
['730', {vr_only: false, vr_supported: false}],
['18446744069414584320', {BSupportsVR() { return true; }}],
]);
const context = {
SteamClient: {Apps: apps, OpenVR: openvr},
appStore: {GetAppOverviewByGameID: id => overview.get(id)},
droiddeckLaunchSteamVr: id => requests.push(id),
setTimeout(callback, ms) { assert.strictEqual(ms, 600000); timers.add(callback); return callback; },
clearTimeout: timer => timers.delete(timer),
console: {error: message => errors.push(message)},
};
context.window = context;
vm.createContext(context);
assert.strictEqual(vm.runInContext(source, context), 'installed');
assert.strictEqual(vm.runInContext(source, context), 'present');
assert.strictEqual(apps.RunGame(730, '', -1, 100), 'native');
assert.deepStrictEqual(requests, []);
assert.strictEqual(calls[0].receiver, apps);
const receiver = {};
apps.RunGame.call(receiver, '611670', 'custom args', 2, 100);
apps.RunGame('611670', 'duplicate', -1, 100);
assert.strictEqual(apps.RunGame(620980, '', -1, 100), 'native');
assert.deepStrictEqual(requests, ['611670']);
assert.strictEqual(calls.length, 2);
assert.deepStrictEqual(calls[1].args, [620980, '', -1, 100]);
changed(false);
assert.strictEqual(calls.length, 2);
changed(true);
assert.strictEqual(calls.length, 3);
assert.strictEqual(calls[2].receiver, receiver);
assert.deepStrictEqual(calls[2].args, ['611670', 'custom args', 2, 100]);
assert.strictEqual(timers.size, 0);
changed(true);
assert.strictEqual(calls.length, 3);
changed(false);
assert.strictEqual(apps.RunGame('18446744069414584320', '', -1, 100), 'native');
assert.deepStrictEqual(calls[3].args, ['18446744069414584320', '', -1, 100]);
assert.deepStrictEqual(requests, ['611670']);
assert.strictEqual(timers.size, 0);
changed(true);
apps.RunGame('250820', '', -1, 100);
openvr.StartVR(true);
assert.deepStrictEqual(requests.slice(-2), ['250820', '250820']);
assert.strictEqual(calls.length, 4);
changed(false);
apps.RunGame('611670', '', -1, 100);
for (const timeout of [...timers]) { timers.delete(timeout); timeout(); }
assert.strictEqual(context.__droiddeckSteamVr.pending.size, 0);
assert.strictEqual(errors.length, 1);
changed(true);
assert.strictEqual(calls.length, 4);
apps.RunGame('611670', '', -1, 100);
assert.strictEqual(calls.length, 5);
assert.strictEqual(context.__droiddeckSteamVr.lastError, null);
changed(false);
context.droiddeckLaunchSteamVr = () => { throw new Error('bridge disconnected'); };
assert.throws(() => apps.RunGame('611670', '', -1, 100), /bridge disconnected/);
assert.strictEqual(context.__droiddeckSteamVr.pending.size, 0);
assert.strictEqual(timers.size, 0);
delete context.droiddeckLaunchSteamVr;
assert.strictEqual(apps.RunGame('611670', '', -1, 100), 'native');
assert.strictEqual(apps.RunGame('250820', '', -1, 100), 'native');
assert.deepStrictEqual(openvr.StartVR(true), [true]);
assert.strictEqual(calls.length, 7);
+35
View File
@@ -0,0 +1,35 @@
import importlib.util
import io
from pathlib import Path
import unittest
import zipfile
spec = importlib.util.spec_from_file_location('build_hand_lite', Path(__file__).parents[1] / 'build_hand_lite.py')
builder = importlib.util.module_from_spec(spec)
spec.loader.exec_module(builder)
class HandLiteBundleTest(unittest.TestCase):
def test_embedded_labels_are_reproducible_without_changing_model_bytes(self):
model = b'\x08\x00\x00\x00TFL3model tensors and weights'
outputs = []
for year, order in [(2020, ['labels.txt', 'handedness.txt']),
(2026, ['handedness.txt', 'labels.txt'])]:
source = io.BytesIO(model)
with zipfile.ZipFile(source, 'a') as archive:
for name in order:
entry = zipfile.ZipInfo(name, (year, 10, 16, 12, 30, 0))
archive.writestr(entry, name.encode())
output = builder.canonicalize_associated_files(source.getvalue())
self.assertEqual(model, output[:len(model)])
self.assertEqual(output, builder.canonicalize_associated_files(output))
with zipfile.ZipFile(io.BytesIO(output)) as archive:
for name in order:
self.assertEqual(name.encode(), archive.read(name))
outputs.append(output)
self.assertEqual(*outputs)
if __name__ == '__main__':
unittest.main()
+59
View File
@@ -516,6 +516,65 @@ class ProtonRunTest(Temp):
self.assertEqual(env["SteamAppId"], "413150")
self.assertTrue((self.root / "steamapps/compatdata/413150").is_dir())
def run_main(self, argv):
calls, dirs = [], []
with mock.patch.dict(os.environ, {"STEAM_COMPAT_CLIENT_INSTALL_PATH": str(self.root)}), \
mock.patch.object(RUN["os"], "execve", lambda *a: calls.append(a)), \
mock.patch.object(RUN["os"], "chdir", dirs.append), mock.patch.dict(RUN, {"say": lambda message: None}):
code = RUN["main"](argv)
return code, calls, dirs
def test_without_steam_a_steam_game_starts_its_default_windows_launch(self):
info = {"common": {"type": "Game", "oslist": "windows,linux"}, "config": {"launch": {
"0": {"executable": "Bin\\Game.exe", "arguments": "-dx11 \"-name=Two Words\"", "workingdir": "bin",
"type": "default", "config": {"oslist": "windows"}},
"1": {"executable": "game.sh", "type": "default", "config": {"oslist": "linux"}},
"2": {"executable": "Beta.exe", "type": "default", "config": {"oslist": "windows", "betakey": "beta"}},
"3": {"executable": "Tools\\Editor.exe", "type": "option1"},
}}}
self.write("Steam/appcache/appinfo.vdf", appinfo({413150: info}))
program = self.game("413150", "Some Game", "bin/game.exe")
self.game("413150", "Some Game", "Tools/Editor.exe")
code, calls, dirs = self.run_main(["--app", "413150", "--options", "-windowed"])
self.assertIsNone(code)
entry, argv, env = calls[0]
self.assertEqual(argv[1:], ["waitforexitandrun", str(program), "-dx11", "-name=Two Words", "-windowed"])
self.assertEqual((env["SteamAppId"], env["STEAM_COMPAT_DATA_PATH"]),
("413150", str(self.root / "steamapps/compatdata/413150")))
self.assertEqual(dirs, [str(program.parent)])
def test_without_steam_a_game_steam_cannot_start_is_refused(self):
self.write("Steam/appcache/appinfo.vdf", appinfo({413150: STARDEW}))
self.assertEqual(self.run_main(["--app", "413150"])[0], 2)
self.assertEqual(self.run_main(["--app", "3384071994"])[0], 2)
self.assertEqual(self.run_main(["--app", "0"])[0], 2)
self.assertEqual(self.run_main(["--app", "game"])[0], 2)
linux = {"common": {"type": "Game"}, "config": {"launch": {"0": {"executable": "run.sh", "config": {"oslist": "linux"}}}}}
self.write("Steam/appcache/appinfo.vdf", appinfo({70: linux}))
self.game("70", "Linux Game", "run.sh")
self.assertEqual(self.run_main(["--app", "70"])[0], 2)
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"
start.mkdir()
code, calls, dirs = self.run_main(["--app", "2733369024", "--dir", str(start), "--options",
"PROTON_LOG=1 %command% -epicportal", "--", str(bat)])
self.assertIsNone(code)
entry, argv, env = calls[0]
self.assertEqual(argv[1:], ["waitforexitandrun", str(bat), "-epicportal"])
self.assertEqual((env["STEAM_COMPAT_DATA_PATH"], env["SteamAppId"], env["SteamGameId"], env["PROTON_LOG"]),
(str(self.root / "steamapps/compatdata/2733369024"), "0", str(2733369024 << 32 | 0x02000000), "1"))
self.assertTrue((self.root / "steamapps/compatdata/2733369024").is_dir())
self.assertEqual(dirs, [str(start)])
def test_launch_options_split_like_steam_does(self):
split = RUN["split_options"]
self.assertEqual(split(""), ({}, []))
self.assertEqual(split("-windowed -w 1280"), ({}, ["-windowed", "-w", "1280"]))
self.assertEqual(split("A=1 B=\"x y\" gamemoderun %command% -dx12"), ({"A": "1", "B": "x y"}, ["-dx12"]))
self.assertEqual(split("\"unterminated -x"), ({}, ["\"unterminated", "-x"]))
if __name__ == "__main__":
unittest.main()
+77
View File
@@ -291,6 +291,53 @@ class AgentTest(unittest.TestCase):
self.assertFalse(result["supported"])
evaluate.assert_not_called()
def test_shortcut_state_tells_a_lost_shortcut_from_a_loading_library(self):
game_id = str((3333273269 << 32) | 0x02000000)
self.assertEqual("not-shortcut", agent.steam_shortcut_state(self.dir, "413150"))
for values, wanted, calls in ((["loading", "ready"], "ready", 2), (["loading", "missing"], "missing", 3),
([None], "loading", 3)):
clock = [0.0]
replies = [{"value": v} for v in values] + [{"value": values[-1]}] * 10
with self.subTest(values=values), patch.object(agent, "cdp_eval", side_effect=replies) as evaluate, \
patch.object(agent.time, "monotonic", side_effect=lambda: clock[0]), \
patch.object(agent.time, "sleep", side_effect=lambda delay: clock.__setitem__(0, clock[0] + delay)):
self.assertEqual(wanted, agent.steam_shortcut_state(self.dir, game_id, timeout=1))
self.assertEqual(calls, evaluate.call_count)
self.assertIn("GetAppOverviewByGameID(%s)" % json.dumps(game_id), evaluate.call_args_list[0].args[1])
def test_shortcut_state_waits_out_an_unreachable_client_but_not_other_errors(self):
game_id = str((3333273269 << 32) | 0x02000000)
clock = [0.0]
with patch.object(agent, "cdp_eval", side_effect=agent.AgentError("NO_DEVTOOLS", "down")), \
patch.object(agent.time, "monotonic", side_effect=lambda: clock[0]), \
patch.object(agent.time, "sleep", side_effect=lambda delay: clock.__setitem__(0, clock[0] + delay)):
self.assertEqual("loading", agent.steam_shortcut_state(self.dir, game_id, timeout=1))
with patch.object(agent, "cdp_eval", side_effect=agent.AgentError("CDP_EXCEPTION", "boom")):
with self.assertRaises(agent.AgentError):
agent.steam_shortcut_state(self.dir, game_id, timeout=1)
def test_shortcut_state_command_exits_with_the_state(self):
game_id = str((3333273269 << 32) | 0x02000000)
launch = self.dir.parent
with patch.dict(os.environ, {"BL_LAUNCH_DIR": str(launch)}):
for state, code in (("ready", 0), ("missing", 4), ("not-shortcut", 3), ("loading", 1)):
with self.subTest(state=state), patch.object(agent, "steam_shortcut_state", return_value=state) as ask:
self.assertEqual(code, agent.main(["--steam-shortcut-state", game_id, "2"]))
self.assertEqual((launch / "agent", game_id, "2"), ask.call_args.args)
with patch.object(agent, "steam_shortcut_state", side_effect=agent.AgentError("CDP_EXCEPTION", "boom")):
self.assertEqual(1, agent.main(["--steam-shortcut-state", game_id]))
self.assertEqual(2, agent.main(["--steam-shortcut-state"]))
def test_asleep_command_reports_steams_own_sleep_state(self):
with patch.dict(os.environ, {"BL_LAUNCH_DIR": str(self.dir.parent)}):
for value, code in (("yes", 0), ("no", 5), ("unknown", 1), (None, 1)):
with self.subTest(value=value), patch.object(agent, "cdp_eval", return_value={"value": value}) as ask:
self.assertEqual(code, agent.main(["--steam-asleep"]))
self.assertIn("m_bSuspending", ask.call_args.args[1])
self.assertFalse(ask.call_args.kwargs["await_promise"])
with patch.object(agent, "cdp_eval", side_effect=agent.AgentError("NO_DEVTOOLS", "down")):
self.assertEqual(1, agent.main(["--steam-asleep"]))
def test_cdp_exception(self):
server = FakeDevTools({"result": {"result": {"type": "object"}, "exceptionDetails": {
"text": "Uncaught", "exception": {"description": "ReferenceError: SteamClient is not defined"}}}})
@@ -335,5 +382,35 @@ class AgentTest(unittest.TestCase):
self.assertIn(child.pid, agent.game_pids(424242))
class VrFocusTest(unittest.TestCase):
def test_scene_dashboard_and_external_focus_changes(self):
focus = agent.VrSceneFocus()
self.assertEqual(focus.order([9, 7], [7, 42], 42), [42, 9, 7])
self.assertIsNone(focus.order([42, 9, 7], [7, 42], 42))
self.assertEqual(focus.order([42, 9, 7], [7, 42], None), [9, 7])
self.assertIsNone(focus.order([9, 7], [7], 42))
self.assertEqual(focus.order([9, 7], [7, 42], 42), [42, 9, 7])
# Do not overwrite a different focus order installed after our last write.
self.assertIsNone(focus.order([123, 7], [7, 42], None))
def test_scene_requires_live_server_and_game_environment(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
state = root / 'scene.json'
for pid in (100, 200):
(root / str(pid)).mkdir()
(root / '100/comm').write_text('vrserver\n')
(root / '200/environ').write_bytes(b'SteamAppId=42\0Other=value\0')
state.write_text(json.dumps(dict(serverPid=100, scenePid=200, dashboard=False)))
self.assertEqual(agent.vr_scene_app(state, root), 42)
state.write_text(json.dumps(dict(serverPid=100, scenePid=200, dashboard=True)))
self.assertIsNone(agent.vr_scene_app(state, root))
state.write_text(json.dumps(dict(serverPid=100, scenePid=200, dashboard=False)))
(root / '100/comm').write_text('other\n')
self.assertIsNone(agent.vr_scene_app(state, root))
(root / '100/comm').unlink()
self.assertIsNone(agent.vr_scene_app(state, root))
if __name__ == "__main__":
unittest.main()
File diff suppressed because it is too large. Load diff
+228 -22
View File
@@ -92,6 +92,38 @@ class FexTestCase(unittest.TestCase):
self.write(self.steam / "steamapps/appmanifest_1628350.acf", '"AppState" { "installdir" "SteamLinuxRuntime_sniper" }')
return platform
def graphics(self, sniper, libc=b"GLIBC_2.2.5 GLIBC_2.31 GLIBC_2.34 GLIBC_2.41", libstdcxx=b"GLIBCXX_3.4.28 GLIBCXX_3.4.33"):
files = Path(sniper) / "files"
x86 = files / "lib/x86_64-linux-gnu"
self.write(x86 / "libc-2.31.so", b"GLIBC_2.2.5 GLIBC_2.31")
os.unlink(x86 / "libc.so.6")
os.symlink("libc-2.31.so", x86 / "libc.so.6")
self.write(x86 / "ld-2.31.so", b"old ld")
os.symlink("ld-2.31.so", x86 / "ld-linux-x86-64.so.2")
self.write(x86 / "libstdc++.so.6", b"GLIBCXX_3.4.28")
self.write(x86 / "libSegFault.so", b"old")
self.write(x86 / "libSDL2-2.0.so.0", b"sdl")
self.write(x86 / "libfoo.so.1.2", b"foo")
os.symlink("libfoo.so.1.2", x86 / "libfoo.so.1")
self.write(x86 / "gconv/OLD.so", b"old gconv")
self.write(files / "lib/i386-linux-gnu/libc.so.6", b"GLIBC_2.31")
self.write(files / "lib/i386-linux-gnu/ld-2.31.so", b"old ld32")
os.symlink("i386-linux-gnu/ld-2.31.so", files / "lib/ld-linux.so.2")
os.unlink(files / "lib64/ld-linux-x86-64.so.2")
os.symlink("../lib/x86_64-linux-gnu/ld-2.31.so", files / "lib64/ld-linux-x86-64.so.2")
platform = self.steam / "steamapps/common/SteamLinuxRuntime_4/steamrt4_platform_4.0.20260928.262390"
provided = platform / "files/lib/x86_64-linux-gnu"
self.write(provided / "libc.so.6", libc)
self.write(provided / "libstdc++.so.6", libstdcxx)
self.write(provided / "ld-linux-x86-64.so.2", b"new ld")
self.write(provided / "gconv/NEW.so", b"new gconv")
self.write(platform / "files/lib/i386-linux-gnu/libc.so.6", b"GLIBC_2.41")
self.write(platform / "files/lib/i386-linux-gnu/ld-linux.so.2", b"new ld32")
with gzip.open(platform / "usr-mtree.txt.gz", "wt") as out:
out.write("#mtree\n. type=dir\n")
self.write(self.steam / "steamapps/appmanifest_4183110.acf", '"AppState" { "installdir" "SteamLinuxRuntime_4" }')
return platform
def quiet(self, function, *args):
with contextlib.redirect_stderr(io.StringIO()) as err:
return function(*args), err.getvalue()
@@ -198,12 +230,11 @@ class PrepareTest(FexTestCase):
for arch in ("x86_64", "i386"):
for name in ("libblsession.so", "libfakeinput.so"):
self.write(self.tmp / "preloads" / arch / name, arch.encode() + name.encode())
self.write(self.tmp / "preloads/x86_64/libthunkaudit.so", b"audit")
self.write(self.tmp / "preloads/x86_64/libvulkan-thunk.so", b"pin")
self.write(self.tmp / "ld.so.preload", "/usr/local/lib/libblsession.so\n/usr/local/lib/libfakeinput.so\n")
FEX["install_preloads"](str(root))
self.assertEqual((root / "lib/x86_64-linux-gnu/droiddeck/libthunkaudit.so").read_bytes(), b"audit")
self.assertEqual((root / "lib/x86_64-linux-gnu/droiddeck/libvulkan-thunk.so").read_bytes(), b"pin")
self.assertEqual((root / "lib/x86_64-linux-gnu/droiddeck/vulkan/libvulkan.so.1").read_bytes(), b"pin")
self.assertEqual(os.readlink(root / "lib/x86_64-linux-gnu/droiddeck/vulkan/libvulkan.so"), "libvulkan.so.1")
self.assertEqual((root / "etc/ld.so.preload").read_text(),
"/usr/$LIB/droiddeck/libblsession.so\n/usr/$LIB/droiddeck/libfakeinput.so\n")
self.assertEqual((root / "lib/i386-linux-gnu/droiddeck/libfakeinput.so").read_bytes(), b"i386libfakeinput.so")
@@ -252,7 +283,71 @@ class PrepareTest(FexTestCase):
status = json.loads((self.home / ".local/share/droiddeck-fex/status.json").read_text())
self.assertEqual((status["ready"], status["runtime"], status["thunks"]), (True, str(platform), True))
self.assertFalse((self.home / ".config/droiddeck/fex-wanted").exists())
self.assertEqual(self.quiet(FEX["prepare"])[1], "")
self.assertNotIn("prepared", self.quiet(FEX["prepare"])[1])
def test_a_newer_runtime_supplies_the_c_and_cxx_libraries(self):
self.fex_tool()
sniper = self.runtime()
FEX["materialize"](str(sniper))
provider = self.graphics(sniper)
fex, said = self.quiet(FEX["prepare"])
root = self.home / ".local/share/droiddeck-fex/rootfs"
self.assertIn("built the x86 runtime from sniper_platform_", said)
self.assertEqual(fex["rootfs"], str(root))
config = json.loads((self.home / ".local/share/droiddeck-fex/config/Config.json").read_text())
self.assertEqual(config["Config"]["RootFS"], str(root))
x86 = root / "lib/x86_64-linux-gnu"
self.assertEqual((x86 / "libc.so.6").read_bytes(), b"GLIBC_2.2.5 GLIBC_2.31 GLIBC_2.34 GLIBC_2.41")
self.assertEqual((x86 / "libstdc++.so.6").read_bytes(), b"GLIBCXX_3.4.28 GLIBCXX_3.4.33")
self.assertEqual((x86 / "ld-linux-x86-64.so.2").read_bytes(), b"new ld")
self.assertEqual((x86 / "gconv/NEW.so").read_bytes(), b"new gconv")
self.assertEqual((root / "lib/i386-linux-gnu/libc.so.6").read_bytes(), b"GLIBC_2.41")
self.assertEqual((x86 / "libSDL2-2.0.so.0").read_bytes(), b"sdl")
self.assertEqual(os.readlink(x86 / "libfoo.so.1"), "libfoo.so.1.2")
self.assertEqual((x86 / "libfoo.so.1").read_bytes(), b"foo")
for stale in ("libc-2.31.so", "ld-2.31.so", "libSegFault.so"):
self.assertFalse(os.path.lexists(x86 / stale), stale)
self.assertEqual(os.readlink(root / "lib/ld-linux.so.2"), "i386-linux-gnu/ld-linux.so.2")
self.assertEqual((root / "lib/ld-linux.so.2").read_bytes(), b"new ld32")
self.assertEqual(os.readlink(root / "lib64/ld-linux-x86-64.so.2"), "../lib/x86_64-linux-gnu/ld-linux-x86-64.so.2")
self.assertEqual((root / "lib64/ld-linux-x86-64.so.2").read_bytes(), b"new ld")
self.assertEqual(os.readlink(root / "usr"), ".")
self.assertEqual((root / "usr/bin/[").read_bytes(), b"blob")
self.assertEqual((sniper / "files/lib/x86_64-linux-gnu/libc.so.6").read_bytes(), b"GLIBC_2.2.5 GLIBC_2.31")
status = json.loads((self.home / ".local/share/droiddeck-fex/status.json").read_text())
self.assertEqual(status["graphics"], str(provider))
self.assertNotIn("built", self.quiet(FEX["prepare"])[1])
os.utime(provider / "usr-mtree.txt.gz", ns=(1, 1))
self.assertIn("built the x86 runtime", self.quiet(FEX["prepare"])[1])
self.assertEqual(sorted(os.listdir(root.parent)), ["config", "lock", "rootfs", "status.json"])
def test_a_runtime_that_is_not_newer_is_left_out(self):
self.fex_tool()
sniper = self.runtime()
FEX["materialize"](str(sniper))
self.graphics(sniper, libc=b"GLIBC_2.2.5 GLIBC_2.31", libstdcxx=b"GLIBCXX_3.4.28")
fex, said = self.quiet(FEX["prepare"])
self.assertEqual(fex["rootfs"], str(sniper / "files"))
self.assertIn("has no newer C and C++ libraries than sniper_platform_", said)
self.assertFalse((self.home / ".local/share/droiddeck-fex/rootfs").exists())
def test_x86_steamworks_finds_the_x86_client(self):
for directory, machine in (("linux64", 62), ("linux32", 3), ("linuxarm64", 183)):
self.write(self.steam / directory / "steamclient.so", elf(machine))
sdk = self.home / ".steam"
sdk.mkdir(parents=True)
os.symlink(self.steam / "linuxarm64", sdk / "sdk64")
os.symlink(self.steam / "linuxarm64", sdk / "sdkarm64")
FEX["link_steam_sdk"]()
self.assertEqual(os.readlink(sdk / "sdk64"), str(self.steam / "linux64"))
self.assertEqual(os.readlink(sdk / "sdk32"), str(self.steam / "linux32"))
self.assertEqual(os.readlink(sdk / "sdkarm64"), str(self.steam / "linuxarm64"))
os.unlink(sdk / "sdk32")
os.symlink(self.tmp / "elsewhere", sdk / "sdk32")
self.write(self.tmp / "elsewhere/steamclient.so", elf(3))
FEX["link_steam_sdk"]()
self.assertEqual(os.readlink(sdk / "sdk32"), str(self.tmp / "elsewhere"))
self.assertEqual(sorted(os.listdir(sdk)), ["sdk32", "sdk64", "sdkarm64"])
def test_status_refreshes_what_the_app_reads_once_steam_installed_fex(self):
with mock.patch.dict(G, {"steam_running": lambda: False}):
@@ -317,6 +412,35 @@ class ExtractTest(FexTestCase):
self.assertTrue((self.home / ".config/droiddeck/fex-wanted").is_file())
self.assertFalse(json.loads((self.home / ".local/share/droiddeck-fex/status.json").read_text())["ready"])
def test_uruntime_that_only_drops_extended_attributes_still_unpacks(self):
tool = self.uruntime(
"mkdir -p AppDir && touch AppDir/AppRun\n"
"echo 'Failed to exec memfd: EACCES: Permission denied. Trying tmpfile in /tmp...' >&2\n"
"echo 'write_xattr: could not write xattr security.selinux for file ./AppDir/.DirIcon because you are not superuser!' >&2\n"
"echo 'Further error messages of this type are suppressed!' >&2\n"
"exit 2\n")
with mock.patch.dict(G, {"URUNTIME": tool, "fex_install": lambda: None, "steam_running": lambda: False}):
status, said = self.quiet(FEX["extract"], "image.AppImage")
self.assertEqual(status, 0)
self.assertIn("could not keep the image's extended attributes", said)
self.assertTrue(Path("squashfs-root/AppRun").is_file())
def test_an_attribute_only_failure_without_apprun_is_not_taken_as_unpacked(self):
tool = self.uruntime(
"mkdir -p AppDir\n"
"echo 'write_xattr: could not write xattr security.selinux for file ./AppDir/.DirIcon because you are not superuser!' >&2\n"
"exit 2\n")
with mock.patch.dict(G, {"URUNTIME": tool, "fex_install": lambda: None, "steam_running": lambda: False, "prepare": lambda: None}):
status, said = self.quiet(FEX["extract"], "image.AppImage")
self.assertIn("uruntime could not extract it (status 2)", said)
self.assertNotIn("could not keep the image's extended attributes", said)
self.assertFalse(os.path.lexists("squashfs-root/AppRun"))
def test_other_uruntime_errors_are_not_taken_as_unpacked(self):
self.assertFalse(FEX["only_xattrs_failed"]("write_xattr: could not write xattr\nwrite_file: failed to create file x\n"))
self.assertFalse(FEX["only_xattrs_failed"](""))
self.assertTrue(FEX["only_xattrs_failed"]("proot error: execveat() failed\nwrite_xattr: could not write xattr\n"))
def test_an_arm64_image_does_not_ask_for_fex(self):
self.write(self.image, elf(183) + b"payload", 0o755)
tool = self.uruntime("mkdir -p squashfs-root\n")
@@ -335,13 +459,40 @@ class ExtractTest(FexTestCase):
self.assertIn("no AppImage runtime for ARM64, no FEX yet and no unsquashfs", said)
self.assertFalse(os.path.lexists("squashfs-root"))
def test_unsquashfs_fallback_disables_unwritable_xattrs(self):
tool = self.uruntime("exit 1\n")
commands = []
def call(argv, **kwargs):
commands.append(argv)
if argv[0] == tool:
return 1
(self.work / "squashfs-root").mkdir()
(self.work / "squashfs-root/AppRun").touch()
return 0
with mock.patch.dict(G, {
"URUNTIME": tool,
"prepare": lambda: None,
"fex_install": lambda: None,
"steam_running": lambda: False,
"want_fex": lambda: None,
}), mock.patch("shutil.which", return_value="/usr/bin/unsquashfs"), \
mock.patch("subprocess.call", side_effect=call):
status, said = self.quiet(FEX["extract"], "image.AppImage")
self.assertEqual(status, 0)
self.assertIn("uruntime could not extract it (status 1)", said)
self.assertEqual(commands[-1][0], "/usr/bin/unsquashfs")
self.assertIn("-no-xattrs", commands[-1])
self.assertTrue(Path("squashfs-root/AppRun").is_file())
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"),
"LD_LIBRARY_PATH": "/steam/steamrtarm64:/usr/lib/aarch64-linux-gnu:/game/lib",
"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"))
@@ -349,8 +500,10 @@ class LaunchTest(FexTestCase):
self.assertEqual(guest["FEX_TSOENABLED"], "1")
self.assertTrue(guest["FEX_APP_CONFIG_LOCATION"].endswith("/config/"))
self.assertEqual((guest["FEX_SILENTLOG"], guest["FEX_OUTPUTLOG"]), ("0", "stderr"))
guest = FEX["guest_environment"]({"portable": False}, {"LD_PRELOAD": str(arm), "FEX_PORTABLE": "1", "FEX_OUTPUTLOG": "/tmp/fex.log"})
self.assertEqual(guest["FEX_OUTPUTLOG"], "/tmp/fex.log")
self.assertEqual(guest["GC_DISABLE_INCREMENTAL"], "1")
guest = FEX["guest_environment"]({"portable": False}, {"LD_PRELOAD": str(arm), "FEX_PORTABLE": "1", "FEX_OUTPUTLOG": "/tmp/fex.log",
"GC_DISABLE_INCREMENTAL": "0"})
self.assertEqual((guest["FEX_OUTPUTLOG"], guest["GC_DISABLE_INCREMENTAL"]), ("/tmp/fex.log", "0"))
self.assertNotIn("LD_PRELOAD", guest)
self.assertNotIn("FEX_PORTABLE", guest)
@@ -414,9 +567,8 @@ class LaunchTest(FexTestCase):
self.runtime()
self.write(tool / "usr/share/fex-emu/GuestThunks/libvulkan-guest.so",
elf(62) + b"\0libstdc++.so.6\0GLIBCXX_3.4\0GLIBCXX_3.4.29\0libc.so.6\0GLIBC_2.2.5\0GLIBC_2.34\0")
self.write(self.tmp / "preloads/x86_64/libthunkaudit.so", elf(62))
pin = self.write(self.tmp / "preloads/x86_64/libvulkan-thunk.so", elf(62))
audit = "/usr/lib/x86_64-linux-gnu/droiddeck/libthunkaudit.so"
pin = self.write(self.tmp / "preloads/x86_64/libvulkan-thunk.so", elf(62) + b"\0libc.so.6\0GLIBC_2.2.5\0")
pinned = "/usr/lib/x86_64-linux-gnu/droiddeck/vulkan"
def app(name, glibc=b"GLIBC_2.34\0GLIBC_2.44", glibcxx=b"GLIBCXX_3.4.29\0GLIBCXX_3.4.36", bundled=True):
run = self.write(self.tmp / name / "AppRun", elf(62), 0o755)
@@ -431,25 +583,32 @@ class LaunchTest(FexTestCase):
_, said = self.quiet(FEX["launch"], [str(program)], dict(env or {}), "on", decide)
return emulated.call_args[0][2], said
def search(env):
return env.get("LD_LIBRARY_PATH", "").split(":")[0]
env, said = started(app("new"))
self.assertEqual(env["LD_AUDIT"], audit)
self.assertIn("thunks on, its own Vulkan loader too", said)
env, _ = started(app("kept"), {"LD_AUDIT": "/opt/audit.so"})
self.assertEqual(env["LD_AUDIT"], audit + ":/opt/audit.so")
env, _ = started(self.write(self.tmp / "elsewhere/run.sh", "#!/bin/sh\n", 0o755), decide=str(self.tmp / "new"))
self.assertEqual(env["LD_AUDIT"], audit)
env, said = started(app("old-cxx", glibcxx=b"GLIBCXX_3.4.28"))
self.assertEqual(search(env), pinned)
self.assertNotIn("LD_AUDIT", env)
self.assertNotIn("LD_BIND_NOW", env)
self.assertIn("thunks on, its own Vulkan loader too", said)
env, _ = started(app("kept"), {"LD_LIBRARY_PATH": "/game/lib"})
self.assertEqual(env["LD_LIBRARY_PATH"], pinned + ":/game/lib")
env, _ = started(self.write(self.tmp / "elsewhere/run.sh", "#!/bin/sh\n", 0o755), decide=str(self.tmp / "new"))
self.assertEqual(search(env), pinned)
env, said = started(app("old-cxx", glibcxx=b"GLIBCXX_3.4.28"))
self.assertNotEqual(search(env), pinned)
self.assertIn("thunks on)", said)
self.assertNotIn("LD_AUDIT", started(app("old-libc", glibc=b"GLIBC_2.31"))[0])
self.assertNotIn("LD_AUDIT", started(app("runtime-only", bundled=False))[0])
self.assertNotEqual(search(started(app("old-libc", glibc=b"GLIBC_2.31"))[0]), pinned)
self.assertNotEqual(search(started(app("runtime-only", bundled=False))[0]), pinned)
i386 = self.write(self.tmp / "new/game.i386", elf(3), 0o755)
self.assertNotIn("LD_AUDIT", started(i386)[0])
self.assertNotEqual(search(started(i386)[0]), pinned)
self.write(pin, elf(62) + b"\0libc.so.6\0GLIBC_2.45\0")
self.assertNotEqual(search(started(app("new"))[0]), pinned)
pin.unlink()
self.assertNotIn("LD_AUDIT", started(app("no-pin"))[0])
self.assertNotEqual(search(started(app("no-pin"))[0]), pinned)
self.write(pin, elf(62))
(tool / "usr/share/fex-emu/GuestThunks/libvulkan-guest.so").unlink()
self.assertNotIn("LD_AUDIT", started(app("no-thunk"))[0])
self.assertNotEqual(search(started(app("no-thunk"))[0]), pinned)
def test_steam_verbs(self):
with mock.patch.dict(G, {"launch": mock.Mock(return_value=0)}):
@@ -517,6 +676,53 @@ class AppInfoTest(unittest.TestCase):
"40": None, "41": None, "50": "droiddeck-fex",
}, hex(magic))
@staticmethod
def manifest(steam, app, flags="4"):
(steam / "steamapps").mkdir(exist_ok=True)
(steam / ("steamapps/appmanifest_%s.acf" % app)).write_text('"AppState" { "appid" "%s" "StateFlags" "%s" }' % (app, flags))
def test_dual_platform_titles_keep_the_proton_default_unless_the_user_picks_fex(self):
with tempfile.TemporaryDirectory() as tmp:
steam = Path(tmp) / "Steam"
(steam / "appcache").mkdir(parents=True)
(steam / "appcache/appinfo.vdf").write_bytes(self.appinfo({
10: ("windows,linux", "", "game"), 20: ("windows,linux", "", "game"), 30: ("windows,linux", "", "game"),
40: ("linux", "", "game"),
}))
self.COMPAT["APPINFO_CACHE"].clear()
for app in ("3127680", "1628350", "4183110"):
self.manifest(steam, app)
tool, fex = self.COMPAT["TOOL"], self.COMPAT["FEX_TOOL"]
state = Path(tmp) / "state"
state.mkdir()
(state / "state.json").write_text(json.dumps({"auto": {"20": fex}}))
catalog = [{"name": tool, "display": "Proton Experimental ARM64", "dir": "Proton Experimental (ARM64)", "valve": True}]
config = steam / "config/config.vdf"
config.parent.mkdir()
config.write_text('"InstallConfigStore" { "Software" { "Valve" { "Steam" { "CompatToolMapping" { '
'"0" { "name" "%s" "config" "" "priority" "75" } '
'"20" { "name" "%s" "config" "" "priority" "250" } '
'"30" { "name" "%s" "config" "" "priority" "250" } } } } } }' % (tool, fex, fex))
self.COMPAT["register_default"](str(config), ["10", "20", "30", "40"], catalog=catalog, directory=str(state))
self.assertEqual(self.COMPAT["read_config_mapping"](str(config)),
{"0": tool, "10": tool, "20": tool, "30": fex, "40": fex})
def test_tools_are_fetched_until_fully_installed_and_up_to_date(self):
with tempfile.TemporaryDirectory() as tmp:
steam = Path(tmp)
(steam / "steamapps").mkdir()
downloads = self.COMPAT["tool_downloads"]
self.assertEqual(downloads(str(steam)), [
("4427310", "install"), ("3127680", "install"), ("1628350", "install"), ("4183110", "install")])
self.manifest(steam, "4427310", flags="6")
self.manifest(steam, "3127680", flags="1026")
self.manifest(steam, "1628350", flags="4")
(steam / "steamapps/appmanifest_4183110.acf").write_text('"AppState" { "appid" "4183110" }')
self.assertEqual(downloads(str(steam)), [("4427310", "update"), ("3127680", "update"), ("4183110", "update")])
for app in ("4427310", "3127680", "4183110"):
self.manifest(steam, app)
self.assertEqual(downloads(str(steam)), [])
def test_titles_with_a_valve_pick_are_found_installed_or_not(self):
def deck(oslist, runtime, kind="game"):
common = {"type": kind, "oslist": oslist, "steam_deck_compatibility": {"configuration": {"recommended_runtime": runtime}}}
+69
View File
@@ -160,6 +160,16 @@ class DroiddeckctlTest(FakeAdbTest):
started = [e["args"] for e in self.calls() if e["args"][:3] == ["shell", "am", "start"]]
self.assertIn("com.antutu.benchmark.full/com.droiddeck.launcher.agent.AgentStartActivity", started[0])
def test_a_malformed_package_is_refused_before_adb(self):
with unittest.mock.patch.dict(os.environ, {"DROIDDECK_PACKAGE": "com.example;reboot"}):
variant = load("droiddeckctl")
out = io.StringIO()
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(io.StringIO()):
code = variant.main(["--adb", str(self.adb), "--serial", "fake-1", "state"])
self.assertEqual(2, code)
self.assertEqual("INVALID_REQUEST", json.loads(out.getvalue())["error"]["code"])
self.assertFalse(self.calls())
def test_state_passes_through_with_the_serial(self):
self.configure({"state": state()})
code, out = self.run_ctl("state")
@@ -305,6 +315,65 @@ class DroiddeckctlTest(FakeAdbTest):
self.assertEqual(4, code)
self.assertEqual("NO_FRAMES", out["error"]["code"])
def test_pacing_counts_both_buckets_of_one_cadence_and_only_the_chosen_layers_rates(self):
text = "SurfaceFlinger TimeStats:\n" + "".join([
timestats_record("droiddeck_wayland_game#7", 910, {16: 450, 17: 450, 33: 10}, 60),
timestats_record("StatusBar#106", 4, {8: 3}, 90),
])
summary = ctl.pacing_summary(text, "com.droiddeck.launcher")
self.assertEqual(10, summary["offCadence"])
self.assertEqual([60], summary["refreshRates"])
def test_pacing_skips_a_game_layer_with_no_frames_for_the_surfaceview(self):
text = "SurfaceFlinger TimeStats:\n" + "".join([
timestats_record("droiddeck_wayland_game#7", 0, {}, 120),
timestats_record("a1 SurfaceView[com.droiddeck.launcher/com.droiddeck.launcher.SessionActivity]#8", 600, {16: 598, 33: 1}, 120),
])
summary = ctl.pacing_summary(text, "com.droiddeck.launcher")
self.assertEqual(600, summary["frames"])
self.assertIn("SurfaceView[com.droiddeck.launcher/", summary["layers"][0])
def test_pacing_with_a_layer_that_drew_no_frames_exits_4(self):
self.configure({}, timestats="SurfaceFlinger TimeStats:\n" + timestats_record("droiddeck_wayland_game#7", 0, {}, 120))
with unittest.mock.patch.object(ctl.time, "sleep"):
code, out = self.run_ctl("pacing", "--seconds", "1")
self.assertEqual(4, code)
self.assertEqual("NO_FRAMES", out["error"]["code"])
def test_pacing_turns_timestats_off_when_the_dump_fails(self):
calls = []
def adb(_adb, _serial, *args, timeout=30):
calls.append(args[3:])
if "-dump" in args:
raise ctl.ControlError("timed out", "ADB_FAILED")
return ctl.subprocess.CompletedProcess(args, 0, b"", b"")
with unittest.mock.patch.object(ctl, "run_adb", adb), unittest.mock.patch.object(ctl.time, "sleep"):
with self.assertRaises(ctl.ControlError) as caught:
ctl.pacing("adb", "fake-1", 1)
self.assertEqual("PACING_FAILED", caught.exception.code)
self.assertEqual(("--timestats", "-disable"), calls[-1])
def test_pacing_fails_when_timestats_cannot_be_turned_off(self):
def adb(_adb, _serial, *args, timeout=30):
return ctl.subprocess.CompletedProcess(args, 1 if "-disable" in args else 0, b"", b"")
with unittest.mock.patch.object(ctl, "run_adb", adb), unittest.mock.patch.object(ctl.time, "sleep"):
with self.assertRaises(ctl.ControlError) as caught:
ctl.pacing("adb", "fake-1", 1)
self.assertEqual("PACING_FAILED", caught.exception.code)
self.assertIn("timestats off", str(caught.exception))
def test_pacing_maps_an_adb_failure_while_enabling_to_pacing_failed(self):
def adb(*_args, **_kwargs):
raise ctl.ControlError("adb vanished", "ADB_FAILED")
with unittest.mock.patch.object(ctl, "run_adb", adb):
with self.assertRaises(ctl.ControlError) as caught:
ctl.pacing("adb", "fake-1", 1)
self.assertEqual("PACING_FAILED", caught.exception.code)
def test_input_requests(self):
self.configure({"input": {"ok": True, "command": "input"}})
self.run_ctl("input", "tap", "0.5", "0.25", "--space", "fraction")
+119
View File
@@ -0,0 +1,119 @@
import importlib.machinery
import importlib.util
import json
import gzip
from pathlib import Path
import struct
import subprocess
import sys
import tempfile
import unittest
from unittest.mock import patch
import zlib
TOOLS = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(TOOLS))
loader = importlib.machinery.SourceFileLoader('ctl_xr', str(TOOLS / 'droiddeckctl'))
spec = importlib.util.spec_from_loader(loader.name, loader)
ctl = importlib.util.module_from_spec(spec)
loader.exec_module(ctl)
class XrCaptureTest(unittest.TestCase):
def test_png_keeps_rgb_rows_and_dimensions(self):
pixels = bytes([255, 0, 0, 0, 255, 0, 0, 0, 255, 255, 255, 255])
png = ctl.xr_ppm_to_png(b'P6\n2 2\n255\n' + pixels)
self.assertEqual(png[:8], b'\x89PNG\r\n\x1a\n')
self.assertEqual(struct.unpack('>II', png[16:24]), (2, 2))
position = png.index(b'IDAT')
size = struct.unpack('>I', png[position - 4:position])[0]
self.assertEqual(zlib.decompress(png[position + 4:position + 4 + size]),
b'\0' + pixels[:6] + b'\0' + pixels[6:])
def test_incomplete_or_invalid_images_are_rejected(self):
for data in (b'P6\n2 2\n255\nabc', b'P6\n0 1\n255\n', b'P6\n999999 1\n255\n', b'junk'):
with self.subTest(data=data), self.assertRaises(ctl.ControlError):
ctl.xr_ppm_to_png(data)
def test_linear_source_and_display_eye_have_distinct_png_transfer_tags(self):
image = b'P6\n1 1\n255\n\x37\x37\x37'
self.assertIn(b'gAMA' + struct.pack('>I', 100000), ctl.xr_ppm_to_png(image, linear=True))
self.assertIn(b'sRGB\0', ctl.xr_ppm_to_png(image))
def capture(self, root, failed=False, replaced=False, no_response=False, source=False, truncated=False):
calls = []
token = None
reads = 0
def adb(_adb, _serial, *args, **kwargs):
nonlocal token, reads
calls.append(args)
stdout = b''
if args[0] == 'push':
token = Path(args[1]).read_text()
if args[:2] == ('shell', 'cat'):
reads += 1
stdout = json.dumps({'id': ('old' if reads == 1 or no_response or (replaced and reads > 2) else token),
'ok': not failed, 'validLayer': not failed, 'sourceImage': source}).encode()
if args[0] == 'exec-out':
stdout = gzip.compress(b'P6\n1 1\n255\n\x12\x34\x56')
if truncated:
stdout = stdout[:-5]
return subprocess.CompletedProcess(args, 0, stdout, b'')
with patch.object(ctl, 'run_adb', side_effect=adb), patch.object(ctl.time, 'sleep'):
result = ctl.xr_capture('adb', 'quest', root, 0.01 if no_response else 2)
return result, calls
def test_stale_response_is_ignored_and_matching_pair_is_published(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory) / 'capture'
result, calls = self.capture(root)
self.assertTrue(result['ok'])
self.assertEqual((root / 'left.png').read_bytes(), (root / 'right.png').read_bytes())
self.assertEqual(len([c for c in calls if c[:2] == ('shell', 'cat')]), 3)
self.assertTrue((root / 'capture.json').is_file())
def test_invalid_layer_replaced_capture_and_timeout_publish_no_images(self):
for flags in ({'failed': True}, {'replaced': True}, {'no_response': True}, {'truncated': True}):
with self.subTest(flags=flags), tempfile.TemporaryDirectory() as directory:
root = Path(directory) / 'capture'
with self.assertRaises(ctl.ControlError):
self.capture(root, **flags)
self.assertFalse(root.exists())
def test_source_capture_is_pulled_when_supported_by_the_headset(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory) / 'capture'
result, calls = self.capture(root, source=True)
self.assertEqual(result['source'], str((root / 'source.png').resolve()))
self.assertEqual(len([c for c in calls if c[0] == 'exec-out']), 3)
def test_output_creation_and_write_failures_are_file_errors(self):
for operation in ('mkdir', 'write_bytes'):
with self.subTest(operation=operation), tempfile.TemporaryDirectory() as directory:
with patch.object(Path, operation, side_effect=PermissionError('output denied')):
with self.assertRaises(ctl.ControlError) as caught:
self.capture(Path(directory) / 'capture')
self.assertEqual(caught.exception.code, 'FILE_IO')
self.assertEqual(ctl.exit_code(caught.exception), 6)
def test_stalled_metadata_read_uses_capture_deadline_and_reports_timeout(self):
calls = []
def adb(_adb, _serial, *args, **kwargs):
calls.append((args, kwargs))
if args[:2] == ('shell', 'cat'):
self.assertGreater(kwargs['timeout'], 0)
self.assertLessEqual(kwargs['timeout'], 0.1)
try:
raise subprocess.TimeoutExpired('adb', kwargs['timeout'])
except subprocess.TimeoutExpired as cause:
raise ctl.ControlError('metadata stalled', 'ADB_FAILED') from cause
return subprocess.CompletedProcess(args, 0, b'', b'')
with tempfile.TemporaryDirectory() as directory, patch.object(ctl, 'run_adb', side_effect=adb):
with self.assertRaises(ctl.ControlError) as caught:
ctl.xr_capture('adb', 'quest', Path(directory) / 'capture', 0.1)
self.assertEqual(caught.exception.code, 'TIMEOUT')
self.assertTrue(any(args[:3] == ('shell', 'rm', '-f') for args, _ in calls))
if __name__ == '__main__':
unittest.main()
+144
View File
@@ -0,0 +1,144 @@
import os
from pathlib import Path
import shutil
import struct
import subprocess
import sys
import tempfile
import unittest
SOURCE = Path(__file__).resolve().parents[2] / "app/src/main/cpp/fakeinput_steam.cpp"
RING_MAGIC = 0x46494252
DESCRIPTION_MAGIC = 0x46495544
HEADER = 64
EVENT = 24
CAPACITY = 4096
DESCRIPTION = 1824
READER = r"""
#include <fcntl.h>
#include <linux/input.h>
#include <stdio.h>
#include <unistd.h>
int main(void)
{
struct input_event events[64];
int fd = open("/dev/input/event16", O_RDONLY | O_NONBLOCK);
if (fd < 0) {
perror("open");
return 1;
}
while (read(fd, events, sizeof(events)) > 0)
;
puts("ready");
fflush(stdout);
char go;
if (read(0, &go, 1) != 1)
return 1;
ssize_t got = read(fd, events, sizeof(events));
for (ssize_t i = 0; i < got / (ssize_t)sizeof(events[0]); i++)
printf("%ld.%06ld %u %u %d\n", (long)events[i].time.tv_sec, (long)events[i].time.tv_usec, events[i].type,
events[i].code, events[i].value);
return got > 0 ? 0 : 1;
}
"""
PROBE = r"""
#include <errno.h>
#include <fcntl.h>
#include <linux/input.h>
#include <linux/joystick.h>
#include <stdio.h>
#include <sys/ioctl.h>
int main(void)
{
char name[128] = "";
struct input_id id = {0};
int fd = open("/dev/input/event16", O_RDONLY | O_NONBLOCK);
if (fd < 0)
return 1;
int joydev = ioctl(fd, JSIOCGNAME(sizeof(name)), name);
printf("JSIOCGNAME %d %s\n", joydev, joydev < 0 && errno == EINVAL ? "EINVAL" : name);
if (ioctl(fd, EVIOCGID, &id) < 0 || ioctl(fd, EVIOCGNAME(sizeof(name)), name) < 0)
return 1;
printf("%04x:%04x %s\n", id.vendor, id.product, name);
return 0;
}
"""
def can_build(bits):
with tempfile.TemporaryDirectory() as tmp:
probe = Path(tmp) / "probe.cpp"
probe.write_text("#include <string>\nint main() { return std::string().size(); }\n")
return subprocess.run(["g++", bits, "-static-libstdc++", "-o", str(Path(tmp) / "probe"), str(probe)],
capture_output=True).returncode == 0
@unittest.skipUnless(sys.platform == "linux" and os.uname().machine == "x86_64" and shutil.which("g++")
and shutil.which("gcc"), "needs gcc and g++ on an x86-64 Linux host")
class FakeinputRingTest(unittest.TestCase):
def setUp(self):
self.tmp = Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, self.tmp, True)
def ring(self):
hooks = self.tmp / "hooks"
hooks.mkdir()
(hooks / "event16").touch()
ring = bytearray(HEADER + CAPACITY * EVENT + DESCRIPTION)
struct.pack_into("<IIIIQQQ", ring, 0, RING_MAGIC, 2, EVENT, CAPACITY, 5, 0, 0)
struct.pack_into("<IiHHHHI80s", ring, HEADER + CAPACITY * EVENT, DESCRIPTION_MAGIC, os.getpid(),
3, 0x28de, 0x11ff, 1, 16, b"Microsoft X-Box 360 pad 0")
path = hooks / ".uinput-event16"
path.write_bytes(bytes(ring))
return hooks, path
def build(self, bits, program, name):
if not can_build(bits):
self.skipTest("no %s C++ toolchain" % bits)
library = self.tmp / ("libfakeinput%s.so" % bits)
subprocess.run(["g++", bits, "-shared", "-fPIC", "-O2", "-Wno-attributes", "-pthread", "-std=c++17",
"-static-libstdc++", "-static-libgcc", "-Wl,--exclude-libs,ALL", "-o", str(library),
str(SOURCE), "-ldl"], check=True, capture_output=True)
binary = self.tmp / (name + bits)
(self.tmp / (name + ".c")).write_text(program)
subprocess.run(["gcc", bits, "-o", str(binary), str(self.tmp / (name + ".c"))], check=True)
return library, binary
def read_through(self, bits):
library, reader = self.build(bits, READER, "reader")
hooks, path = self.ring()
env = dict(os.environ, LD_PRELOAD=str(library), FAKE_EVDEV_DIR=str(hooks))
process = subprocess.Popen([str(reader)], stdin=subprocess.PIPE, stdout=subprocess.PIPE, env=env, text=True)
self.addCleanup(process.kill)
self.assertEqual(process.stdout.readline(), "ready\n")
with open(path, "r+b") as ring:
for i, (kind, code, value) in enumerate(((1, 304, 1), (3, 1, -32768), (0, 0, 0))):
ring.seek(HEADER + (5 + i) * EVENT)
ring.write(struct.pack("<qqHHi", 1700000000 + i, 250000, kind, code, value))
ring.seek(16)
ring.write(struct.pack("<Q", 8))
output, _ = process.communicate("g", timeout=10)
self.assertEqual(process.returncode, 0)
return output
def test_a_32_bit_guest_reads_the_64_bit_ring(self):
self.assertEqual(self.read_through("-m32"),
"1700000000.250000 1 304 1\n1700000001.250000 3 1 -32768\n1700000002.250000 0 0 0\n")
def test_a_64_bit_guest_reads_the_same_ring(self):
self.assertEqual(self.read_through("-m64"),
"1700000000.250000 1 304 1\n1700000001.250000 3 1 -32768\n1700000002.250000 0 0 0\n")
def test_an_event_node_rejects_joydev_requests_so_sdl_reads_its_id(self):
library, probe = self.build("-m64", PROBE, "probe")
hooks, _ = self.ring()
run = subprocess.run([str(probe)], capture_output=True, text=True, timeout=10,
env=dict(os.environ, LD_PRELOAD=str(library), FAKE_EVDEV_DIR=str(hooks)))
self.assertEqual(run.returncode, 0, run.stderr)
self.assertEqual(run.stdout, "JSIOCGNAME -1 EINVAL\n28de:11ff Microsoft X-Box 360 pad 0\n")
if __name__ == "__main__":
unittest.main()
+91
View File
@@ -0,0 +1,91 @@
import hashlib
import os
from pathlib import Path
import subprocess
import tempfile
import textwrap
import unittest
SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-steam-x64"
SOURCE = SCRIPT.read_text()
START = SOURCE.index("fex_install() {")
END = SOURCE.index("\n}\n", START) + 3
FEX_INSTALL = SOURCE[START:END]
HARNESS = textwrap.dedent("""\
set -eu
# The archive comes from PKG; the installed tree loads when INSTALLED_LOADS=1, any staged tree always does.
curl() { local out=; while [ $# -gt 0 ]; do [ "$1" = -o ] && out=$2; shift; done; cp "$PKG" "$out"; }
fex_loads() { case $1 in "$ROOT"/) [ "${INSTALLED_LOADS:-1}" = 1 ] ;; *) true ;; esac; }
""")
class FexInstallTest(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
base = Path(self.temp.name)
self.root = base / "root"
old = self.root / "usr/local"
(old / "bin").mkdir(parents=True)
(old / "bin/FEX").write_text("old FEX\n")
(old / "share/fex-emu").mkdir(parents=True)
(old / "share/fex-emu/.droiddeck-tag").write_text("fex-2610-r5\n")
new = base / "pkg/usr/local"
(new / "bin").mkdir(parents=True)
(new / "bin/FEX").write_text("new FEX\n")
(new / "lib").mkdir()
(new / "lib/libxxhash.so.0").write_text("lib\n")
self.pkg = base / "fex.tzst"
subprocess.run(f"tar -C '{base / 'pkg'}' -c . | zstd -q -o '{self.pkg}'", shell=True, check=True)
self.sha = hashlib.sha256(self.pkg.read_bytes()).hexdigest()
def install(self, installed_loads, sha=None):
body = FEX_INSTALL.replace("local tag=$1 sha=$2 urls=$3 dst=/ ", "local tag=$1 sha=$2 urls=$3 dst=$ROOT/ ")
self.assertNotEqual(body, FEX_INSTALL)
script = HARNESS + body + 'if fex_install fex-2610-r6 "$SHA" u; then echo OK; else echo FAILED; fi\n'
env = dict(os.environ, ROOT=str(self.root), PKG=str(self.pkg), SHA=sha or self.sha,
INSTALLED_LOADS="1" if installed_loads else "0")
out = subprocess.run(["bash", "-c", script], env=env, text=True, capture_output=True, timeout=30)
self.assertEqual(0, out.returncode, out.stderr)
return out.stdout.strip().splitlines()[-1], out.stderr
def tag(self):
return (self.root / "usr/local/share/fex-emu/.droiddeck-tag").read_text().strip()
def test_a_build_that_loads_once_installed_replaces_the_old_one(self):
result, _ = self.install(installed_loads=True)
self.assertEqual("OK", result)
self.assertEqual("new FEX\n", (self.root / "usr/local/bin/FEX").read_text())
self.assertTrue((self.root / "usr/local/lib/libxxhash.so.0").is_file())
self.assertEqual("fex-2610-r6", self.tag())
def test_an_installed_copy_that_does_not_load_puts_the_old_files_back(self):
result, err = self.install(installed_loads=False)
self.assertEqual("FAILED", result)
self.assertIn("putting the previous files back", err)
self.assertEqual("old FEX\n", (self.root / "usr/local/bin/FEX").read_text())
self.assertFalse((self.root / "usr/local/lib/libxxhash.so.0").exists())
self.assertEqual("fex-2610-r5", self.tag())
def test_a_tag_that_cannot_be_written_puts_the_old_files_back(self):
share = self.root / "usr/local/share/fex-emu"
(share / ".droiddeck-tag").unlink()
share.rmdir()
share.write_text("not a folder\n")
result, err = self.install(installed_loads=True)
self.assertEqual("FAILED", result)
self.assertIn("putting the previous files back", err)
self.assertEqual("old FEX\n", (self.root / "usr/local/bin/FEX").read_text())
self.assertFalse((self.root / "usr/local/lib/libxxhash.so.0").exists())
def test_an_archive_that_does_not_match_installs_nothing(self):
result, err = self.install(installed_loads=True, sha="0" * 64)
self.assertEqual("FAILED", result)
self.assertIn("no source gave the archive", err)
self.assertEqual("old FEX\n", (self.root / "usr/local/bin/FEX").read_text())
self.assertEqual("fex-2610-r5", self.tag())
if __name__ == "__main__":
unittest.main()
+85
View File
@@ -0,0 +1,85 @@
import os
from pathlib import Path
import subprocess
import tempfile
import textwrap
import unittest
SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-steam-x64"
SOURCE = SCRIPT.read_text()
START = SOURCE.index("x64_fex() {")
END = SOURCE.index("\n}\n", START) + 3
X64_FEX = SOURCE[START:END]
HARNESS = textwrap.dedent("""\
set -eu
FEX_TAG=fex-2610-r5 FEX_SHA256=builtin FEX_URL=builtin-url
step() { echo "STEP $*"; }
# Installed FEX loads when LOADS=1; a build installs when its tag is in INSTALLABLE.
fex_loads() { [ "${LOADS:-0}" = 1 ]; }
fex_install() {
echo "INSTALL $1 $2 $3"
case " ${INSTALLABLE:-} " in *" $1 "*) echo "$1" > "$ROOT/tag"; : > "$ROOT/FEX"; chmod +x "$ROOT/FEX"; return 0 ;; esac
return 1
}
""")
class FexSelectTest(unittest.TestCase):
def run_select(self, installed=None, loads=False, catalog=None, installable=()):
with tempfile.TemporaryDirectory() as root:
if installed:
Path(root, "tag").write_text(installed + "\n")
fex = Path(root, "FEX")
fex.write_text("")
fex.chmod(0o755)
body = (X64_FEX.replace("/usr/local/share/fex-emu/.droiddeck-tag", "$ROOT/tag")
.replace("/usr/local/bin/FEX", "$ROOT/FEX"))
script = HARNESS + body + 'if x64_fex; then echo "NOW $FEX_NOW|$FEX_FROM"; else echo FAILED; fi\n'
env = dict(os.environ, ROOT=root, LOADS="1" if loads else "0", INSTALLABLE=" ".join(installable))
env.pop("BL_FEX_TAG", None)
if catalog:
env.update(BL_FEX_TAG=catalog, BL_FEX_SHA256="catsha", BL_FEX_URLS="a b")
out = subprocess.run(["bash", "-c", script], env=env, text=True, capture_output=True, timeout=10)
self.assertEqual(0, out.returncode, out.stderr)
lines = out.stdout.splitlines()
return [l for l in lines if l.startswith("INSTALL")], lines[-1]
def test_the_catalog_build_already_installed_is_used(self):
installs, now = self.run_select(installed="fex-2610-r6", loads=True, catalog="fex-2610-r6")
self.assertEqual([], installs)
self.assertEqual("NOW fex-2610-r6|catalog", now)
def test_a_newer_catalog_build_is_installed(self):
installs, now = self.run_select(installed="fex-2610-r5", loads=True, catalog="fex-2610-r6", installable=["fex-2610-r6"])
self.assertEqual(["INSTALL fex-2610-r6 catsha a b"], installs)
self.assertEqual("NOW fex-2610-r6|catalog", now)
def test_a_catalog_build_that_does_not_install_keeps_the_working_one(self):
installs, now = self.run_select(installed="fex-2610-r5", loads=True, catalog="fex-2610-r6")
self.assertEqual(["INSTALL fex-2610-r6 catsha a b"], installs)
self.assertEqual("NOW fex-2610-r5|kept; fex-2610-r6 did not install", now)
def test_without_a_catalog_the_built_in_build_replaces_an_older_one(self):
installs, now = self.run_select(installed="fex-2610-r4", loads=True, installable=["fex-2610-r5"])
self.assertEqual(["INSTALL fex-2610-r5 builtin builtin-url"], installs)
self.assertEqual("NOW fex-2610-r5|built-in", now)
def test_an_installed_build_that_does_not_load_is_replaced(self):
installs, now = self.run_select(installed="fex-2610-r6", loads=False, catalog="fex-2610-r6", installable=["fex-2610-r6"])
self.assertEqual(["INSTALL fex-2610-r6 catsha a b"], installs)
self.assertEqual("NOW fex-2610-r6|catalog", now)
def test_a_first_install_falls_back_to_the_built_in_build(self):
installs, now = self.run_select(catalog="fex-2610-r6", installable=["fex-2610-r5"])
self.assertEqual(["INSTALL fex-2610-r6 catsha a b", "INSTALL fex-2610-r5 builtin builtin-url"], installs)
self.assertEqual("NOW fex-2610-r5|built-in", now)
def test_nothing_usable_fails(self):
installs, now = self.run_select(catalog="fex-2610-r6")
self.assertEqual(2, len(installs))
self.assertEqual("FAILED", now)
if __name__ == "__main__":
unittest.main()
+16 -32
View File
@@ -220,6 +220,12 @@ class GameEnvironmentTest(unittest.TestCase):
self.assertEqual(env["REMOVE"], "inherited")
self.assertEqual(MODULE["apply_config"](env, config, "43")["CUSTOM"], "shared")
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"}}}
chosen = MODULE["apply_config"](env, MODULE["sync_config"](config, "42"), "42")
self.assertEqual(chosen, {"BL_SYNC": "0", "BL_SYNC_FALLBACK": "1", "BL_FSYNC_FIRST": "1", "PROTON_NO_ESYNC": "1", "OTHER": "kept"})
def test_component_profiles_override_general_and_restore_it_for_the_next_game(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
@@ -729,7 +735,7 @@ class ProtonDefaultTest(unittest.TestCase):
(root / "state.json").write_text(json.dumps({
"default": self.TOOL,
"auto": {},
"native": [app],
"native_choices": [app],
}))
globals_ = COMPAT["register_default"].__globals__
@@ -741,7 +747,7 @@ class ProtonDefaultTest(unittest.TestCase):
self.assertEqual(mapping_of(config.read_text()), {"0": self.TOOL})
state = json.loads((root / "state.json").read_text())
self.assertEqual(state["auto"], {})
self.assertEqual(state["native"], [app])
self.assertEqual(state["native_choices"], [app])
finally:
globals_["native_targets"] = original_native_targets
@@ -758,7 +764,7 @@ class ProtonDefaultTest(unittest.TestCase):
(root / "state.json").write_text(json.dumps({
"default": self.TOOL,
"auto": {},
"native": [app],
"native_choices": [app],
}))
globals_ = COMPAT["register_default"].__globals__
@@ -769,12 +775,12 @@ class ProtonDefaultTest(unittest.TestCase):
try:
COMPAT["register_default"](
str(config), [app], catalog=self.CATALOG, directory=tmp)
self.assertEqual(json.loads((root / "state.json").read_text())["native"], [app])
self.assertEqual(json.loads((root / "state.json").read_text())["native_choices"], [app])
COMPAT["register_default"](
str(config), [added_shortcut], catalog=self.CATALOG, directory=tmp)
state = json.loads((root / "state.json").read_text())
self.assertEqual(state["native"], [app])
self.assertEqual(state["native_choices"], [app])
self.assertEqual(state["auto"], {added_shortcut: self.TOOL})
self.assertEqual(mapping_of(config.read_text()), {
"0": self.TOOL,
@@ -820,7 +826,7 @@ class ProtonDefaultTest(unittest.TestCase):
self.assertEqual(COMPAT["tokenize"](first.decode()),
COMPAT["tokenize"](config_text([("0", self.TOOL)])))
self.assertEqual(json.loads((Path(tmp) / "state.json").read_text())["auto"], {})
self.assertEqual(json.loads((Path(tmp) / "state.json").read_text())["native"], ["427520"])
self.assertEqual(json.loads((Path(tmp) / "state.json").read_text())["native_choices"], ["427520"])
COMPAT["register_default"](
str(config), ["427520"], catalog=self.CATALOG, directory=tmp)
@@ -832,7 +838,7 @@ class ProtonDefaultTest(unittest.TestCase):
native_choice = config.read_bytes()
self.assertEqual(mapping_of(native_choice.decode()), {"0": self.TOOL, "427520": ""})
self.assertEqual(json.loads((Path(tmp) / "state.json").read_text())["auto"], {})
self.assertEqual(json.loads((Path(tmp) / "state.json").read_text())["native"], ["427520"])
self.assertEqual(json.loads((Path(tmp) / "state.json").read_text())["native_choices"], ["427520"])
COMPAT["register_default"](
str(config), ["427520"], catalog=self.CATALOG, directory=tmp)
self.assertEqual(config.read_bytes(), native_choice)
@@ -842,10 +848,10 @@ class ProtonDefaultTest(unittest.TestCase):
COMPAT["register_default"](
str(config), ["427520"], catalog=self.CATALOG, directory=tmp)
self.assertEqual(mapping_of(config.read_text()), {"0": self.TOOL, "427520": choice})
self.assertEqual(json.loads((Path(tmp) / "state.json").read_text())["native"], [])
self.assertEqual(json.loads((Path(tmp) / "state.json").read_text())["native_choices"], [])
state = json.loads((Path(tmp) / "state.json").read_text())
state["native"] = ["427520"]
state["native_choices"] = ["427520"]
state["auto"] = {}
(Path(tmp) / "state.json").write_text(json.dumps(state))
config.write_text(config_text([("0", self.TOOL), ("427520", "proton_experimental")]))
@@ -853,7 +859,7 @@ class ProtonDefaultTest(unittest.TestCase):
str(config), ["427520"], catalog=self.CATALOG, directory=tmp)
self.assertEqual(mapping_of(config.read_text()), {"0": self.TOOL, "427520": self.TOOL})
saved = json.loads((Path(tmp) / "state.json").read_text())
self.assertEqual(saved["native"], [])
self.assertEqual(saved["native_choices"], [])
self.assertEqual(saved["auto"], {"427520": self.TOOL})
finally:
globals_["appinfo_platforms"] = original_platforms
@@ -1160,28 +1166,6 @@ if __name__ == "__main__":
unittest.main()
class StartWithoutSteamTest(unittest.TestCase):
def test_start_without_steam_uses_umu_or_runinprefix_and_only_when_asked(self):
with tempfile.TemporaryDirectory() as tmp:
ge = Path(tmp) / "ge/proton"
ge.parent.mkdir()
ge.write_text('if "UMU_ID" in os.environ:\n argv = [wine, "c:\\\\windows\\\\system32\\\\umu.exe"]\n')
valve = Path(tmp) / "valve/proton"
valve.parent.mkdir()
valve.write_text('argv = [wine, "c:\\\\windows\\\\system32\\\\steam.exe"]\n')
start = MODULE["start_without_steam"]
game = [str(ge), "waitforexitandrun", "/games/Game.exe", "-windowed"]
self.assertEqual(start(game, {}, "3384071994"), (game, {}))
on = {"DROIDDECK_NO_STEAM": "1"}
self.assertEqual(start(game, on, "3384071994"), (game, dict(on, UMU_ID="0")))
self.assertEqual(start(game, on, "570940")[1]["UMU_ID"], "570940")
self.assertEqual(start(game, dict(on, UMU_ID="umu-1"), "570940")[1]["UMU_ID"], "umu-1")
plain = [str(valve)] + game[1:]
self.assertEqual(start(plain, on, "570940"), ([str(valve), "runinprefix", "/games/Game.exe", "-windowed"], on))
for other in ([str(ge), "run", "/x.exe"], [str(ge), "waitforexitandrun"], [str(valve), "getcompatpath", "/x"]):
self.assertEqual(start(other, on, "570940"), (other, on))
class ForceSsbsTest(unittest.TestCase):
def test_libssbs_is_preloaded_only_when_asked_and_only_into_arm64_proton(self):
with tempfile.TemporaryDirectory() as tmp:
+71
View File
@@ -0,0 +1,71 @@
import collections
from pathlib import Path
import re
import unicodedata
import unittest
import xml.etree.ElementTree as ET
ROOT = Path(__file__).resolve().parents[2]
RES = ROOT / "app/src/main/res"
FORMAT = re.compile(r"%(?:\d+\$)?[-#+ 0,(]*\d*(?:\.\d+)?[a-zA-Z%]")
def strings(path):
return {
element.attrib["name"]: "".join(element.itertext())
for element in ET.parse(path).getroot()
if element.tag == "string" and element.get("translatable") != "false"
}
class GlassesLocalizationTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.english = strings(RES / "values/strings.xml")
cls.required = {
key: value for key, value in cls.english.items()
if key.startswith(("glasses_", "spatial_", "tracking_recovery_", "setup_glasses_", "phone_camera_tracking_"))
or key in ("setup_tab_glasses", "hand_camera_prompt_title", "hand_camera_prompt_body", "hand_camera_setting_hint")
}
language_source = (ROOT / "app/src/main/java/com/droiddeck/launcher/core/AppLanguage.kt").read_text(encoding="utf-8")
tags = re.findall(r'"([a-zA-Z0-9-]+)"', re.search(r"val supported:.*?listOf\((.*?)\)", language_source, re.S).group(1))
special = {"id": "in", "es-419": "b+es+419", "pt-BR": "pt"}
cls.locales = {}
for tag in tags:
if tag == "en":
continue
qualifier = special.get(tag, tag.replace("-", "-r"))
cls.locales[tag] = strings(RES / f"values-{qualifier}/strings.xml")
def test_every_supported_language_has_nonempty_glasses_and_calibration_text(self):
for locale, translated in self.locales.items():
for key in self.required:
with self.subTest(locale=locale, key=key):
self.assertTrue(translated.get(key, "").strip(), "Missing translation would fall back to English")
def test_translations_preserve_format_arguments_and_explicit_line_breaks(self):
for locale, translated in self.locales.items():
for key, source in self.required.items():
with self.subTest(locale=locale, key=key):
target = translated.get(key, "")
self.assertEqual(collections.Counter(FORMAT.findall(source)), collections.Counter(FORMAT.findall(target)))
self.assertEqual(source.count(r"\n"), target.count(r"\n"))
def test_printed_board_and_distance_guidance_preserve_measurements(self):
keys = ("spatial_print_hint", "spatial_print_scale", "spatial_print_check", "spatial_distance_12in",
"spatial_distance_30cm", "spatial_distance_20in", "spatial_distance_50cm",
"spatial_distance_hint", "spatial_distance_corners")
def numbers(value):
value = "".join(str(unicodedata.decimal(char)) if char.isdecimal() else char for char in value)
return collections.Counter(number.replace(",", ".") for number in re.findall(r"\d+(?:[.,]\d+)?", value))
for locale, translated in self.locales.items():
for key in keys:
with self.subTest(locale=locale, key=key):
self.assertEqual(numbers(self.english[key]), numbers(translated.get(key, "")))
if __name__ == "__main__":
unittest.main()
+58 -1
View File
@@ -23,6 +23,7 @@ IFACE = NAME + ".Manager"
@unittest.skipUnless(Gio and os.environ.get("DBUS_SESSION_BUS_ADDRESS"), "requires dbus-run-session and PyGObject")
class SleepHandshakeTest(unittest.TestCase):
ARGS = []
AGENT_EXIT = None
def setUp(self):
self.directory = tempfile.TemporaryDirectory()
@@ -37,7 +38,16 @@ class SleepHandshakeTest(unittest.TestCase):
lambda bus, sender, path, interface, name, body: self.signals.append(body.unpack()[0]))
env = dict(os.environ, BL_LAUNCH_DIR=str(self.dir),
DBUS_SYSTEM_BUS_ADDRESS=os.environ["DBUS_SESSION_BUS_ADDRESS"])
self.process = subprocess.Popen(["/usr/bin/python3", str(SCRIPT), *self.ARGS], env=env,
script = SCRIPT
if self.AGENT_EXIT is not None:
bin_dir = self.dir / "bin"
bin_dir.mkdir()
script = bin_dir / SCRIPT.name
script.write_text(SCRIPT.read_text())
agent = bin_dir / "droiddeck-agent"
agent.write_text("#!/bin/sh\necho \"$@\" >> \"%s\"\nexit %d\n" % (self.dir / "agent-calls", self.AGENT_EXIT))
agent.chmod(0o755)
self.process = subprocess.Popen(["/usr/bin/python3", str(script), *self.ARGS], env=env,
stdout=subprocess.DEVNULL)
self.wait_for(lambda: (self.dir / "steam-sleep-ready").exists())
@@ -220,6 +230,53 @@ class SleepHandshakeTest(unittest.TestCase):
self.call(IFACE, "PowerOff", GLib.Variant("(b)", (True,)))
class FakeAgentCase(unittest.TestCase):
ARGS = []
setUp = SleepHandshakeTest.setUp
tearDown = SleepHandshakeTest.tearDown
wait_for = SleepHandshakeTest.wait_for
call = SleepHandshakeTest.call
suspend = SleepHandshakeTest.suspend
state = SleepHandshakeTest.state
request_wake = SleepHandshakeTest.request_wake
def asked(self):
path = self.dir / "agent-calls"
return path.read_text().split() if path.exists() else []
@unittest.skipUnless(Gio and os.environ.get("DBUS_SESSION_BUS_ADDRESS"), "requires dbus-run-session and PyGObject")
class AwakeSteamTest(FakeAgentCase):
AGENT_EXIT = 5
def test_resuming_an_awake_steam_sends_no_sleep_wake_pair(self):
self.request_wake()
self.wait_for(lambda: self.asked())
deadline = time.monotonic() + 1.5
while time.monotonic() < deadline:
self.wait_for(lambda: True)
time.sleep(0.05)
self.assertEqual([], self.signals)
self.assertEqual(["--steam-asleep"], self.asked())
def test_a_pending_sleep_still_wakes_without_asking_steam(self):
token = self.suspend()
self.state(token, "paused")
self.request_wake()
self.wait_for(lambda: self.signals == [True, False])
self.assertEqual([], self.asked())
@unittest.skipUnless(Gio and os.environ.get("DBUS_SESSION_BUS_ADDRESS"), "requires dbus-run-session and PyGObject")
class AsleepSteamTest(FakeAgentCase):
AGENT_EXIT = 0
def test_resuming_a_sleeping_steam_replays_the_pair(self):
self.request_wake()
self.wait_for(lambda: self.signals == [True, False])
self.assertEqual(["--steam-asleep"], self.asked())
class WithNetworkManagerTest(SleepHandshakeTest):
ARGS = ["--with-netmanager"]
+23
View File
@@ -0,0 +1,23 @@
#include "../../app/src/main/cpp/viture/mjpeg_payload.h"
#include <cassert>
#include <cstdio>
#include <cstring>
int main() {
const uint8_t jpeg[] = {0xff,0xd8,0xff,0xc0,0,4,1,2,0xff,0xd9};
uint8_t frame[32]{};
std::memcpy(frame,jpeg,sizeof(jpeg));
for (std::size_t padding=0; padding<=7; ++padding)
assert(mjpeg_payload_size(frame,sizeof(jpeg)+padding) == sizeof(jpeg));
assert(mjpeg_payload_size(frame,sizeof(jpeg)+8) == 0);
for (std::size_t size=0; size<sizeof(jpeg); ++size)
assert(mjpeg_payload_size(frame,size) == 0);
frame[sizeof(jpeg)] = 0x42;
assert(mjpeg_payload_size(frame,sizeof(jpeg)+1) == 0);
frame[sizeof(jpeg)] = 0;
frame[0] = 0;
assert(mjpeg_payload_size(frame,sizeof(jpeg)) == 0);
assert(mjpeg_payload_size(nullptr,10) == 0);
assert(mjpeg_payload_size(jpeg,4*1024*1024+1) == 0);
std::puts("PASS: JPEG boundaries, 0-7 padding bytes, truncation, garbage, and bounds");
}
+192
View File
@@ -0,0 +1,192 @@
import errno
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
# Opens each "<dirfd>\t<flags>\t<path>" case with openat2(RESOLVE_IN_ROOT) as FEX does: first through the kernel's own
# openat2 on argv[1] when it has one, then, with openat2 failing ENOSYS as under proot, through the preload on argv[2].
PROGRAM = r"""
#define _GNU_SOURCE
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <linux/filter.h>
#include <linux/seccomp.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/prctl.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <unistd.h>
#ifndef SYS_openat2
#define SYS_openat2 437
#endif
struct how { uint64_t flags, mode, resolve; };
static char cases[256][512];
static int count;
static void run(long (*call)(long, ...), const char *tree) {
int root = open(tree, O_PATH | O_DIRECTORY | O_CLOEXEC), outer = open("/", O_PATH | O_DIRECTORY | O_CLOEXEC);
for (int i = 0; i < count; i++) {
char *flags = strchr(cases[i], '\t') + 1, *path = strchr(flags, '\t') + 1;
struct how h = {strtoull(flags, NULL, 0), 0, 0x10};
if (h.flags & O_CREAT) h.mode = 0644;
long fd = call(SYS_openat2, (long)(cases[i][0] == 'o' ? outer : root), (long)path, (long)&h, (long)sizeof(h));
struct stat st;
if (fd < 0) {
printf("ERR %d\n", errno);
} else {
fstat((int)fd, &st);
printf("OK %llu %llu\n", (unsigned long long)st.st_dev, (unsigned long long)st.st_ino);
close((int)fd);
}
}
}
int main(int argc, char **argv) {
if (argc < 3) return 2;
while (count < 256 && fgets(cases[count], sizeof(cases[count]), stdin)) {
cases[count][strcspn(cases[count], "\n")] = 0;
count++;
}
long (*kernel)(long, ...) = (long (*)(long, ...))dlsym(dlopen("libc.so.6", RTLD_LAZY | RTLD_NOLOAD), "syscall");
struct how probe = {O_RDONLY, 0, 0x10};
long fd = kernel(SYS_openat2, (long)AT_FDCWD, (long)".", (long)&probe, (long)sizeof(probe));
if (fd >= 0) {
close((int)fd);
printf("kernel\n");
run(kernel, argv[1]);
struct sock_filter filter[] = {
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, nr)),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SYS_openat2, 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ERRNO | ENOSYS),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
};
struct sock_fprog prog = {sizeof(filter) / sizeof(filter[0]), filter};
if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) || prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog)) {
perror("seccomp");
return 3;
}
}
printf("preload\n");
run(syscall, argv[2]);
return 0;
}
"""
O_PATH = getattr(os, "O_PATH", 0o10000000)
# (dirfd: r = the tree, o = "/"), flags, path, expected: a path in the tree, an errno name, or "proc" for a file outside it.
CASES = [
("r", os.O_RDONLY, "etc/alternatives/hn", "etc/hostname"),
("r", os.O_RDONLY, "/lib64/x86_64-linux-gnu/libfoo.so.1", "usr/lib/x86_64-linux-gnu/libfoo.so.1.2"),
("r", os.O_RDONLY, "lib/x86_64-linux-gnu/libfoo.so.1", "usr/lib/x86_64-linux-gnu/libfoo.so.1.2"),
("r", os.O_RDONLY, "etc/escape", "etc/hostname"),
("r", os.O_RDONLY, "dirlink/../etc/hostname", "etc/hostname"),
("r", os.O_RDONLY, "rootlink/rootlink//etc/./hostname", "etc/hostname"),
("r", os.O_RDONLY, "../../etc/hostname", "etc/hostname"),
("r", os.O_RDONLY | os.O_DIRECTORY, "/", "."),
("r", os.O_RDONLY | os.O_DIRECTORY, "usr/../..", "."),
("r", os.O_RDONLY, "chain/l2", "chain/end"),
("r", os.O_RDONLY, "chain/l1", "ELOOP"),
("r", os.O_RDONLY, "loop/a/x", "ELOOP"),
("r", os.O_RDONLY | os.O_NOFOLLOW, "etc/alternatives/hn", "ELOOP"),
("r", O_PATH | os.O_NOFOLLOW, "etc/alternatives/hn", "etc/alternatives/hn"),
("r", os.O_RDONLY | os.O_NOFOLLOW, "lib/x86_64-linux-gnu/libfoo.so.1.2", "usr/lib/x86_64-linux-gnu/libfoo.so.1.2"),
("r", os.O_RDONLY | os.O_NOFOLLOW | os.O_DIRECTORY, "dirlink/", "usr"),
("r", os.O_RDONLY, "file/", "ENOTDIR"),
("r", os.O_RDONLY, "file/../etc/hostname", "ENOTDIR"),
("r", os.O_RDONLY, "nonexist/../etc/hostname", "ENOENT"),
("r", os.O_RDWR | os.O_CREAT | os.O_EXCL, "dangling", "EEXIST"),
("r", os.O_RDWR | os.O_CREAT, "dangling", "usr/newfile"),
("r", os.O_RDWR | os.O_CREAT, "missing/newfile", "ENOENT"),
("r", os.O_RDWR | os.O_CREAT, "newdir/", "EISDIR"),
("o", os.O_RDONLY | os.O_NONBLOCK, "proc/self/fd/0", "EXDEV"),
("o", os.O_RDONLY, "proc/self/exe", "EXDEV"),
("o", os.O_RDONLY, "proc/self/cwd/x", "EXDEV"),
("o", os.O_RDONLY, "proc/self/status", "proc"),
]
def make_tree(root):
for folder in ("usr/lib/x86_64-linux-gnu", "etc/alternatives", "loop", "chain"):
(root / folder).mkdir(parents=True)
(root / "usr/lib/x86_64-linux-gnu/libfoo.so.1.2").write_text("x86")
(root / "etc/hostname").write_text("inside")
(root / "file").write_text("f")
(root / "chain/end").write_text("end")
links = {"usr/lib/x86_64-linux-gnu/libfoo.so.1": "libfoo.so.1.2", "lib": "usr/lib", "lib64": "/usr/lib",
"etc/alternatives/hn": "/etc/hostname", "etc/escape": "../../../../../../etc/hostname", "loop/a": "b",
"loop/b": "a", "dirlink": "/usr", "rootlink": "/", "dangling": "/usr/newfile"}
links.update({"chain/l%d" % i: ("l%d" % (i + 1) if i < 41 else "end") for i in range(1, 42)})
for link, target in links.items():
os.symlink(target, root / link)
def labels(lines, root):
inodes = {(os.lstat(root).st_dev, os.lstat(root).st_ino): "."}
for folder, dirs, files in os.walk(root):
for name in dirs + files:
st = os.lstat(os.path.join(folder, name))
inodes[(st.st_dev, st.st_ino)] = os.path.relpath(os.path.join(folder, name), root)
out = []
for line in lines:
kind, *values = line.split()
if kind == "OK":
out.append(inodes.get((int(values[0]), int(values[1])), "proc"))
else:
out.append(errno.errorcode[int(values[0])])
return out
@unittest.skipUnless(shutil.which("cc") and os.path.isdir("/proc/self"), "needs cc and procfs")
class Openat2PreloadTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.tmp = Path(tempfile.mkdtemp())
cls.lib = cls.tmp / "libopenat2.so"
subprocess.run(["cc", "-O2", "-Wall", "-Werror", "-fPIC", "-shared", "-pthread", "-o", str(cls.lib),
str(PRELOAD / "robust.c"), str(PRELOAD / "fsync.c"), str(PRELOAD / "noexec.c"), "-ldl"], check=True)
source = cls.tmp / "openat2.c"
source.write_text(PROGRAM)
subprocess.run(["cc", "-O2", "-Wall", "-Werror", "-o", str(cls.tmp / "openat2"), str(source), "-ldl"], check=True)
cls.trees = (cls.tmp / "kernel", cls.tmp / "preload")
for tree in cls.trees:
make_tree(tree)
cases = "".join("%s\t%d\t%s\n" % case[:3] for case in CASES)
result = subprocess.run([str(cls.tmp / "openat2"), *map(str, cls.trees)], input=cases, capture_output=True, text=True,
env=dict(os.environ, LD_PRELOAD=str(cls.lib)), timeout=60)
if result.returncode != 0:
raise AssertionError(result.stdout + result.stderr)
lines = result.stdout.splitlines()
cls.kernel = labels(lines[1:1 + len(CASES)], cls.trees[0]) if lines[0] == "kernel" else None
cls.preload = labels(lines[-len(CASES):], cls.trees[1])
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.tmp, ignore_errors=True)
def test_preload_resolves_in_the_root_without_openat2(self):
for case, got in zip(CASES, self.preload):
self.assertEqual(got, case[3], case)
self.assertTrue((self.trees[1] / "usr/newfile").exists())
def test_the_kernel_agrees(self):
if self.kernel is None:
self.skipTest("this kernel or sandbox has no openat2")
for case, got in zip(CASES, self.kernel):
self.assertEqual(got, case[3], case)
if __name__ == "__main__":
unittest.main()
+170
View File
@@ -0,0 +1,170 @@
import os
from pathlib import Path
import re
import shutil
import subprocess
import sys
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[2]
SOURCE = ROOT / 'app/src/main/cpp/waylandcomp/src/compositor.c'
def extract_function(source, name):
match = re.search(r'^(?:static )?(?:void|int|uint32_t) ' + re.escape(name) + r'\([^;]*?\) \{',
source, re.MULTILINE)
if match is None:
raise AssertionError(f'Missing compositor function: {name}')
cursor, depth = match.end(), 1
while depth:
depth += (source[cursor] == '{') - (source[cursor] == '}')
cursor += 1
return source[match.start():cursor]
PREAMBLE = r'''
#define _GNU_SOURCE
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <stdatomic.h>
#include <stdint.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/ioctl.h>
struct wl_resource { int version, modes, done, hz, w, h; struct wl_resource *next; };
struct surface { int xdg_toplevel, toplevel_committed; struct surface *next; };
struct input_msg { int type, p1, p2, p3, p4; };
static struct wl_resource second = { .version = 1 };
static struct wl_resource first = { .version = 4, .next = &second };
static struct surface surface = { .xdg_toplevel = 1, .toplevel_committed = 1 };
static int g_input_pipe[2] = {-1, -1};
static atomic_int g_output_refresh_mhz = 60000;
static atomic_int g_output_refresh_pending;
static int g_output_announced_refresh_mhz = 60000;
static int g_output_w = 1920, g_output_h = 1080;
static int flushes, resizes, pointers, ticks;
static int scale_changes, scale_mode, scale_alignment, renders;
static void *g_display;
#define WL_OUTPUT_MODE_CURRENT 1
#define WL_OUTPUT_MODE_PREFERRED 2
#define wl_resource_for_each(r, list) for ((r) = &first; (r); (r) = (r)->next)
#define wl_list_for_each(s, list, link) for ((s) = &surface; (s); (s) = (s)->next)
static int wl_resource_get_version(struct wl_resource *r) { return r->version; }
static void wl_output_send_mode(struct wl_resource *r, int flags, int w, int h, int hz) {
assert(flags == 3); r->modes++; r->hz = hz; r->w = w; r->h = h;
}
static void wl_output_send_done(struct wl_resource *r) { r->done++; }
static void wl_display_flush_clients(void *display) { (void)display; flushes++; }
static void send_toplevel_configure(struct surface *s) { (void)s; resizes++; }
#define droiddeck_log(...) ((void)0)
#define deliver_key(m) ((void)0)
#define pointer_event(...) ((void)0)
#define pointer_button(...) ((void)0)
#define scroll_event(...) ((void)0)
#define axis_event(...) ((void)0)
#define pointer_delta(...) ((void)0)
#define deliver_touch(m) ((void)0)
#define deliver_pointer(m) (pointers++)
static void on_vsync(int64_t ns) { assert(ns > 0); ticks++; }
static void vk_present_set_scale_mode(int mode, int alignment) {
scale_changes++; scale_mode = mode; scale_alignment = alignment;
}
static void schedule_render(void) { renders++; }
'''
CHECKS = r'''
static int queued(void) { int n; assert(ioctl(g_input_pipe[0], FIONREAD, &n) == 0); return n; }
static void drain(void) { on_input_readable(g_input_pipe[0], 0, NULL); }
static void expect(int modes, int hz, int resize_count) {
assert(first.modes == modes && second.modes == modes);
assert(first.hz == hz && second.hz == hz);
assert(first.w == 1920 && second.w == 1920 && first.h == 1080 && second.h == 1080);
assert(first.done == modes && second.done == 0);
assert(resizes == resize_count);
assert(pointers == 0);
}
int main(void) {
droiddeck_wayland_set_output_refresh_rate(120000);
assert(atomic_load(&g_output_refresh_mhz) == 120000);
assert(!atomic_load(&g_output_refresh_pending));
assert(first.modes == 0 && second.modes == 0);
assert(pipe2(g_input_pipe, O_CLOEXEC | O_NONBLOCK) == 0);
g_output_announced_refresh_mhz = atomic_load(&g_output_refresh_mhz);
droiddeck_wayland_set_scale_mode(1, 4);
assert(queued() == sizeof(struct input_msg));
drain();
assert(scale_changes == 1 && scale_mode == 1 && scale_alignment == 4 && renders == 1);
assert(first.modes == 0 && second.modes == 0);
droiddeck_wayland_set_output_refresh_rate(120000);
assert(queued() == 0);
droiddeck_wayland_set_output_refresh_rate(60000);
assert(first.modes == 0 && queued() == sizeof(struct input_msg));
drain(); expect(1, 60000, 0); assert(flushes == 1);
droiddeck_wayland_set_output_refresh_rate(60000);
assert(queued() == 0); drain(); expect(1, 60000, 0);
droiddeck_wayland_set_output_refresh_rate(90000);
droiddeck_wayland_set_output_refresh_rate(120000);
drain(); expect(2, 120000, 0);
droiddeck_wayland_set_output_refresh_rate(90000);
droiddeck_wayland_set_output_refresh_rate(120000);
drain(); expect(2, 120000, 0);
droiddeck_wayland_set_output_refresh_rate(60000);
droiddeck_wayland_output_resized();
drain(); expect(3, 60000, 1); assert(flushes == 3);
struct input_msg wake = {10, 0, 0, 0, 0};
int n = 0;
while (write(g_input_pipe[1], &wake, sizeof(wake)) == sizeof(wake)) n++;
assert(n > 0 && errno == EAGAIN);
droiddeck_wayland_set_output_refresh_rate(120000);
drain(); expect(4, 120000, 1);
droiddeck_wayland_set_output_refresh_rate(0);
drain(); expect(5, 60000, 1);
droiddeck_wayland_set_output_refresh_rate(-1);
assert(queued() == 0);
struct input_msg vsync = {5, 0, 16000000, 0, 0};
assert(write(g_input_pipe[1], &vsync, sizeof(vsync)) == sizeof(vsync));
drain(); expect(5, 60000, 1); assert(ticks == 1);
assert(nominal_refresh_ns() == 16666666);
assert(flushes == 5);
assert(scale_changes == 1 && scale_mode == 1 && scale_alignment == 4 && renders == 1);
droiddeck_wayland_set_scale_mode(1, 3);
droiddeck_wayland_set_output_refresh_rate(90000);
drain(); expect(6, 90000, 1);
assert(scale_changes == 2 && scale_mode == 1 && scale_alignment == 3 && renders == 2);
close(g_input_pipe[0]); close(g_input_pipe[1]);
puts("PASS");
}
'''
@unittest.skipUnless(sys.platform.startswith('linux'), 'needs Linux nonblocking pipes')
class OutputRefreshTest(unittest.TestCase):
def test_refresh_notifications_preserve_client_pacing_without_resizing(self):
compiler = shutil.which(os.environ.get('CC', 'cc'))
if compiler is None:
self.skipTest('A host C compiler is required')
source = SOURCE.read_text()
functions = ('nominal_refresh_ns', 'output_send_mode', 'output_notify_mode',
'output_resized', 'on_input_readable', 'droiddeck_wayland_output_resized',
'droiddeck_wayland_set_scale_mode',
'droiddeck_wayland_set_output_refresh_rate')
harness = PREAMBLE + '\n'.join(extract_function(source, name) for name in functions) + CHECKS
with tempfile.TemporaryDirectory(prefix='droiddeck-output-refresh-') as folder:
path = Path(folder)
(path / 'refresh.c').write_text(harness)
binary = path / 'refresh-test'
build = subprocess.run([compiler, '-std=c11', '-Wall', '-Wextra', '-Werror',
'-Wno-unused-parameter', '-O2', str(path / 'refresh.c'),
'-o', str(binary)], capture_output=True, text=True)
self.assertEqual(0, build.returncode, build.stderr)
result = subprocess.run([str(binary)], capture_output=True, text=True, timeout=10)
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual('PASS', result.stdout.strip())
if __name__ == '__main__':
unittest.main()
+179
View File
@@ -0,0 +1,179 @@
import importlib.util
from pathlib import Path
import struct
import tempfile
import unittest
from unittest import mock
from zipfile import ZipFile
spec = importlib.util.spec_from_file_location(
'prepare_windows_runtime', Path(__file__).resolve().parents[1] / 'prepare_windows_runtime.py')
prepare = importlib.util.module_from_spec(spec)
spec.loader.exec_module(prepare)
class WindowsRuntimePreparationTest(unittest.TestCase):
def test_archive_paths_cannot_escape_destination(self):
for name in ('../outside', '/absolute', 'dir/../../outside', 'C:/absolute', 'dir\\outside', '.'):
with self.subTest(name=name), self.assertRaises(ValueError):
prepare.validate_relative(name)
def test_tracked_outputs_cannot_be_overwritten(self):
with mock.patch.object(prepare, 'git', return_value=b'tracked/file\n'):
with self.assertRaisesRegex(ValueError, 'overwrite tracked'):
prepare.checked_output('tracked/file')
def test_rebuilt_libraries_must_match_each_architecture(self):
with tempfile.TemporaryDirectory() as folder:
path = Path(folder) / 'libblsession.so'
elf = bytearray(64)
elf[:4] = b'\x7fELF'
elf[5] = 1
elf[18:20] = struct.pack('<H', 183)
path.write_bytes(elf)
self.assertEqual(prepare.validate_rebuilt(path, 183), elf)
with self.assertRaisesRegex(ValueError, 'wrong ELF architecture'):
prepare.validate_rebuilt(path, 62)
path.write_bytes(b'not an ELF')
with self.assertRaisesRegex(ValueError, 'wrong ELF architecture'):
prepare.validate_rebuilt(path, 183)
def test_new_committed_native_changes_reject_donor_reuse(self):
with mock.patch.object(prepare, 'git', return_value=prepare.DONOR_TREE.encode()), \
mock.patch.object(prepare, 'changed', return_value={'tools/linuxfs/preload/net.c'}):
with self.assertRaisesRegex(ValueError, 'Sources changed since'):
prepare.check_sources()
def test_vr_sources_are_classified_as_rebuilt_including_local_and_new_files(self):
committed = {'tools/vr/src/vk_layer_droiddeck_vr.c', 'tools/vr/build.sh'}
local = {'tools/vr/src/presenter.cpp'}
new = {'tools/vr/src/fence_tracker.h'}
with mock.patch.object(prepare, 'changed', side_effect=[committed, local, committed]), \
mock.patch.object(prepare, 'git', side_effect=[prepare.DONOR_TREE.encode(),
b'tools/vr/src/fence_tracker.h\0']):
classifications = prepare.check_sources()
self.assertEqual(set(classifications), committed | local | new)
self.assertTrue(all('never imported from donor' in value for value in classifications.values()))
def test_preparation_excludes_all_donor_vr_files_and_records_replacement_origin(self):
with tempfile.TemporaryDirectory() as folder:
root = Path(folder)
apk = root / 'donor.apk'
vr_name = 'layer/libVkLayer_droiddeck_vr.so'
with ZipFile(apk, 'w') as package:
package.writestr(prepare.VR_PREFIX + vr_name, b'old library')
package.writestr(prepare.VR_PREFIX + 'obsolete.so', b'obsolete donor file')
package.writestr('assets/linuxfs/unchanged.so', b'unchanged component')
(root / 'app/build').mkdir(parents=True)
(root / 'app/build/runtime-inputs.json').write_text('{}')
vr_manifest = {'version': 1, 'source_commit': 'current', 'outputs': {vr_name: 'verified'}}
with mock.patch.object(prepare, 'ROOT', root), \
mock.patch.object(prepare, 'check_sources', return_value={}), \
mock.patch.object(prepare, 'DONOR_SHA256', prepare.runtime.digest(apk)), \
mock.patch.object(prepare, 'REBUILT', {}), \
mock.patch.object(prepare, 'JNI', ()), mock.patch.object(prepare, 'PREPARED', ()), \
mock.patch.object(prepare, 'LOCAL_BUILD_PLUMBING', set()), \
mock.patch.object(prepare, 'source_assets', return_value={}), \
mock.patch.object(prepare, 'read_gamescope', return_value=({}, {
'GAMESCOPE_REPO': 'repo', 'GAMESCOPE_TAG': 'tag', 'GAMESCOPE_SHA256': 'hash'})), \
mock.patch.object(prepare, 'validate_tracked_assets', return_value={}), \
mock.patch.object(prepare, 'git', return_value=b''), \
mock.patch.object(prepare.runtime, 'record'), mock.patch.object(prepare.runtime, 'verify'), \
mock.patch.object(prepare.vr_build, 'build', return_value=({vr_name: b'new library'}, vr_manifest)) as build:
prepare.prepare(apk, root, root, llvm_strip=root / 'bin/llvm-strip')
build.assert_called_once()
vr_folder = root / 'app/src/main' / prepare.VR_PREFIX
self.assertEqual((vr_folder / vr_name).read_bytes(), b'new library')
self.assertFalse((vr_folder / 'obsolete.so').exists())
import json
provenance = json.loads((root / 'app/build/windows-runtime-provenance.json').read_text())
self.assertEqual(provenance['vr_build'], vr_manifest)
self.assertIn('VR rebuilt', provenance['outputs']['app/src/main/' + prepare.VR_PREFIX + vr_name]['origin'])
def test_invalid_cached_vr_stops_before_reading_or_staging_the_donor(self):
with tempfile.TemporaryDirectory() as folder:
root = Path(folder)
apk = root / 'donor.apk'
apk.write_bytes(b'donor')
with mock.patch.object(prepare, 'check_sources', return_value={}), \
mock.patch.object(prepare, 'DONOR_SHA256', prepare.runtime.digest(apk)), \
mock.patch.object(prepare, 'REBUILT', {}), \
mock.patch.object(prepare, 'read_gamescope', return_value=({}, {})), \
mock.patch.object(prepare.vr_build, 'validate', side_effect=ValueError('VR build is stale')), \
mock.patch.object(prepare.vr_build, 'build') as build, \
mock.patch.object(prepare, 'ZipFile') as archive:
with self.assertRaisesRegex(ValueError, 'VR build is stale'):
prepare.prepare(apk, root, root, rebuilt_vr=root, vk_include=root)
build.assert_not_called()
archive.assert_not_called()
def test_current_helpers_are_allowed_only_when_restaged_from_source(self):
helpers = prepare.LOCAL_SESSION_HELPERS
sources = {prepare.ROOT / path: 'assets/linuxfs/' + path.split('/overlay/')[1]
for path in helpers}
for local_changes in (set(), helpers):
with self.subTest(local_changes=local_changes), \
mock.patch.object(prepare, 'source_assets', return_value=sources), \
mock.patch.object(prepare, 'changed', side_effect=[helpers, local_changes, helpers]), \
mock.patch.object(prepare, 'git', side_effect=[prepare.DONOR_TREE.encode(), b'']):
classifications = prepare.check_sources()
self.assertEqual(set(classifications), helpers)
self.assertTrue(all('restaged from current source' in action
for action in classifications.values()))
with mock.patch.object(prepare, 'source_assets', return_value={}), \
mock.patch.object(prepare, 'changed', return_value=helpers), \
mock.patch.object(prepare, 'git', return_value=prepare.DONOR_TREE.encode()):
with self.assertRaisesRegex(ValueError, 'Sources changed since'):
prepare.check_sources()
def test_cardboard_changes_are_compiled_by_gradle_not_reused_from_donor(self):
changed = {'app/src/main/cpp/waylandcomp/src/cardboard.c'}
with mock.patch.object(prepare, 'changed', side_effect=[changed, changed, changed]), \
mock.patch.object(prepare, 'git', side_effect=[prepare.DONOR_TREE.encode(), b'']):
classifications = prepare.check_sources()
self.assertEqual(set(classifications), changed)
self.assertIn('compiled by Gradle; not imported', next(iter(classifications.values())))
def test_other_helper_changes_still_need_an_audit(self):
with mock.patch.object(prepare, 'git', return_value=prepare.DONOR_TREE.encode()), \
mock.patch.object(prepare, 'changed', return_value={
'tools/linuxfs/overlay/usr/local/bin/droiddeck-session'}):
with self.assertRaisesRegex(ValueError, 'Sources changed since'):
prepare.check_sources()
def test_uncommitted_native_changes_reject_donor_reuse(self):
with mock.patch.object(prepare, 'git', side_effect=[prepare.DONOR_TREE.encode(), b'']), \
mock.patch.object(prepare, 'changed', side_effect=[set(), {'tools/linuxfs/preload/net.c'}]):
with self.assertRaisesRegex(ValueError, 'Unreviewed runtime'):
prepare.check_sources()
def test_wrong_apk_hash_fails_before_replacement_or_output_access(self):
with tempfile.TemporaryDirectory() as folder:
apk = Path(folder) / 'incorrect.apk'
apk.write_bytes(b'incorrect donor')
with mock.patch.object(prepare, 'check_sources', return_value={}), \
mock.patch.object(prepare, 'read_gamescope') as read_gamescope:
with self.assertRaisesRegex(ValueError, 'Donor APK checksum mismatch'):
prepare.prepare(apk, Path(folder) / 'missing', Path(folder) / 'missing.tzst')
read_gamescope.assert_not_called()
def test_sdk_bridge_is_compiled_locally_while_other_untracked_native_files_fail(self):
with mock.patch.object(prepare, 'source_assets', return_value={}), \
mock.patch.object(prepare, 'changed', side_effect=[set(), {'app/src/main/cpp/CMakeLists.txt'}, set()]), \
mock.patch.object(prepare, 'git', side_effect=[prepare.DONOR_TREE.encode(),
b'app/src/main/cpp/viture/sdk_bridge.cpp\0app/src/main/cpp/viture/stereo_frame_gate.h\0']):
classifications = prepare.check_sources()
self.assertEqual(set(classifications), {'app/src/main/cpp/CMakeLists.txt',
'app/src/main/cpp/viture/sdk_bridge.cpp',
'app/src/main/cpp/viture/stereo_frame_gate.h'})
self.assertTrue(all('compiled by Gradle' in action for action in classifications.values()))
with mock.patch.object(prepare, 'changed', side_effect=[set(), set()]), \
mock.patch.object(prepare, 'git', side_effect=[prepare.DONOR_TREE.encode(),
b'app/src/main/cpp/unreviewed.cpp\0']):
with self.assertRaisesRegex(ValueError, 'Unreviewed runtime'):
prepare.check_sources()
if __name__ == '__main__':
unittest.main()
+85
View File
@@ -0,0 +1,85 @@
import sys
import unittest
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from test_quest_xr import collect_device_metrics, summarize_samples, validate_samples
import subprocess
class QuestXrValidationTest(unittest.TestCase):
def samples(self, source='frames'):
return [{'rendered': count, 'sessionState': 5, 'headFlags': 15, 'source': source,
'controllersActive': [False, False], 'guestFrames': count,
'uploadedFrames': count, 'sourceFrameId': count + 1, 'steamvrState': 4}
for count in (0, 144)]
def test_requires_owned_frame_projection(self):
self.assertIsNone(validate_samples(self.samples()))
self.assertEqual('Wrong projection source', validate_samples(self.samples('surface')))
def test_position_must_be_tracked_not_merely_valid(self):
samples = self.samples()
for sample in samples:
sample['headFlags'] = 7
self.assertIn('tracked 6DoF', validate_samples(samples))
def test_optional_controllers_cannot_be_claimed_as_tested(self):
self.assertIn('controllers', validate_samples(self.samples(), require_controllers=True))
def test_one_early_tracked_sample_cannot_hide_final_tracking_loss(self):
samples = self.samples()
samples[-1]['headFlags'] = 7
self.assertIn('final sample', validate_samples(samples))
samples[-1]['headFlags'] = 15
samples[-1]['sessionState'] = 4
self.assertIn('final sample', validate_samples(samples))
def test_measured_rates_are_separate_from_runtime_refresh(self):
samples = self.samples('frames')
samples[0]['_hostMonotonicSeconds'] = 10
samples[-1]['_hostMonotonicSeconds'] = 12
samples[-1]['periodNs'] = 8333333
summary = summarize_samples(samples)
self.assertEqual(summary['observedSeconds'], 2)
self.assertEqual(summary['ratesHz']['uploadedFrames'], 72)
self.assertAlmostEqual(summary['runtimeRefreshHz'], 120, places=3)
self.assertEqual(summary['focusedTrackedFraction'], 1)
samples[-1]['uploadedFrames'] = -1
self.assertIsNone(summarize_samples(samples)['ratesHz']['uploadedFrames'])
self.assertIsNone(summarize_samples(self.samples())['observedSeconds'])
self.assertIsNone(summarize_samples([])['focusedTrackedFraction'])
def test_metrics_failures_stay_unavailable_without_privileged_fallback(self):
commands = []
def adb(*command):
commands.append(command)
if command[-1] == 'battery':
return 'temperature: 310'
raise subprocess.CalledProcessError(1, command, stderr='Permission denied')
metrics = collect_device_metrics(adb, 'com.droiddeck.launcher')
self.assertEqual(len(commands), 3)
self.assertTrue(metrics['battery']['available'])
self.assertFalse(metrics['thermal']['available'])
self.assertFalse(metrics['memory']['available'])
def test_steamvr_requires_owned_images_and_source_frame_ids(self):
samples = self.samples('frames')
self.assertIsNone(validate_samples(samples))
samples[-1]['uploadedFrames'] = 0
self.assertIn('owned SteamVR images', validate_samples(samples))
samples[-1]['uploadedFrames'] = 144
samples[-1]['sourceFrameId'] = samples[0]['sourceFrameId']
self.assertIn('frame IDs', validate_samples(samples))
def test_running_process_alone_is_not_success(self):
samples = self.samples('frames')
samples[-1]['rendered'] = 0
self.assertIn('stereo frames', validate_samples(samples))
samples[-1]['rendered'] = 144
samples[-1]['steamvrState'] = 3
self.assertIn('RUNNING', validate_samples(samples))
if __name__ == '__main__':
unittest.main()
+3 -1
View File
@@ -32,8 +32,10 @@ class RequestFexTest(unittest.TestCase):
"start steam://install/1628350", "end steam://install/1628350"],
self.log.read_text().splitlines())
self.install("1628350")
self.assertEqual(["4183110"], COMPAT["request_fex"](str(self.root), asked))
self.install("4183110")
self.assertEqual([], COMPAT["request_fex"](str(self.root), asked))
self.assertEqual({"3127680", "1628350"}, asked)
self.assertEqual({"3127680", "1628350", "4183110"}, asked)
def test_a_declined_install_is_not_asked_again_in_the_same_session(self):
asked = set()
+76
View File
@@ -0,0 +1,76 @@
"""Exercise the Windows launcher without building an APK or contacting a phone."""
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
POWERSHELL = shutil.which('pwsh') or shutil.which('powershell')
SCRIPT = Path(__file__).resolve().parents[1] / 'run_windows.ps1'
@unittest.skipUnless(os.name == 'nt' and POWERSHELL, 'Windows PowerShell launcher')
class WindowsLauncherTest(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory(prefix='droiddeck windows launcher ')
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
(self.root / 'tools').mkdir()
shutil.copyfile(SCRIPT, self.root / 'tools/run_windows.ps1')
self.calls = self.root / 'calls.txt'
(self.root / 'gradlew.bat').write_text(
'@echo off\necho gradle JAVA_HOME=%JAVA_HOME%>>"%DROIDDECK_TEST_CALLS%"\n'
'exit /b %DROIDDECK_TEST_GRADLE_EXIT%\n')
(self.root / 'adb.cmd').write_text(
'@echo off\necho adb %*>>"%DROIDDECK_TEST_CALLS%"\nexit /b 0\n')
self.env = dict(os.environ, JAVA_HOME=r'C:\provided-java',
DROIDDECK_TEST_CALLS=str(self.calls), DROIDDECK_TEST_GRADLE_EXIT='0')
self.env['PATH'] = str(self.root) + os.pathsep + self.env.get('PATH', '')
def launch(self):
return subprocess.run(
[POWERSHELL, '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass',
'-File', str(self.root / 'tools/run_windows.ps1'), '-Serial', 'test-phone'],
env=self.env, cwd=self.root, capture_output=True, text=True, timeout=30)
def test_missing_optional_configs_keep_environment_java_and_base_package(self):
result = self.launch()
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
calls = self.calls.read_text().splitlines()
self.assertEqual(calls[0], r'gradle JAVA_HOME=C:\provided-java')
self.assertEqual(calls[1], 'adb -s test-phone install -r app/build/outputs/apk/debug/app-debug.apk')
self.assertEqual(calls[2], 'adb -s test-phone shell am start -W -n '
'com.droiddeck.launcher/com.droiddeck.launcher.MainActivity')
def test_existing_configs_select_java_and_suffixed_package(self):
(self.root / '.gradle').mkdir()
(self.root / '.gradle/config.properties').write_text('java.home=C\\:\\\\configured-java\n')
(self.root / 'local.properties').write_text('droiddeck.debugApplicationIdSuffix=.xr\n')
result = self.launch()
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
calls = self.calls.read_text().splitlines()
self.assertEqual(calls[0], r'gradle JAVA_HOME=C:\configured-java')
self.assertTrue(calls[2].endswith('com.droiddeck.launcher.xr/com.droiddeck.launcher.MainActivity'))
def test_empty_configs_use_defaults(self):
(self.root / '.gradle').mkdir()
(self.root / '.gradle/config.properties').touch()
(self.root / 'local.properties').touch()
result = self.launch()
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
calls = self.calls.read_text().splitlines()
self.assertEqual(calls[0], r'gradle JAVA_HOME=C:\provided-java')
self.assertTrue(calls[2].endswith('com.droiddeck.launcher/com.droiddeck.launcher.MainActivity'))
def test_build_failure_still_stops_before_installation(self):
self.env['DROIDDECK_TEST_GRADLE_EXIT'] = '1'
result = self.launch()
self.assertNotEqual(result.returncode, 0)
self.assertIn('Android build failed.', result.stderr)
self.assertEqual(self.calls.read_text().splitlines(), [r'gradle JAVA_HOME=C:\provided-java'])
if __name__ == '__main__':
unittest.main()
+25 -1
View File
@@ -1,12 +1,13 @@
import importlib.util
import gzip
import io
from pathlib import Path
from pathlib import Path, PureWindowsPath
import subprocess
import tarfile
import tempfile
import unittest
from unittest.mock import patch
from unittest import mock
from zipfile import ZipFile
@@ -114,6 +115,29 @@ class RuntimeInputsTest(unittest.TestCase):
package.writestr(name, (self.root / output['path']).read_bytes())
runtime.check_apk(apk, self.root)
def test_windows_manifest_matches_portable_apk_paths(self):
path_type = type(self.root)
original_relative_to = path_type.relative_to
def windows_relative_to(path, *args, **kwargs):
return PureWindowsPath(original_relative_to(path, *args, **kwargs))
with mock.patch.object(path_type, 'relative_to', windows_relative_to):
runtime.record(self.root)
data = runtime.verify(self.root)
self.assertIn('tools/linuxfs/preload/test.c', data['sources'])
nested_asset = 'assets/linuxfs/usr/local/bin/gamescope'
self.assertEqual(data['outputs'][nested_asset]['path'], 'app/src/main/' + nested_asset)
for name in data['sources']:
self.assertNotIn('\\', name)
apk = self.root / 'portable.apk'
with ZipFile(apk, 'w') as package:
for name, output in data['outputs'].items():
self.assertNotIn('\\', name)
self.assertNotIn('\\', output['path'])
package.writestr(name, (self.root / output['path']).read_bytes())
runtime.check_apk(apk, self.root)
def test_android_expanding_or_renaming_a_compressed_inventory_is_rejected(self):
runtime.record(self.root)
data = runtime.verify(self.root)
+6
View File
@@ -37,3 +37,9 @@ class SessionAssetsTest(unittest.TestCase):
with ZipFile(self.apk, 'w') as package:
package.writestr(self.name, self.helper.read_bytes())
self.assertEqual([], assets.check(self.apk, self.overlay))
def test_bundled_helper_must_also_be_extracted(self):
self.assertEqual(['not extracted at session start: usr/local/bin/droiddeck-login1'],
assets.check_extraction(self.overlay, ''))
mapping = '"usr/local/bin/droiddeck-login1" to "usr/local/bin/droiddeck-login1"'
self.assertEqual([], assets.check_extraction(self.overlay, mapping))
+74
View File
@@ -0,0 +1,74 @@
import os
import re
import shutil
import signal
import subprocess
import tempfile
import time
import unittest
from pathlib import Path
SESSION = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-session"
def run_program_function():
match = re.search(r"^ run_program\(\) \{\n.*?^ \}\n", SESSION.read_text(), re.M | re.S)
return match.group(0)
class RunStatusTest(unittest.TestCase):
def setUp(self):
self.dir = Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, self.dir, True)
def run_with(self, command, launch_dir=True):
env = dict(os.environ)
env.pop("BL_LAUNCH_DIR", None)
if launch_dir:
env["BL_LAUNCH_DIR"] = str(self.dir)
return subprocess.run(["bash", "-c", run_program_function() + "run_program " + command + "; echo unreachable"],
env=env, capture_output=True, text=True, timeout=30)
def test_the_program_status_is_kept_for_the_app(self):
run = self.run_with("sh -c 'exit 7'")
self.assertEqual(7, run.returncode)
self.assertNotIn("unreachable", run.stdout)
self.assertEqual("7\n", (self.dir / "run-status").read_text())
self.assertFalse((self.dir / "run-status.tmp").exists())
def test_a_clean_exit_is_recorded_as_zero(self):
self.assertEqual(0, self.run_with("true").returncode)
self.assertEqual("0\n", (self.dir / "run-status").read_text())
def test_nothing_is_written_without_a_launch_dir(self):
self.assertEqual(3, self.run_with("sh -c 'exit 3'", launch_dir=False).returncode)
self.assertEqual([], os.listdir(self.dir))
def signalled(self, sig, program):
env = dict(os.environ, BL_LAUNCH_DIR=str(self.dir))
ready = self.dir / "ready"
proc = subprocess.Popen(["bash", "-c", run_program_function() + "run_program " + program],
env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
self.addCleanup(proc.kill)
deadline = time.monotonic() + 10
while not ready.exists() and time.monotonic() < deadline:
time.sleep(0.05)
self.assertTrue(ready.exists())
proc.send_signal(sig)
return proc.wait(timeout=10)
def test_a_stop_signal_reaches_the_program(self):
program = ("python3 -c 'import signal, sys, time; signal.signal(signal.SIGTERM, lambda *a: sys.exit(9)); "
"open(sys.argv[1], \"w\").close(); time.sleep(30)' %s" % (self.dir / "ready"))
self.assertEqual(9, self.signalled(signal.SIGTERM, program))
self.assertEqual("9\n", (self.dir / "run-status").read_text())
def test_an_interrupt_reaches_the_program(self):
program = ("python3 -c 'import sys, time; open(sys.argv[1], \"w\").close(); time.sleep(30)' %s"
% (self.dir / "ready"))
self.assertEqual(130, self.signalled(signal.SIGINT, program))
self.assertEqual("130\n", (self.dir / "run-status").read_text())
if __name__ == "__main__":
unittest.main()
+45 -13
View File
@@ -8,15 +8,8 @@ import unittest
SESSION = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-session"
SOURCE = SESSION.read_text()
END = SOURCE.index(
' if [ -s "$HOME/.bl-autolaunch" ]; then',
SOURCE.index(" _bl_launch_ready="),
)
START = SOURCE.rfind(
' if [ -n "${BL_LAUNCH_DIR:-}" ] && [ -z "${BL_DESKTOP:-}" ]; then',
0,
END,
)
START = SOURCE.index(" steam_hold_launch() {")
END = SOURCE.index(' if [ -s "$HOME/.bl-autolaunch" ]; then', START)
assert START >= 0
LAUNCH_BLOCK = textwrap.dedent(SOURCE[START:END])
@@ -32,12 +25,19 @@ class SteamColdLaunchTest(unittest.TestCase):
self.bin.mkdir()
self.agent_args = self.root / "agent-args"
self.sleep_args = self.root / "sleep-args"
self.agent_count = self.root / "agent-count"
xprop = self.bin / "xprop"
xprop.write_text("#!/bin/sh\necho 'GAMESCOPE_FOCUSED_APP(CARDINAL) = 769'\n")
xprop.chmod(0o755)
agent = self.bin / "droiddeck-agent"
agent.write_text("#!/bin/sh\nprintf '%s\\n' \"$@\" > \"$AGENT_ARGS\"\nexit \"$AGENT_STATUS\"\n")
agent.write_text(
"#!/bin/sh\n"
"printf '%s\\n' \"$@\" > \"$AGENT_ARGS\"\n"
"n=$(cat \"$AGENT_COUNT\" 2>/dev/null || echo 0); n=$((n + 1)); echo $n > \"$AGENT_COUNT\"\n"
"i=0; last=1\n"
"for s in $AGENT_STATUS; do i=$((i + 1)); last=$s; [ \"$i\" -eq \"$n\" ] && exit \"$s\"; done\n"
"exit \"$last\"\n")
agent.chmod(0o755)
sleep = self.bin / "sleep"
sleep.write_text("#!/bin/sh\nprintf '%s\\n' \"$@\" >> \"$SLEEP_ARGS\"\n")
@@ -48,7 +48,7 @@ class SteamColdLaunchTest(unittest.TestCase):
env = dict(os.environ, HOME=str(self.root), BL_LAUNCH_DIR=str(self.launch_dir),
PATH=str(self.bin) + os.pathsep + os.environ["PATH"],
AGENT_ARGS=str(self.agent_args), SLEEP_ARGS=str(self.sleep_args),
AGENT_STATUS=str(helper_status))
AGENT_COUNT=str(self.agent_count), AGENT_STATUS=str(helper_status))
script = self.block + "\nprintf 'ARG:%s\\n' \"$@\"\nwait\n"
url = target if target.startswith("steam://") else "steam://rungameid/" + target
result = subprocess.run(["bash", "-c", script, "cold-launch", url],
@@ -71,13 +71,45 @@ class SteamColdLaunchTest(unittest.TestCase):
self.assertEqual(["--wait-steam-shortcut-overview", game_id, "45"], self.agent_args.read_text().splitlines())
self.assertEqual("4", self.sleep_args.read_text().strip())
def test_shortcut_without_the_expected_overview_does_not_forward_cgameid(self):
def test_a_shortcut_whose_overview_never_appears_is_launched_after_a_bounded_wait(self):
game_id = str((3551182975 << 32) | 0x02000000)
result = self.run_launch(game_id, 1)
self.assertFalse((self.launch_dir / "steam-game").exists(), result.stdout)
self.assertEqual(game_id, (self.launch_dir / "steam-game").read_text().strip(), result.stdout)
self.assertEqual(["--wait-steam-shortcut-overview", game_id, "45"], self.agent_args.read_text().splitlines())
self.assertEqual("2", self.agent_count.read_text().strip())
self.assertEqual(["2", "2"], self.sleep_args.read_text().split())
self.assertIn("launching the requested game anyway", result.stdout)
def test_a_late_overview_is_still_waited_for_once_more(self):
game_id = str((3551182975 << 32) | 0x02000000)
result = self.run_launch(game_id, "1 0")
self.assertEqual(game_id, (self.launch_dir / "steam-game").read_text().strip(), result.stdout)
self.assertEqual("2", self.agent_count.read_text().strip())
self.assertEqual(["2"], self.sleep_args.read_text().split())
self.assertIn("attempt 1 of 2", result.stdout)
self.assertNotIn("anyway", result.stdout)
def test_an_agent_failure_other_than_a_timeout_launches_without_retrying(self):
game_id = str((3551182975 << 32) | 0x02000000)
result = self.run_launch(game_id, 2)
self.assertEqual(game_id, (self.launch_dir / "steam-game").read_text().strip(), result.stdout)
self.assertEqual("1", self.agent_count.read_text().strip())
self.assertFalse(self.sleep_args.exists())
def test_a_restart_for_a_game_waits_for_its_overview_too(self):
game_id = str((3551182975 << 32) | 0x02000000)
loop = SOURCE[SOURCE.index(' if [ -s "$HOME/.bl-restart-game" ]; then'):SOURCE.index(' if [ -f "$HOME/.bl-restart-once" ]; then')]
self.assertIn('steam_hold_launch "$_bl_again" &', loop)
self.assertNotIn("set -- \"steam://rungameid/", loop)
script = self.block + '\nsteam_hold_launch "%s"\n' % game_id
env = dict(os.environ, HOME=str(self.root), BL_LAUNCH_DIR=str(self.launch_dir),
PATH=str(self.bin) + os.pathsep + os.environ["PATH"],
AGENT_ARGS=str(self.agent_args), SLEEP_ARGS=str(self.sleep_args),
AGENT_COUNT=str(self.agent_count), AGENT_STATUS="1 0")
result = subprocess.run(["bash", "-c", script, "restart"], env=env, text=True, capture_output=True, timeout=10, check=True)
self.assertEqual(game_id, (self.launch_dir / "steam-game").read_text().strip(), result.stdout)
self.assertEqual(["--wait-steam-shortcut-overview", game_id, "45"], self.agent_args.read_text().splitlines())
def test_non_game_steam_urls_remain_on_the_original_startup_arguments(self):
url = "steam://open/library"
result = self.run_launch(url, 0)
@@ -0,0 +1,50 @@
import json
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
BIN = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin'
class SteamCompatEnvironmentTest(unittest.TestCase):
def test_library_launch_preserves_guest_environment_without_steam_client_libraries(self):
source = (BIN / 'droiddeck-session').read_text()
setup = source[source.index(' _bl_compat_env='):source.index(' export SDL_VIDEO_X11_DGAMOUSE=')]
launch = next(line for line in source.splitlines()
if 'droiddeck-steam-compat "$steam_root"' in line)
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
helper = root / 'droiddeck-steam-compat'
helper.write_text('#!/usr/bin/env python3\nimport json, os, sys\n'
'json.dump({"env": dict(os.environ), "args": sys.argv[1:]}, '
'open(os.environ["BRIDGE_CAPTURE"], "w"))\n')
helper.chmod(0o755)
for inherited in ({}, {'LD_LIBRARY_PATH': '/guest/driver:/guest/libs'},
{'LD_LIBRARY_PATH': '', 'STEAM_RUNTIME': ''},
{'LD_LIBRARY_PATH': '/custom path/lib', 'STEAM_RUNTIME': '0'}):
with self.subTest(inherited=inherited):
env = dict(os.environ, PATH=str(root) + os.pathsep + os.environ['PATH'],
BRIDGE_CAPTURE=str(root / 'captured.json'),
VK_ICD_FILENAMES='/guest/driver/turnip.json', steam_root='/steam')
for key in ('LD_LIBRARY_PATH', 'STEAM_RUNTIME'):
env.pop(key, None)
env.update(inherited)
result = subprocess.run(['bash', '-c', setup + '\n' + launch + '\nwait $!\n'
'printf "%s\\n" "$STEAM_RUNTIME" "$LD_LIBRARY_PATH"'],
env=env, capture_output=True, text=True, timeout=10)
self.assertEqual(result.returncode, 0, result.stderr)
bridge = json.loads((root / 'captured.json').read_text())
self.assertEqual(bridge['args'], ['/steam'])
for key in ('LD_LIBRARY_PATH', 'STEAM_RUNTIME', 'VK_ICD_FILENAMES'):
self.assertEqual(bridge['env'].get(key), env.get(key), key)
client_path = '/steam/steamrtarm64:/steam/steamrtarm64/panorama'
if inherited.get('LD_LIBRARY_PATH'):
client_path += ':' + inherited['LD_LIBRARY_PATH']
self.assertEqual(result.stdout.splitlines(), ['1', client_path])
if __name__ == '__main__':
unittest.main()
+272 -11
View File
@@ -108,6 +108,86 @@ class FakePage:
@unittest.skipUnless(shutil.which("node"), "node is not installed")
class PageScriptTest(unittest.TestCase):
def test_vr_games_wait_for_steamvr_and_preserve_the_original_launch(self):
with tempfile.TemporaryDirectory() as tmp:
script = Path(tmp) / "vr.js"
script.write_text(LIVE["VR_JS"])
harness = Path(__file__).with_name("steam_vr_launch_harness.js")
result = subprocess.run(["node", str(harness), str(script)],
capture_output=True, text=True, timeout=20)
self.assertEqual(result.returncode, 0, result.stderr)
def test_tool_installs_skip_only_their_own_install_dialog(self):
harness_source = r"""
const assert = require('assert');
globalThis.window = globalThis;
const script = require('fs').readFileSync(process.argv[2], 'utf8');
globalThis.SteamClient = { Installs: {}, Downloads: {} };
assert.throws(() => eval(script), /install calls are not ready/);
const opened = [], queued = [];
let wizard = null, continued = 0;
globalThis.SteamClient = {
Installs: {
OpenInstallWizard(apps, client) { opened.push([apps, client]); },
RegisterForShowInstallWizard(callback) { assert.strictEqual(wizard, null); wizard = callback; return { unregister() {} }; },
ContinueInstall() { continued++; },
},
Downloads: { QueueAppUpdate(app, client) { queued.push([app, client]); } },
};
assert.strictEqual(eval(script), 'installed');
assert.strictEqual(eval(script), 'present');
const tools = window.__droiddeckTools;
wizard({ eInstallState: 7, currentAppID: 4183110 });
assert.strictEqual(continued, 0);
tools.install(4183110);
assert.deepStrictEqual(opened, [[[4183110], '0']]);
wizard({ eInstallState: 8, currentAppID: 4183110 });
wizard({ eInstallState: 7, currentAppID: 892970 });
assert.strictEqual(continued, 0);
wizard({ eInstallState: 7, currentAppID: 4183110 });
wizard({ eInstallState: 7, currentAppID: 4183110 });
assert.strictEqual(continued, 1);
tools.update(4427310);
assert.deepStrictEqual(queued, [[4427310, '0']]);
"""
with tempfile.TemporaryDirectory() as tmp:
script = Path(tmp) / "tools.js"
script.write_text(LIVE["TOOLS_JS"])
harness = Path(tmp) / "harness.js"
harness.write_text(harness_source)
result = subprocess.run(["node", str(harness), str(script)], capture_output=True, text=True, timeout=20)
self.assertEqual(result.returncode, 0, result.stderr)
def test_steamvr_library_launch_uses_binding_and_other_games_pass_through(self):
harness_source = r"""
const assert = require('assert');
globalThis.window = globalThis;
const calls = [], requests = [];
const apps = { RunGame(...args) { assert.strictEqual(this, apps); calls.push(args); return 'native'; } };
globalThis.SteamClient = { Apps: apps };
window.droiddeckLaunchSteamVr = id => requests.push(id);
const script = require('fs').readFileSync(process.argv[2], 'utf8');
assert.strictEqual(eval(script), 'installed');
assert.strictEqual(eval(script), 'present');
assert.strictEqual(apps.RunGame('250820', '', -1, 100), undefined);
apps.RunGame(250820, '', -1, 100);
assert.deepStrictEqual(requests, ['250820', '250820']);
assert.deepStrictEqual(calls, []);
assert.strictEqual(apps.RunGame('611670', 'custom args', -1, 100), 'native');
assert.strictEqual(apps.RunGame('2508200', '', -1, 100), 'native');
delete window.droiddeckLaunchSteamVr;
assert.strictEqual(apps.RunGame('250820', '', -1, 100), 'native');
assert.deepStrictEqual(calls, [['611670', 'custom args', -1, 100], ['2508200', '', -1, 100], ['250820', '', -1, 100]]);
"""
with tempfile.TemporaryDirectory() as tmp:
script = Path(tmp) / "vr.js"
script.write_text(LIVE["VR_JS"])
harness = Path(tmp) / "test.js"
harness.write_text(harness_source)
result = subprocess.run(["node", str(harness), str(script)],
capture_output=True, text=True, timeout=20)
self.assertEqual(result.returncode, 0, result.stderr)
def test_transport_framing_auth_and_notifications(self):
with tempfile.TemporaryDirectory() as tmp:
script = Path(tmp) / "install.js"
@@ -295,19 +375,19 @@ class ReconcileTest(unittest.TestCase):
state = self.reconcile(page)
self.assertEqual(page.sets, [])
self.assertEqual(state["auto"], {})
self.assertEqual(state["native"], [app])
self.assertEqual(state["native_choices"], [app])
self.assertEqual(COMPAT["read_config_mapping"](str(config)), {"0": TOOL})
page.sets.clear()
state = self.reconcile(page)
self.assertEqual(page.sets, [])
self.assertEqual(state["native"], [app])
self.assertEqual(state["native_choices"], [app])
restarted = LIVE["Helper"](str(self.steam), 1)
restarted.page = page
restarted.reconcile()
state = json.loads((self.state / "state.json").read_text())
self.assertEqual(page.sets, [])
self.assertEqual(state["native"], [app])
self.assertEqual(state["native_choices"], [app])
config.write_text(
'"InstallConfigStore" { "Software" { "Valve" { "Steam" { '
@@ -317,13 +397,13 @@ class ReconcileTest(unittest.TestCase):
state = self.reconcile(page)
self.assertEqual(page.mapping[app], "GE-Proton11-7")
self.assertEqual(page.sets, [])
self.assertEqual(state["native"], [])
self.assertEqual(state["native_choices"], [])
for choice in ("steamlinuxruntime", COMPAT["FEX_TOOL"], TOOL_11):
(self.state / "state.json").write_text(json.dumps({
"default": TOOL,
"auto": {},
"native": [app],
"native_choices": [app],
}))
config.write_text(
'"InstallConfigStore" { "Software" { "Valve" { "Steam" { '
@@ -334,7 +414,7 @@ class ReconcileTest(unittest.TestCase):
state = self.reconcile(page)
self.assertEqual(page.mapping[app], choice)
self.assertEqual(page.sets, [])
self.assertEqual(state["native"], [], choice)
self.assertEqual(state["native_choices"], [], choice)
finally:
COMPAT["native_targets"] = original_native_targets
@@ -348,7 +428,7 @@ class ReconcileTest(unittest.TestCase):
(self.state / "state.json").write_text(json.dumps({
"default": TOOL,
"auto": {},
"native": [app],
"native_choices": [app],
}))
original_native_targets = COMPAT["native_targets"]
@@ -357,14 +437,14 @@ class ReconcileTest(unittest.TestCase):
page = FakePage({"0": TOOL, app: "proton"}, [TOOL, TOOL_11])
state = self.reconcile(page)
self.assertNotIn(app, self.helper.installed)
self.assertEqual(state["native"], [app])
self.assertEqual(state["native_choices"], [app])
self.assertNotIn(app, state["auto"])
self.assertNotIn((app, TOOL), page.sets)
self.assertEqual(COMPAT["read_config_mapping"](str(config)), {"0": TOOL})
config.write_text('"InstallConfigStore" { "Software" { "Other" {} } }')
state = self.reconcile(page)
self.assertEqual(state["native"], [app])
self.assertEqual(state["native_choices"], [app])
self.assertNotIn((app, TOOL), page.sets)
config.write_text(
@@ -373,12 +453,72 @@ class ReconcileTest(unittest.TestCase):
'"%s" { "name" "GE-Proton11-7" } } } } } }' % (TOOL, app))
page.mapping[app] = "proton"
state = self.reconcile(page)
self.assertEqual(state["native"], [])
self.assertEqual(state["native_choices"], [])
self.assertNotIn((app, TOOL), page.sets)
self.assertEqual(COMPAT["read_config_mapping"](str(config))[app], "GE-Proton11-7")
finally:
COMPAT["native_targets"] = original_native_targets
def dual_platform_game(self, state):
app = "892970"
(self.steam / ("steamapps/appmanifest_%s.acf" % app)).write_text("")
config = self.steam / "config/config.vdf"
config.parent.mkdir(parents=True)
config.write_text(
'"InstallConfigStore" { "Software" { "Valve" { "Steam" { '
'"CompatToolMapping" { "0" { "name" "%s" } } } } } }' % TOOL)
(self.state / "state.json").write_text(json.dumps(state))
patcher = mock.patch.dict(COMPAT, {"native_targets": lambda _root, apps: {
app: COMPAT["NATIVE_CHOICE"]
} if app in apps else {}})
patcher.start()
self.addCleanup(patcher.stop)
return app, FakePage({"0": TOOL, "10": TOOL, "11": TOOL}, [TOOL, TOOL_11])
def test_unmapped_dual_platform_game_gets_the_default_live(self):
app, page = self.dual_platform_game({"default": TOOL, "auto": {"10": TOOL, "11": TOOL}})
state = self.reconcile(page)
self.assertEqual(page.sets, [(app, TOOL)])
self.assertEqual(state["auto"][app], TOOL)
self.assertEqual(state["native_choices"], [])
page.mapping[app] = ""
page.sets.clear()
state = self.reconcile(page)
self.assertEqual(page.sets, [])
self.assertEqual(state["native_choices"], [app])
def test_unmapped_dual_platform_game_gets_the_default_without_a_readable_config(self):
app, page = self.dual_platform_game({"default": TOOL, "auto": {"10": TOOL}, "native_choices": ["11"]})
(self.steam / "config/config.vdf").unlink()
page.mapping["11"] = ""
state = self.reconcile(page)
self.assertEqual(page.sets, [(app, TOOL)])
self.assertEqual(state["auto"][app], TOOL)
self.assertEqual(state["native_choices"], ["11"])
def test_a_tool_set_live_is_kept_before_the_client_writes_its_config(self):
app, page = self.dual_platform_game({"default": TOOL, "auto": {"10": TOOL, "11": TOOL, "892970": TOOL}})
page.known.append(COMPAT["FEX_TOOL"])
page.mapping[app] = TOOL
config = self.steam / "config/config.vdf"
config.write_text(
'"InstallConfigStore" { "Software" { "Valve" { "Steam" { '
'"CompatToolMapping" { "0" { "name" "%s" } "%s" { "name" "%s" } } } } } }' % (TOOL, app, TOOL))
with mock.patch.dict(COMPAT, {"native_targets": lambda _root, apps: {app: COMPAT["FEX_TOOL"]} if app in apps else {}}):
state = self.reconcile(page)
self.assertEqual(page.sets, [(app, COMPAT["FEX_TOOL"])])
state = self.reconcile(page)
self.assertEqual(page.sets, [(app, COMPAT["FEX_TOOL"])])
self.assertEqual(state["auto"][app], COMPAT["FEX_TOOL"])
def test_native_list_from_earlier_builds_is_not_trusted(self):
app, page = self.dual_platform_game({"default": TOOL, "auto": {"10": TOOL, "11": TOOL}, "native": ["892970"]})
state = self.reconcile(page)
self.assertEqual(page.sets, [(app, TOOL)])
self.assertNotIn("native", state)
self.assertEqual(state["native_choices"], [])
def test_factorio_without_prior_auto_state_uses_the_default_proton(self):
app = "427520"
(self.steam / ("steamapps/appmanifest_%s.acf" % app)).write_text("")
@@ -397,7 +537,7 @@ class ReconcileTest(unittest.TestCase):
state = self.reconcile(page)
self.assertEqual(page.sets, [(app, TOOL)])
self.assertEqual(state["auto"], {app: TOOL})
self.assertEqual(state["native"], [])
self.assertEqual(state["native_choices"], [])
self.assertEqual(COMPAT["read_config_mapping"](str(config)), {"0": TOOL})
finally:
COMPAT["native_targets"] = original_native_targets
@@ -446,6 +586,79 @@ console.log(JSON.stringify({ sent: sent.length, asked: asked.length }));
"""
class ToolPage(FakePage):
def __init__(self, fail=False):
super().__init__({"0": TOOL}, [TOOL])
self.calls = []
self.fail = fail
def tools(self, call):
self.calls.append(call)
if self.fail:
raise RuntimeError("the client's install calls are not ready")
return True
class ToolDownloadTest(unittest.TestCase):
def setUp(self):
tmp = tempfile.TemporaryDirectory()
self.addCleanup(tmp.cleanup)
self.steam = Path(tmp.name) / "Steam"
(self.steam / "steamapps").mkdir(parents=True)
self.helper = LIVE["Helper"](str(self.steam), 1)
self.now = [1000.0]
self.running = [False]
self.requested = []
patcher = mock.patch.dict(COMPAT, {
"game_running": lambda: self.running[0],
"request_fex": lambda root, asked: self.requested.append(root) or ["3127680"],
})
patcher.start()
self.addCleanup(patcher.stop)
clock = mock.patch.object(LIVE["time"], "monotonic", lambda: self.now[0])
clock.start()
self.addCleanup(clock.stop)
def manifest(self, app, flags):
(self.steam / ("steamapps/appmanifest_%s.acf" % app)).write_text('"AppState" { "StateFlags" "%s" }' % flags)
def test_missing_tools_are_installed_and_deferred_ones_queued(self):
self.manifest("4427310", "6")
self.manifest("3127680", "4")
self.manifest("1628350", "1026")
self.helper.page = page = ToolPage()
self.helper.ensure_tools()
self.assertEqual(page.calls, ["update(4427310)", "update(1628350)", "install(4183110)"])
self.now[0] += 30
self.helper.ensure_tools()
self.now[0] += 60
self.helper.ensure_tools()
self.assertEqual(len(page.calls), 3)
self.now[0] += 300
self.manifest("4427310", "4")
self.helper.ensure_tools()
self.assertEqual(page.calls[3:], ["update(1628350)", "install(4183110)"])
self.assertEqual(self.requested, [])
def test_nothing_is_queued_while_a_game_runs(self):
self.running[0] = True
self.helper.page = page = ToolPage()
self.helper.ensure_tools()
self.assertEqual(page.calls, [])
self.running[0] = False
self.now[0] += 60
self.helper.ensure_tools()
self.assertEqual(len(page.calls), 4)
def test_an_install_falls_back_to_the_steam_url(self):
for app in ("4427310", "1628350", "4183110"):
self.manifest(app, "4")
self.helper.page = page = ToolPage(fail=True)
self.helper.ensure_tools()
self.assertEqual(page.calls, ["install(3127680)"])
self.assertEqual(self.requested, [str(self.steam)])
@unittest.skipUnless(shutil.which("node"), "node is not installed")
class SwitchScriptTest(unittest.TestCase):
def test_the_request_is_reported_and_still_sent(self):
@@ -493,6 +706,54 @@ class SwitchToDesktopTest(unittest.TestCase):
self.assertNotIn(("Runtime.addBinding", LIVE["SWITCH_BINDING"]), helper.page.calls)
self.assertNotIn(LIVE["SWITCH_JS"], helper.page.scripts)
def test_vr_bridge_is_installed_for_both_steam_ui_modes(self):
for steamos in (False, True):
helper = LIVE["Helper"]("/steam", 1, steamos=steamos)
helper.attach()
self.assertIn(("Runtime.addBinding", LIVE["VR_BINDING"]), helper.page.calls)
self.assertIn(LIVE["VR_JS"], helper.page.scripts)
def test_vr_bridge_accepts_only_steamvr_and_coalesces_requests(self):
helper = LIVE["Helper"]("/steam", 1)
helper.page = mock.Mock()
event = lambda payload: {"method": "Runtime.bindingCalled", "params": {
"name": LIVE["VR_BINDING"], "payload": payload}}
with mock.patch.dict(self.globals, {"launch_steamvr": mock.Mock()}) as patched:
launch = patched["launch_steamvr"]
helper.page.drain.return_value = [event("0"), event("250820; touch /tmp/wrong"),
event("-1"), event("01"), event("18446744073709551616"),
event("\u0661"), event(None), event({})]
helper.drain()
launch.assert_not_called()
helper.page.drain.return_value = [event("250820"), event("250820")]
helper.drain()
launch.assert_called_once_with()
def test_vr_game_requests_share_an_in_progress_helper_and_retry_after_it_exits(self):
helper = LIVE["Helper"]("/steam", 1)
helper.page = mock.Mock()
event = lambda app: {"method": "Runtime.bindingCalled", "params": {
"name": LIVE["VR_BINDING"], "payload": app}}
child = mock.Mock()
child.poll.return_value = None
with mock.patch.dict(self.globals, {"launch_steamvr": mock.Mock(return_value=child)}) as patched:
helper.page.drain.return_value = [event("611670"), event("620980")]
helper.drain()
helper.drain()
patched["launch_steamvr"].assert_called_once_with()
child.poll.return_value = 0
helper.drain()
self.assertEqual(patched["launch_steamvr"].call_count, 2)
def test_vr_launch_runs_helper_without_shell_in_background(self):
with tempfile.TemporaryDirectory() as tmp, mock.patch.dict(os.environ, {"XDG_RUNTIME_DIR": tmp}):
with mock.patch.object(self.globals["subprocess"], "Popen") as popen:
LIVE["launch_steamvr"]()
self.assertEqual(popen.call_args.args, ([LIVE["VR_HELPER"], "launch"],))
self.assertTrue(popen.call_args.kwargs["start_new_session"])
self.assertNotIn("shell", popen.call_args.kwargs)
self.assertTrue((Path(tmp) / "droiddeck-steamvr/library-launch.log").exists())
def test_the_request_goes_to_steamos_session_select(self):
helper = LIVE["Helper"]("/steam", 1)
helper.page = mock.Mock()
+108
View File
@@ -0,0 +1,108 @@
import os
from pathlib import Path
import runpy
import tempfile
import unittest
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
COMPAT = runpy.run_path(str(BIN / "steam-compatibility"))
CONFIG = '''"InstallConfigStore"
{
\t"Software"
\t{
\t\t"Valve"
\t\t{
\t\t\t"Steam"
\t\t\t{
\t\t\t\t"CompatToolMapping"
\t\t\t\t{
\t\t\t\t\t"550"
\t\t\t\t\t{
\t\t\t\t\t\t"name"\t\t"proton_experimental"
\t\t\t\t\t\t"config"\t\t""
\t\t\t\t\t\t"priority"\t\t"250"
\t\t\t\t\t}
\t\t\t\t\t"620"
\t\t\t\t\t{
\t\t\t\t\t\t"name"\t\t"proton-cachyos-a64"
\t\t\t\t\t\t"config"\t\t""
\t\t\t\t\t\t"priority"\t\t"250"
\t\t\t\t\t}
\t\t\t\t\t"880"
\t\t\t\t\t{
\t\t\t\t\t\t"name"\t\t"droiddeck-proton-arm64"
\t\t\t\t\t\t"config"\t\t""
\t\t\t\t\t\t"priority"\t\t"250"
\t\t\t\t\t}
\t\t\t\t\t"730"
\t\t\t\t\t{
\t\t\t\t\t\t"name"\t\t"steamlinuxruntime"
\t\t\t\t\t\t"config"\t\t""
\t\t\t\t\t\t"priority"\t\t"250"
\t\t\t\t\t}
\t\t\t\t}
\t\t\t}
\t\t}
\t}
}
'''
class X64RepointTest(unittest.TestCase):
"""steam-compatibility --x64: the x86-64 client's Proton entries go to its arm64 wrapper."""
def setUp(self):
self.home = tempfile.TemporaryDirectory()
self.root = Path(self.home.name) / "Steam"
(self.root / "config").mkdir(parents=True)
(self.root / "config" / "config.vdf").write_text(CONFIG)
# A wrapper of its own whose name starts with "proton": kept, never repointed.
own = self.root / "compatibilitytools.d" / "proton-cachyos-a64"
own.mkdir(parents=True)
(own / "compatibilitytool.vdf").write_text('"compatibilitytools"\n{\n\t"compat_tools"\n\t{\n\t\t"proton-cachyos-a64"\n\t\t{\n\t\t}\n\t}\n}\n')
self.old_home = os.environ.get("HOME")
os.environ["HOME"] = self.home.name
def tearDown(self):
if self.old_home is None:
os.environ.pop("HOME", None)
else:
os.environ["HOME"] = self.old_home
self.home.cleanup()
def mapping(self):
tokens = COMPAT["tokenize"]((self.root / "config" / "config.vdf").read_text())
return COMPAT["read_mapping"](tokens, COMPAT["mapping_block"](tokens))
def test_repoints_valve_proton_only(self):
moved = COMPAT["x64_repoint"](str(self.root), "GE-Proton11-7-a64")
self.assertEqual(moved, ["550", "880"])
m = self.mapping()
self.assertEqual(m["550"], "GE-Proton11-7-a64")
self.assertEqual(m["620"], "proton-cachyos-a64")
self.assertEqual(m["730"], "steamlinuxruntime")
# The arm64 client's own Proton name, which this client ignores.
self.assertEqual(m["880"], "GE-Proton11-7-a64")
self.assertEqual(m["0"], "GE-Proton11-7-a64")
def test_repoints_arm64_name_even_with_its_stray_tool(self):
# An arm64 compat pass that ran against this client also left its tool folder here.
stray = self.root / "compatibilitytools.d" / "droiddeck-proton-arm64"
stray.mkdir(parents=True)
(stray / "compatibilitytool.vdf").write_text('"compatibilitytools"\n{\n\t"compat_tools"\n\t{\n\t\t"droiddeck-proton-arm64"\n\t\t{\n\t\t}\n\t}\n}\n')
self.assertIn("880", COMPAT["x64_repoint"](str(self.root), "GE-Proton11-7-a64"))
self.assertEqual(self.mapping()["880"], "GE-Proton11-7-a64")
def test_live_notes_pending_restart(self):
COMPAT["x64_repoint"](str(self.root), "GE-Proton11-7-a64", live=True)
self.assertEqual((Path(self.home.name) / ".bl-compat-pending").read_text(), "550\n880\n")
def test_no_tool_changes_nothing(self):
before = (self.root / "config" / "config.vdf").read_text()
self.assertEqual(COMPAT["x64_repoint"](str(self.root), None), [])
self.assertEqual((self.root / "config" / "config.vdf").read_text(), before)
if __name__ == "__main__":
unittest.main()
+21 -1
View File
@@ -23,9 +23,13 @@ class DesktopSteamLaunchTest(unittest.TestCase):
supervisor = self.root / 'supervisor'
supervisor.write_text('#!/bin/bash\nprintf "%s\\n" "$BL_INSIDE" "$BL_STEAM_UI" "$DISPLAY" "$@"\n')
supervisor.chmod(0o755)
x64 = self.root / 'steam-x64'
x64.write_text('#!/bin/bash\nprintf "%s\\n" x64 "$@"\n')
x64.chmod(0o755)
self.launcher = self.root / 'launch'
self.launcher.write_text((BIN / 'droiddeck-steam-launch').read_text().replace(
'/usr/local/bin/droiddeck-session', str(supervisor)))
'/usr/local/bin/droiddeck-session', str(supervisor)).replace(
'/usr/local/bin/droiddeck-steam-x64', str(x64)))
def launch(self, *args):
return subprocess.run(['bash', str(self.launcher), *args], env=self.env,
@@ -62,6 +66,22 @@ class DesktopSteamLaunchTest(unittest.TestCase):
'-cef-disable-gpu', 'steam://open/settings'])
self.assertFalse((self.session / 'steam-launch').exists())
def test_second_click_forwards_to_the_x86_64_client_in_its_own_home(self):
lock = self.root / 'cache/droiddeck/steam-desktop.lock'
lock.parent.mkdir(parents=True)
x64_home = self.root / 'x64'
(x64_home / '.steam').mkdir(parents=True)
os.mkfifo(x64_home / '.steam/steam.pipe')
(x64_home / '.steam/steam.pid').write_text(str(os.getpid()))
self.env.update(BL_STEAM_CLIENT_ARCH='x86_64', BL_X64_HOME=str(x64_home))
with lock.open('w') as handle:
fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
result = self.launch('desktop', '501590')
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(result.stdout.splitlines(), ['x64', '--exec', '-nobigpicture', '-no-cef-sandbox',
'-cef-ozone-platform=x11', '-cef-disable-gpu',
'steam://rungameid/501590'])
def test_second_click_waits_for_steam_ipc_during_startup(self):
lock = self.root / 'cache/droiddeck/steam-desktop.lock'
lock.parent.mkdir(parents=True)
+11
View File
@@ -84,6 +84,17 @@ class ImportsTest(unittest.TestCase):
imports.watch(str(self.steam), str(listing))
identify.assert_not_called()
def test_native_programs_stay_shortcuts_and_are_never_looked_up(self):
self.snapshot()
game = dict(self.game, native=True)
self.assertEqual(([game], {}), imports.route(self.steam, self.acct, [game]))
self.assertFalse((self.steam / 'steamapps/appmanifest_42.acf').exists())
listing = self.root / 'games.json'
listing.write_text(json.dumps([game]))
with patch.object(imports, 'identify') as identify:
imports.watch(str(self.steam), str(listing))
identify.assert_not_called()
def test_migrates_only_unchanged_legacy_import_manifests(self):
self.snapshot()
imports.route(self.steam, self.acct, [self.game])
+34 -10
View File
@@ -28,8 +28,21 @@ class SteamInstallTest(unittest.TestCase):
curl = self.bin / 'curl'
curl.write_text('''#!/bin/bash
set -eu
printf '%s\\n' "$2" >> "$TEST_REQUESTS"
cp "$TEST_CDN/${2##*/}" "$4"
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.chmod(0o755)
if shutil.which('sha256sum') is None:
@@ -55,11 +68,12 @@ cp "$TEST_CDN/${2##*/}" "$4"
f'\t\t"file" "{archive.name}"\n\t\t"sha2" "{digest}"\n'
'\t}\n}\n')
def install(self):
return subprocess.run(['bash', str(SCRIPT)], env=self.env, text=True, capture_output=True)
def install(self, fail_host=None):
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)
def assert_installed(self, channel='steamdeck_publicbeta'):
result = self.install()
def assert_installed(self, channel='steamdeck_publicbeta', fail_host=None, expected=None):
result = self.install(fail_host)
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())
@@ -67,14 +81,24 @@ cp "$TEST_CDN/${2##*/}" "$4"
self.assertTrue(os.access(client, os.X_OK))
self.assertEqual(channel, client.read_text())
self.assertEqual((self.steam / 'linuxarm64').resolve(), (self.home / '.steam/sdkarm64').resolve())
self.assertEqual([
'https://client-update.fastly.steamstatic.com/steam_client_' + channel + '_linuxarm64',
'https://client-update.fastly.steamstatic.com/' + channel + '.zip',
], self.requests.read_text().splitlines())
if expected is None:
expected = [
'https://client-update.steamstatic.com/steam_client_' + channel + '_linuxarm64',
'https://client-update.steamstatic.com/' + channel + '.zip',
]
self.assertEqual(expected, self.requests.read_text().splitlines())
def test_downloads_the_deck_beta_client(self):
self.assert_installed()
def test_a_cdn_that_does_not_answer_hands_over_to_the_next_one(self):
akamai = 'https://client-update.akamai.steamstatic.com'
self.assert_installed(fail_host='client-update.steamstatic.com', expected=[
'https://client-update.steamstatic.com/steam_client_steamdeck_publicbeta_linuxarm64',
akamai + '/steam_client_steamdeck_publicbeta_linuxarm64',
akamai + '/steamdeck_publicbeta.zip',
])
def test_an_install_from_another_branch_is_left_for_steam_to_move(self):
self.assert_installed()
requests = self.requests.read_text()
+1 -1
View File
@@ -121,7 +121,7 @@ class CompatLibrariesTest(unittest.TestCase):
manifest(self.pc / "steamapps", 30)
manifest(self.pc / "steamapps", 3127680, installdir="FEX")
self.assertEqual(["20", "30"], COMPAT["installed_apps"](str(self.steam)))
self.assertEqual(["1628350"], COMPAT["fex_missing"](str(self.steam)))
self.assertEqual(["1628350", "4183110"], COMPAT["fex_missing"](str(self.steam)))
def test_newest_proton_across_libraries_wins(self):
for root, build in ((self.steam, "100"), (self.pc, "200")):
+185
View File
@@ -0,0 +1,185 @@
import os
from pathlib import Path
import subprocess
import tempfile
import textwrap
import unittest
SESSION = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-session"
SOURCE = SESSION.read_text()
START = SOURCE.index(" steam_other_game_running() {")
END = SOURCE.index(" steam_bring_forward() {", START)
FUNCTIONS = textwrap.dedent(SOURCE[START:END])
GAME = str((3333273269 << 32) | 0x02000000)
class SteamShortcutRecoveryTest(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.launch = self.root / "session"
self.launch.mkdir()
self.bin = self.root / "bin"
self.bin.mkdir()
steam = self.root / "steam/steamrtarm64"
steam.mkdir(parents=True)
self.steam_log = self.root / "steam-args"
(steam / "steam").write_text("#!/bin/sh\nprintf '%s\\n' \"$*\" >> \"$STEAM_LOG\"\n")
(steam / "steam").chmod(0o755)
self.agent = self.bin / "droiddeck-agent"
self.agent.write_text(
"#!/bin/sh\n"
"n=$(cat \"$AGENT_COUNT\" 2>/dev/null || echo 0); n=$((n + 1)); echo $n > \"$AGENT_COUNT\"\n"
"i=0; last=0\n"
"for s in $AGENT_STATES; do i=$((i + 1)); last=$s; [ \"$i\" -eq \"$n\" ] && exit \"$s\"; done\n"
"exit \"$last\"\n")
self.agent.chmod(0o755)
def launch_game(self, states, focusable="769", extra=None, client=None):
xprop = self.bin / "xprop"
xprop.write_text("#!/bin/sh\necho 'GAMESCOPE_FOCUSABLE_APPS(CARDINAL) = %s'\n" % focusable)
xprop.chmod(0o755)
script = "nap() { :; }\nsteam_root=%s\n%s%s\nsteam_launch_game %s\n" % (
self.root / "steam", "steam_client=(%s --exec)\n" % client if client else "",
FUNCTIONS.replace("/usr/local/bin/droiddeck-agent", str(self.agent)), GAME)
env = dict(os.environ, HOME=str(self.root), BL_LAUNCH_DIR=str(self.launch),
PATH=str(self.bin) + os.pathsep + os.environ["PATH"], STEAM_LOG=str(self.steam_log),
AGENT_COUNT=str(self.root / "agent-count"), AGENT_STATES=states, **(extra or {}))
result = subprocess.run(["bash", "-c", script], env=env, text=True, capture_output=True, timeout=10)
self.assertEqual(0, result.returncode, result.stderr)
steam = self.steam_log.read_text().splitlines() if self.steam_log.exists() else []
restart = self.root / ".bl-restart-game"
return steam, restart.read_text().strip() if restart.exists() else None, result.stdout
def test_a_shortcut_that_stays_known_launches_once(self):
steam, restart, _ = self.launch_game("0")
self.assertEqual(["steam://rungameid/" + GAME], steam)
self.assertIsNone(restart)
self.assertEqual("9", (self.root / "agent-count").read_text().strip())
def test_a_shortcut_dropped_while_launching_restarts_steam_for_it(self):
steam, restart, out = self.launch_game("0 0 4")
self.assertEqual(["steam://rungameid/" + GAME, "-shutdown"], steam)
self.assertEqual(GAME, restart)
self.assertIn("dropped shortcut", out)
def test_the_running_x86_64_client_gets_the_launch_and_the_restart(self):
x64 = self.bin / "droiddeck-steam-x64"
x64_log = self.root / "x64-args"
x64.write_text("#!/bin/sh\nprintf '%s\\n' \"$*\" >> \"$X64_LOG\"\n")
x64.chmod(0o755)
steam, restart, _ = self.launch_game("0 0 4", client=x64, extra={"X64_LOG": str(x64_log)})
self.assertEqual([], steam)
self.assertEqual(["--exec steam://rungameid/" + GAME, "--exec -shutdown"], x64_log.read_text().splitlines())
self.assertEqual(GAME, restart)
def test_a_shortcut_already_lost_restarts_steam_without_launching(self):
steam, restart, out = self.launch_game("4")
self.assertEqual(["-shutdown"], steam)
self.assertEqual(GAME, restart)
self.assertIn("lost shortcut", out)
def test_steam_is_restarted_only_once_for_the_same_game(self):
steam, restart, _ = self.launch_game("4")
self.assertEqual(GAME, restart)
(self.root / ".bl-restart-game").unlink()
self.steam_log.unlink()
(self.root / "agent-count").unlink()
steam, restart, out = self.launch_game("4")
self.assertEqual(["steam://rungameid/" + GAME], steam)
self.assertIsNone(restart)
self.assertIn("already restarted", out)
def test_a_ready_shortcut_allows_a_later_restart_again(self):
self.launch_game("4")
(self.root / ".bl-restart-game").unlink()
(self.root / "agent-count").unlink()
self.launch_game("0")
self.assertFalse((self.root / ".bl-restarted-for").exists())
def test_a_running_game_is_never_cut_off_by_a_restart(self):
steam, restart, _ = self.launch_game("0 4", focusable="769,3703311242")
self.assertEqual(["steam://rungameid/" + GAME], steam)
self.assertIsNone(restart)
steam, restart, _ = self.launch_game("4", focusable="769,3703311242")
self.assertIsNone(restart)
def test_the_open_launcher_does_not_count_as_a_running_game(self):
(self.launch / "epic-open").write_text("2702387189\n")
steam, restart, _ = self.launch_game("0 4", focusable="769,2702387189")
self.assertEqual(GAME, restart)
def test_the_launcher_without_its_steam_id_still_does_not_count_as_a_running_game(self):
(self.launch / "epic-open").write_text("1\n")
launcher = {"BL_EPIC_APP_ID": "2702387189"}
steam, restart, _ = self.launch_game("0 4", focusable="769,2702387189", extra=launcher)
self.assertEqual(GAME, restart)
for marker in (".bl-restart-game", ".bl-restarted-for", "agent-count"):
(self.root / marker).unlink(missing_ok=True)
steam, restart, _ = self.launch_game("4", focusable="769,2702387189,3703311242", extra=launcher)
self.assertIsNone(restart)
def test_steam_games_are_launched_without_watching(self):
steam, restart, _ = self.launch_game("3")
self.assertEqual(["steam://rungameid/" + GAME], steam)
self.assertIsNone(restart)
self.assertEqual("1", (self.root / "agent-count").read_text().strip())
def check_exits(self, listings, states, beats):
pgrep = self.bin / "pgrep"
pgrep.write_text(
"#!/bin/bash\n"
"n=$(cat \"$PGREP_COUNT\" 2>/dev/null || echo 0); n=$((n + 1)); echo $n > \"$PGREP_COUNT\"\n"
"IFS='|' read -r -a runs <<< \"$PGREP_RUNS\"\n"
"line=${runs[$((n - 1))]:-}\n"
"[ -n \"$line\" ] || exit 1\n"
"printf '%s\\n' \"$line\"\n")
pgrep.chmod(0o755)
script = "steam_root=%s\n%s\ndeclare -A _bl_ran=()\n_bl_exited=\n%s" % (
self.root / "steam", FUNCTIONS.replace("/usr/local/bin/droiddeck-agent", str(self.agent)),
"steam_check_exits\n" * beats)
env = dict(os.environ, HOME=str(self.root), BL_LAUNCH_DIR=str(self.launch),
PATH=str(self.bin) + os.pathsep + os.environ["PATH"], STEAM_LOG=str(self.steam_log),
AGENT_COUNT=str(self.root / "agent-count"), AGENT_STATES=states,
PGREP_COUNT=str(self.root / "pgrep-count"), PGREP_RUNS="|".join(listings))
result = subprocess.run(["bash", "-c", script], env=env, text=True, capture_output=True, timeout=10)
self.assertEqual(0, result.returncode, result.stderr)
steam = self.steam_log.read_text().splitlines() if self.steam_log.exists() else []
agent = self.root / "agent-count"
return steam, (self.root / ".bl-restart-lost").exists(), int(agent.read_text()) if agent.exists() else 0, result.stdout
RUNNING = "41 /root/.local/share/Steam/steamrtarm64/reaper SteamLaunch AppId=3333273269 -- /x/.droiddeck-launch.bat"
def test_a_shortcut_dropped_when_its_game_exits_restarts_steam_once_nothing_runs(self):
steam, marker, asked, out = self.check_exits([self.RUNNING, "", "", ""], "4", 3)
self.assertEqual(["-shutdown"], steam)
self.assertTrue(marker)
self.assertEqual(1, asked)
self.assertIn("3333273269", out)
def test_a_shortcut_still_listed_after_its_game_exits_is_left_alone(self):
steam, marker, asked, _ = self.check_exits([self.RUNNING, "", "", ""], "0", 4)
self.assertEqual([], steam)
self.assertFalse(marker)
self.assertEqual(1, asked)
def test_the_check_waits_a_quiet_beat_after_the_exit(self):
steam, _, asked, _ = self.check_exits([self.RUNNING, ""], "4", 2)
self.assertEqual([], steam)
self.assertEqual(0, asked)
def test_a_game_started_meanwhile_is_never_cut_off(self):
steam, marker, _, _ = self.check_exits([self.RUNNING, "", "", self.RUNNING], "4", 3)
self.assertEqual([], steam)
self.assertFalse(marker)
def test_steam_games_are_not_checked(self):
game = "41 /root/.local/share/Steam/steamrtarm64/reaper SteamLaunch AppId=1245620 -- /x/eldenring.exe"
steam, _, asked, _ = self.check_exits([game, "", "", ""], "4", 3)
self.assertEqual([], steam)
self.assertEqual(0, asked)
if __name__ == "__main__":
unittest.main()
+12
View File
@@ -147,6 +147,18 @@ class ShortcutsTest(unittest.TestCase):
self.assertEqual({'1': 'Favorites', '0': shortcuts.TAG}, entry['tags'])
self.assertEqual({'0': shortcuts.TAG}, shortcuts.merge(shortcuts.shortcut(self.game()), dict(shortcuts.shortcut(self.game()), tags={}), None, 0)[0]['tags'])
def test_a_copy_the_running_client_added_of_an_added_game_is_dropped(self):
self.run_writer(self.game())
path = self.config / 'shortcuts.vdf'
data = shortcuts.parse(path.read_bytes())['shortcuts']
live = dict(shortcuts.shortcut(self.game(appid=0x91234567)), tags={})
own = dict(shortcuts.shortcut(self.game(exe='Other.exe', appid=0x92345678)), tags={})
renamed = dict(shortcuts.shortcut(self.game(appid=0x93456789, name='My copy')), tags={})
data.update({'7': live, '8': own, '9': renamed})
path.write_bytes(shortcuts.write({'shortcuts': data}))
entries = self.run_writer(self.game())
self.assertEqual({APPID, 0x92345678, 0x93456789}, set(entries))
def test_a_damaged_record_is_started_over(self):
self.run_writer(self.game())
(self.config / shortcuts.RECORD).write_text('{not json')
+65
View File
@@ -0,0 +1,65 @@
import json
import os
from pathlib import Path
import socket
import subprocess
import tempfile
import unittest
SOURCE = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-steamvr-game'
class SteamVrGameTest(unittest.TestCase):
def setUp(self):
temporary = tempfile.TemporaryDirectory()
self.addCleanup(temporary.cleanup)
self.root = Path(temporary.name)
self.helper = self.root / 'helper'
self.assertIn('/run/droiddeck/droiddeck-xr-frames', SOURCE.read_text())
self.helper.write_text(SOURCE.read_text().replace('/run/droiddeck/droiddeck-xr-frames',
str(self.root / 'droiddeck-xr-frames')), encoding='utf-8')
self.command('pgrep', '#!/bin/sh\nexit 0\n')
self.command('gamescope', '#!/usr/bin/env python3\nimport json, os, sys\n'
'print(json.dumps(dict(argv=sys.argv[1:], modifiers=os.getenv("gamescope_vr_use_modifiers"), '
'layers=os.getenv("VK_INSTANCE_LAYERS"))))\n')
self.env = {key: value for key, value in os.environ.items()
if not key.startswith(('gamescope_vr_', 'VK_'))}
self.env.update(PATH=str(self.root) + os.pathsep + os.environ['PATH'],
XDG_RUNTIME_DIR=str(self.root))
def command(self, name, text):
path = self.root / name
path.write_text(text, encoding='utf-8')
path.chmod(0o755)
def run_game(self, *args):
return subprocess.run(['sh', str(self.helper), *args], env=self.env,
capture_output=True, text=True, timeout=5)
def test_native_backend_preserves_command_arguments_and_nonquest_defaults(self):
result = self.run_game('game with spaces', 'a b', '$literal')
self.assertEqual(result.returncode, 0, result.stderr)
data = json.loads(result.stdout)
self.assertEqual(data['argv'][:2], ['--backend', 'openvr'])
self.assertEqual(data['argv'][-4:], ['--', 'game with spaces', 'a b', '$literal'])
self.assertIsNone(data['modifiers'])
self.assertEqual(data['layers'], 'VK_LAYER_DROIDDECK_vr')
def test_quest_selects_vulkan_sharing_and_preserves_explicit_override(self):
with socket.socket(socket.AF_UNIX) as receiver:
receiver.bind(str(self.root / 'droiddeck-xr-frames'))
self.assertEqual(json.loads(self.run_game('game').stdout)['modifiers'], 'false')
self.env['gamescope_vr_use_modifiers'] = 'true'
self.assertEqual(json.loads(self.run_game('game').stdout)['modifiers'], 'true')
def test_missing_runtime_and_missing_command_fail_clearly(self):
self.assertEqual(self.run_game().returncode, 2)
self.command('pgrep', '#!/bin/sh\nexit 1\n')
result = self.run_game('game')
self.assertEqual(result.returncode, 1)
self.assertIn('Start SteamVR', result.stderr)
if __name__ == '__main__':
unittest.main()
+79
View File
@@ -0,0 +1,79 @@
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import time
import unittest
HELPER = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-steamvr'
@unittest.skipUnless(shutil.which('sh'), 'requires a POSIX shell')
class SteamVrGraphicsTest(unittest.TestCase):
def launch(self, model, debug=None, action='start', preload=None):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
bindir = root / 'bin'
bindir.mkdir()
runtime = root / 'steamvr/bin/linuxarm64'
runtime.mkdir(parents=True)
(runtime / 'vrstartup').touch(mode=0o755)
driver = root / 'driver/droiddeck/bin/linuxarm64'
driver.mkdir(parents=True)
(driver / 'driver_droiddeck.so').touch()
result = root / 'launch-env'
preloads = root / 'launch-preload'
scripts = {
'cat': 'if [ "$1" = /sys/class/kgsl/kgsl-3d0/gpu_model ]; then printf "%s" "$TEST_GPU_MODEL"; else exec /bin/cat "$@"; fi',
'pgrep': 'exit 1',
'setsid': 'printf "%s" "$LD_PRELOAD" > "$TEST_LAUNCH_PRELOAD"; printf "%s" "${TU_DEBUG-unset}" > "$TEST_LAUNCH_ENV"',
}
for name, script in scripts.items():
path = bindir / name
path.write_text('#!/bin/sh\n' + script + '\n')
path.chmod(0o755)
env = dict(os.environ, HOME=str(root), XDG_RUNTIME_DIR=str(root / 'run'),
STEAMVR=str(root / 'steamvr'), DROIDDECK_VR_DIR=str(root / 'driver'),
PATH=str(bindir) + os.pathsep + os.environ['PATH'],
TEST_GPU_MODEL=model, TEST_LAUNCH_ENV=str(result), TEST_LAUNCH_PRELOAD=str(preloads))
env.pop('TU_DEBUG', None)
env.pop('LD_PRELOAD', None)
if debug is not None:
env['TU_DEBUG'] = debug
if preload is not None:
env['LD_PRELOAD'] = preload
run = subprocess.run(['sh', str(HELPER), action], env=env,
capture_output=True, text=True, timeout=10)
self.assertEqual(run.returncode, 0, run.stderr)
until = time.monotonic() + 2
while not result.exists() and time.monotonic() < until:
time.sleep(0.01)
self.assertEqual(preloads.read_text(), str(root / 'driver/layer/libdroiddeck_vr_scheduling.so') +
(':' + preload if preload else ''))
return result.read_text()
def test_adreno_840_start_removes_forced_sysmem(self):
self.assertEqual(self.launch('Adreno840v2', 'sysmem'), '')
self.assertEqual(self.launch('Adreno840v2'), '')
def test_preserves_other_debug_flags_and_removes_repeated_sysmem(self):
self.assertEqual(self.launch('Adreno840v2', 'sysmem,forcecb,sysmem,noubwc'), 'forcecb,noubwc')
self.assertEqual(self.launch('Adreno840v2', 'forcecb sysmem flushall'), 'forcecb,flushall')
def test_library_launch_uses_the_same_graphics_setup(self):
self.assertEqual(self.launch('Adreno840v2', 'sysmem,forcecb', action='launch'), 'forcecb')
def test_scheduling_preload_preserves_existing_preloads(self):
self.assertEqual(self.launch('Adreno840v2', 'sysmem', action='launch',
preload='/existing/preload.so'), '')
def test_other_and_unknown_gpus_keep_their_environment(self):
self.assertEqual(self.launch('Adreno740'), 'unset')
self.assertEqual(self.launch('Adreno740', 'sysmem,forcecb'), 'sysmem,forcecb')
self.assertEqual(self.launch('', 'sysmem'), 'sysmem')
if __name__ == '__main__':
unittest.main()
+215
View File
@@ -0,0 +1,215 @@
import os
import json
import shutil
import socket
import subprocess
import sys
import tempfile
import time
import unittest
from pathlib import Path
SOURCE = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-steamvr'
class SteamVrHelperTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.compiler_output = tempfile.TemporaryDirectory()
cls.addClassCleanup(cls.compiler_output.cleanup)
cls.scheduling = Path(cls.compiler_output.name) / 'libdroiddeck_vr_scheduling.so'
source = Path(__file__).resolve().parents[1] / 'vr/src/scheduling.c'
subprocess.run(['cc', '-shared', '-fPIC', '-o', str(cls.scheduling), str(source), '-ldl'], check=True)
def setUp(self):
self.temporary = tempfile.TemporaryDirectory()
self.addCleanup(self.temporary.cleanup)
self.root = Path(self.temporary.name)
self.home = self.root / 'home'
self.runtime = self.root / 'runtime'
self.commands = self.root / 'commands'
self.driver = self.root / 'driver/droiddeck/bin/linuxarm64'
self.steamvr = self.root / 'steamvr'
for directory in (self.commands, self.driver, self.steamvr / 'bin/linuxarm64'):
directory.mkdir(parents=True)
self.helper = self.root / 'droiddeck-steamvr'
self.assertIn('/run/droiddeck/droiddeck-xr-frames', SOURCE.read_text())
self.helper.write_text(SOURCE.read_text().replace('/run/droiddeck/droiddeck-xr-frames',
str(self.runtime / 'droiddeck-xr-frames')), encoding='utf-8')
self.executable(self.commands / 'pgrep', 'exit 1')
self.executable(self.commands / 'sleep', 'exit 0')
self.executable(self.commands / 'xset', 'exit 0')
self.executable(self.commands / 'setsid', 'exec "$@"')
self.executable(self.driver / 'xr-display-mode', 'echo 3360x1760@120')
self.executable(self.steamvr / 'bin/linuxarm64/vrstartup',
'echo "display=${DROIDDECK_VR_DISPLAY_MODE:-unset}"')
(self.driver / 'driver_droiddeck.so').touch()
layer = self.root / 'driver/layer'
layer.mkdir()
shutil.copyfile(self.scheduling, layer / self.scheduling.name)
self.environment = dict(os.environ)
self.environment.pop('DROIDDECK_VR_DISPLAY_MODE', None)
self.environment.pop('DROIDDECK_VR_PRESENT', None)
self.environment.pop('DROIDDECK_VR_PRODUCER_LEASE', None)
self.environment.update(HOME=str(self.home), XDG_RUNTIME_DIR=str(self.runtime),
STEAMVR=str(self.steamvr), DROIDDECK_VR_DIR=str(self.root / 'driver'),
DROIDDECK_VR_SETTINGS_HELPER=str(SOURCE.with_name('droiddeck-steamvr-settings')),
PATH=str(self.commands) + os.pathsep + os.environ['PATH'])
def executable(self, destination, body):
destination.write_text('#!/bin/sh\n' + body + '\n', encoding='utf-8')
destination.chmod(0o755)
def start(self):
result = subprocess.run(['sh', str(self.helper), 'start'], env=self.environment,
capture_output=True, text=True, timeout=5)
self.assertEqual(result.returncode, 0, result.stderr)
log = self.home / '.local/share/Steam/logs/droiddeck-vrstartup.log'
deadline = time.monotonic() + 2
while time.monotonic() < deadline:
if log.is_file() and 'display=' in log.read_text():
return log
time.sleep(0.01)
self.fail('Startup log did not arrive')
def test_fresh_runtime_mode_is_selected_and_log_survives_runtime_cleanup(self):
log = self.start()
self.assertEqual((self.runtime / 'droiddeck-steamvr').stat().st_mode & 0o777, 0o700)
self.assertEqual(log.read_text().strip(), 'display=3360x1760@120')
self.assertEqual((self.runtime / 'droiddeck-steamvr/vrstartup.log').resolve(), log)
shutil.rmtree(self.runtime)
self.assertTrue(log.is_file())
def test_explicit_display_override_is_preserved(self):
self.environment['DROIDDECK_VR_DISPLAY_MODE'] = '1920x1080@90'
self.assertEqual(self.start().read_text().strip(), 'display=1920x1080@90')
def test_stale_or_missing_tracking_keeps_the_default(self):
self.executable(self.driver / 'xr-display-mode', 'exit 1')
self.assertEqual(self.start().read_text().strip(), 'display=unset')
def test_older_runtime_without_the_reader_still_starts(self):
(self.driver / 'xr-display-mode').unlink()
self.assertEqual(self.start().read_text().strip(), 'display=unset')
def lease_log(self):
self.executable(self.steamvr / 'bin/linuxarm64/vrstartup',
'printf "display=%s present=%s lease=%s\\n" "${DROIDDECK_VR_DISPLAY_MODE:-unset}" '
'"${DROIDDECK_VR_PRESENT:-unset}" "${DROIDDECK_VR_PRODUCER_LEASE:-unset}"')
return self.start().read_text().strip()
def test_quest_receiver_uses_normal_compositor_and_excludes_unsupported_frame_backend(self):
self.runtime.mkdir()
cvp = self.steamvr / 'drivers/cv/bin/linuxarm64/libArcturusPerception.so'
cvp.parent.mkdir(parents=True)
cvp.write_bytes(b'frame-only backend')
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as receiver:
receiver.bind(str(self.runtime / 'droiddeck-xr-frames'))
self.assertIn('present=questwsi lease=unset', self.lease_log())
settings = json.loads((self.home / '.local/share/Steam/config/steamvr.vrsettings').read_text())
self.assertEqual(settings['steamvr'], {'enableLinuxVulkanAsync': True, 'motionSmoothing': False})
self.assertFalse(cvp.exists())
self.assertEqual(Path(str(cvp) + '.droiddeck-disabled').read_bytes(), b'frame-only backend')
def test_quest_settings_preserve_other_preferences_and_start_is_idempotent(self):
self.environment['DROIDDECK_VR_PRESENT'] = 'questwsi'
path = self.home / '.local/share/Steam/config/steamvr.vrsettings'
path.parent.mkdir(parents=True)
path.write_text(json.dumps({'steamvr': {'somePreference': 42}, 'dashboard': {'somePreference': True}}))
self.start()
self.start()
settings = json.loads(path.read_text())
self.assertEqual(settings['steamvr']['somePreference'], 42)
self.assertEqual(settings['dashboard'], {'somePreference': True})
def test_quest_refuses_to_overwrite_malformed_settings(self):
self.environment['DROIDDECK_VR_PRESENT'] = 'questwsi'
path = self.home / '.local/share/Steam/config/steamvr.vrsettings'
path.parent.mkdir(parents=True)
path.write_text('invalid json')
result = subprocess.run(['sh', str(self.helper), 'start'], env=self.environment,
capture_output=True, text=True, timeout=5)
self.assertNotEqual(result.returncode, 0)
self.assertEqual(path.read_text(), 'invalid json')
def test_quest_stop_restores_only_overridden_preferences(self):
self.environment['DROIDDECK_VR_PRESENT'] = 'questwsi'
path = self.home / '.local/share/Steam/config/steamvr.vrsettings'
path.parent.mkdir(parents=True)
path.write_text(json.dumps({'steamvr': {'motionSmoothing': True, 'somePreference': 42}}))
self.start()
settings = json.loads(path.read_text())
settings['dashboard'] = {'changedDuringSession': True}
path.write_text(json.dumps(settings))
subprocess.run(['sh', str(self.helper), 'stop'], env=self.environment, check=True)
self.assertEqual(json.loads(path.read_text()), {'steamvr': {'motionSmoothing': True, 'somePreference': 42},
'dashboard': {'changedDuringSession': True}})
def test_invalid_backup_preserves_preferences_until_repaired(self):
settings = self.root / 'steamvr.vrsettings'
backup = self.root / 'quest-backup.json'
helper = SOURCE.with_name('droiddeck-steamvr-settings')
original = {'steamvr': {'motionSmoothing': True}, 'dashboard': {'unchanged': 42}}
settings.write_text(json.dumps(original))
subprocess.run([sys.executable, str(helper), 'apply', str(settings), str(backup)], check=True)
valid_backup = backup.read_bytes()
applied = settings.read_bytes()
invalid = ['truncated {', '{}', '{"section": true, "values": []}',
'{"section": false, "values": {"motionSmoothing": [false]}}']
for content in invalid:
for operation in ('apply', 'restore'):
with self.subTest(content=content, operation=operation):
backup.write_text(content)
result = subprocess.run([sys.executable, str(helper), operation, str(settings), str(backup)],
capture_output=True, text=True)
self.assertNotEqual(result.returncode, 0)
self.assertIn('repair the saved section/values and retry restore', result.stderr)
self.assertEqual(backup.read_text(), content)
self.assertEqual(settings.read_bytes(), applied)
backup.write_bytes(valid_backup)
subprocess.run([sys.executable, str(helper), 'restore', str(settings), str(backup)], check=True)
self.assertEqual(json.loads(settings.read_text()), original)
self.assertFalse(backup.exists())
def test_quest_update_preserves_previous_cvp_backup(self):
self.environment['DROIDDECK_VR_PRESENT'] = 'questwsi'
cvp = self.steamvr / 'drivers/cv/bin/linuxarm64/libArcturusPerception.so'
cvp.parent.mkdir(parents=True)
cvp.write_bytes(b'updated library')
backup = Path(str(cvp) + '.droiddeck-disabled')
backup.write_bytes(b'previous library')
self.start()
self.assertFalse(cvp.exists())
self.assertEqual(backup.read_bytes(), b'previous library')
self.assertEqual([p.read_bytes() for p in cvp.parent.glob('*.droiddeck-disabled.*')], [b'updated library'])
def test_start_failure_after_overrides_restores_preferences(self):
self.environment['DROIDDECK_VR_PRESENT'] = 'questwsi'
path = self.home / '.local/share/Steam/config/steamvr.vrsettings'
path.parent.mkdir(parents=True)
original = {'steamvr': {'enableLinuxVulkanAsync': False, 'motionSmoothing': True}}
path.write_text(json.dumps(original))
cvp = self.steamvr / 'drivers/cv/bin/linuxarm64/libArcturusPerception.so'
cvp.parent.mkdir(parents=True)
cvp.touch()
self.executable(self.commands / 'mv', 'exit 1')
result = subprocess.run(['sh', str(self.helper), 'start'], env=self.environment,
capture_output=True, text=True, timeout=5)
self.assertNotEqual(result.returncode, 0)
self.assertEqual(json.loads(path.read_text()), original)
def test_explicit_quest_presenter_enables_the_lease(self):
self.environment['DROIDDECK_VR_PRESENT'] = 'questframes'
self.assertIn('present=questframes lease=1', self.lease_log())
def test_explicit_diagnostic_override_is_preserved(self):
self.environment.update(DROIDDECK_VR_PRESENT='questframes', DROIDDECK_VR_PRODUCER_LEASE='0')
self.assertIn('present=questframes lease=0', self.lease_log())
def test_flat_presenter_does_not_enable_the_producer_lease(self):
self.assertIn('present=unset lease=unset', self.lease_log())
if __name__ == '__main__':
unittest.main()
+83
View File
@@ -0,0 +1,83 @@
import json
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
HELPER = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-steamvr'
SCRIPT = HELPER.read_text().split("<<'PY'\n", 1)[1].split('\nPY\n', 1)[0]
class SteamVrSettingsTest(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.path = Path(self.temp.name) / 'steamvr.vrsettings'
def run_defaults(self):
result = subprocess.run([sys.executable, '-', str(self.path)], input=SCRIPT,
capture_output=True, text=True, timeout=10)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(list(self.path.parent.iterdir()), [self.path])
return result
def test_new_install_defaults_to_manual_100_percent(self):
self.run_defaults()
self.assertEqual(json.loads(self.path.read_text()), {
'steamvr': {'supersampleManualOverride': True, 'supersampleScale': 1.0}})
def test_existing_automatic_gpu_estimate_does_not_override_app_resolution(self):
settings = {'GpuSpeed': {'gpuSpeedRenderTargetScale': 1.1},
'steamvr': {'environmentMode': 0}, 'driver_droiddeck': {'directMode': True}}
self.path.write_text(json.dumps(settings))
self.run_defaults()
settings['steamvr'].update(supersampleManualOverride=True, supersampleScale=1.0)
self.assertEqual(json.loads(self.path.read_text()), settings)
def test_explicit_user_and_per_game_settings_are_preserved_without_rewrite(self):
for manual in (False, True):
with self.subTest(manual=manual):
settings = {'steamvr': {'supersampleManualOverride': manual, 'supersampleScale': 0.7},
'steam.app.611670': {'resolutionScale': 80}}
content = json.dumps(settings)
self.path.write_text(content)
self.run_defaults()
self.assertEqual(self.path.read_text(), content)
def test_defaults_are_idempotent(self):
self.run_defaults()
before = self.path.read_bytes()
self.run_defaults()
self.assertEqual(self.path.read_bytes(), before)
def test_partial_user_settings_are_preserved(self):
self.path.write_text('{"steamvr": {"supersampleScale": 0.5}}')
self.run_defaults()
self.assertEqual(json.loads(self.path.read_text())['steamvr'], {
'supersampleScale': 0.5, 'supersampleManualOverride': True})
def test_a_crash_block_on_the_droiddeck_driver_is_cleared_and_others_kept(self):
settings = {'steamvr': {'supersampleManualOverride': True, 'supersampleScale': 1.0},
'driver_droiddeck': {'blocked_by_safe_mode': True, 'directMode': True},
'driver_lighthouse': {'blocked_by_safe_mode': True}}
self.path.write_text(json.dumps(settings))
self.assertIn('unblocked it', self.run_defaults().stdout)
settings['driver_droiddeck']['blocked_by_safe_mode'] = False
self.assertEqual(json.loads(self.path.read_text()), settings)
def test_the_crash_marker_is_removed_so_steamvr_does_not_start_in_safe_mode(self):
(self.path.parent / 'vrserver_crash_timestamp.txt').write_text('1792116926 1789606310 223')
self.assertIn('crash marker', self.run_defaults().stdout)
def test_invalid_settings_are_reported_without_losing_the_original(self):
for content in ('{broken', '[]', '{"steamvr": null}', '{"steamvr": []}'):
with self.subTest(content=content):
self.path.write_text(content)
self.assertIn('Could not set SteamVR resolution defaults', self.run_defaults().stderr)
self.assertEqual(self.path.read_text(), content)
if __name__ == '__main__':
unittest.main()
+66
View File
@@ -0,0 +1,66 @@
#include "../../app/src/main/cpp/viture/stereo_frame_gate.h"
#include <cassert>
#include <cstdio>
#include <initializer_list>
#include <limits>
int main() {
StereoFrameGate gate;
gate.SetHalfRate(true);
int copies = 0;
for (int i = 0; i < 250; ++i) {
const bool accepted = gate.Accept(1 + i*.04);
assert(accepted == (i%2 == 0));
copies += accepted;
}
assert(copies == 125 && gate.received == 250 && gate.skipped == 125);
gate.SetHalfRate(false);
for (int i = 0; i < 25; ++i) assert(gate.Accept(20 + i*.04));
assert(gate.received == 275 && gate.skipped == 125);
gate.SetHalfRate(true);
assert(gate.Accept(30));
gate.SetHalfRate(true);
assert(!gate.Accept(30.04));
assert(gate.Accept(30.08));
assert(gate.Accept(1));
assert(!gate.Accept(1.04));
const auto count = gate.received;
assert(!gate.Accept(std::numeric_limits<double>::quiet_NaN()));
assert(!gate.Accept(0));
assert(gate.received == count);
gate = {};
gate.SetHalfRate(true);
assert(gate.Accept(1) && gate.received == 1 && gate.skipped == 0);
for (int rate : {500, 600, 800, 1000}) {
gate = {};
gate.SetRatePermille(rate);
copies = 0;
int previousCopy = 0;
for (int i = 0; i < 250; ++i) {
gate.SetRatePermille(rate);
const bool accepted = gate.Accept(1 + i*.04);
if (i == 0) assert(accepted);
if (accepted) {
assert(i-previousCopy <= 2);
previousCopy = i;
++copies;
}
}
assert(copies == 250*rate/1000);
assert(gate.received == 250 && gate.skipped == uint64_t(250-copies));
assert(gate.Accept(.5));
}
gate = {};
for (int rate : {500, 600, 800, 1000, 800, 600, 500}) {
gate.SetRatePermille(rate);
assert(gate.Accept(1 + gate.received*.04));
}
for (int invalid : {-1, 0, 499, 700, 1001}) {
gate = {};
gate.SetRatePermille(invalid);
assert(gate.Accept(1));
assert(!gate.Accept(1.04));
assert(gate.Accept(1.08));
}
puts("PASS: fractional stereo copies, stable phase, full-rate setup, source resets, invalid settings and reconnect reset");
}
+9
View File
@@ -88,6 +88,9 @@ class StoragePreloadTest(unittest.TestCase):
subprocess.run(["cc", "-O2", "-o", str(cls.steam), str(build / "program.c")], check=True)
cls.other = build / "steamwebhelper"
shutil.copy(cls.steam, cls.other)
cls.steam_x64 = cls.dir / "steamrt64/steam"
cls.steam_x64.parent.mkdir()
shutil.copy(cls.steam, cls.steam_x64)
@classmethod
def tearDownClass(cls):
@@ -117,6 +120,12 @@ class StoragePreloadTest(unittest.TestCase):
self.assertEqual(["fallocate -1 EOPNOTSUPP 0", "ftruncate 0 - 0", "ftruncate 0 - 0"], out)
self.assertEqual(["data.pak 0"], self.reached())
def test_x86_64_client_reservation_is_not_zero_filled_either(self):
data = self.staging / "data.pak"
out = self.run_program(("fallocate", data, 1 << 20), ("ftruncate", data, 1 << 20), program=self.steam_x64)
self.assertEqual(["fallocate -1 EOPNOTSUPP 0", "ftruncate 0 - 0"], out)
self.assertEqual([], self.reached())
def test_reservation_is_real_until_the_device_has_refused_one(self):
data = self.staging / "data.pak"
self.assertEqual(["ftruncate 0 - 4096"], self.run_program(("ftruncate", data, 4096)))
+1 -1
View File
@@ -241,7 +241,7 @@ class CloudHooks(unittest.TestCase):
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('droiddeck-store-launch --exited "${BL_STORE_ARGS[@]}"', 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)
+25
View File
@@ -0,0 +1,25 @@
import json
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
@unittest.skipUnless(shutil.which("g++"), "needs a Linux C++ compiler")
class XrChaperoneTest(unittest.TestCase):
def test_seated_origin_and_stage_preservation(self):
repository = Path(__file__).resolve().parents[2]
with tempfile.TemporaryDirectory() as directory:
executable = Path(directory) / "chaperone-test"
subprocess.run(["g++", "-std=c++17", "-Wall", "-Wextra", "-Werror", "-O2",
str(repository / "tools/vr/tests/test_xr_chaperone.cpp"), "-o", str(executable)], check=True)
result = json.loads(subprocess.check_output([str(executable)], text=True))
self.assertEqual((result["jsonid"], result["version"]), ("chaperone_info", 5))
self.assertEqual(result["time"], "2026-10-15T21:00:00Z")
universe, = result["universes"]
self.assertEqual(int(universe["universeID"]), 2)
self.assertEqual(universe["standing"], {"translation": [0, 0, 0], "yaw": 0})
self.assertEqual(universe["collision_bounds"], [])
self.assertEqual(universe["play_area"], [0, 0])
self.assertAlmostEqual(universe["seated"]["translation"][1], -1.6, places=6)
+45
View File
@@ -0,0 +1,45 @@
import ctypes.util
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
@unittest.skipUnless(shutil.which("gcc"), "needs gcc on a Linux host")
class VrProducerLeaseTest(unittest.TestCase):
def compile_and_run(self, source, headers=None, gpu=False):
repository = Path(__file__).resolve().parents[2]
with tempfile.TemporaryDirectory() as directory:
executable = Path(directory) / "producer-test"
command = ["gcc", "-std=c11", "-O2", "-Wall", "-Wextra", "-Werror", "-Wno-unused-parameter", "-pthread"]
if headers:
command += ["-I" + str(headers)]
command += [str(repository / "tools/vr/tests" / source), "-ldl"]
if gpu:
command += ["-l:libvulkan.so.1"]
subprocess.run(command + ["-o", str(executable)], check=True)
environment = dict(os.environ)
if gpu:
manifests = sorted(Path("/usr/share/vulkan/icd.d").glob("lvp_icd*.json"))
environment["VK_DRIVER_FILES"] = str(manifests[0])
environment["VK_ICD_FILENAMES"] = str(manifests[0])
result = subprocess.run([str(executable)], env=environment, capture_output=True, text=True, timeout=20)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
return result.stdout
def test_protocol_and_retained_ownership(self):
self.assertIn("disconnect quarantine passed", self.compile_and_run("test_producer_lease.c"))
def test_real_gpu_completion_and_frozen_overwrite(self):
if not ctypes.util.find_library("vulkan") or not list(Path("/usr/share/vulkan/icd.d").glob("lvp_icd*.json")):
self.skipTest("needs Vulkan loader and Lavapipe")
repository = Path(__file__).resolve().parents[2]
candidates = [os.environ.get("VK_INCLUDE", ""), "/usr/include", repository / "build/vr/include"]
candidates += [path for root in (os.environ.get("ANDROID_HOME"), os.environ.get("ANDROID_SDK_ROOT")) if root
for path in Path(root).glob("ndk/*/toolchains/llvm/prebuilt/*/sysroot/usr/include")]
headers = next((Path(path) for path in candidates if path and (Path(path) / "vulkan/vk_layer.h").is_file()), None)
if headers is None:
self.skipTest("needs Vulkan headers")
self.assertIn("1024 buffer values passed", self.compile_and_run("test_producer_gpu.c", headers=headers, gpu=True))
+26
View File
@@ -0,0 +1,26 @@
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
@unittest.skipUnless(shutil.which("gcc"), "needs gcc on a Linux host")
class VrSemaphoreLayerTest(unittest.TestCase):
def test_waits_are_never_fabricated(self):
repository = Path(__file__).resolve().parents[2]
candidates = [os.environ.get("VK_INCLUDE", ""), "/usr/include", repository / "build/vr/include"]
candidates += [path for root in (os.environ.get("ANDROID_HOME"), os.environ.get("ANDROID_SDK_ROOT")) if root
for path in Path(root).glob("ndk/*/toolchains/llvm/prebuilt/*/sysroot/usr/include")]
headers = next((Path(path) for path in candidates if path and (Path(path) / "vulkan/vk_layer.h").is_file()), None)
if headers is None:
self.skipTest("needs Vulkan headers")
with tempfile.TemporaryDirectory() as directory:
executable = Path(directory) / "semaphore-layer-test"
subprocess.run(["gcc", "-std=c11", "-O2", "-Wall", "-Wextra", "-Werror", "-Wno-unused-parameter",
"-pthread", "-I" + str(headers), str(repository / "tools/vr/tests/test_semaphore_layer.c"),
"-ldl", "-o", str(executable)], check=True)
result = subprocess.run([str(executable)], capture_output=True, text=True, timeout=20)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
self.assertIn("fd ownership passed", result.stdout)
+23
View File
@@ -0,0 +1,23 @@
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
@unittest.skipUnless(shutil.which('g++'), 'needs a Linux C++ compiler')
class VrWsiTest(unittest.TestCase):
def test_compositor_handoff_and_frame_transport(self):
repository = Path(__file__).resolve().parents[2]
headers = next((p for p in (Path('/usr/include'), repository / 'build/vr/include')
if (p / 'vulkan/vulkan.h').is_file()), None)
if headers is None:
self.skipTest('needs Vulkan headers')
with tempfile.TemporaryDirectory() as directory:
for name in ('test_wsi_capture', 'test_xr_shared', 'test_xr_frames', 'test_xr_gpu'):
with self.subTest(name=name):
executable = Path(directory) / name
subprocess.run(['g++', '-std=c++17', '-O2', '-pthread', '-Wall', '-Wextra', '-Werror',
'-Wno-missing-field-initializers', '-I' + str(headers),
str(repository / 'tools/vr/tests' / (name + '.cpp')), '-o', str(executable)], check=True)
subprocess.run([str(executable)], check=True, timeout=20)
+141
View File
@@ -0,0 +1,141 @@
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
SOURCE = Path(__file__).resolve().parents[1] / "linuxfs/fex/vulkanpin.c"
THUNK = r"""
#include <string.h>
typedef struct { char extensionName[256]; unsigned int specVersion; } VkExtensionProperties;
typedef void (*Function)(void);
static const char *names[] = {"VK_KHR_surface", "VK_KHR_display", "VK_KHR_xlib_surface", "VK_EXT_direct_mode_display",
"VK_KHR_get_display_properties2", "VK_EXT_swapchain_colorspace"};
int vkEnumerateInstanceExtensionProperties(const char *layer, unsigned int *count, VkExtensionProperties *properties)
{
unsigned int total = layer ? 0 : sizeof(names) / sizeof(names[0]);
if (!properties) {
*count = total;
return 0;
}
unsigned int n = *count < total ? *count : total;
for (unsigned int i = 0; i < n; i++) {
memset(&properties[i], 0, sizeof(properties[i]));
strcpy(properties[i].extensionName, names[i]);
properties[i].specVersion = i + 1;
}
*count = n;
return n < total ? 5 : 0;
}
int vkCreateInstance(void) { return 42; }
Function vkGetInstanceProcAddr(void *instance, const char *name)
{
(void)instance;
if (!strcmp(name, "vkEnumerateInstanceExtensionProperties"))
return (Function)vkEnumerateInstanceExtensionProperties;
if (!strcmp(name, "vkCreateInstance"))
return (Function)vkCreateInstance;
if (!strcmp(name, "vkGetInstanceProcAddr"))
return (Function)vkGetInstanceProcAddr;
return 0;
}
"""
GAME = r"""
#include <dlfcn.h>
#include <stdio.h>
typedef struct { char extensionName[256]; unsigned int specVersion; } VkExtensionProperties;
typedef void (*Function)(void);
typedef int (*Enumerate)(const char *, unsigned int *, VkExtensionProperties *);
typedef Function (*ProcAddr)(void *, const char *);
#ifdef LINKED
int vkCreateInstance(void);
Function vkGetInstanceProcAddr(void *, const char *);
#endif
static void list(Enumerate enumerate)
{
VkExtensionProperties found[8];
unsigned int count = 0;
int result = enumerate(0, &count, 0);
printf("count %u %d\n", count, result);
enumerate(0, &count, found);
for (unsigned int i = 0; i < count; i++)
printf("%s %u\n", found[i].extensionName, found[i].specVersion);
count = 1;
result = enumerate(0, &count, found);
printf("short %u %d %s\n", count, result, found[0].extensionName);
}
int main(void)
{
#ifdef LINKED
ProcAddr proc = vkGetInstanceProcAddr;
printf("linked %d\n", vkCreateInstance());
#else
void *vulkan = dlopen("libvulkan.so.1", RTLD_NOW | RTLD_LOCAL);
if (!vulkan)
return 1;
ProcAddr proc = (ProcAddr)dlsym(vulkan, "vkGetInstanceProcAddr");
printf("same handle %d\n", dlopen("libvulkan.so", RTLD_NOW | RTLD_NOLOAD) == vulkan);
printf("create %d\n", ((int (*)(void))dlsym(vulkan, "vkCreateInstance"))());
list((Enumerate)dlsym(vulkan, "vkEnumerateInstanceExtensionProperties"));
#endif
printf("same proc %d create %d missing %d\n", proc(0, "vkGetInstanceProcAddr") == (Function)proc,
((int (*)(void))proc(0, "vkCreateInstance"))(), proc(0, "vkNothing") == 0);
list((Enumerate)proc(0, "vkEnumerateInstanceExtensionProperties"));
return 0;
}
"""
LISTED = """count 3 0
VK_KHR_surface 1
VK_KHR_xlib_surface 3
VK_EXT_swapchain_colorspace 6
short 1 5 VK_KHR_surface
"""
@unittest.skipUnless(shutil.which("gcc") and os.uname().machine == "x86_64", "needs gcc on an x86-64 host")
class VulkanPinTest(unittest.TestCase):
def setUp(self):
self.tmp = Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, self.tmp, ignore_errors=True)
def gcc(self, *args):
made = subprocess.run(["gcc"] + [str(a) for a in args], capture_output=True, text=True)
self.assertEqual(made.returncode, 0, made.stderr)
def test_display_extensions_are_hidden_in_front_of_the_thunk(self):
thunk = self.tmp / "usr/lib/libvulkan.so.1"
thunk.parent.mkdir(parents=True)
(self.tmp / "thunk.c").write_text(THUNK)
self.gcc("-shared", "-fPIC", "-Wl,-soname,libvulkan.so.1", "-o", thunk, self.tmp / "thunk.c")
stub = self.tmp / "stub/libvulkan.so.1"
stub.parent.mkdir()
self.gcc("-shared", "-nostdlib", "-Wl,-soname," + str(thunk), "-o", stub, "-x", "c", "/dev/null")
pinned = self.tmp / "pin"
pinned.mkdir()
self.gcc("-shared", "-fPIC", "-O2", "-Wall", "-Wextra", "-Werror", "-fvisibility=hidden", '-DVULKAN_THUNK="%s"' % thunk,
"-Wl,-soname,libvulkan.so.1", "-Wl,-z,nodelete", "-Wl,--no-as-needed", "-o", pinned / "libvulkan.so.1",
SOURCE, stub, "-ldl")
os.symlink("libvulkan.so.1", pinned / "libvulkan.so")
exported = subprocess.run(["nm", "-D", "--defined-only", pinned / "libvulkan.so.1"], capture_output=True, text=True)
self.assertEqual(sorted(line.split()[-1] for line in exported.stdout.splitlines()),
["vkEnumerateInstanceExtensionProperties", "vkGetInstanceProcAddr"])
(self.tmp / "game.c").write_text(GAME)
env = dict(os.environ, LD_LIBRARY_PATH=str(pinned))
self.gcc("-o", self.tmp / "loader", self.tmp / "game.c", "-ldl")
run = subprocess.run([self.tmp / "loader"], capture_output=True, text=True, env=env)
self.assertEqual(run.returncode, 0, run.stderr)
self.assertEqual(run.stdout, "same handle 1\ncreate 42\n" + LISTED + "same proc 1 create 42 missing 1\n" + LISTED)
self.gcc("-DLINKED", "-o", self.tmp / "linked", self.tmp / "game.c", "-L", thunk.parent, "-l:libvulkan.so.1", "-ldl")
run = subprocess.run([self.tmp / "linked"], capture_output=True, text=True, env=env)
self.assertEqual(run.returncode, 0, run.stderr)
self.assertEqual(run.stdout, "linked 42\nsame proc 1 create 42 missing 1\n" + LISTED)
if __name__ == "__main__":
unittest.main()
+127
View File
@@ -0,0 +1,127 @@
import importlib.util
import json
from pathlib import Path
import struct
import tempfile
import unittest
from unittest import mock
spec = importlib.util.spec_from_file_location(
'windows_vr_build', Path(__file__).resolve().parents[1] / 'vr/build_windows.py')
vr = importlib.util.module_from_spec(spec)
spec.loader.exec_module(vr)
class WindowsVrBuildTest(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.out = self.root / 'build/vr'
self.include = self.root / 'ndk/include'
for name in vr.SOURCE_FILES:
self.write(self.root / name, b'build source\n')
for tree in vr.SOURCE_TREES:
self.write(self.root / tree / 'input.h', b'header\n')
for name, source in vr.CONFIGS.items():
self.write(self.root / source, b'{"name": "current"}\n')
self.write(self.out / name, b'{"name": "current"}\n')
for name in vr.LIBRARIES | vr.EXECUTABLES:
data = bytearray(64)
data[:6] = b'\x7fELF\x02\x01'
struct.pack_into('<HH', data, 16, 3, 183)
self.write(self.out / name, data)
for name in vr.HAND_MODELS:
self.write(self.out / name, b'generated hand model\n')
for name in ('vulkan/vulkan_core.h', 'vulkan/vk_layer.h'):
self.write(self.include / name, b'vulkan header\n')
self.commit = mock.patch.object(vr, 'commit', return_value='current-revision')
self.commit.start()
self.addCleanup(self.commit.stop)
self.record()
@staticmethod
def write(path, data):
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(data)
def record(self):
self.manifest = {'version': 1, 'source_commit': 'current-revision',
'sources': vr.hashes(vr.sources(self.root)),
'headers': vr.hashes(vr.headers(self.include)),
'outputs': {n: vr.sha((self.out / n).read_bytes()) for n in vr.OUTPUTS}}
self.save_manifest()
def save_manifest(self):
(self.out / vr.MANIFEST).write_text(json.dumps(self.manifest))
def validate(self):
return vr.validate(self.out, self.include, self.root)
def test_complete_current_build_accepts_windows_line_endings(self):
self.write(self.root / 'tools/vr/src/input.h', b'header\r\n')
files, manifest = self.validate()
self.assertEqual(set(files), vr.OUTPUTS)
self.assertEqual(manifest['source_commit'], 'current-revision')
def test_missing_manifest_cannot_import_old_unattested_binaries(self):
(self.out / vr.MANIFEST).unlink()
with self.assertRaisesRegex(ValueError, 'Missing or invalid VR build manifest'):
self.validate()
def test_modified_or_new_source_rejects_cached_build(self):
for name in ('tools/vr/src/input.h', 'tools/vr/src/new.h'):
with self.subTest(name=name):
path = self.root / name
previous = path.read_bytes() if path.exists() else None
self.write(path, b'changed\n')
with self.assertRaisesRegex(ValueError, 'VR build is stale'):
self.validate()
if previous is None:
path.unlink()
else:
path.write_bytes(previous)
def test_changed_revision_or_vulkan_headers_reject_cached_build(self):
with mock.patch.object(vr, 'commit', return_value='new-revision'):
with self.assertRaisesRegex(ValueError, 'VR build is stale'):
self.validate()
self.write(self.include / 'vulkan/vulkan_core.h', b'new header\n')
with self.assertRaisesRegex(ValueError, 'VR build is stale'):
self.validate()
def test_changed_binary_rejects_cached_build(self):
path = self.out / sorted(vr.LIBRARIES)[0]
path.write_bytes(path.read_bytes() + b'changed')
with self.assertRaisesRegex(ValueError, 'output checksum mismatch'):
self.validate()
def test_wrong_architecture_rejected_even_with_matching_checksum(self):
path = self.out / sorted(vr.LIBRARIES)[0]
data = bytearray(path.read_bytes())
struct.pack_into('<H', data, 18, 62)
path.write_bytes(data)
self.record()
with self.assertRaisesRegex(ValueError, 'not an ARM64 ELF shared library'):
self.validate()
def test_missing_or_unexpected_outputs_reject_build(self):
path = self.out / sorted(vr.LIBRARIES)[0]
data = path.read_bytes()
path.unlink()
with self.assertRaisesRegex(ValueError, 'missing or unexpected'):
self.validate()
path.write_bytes(data)
self.write(self.out / 'old-library.so', data)
with self.assertRaisesRegex(ValueError, 'missing or unexpected'):
self.validate()
def test_old_configuration_rejected_even_with_matching_checksum(self):
self.write(self.out / sorted(vr.CONFIGS)[0], b'{"name": "old"}')
self.record()
with self.assertRaisesRegex(ValueError, 'configuration differs'):
self.validate()
if __name__ == '__main__':
unittest.main()
+101
View File
@@ -0,0 +1,101 @@
from pathlib import Path
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
# Stands in for libfakeinput.so, which ld.so.preload lists after libblsession.so.
SHIM = r"""
#include <linux/input.h>
#include <stdarg.h>
#include <stdio.h>
int ioctl(int fd, unsigned long request, ...) {
va_list ap;
va_start(ap, request);
struct ff_effect *effect = va_arg(ap, struct ff_effect *);
va_end(ap);
if (request == EVIOCSFF) printf("shim type %u length %u\n", effect->type, effect->replay.length);
return 0;
}
"""
UPLOAD = r"""
#include <linux/input.h>
#include <stdio.h>
#include <string.h>
#include <sys/ioctl.h>
void upload(unsigned short type, unsigned short length) {
struct ff_effect effect;
memset(&effect, 0, sizeof(effect));
effect.id = -1;
effect.type = type;
effect.replay.length = length;
ioctl(3, EVIOCSFF, &effect);
printf("caller length %u\n", effect.replay.length);
}
"""
PROGRAM = r"""
#include <dlfcn.h>
#include <linux/input.h>
#include <stdio.h>
void upload(unsigned short type, unsigned short length);
int main(int argc, char **argv) {
void *winebus = dlopen(argv[1], RTLD_NOW);
void (*from_winebus)(unsigned short, unsigned short) = (void (*)(unsigned short, unsigned short))dlsym(winebus, "upload");
if (argv[2][0] == 'w') from_winebus(argv[3][0] == 'r' ? FF_RUMBLE : FF_PERIODIC, 1000);
else upload(FF_RUMBLE, 1000);
fflush(stdout);
return 0;
}
"""
@unittest.skipUnless(sys.platform == "linux" and shutil.which("cc"), "needs Linux and cc")
class WinebusRumblePreloadTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.dir = Path(tempfile.mkdtemp())
build = cls.dir / "build"
build.mkdir()
for name, text in (("shim.c", SHIM), ("upload.c", UPLOAD), ("program.c", PROGRAM)):
(build / name).write_text(text)
cls.lib = cls.dir / "libblsession.so"
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-Wall", "-pthread", "-o", str(cls.lib),
*map(str, sorted(PRELOAD.glob("*.c"))), "-ldl"], check=True)
cls.shim = cls.dir / "libshim.so"
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-o", str(cls.shim), str(build / "shim.c")], check=True)
cls.winebus = cls.dir / "winebus.so"
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-o", str(cls.winebus), str(build / "upload.c")], check=True)
cls.program = cls.dir / "program"
subprocess.run(["cc", "-O2", "-o", str(cls.program), str(build / "program.c"), str(build / "upload.c"), "-ldl"],
check=True)
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.dir, True)
def upload(self, caller, kind="rumble"):
env = dict(os.environ, LD_PRELOAD="%s:%s" % (self.lib, self.shim))
result = subprocess.run([str(self.program), str(self.winebus), caller, kind], env=env,
capture_output=True, text=True, timeout=10, check=True)
return result.stdout.splitlines()
def test_winebus_rumble_reaches_the_shim_held_and_comes_back_unchanged(self):
self.assertEqual(self.upload("winebus"), ["shim type %d length 0" % 0x50, "caller length 1000"])
def test_other_callers_and_effects_keep_their_length(self):
self.assertEqual(self.upload("program"), ["shim type %d length 1000" % 0x50, "caller length 1000"])
self.assertEqual(self.upload("winebus", "periodic"), ["shim type %d length 1000" % 0x51, "caller length 1000"])
if __name__ == "__main__":
unittest.main()