Merge current main into PR #1317

This commit is contained in:
Kurt Himebauch committed 2026-10-22 12:13:54 -04:00
commit e8a8de1b22
161 files changed
+7157 -479

No files matched your search

+164
View File
@@ -0,0 +1,164 @@
import hashlib
import importlib.util
import json
from pathlib import Path
import struct
import stat
import tempfile
import unittest
from unittest import mock
import zipfile
spec = importlib.util.spec_from_file_location(
'prepare_a850_driver_bundle', Path(__file__).resolve().parents[1] / 'prepare_a850_driver_bundle.py')
prepare = importlib.util.module_from_spec(spec)
spec.loader.exec_module(prepare)
class A850BundleTest(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.android = self.root / 'android.zip'
self.linux = self.root / 'linux.zip'
self.output = self.root / 'bundle.zip'
self.android_files = self.files('android')
self.linux_files = self.files('linux')
self.write(self.android, self.android_files)
self.write(self.linux, self.linux_files)
def files(self, platform):
elf = bytearray(64)
elf[:6] = b'\x7fELF\x02\x01'
struct.pack_into('<H', elf, 18, 183)
elf += b'libc.so.6\x00' if platform == 'linux' else b'libc.so\x00'
meta = ({'libc': 'glibc', 'kind': 'linux-vulkan-icd'} if platform == 'linux'
else {'libraryName': prepare.LIBRARY})
files = {'meta.json': json.dumps(meta).encode(), prepare.LIBRARY: bytes(elf)}
if platform == 'linux':
files['freedreno_icd.aarch64.json'] = json.dumps({'ICD': {'library_path': './' + prepare.LIBRARY}}).encode()
return files
def write(self, path, files):
with zipfile.ZipFile(path, 'w') as archive:
for name, data in files.items():
archive.writestr(name, data)
def pinned_fixture(self):
return mock.patch.multiple(prepare,
ANDROID_SHA256=hashlib.sha256(self.android.read_bytes()).hexdigest(),
LINUX_SHA256=hashlib.sha256(self.linux.read_bytes()).hexdigest())
def test_manifest_roundtrip_preserves_both_original_halves_and_is_deterministic(self):
with self.pinned_fixture():
prepare.prepare_bundle(self.android, self.linux, self.output)
first = self.output.read_bytes()
prepare.prepare_bundle(self.android, self.linux, self.output)
self.assertEqual(first, self.output.read_bytes())
with zipfile.ZipFile(self.output) as archive:
manifest = json.loads(archive.read('manifest.json'))
self.assertEqual('Adreno 850 community experimental', manifest['package'])
self.assertEqual('20261012-a850exp1', manifest['version'])
self.assertEqual(manifest['version'], manifest['tag'])
for platform, originals in (('android', self.android_files), ('linux', self.linux_files)):
directory = manifest['drivers'][platform]['path']
self.assertEqual(platform, directory)
for name, data in originals.items():
self.assertEqual(data, archive.read(directory + '/' + name))
self.assertIn(b'not native Adreno 850 support', archive.read('README.md'))
self.assertIn(b'issues/342', archive.read('NOTICE'))
def test_hash_mismatch_refuses_and_preserves_old_output(self):
self.output.write_bytes(b'previous bundle')
with self.assertRaisesRegex(ValueError, 'SHA256 mismatch'):
prepare.prepare_bundle(self.android, self.linux, self.output)
self.assertEqual(b'previous bundle', self.output.read_bytes())
def test_unsafe_extra_and_missing_entries_refused_before_output_write(self):
for entry in ('../escape', '/absolute', 'sub/../meta.json', 'sub\\meta.json', 'extra.so', None):
with self.subTest(entry=entry):
files = self.android_files.copy()
if entry is None:
files.pop(prepare.LIBRARY)
else:
files[entry] = b'unexpected'
self.write(self.android, files)
self.output.write_bytes(b'old')
with self.pinned_fixture(), self.assertRaisesRegex(ValueError, 'unsafe, extra or missing'):
prepare.prepare_bundle(self.android, self.linux, self.output)
self.assertEqual(b'old', self.output.read_bytes())
def test_bad_linux_half_does_not_replace_output(self):
self.linux_files['meta.json'] = b'{"libc":"bionic","kind":"linux-vulkan-icd"}'
self.write(self.linux, self.linux_files)
self.output.write_bytes(b'old')
with self.pinned_fixture(), self.assertRaisesRegex(ValueError, 'libc/kind'):
prepare.prepare_bundle(self.android, self.linux, self.output)
self.assertEqual(b'old', self.output.read_bytes())
def test_bad_android_library_name_refused(self):
self.android_files['meta.json'] = b'{"libraryName":"../evil.so"}'
self.write(self.android, self.android_files)
with self.pinned_fixture(), self.assertRaisesRegex(ValueError, 'libraryName'):
prepare.prepare_bundle(self.android, self.linux, self.output)
def test_wrong_elf_class_endian_architecture_and_libc_refused(self):
original = self.linux_files[prepare.LIBRARY]
for offset, replacement in ((4, 1), (5, 2), (18, 62)):
elf = bytearray(original)
elf[offset] = replacement
with self.subTest(offset=offset), self.assertRaisesRegex(ValueError, 'ELF64'):
prepare.validate_elf(elf, 'linux')
with self.assertRaisesRegex(ValueError, 'glibc'):
prepare.validate_elf(self.android_files[prepare.LIBRARY], 'linux')
with self.assertRaisesRegex(ValueError, 'AdrenoTools'):
prepare.validate_elf(original, 'android')
def test_output_cannot_overwrite_either_input_or_alias(self):
for source in (self.android, self.linux):
with self.subTest(source=source), self.assertRaisesRegex(ValueError, 'differ'):
prepare.prepare_bundle(self.android, self.linux, source)
alias = self.root / 'alias.zip'
alias.symlink_to(self.android)
with self.assertRaisesRegex(ValueError, 'differ'):
prepare.prepare_bundle(self.android, self.linux, alias)
def test_duplicate_and_symlink_entries_refused(self):
for duplicate in (True, False):
with self.subTest(duplicate=duplicate):
with zipfile.ZipFile(self.android, 'w') as archive:
for name, data in self.android_files.items():
info = zipfile.ZipInfo(name)
if not duplicate and name == prepare.LIBRARY:
info.create_system = 3
info.external_attr = (stat.S_IFLNK | 0o777) << 16
archive.writestr(info, data)
if duplicate:
import warnings
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
archive.writestr('meta.json', b'{}')
with self.pinned_fixture(), self.assertRaises(ValueError):
prepare.prepare_bundle(self.android, self.linux, self.output)
self.assertFalse(self.output.exists())
def test_malformed_icd_refused(self):
for icd in ({'ICD': []}, {'ICD': {'library_path': '../evil.so'}}):
with self.subTest(icd=icd):
self.linux_files['freedreno_icd.aarch64.json'] = json.dumps(icd).encode()
self.write(self.linux, self.linux_files)
with self.pinned_fixture(), self.assertRaisesRegex(ValueError, 'ICD library_path'):
prepare.prepare_bundle(self.android, self.linux, self.output)
def test_failed_replace_cleans_temporary_and_preserves_previous_output(self):
self.output.write_bytes(b'old')
with self.pinned_fixture(), mock.patch.object(prepare.os, 'replace', side_effect=OSError('fixture failure')):
with self.assertRaisesRegex(OSError, 'fixture failure'):
prepare.prepare_bundle(self.android, self.linux, self.output)
self.assertEqual(b'old', self.output.read_bytes())
self.assertEqual([], list(self.root.glob('.bundle.zip.*')))
if __name__ == '__main__':
unittest.main()
+83
View File
@@ -0,0 +1,83 @@
import importlib.util
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
path = Path(__file__).resolve().parents[1] / "release/check_authorship.py"
spec = importlib.util.spec_from_file_location("check_authorship", path)
check = importlib.util.module_from_spec(spec)
spec.loader.exec_module(check)
class AuthorshipTest(unittest.TestCase):
def commit(self, author="Human Contributor <human@example.com>", message="Fix a bug\n"):
return (f"tree {'0' * 40}\nauthor {author} 1 +0000\n"
"committer GitHub <noreply@github.com> 1 +0000\n\n" + message).encode()
def test_bot_primary_author_is_rejected_without_a_trailer(self):
for author in ("OpenAI Codex <codex@openai.com>", "Claude <noreply@anthropic.com>",
"github-actions[bot] <actions@example.com>"):
with self.subTest(author=author):
self.assertTrue(check.commit_violations("abc", self.commit(author=author)))
def test_bot_trailers_are_rejected_even_after_human_trailers(self):
message = "Fix\n\nCo-authored-by: Resul Övür <human@example.com>\nco-AUTHORED-by: OpenAI Codex <codex@openai.com>\n"
self.assertEqual(1, len(check.commit_violations("abc", self.commit(message=message))))
def test_human_authors_and_human_coauthors_are_preserved(self):
message = "Fix the Codex configuration\n\nCo-authored-by: Resul Övür <human@example.com>\n"
self.assertEqual([], check.commit_violations("abc", self.commit(message=message)))
def test_record_separator_in_message_does_not_hide_a_bot_trailer(self):
self.assertTrue(check.commit_violations("abc", self.commit(message="Fix\x1e\nCo-authored-by: Claude <noreply@anthropic.com>\n")))
def test_pr_metadata_cannot_add_a_bot_to_the_squash_message(self):
for field in ("title", "body"):
self.assertTrue(check.event_violations({"pull_request": {field: "Co-authored-by: Copilot <bot@example.com>"}}))
def test_bot_pr_author_is_rejected(self):
self.assertTrue(check.event_violations({"pull_request": {"user": {"login": "service", "type": "Bot"}}}))
def test_missing_author_fails_closed(self):
self.assertTrue(check.commit_violations("abc", b"tree 000\n\nmessage\n"))
class InstalledHooksTest(unittest.TestCase):
def setUp(self):
self.directory = tempfile.TemporaryDirectory()
self.repo = Path(self.directory.name)
self.git("init", "-q")
self.git("config", "user.name", "Human Contributor")
self.git("config", "user.email", "human@example.com")
installer = path.with_name("install_authorship_hooks.py")
subprocess.run([sys.executable, str(installer)], cwd=self.repo, check=True, capture_output=True)
(self.repo / "file").write_text("content")
self.git("add", "file")
def tearDown(self):
self.directory.cleanup()
def git(self, *args):
return subprocess.run(["git", *args], cwd=self.repo, text=True, capture_output=True)
def test_explicit_bot_author_override_is_blocked(self):
result = self.git("commit", "--author=OpenAI Codex <codex@openai.com>", "-m", "Fix")
self.assertNotEqual(0, result.returncode, result.stdout + result.stderr)
self.assertIn("Bot commit author is forbidden", result.stderr)
def test_no_verify_does_not_skip_automatic_trailer_scrubbing(self):
result = self.git("commit", "--no-verify", "-m", "Fix\n\nCo-authored-by: Another Human <other@example.com>\nCo-authored-by: Claude <noreply@anthropic.com>")
self.assertEqual(0, result.returncode, result.stdout + result.stderr)
message = self.git("log", "-1", "--format=%B").stdout
self.assertNotIn("noreply@anthropic.com", message)
self.assertIn("Co-authored-by: Another Human <other@example.com>", message)
def test_human_commit_and_human_coauthor_are_allowed(self):
result = self.git("commit", "-m", "Fix\n\nCo-authored-by: Another Human <other@example.com>")
self.assertEqual(0, result.returncode, result.stdout + result.stderr)
if __name__ == "__main__":
unittest.main()
+123
View File
@@ -0,0 +1,123 @@
import json
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
SCRIPT = Path(__file__).resolve().parents[1] / "device-smoke.sh"
FAKE_ADB = r'''#!/usr/bin/env python3
import json, os, shlex, sys
from pathlib import Path
p = Path(os.environ["SMOKE_STATE"])
s = json.loads(p.read_text())
a = sys.argv[1:]
if a == ["get-state"]:
print("device")
elif a[:1] == ["shell"]:
a = shlex.split(a[1])
if a[:1] == ["wm"]:
kind = a[1]
if len(a) == 2:
if s.get("unreadable") == kind:
print("permission denied")
else:
print("Physical " + kind + ": " + ("400" if kind == "density" else "1080x1920"))
if s.get(kind): print("Override " + kind + ": " + s[kind])
else:
value = a[2]
s["writes"].append([kind, value])
restoring = value in ("reset", "420", "1000x1800")
if not (s.get("ignored") == kind or restoring and s.get("restore_ignored") == kind):
s[kind] = "" if value == "reset" else value
p.write_text(json.dumps(s))
elif a[:1] == ["getconf"]: print("4096")
elif a[:1] == ["pidof"]: print("123")
elif a[:2] == ["dumpsys", "activity"]:
print("topResumedActivity=ActivityRecord{abc u0 com.droiddeck.launcher/.MainActivity t1}")
elif a[:3] == ["pm", "list", "packages"]:
if s.get("query_failed"): sys.exit(1)
print("package:" + s.get("package", "com.droiddeck.launcher"))
elif a[:2] == ["am", "start"] and s.get("launch_failed"):
print("Error: activity could not be started")
sys.exit(1 if s["launch_failed"] == "exit" else 0)
elif a[:1] == ["run-as"]:
if s.get("session"):
s.setdefault("log_commands", []).append(a)
p.write_text(json.dumps(s))
if "ls" in a: print(s["session"])
else: print("package not debuggable")
'''
class DeviceSmokeTest(unittest.TestCase):
def run_smoke(self, **scenario):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
adb = root / "adb"
adb.write_text(FAKE_ADB)
adb.chmod(0o755)
sleep = root / "sleep"
sleep.write_text("#!/bin/sh\nexit 0\n")
sleep.chmod(0o755)
state = root / "state.json"
state.write_text(json.dumps({"density": "", "size": "", "writes": [], **scenario}))
env = dict(os.environ, ADB=str(adb), SMOKE_STATE=str(state), PATH=str(root) + os.pathsep + os.environ["PATH"])
result = subprocess.run(["bash", str(SCRIPT), "--no-fold"], env=env, capture_output=True, text=True, timeout=30)
return result, json.loads(state.read_text())
def test_restores_preexisting_display_overrides(self):
result, state = self.run_smoke(density="420", size="1000x1800")
self.assertEqual(0, result.returncode, result.stdout + result.stderr)
self.assertEqual("420", state["density"])
self.assertEqual("1000x1800", state["size"])
def test_ignored_display_changes_do_not_pass(self):
for kind in ("density", "size"):
with self.subTest(kind=kind):
result, state = self.run_smoke(ignored=kind)
self.assertEqual(1, result.returncode, result.stdout)
self.assertIn("wm " + kind + " failed", result.stdout)
self.assertNotIn("PASS same process " + ("after" if kind == "density" else "at"), result.stdout)
self.assertEqual("", state[kind])
def test_ignored_restore_remains_a_failure_and_is_retried_on_exit(self):
for kind in ("density", "size"):
with self.subTest(kind=kind):
result, state = self.run_smoke(restore_ignored=kind)
self.assertEqual(1, result.returncode, result.stdout)
self.assertIn("could not restore", result.stdout)
self.assertNotEqual("", state[kind])
self.assertEqual(2, state["writes"].count([kind, "reset"]))
def test_unreadable_original_settings_are_not_changed(self):
for kind in ("density", "size"):
with self.subTest(kind=kind):
result, state = self.run_smoke(unreadable=kind)
self.assertEqual(0, result.returncode, result.stdout)
self.assertFalse(any(item[0] == kind for item in state["writes"]))
def test_package_filter_does_not_accept_another_variant_or_a_failed_query(self):
for scenario in ({"package": "com.droiddeck.launcher.debug"}, {"query_failed": True}):
with self.subTest(scenario=scenario):
result, state = self.run_smoke(**scenario)
self.assertEqual(2, result.returncode, result.stdout)
self.assertEqual([], state["writes"])
def test_failed_launch_is_not_masked_by_an_existing_process(self):
for failure in ("exit", "message"):
with self.subTest(failure=failure):
result, _ = self.run_smoke(launch_failed=failure)
self.assertEqual(1, result.returncode, result.stdout)
self.assertIn("could not launch", result.stdout)
def test_session_name_remains_one_remote_argument(self):
session = "x';id;#"
result, state = self.run_smoke(session=session)
self.assertEqual(0, result.returncode, result.stdout + result.stderr)
self.assertIn(["run-as", "com.droiddeck.launcher", "cat", "files/logs/" + session + "/events.jsonl"], state["log_commands"])
if __name__ == "__main__":
unittest.main()
+17
View File
@@ -6,6 +6,7 @@ import os
import runpy
import shutil
import struct
import subprocess
import tempfile
import unittest
from pathlib import Path
@@ -866,6 +867,22 @@ class AppInfoTest(unittest.TestCase):
self.assertIn('"from_oslist" "linux"', vdf)
self.assertIn('"to_oslist" "linux"', vdf)
def test_the_tool_runs_games_on_the_chosen_cores(self):
with tempfile.TemporaryDirectory() as tmp:
tool, bin_dir = Path(tmp) / "droiddeck-fex", Path(tmp) / "bin"
self.COMPAT["build_fex_tool"](str(tool))
bin_dir.mkdir()
(bin_dir / "taskset").write_text('#!/bin/sh\necho "taskset $*"\n')
(bin_dir / "taskset").chmod(0o755)
env = dict(os.environ, PATH="%s:%s" % (bin_dir, os.environ.get("PATH", "")), BL_GAME_CPUS="2-7")
run = subprocess.run([str(tool / "droiddeck-fex-tool"), "waitforexitandrun", "/games/a/game"],
env=env, capture_output=True, text=True, timeout=10)
self.assertEqual(run.stdout,
"taskset -c 2-7 /usr/local/bin/droiddeck-fex steam waitforexitandrun /games/a/game\n")
self.assertIn("game cores 2-7", run.stderr)
self.assertIn('exec /usr/local/bin/droiddeck-steamvr-game ${BL_TASKSET:-} '
'/usr/local/bin/droiddeck-fex steam "$verb" "$@"', self.COMPAT["FEX_LAUNCHER_SH"])
if __name__ == "__main__":
unittest.main()
+144
View File
@@ -0,0 +1,144 @@
#!/usr/bin/env python3
"""Live regression probe; run inside a running Gamescope session.
Requires Python 3, WAYLAND_DISPLAY, XDG_RUNTIME_DIR and access to Gamescope's
/proc/<pid>/fd. Creates only a temporary surface with the cursor role; it does
not take pointer focus or change game/save files. Affected Gamescope retains all
20 SHM allocations; fixed Gamescope retains at most the current cursor buffer.
"""
import os
import socket
import struct
import time
import json
import array
import argparse
from pathlib import Path
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--unassigned-control', action='store_true', help='verify that window buffers awaiting association remain queued')
args = parser.parse_args()
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.settimeout(2)
s.connect(os.path.join(os.environ['XDG_RUNTIME_DIR'], os.environ['WAYLAND_DISPLAY']))
U = lambda *v: struct.pack('<' + 'I' * len(v), *v)
def string(v):
b = v.encode() + b'\x00'
return U(len(b)) + b + b'\x00' * (-len(b) % 4)
def send(obj, op, p=b'', fd=None):
b = U(obj, len(p) + 8 << 16 | op) + p
if fd is None:
s.sendall(b)
else:
s.sendmsg([b], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, array.array('i', [fd]))])
nextid = 2
pids = []
for process in Path('/proc').iterdir():
if not process.name.isdigit():
continue
try:
if (process / 'comm').read_text().strip() == 'gamescope':
pids.append(process)
except (FileNotFoundError, PermissionError):
pass
assert len(pids) == 1, f'expected one Gamescope process, found {[p.name for p in pids]}'
fd_dir = pids[0] / 'fd'
def alloc():
nonlocal nextid
nextid += 1
return nextid
pending = b''
globals = {}
def roundtrip():
nonlocal pending
cb = alloc()
send(1, 0, U(cb))
while True:
while len(pending) >= 8:
obj, h = struct.unpack_from('<II', pending)
n = h >> 16
op = h & 65535
if len(pending) < n:
break
p = pending[8:n]
pending = pending[n:]
if obj == 1 and op == 0:
raise RuntimeError('wayland error ' + repr(p))
if obj == 2 and op == 0:
name, l = struct.unpack_from('<II', p)
itf = p[8:8 + l - 1].decode()
ver = struct.unpack_from('<I', p, 8 + (l + 3) // 4 * 4)[0]
globals[itf] = (name, ver)
if obj == cb:
return
chunk = s.recv(65536)
if not chunk:
raise RuntimeError('Wayland connection closed during roundtrip')
pending += chunk
def bind(itf, version):
obj = alloc()
name, ver = globals[itf]
send(2, 0, U(name) + string(itf) + U(min(ver, version), obj))
return obj
def count():
n = 0
for f in fd_dir.iterdir():
try:
n += 'dd-shm-probe' in os.readlink(f)
except FileNotFoundError:
pass
return n
send(1, 1, U(2))
roundtrip()
comp = bind('wl_compositor', 4)
shm = bind('wl_shm', 1)
seat = bind('wl_seat', 1)
pointer = alloc()
send(seat, 0, U(pointer))
surface = alloc()
send(comp, 0, U(surface))
if not args.unassigned_control:
# wlroots 0.20.2 assigns the cursor role before forwarding this serial
# to Gamescope, so zero avoids needing pointer focus but still tests the
# role guard in xwayland_surface_commit.
send(pointer, 0, U(0, surface, 0, 0))
roundtrip()
before = count()
for i in range(20):
fd = os.memfd_create('dd-shm-probe', os.MFD_CLOEXEC)
os.ftruncate(fd, 64 * 64 * 4)
pool = alloc()
send(shm, 0, U(pool, 64 * 64 * 4), fd)
os.close(fd)
buffer = alloc()
send(pool, 0, U(buffer, 0, 64, 64, 64 * 4, 0))
send(pool, 1)
send(surface, 1, U(buffer, 0, 0))
send(surface, 2, U(0, 0, 64, 64))
send(surface, 6)
send(buffer, 0)
roundtrip()
after_commits = count()
send(surface, 0)
roundtrip()
time.sleep(0.2)
after_surface_destroy = count()
s.close()
print(json.dumps(dict(before=before, after_commits=after_commits, after_surface_destroy=after_surface_destroy, growth=after_commits - before)))
if args.unassigned_control:
assert after_commits - before == 20, 'unassigned window commits were unexpectedly discarded'
else:
assert after_commits - before <= 1, f'cursor buffers leaked: {after_commits - before} retained after 20 commits'
assert after_surface_destroy == before, 'cursor buffers remain after destroying the test surface'
if __name__ == "__main__":
main()
+135 -1
View File
@@ -53,6 +53,8 @@ class SeedRedistsTest(unittest.TestCase):
self.reg = self.steam / "steamapps/compatdata/1234/pfx/system.reg"
self.reg.parent.mkdir(parents=True)
self.reg.write_text("WINE REGISTRY Version 2\n")
self.user = self.reg.with_name("user.reg")
self.user.write_text('WINE REGISTRY Version 2\n\n[Software\\\\Unrelated] 1\n"Keep"="untouched"\n')
def game(self, name="Some Game", script=GAME_SCRIPT, library=None):
root = Path(library or self.steam)
@@ -81,6 +83,93 @@ class SeedRedistsTest(unittest.TestCase):
self.run_seed(str(sd))
self.assertIn('"VCRedist2022"=dword:00000001', self.reg.read_text())
def test_current_user_and_machine_markers_go_to_their_own_registries(self):
self.game(script=GAME_SCRIPT + GAME_SCRIPT.replace("HKEY_LOCAL_MACHINE", "HKEY_CURRENT_USER").replace("VCRedist2022", "UserRedist"))
with self.reg.open("a") as out:
out.write('\n[Software\\\\Unrelated] 1\n"Keep"="machine"\n')
for reg in (self.reg, self.user):
os.utime(reg, ns=(1_000_000_000_123456789, 1_000_000_000_123456789))
self.run_seed()
system, user = self.reg.read_text(), self.user.read_text()
self.assertEqual(system.count('"VCRedist2022"=dword:00000001'), 2)
self.assertNotIn("UserRedist", system)
self.assertEqual(user.count('"UserRedist"=dword:00000001'), 1)
self.assertNotIn("Wow6432Node", user)
self.assertNotIn("VCRedist2022", user)
self.assertIn('"Keep"="machine"', system)
self.assertIn('"Keep"="untouched"', user)
self.run_seed()
self.assertEqual(system, self.reg.read_text())
self.assertEqual(user, self.user.read_text())
for reg in (self.reg, self.user):
self.assertEqual(reg.stat().st_mtime_ns, 1_000_000_000_123456789)
def test_a_user_marker_with_the_same_machine_path_and_value_is_separate(self):
self.game(script=GAME_SCRIPT + GAME_SCRIPT.replace("HKEY_LOCAL_MACHINE", "HKEY_CURRENT_USER"))
self.run_seed()
system = self.reg.read_text()
self.assertEqual(self.user.read_text().count('"VCRedist2022"=dword:00000001'), 1)
self.user.write_text("WINE REGISTRY Version 2\n")
self.run_seed()
self.assertEqual(self.user.read_text().count('"VCRedist2022"=dword:00000001'), 1)
self.assertEqual(system, self.reg.read_text())
def test_a_legacy_user_ledger_entry_is_checked_in_user_reg(self):
self.game(script=GAME_SCRIPT.replace("HKEY_LOCAL_MACHINE", "HKEY_CURRENT_USER"))
self.run_seed()
system = self.reg.read_bytes()
self.user.write_text("WINE REGISTRY Version 2\n")
(self.reg.parent / ".droiddeck-redists-checked").write_text(subprocess.check_output(["stat", "-c", "%i %s %.9Y", str(self.reg)], text=True))
self.run_seed()
self.assertEqual(self.user.read_text().count('"VCRedist2022"=dword:00000001'), 1)
self.assertEqual(system, self.reg.read_bytes())
def test_an_absent_user_registry_is_not_created_or_claimed(self):
self.game(script=GAME_SCRIPT + GAME_SCRIPT.replace("HKEY_LOCAL_MACHINE", "HKEY_CURRENT_USER").replace("VCRedist2022", "UserRedist"))
self.user.unlink()
self.run_seed()
self.assertFalse(self.user.exists())
self.assertNotIn("UserRedist", (self.reg.parent / ".droiddeck-redists").read_text())
self.assertEqual(self.reg.read_text().count('"VCRedist2022"=dword:00000001'), 2)
system = self.reg.read_bytes()
self.user.write_text("WINE REGISTRY Version 2\n")
self.run_seed()
self.assertIn('"UserRedist"=dword:00000001', self.user.read_text())
self.run_seed()
self.user.unlink()
self.run_seed()
self.assertFalse(self.user.exists())
self.assertNotIn("UserRedist", (self.reg.parent / ".droiddeck-redists").read_text())
self.assertEqual(system, self.reg.read_bytes())
@unittest.skipIf(os.name == "posix" and os.geteuid() == 0, "root can write through read-only mode bits")
def test_an_unwritable_user_registry_does_not_claim_a_missing_marker(self):
self.game(script=GAME_SCRIPT + GAME_SCRIPT.replace("HKEY_LOCAL_MACHINE", "HKEY_CURRENT_USER").replace("VCRedist2022", "UserRedist"))
ledger = self.reg.parent / ".droiddeck-redists"
ledger.write_text("HKEY_CURRENT_USER\\\\Software\\\\Valve\\\\Steam\\\\Apps\\\\CommonRedist\\\\vcredist\\\\2022\tUserRedist\n")
user = self.user.read_bytes()
self.user.chmod(0o444)
try:
self.run_seed()
self.assertEqual(user, self.user.read_bytes())
self.assertEqual(self.user.stat().st_mode & 0o777, 0o444)
self.assertNotIn("UserRedist", ledger.read_text())
self.assertEqual(self.reg.read_text().count('"VCRedist2022"=dword:00000001'), 2)
finally:
self.user.chmod(0o644)
def test_user_markers_in_a_default_prefix_and_another_library_are_seeded(self):
default = self.steam / "steamapps/common/Proton Test/files/share/default_pfx"
default.mkdir(parents=True)
for name in ("system.reg", "user.reg"):
(default / name).write_text("WINE REGISTRY Version 2\n")
sd = self.tmp / "sd"
self.game(library=sd, script=GAME_SCRIPT.replace("HKEY_LOCAL_MACHINE", "HKEY_CURRENT_USER"))
self.run_seed(str(sd))
self.assertIn('"VCRedist2022"=dword:00000001', (default / "user.reg").read_text())
self.assertNotIn('"VCRedist2022"', (default / "system.reg").read_text())
self.assertIn('"VCRedist2022"=dword:00000001', self.user.read_text())
def test_the_vc_runtime_is_recorded_for_every_architecture_and_view(self):
self.run_seed()
reg = self.reg.read_text()
@@ -156,7 +245,7 @@ class SeedRedistsTest(unittest.TestCase):
self.assertIn('"x64 14.99.1.0"=dword:00000001', self.reg.read_text())
def test_an_unchanged_registry_is_not_read_again(self):
self.game()
self.game(script=GAME_SCRIPT + GAME_SCRIPT.replace("HKEY_LOCAL_MACHINE", "HKEY_CURRENT_USER").replace("VCRedist2022", "UserRedist"))
self.run_seed()
self.run_seed()
shim = self.tmp / "bin"
@@ -166,9 +255,21 @@ class SeedRedistsTest(unittest.TestCase):
(shim / "awk").chmod(0o755)
env = dict(os.environ, DROIDDECK_LIBRARIES="", PATH="%s:%s" % (shim, os.environ["PATH"]))
once = self.reg.read_text()
user = self.user.read_text()
subprocess.run(["bash", str(SCRIPT), str(self.steam)], env=env, capture_output=True, text=True, check=True)
self.assertEqual(once, self.reg.read_text())
self.assertEqual(user, self.user.read_text())
self.assertNotIn(str(self.reg), log.read_text() if log.exists() else "")
self.assertNotIn(str(self.user), log.read_text() if log.exists() else "")
replaced = self.user.with_name("user.reg.new")
replaced.write_text(user.replace('"UserRedist"', '"OtherValue"'))
os.utime(replaced, ns=(self.user.stat().st_atime_ns, self.user.stat().st_mtime_ns))
self.assertEqual(replaced.stat().st_size, self.user.stat().st_size)
os.replace(replaced, self.user)
subprocess.run(["bash", str(SCRIPT), str(self.steam)], env=env, capture_output=True, text=True, check=True)
self.assertEqual(self.user.read_text().count('"UserRedist"=dword:00000001'), 1)
self.assertIn('"OtherValue"=dword:00000001', self.user.read_text())
self.assertEqual(once, self.reg.read_text())
replaced = self.reg.with_name("system.reg.new")
replaced.write_text("WINE REGISTRY Version 2\n")
os.replace(replaced, self.reg)
@@ -194,6 +295,39 @@ class SeedRedistsTest(unittest.TestCase):
self.assertIn('"RockstarLauncher"=dword:00000001', reg)
self.assertNotIn("Vulkan111080", (self.reg.parent / ".droiddeck-redists").read_text())
def test_a_current_user_vulkan_installer_is_left_to_run(self):
self.game(script=VULKAN_SCRIPT.replace("HKEY_LOCAL_MACHINE", "HKEY_CURRENT_USER"))
self.run_seed()
self.assertIn('"RockstarLauncher"=dword:00000001', self.user.read_text())
self.assertNotIn("Vulkan111080", self.user.read_text())
self.assertNotIn("Vulkan111080", self.reg.read_text())
self.assertNotIn("Vulkan111080", (self.reg.parent / ".droiddeck-redists").read_text())
def test_a_current_user_vulkan_marker_comes_out_of_only_its_own_hive(self):
self.game(script=VULKAN_SCRIPT.replace("HKEY_LOCAL_MACHINE", "HKEY_CURRENT_USER"))
self.run_seed()
system = self.reg.read_bytes() + b'\n[Software\\\\Valve\\\\Steam\\\\Apps\\\\1174180] 1\n"Vulkan111080"=dword:00000001\n'
self.reg.write_bytes(system)
with self.user.open("a") as out:
out.write('\n[Software\\\\Valve\\\\Steam\\\\Apps\\\\1174180] 1\n"Other"="keep"\n"Vulkan111080"=dword:00000001\n'
'\n[Software\\\\Wow6432Node\\\\Valve\\\\Steam\\\\Apps\\\\1174180] 1\n"Vulkan111080"=dword:00000001\n'
'\n[Software\\\\Valve\\\\Steam\\\\Apps\\\\22380] 1\n"Vulkan111080"=dword:00000001\n')
with (self.reg.parent / ".droiddeck-redists").open("a") as out:
out.write("HKEY_CURRENT_USER\\\\Software\\\\Valve\\\\Steam\\\\Apps\\\\1174180\tVulkan111080\n")
os.utime(self.user, ns=(1_000_000_000_123456789, 1_000_000_000_123456789))
self.run_seed()
user = self.user.read_text()
self.assertEqual(user.count('"Vulkan111080"'), 2, "the other path and the unseeded user view stay")
self.assertIn('"Other"="keep"', user)
self.assertEqual(system, self.reg.read_bytes())
self.assertNotIn("Vulkan111080", (self.reg.parent / ".droiddeck-redists").read_text())
self.assertEqual(self.user.stat().st_mtime_ns, 1_000_000_000_123456789)
with self.user.open("a") as out:
out.write('\n[Software\\\\Valve\\\\Steam\\\\Apps\\\\1174180] 1\n"Vulkan111080"=dword:00000001\n')
user = self.user.read_bytes()
self.run_seed()
self.assertEqual(user, self.user.read_bytes())
def test_a_vulkan_marker_an_earlier_seeding_wrote_comes_out_once(self):
self.rdr2()
marker = "HKEY_LOCAL_MACHINE\\\\Software\\\\Valve\\\\Steam\\\\Apps\\\\1174180\tVulkan111080"
+27
View File
@@ -0,0 +1,27 @@
import re
import subprocess
import unittest
from pathlib import Path
SESSION = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-session"
def step_function():
match = re.search(r"^step\(\) \{.*\}$", SESSION.read_text(), re.M)
return match.group(0)
class SessionStepTimeTest(unittest.TestCase):
def test_a_step_line_carries_milliseconds_before_its_text(self):
out = subprocess.run(["bash", "-c", step_function() + "\nstep starting the Steam client"],
capture_output=True, text=True, timeout=30).stdout.strip()
self.assertRegex(out, r"^== STEP \d{2}:\d{2}:\d{2}\.\d{3} starting the Steam client$")
def test_the_text_after_the_first_space_is_the_step_name(self):
out = subprocess.run(["bash", "-c", step_function() + "\nstep checking the Steam client"],
capture_output=True, text=True, timeout=30).stdout.strip()
self.assertEqual("checking the Steam client", out.removeprefix("== STEP ").split(" ", 1)[1])
if __name__ == "__main__":
unittest.main()
+16
View File
@@ -774,6 +774,14 @@ class AttachPage:
return {"selected": "", "fallback": "", "tools": []}
class TourFailurePage(AttachPage):
def evaluate(self, expression, timeout=30):
self.scripts.append(expression)
if expression == LIVE["TOUR_JS"]:
raise RuntimeError("SteamClient.Settings.SetSetting is unavailable")
return True
class SwitchToDesktopTest(unittest.TestCase):
def setUp(self):
self.globals = LIVE["Helper"].attach.__globals__
@@ -798,6 +806,14 @@ class SwitchToDesktopTest(unittest.TestCase):
self.assertIn(("Runtime.addBinding", LIVE["VR_BINDING"]), helper.page.calls)
self.assertIn(LIVE["VR_JS"], helper.page.scripts)
def test_missing_optional_tour_setting_does_not_block_attach(self):
with mock.patch.dict(self.globals, {"shared_context": lambda port: "/devtools/page/1", "Page": TourFailurePage}):
helper = LIVE["Helper"]("/steam", 1)
self.assertTrue(helper.attach())
self.assertIn(LIVE["VR_JS"], helper.page.scripts)
self.assertIn(LIVE["TOUR_JS"], helper.page.scripts)
self.assertIsNotNone(helper.page)
def test_vr_bridge_accepts_only_steamvr_and_coalesces_requests(self):
helper = LIVE["Helper"]("/steam", 1)
helper.page = mock.Mock()
+107
View File
@@ -0,0 +1,107 @@
import contextlib
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
from unittest.mock import patch
RELEASE = Path(__file__).resolve().parents[1] / "release"
sys.path.insert(0, str(RELEASE))
import validate_apk
class ValidateApkTest(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
subprocess.run(["git", "init", "-q", self.root], check=True)
self.git("config", "user.name", "Human Developer")
self.git("config", "user.email", "human@example.org")
self.git("commit", "--allow-empty", "-qm", "Baseline")
self.git("update-ref", "refs/remotes/origin/main", "HEAD")
self.statuses = []
def git(self, *args):
return subprocess.check_output(["git", "-C", self.root, *args], text=True).strip()
def validate(self, message="Source change", body="", result="success", stale=False, completed=False, filename="source.kt"):
(self.root / filename).write_text(message)
self.git("add", filename)
self.git("commit", "--allow-empty", "-qm", message)
sha = self.git("rev-parse", "HEAD")
pr = {"number": 1, "state": "open", "head": {"sha": sha}, "user": {"login": "human", "type": "User"},
"title": "Source change", "body": body}
event = {"number": 1, "pull_request": {"head": {"sha": "stale" if stale else sha}}}
if completed:
event = {"workflow_run": {"event": "pull_request", "head_sha": "stale" if stale else sha}}
path = self.root / "event.json"
path.write_text(json.dumps(event))
def api(path, *args):
if "/statuses/" in path:
self.statuses.append(dict(value.split("=", 1) for value in args if "=" in value))
return {}
if path.endswith("/pulls/1"):
return pr
if "/commits/" in path and path.endswith("/pulls"):
return [pr]
if "workflows/build.yml/runs?" in path:
return {"workflow_runs": [{"id": 7, "head_sha": sha, "status": "completed", "html_url": "https://example.org/build"}]}
if path.endswith("/jobs?per_page=100"):
return {"jobs": [{"name": "Compile and test APK", "status": "in_progress" if result == "pending" else "completed", "conclusion": result}]}
raise AssertionError(path)
env = {"GITHUB_EVENT_PATH": str(path), "GITHUB_REPOSITORY": "owner/repo",
"GITHUB_EVENT_NAME": "workflow_run" if completed else "pull_request_target", "GITHUB_RUN_ID": "8"}
with contextlib.chdir(self.root), patch.dict(os.environ, env), patch.object(validate_apk, "api", side_effect=api), patch.object(validate_apk, "fetch_source"):
validate_apk.main()
def test_success_requires_compilation_and_clean_authorship(self):
self.validate()
self.assertEqual(self.statuses[-1]["state"], "success")
def test_successful_build_cannot_hide_bot_commit(self):
with self.assertRaises(RuntimeError):
self.validate(message="Change\n\nCo-authored-by: OpenAI Codex <codex@openai.com>")
self.assertEqual(self.statuses[-1]["state"], "failure")
def test_successful_build_cannot_hide_squash_metadata(self):
with self.assertRaises(RuntimeError):
self.validate(body="Co-authored-by: Claude <claude@example.org>")
self.assertEqual(self.statuses[-1]["state"], "failure")
def test_pending_or_failed_compilation_never_passes(self):
for result in ("pending", "failure"):
self.validate(result=result)
self.assertEqual(self.statuses[-1]["state"], result)
def test_superseded_event_cannot_replace_current_status(self):
self.validate(stale=True)
self.assertEqual(self.statuses, [])
def test_completed_build_revalidates_current_squash_metadata(self):
with self.assertRaises(RuntimeError):
self.validate(body="Co-authored-by: Claude <claude@example.org>", completed=True)
self.assertEqual(self.statuses[-1]["state"], "failure")
def test_superseded_build_cannot_replace_current_status(self):
self.validate(stale=True, completed=True)
self.assertEqual(self.statuses, [])
def test_documentation_passes_without_waiting_for_a_skipped_build(self):
self.validate(filename="README.md", result="pending")
self.assertEqual(self.statuses[-1]["state"], "success")
def test_renaming_code_to_documentation_still_requires_compilation(self):
(self.root / "source.kt").write_text("source")
self.git("add", "source.kt")
self.git("commit", "-qm", "Add source")
self.git("update-ref", "refs/remotes/origin/main", "HEAD")
self.git("mv", "source.kt", "README.md")
self.git("commit", "-qm", "Rename source")
with contextlib.chdir(self.root):
self.assertFalse(validate_apk.documentation_only(self.git("rev-parse", "HEAD")))