ui_monkey.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. #!/usr/bin/env python3
  2. """Seeded UI monkey test of the real LYNX window (round 190rb, the 0.1.32 quality release).
  3. Starts `LYNX --demo [project]` on an X display (a private Xvfb), then drives it for a while with a seeded random mix of
  4. real X input (xdotool: clicks, right-clicks, drags, wheel, keys) and structured Remote Control / --demo operations
  5. (docs/DEMO_MODE.md: click a random showing control, run a random key-map action, switch layouts, open panels and
  6. editors, undo / redo, save and reload). Every action is written to <out>/actions.jsonl *before* it runs, fully resolved
  7. (coordinates, control IDs), so `--replay <actions.jsonl>` repeats a run without the random generator.
  8. It stops at the first crash (the process died: its exit code and the sanitizer reports in <out>/san.*), a hang (the
  9. API stopped answering for --hang-seconds: SIGABRT, so ASan prints the main thread's stack) or the time limit.
  10. <out>/result.json says which. Run it inside a sandbox where the files that matter are read-only
  11. (scripts/ui-monkey.sh does): random clicks reach Save as..., the file browser and every other menu item.
  12. ui_monkey.py --app LYNX --display :190 --seed 7 --minutes 5 --layout pattern --project song.flp --out runs/s7
  13. ui_monkey.py --app LYNX --display :190 --replay runs/s7/actions.jsonl --out runs/s7-replay
  14. """
  15. import argparse
  16. import json
  17. import os
  18. from pathlib import Path
  19. import random
  20. import signal
  21. import subprocess
  22. import sys
  23. import time
  24. sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "examples"))
  25. from remote_control import Client # noqa: E402 (the repo's standard-library client)
  26. LAYOUTS = ["pattern", "clipLaunch", "simple"]
  27. PANELS = ["channelRack", "pianoRoll", "playlist", "mixer", "browser", "loops", "dock", "pluginManager", "versions"]
  28. # keys a user presses (FL's and LYNX's shortcuts among them); no Alt+F4 (it would only end the run early)
  29. KEYS = ["Escape", "Escape", "Return", "space", "Tab", "Delete", "BackSpace", "Left", "Right", "Up", "Down", "Home", "End",
  30. "Prior", "Next", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12",
  31. "ctrl+z", "ctrl+y", "ctrl+shift+z", "alt+z", "ctrl+c", "ctrl+v", "ctrl+x", "ctrl+a", "ctrl+d", "ctrl+b",
  32. "ctrl+l", "ctrl+n", "ctrl+o", "ctrl+s", "ctrl+shift+s", "ctrl+t", "ctrl+f", "ctrl+e", "ctrl+r", "ctrl+i",
  33. "shift+Delete", "shift+Left", "shift+Right", "ctrl+Left", "ctrl+Right", "ctrl+Up", "ctrl+Down", "ctrl+Insert",
  34. "ctrl+alt+Insert", "shift+Insert", "Insert", "plus", "minus", "ctrl+plus", "ctrl+minus", "Menu",
  35. "a", "b", "c", "d", "e", "g", "l", "m", "n", "p", "q", "r", "s", "t", "u", "w", "x", "y", "z",
  36. "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "alt+1", "alt+2", "alt+3", "ctrl+1", "ctrl+2", "shift+1"]
  37. WEIGHTS = {
  38. "api_click": 22, "x_click": 16, "x_drag": 8, "x_wheel": 7, "x_key": 13, "action": 10, "escape": 6, "show": 5,
  39. "undo_redo": 5, "editor": 3, "api_drag": 3, "layout": 2, "save_reload": 1, "open": 1, "repaint": 1,
  40. }
  41. class Monkey:
  42. def __init__(self, a):
  43. self.a = a
  44. self.out = Path(a.out).resolve()
  45. self.out.mkdir(parents=True, exist_ok=True)
  46. self.profile = self.out / "profile"
  47. self.profile.mkdir(exist_ok=True)
  48. (self.profile / "control").mkdir(mode=0o700, exist_ok=True) # (the discovery folder must be private)
  49. os.chmod(self.profile / "control", 0o700)
  50. self.log = open(self.out / "actions.jsonl", "a", buffering=1)
  51. self.proc = None
  52. self.client = None
  53. self.controls = []
  54. self.controls_at = -99
  55. self.window = None
  56. self.actions = self.load_actions()
  57. self.saves = 0
  58. self.count = 0
  59. # --- process ---------------------------------------------------------------------------------------------------
  60. def env(self):
  61. e = dict(os.environ)
  62. san = str(self.out / "san")
  63. e.update({
  64. "DISPLAY": self.a.display, "LYNX_PROFILE_DIR": str(self.profile), "XDG_CONFIG_HOME": str(self.profile / "config"),
  65. "XDG_DATA_HOME": str(self.profile / "data"), "XDG_CACHE_HOME": str(self.profile / "cache"),
  66. "LYNX_CONTROL_ENABLED": "1", "LYNX_CONTROL_DISCOVERY": str(self.profile / "control/connection.json"),
  67. "ASAN_OPTIONS": e.get("ASAN_OPTIONS", "") + f":log_path={san}.asan:handle_abort=1:detect_leaks=0",
  68. "UBSAN_OPTIONS": e.get("UBSAN_OPTIONS", "print_stacktrace=1:halt_on_error=0") + f":log_path={san}.ubsan",
  69. })
  70. e.pop("WAYLAND_DISPLAY", None)
  71. return e
  72. def start(self, project):
  73. args = [self.a.app, "--demo"] + ([project] if project else [])
  74. self.stdout = open(self.out / "lynx.out", "ab")
  75. self.proc = subprocess.Popen(args, env=self.env(), stdin=subprocess.DEVNULL, stdout=self.stdout, stderr=subprocess.STDOUT,
  76. cwd=str(self.out))
  77. disc = self.profile / "control/connection.json"
  78. deadline = time.time() + self.a.start_seconds
  79. while time.time() < deadline:
  80. if self.proc.poll() is not None:
  81. return False
  82. if disc.exists():
  83. try:
  84. self.client = Client(disc)
  85. self.call("ui.window", timeout_ok=True)
  86. return True
  87. except Exception:
  88. pass
  89. time.sleep(0.5)
  90. return False
  91. def alive(self):
  92. return self.proc is not None and self.proc.poll() is None
  93. def call(self, op, args=None, timeout_ok=False):
  94. try:
  95. return self.client.call(op, args or {})
  96. except RuntimeError as e: # an error answer: a refused operation is fine for a monkey
  97. return {"error": str(e)[:200]}
  98. except OSError as e:
  99. if timeout_ok:
  100. raise
  101. return {"oserror": str(e)[:200]}
  102. # --- helpers ---------------------------------------------------------------------------------------------------
  103. def load_actions(self):
  104. f = Path(__file__).resolve().parent.parent / "src/core/KeyMap.cpp"
  105. import re
  106. ids = sorted(set(re.findall(r'\{\s*"([a-z]+\.[A-Za-z0-9.]+)"', f.read_text(errors="replace")))) if f.exists() else []
  107. return ids or ["edit.undo", "edit.redo"]
  108. def xdo(self, *args):
  109. subprocess.run([self.a.xdotool] + [str(x) for x in args], env={**os.environ, "DISPLAY": self.a.display},
  110. stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=20)
  111. def win(self, rng):
  112. if self.window is None or rng.random() < 0.05:
  113. r = self.call("ui.window")
  114. s = r.get("screen") if isinstance(r, dict) else None
  115. if isinstance(s, dict):
  116. self.window = (s.get("x", 0), s.get("y", 0), max(200, s.get("width", 1600)), max(200, s.get("height", 900)))
  117. elif isinstance(s, list) and len(s) == 4:
  118. self.window = tuple(s)
  119. return self.window or (0, 0, 1600, 900)
  120. def point(self, rng):
  121. x, y, w, h = self.win(rng)
  122. return int(x + rng.random() * w), int(y + rng.random() * h)
  123. def control(self, rng):
  124. if self.count - self.controls_at > 8 or not self.controls:
  125. r = self.call("ui.list", {"limit": 2000})
  126. self.controls = [c for c in (r.get("controls") or []) if isinstance(c, dict) and c.get("id")] if isinstance(r, dict) else []
  127. self.controls_at = self.count
  128. return rng.choice(self.controls) if self.controls else None
  129. # --- one random action, resolved to a replayable record --------------------------------------------------------
  130. def plan(self, rng):
  131. kind = rng.choices(list(WEIGHTS), weights=list(WEIGHTS.values()))[0]
  132. if kind == "api_click":
  133. c = self.control(rng)
  134. if c is None:
  135. return {"k": "escape"}
  136. return {"k": kind, "target": c["id"], "right": rng.random() < 0.2, "double": rng.random() < 0.1,
  137. "at": {"x": round(rng.random(), 3), "y": round(rng.random(), 3)}}
  138. if kind == "api_drag":
  139. c1, c2 = self.control(rng), self.control(rng)
  140. if c1 is None or c2 is None:
  141. return {"k": "escape"}
  142. return {"k": kind, "from": c1["id"], "to": c2["id"], "dx": rng.randint(-80, 80), "dy": rng.randint(-40, 40),
  143. "mods": rng.choice([[], [], ["ctrl"], ["shift"], ["alt"]])}
  144. if kind == "x_click":
  145. x, y = self.point(rng)
  146. return {"k": kind, "x": x, "y": y, "button": rng.choice([1, 1, 1, 3]), "repeat": rng.choice([1, 1, 1, 2]),
  147. "mod": rng.choice(["", "", "", "ctrl", "shift", "alt"])}
  148. if kind == "x_drag":
  149. x, y = self.point(rng)
  150. return {"k": kind, "x": x, "y": y, "x2": x + rng.randint(-400, 400), "y2": y + rng.randint(-250, 250),
  151. "button": rng.choice([1, 1, 3]), "mod": rng.choice(["", "", "ctrl", "shift", "alt"]), "steps": rng.randint(2, 12)}
  152. if kind == "x_wheel":
  153. x, y = self.point(rng)
  154. return {"k": kind, "x": x, "y": y, "button": rng.choice([4, 5, 6, 7]), "n": rng.randint(1, 8),
  155. "mod": rng.choice(["", "", "ctrl", "shift", "alt"])}
  156. if kind == "x_key":
  157. return {"k": kind, "key": rng.choice(KEYS)}
  158. if kind == "action":
  159. return {"k": kind, "id": rng.choice(self.actions)}
  160. if kind == "show":
  161. return {"k": kind, "panel": rng.choice(PANELS)}
  162. if kind == "undo_redo":
  163. return {"k": kind, "seq": [rng.choice(["edit.undo", "edit.undo", "edit.redo"]) for _ in range(rng.randint(1, 6))]}
  164. if kind == "editor":
  165. return {"k": kind, "channel": rng.randint(0, 20)}
  166. if kind == "layout":
  167. return {"k": kind, "style": rng.choice(LAYOUTS)}
  168. if kind == "save_reload":
  169. self.saves += 1
  170. return {"k": kind, "path": str(self.out / f"save{self.saves}.lynx")}
  171. if kind == "open":
  172. return {"k": kind, "file": rng.choice(self.a.projects)} if self.a.projects else {"k": "escape"}
  173. return {"k": kind}
  174. def run_action(self, act):
  175. k = act["k"]
  176. if k == "api_click":
  177. self.call("ui.click", {"target": act["target"], "right": act["right"], "double": act["double"], "at": act["at"]})
  178. elif k == "api_drag":
  179. self.call("ui.drag", {"from": {"target": act["from"]}, "to": {"target": act["to"], "dx": act["dx"], "dy": act["dy"]},
  180. "mods": act["mods"], "seconds": 0.3})
  181. time.sleep(0.35)
  182. elif k == "x_click":
  183. self.xdo("mousemove", act["x"], act["y"])
  184. if act["mod"]:
  185. self.xdo("keydown", act["mod"])
  186. self.xdo("click", "--repeat", act["repeat"], "--delay", 60, act["button"])
  187. if act["mod"]:
  188. self.xdo("keyup", act["mod"])
  189. elif k == "x_drag":
  190. self.xdo("mousemove", act["x"], act["y"])
  191. if act["mod"]:
  192. self.xdo("keydown", act["mod"])
  193. self.xdo("mousedown", act["button"])
  194. for i in range(1, act["steps"] + 1):
  195. t = i / act["steps"]
  196. self.xdo("mousemove", int(act["x"] + (act["x2"] - act["x"]) * t), int(act["y"] + (act["y2"] - act["y"]) * t))
  197. self.xdo("mouseup", act["button"])
  198. if act["mod"]:
  199. self.xdo("keyup", act["mod"])
  200. elif k == "x_wheel":
  201. self.xdo("mousemove", act["x"], act["y"])
  202. if act["mod"]:
  203. self.xdo("keydown", act["mod"])
  204. self.xdo("click", "--repeat", act["n"], "--delay", 30, act["button"])
  205. if act["mod"]:
  206. self.xdo("keyup", act["mod"])
  207. elif k == "x_key":
  208. self.xdo("key", "--clearmodifiers", act["key"])
  209. elif k == "escape":
  210. self.xdo("key", "Escape")
  211. elif k == "action":
  212. self.call("ui.action", {"id": act["id"]})
  213. elif k == "show":
  214. self.call("ui.show", {"panel": act["panel"]})
  215. elif k == "undo_redo":
  216. for a in act["seq"]:
  217. self.call("ui.action", {"id": a})
  218. elif k == "editor":
  219. self.call("ui.editor", {"channel": act["channel"]})
  220. elif k == "layout":
  221. self.call("ui.layout", {"style": act["style"]})
  222. self.controls = []
  223. elif k == "save_reload":
  224. r = self.call("file.save", {"path": act["path"]})
  225. if Path(act["path"]).exists():
  226. self.call("ui.open", {"file": act["path"]})
  227. elif k == "open":
  228. self.call("ui.open", {"file": act["file"]})
  229. self.controls = []
  230. elif k == "repaint":
  231. self.call("ui.repaint")
  232. elif k == "welcome":
  233. self.call("ui.welcome", {"choice": act["choice"]})
  234. elif k == "start_layout":
  235. self.call("ui.layout", {"style": act["style"]})
  236. # --- the run ---------------------------------------------------------------------------------------------------
  237. def responsive(self):
  238. t0 = time.time()
  239. while time.time() - t0 < self.a.hang_seconds:
  240. if not self.alive():
  241. return True # (dead, not hung: the caller sees it)
  242. try:
  243. self.client.call("ui.window", {})
  244. return True
  245. except RuntimeError:
  246. return True
  247. except OSError:
  248. time.sleep(1)
  249. return False
  250. def finish(self, status, detail=""):
  251. rc = self.proc.poll() if self.proc else None
  252. if status == "hang" and self.alive():
  253. os.kill(self.proc.pid, signal.SIGABRT) # ASan (handle_abort=1) prints where the main thread is
  254. try:
  255. self.proc.wait(30)
  256. except subprocess.TimeoutExpired:
  257. self.proc.kill()
  258. rc = self.proc.poll()
  259. elif status == "timeout" and self.alive():
  260. # the app's own shutdown (engine, plugins, windows torn down in order) is part of the test
  261. self.log.write(json.dumps({"k": "quit", "n": self.count, "t": round(time.time() - self.t0, 2)}) + "\n")
  262. answer = self.call("app.quit", {"discard": True})
  263. terminated = not (isinstance(answer, dict) and answer.get("quitting"))
  264. if terminated:
  265. self.proc.terminate() # (an older build without app.quit)
  266. try:
  267. rc = self.proc.wait(self.a.quit_seconds)
  268. if rc != 0 and not terminated:
  269. status, detail = "quit-crash", f"exit code {rc} on quit"
  270. except subprocess.TimeoutExpired:
  271. status, detail = "exit-hang", f"did not quit within {self.a.quit_seconds} s of app.quit"
  272. os.kill(self.proc.pid, signal.SIGABRT)
  273. try:
  274. self.proc.wait(30)
  275. except subprocess.TimeoutExpired:
  276. self.proc.kill()
  277. rc = self.proc.poll()
  278. reports = sorted(p.name for p in self.out.glob("san.*"))
  279. result = {"status": status, "detail": detail, "actions": self.count, "rc": rc, "seed": self.a.seed,
  280. "layout": self.a.layout, "project": self.a.project, "sanitizer_reports": reports,
  281. "seconds": round(time.time() - self.t0, 1)}
  282. (self.out / "result.json").write_text(json.dumps(result, indent=1))
  283. print(json.dumps(result))
  284. return 0 if status == "timeout" and not reports else 1 # (a quit that crashed or hung is a failure too)
  285. def main(self):
  286. self.t0 = time.time()
  287. if not self.start(self.a.project):
  288. return self.finish("start-failed" if self.alive() else "crash", "no API answer after start")
  289. replay = None
  290. if self.a.replay:
  291. replay = [json.loads(l) for l in open(self.a.replay) if l.strip()]
  292. else:
  293. first = [{"k": "welcome", "choice": "skip"}, {"k": "start_layout", "style": self.a.layout}]
  294. replay_head = first
  295. rng = random.Random(self.a.seed)
  296. end = self.t0 + self.a.minutes * 60
  297. queue = list(replay) if replay is not None else list(replay_head)
  298. while True:
  299. if replay is not None and (not queue or queue[0].get("k") == "quit"):
  300. return self.finish("timeout", "replay finished")
  301. if replay is None and time.time() > end:
  302. return self.finish("timeout")
  303. act = queue.pop(0) if queue else self.plan(rng)
  304. act.setdefault("n", self.count)
  305. act["t"] = round(time.time() - self.t0, 2)
  306. self.log.write(json.dumps(act) + "\n")
  307. self.count += 1
  308. try:
  309. self.run_action(act)
  310. except subprocess.TimeoutExpired:
  311. pass
  312. time.sleep(self.a.delay)
  313. if not self.alive():
  314. return self.finish("crash", f"died after action {act['n']} ({act['k']})")
  315. if self.count % 10 == 0 and not self.responsive():
  316. return self.finish("hang", f"no API answer for {self.a.hang_seconds} s after action {act['n']}")
  317. def parse():
  318. p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
  319. p.add_argument("--app", required=True)
  320. p.add_argument("--display", required=True)
  321. p.add_argument("--out", required=True)
  322. p.add_argument("--seed", type=int, default=1)
  323. p.add_argument("--minutes", type=float, default=5)
  324. p.add_argument("--layout", default="pattern", choices=LAYOUTS)
  325. p.add_argument("--project", default="")
  326. p.add_argument("--projects", nargs="*", default=[], help="files the 'open' action picks from")
  327. p.add_argument("--replay", default="")
  328. p.add_argument("--delay", type=float, default=0.08, help="seconds after each action")
  329. p.add_argument("--hang-seconds", type=float, default=45)
  330. p.add_argument("--start-seconds", type=float, default=240)
  331. p.add_argument("--quit-seconds", type=float, default=120)
  332. p.add_argument("--xdotool", default="xdotool")
  333. return p.parse_args()
  334. if __name__ == "__main__":
  335. sys.exit(Monkey(parse()).main())