Files
AndroidDeviceStreaming/tests/real_device.py
T

149 lines
7.3 KiB
Python

"""Opt-in, read-only smoke test through a remote ADB smart socket and all three programs."""
import argparse
import http.client
import json
import os
from pathlib import Path
import secrets
import socket
import ssl
import subprocess
import time
import urllib.request
import urllib.parse
from e2e import ROOT, free_port, wait_until
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--adb-server")
parser.add_argument("--serial")
parser.add_argument("--existing-device", help="Use a deployed gateway device; do not start a temporary agent")
parser.add_argument("--adb", default="adb")
parser.add_argument("--bin-dir", type=Path, default=ROOT / "bin")
parser.add_argument("--rust-dir", type=Path)
parser.add_argument("--relay-url", help="Use an already deployed wss:// relay instead of a temporary local server")
parser.add_argument("--connect-address", help="Optional origin host:port; TLS still verifies relay hostname")
parser.add_argument("--credentials-dir", type=Path)
args = parser.parse_args()
if args.existing_device and not args.relay_url:
parser.error('--existing-device requires --relay-url')
if not args.existing_device and (not args.adb_server or not args.serial):
parser.error('provide --adb-server and --serial, or use --existing-device')
device_id = args.existing_device or 'smoke-phone'
suffix = ".exe" if os.name == "nt" else ""
rust_dir = args.rust_dir or args.bin_dir
relay_port, local_port = free_port(), free_port()
server_url = args.relay_url or f"ws://127.0.0.1:{relay_port}"
endpoint = f"127.0.0.1:{local_port}"
env = os.environ.copy()
if args.relay_url:
if not args.relay_url.startswith('wss://'):
raise SystemExit('External relay smoke test requires wss://')
if args.credentials_dir:
for role in (('client',) if args.existing_device else ('agent', 'client')):
for line in (args.credentials_dir / (role + '.env')).read_text().splitlines():
name, separator, value = line.partition('=')
if separator and name in ('ADS_AGENT_TOKEN', 'ADS_CLIENT_TOKEN'):
env[name] = value
if not env.get('ADS_CLIENT_TOKEN') or (not args.existing_device and not env.get('ADS_AGENT_TOKEN')):
raise SystemExit('External relay requires role tokens in env or --credentials-dir')
if args.existing_device:
env.pop('ADS_AGENT_TOKEN', None)
else:
env["ADS_AGENT_TOKEN"] = secrets.token_hex(32)
env["ADS_CLIENT_TOKEN"] = secrets.token_hex(32)
env.pop('ADS_CONNECT_ADDRESS', None)
for key in ("ADB_SERVER_SOCKET", "ANDROID_ADB_SERVER_ADDRESS", "ANDROID_ADB_SERVER_PORT"):
env.pop(key, None)
folder = ROOT / "work" / "real-device"
folder.mkdir(parents=True, exist_ok=True)
processes, files = [], []
def start(name, command):
handle = open(folder / f"{name}.log", "wb")
files.append(handle)
process = subprocess.Popen([str(value) for value in command], env=env,
stdout=handle, stderr=subprocess.STDOUT,
creationflags=subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0)
processes.append(process)
def adb(*command):
return subprocess.run([args.adb, *command], env=env, capture_output=True,
text=True, timeout=10)
def leased():
if args.relay_url:
url = urllib.parse.urlsplit(args.relay_url)
connection = http.client.HTTPSConnection(url.hostname, url.port or 443, timeout=5)
if args.connect_address:
host, port = args.connect_address.rsplit(':', 1)
tcp = socket.create_connection((host, int(port)), timeout=5)
connection.sock = ssl.create_default_context().wrap_socket(tcp, server_hostname=url.hostname)
try:
connection.request('GET', url.path.rstrip('/') + '/v1/devices',
headers={'Authorization': 'Bearer ' + env['ADS_CLIENT_TOKEN']})
response = connection.getresponse()
if response.status != 200:
raise ConnectionError(f'Device query failed: HTTP {response.status}')
return any(device['id'] == device_id and device['busy'] for device in json.load(response))
finally:
connection.close()
request = urllib.request.Request(f"http://127.0.0.1:{relay_port}/v1/devices",
headers={"Authorization": "Bearer " + env["ADS_CLIENT_TOKEN"]})
with urllib.request.urlopen(request, timeout=2) as response:
return b'"busy":true' in response.read()
try:
if not args.relay_url:
start("server", [(args.bin_dir / f"ads-server{suffix}").resolve(), "--listen", f"127.0.0.1:{relay_port}"])
network_args = [] if args.relay_url else ['--allow-insecure']
if args.connect_address:
network_args += ['--connect-address', args.connect_address]
if not args.existing_device:
start("agent", [(rust_dir / f"ads-agent{suffix}").resolve(), "--server", server_url,
*network_args, "--device", device_id, "--adb-server", args.adb_server,
"--adb-serial", args.serial])
start("client", [(rust_dir / f"ads-client{suffix}").resolve(), "--server", server_url,
*network_args, "--device", device_id, "--listen", endpoint,
"--no-auto-connect"])
wait_until(leased, "remote phone lease", seconds=20)
print(adb("connect", endpoint).stdout.strip(), flush=True)
print("If requested, approve this computer's debugging key on the phone.", flush=True)
deadline = time.monotonic() + 20
while True:
state = adb("-s", endpoint, "get-state")
if state.returncode == 0 and state.stdout.strip() == "device":
break
if time.monotonic() >= deadline:
raise RuntimeError("Phone did not authorize local ADB: " + state.stderr.strip())
time.sleep(1)
listing = adb("devices", "-l")
assert listing.returncode == 0 and endpoint in listing.stdout
print(listing.stdout.strip())
model = adb("-s", endpoint, "shell", "getprop", "ro.product.model")
assert model.returncode == 0, model.stderr
marker = adb("-s", endpoint, "shell", "echo", "ads-read-only-smoke-ok")
assert marker.returncode == 0 and marker.stdout.strip() == "ads-read-only-smoke-ok", marker.stderr
print("PASS: ordinary local adb devices and remote shell via Go server + both Rust daemons")
print("Remote model:", model.stdout.strip())
finally:
try:
adb("disconnect", endpoint)
finally:
for process in reversed(processes):
if process.poll() is None:
process.terminate()
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
process.kill()
process.wait(timeout=5)
for handle in files:
handle.close()
if __name__ == "__main__":
main()