Files
werk/scripts/apps_gui_test.py
T

282 lines
13 KiB
Python

#!/usr/bin/env python3
"""Verify the configurable dashboard and native tool navigation."""
import csv
import hashlib
import io
import json
import os
import re
from pathlib import Path
import shutil
import subprocess
import time
from PIL import Image
assert os.environ.get("WERK_TEST_PRIVATE_DISPLAY") == "1", "Use private-display.py"
root = Path(__file__).resolve().parents[1]
work = Path(os.environ.get("WERK_APPS_TEST_OUTPUT", root / "build/apps-gui-test"))
binary = Path(os.environ.get("WERK_TEST_BINARY", root / "build/werk"))
assets = Path(os.environ.get("WERK_TEST_ASSETS", root / "build"))
shutil.rmtree(work, ignore_errors=True)
work.mkdir(parents=True)
expected = (root / "apps-controller.sha256").read_text().strip()
assert hashlib.sha256((assets / "apps/apps.zx").read_bytes()).hexdigest() == expected
environment = dict(os.environ, HOME=str(work / "home"), WERK_DATA=str(work / "data"),
WERK_ASSETS=str(assets), ENTITY_DATA=str(work / "entity"),
XDG_CONFIG_HOME=str(work / "config"), XDG_DATA_HOME=str(work / "share"),
XDG_CACHE_HOME=str(work / "cache"))
for name in ("HOME", "WERK_DATA", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME"):
Path(environment[name]).mkdir(parents=True)
profile = Path(environment["WERK_DATA"]) / "profile"
profile.mkdir()
(profile / "settings.txt").write_text("name=Fixture Person\ntheme_mode=1\n")
def command(*arguments, timeout=20):
return subprocess.check_output(arguments, env=environment, text=True, timeout=timeout)
def recognize(picture, *options):
return command("tesseract", str(picture), "stdout", "--psm", "11", *options, timeout=75)
def capture_variants(name):
time.sleep(.3)
picture = work / (name + ".png")
command("import", "-window", window, str(picture))
# Separate dark text from the soft card fills for reliable recognition.
with Image.open(picture) as source:
labels = source.convert("L").point(lambda value: 0 if value < 140 else 255)
labels.resize((source.width * 3, source.height * 3)).save(work / "labels.png")
source.resize((source.width * 3, source.height * 3)).save(work / "full-text.png")
# Keep both views: thresholding can erase thin strokes at narrow sizes.
return work / "labels.png", work / "full-text.png"
def capture(name):
return "\n".join(recognize(picture) for picture in capture_variants(name))
def click(x, y):
command("xdotool", "mousemove", "--window", window, str(x), str(y))
# XTEST updates the private display's physical button state. XSendEvent
# (--window) cannot represent a held press to the native SDL sampler.
command("xdotool", "mousedown", "1")
time.sleep(.2) # Keep the press visible to the native frame sampler.
command("xdotool", "mouseup", "1")
time.sleep(.2)
def word_position(word):
for picture in capture_variants("control"):
text = recognize(picture, "-c", "tessedit_create_tsv=1")
for item in csv.DictReader(io.StringIO(text), delimiter="\t"):
if item["text"].strip() == word:
return ((int(item["left"]) + int(item["width"]) // 2) // 3,
(int(item["top"]) + int(item["height"]) // 2) // 3)
raise AssertionError("Missing visible app control: " + word)
def click_word(word):
click(*word_position(word))
def key(value):
command("xdotool", "key", "--clearmodifiers", value)
time.sleep(.2)
def type_text(value):
command("xdotool", "type", "--clearmodifiers", "--delay", "30", value)
time.sleep(.3)
def expect_title(expected):
deadline = time.monotonic() + 10
while time.monotonic() < deadline:
assert app.poll() is None, "Werkzeug exited during navigation"
title = command("xdotool", "getwindowname", window).strip()
if title == expected:
return
time.sleep(.1)
capture("navigation-failure")
raise AssertionError(f"Expected window title {expected!r}, got {title!r}")
app = subprocess.Popen([str(binary)], env=environment)
try:
deadline = time.monotonic() + 30
window = None
while time.monotonic() < deadline:
assert app.poll() is None, "Werkzeug exited during startup"
found = subprocess.run(["xdotool", "search", "--onlyvisible", "--pid", str(app.pid)],
env=environment, capture_output=True, text=True, timeout=5)
if found.returncode == 0:
window = found.stdout.splitlines()[0]
break
time.sleep(.1)
assert window, "Werkzeug did not show its owned window"
command("xdotool", "windowfocus", "--sync", window)
# Window creation precedes loading the portable apps and the first frame.
deadline = time.monotonic() + 20
while True:
home = capture("home")
if all(name in home for name in ("Pass", "Auth", "Calculator", "Clock", "Calendar", "Workbook", "Gallery", "Task")):
break
assert app.poll() is None, "Werkzeug exited while loading Apps"
assert time.monotonic() < deadline, "Home dashboard did not render: " + home
assert "Pinned tools" not in home, home
assert not re.search(r"\d[\d.]*\s*(?:kB|MB)\b", home, re.I), home
pictures = work / "cache/werk/apps/entity/assets/entity"
expected_pictures = {"abstract-amber.webp", "abstract-jade.webp", "abstract-violet.webp",
"flowers.webp", "pfp.webp", "wurm-base.webp", "wurm-reward-skins.webp",
"wurm-skins.webp", "wurm-special-skins.webp", "jungle-tiger.png",
"jungle-toucan.png", "wurm.png"}
expected_pictures.update(f"shovey-{index}.png" for index in range(8))
assert {path.name for path in pictures.glob("*")} == expected_pictures, "Entity's bundled picture resources were not extracted"
picture_diagnostics = []
for path in sorted(pictures.iterdir()):
assert path.stat().st_mode & 0o777 == 0o600, path.name
with Image.open(path) as image:
image.load()
picture_diagnostics.append({'resource': path.name, 'size': image.size,
'private': True})
(work / 'entity-resource-diagnostics.json').write_text(json.dumps({
'fixture_only': True, 'bundle': 'entity',
'extraction_path': 'assets/entity', 'decoded': picture_diagnostics,
}, indent=2) + '\n')
click_word("Calculator")
expect_title("Calculator")
type_text("37+58")
key("Return")
result = capture("calculator-result")
assert re.search(r"^\s*95\s*$", result, re.M), result
click(28, 28)
expect_title("Werkzeug")
click_word("Calculator")
expect_title("Calculator")
reopened = capture("calculator-reopened")
assert re.search(r"^\s*95\s*$", reopened, re.M), reopened
click(28, 28)
expect_title("Werkzeug")
for name in ("Auth", "Clock", "Calendar", "Workbook", "Gallery", "Pass"):
click_word(name)
expect_title(name)
assert "stopped" not in capture(name.lower()).lower(), name + " failed to run"
click(28, 28)
expect_title("Werkzeug")
click_word("Task")
expect_title("Task Manager")
assert "stopped" not in capture("taskmgr").lower(), "Task Manager failed to run"
click(28, 28)
expect_title("Werkzeug")
for width, height in ((360, 640), (720, 520)):
command("xdotool", "windowsize", "--sync", window, str(width), str(height))
text = capture(f"home-{width}")
assert all(name in text for name in ("Pass", "Clock", "Calendar", "Edit")), text
_, nav_y = word_position("Calculator")
assert nav_y > height - 80, "Navigation is not anchored to the bottom"
if width == 720:
command("xdotool", "mousemove", "--window", window, "200", "200")
command("xdotool", "click", "--repeat", "4", "--delay", "100", "5")
time.sleep(.3)
assert abs(word_position("Calculator")[1] - nav_y) <= 2, "Navigation scrolled with widgets"
command("xdotool", "click", "--repeat", "8", "--delay", "50", "4")
command("xdotool", "windowsize", "--sync", window, "420", "760")
time.sleep(.3)
preferences = profile / "home.json"
original_apps = (profile / "apps.json").read_bytes() if (profile / "apps.json").exists() else None
def mode(tool, x):
_, y = word_position(tool)
click(x, y + 18)
# A cancelled draft must leave both the screen and storage unchanged.
click_word("Edit")
assert "Customize" in capture("editor")
mode("Clock", 360) # Hidden
mode("Pass", 293) # Pinned
assert not preferences.exists(), "Draft was written before Done"
click_word("Cancel")
assert "Clock" in capture("cancelled")
assert not preferences.exists(), "Cancel created a saved layout"
click_word("Edit")
mode("Clock", 360)
mode("Pass", 293)
# Drag Clock past Calendar. This exercises Kryon's retained drag capture.
_, clock_y = word_position("Clock")
command("xdotool", "mousemove", "--window", window, "35", str(clock_y))
command("xdotool", "mousedown", "1")
time.sleep(.2)
for offset in range(20, 141, 20):
command("xdotool", "mousemove", "--window", window, "35", str(clock_y + offset))
time.sleep(.08)
command("xdotool", "mouseup", "1")
time.sleep(.3)
capture("reordered-editor")
click_word("Done")
saved = json.loads(preferences.read_text())
by_id = {entry["id"]: entry["mode"] for entry in saved["order"]}
assert by_id["clock"] == 0 and by_id["pass"] == 1, saved
assert saved["order"][0]["id"] == "calendar", saved
assert len(by_id) == 8 and "entity" not in by_id, saved
assert preferences.stat().st_mode & 0o777 == 0o600
assert profile.stat().st_mode & 0o777 == 0o700
current_apps = (profile / "apps.json").read_bytes() if (profile / "apps.json").exists() else None
assert current_apps == original_apps, "Dashboard changed unrelated launcher preferences"
assert "Clock" not in capture("saved-layout")
# Restart only this disposable test process and verify the saved modes.
app.terminate()
app.wait(timeout=10)
app = subprocess.Popen([str(binary)], env=environment)
deadline = time.monotonic() + 30
while True:
found = subprocess.run(["xdotool", "search", "--onlyvisible", "--pid", str(app.pid)],
env=environment, capture_output=True, text=True, timeout=5)
if found.returncode == 0:
window = found.stdout.splitlines()[0]
command("xdotool", "windowsize", "--sync", window, "420", "760")
command("xdotool", "windowfocus", "--sync", window)
text = capture("restarted")
if "Calendar" in text and "Edit" in text:
assert "Clock" not in text, text
break
assert time.monotonic() < deadline, "Dashboard preferences did not survive restart"
time.sleep(.1)
click_word("Edit")
assert "Clock" in capture("hidden-tool-in-editor")
mode("Clock", 228) # Widget
clock_position = next(at for at, entry in enumerate(saved["order"]) if entry["id"] == "clock")
_, clock_y = word_position("Clock")
click(102, clock_y + 34) # The row's Move up control.
click_word("Done")
assert "Clock" in capture("restored-widget")
assert json.loads(preferences.read_text())["order"][clock_position - 1]["id"] == "clock"
assert next(entry for entry in json.loads(preferences.read_text())["order"] if entry["id"] == "clock")["mode"] == 2
click_word("Edit")
click_word("Reset")
click_word("Done")
reset = json.loads(preferences.read_text())["order"]
assert [entry["id"] for entry in reset] == ["clock", "calendar", "pass", "gallery", "auth", "calculator", "workbook", "taskmgr"], reset
assert [entry["mode"] for entry in reset] == [2, 2, 2, 2, 1, 1, 1, 1], reset
# Every tool can join the bottom dock, including a second row on a phone.
click_word("Edit")
for name in ("Clock", "Calendar", "Pass", "Gallery", "Auth", "Calculator", "Workbook", "Task"):
mode(name, 293)
click_word("Done")
all_pinned = capture("all-navigation")
assert all(name in all_pinned for name in ("Clock", "Calendar", "Pass", "Gallery", "Auth", "Calculator", "Workbook", "Task")), all_pinned
assert all(entry["mode"] == 1 for entry in json.loads(preferences.read_text())["order"])
click_word("Edit")
click_word("Reset")
click_word("Done")
capture("home")
print("Dashboard: fixed bottom navigation, modes, draft cancel, drag and arrow reorder, private persistence, reset, eight tools, navigation, Entity artwork and responsive layouts verified locally")
finally:
if app.poll() is None:
app.terminate()
app.wait(timeout=10)