mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-21 05:46:03 +00:00
feat: agent bridge wayland and gamescope coverage (#406)
* feat: run a guest agent in every session for commands, focus and the Steam client's DevTools * feat: give the agent bridge game, input, UI and experiment commands behind a Setup toggle * feat: droiddeckctl commands for the new bridge, a scenario runner and contract tests * feat: run cleanup steps after every scenario run so a failure cannot leak into the next * feat: restart a session that died between scenario runs with start --reuse * fix: give droiddeckctl stop its own, longer wait for the session's logs * fix: harden debugging tools access and output
This commit is contained in:
1 parent
37e89c5b4d
commit
d231564f8e
42 files changed
+3787
-168
No files matched your search
@@ -0,0 +1,118 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
SOURCE = Path(__file__).resolve().parents[1] / "linuxfs/preload/net.c"
|
||||
|
||||
|
||||
@unittest.skipUnless(sys.platform.startswith("linux") and shutil.which("cc"), "needs Linux and a C compiler")
|
||||
class CdpGuardTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.build = tempfile.TemporaryDirectory()
|
||||
cls.library = Path(cls.build.name) / "net.so"
|
||||
subprocess.run(["cc", "-shared", "-fPIC", "-O2", str(SOURCE), "-x", "c", "-", "-ldl", "-o", str(cls.library)],
|
||||
input=b"int bl_udevmon_stand_in(int fd) { return 0; }", check=True, capture_output=True)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.build.cleanup()
|
||||
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.registry = Path(self.temp.name) / "net"
|
||||
self.registry.mkdir()
|
||||
|
||||
def port(self, ipv6=False):
|
||||
with socket.socket(socket.AF_INET6 if ipv6 else socket.AF_INET) as s:
|
||||
s.bind(("::1" if ipv6 else "127.0.0.1", 0))
|
||||
return s.getsockname()[1]
|
||||
|
||||
def env(self, port):
|
||||
return dict(os.environ, LD_PRELOAD=str(self.library), BL_CDP_GUARD=str(port), BL_SYSV_DIR=self.temp.name)
|
||||
|
||||
def test_guarded_ipv4_bind_is_loopback_only(self):
|
||||
port = self.port()
|
||||
program = "import socket; s=socket.socket(); s.bind(('0.0.0.0', %d)); print(s.getsockname()[0])" % port
|
||||
result = subprocess.run([sys.executable, "-c", program], env=self.env(port), check=True, capture_output=True, text=True)
|
||||
self.assertEqual("127.0.0.1", result.stdout.strip())
|
||||
|
||||
def test_guarded_ipv6_bind_is_loopback_only(self):
|
||||
if not socket.has_ipv6:
|
||||
self.skipTest("needs IPv6")
|
||||
port = self.port(True)
|
||||
program = "import socket; s=socket.socket(socket.AF_INET6); s.bind(('::', %d)); print(s.getsockname()[0])" % port
|
||||
result = subprocess.run([sys.executable, "-c", program], env=self.env(port), check=True, capture_output=True, text=True)
|
||||
self.assertEqual("::1", result.stdout.strip())
|
||||
|
||||
def test_other_listeners_are_unchanged(self):
|
||||
port = self.port()
|
||||
program = "import socket; s=socket.socket(); s.bind(('0.0.0.0', %d)); print(s.getsockname()[0])" % port
|
||||
result = subprocess.run([sys.executable, "-c", program], env=self.env(0), check=True, capture_output=True, text=True)
|
||||
self.assertEqual("0.0.0.0", result.stdout.strip())
|
||||
|
||||
def connect(self, address, registered, stale=False, wrong_destination=False):
|
||||
port = self.port()
|
||||
program = "import socket; s=socket.socket(); s.bind(('0.0.0.0', %d)); s.listen(); print('ready', flush=True); c,_=s.accept(); c.sendall(b'accepted')" % port
|
||||
server = subprocess.Popen([sys.executable, "-u", "-c", program], env=self.env(port), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
try:
|
||||
self.assertEqual(b"ready\n", server.stdout.readline())
|
||||
with socket.socket() as client:
|
||||
client.settimeout(3)
|
||||
client.bind((address, 0))
|
||||
if registered:
|
||||
peer = client.getsockname()[1]
|
||||
inode = os.fstat(client.fileno()).st_ino + (1 if stale else 0)
|
||||
destination = port + (1 if wrong_destination else 0)
|
||||
(self.registry / ("p%d" % peer)).write_text("%d 1 %d %d %d %d %d\n" %
|
||||
(os.getpid(), os.getuid(), destination, client.fileno(), inode, socket.AF_INET))
|
||||
client.connect(("127.0.0.1", port))
|
||||
try:
|
||||
return client.recv(8)
|
||||
except ConnectionResetError:
|
||||
return b""
|
||||
finally:
|
||||
server.kill()
|
||||
server.wait()
|
||||
server.stdout.close()
|
||||
server.stderr.close()
|
||||
|
||||
def test_registered_guest_loopback_peer_is_accepted(self):
|
||||
self.assertEqual(b"accepted", self.connect("127.0.0.1", True))
|
||||
|
||||
def test_unregistered_local_peer_is_refused(self):
|
||||
self.assertEqual(b"", self.connect("127.0.0.1", False))
|
||||
|
||||
def test_matching_port_record_cannot_authorize_another_address(self):
|
||||
self.assertEqual(b"", self.connect("127.0.0.2", True))
|
||||
|
||||
def test_stale_socket_record_does_not_authorize_a_reused_port(self):
|
||||
self.assertEqual(b"", self.connect("127.0.0.1", True, stale=True))
|
||||
|
||||
def test_record_for_another_destination_does_not_authorize_cdp(self):
|
||||
self.assertEqual(b"", self.connect("127.0.0.1", True, wrong_destination=True))
|
||||
|
||||
def test_preloaded_guest_connect_still_works(self):
|
||||
port = self.port()
|
||||
program = "import socket; s=socket.socket(); s.bind(('0.0.0.0', %d)); s.listen(); print('ready', flush=True); c,_=s.accept(); c.sendall(b'accepted')" % port
|
||||
server = subprocess.Popen([sys.executable, "-u", "-c", program], env=self.env(port), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
try:
|
||||
self.assertEqual(b"ready\n", server.stdout.readline())
|
||||
client = "import socket; s=socket.create_connection(('127.0.0.1', %d), timeout=3); print(s.recv(8).decode())" % port
|
||||
result = subprocess.run([sys.executable, "-c", client], env=self.env(port), check=True, capture_output=True, text=True, timeout=5)
|
||||
self.assertEqual("accepted", result.stdout.strip())
|
||||
finally:
|
||||
server.kill()
|
||||
server.wait()
|
||||
server.stdout.close()
|
||||
server.stderr.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,250 @@
|
||||
"""The guest agent: its request files, exec, errors and the DevTools client, without a session."""
|
||||
import base64
|
||||
import hashlib
|
||||
import importlib.machinery
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import struct
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
import tracemalloc
|
||||
|
||||
SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-agent"
|
||||
loader = importlib.machinery.SourceFileLoader("droiddeck_agent", str(SCRIPT))
|
||||
spec = importlib.util.spec_from_loader(loader.name, loader)
|
||||
agent = importlib.util.module_from_spec(spec)
|
||||
loader.exec_module(agent)
|
||||
|
||||
|
||||
class FakeDevTools(threading.Thread):
|
||||
"""GET /json lists one target; its WebSocket answers Runtime.evaluate the way Chromium does."""
|
||||
|
||||
def __init__(self, answer):
|
||||
super().__init__(daemon=True)
|
||||
self.answer = answer
|
||||
self.server = socket.socket()
|
||||
self.server.bind(("127.0.0.1", 0))
|
||||
self.server.listen(4)
|
||||
self.port = self.server.getsockname()[1]
|
||||
self.seen = []
|
||||
|
||||
def run(self):
|
||||
while True:
|
||||
try:
|
||||
conn, _ = self.server.accept()
|
||||
except OSError:
|
||||
return
|
||||
threading.Thread(target=self.serve, args=(conn,), daemon=True).start()
|
||||
|
||||
def serve(self, conn):
|
||||
head = b""
|
||||
while b"\r\n\r\n" not in head:
|
||||
head += conn.recv(4096)
|
||||
request = head.decode()
|
||||
if request.startswith("GET /json"):
|
||||
body = json.dumps([{"title": "SharedJSContext", "url": "https://steamloopback.host/", "type": "page",
|
||||
"webSocketDebuggerUrl": "ws://127.0.0.1:%d/devtools/page/1" % self.port}]).encode()
|
||||
conn.sendall(b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: %d\r\n\r\n" % len(body) + body)
|
||||
conn.close()
|
||||
return
|
||||
key = [l.split(":", 1)[1].strip() for l in request.split("\r\n") if l.lower().startswith("sec-websocket-key")][0]
|
||||
accept = base64.b64encode(hashlib.sha1((key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").encode()).digest()).decode()
|
||||
conn.sendall(("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n"
|
||||
"Sec-WebSocket-Accept: %s\r\n\r\n" % accept).encode())
|
||||
b0, b1 = conn.recv(2)
|
||||
n = b1 & 0x7F
|
||||
if n == 126:
|
||||
n = struct.unpack(">H", conn.recv(2))[0]
|
||||
mask = conn.recv(4)
|
||||
data = b""
|
||||
while len(data) < n:
|
||||
data += conn.recv(n - len(data))
|
||||
message = json.loads(bytes(b ^ mask[i % 4] for i, b in enumerate(data)))
|
||||
self.seen.append(message)
|
||||
for reply in ({"method": "Runtime.consoleAPICalled", "params": {}}, dict(self.answer, id=message["id"])):
|
||||
payload = json.dumps(reply).encode()
|
||||
header = bytes([0x81, 126]) + struct.pack(">H", len(payload)) if len(payload) > 125 else bytes([0x81, len(payload)])
|
||||
conn.sendall(header + payload)
|
||||
time.sleep(0.2)
|
||||
conn.close()
|
||||
|
||||
|
||||
class AgentTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.dir = Path(self.temp.name)
|
||||
(self.dir / "resp").mkdir()
|
||||
|
||||
def ask(self, request):
|
||||
path = self.dir / "req.json"
|
||||
path.write_text(json.dumps(request))
|
||||
agent.answer(self.dir, path)
|
||||
self.assertFalse(path.exists(), "the request file is consumed")
|
||||
return json.loads((self.dir / "resp" / "req.json").read_text())
|
||||
|
||||
def test_exec_output_and_status(self):
|
||||
answer = self.ask({"kind": "exec", "argv": ["sh", "-c", "echo out; echo err >&2; exit 3"], "env": {"X": "1"}})
|
||||
self.assertTrue(answer["ok"])
|
||||
self.assertEqual(3, answer["exitCode"])
|
||||
self.assertEqual("out\n", answer["stdout"]["text"])
|
||||
self.assertEqual("err\n", answer["stderr"]["text"])
|
||||
self.assertFalse(answer["timedOut"])
|
||||
|
||||
def test_exec_environment_stdin_and_cap(self):
|
||||
answer = self.ask({"kind": "exec", "argv": ["sh", "-c", "printf %s \"$X\"; cat"], "env": {"X": "a"}, "stdin": "b"})
|
||||
self.assertEqual("ab", answer["stdout"]["text"])
|
||||
big = self.ask({"kind": "exec", "argv": ["sh", "-c", "head -c 300000 /dev/zero"]})
|
||||
self.assertTrue(big["stdout"]["truncated"])
|
||||
self.assertEqual(agent.OUTPUT_CAP, len(big["stdout"]["text"]))
|
||||
|
||||
def test_exec_timeout_kills_the_process_group(self):
|
||||
started = time.monotonic()
|
||||
answer = self.ask({"kind": "exec", "argv": ["sh", "-c", "sleep 30 & sleep 30"], "timeout": 0.5})
|
||||
self.assertTrue(answer["timedOut"])
|
||||
self.assertLess(time.monotonic() - started, 10)
|
||||
|
||||
def test_exec_memory_is_bounded_while_draining_large_output(self):
|
||||
tracemalloc.start()
|
||||
try:
|
||||
answer = agent.run_exec({"argv": [sys.executable, "-c", "import os; [os.write(1, b'x' * 65536) for _ in range(1024)]"]})
|
||||
_, peak = tracemalloc.get_traced_memory()
|
||||
finally:
|
||||
tracemalloc.stop()
|
||||
self.assertEqual(0, answer["exitCode"])
|
||||
self.assertEqual(agent.OUTPUT_CAP, len(answer["stdout"]["text"]))
|
||||
self.assertTrue(answer["stdout"]["truncated"])
|
||||
self.assertLess(peak, 6 * 1024 * 1024)
|
||||
|
||||
def test_exec_drains_both_streams_while_writing_stdin(self):
|
||||
program = "import os, sys; os.write(1, b'x' * 300000); print(len(sys.stdin.read()), file=sys.stderr)"
|
||||
answer = self.ask({"kind": "exec", "argv": [sys.executable, "-c", program], "stdin": "y" * 100000})
|
||||
self.assertFalse(answer["timedOut"])
|
||||
self.assertTrue(answer["stdout"]["truncated"])
|
||||
self.assertEqual("100000\n", answer["stderr"]["text"])
|
||||
|
||||
def test_flooding_both_streams_still_times_out(self):
|
||||
program = "import os\nwhile True:\n os.write(1, b'o' * 65536)\n os.write(2, b'e' * 65536)"
|
||||
answer = self.ask({"kind": "exec", "argv": [sys.executable, "-c", program], "timeout": 0.5})
|
||||
self.assertTrue(answer["timedOut"])
|
||||
for name in ("stdout", "stderr"):
|
||||
self.assertEqual(agent.OUTPUT_CAP, len(answer[name]["text"]))
|
||||
self.assertTrue(answer[name]["truncated"])
|
||||
|
||||
def test_timeout_applies_when_parent_exits_with_inherited_pipes(self):
|
||||
started = time.monotonic()
|
||||
answer = self.ask({"kind": "exec", "argv": ["sh", "-c", "sleep 30 & exit 0"], "timeout": 0.5})
|
||||
self.assertTrue(answer["timedOut"])
|
||||
self.assertLess(time.monotonic() - started, 5)
|
||||
|
||||
def test_invalid_timeout_and_input_are_refused_before_exec(self):
|
||||
for value in (0, -1, 601, "NaN", "Infinity", "invalid"):
|
||||
answer = self.ask({"kind": "exec", "argv": ["true"], "timeout": value})
|
||||
self.assertEqual("INVALID_REQUEST", answer["error"]["code"])
|
||||
for fields in ({"stdin": 1}, {"env": []}, {"env": {"BAD=KEY": "value"}}, {"argv": ["true\0"]}):
|
||||
answer = self.ask({"kind": "exec", "argv": ["true"], **fields})
|
||||
self.assertEqual("INVALID_REQUEST", answer["error"]["code"])
|
||||
|
||||
def test_errors_are_answers(self):
|
||||
self.assertEqual("INVALID_REQUEST", self.ask({"kind": "exec", "argv": []})["error"]["code"])
|
||||
self.assertEqual("EXEC_FAILED", self.ask({"kind": "exec", "argv": ["/no/such/program"]})["error"]["code"])
|
||||
self.assertEqual("UNKNOWN_REQUEST", self.ask({"kind": "nope"})["error"]["code"])
|
||||
self.assertEqual("INVALID_APP_ID", self.ask({"kind": "quit", "appId": "x"})["error"]["code"])
|
||||
(self.dir / "req.json").write_text("{not json")
|
||||
agent.answer(self.dir, self.dir / "req.json")
|
||||
self.assertEqual("INVALID_REQUEST", json.loads((self.dir / "resp" / "req.json").read_text())["error"]["code"])
|
||||
|
||||
def test_request_shape_and_size_are_bounded(self):
|
||||
self.assertEqual("INVALID_REQUEST", self.ask([])["error"]["code"])
|
||||
self.assertEqual("INVALID_REQUEST", self.ask({"kind": "ping", "unused": "x" * agent.REQUEST_CAP})["error"]["code"])
|
||||
|
||||
def test_replies_are_owner_only_even_when_replacing_a_public_file(self):
|
||||
path = self.dir / "private.json"
|
||||
path.write_text("old")
|
||||
path.chmod(0o644)
|
||||
agent.write_json(path, {"ok": True})
|
||||
self.assertEqual(0o600, path.stat().st_mode & 0o777)
|
||||
|
||||
def test_oversized_websocket_frames_are_refused_before_reading_payload(self):
|
||||
ws = agent.WebSocket.__new__(agent.WebSocket)
|
||||
ws.buffer = bytes([0x81, 127]) + struct.pack(">Q", agent.RESPONSE_CAP + 1)
|
||||
with self.assertRaises(agent.AgentError) as caught:
|
||||
ws.recv()
|
||||
self.assertEqual("RESPONSE_TOO_LARGE", caught.exception.code)
|
||||
|
||||
def test_devtools_targets_cannot_connect_to_remote_hosts(self):
|
||||
for url in ("ws://example.com/devtools", "ws://127.0.0.1@example.com/devtools", "wss://127.0.0.1/devtools"):
|
||||
with patch.object(agent.socket, "create_connection") as connect:
|
||||
with self.assertRaises(agent.AgentError) as caught:
|
||||
agent.WebSocket(url, 1)
|
||||
self.assertEqual("INVALID_TARGET", caught.exception.code)
|
||||
connect.assert_not_called()
|
||||
|
||||
def test_cdp_without_a_port(self):
|
||||
os.environ.pop("BL_CDP_PORT", None)
|
||||
self.assertEqual("NO_DEVTOOLS", self.ask({"kind": "cdp", "expression": "1"})["error"]["code"])
|
||||
|
||||
def test_cdp_eval(self):
|
||||
server = FakeDevTools({"result": {"result": {"type": "number", "value": 42}}})
|
||||
server.start()
|
||||
self.addCleanup(server.server.close)
|
||||
(self.dir / "cdp-port").write_text("%d\n" % server.port)
|
||||
answer = self.ask({"kind": "cdp", "expression": "6 * 7"})
|
||||
self.assertTrue(answer["ok"], answer)
|
||||
self.assertEqual(42, answer["value"])
|
||||
self.assertEqual("SharedJSContext", answer["target"])
|
||||
self.assertEqual("Runtime.evaluate", server.seen[0]["method"])
|
||||
self.assertEqual("6 * 7", server.seen[0]["params"]["expression"])
|
||||
targets = self.ask({"kind": "cdp", "op": "targets"})
|
||||
self.assertEqual("SharedJSContext", targets["targets"][0]["title"])
|
||||
missing = self.ask({"kind": "cdp", "expression": "1", "target": "Nope"})
|
||||
self.assertEqual("NO_TARGET", missing["error"]["code"])
|
||||
|
||||
def test_cdp_exception(self):
|
||||
server = FakeDevTools({"result": {"result": {"type": "object"}, "exceptionDetails": {
|
||||
"text": "Uncaught", "exception": {"description": "ReferenceError: SteamClient is not defined"}}}})
|
||||
server.start()
|
||||
self.addCleanup(server.server.close)
|
||||
(self.dir / "cdp-port").write_text(str(server.port))
|
||||
answer = self.ask({"kind": "cdp", "expression": "SteamClient"})
|
||||
self.assertEqual("JS_EXCEPTION", answer["error"]["code"])
|
||||
self.assertIn("ReferenceError", answer["error"]["message"])
|
||||
|
||||
def test_serve_answers_request_files(self):
|
||||
os.environ.pop("DISPLAY", None)
|
||||
thread = threading.Thread(target=agent.serve, args=(self.dir, False, 0.02), daemon=True)
|
||||
thread.start()
|
||||
for _ in range(100):
|
||||
if (self.dir / "hello.json").exists():
|
||||
break
|
||||
time.sleep(0.02)
|
||||
hello = json.loads((self.dir / "hello.json").read_text())
|
||||
self.assertEqual(os.getpid(), hello["pid"])
|
||||
self.assertFalse(hello["focus"])
|
||||
(self.dir / "req" / "a.json.tmp").write_text(json.dumps({"kind": "ping"}))
|
||||
os.replace(self.dir / "req" / "a.json.tmp", self.dir / "req" / "a.json")
|
||||
for _ in range(200):
|
||||
if (self.dir / "resp" / "a.json").exists():
|
||||
break
|
||||
time.sleep(0.02)
|
||||
self.assertEqual(agent.VERSION, json.loads((self.dir / "resp" / "a.json").read_text())["version"])
|
||||
|
||||
def test_game_pids_reads_the_steam_environment(self):
|
||||
import subprocess
|
||||
if not Path("/proc").is_dir():
|
||||
self.skipTest("needs /proc")
|
||||
child = subprocess.Popen(["sleep", "30"], env=dict(os.environ, SteamAppId="424242"))
|
||||
self.addCleanup(lambda: (child.kill(), child.wait()))
|
||||
time.sleep(0.2)
|
||||
self.assertIn(child.pid, agent.game_pids(424242))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,353 @@
|
||||
"""droiddeckctl and droiddeck-scenario against a fake adb: the JSON contract and exit codes."""
|
||||
import base64
|
||||
import contextlib
|
||||
import importlib.machinery
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import stat
|
||||
import sys
|
||||
import tempfile
|
||||
import textwrap
|
||||
import unittest
|
||||
|
||||
TOOLS = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(TOOLS))
|
||||
|
||||
|
||||
def load(name):
|
||||
loader = importlib.machinery.SourceFileLoader(name.replace("-", "_"), str(TOOLS / name))
|
||||
spec = importlib.util.spec_from_loader(loader.name, loader)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
ctl = load("droiddeckctl")
|
||||
scenario = load("droiddeck-scenario")
|
||||
|
||||
# A stand-in for adb: answers the provider's content calls from a JSON config (a list answers
|
||||
# successive calls), records every invocation, and fakes the few shell commands droiddeckctl uses.
|
||||
FAKE_ADB = textwrap.dedent('''\
|
||||
#!/usr/bin/env python3
|
||||
import base64, json, os, sys
|
||||
config_path = os.environ["FAKE_ADB_CONFIG"]
|
||||
config = json.load(open(config_path))
|
||||
args = sys.argv[1:]
|
||||
if args[:1] == ["-s"]:
|
||||
args = args[2:]
|
||||
entry = {"args": args}
|
||||
if args[:1] == ["get-state"]:
|
||||
print("device"); sys.exit(0)
|
||||
if args[:3] == ["shell", "content", "call"]:
|
||||
method = args[args.index("--method") + 1]
|
||||
request = None
|
||||
if "--extra" in args:
|
||||
request = json.loads(base64.b64decode(args[args.index("--extra") + 1].split(":", 2)[2]))
|
||||
entry.update(method=method, request=request)
|
||||
answers = config["provider"].get(method, {"ok": False, "error": {"code": "UNKNOWN_COMMAND", "message": method}})
|
||||
if isinstance(answers, list):
|
||||
count = config.setdefault("counts", {}).get(method, 0)
|
||||
config["counts"][method] = count + 1
|
||||
answers = answers[min(count, len(answers) - 1)]
|
||||
json.dump(config, open(config_path, "w"))
|
||||
print("Result: Bundle[{json=" + json.dumps(answers) + "}]")
|
||||
elif args[:3] == ["shell", "dumpsys", "display"]:
|
||||
print(config.get("dumpsys_display", ""))
|
||||
elif args[:3] == ["shell", "dumpsys", "power"]:
|
||||
print(" mWakefulness=Awake")
|
||||
elif args[:2] == ["exec-out", "screencap"]:
|
||||
sys.stdout.buffer.write(b"\\x89PNG fake")
|
||||
with open(config["log"], "a") as log:
|
||||
log.write(json.dumps(entry) + "\\n")
|
||||
''')
|
||||
|
||||
DUMPSYS_DISPLAY = textwrap.dedent('''\
|
||||
Display Devices: size=2
|
||||
DisplayDeviceInfo{"Built-in Screen": uniqueId="local:111", 1080 x 1920}
|
||||
DisplayDeviceInfo{"Screen-2": uniqueId="local:222", 1080 x 1240}
|
||||
Logical Displays: size=2
|
||||
Display 0:
|
||||
mDisplayId=0
|
||||
mPrimaryDisplayDevice=Built-in Screen
|
||||
mBaseDisplayInfo=DisplayInfo{"Built-in Screen", displayId 0", real 1080 x 1920, x}
|
||||
Display 4:
|
||||
mDisplayId=4
|
||||
mPrimaryDisplayDevice=Screen-2
|
||||
mBaseDisplayInfo=DisplayInfo{"Screen-2", displayId 4", real 1080 x 1240, x}
|
||||
''')
|
||||
|
||||
|
||||
def state(phase="READY", focused=None, focusable=()):
|
||||
focus = None if focused is None else {"focusedApp": focused, "focusableApps": list(focusable),
|
||||
"baselayerAppIds": [], "seq": 1, "t": 0}
|
||||
return {"ok": True, "schema": 2, "session": {"id": "s1", "phase": phase, "running": phase == "READY",
|
||||
"focus": focus, "failure": None}}
|
||||
|
||||
|
||||
class FakeAdbTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.dir = Path(self.temp.name)
|
||||
self.adb = self.dir / "adb"
|
||||
self.adb.write_text(FAKE_ADB)
|
||||
self.adb.chmod(self.adb.stat().st_mode | stat.S_IEXEC)
|
||||
self.config = self.dir / "config.json"
|
||||
self.log = self.dir / "log.jsonl"
|
||||
self.configure({})
|
||||
os.environ["FAKE_ADB_CONFIG"] = str(self.config)
|
||||
self.addCleanup(os.environ.pop, "FAKE_ADB_CONFIG", None)
|
||||
|
||||
def configure(self, provider, **extra):
|
||||
self.config.write_text(json.dumps(dict({"provider": provider, "log": str(self.log)}, **extra)))
|
||||
|
||||
def run_ctl(self, *argv):
|
||||
out = io.StringIO()
|
||||
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(io.StringIO()):
|
||||
code = ctl.main(["--adb", str(self.adb), "--serial", "fake-1", *argv])
|
||||
return code, json.loads(out.getvalue())
|
||||
|
||||
def calls(self, method=None):
|
||||
if not self.log.exists():
|
||||
return []
|
||||
entries = [json.loads(line) for line in self.log.read_text().splitlines()]
|
||||
return [e for e in entries if method is None or e.get("method") == method]
|
||||
|
||||
|
||||
class DroiddeckctlTest(FakeAdbTest):
|
||||
def test_oversized_requests_are_refused_before_adb(self):
|
||||
with self.assertRaises(ctl.ControlError) as caught:
|
||||
ctl.provider_call(str(self.adb), "fake-1", "guest", request={"stdin": "x" * ctl.REQUEST_CAP})
|
||||
self.assertEqual("INVALID_REQUEST", caught.exception.code)
|
||||
self.assertFalse(self.calls())
|
||||
|
||||
def test_state_passes_through_with_the_serial(self):
|
||||
self.configure({"state": state()})
|
||||
code, out = self.run_ctl("state")
|
||||
self.assertEqual(0, code)
|
||||
self.assertEqual("READY", out["session"]["phase"])
|
||||
self.assertEqual("fake-1", out["deviceSerial"])
|
||||
|
||||
def test_launch_sends_the_app_id_and_waits_for_focus(self):
|
||||
self.configure({
|
||||
"launch": {"ok": True, "command": "launch", "appId": "489830"},
|
||||
"state": [state(focused=769, focusable=[769]), state(focused=489830, focusable=[769])],
|
||||
})
|
||||
# Focus alone is not enough: the game must also be in the list Steam orders from.
|
||||
code, out = self.run_ctl("launch", "489830", "--wait", "--timeout", "1")
|
||||
self.assertEqual(5, code)
|
||||
self.assertEqual("TIMEOUT", out["error"]["code"])
|
||||
self.assertIn("focused app 489830", out["error"]["message"])
|
||||
self.assertEqual({"appId": "489830"}, self.calls("launch")[0]["request"])
|
||||
|
||||
self.configure({
|
||||
"launch": {"ok": True, "command": "launch", "appId": "489830"},
|
||||
"state": [state(focused=769, focusable=[769]), state(focused=489830, focusable=[489830, 769])],
|
||||
})
|
||||
code, out = self.run_ctl("launch", "489830", "--wait", "--timeout", "5")
|
||||
self.assertEqual(0, code)
|
||||
self.assertEqual(489830, out["focus"]["focusedApp"])
|
||||
|
||||
def test_start_reuse_keeps_a_running_session(self):
|
||||
running = state(focused=769)
|
||||
running["session"]["mode"] = "steam"
|
||||
self.configure({"state": running})
|
||||
code, out = self.run_ctl("start", "steam", "--reuse", "--wait")
|
||||
self.assertEqual(0, code)
|
||||
self.assertTrue(out["reused"])
|
||||
self.assertFalse([c for c in self.calls() if c["args"][:2] == ["shell", "am"]])
|
||||
|
||||
def test_start_without_reuse_refuses_a_running_session(self):
|
||||
running = state()
|
||||
running["session"]["mode"] = "steam"
|
||||
self.configure({"state": running})
|
||||
code, out = self.run_ctl("start", "steam")
|
||||
self.assertEqual(4, code)
|
||||
self.assertEqual("SESSION_ACTIVE", out["error"]["code"])
|
||||
|
||||
def test_wait_game_ignores_the_client(self):
|
||||
self.configure({"state": [state(focused=769), state(focused=752590, focusable=[752590])]})
|
||||
code, out = self.run_ctl("wait", "game", "--timeout", "5")
|
||||
self.assertEqual(0, code)
|
||||
self.assertEqual(752590, out["session"]["focus"]["focusedApp"])
|
||||
|
||||
def test_a_failed_session_ends_a_wait(self):
|
||||
failed = state(phase="FAILED")
|
||||
failed["session"]["failure"] = {"code": "GUEST_EXIT", "message": "boom"}
|
||||
self.configure({"state": failed})
|
||||
code, out = self.run_ctl("wait", "focused", "1", "--timeout", "5")
|
||||
self.assertEqual(4, code)
|
||||
self.assertEqual("GUEST_EXIT", out["error"]["code"])
|
||||
|
||||
def test_disabled_agent_commands_exit_7(self):
|
||||
self.configure({"guest": {"ok": False, "error": {"code": "AGENT_COMMANDS_DISABLED", "message": "off"}}})
|
||||
code, out = self.run_ctl("guest", "--", "true")
|
||||
self.assertEqual(7, code)
|
||||
self.assertEqual("AGENT_COMMANDS_DISABLED", out["error"]["code"])
|
||||
|
||||
def test_run_checks_access_before_launching_an_activity(self):
|
||||
self.configure({"access": {"ok": True, "commands": False}})
|
||||
code, out = self.run_ctl("run", "/usr/bin/sh", "--", "-c", "true")
|
||||
self.assertEqual(7, code)
|
||||
self.assertEqual("AGENT_COMMANDS_DISABLED", out["error"]["code"])
|
||||
self.assertIn("Debugging tools", out["error"]["message"])
|
||||
self.assertEqual(["access"], [c.get("method") for c in self.calls()])
|
||||
|
||||
def test_override_checks_names_before_pushing_any_file(self):
|
||||
self.configure({"access": {"ok": True, "commands": True, "inbox": "/tmp/inbox"}})
|
||||
source = self.dir / "binary"
|
||||
source.write_bytes(b"test")
|
||||
code, out = self.run_ctl("override", "../outside", str(source))
|
||||
self.assertEqual(2, code)
|
||||
self.assertEqual("INVALID_NAME", out["error"]["code"])
|
||||
self.assertEqual(["access"], [c.get("method") for c in self.calls()])
|
||||
|
||||
def test_guest_request_and_check(self):
|
||||
self.configure({"guest": {"ok": True, "exitCode": 3, "stdout": {"text": ""}, "stderr": {"text": "nope"}}})
|
||||
code, out = self.run_ctl("guest", "--timeout", "7", "--env", "A=1", "--check", "--", "xprop", "-root")
|
||||
self.assertEqual(4, code)
|
||||
self.assertEqual("GUEST_EXIT", out["error"]["code"])
|
||||
self.assertEqual({"argv": ["xprop", "-root"], "timeout": 7.0, "env": {"A": "1"}},
|
||||
self.calls("guest")[0]["request"])
|
||||
|
||||
def test_screenshot_resolves_the_logical_display(self):
|
||||
self.configure({}, dumpsys_display=DUMPSYS_DISPLAY)
|
||||
target = self.dir / "shot.png"
|
||||
code, out = self.run_ctl("screenshot", str(target), "--display", "4")
|
||||
self.assertEqual(0, code)
|
||||
self.assertTrue(target.read_bytes().startswith(b"\x89PNG"))
|
||||
shot = [c for c in self.calls() if c["args"][:2] == ["exec-out", "screencap"]][0]
|
||||
self.assertEqual(["exec-out", "screencap", "-p", "-d", "222"], shot["args"])
|
||||
|
||||
def test_displays(self):
|
||||
self.configure({}, dumpsys_display=DUMPSYS_DISPLAY)
|
||||
code, out = self.run_ctl("displays")
|
||||
self.assertEqual(0, code)
|
||||
self.assertEqual([0, 4], [d["display"] for d in out["displays"]])
|
||||
self.assertEqual("222", out["displays"][1]["physicalId"])
|
||||
self.assertEqual([1080, 1240], out["displays"][1]["size"])
|
||||
|
||||
def test_unknown_display_is_an_error(self):
|
||||
self.configure({}, dumpsys_display=DUMPSYS_DISPLAY)
|
||||
code, out = self.run_ctl("screenshot", str(self.dir / "x.png"), "--display", "9")
|
||||
self.assertEqual(2, code)
|
||||
self.assertEqual("NO_SUCH_DISPLAY", out["error"]["code"])
|
||||
|
||||
def test_input_requests(self):
|
||||
self.configure({"input": {"ok": True, "command": "input"}})
|
||||
self.run_ctl("input", "tap", "0.5", "0.25", "--space", "fraction")
|
||||
self.run_ctl("input", "key", "enter", "--mod", "CTRL")
|
||||
self.run_ctl("input", "pad", "a", "--hold", "50")
|
||||
requests = [c["request"] for c in self.calls("input")]
|
||||
self.assertEqual({"type": "tap", "x": 0.5, "y": 0.25, "space": "fraction", "holdMs": 60}, requests[0])
|
||||
self.assertEqual({"type": "key", "key": "enter", "action": "tap", "modifiers": ["CTRL"], "holdMs": 40}, requests[1])
|
||||
self.assertEqual({"type": "pad", "button": "a", "action": "tap", "holdMs": 50}, requests[2])
|
||||
|
||||
def test_ui_click_by_tag_or_match(self):
|
||||
self.configure({"ui": {"ok": True, "command": "ui"}})
|
||||
self.run_ctl("ui", "click", "rail-steam")
|
||||
self.run_ctl("ui", "click", "--match", "Play", "--index", "1")
|
||||
requests = [c["request"] for c in self.calls("ui")]
|
||||
self.assertEqual({"op": "click", "index": 0, "tag": "rail-steam"}, requests[0])
|
||||
self.assertEqual({"op": "click", "index": 1, "match": "Play"}, requests[1])
|
||||
|
||||
def test_cdp_targets_and_eval_requests(self):
|
||||
self.configure({"cdp": {"ok": True, "targets": []}})
|
||||
self.assertEqual(0, self.run_ctl("cdp", "targets")[0])
|
||||
self.assertEqual(0, self.run_ctl("cdp", "eval", "1+1", "--target", "Big Picture")[0])
|
||||
requests = [c["request"] for c in self.calls("cdp")]
|
||||
self.assertEqual({"op": "targets"}, requests[0])
|
||||
self.assertEqual({"op": "eval", "expression": "1+1", "awaitPromise": True, "timeout": 15.0,
|
||||
"target": "Big Picture"}, requests[1])
|
||||
|
||||
def test_a_bug_still_answers_json(self):
|
||||
self.configure({"state": {"ok": True, "session": "not an object"}})
|
||||
code, out = self.run_ctl("wait", "game", "--timeout", "1")
|
||||
self.assertEqual(2, code)
|
||||
self.assertEqual("INTERNAL_ERROR", out["error"]["code"])
|
||||
|
||||
def test_wake(self):
|
||||
code, out = self.run_ctl("wake")
|
||||
self.assertEqual(0, code)
|
||||
self.assertEqual("Awake", out["wakefulness"])
|
||||
self.assertIn(["shell", "input", "keyevent", "KEYCODE_WAKEUP"], [c["args"] for c in self.calls()])
|
||||
|
||||
def test_override_pushes_to_the_inbox_first(self):
|
||||
self.configure({
|
||||
"access": {"ok": True, "commands": True, "inbox": "/sdcard/Android/data/x/files/agent-inbox"},
|
||||
"override": {"ok": True, "installed": "/opt/droiddeck-agent/bin/gamescope"},
|
||||
})
|
||||
binary = self.dir / "gamescope"
|
||||
binary.write_bytes(b"\x7fELF")
|
||||
code, out = self.run_ctl("override", "gamescope", str(binary))
|
||||
self.assertEqual(0, code)
|
||||
push = [c for c in self.calls() if c["args"][:1] == ["push"]][0]
|
||||
self.assertEqual("/sdcard/Android/data/x/files/agent-inbox/gamescope", push["args"][2])
|
||||
self.assertEqual({"name": "gamescope"}, self.calls("override")[0]["request"])
|
||||
|
||||
def test_override_refused_before_pushing_when_commands_are_off(self):
|
||||
self.configure({"access": {"ok": True, "commands": False, "inbox": "/x"}})
|
||||
binary = self.dir / "gamescope"
|
||||
binary.write_bytes(b"x")
|
||||
code, out = self.run_ctl("override", "gamescope", str(binary))
|
||||
self.assertEqual(7, code)
|
||||
self.assertFalse([c for c in self.calls() if c["args"][:1] == ["push"]])
|
||||
|
||||
|
||||
class ScenarioTest(FakeAdbTest):
|
||||
def write(self, body):
|
||||
path = self.dir / "scenario.json"
|
||||
path.write_text(json.dumps(body))
|
||||
return path
|
||||
|
||||
def run_scenario(self, path, *extra):
|
||||
out = io.StringIO()
|
||||
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(io.StringIO()):
|
||||
code = scenario.main([str(path), "--adb", str(self.adb), "--serial", "fake-1",
|
||||
"--out", str(self.dir / "runs"), *extra])
|
||||
return code, json.loads(out.getvalue())
|
||||
|
||||
def test_variables_asserts_and_repeats(self):
|
||||
self.configure({"state": state(focused=489830, focusable=[489830])})
|
||||
path = self.write({
|
||||
"name": "t", "vars": {"appId": 1}, "repeat": 2,
|
||||
"steps": [["state"], {"assert": "session.focus.focusedApp", "equals": "${appId}"}],
|
||||
})
|
||||
code, report = self.run_scenario(path, "--var", "appId=489830")
|
||||
self.assertEqual(0, code)
|
||||
self.assertEqual(2, report["passed"])
|
||||
output = Path(report["out"])
|
||||
self.assertEqual(0o700, output.stat().st_mode & 0o777)
|
||||
for artifact in output.rglob("*.json"):
|
||||
self.assertEqual(0o600, artifact.stat().st_mode & 0o777, str(artifact))
|
||||
for run in report["runs"]:
|
||||
self.assertEqual(0o700, Path(run["folder"]).stat().st_mode & 0o777)
|
||||
|
||||
def test_a_failed_assert_fails_the_run_and_collects_evidence(self):
|
||||
self.configure({"state": state(focused=769, focusable=[769]), "focus": {"ok": True, "focusedApp": 769}},
|
||||
dumpsys_display=DUMPSYS_DISPLAY)
|
||||
path = self.write({"name": "t", "repeat": 3,
|
||||
"steps": [["state"], {"assert": "session.focus.focusedApp", "equals": 489830}]})
|
||||
code, report = self.run_scenario(path)
|
||||
self.assertEqual(1, code)
|
||||
self.assertEqual(1, len(report["runs"])) # stops at the first failure without --keep-going
|
||||
self.assertIn("is 769", report["runs"][0]["error"])
|
||||
evidence = json.loads((Path(report["runs"][0]["folder"]) / "evidence.json").read_text())
|
||||
self.assertEqual(769, evidence["focus"]["focusedApp"])
|
||||
|
||||
def test_after_steps_run_after_a_failure(self):
|
||||
self.configure({"state": state(focused=769), "quit": {"ok": True, "remaining": []}})
|
||||
path = self.write({"name": "t", "repeat": 2, "vars": {"appId": 7},
|
||||
"steps": [["state"], {"assert": "session.focus.focusedApp", "equals": 7}],
|
||||
"after": [["quit", "${appId}"]]})
|
||||
code, report = self.run_scenario(path, "--keep-going")
|
||||
self.assertEqual(1, code)
|
||||
self.assertEqual(2, len(report["runs"]))
|
||||
self.assertEqual([{"appId": 7, "timeout": 15.0}] * 2, [c["request"] for c in self.calls("quit")])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user