Files
werk/scripts/workbook_android_test.py
waoziandClaude Opus 5.5 aa6cc16955 Run Android input and document tests on a private emulator
scripts/private-emulator.py owns a disposable headless API 31 emulator.
android_startup.py launches Werkzeug and waits for visible Home; it waits
out only the System UI "isn't responding" dialog, so an app ANR still
fails. Its regression tests run in make test. The input, profile and
Workbook document-picker tests use it, find controls by text or content
description, and allow a cold system picker more time.

Local tests (on the final tree of this series, published pins, no local
overrides, through build-queue): make test including ziran fmt --check,
gui-smoke, gui-test, gallery-gui-test and web-smoke on private displays.
Not run on these pins: the private-emulator Android gate. On an earlier
pin the x86_64 APK built and validated and android-input-test passed
until Entity's add-node page, which needs Kryon's density damage fix
(78af4090); it runs with the next Kryon pin update.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 01:10:41 -03:00

254 lines
10 KiB
Python

"""Workbook editing and document transfers on an explicitly owned emulator."""
from pathlib import Path
import os
import re
import shlex
import subprocess
import time
import xml.etree.ElementTree as ET
from android_labels import label_position
from android_apk_check import check_apk
from android_startup import launch_home
root = Path(__file__).resolve().parents[1]
output = root / "build/workbook-android-test"
output.mkdir(parents=True, exist_ok=True)
serial = os.environ.get("WERK_ANDROID_EMULATOR", "")
if not serial and os.environ.get("CI"):
devices = subprocess.check_output(["adb", "devices"], text=True).splitlines()
serial = next((line.split()[0] for line in devices if line.startswith("emulator-") and line.split()[-1] == "device"), "")
assert serial.startswith("emulator-"), "Set WERK_ANDROID_EMULATOR to the private test emulator"
package = "xyz.waozi.pass"
apk = Path(os.environ.get("WERK_ANDROID_APK", root / "build/werk-android-emulator.apk"))
check_apk(apk)
def adb(*args, check=True, timeout=90):
command = ["adb", "-s", serial, *map(str, args)]
result = subprocess.run(command, capture_output=True, timeout=timeout)
if check and result.returncode:
# CalledProcessError's default traceback omits captured output, which
# is essential to distinguish a failed shell command from lost ADB.
raise RuntimeError(
f"{shlex.join(command)} exited {result.returncode}\n"
f"stdout: {result.stdout[-4000:].decode(errors='replace')}\n"
f"stderr: {result.stderr[-4000:].decode(errors='replace')}")
return result
def shell(*args, check=True):
return adb("shell", *args, check=check).stdout.decode()
def shot(name):
path = output / (name + ".png")
path.write_bytes(adb("exec-out", "screencap", "-p").stdout)
return path
def tap(x, y):
shell("input", "tap", round(x), round(y))
time.sleep(.25)
def label(word, scroll=False):
until = time.monotonic() + 20
swipes = 0
while time.monotonic() < until:
point = label_position(shot("label"), word)
if point:
tap(*point)
return
if scroll and swipes < 6:
shell("input", "swipe", width // 2, height * 3 // 4,
width // 2, height // 3, "450")
swipes += 1
time.sleep(.4)
time.sleep(.2)
raise AssertionError("Missing Workbook control: " + word)
def native_label(word):
# A cold Android document picker can take longer than in-app controls.
until = time.monotonic() + 90
while time.monotonic() < until:
path = "/data/local/tmp/werk-window.xml"
shell("rm", "-f", path, check=False)
shell("uiautomator", "dump", "--compressed", path, check=False)
data = shell("cat", path, check=False)
(output / "system-window.xml").write_text(data)
try:
nodes = ET.fromstring(data).iter("node")
except ET.ParseError:
nodes = []
for node in nodes:
if word.casefold() in (node.get("text", "").casefold(),
node.get("content-desc", "").casefold()):
bounds = list(map(int, re.findall(r"\d+", node.get("bounds", ""))))
if len(bounds) == 4:
tap((bounds[0] + bounds[2]) / 2, (bounds[1] + bounds[3]) / 2)
return
point = label_position(shot("system-control"), word)
if point:
tap(*point)
return
time.sleep(.2)
raise AssertionError("Missing system document control: " + word)
def document():
return shell("run-as", package, "cat", "files/apps/workbook/documents/workbook.gnumeric", check=False)
def expect(value, col=0):
until = time.monotonic() + 20
while time.monotonic() < until:
try:
doc = ET.fromstring(document())
cells = doc.iter("{http://www.gnumeric.org/v10.dtd}Cell")
if any(c.get("Row") == "0" and c.get("Col") == str(col) and (c.text or "") == value for c in cells):
return
except ET.ParseError:
pass
time.sleep(.2)
raise AssertionError("Workbook did not save fixture " + repr(value))
def hide_keyboard():
if "mInputShown=true" in shell("dumpsys", "input_method"):
shell("input", "keyevent", "4")
time.sleep(.4)
def edit(col, value):
try:
previous = next((cell.text or "" for cell in ET.fromstring(document()).iter(
"{http://www.gnumeric.org/v10.dtd}Cell")
if cell.get("Row") == "0" and cell.get("Col") == str(col)), "")
except ET.ParseError:
previous = ""
hide_keyboard()
x, y = (88 + col * 96) * zoom, top + 177 * zoom
tap(x, y)
tap(180 * zoom, top + 127 * zoom)
until = time.monotonic() + 10
while "mInputShown=true" not in shell("dumpsys", "input_method"):
if time.monotonic() > until:
raise AssertionError("Workbook did not focus Android's keyboard")
time.sleep(.2)
# These ASCII fixtures clear the actual framework editor through its
# caret and delete keys. ADB chord injection varies across Android APIs.
shell("input", "keyevent", "123", *["67" for _ in previous])
shell("input", "text", shlex.quote(value))
time.sleep(.5)
hide_keyboard()
tap(18 * zoom, top + 98 * zoom)
expect(value, col)
def file_menu():
hide_keyboard()
tap(28 * zoom, top + 68 * zoom)
def failure_diagnostics():
# Collect each item independently: screencap can fail for the same reason
# as the test. Neither that failure nor a timeout should hide the original
# exception or prevent the remaining diagnostics from being attempted.
commands = {
"adb-state.txt": ("get-state",),
"failure.png": ("exec-out", "screencap", "-p"),
"input-method.txt": ("shell", "dumpsys", "input_method"),
"saved-workbook.gnumeric": ("exec-out", "run-as", package, "cat", "files/apps/workbook/documents/workbook.gnumeric"),
"document-intents.txt": ("shell", "dumpsys", "activity", "activities"),
"crash-log.txt": ("logcat", "-d", "-b", "crash"),
"startup-log.txt": ("logcat", "-d", "-s", "Werkzeug:I", "art:E", "AndroidRuntime:E"),
"ui-task.dex": ("exec-out", "run-as", package, "cat", "files/ui-task.dex"),
"runtime-trace.txt": ("exec-out", "run-as", package, "cat", "files/runtime-trace.txt"),
}
errors = []
try:
pid = shell("pidof", package, check=False).strip()
if pid.isdigit():
commands["application-log.txt"] = ("logcat", "-d", "--pid=" + pid)
except Exception as error:
errors.append(f"pidof: {error!r}")
for name, command in commands.items():
try:
result = adb(*command, check=False)
if result.returncode:
errors.append(f"{name}: exit {result.returncode}\n"
f"stdout: {result.stdout[-4000:]!r}\n"
f"stderr: {result.stderr[-4000:]!r}")
else:
(output / name).write_bytes(result.stdout)
except Exception as error:
errors.append(f"{name}: {error!r}")
try:
(output / "diagnostic-errors.txt").write_text("\n".join(errors))
except OSError as error:
print(f"Could not save diagnostic errors: {error}", flush=True)
try:
# Package verification on a cold software guest can outlast ordinary ADB
# commands. Keep its separate deadline bounded and retain diagnostics.
adb("install", "-r", apk, timeout=300)
shell("am", "force-stop", package)
shell("run-as", package, "rm", "-rf", "files/apps/workbook", check=False)
shell("rm", "-f", "/sdcard/Download/workbook.gnumeric", check=False)
launch_home(adb, output, package, "launch")
width, height = map(int, shell("wm", "size").strip().split()[-1].split("x"))
# Native Kryon uses Android's configured density, independent of the
# display width. The private guest deliberately uses a wide viewport.
density = shell("wm", "density")
densities = re.findall(r"(?:Physical|Override) density:\s*(\d+)", density)
assert densities, "Android did not report its display density: " + density
zoom = int(densities[-1]) / 160
windows = shell("dumpsys", "window")
(output / "window-dump.txt").write_text(windows)
status = re.search(r"type=(?:statusBars|ITYPE_STATUS_BAR).*?frame=\[0,0\]\[\d+,(\d+)\]", windows)
top = int(status.group(1)) if status else round(24 * zoom)
label("Workbook", scroll=True)
edit(0, "12")
edit(1, "=A1*2")
shot("calculated")
assert shell("run-as", package, "stat", "-c", "%a", "files/apps/workbook/documents/workbook.gnumeric").strip() == "600"
shell("am", "force-stop", package)
launch_home(adb, output, package, "restart")
label("Workbook", scroll=True)
expect("12"); expect("=A1*2", 1)
original = document()
file_menu(); label("As")
# DocumentsUI remembers other apps' last folder. Choose the fixture's
# destination explicitly so a previous Gallery picker cannot redirect it.
native_label("Show roots")
native_label("Downloads")
native_label("Save")
until = time.monotonic() + 30
exported = ""
while time.monotonic() < until:
exported = shell("cat", "/sdcard/Download/workbook.gnumeric", check=False)
if exported == original:
break
time.sleep(.3)
assert exported == original, "Android export changed document bytes"
edit(0, "7")
file_menu(); label("Open")
native_label("Show roots")
native_label("Downloads")
native_label("workbook.gnumeric")
expect("12"); expect("=A1*2", 1)
assert shell("cat", "/sdcard/Download/workbook.gnumeric") == exported, "Import modified the selected source"
file_menu(); label("Open")
time.sleep(.5)
shell("input", "keyevent", "4")
time.sleep(.5)
expect("12")
edit(0, "9")
shot("transferred")
print("Workbook Android: IME editing, formulas, private save/restart, system document export/import and cancellation passed")
except BaseException:
failure_diagnostics()
raise