runner.py 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080
  1. #!/usr/bin/env python3
  2. """Deterministic Android debug scenario runner for Legado."""
  3. from __future__ import annotations
  4. import argparse
  5. import base64
  6. import datetime as dt
  7. import hashlib
  8. import json
  9. from pathlib import Path
  10. import re
  11. import shutil
  12. import subprocess
  13. import sys
  14. import time
  15. from typing import Any, Callable, Sequence
  16. import xml.etree.ElementTree as ET
  17. import zipfile
  18. EXIT_ASSERTION = 1
  19. EXIT_CRASH = 2
  20. EXIT_BUILD = 3
  21. EXIT_ENVIRONMENT = 4
  22. EXIT_SCENARIO = 5
  23. PACKAGE = "io.legato.kazusa.debug"
  24. DEBUG_ACTIVITY = "io.legado.app.debug.DebugScenarioActivity"
  25. MAIN_ACTIVITY = "io.legado.app.ui.main.MainActivity"
  26. SOURCE_EDIT_ACTIVITY = "io.legado.app.ui.book.source.edit.BookSourceEditActivity"
  27. SOURCE_MANAGE_ACTIVITY = "io.legado.app.ui.book.source.manage.BookSourceActivity"
  28. THEME_MANIFEST_PATH = "manifest.json"
  29. THEME_ASSET_REMOTE = f"/sdcard/Android/data/{PACKAGE}/files/debug-theme-assets/background.png"
  30. SCRIPT_DIR = Path(__file__).resolve().parent
  31. PROJECT_ROOT = SCRIPT_DIR.parent.parent
  32. THEME_ASSET_FIXTURE = PROJECT_ROOT / "app" / "src" / "main" / "assets" / "web" / "uploadBook" / "img" / "close.png"
  33. SCENARIO_ROOT = SCRIPT_DIR / "scenarios"
  34. RUN_ROOT = PROJECT_ROOT / ".debug-runs"
  35. FIXTURE_ROOT = PROJECT_ROOT / "app" / "src" / "debug" / "assets" / "debug-fixtures"
  36. # Capability registries. New bug scenarios extend the tool by registering an
  37. # entry / action / assertion below, never by editing execute() or
  38. # validate_scenario(). See the classes near the end of this module.
  39. ENTRIES: dict[str, "Entry"] = {}
  40. ACTIONS: dict[str, "Action"] = {}
  41. ASSERTIONS: dict[str, Callable[["Context"], bool]] = {}
  42. class ScenarioError(ValueError):
  43. pass
  44. class CommandError(RuntimeError):
  45. def __init__(self, command: Sequence[str], result: subprocess.CompletedProcess[str]):
  46. self.command = list(command)
  47. self.result = result
  48. super().__init__(f"command failed ({result.returncode}): {' '.join(command)}")
  49. def load_scenario(name: str) -> dict[str, Any]:
  50. if not re.fullmatch(r"[a-z0-9][a-z0-9/_-]*", name):
  51. raise ScenarioError(f"invalid scenario name: {name}")
  52. path = (SCENARIO_ROOT / f"{name}.json").resolve()
  53. if SCENARIO_ROOT.resolve() not in path.parents or not path.is_file():
  54. raise ScenarioError(f"scenario not found: {name}")
  55. try:
  56. scenario = json.loads(path.read_text(encoding="utf-8"))
  57. except (OSError, json.JSONDecodeError) as error:
  58. raise ScenarioError(f"cannot read scenario {name}: {error}") from error
  59. validate_scenario(scenario, name)
  60. return scenario
  61. def validate_scenario(scenario: Any, requested_name: str | None = None) -> None:
  62. if not isinstance(scenario, dict):
  63. raise ScenarioError("scenario root must be an object")
  64. if scenario.get("schemaVersion") != 1:
  65. raise ScenarioError("schemaVersion must be 1")
  66. name = scenario.get("name")
  67. if not isinstance(name, str) or not name:
  68. raise ScenarioError("name must be a non-empty string")
  69. if requested_name is not None and name != requested_name:
  70. raise ScenarioError(f"scenario name mismatch: expected {requested_name}, got {name}")
  71. fixture = scenario.get("fixture")
  72. if not isinstance(fixture, str) or not re.fullmatch(r"[a-z0-9][a-z0-9-]*", fixture):
  73. raise ScenarioError("fixture must be a lowercase ID")
  74. marker = scenario.get("readyMarker")
  75. if not isinstance(marker, str) or not marker.strip():
  76. raise ScenarioError("readyMarker must be a non-empty string")
  77. timeout = scenario.get("readyTimeoutSeconds", 30)
  78. if not isinstance(timeout, int) or timeout < 1 or timeout > 300:
  79. raise ScenarioError("readyTimeoutSeconds must be between 1 and 300")
  80. change_timeout = scenario.get("contentChangeTimeoutSeconds", 5)
  81. if not isinstance(change_timeout, int) or change_timeout < 1 or change_timeout > 30:
  82. raise ScenarioError("contentChangeTimeoutSeconds must be between 1 and 30")
  83. record = scenario.get("record", False)
  84. if not isinstance(record, bool):
  85. raise ScenarioError("record must be a boolean")
  86. validate_preferences(scenario.get("preferences"))
  87. entry = scenario.get("entry")
  88. if not isinstance(entry, dict) or entry.get("type") not in ENTRIES:
  89. raise ScenarioError(f"entry.type must be one of: {', '.join(sorted(ENTRIES))}")
  90. entry_handler = ENTRIES[entry["type"]]
  91. theme_asset = scenario.get("themeAsset")
  92. if theme_asset is not None:
  93. if entry["type"] != "theme_config":
  94. raise ScenarioError("themeAsset is only supported by theme_config scenarios")
  95. if theme_asset not in {"valid-file", "missing-file", "missing-content-uri"}:
  96. raise ScenarioError("themeAsset must be valid-file, missing-file, or missing-content-uri")
  97. actions = scenario.get("actions")
  98. if not isinstance(actions, list) or not actions:
  99. raise ScenarioError("actions must be a non-empty array")
  100. for index, action in enumerate(actions):
  101. if not isinstance(action, dict):
  102. raise ScenarioError(f"actions[{index}] must be an object")
  103. action_type = action.get("type")
  104. if action_type not in entry_handler.allowed_actions:
  105. raise ScenarioError(f"actions[{index}] has an unsupported type")
  106. ACTIONS[action_type].validate(action, index)
  107. assertions = scenario.get("assertions")
  108. if not isinstance(assertions, list) or not assertions:
  109. raise ScenarioError("assertions must be a non-empty array")
  110. unknown = set(assertions) - set(ASSERTIONS)
  111. if unknown:
  112. raise ScenarioError(f"unsupported assertions: {', '.join(sorted(unknown))}")
  113. def validate_preferences(preferences: Any) -> None:
  114. # Scenario-declared app settings applied before launch (theme engine,
  115. # reader toggles, ...). Restricted to String/Boolean so the debug Activity
  116. # can apply them unambiguously via AppConfigStore.
  117. if preferences is None:
  118. return
  119. if not isinstance(preferences, dict) or not preferences:
  120. raise ScenarioError("preferences must be a non-empty object when present")
  121. for key, value in preferences.items():
  122. if not re.fullmatch(r"[a-zA-Z][a-zA-Z0-9]*", key):
  123. raise ScenarioError(f"invalid preference key: {key}")
  124. if not isinstance(value, (str, bool)):
  125. raise ScenarioError(f"preference {key} must be a string or boolean")
  126. def validate_fixture(fixture_id: str) -> dict[str, Any]:
  127. if not re.fullmatch(r"[a-z0-9][a-z0-9-]*", fixture_id):
  128. raise ScenarioError("fixture must be a lowercase ID")
  129. path = FIXTURE_ROOT / f"{fixture_id}.json"
  130. if not path.is_file():
  131. raise ScenarioError(f"fixture not found: {fixture_id}")
  132. try:
  133. fixture = json.loads(path.read_text(encoding="utf-8"))
  134. except (OSError, json.JSONDecodeError) as error:
  135. raise ScenarioError(f"cannot read fixture {fixture_id}: {error}") from error
  136. validate_fixture_data(fixture, fixture_id)
  137. return fixture
  138. def validate_fixture_data(fixture: Any, fixture_id: str) -> None:
  139. if not isinstance(fixture, dict):
  140. raise ScenarioError(f"fixture root must be an object: {fixture_id}")
  141. if fixture.get("schemaVersion") != 1 or fixture.get("id") != fixture_id:
  142. raise ScenarioError(f"invalid fixture metadata: {fixture_id}")
  143. if fixture.get("resetPolicy") != "replace":
  144. raise ScenarioError(f"unsupported fixture resetPolicy: {fixture_id}")
  145. book = fixture.get("book")
  146. if not isinstance(book, dict):
  147. raise ScenarioError(f"fixture book must be an object: {fixture_id}")
  148. required_strings = ("bookUrl", "name", "author")
  149. if any(not isinstance(book.get(key), str) or not book[key] for key in required_strings):
  150. raise ScenarioError(f"fixture book metadata is incomplete: {fixture_id}")
  151. if book.get("pageMode") != "simulation":
  152. raise ScenarioError(f"unsupported fixture pageMode: {fixture_id}")
  153. chapters = fixture.get("chapters")
  154. if not isinstance(chapters, list) or not chapters:
  155. raise ScenarioError(f"fixture must contain chapters: {fixture_id}")
  156. start_chapter = book.get("startChapter")
  157. start_position = book.get("startPosition")
  158. if not isinstance(start_chapter, int) or start_chapter not in range(len(chapters)):
  159. raise ScenarioError(f"fixture startChapter is invalid: {fixture_id}")
  160. if not isinstance(start_position, int) or start_position < 0:
  161. raise ScenarioError(f"fixture startPosition is invalid: {fixture_id}")
  162. for index, chapter in enumerate(chapters):
  163. if not isinstance(chapter, dict):
  164. raise ScenarioError(f"fixture chapters[{index}] must be an object")
  165. for key in ("title", "readyMarker", "paragraph"):
  166. if not isinstance(chapter.get(key), str) or not chapter[key]:
  167. raise ScenarioError(f"fixture chapters[{index}].{key} is required")
  168. repeat = chapter.get("repeat")
  169. if not isinstance(repeat, int) or repeat < 1 or repeat > 1000:
  170. raise ScenarioError(f"fixture chapters[{index}].repeat must be between 1 and 1000")
  171. def run_command(
  172. command: Sequence[str],
  173. *,
  174. timeout: int = 120,
  175. check: bool = True,
  176. cwd: Path = PROJECT_ROOT,
  177. ) -> subprocess.CompletedProcess[str]:
  178. result = subprocess.run(
  179. list(command),
  180. cwd=cwd,
  181. text=True,
  182. encoding="utf-8",
  183. errors="replace",
  184. stdout=subprocess.PIPE,
  185. stderr=subprocess.STDOUT,
  186. timeout=timeout,
  187. )
  188. if check and result.returncode != 0:
  189. raise CommandError(command, result)
  190. return result
  191. def adb(device: str, *arguments: str, timeout: int = 60, check: bool = True) -> subprocess.CompletedProcess[str]:
  192. return run_command(["adb", "-s", device, *arguments], timeout=timeout, check=check)
  193. def prepare_theme_asset(device: str, scenario: dict[str, Any]) -> dict[str, Any] | None:
  194. preferences = dict(scenario.get("preferences") or {})
  195. mode = scenario.get("themeAsset")
  196. if mode is None:
  197. return preferences or None
  198. remote_folder = THEME_ASSET_REMOTE.rsplit("/", 1)[0]
  199. adb(device, "shell", "rm", "-rf", remote_folder, timeout=10, check=False)
  200. if mode == "valid-file":
  201. adb(device, "shell", "mkdir", "-p", remote_folder, timeout=10)
  202. run_command(
  203. ["adb", "-s", device, "push", str(THEME_ASSET_FIXTURE), THEME_ASSET_REMOTE],
  204. timeout=30,
  205. )
  206. background = THEME_ASSET_REMOTE
  207. elif mode == "missing-file":
  208. background = f"{remote_folder}/missing-background.png"
  209. else:
  210. background = f"content://{PACKAGE}.debug-theme-assets/missing-background.png"
  211. preferences["backgroundImage"] = background
  212. preferences["backgroundImageNight"] = ""
  213. return preferences
  214. def arm_theme_content_failure(device: str) -> None:
  215. adb(
  216. device,
  217. "shell",
  218. "content",
  219. "call",
  220. "--uri",
  221. f"content://{PACKAGE}.debug-theme-assets",
  222. "--method",
  223. "armFailure",
  224. timeout=15,
  225. )
  226. def select_device(requested: str | None) -> str:
  227. if shutil.which("adb") is None:
  228. raise RuntimeError("adb is not available on PATH")
  229. result = run_command(["adb", "devices"], timeout=15)
  230. devices = []
  231. for line in result.stdout.splitlines()[1:]:
  232. fields = line.split()
  233. if len(fields) >= 2 and fields[1] == "device":
  234. devices.append(fields[0])
  235. if requested:
  236. if requested not in devices:
  237. raise RuntimeError(f"device is not ready: {requested}")
  238. return requested
  239. if len(devices) == 1:
  240. return devices[0]
  241. if not devices:
  242. raise RuntimeError("no ready Android device found")
  243. raise RuntimeError("multiple devices found; pass --device")
  244. def create_session(scenario_name: str, fixture: str, device: str | None) -> tuple[str, Path, dict[str, Any]]:
  245. now = dt.datetime.now().astimezone()
  246. session_id = now.strftime("%Y%m%d-%H%M%S-%f")[:-3]
  247. run_dir = RUN_ROOT / session_id
  248. run_dir.mkdir(parents=True, exist_ok=False)
  249. metadata = {
  250. "schemaVersion": 1,
  251. "sessionId": session_id,
  252. "scenario": scenario_name,
  253. "fixture": fixture,
  254. "device": device,
  255. "startedAt": now.isoformat(timespec="milliseconds"),
  256. "package": PACKAGE,
  257. }
  258. write_json(run_dir / "metadata.json", metadata)
  259. return session_id, run_dir, metadata
  260. def write_json(path: Path, value: Any) -> None:
  261. path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
  262. def find_debug_apk() -> Path:
  263. output_root = PROJECT_ROOT / "app" / "build" / "outputs" / "apk"
  264. candidates = [
  265. path
  266. for path in output_root.rglob("*.apk")
  267. if "androidTest" not in path.parts and "debug" in path.parts
  268. ]
  269. if not candidates:
  270. raise RuntimeError("debug APK was not produced")
  271. universal = [path for path in candidates if "universal" in path.name]
  272. return max(universal or candidates, key=lambda path: path.stat().st_mtime)
  273. def build_and_install(device: str, run_dir: Path) -> tuple[dict[str, Any], Path]:
  274. started = time.monotonic()
  275. command = ["./gradlew", ":app:assembleAppDebug", "-PenableAbiSplits=false"]
  276. result = run_command(command, timeout=900, check=False)
  277. (run_dir / "build.log").write_text(result.stdout, encoding="utf-8")
  278. build = {
  279. "status": "passed" if result.returncode == 0 else "failed",
  280. "durationMs": round((time.monotonic() - started) * 1000),
  281. "artifact": "build.log",
  282. }
  283. if result.returncode != 0:
  284. raise CommandError(command, result)
  285. apk = find_debug_apk()
  286. install_mode = install_apk(device, apk, run_dir)
  287. build["apk"] = str(apk.relative_to(PROJECT_ROOT))
  288. build["installMode"] = install_mode
  289. return build, apk
  290. def install_apk(device: str, apk: Path, run_dir: Path) -> str:
  291. attempts = [
  292. ("no_streaming", ["adb", "-s", device, "install", "--no-streaming", "-r", "-t", str(apk)], 120),
  293. ("streaming_retry", ["adb", "-s", device, "install", "-r", "-t", str(apk)], 60),
  294. ]
  295. log_parts = []
  296. last_error: Exception | None = None
  297. for mode, command, timeout in attempts:
  298. try:
  299. result = run_command(command, timeout=timeout, check=False)
  300. log_parts.append(f"[{mode}] exit={result.returncode}\n{result.stdout}")
  301. if result.returncode == 0 and "Success" in result.stdout:
  302. (run_dir / "install.log").write_text("\n".join(log_parts), encoding="utf-8")
  303. return mode
  304. last_error = CommandError(command, result)
  305. except subprocess.TimeoutExpired as error:
  306. log_parts.append(f"[{mode}] timeout={timeout}s\n")
  307. last_error = error
  308. cleanup_device(device)
  309. (run_dir / "install.log").write_text("\n".join(log_parts), encoding="utf-8")
  310. raise RuntimeError(f"APK install failed after {len(attempts)} attempts: {last_error}")
  311. def launch_fixture(
  312. device: str,
  313. fixture: str,
  314. entry: str,
  315. session_id: str,
  316. preferences: dict[str, Any] | None = None,
  317. ) -> None:
  318. adb(device, "shell", "am", "force-stop", PACKAGE)
  319. adb(device, "logcat", "-c")
  320. component = f"{PACKAGE}/{DEBUG_ACTIVITY}"
  321. extras = [
  322. "--es", "fixture", fixture,
  323. "--es", "session", session_id,
  324. "--es", "entry", entry,
  325. ]
  326. if preferences:
  327. # base64 so the JSON survives `adb shell am` re-parsing on the device
  328. # (raw JSON gets quote-stripped and brace-expanded by the device shell).
  329. payload = json.dumps(preferences, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
  330. extras += ["--es", "preferencesB64", base64.b64encode(payload).decode("ascii")]
  331. result = adb(
  332. device,
  333. "shell",
  334. "am",
  335. "start",
  336. "-W",
  337. "-n",
  338. component,
  339. *extras,
  340. timeout=60,
  341. check=False,
  342. )
  343. if result.returncode != 0 or "Error:" in result.stdout:
  344. raise CommandError(["adb", "shell", "am", "start", component], result)
  345. def ui_dump(device: str) -> str:
  346. return adb(device, "exec-out", "uiautomator", "dump", "/dev/tty", timeout=20, check=False).stdout
  347. def window_state(device: str) -> str:
  348. # Full `dumpsys window windows` output. Callers substring-match against it,
  349. # so a hit means the activity is present in the window stack, not strictly
  350. # the foreground window.
  351. return adb(device, "shell", "dumpsys", "window", "windows", timeout=20, check=False).stdout
  352. def device_is_awake(device: str) -> bool:
  353. output = adb(device, "shell", "dumpsys", "power", timeout=20, check=False).stdout
  354. return "mWakefulness=Awake" in output
  355. def keyguard_is_showing(device: str) -> bool:
  356. output = adb(device, "shell", "dumpsys", "window", "policy", timeout=20, check=False).stdout
  357. match = re.search(r"^\s+showing=(true|false)\b", output, re.MULTILINE)
  358. return match is not None and match.group(1) == "true"
  359. def device_ready_for_ui(device: str) -> bool:
  360. return device_is_awake(device) and not keyguard_is_showing(device)
  361. def prepare_device(device: str) -> dict[str, Any]:
  362. state = {
  363. "wasAwake": device_is_awake(device),
  364. "wasKeyguardShowing": keyguard_is_showing(device),
  365. "stayOnWhilePluggedIn": adb(
  366. device,
  367. "shell",
  368. "settings",
  369. "get",
  370. "global",
  371. "stay_on_while_plugged_in",
  372. timeout=20,
  373. check=False,
  374. ).stdout.strip(),
  375. }
  376. adb(
  377. device,
  378. "shell",
  379. "settings",
  380. "put",
  381. "global",
  382. "stay_on_while_plugged_in",
  383. "2",
  384. timeout=20,
  385. )
  386. if not state["wasAwake"]:
  387. adb(device, "shell", "input", "keyevent", "KEYCODE_WAKEUP", timeout=20)
  388. if keyguard_is_showing(device):
  389. adb(device, "shell", "wm", "dismiss-keyguard", timeout=20, check=False)
  390. time.sleep(0.2)
  391. if keyguard_is_showing(device):
  392. adb(device, "shell", "input", "keyevent", "82", timeout=20, check=False)
  393. time.sleep(0.5)
  394. if not device_ready_for_ui(device):
  395. restore_device(device, state)
  396. raise RuntimeError("device could not be awakened and unlocked for UI automation")
  397. return state
  398. def restore_device(device: str, state: dict[str, Any] | None) -> None:
  399. if state is None:
  400. return
  401. stay_on = state.get("stayOnWhilePluggedIn")
  402. if stay_on in {"", "null", None}:
  403. adb(
  404. device,
  405. "shell",
  406. "settings",
  407. "delete",
  408. "global",
  409. "stay_on_while_plugged_in",
  410. timeout=20,
  411. check=False,
  412. )
  413. else:
  414. adb(
  415. device,
  416. "shell",
  417. "settings",
  418. "put",
  419. "global",
  420. "stay_on_while_plugged_in",
  421. str(stay_on),
  422. timeout=20,
  423. check=False,
  424. )
  425. if state.get("wasKeyguardShowing"):
  426. adb(device, "shell", "input", "keyevent", "KEYCODE_SLEEP", timeout=20, check=False)
  427. if state.get("wasAwake"):
  428. adb(device, "shell", "input", "keyevent", "KEYCODE_WAKEUP", timeout=20, check=False)
  429. elif not state.get("wasAwake"):
  430. adb(device, "shell", "input", "keyevent", "KEYCODE_SLEEP", timeout=20, check=False)
  431. def parse_ui_nodes(dump: str) -> list[dict[str, str]]:
  432. start = dump.find("<?xml")
  433. end = dump.rfind("</hierarchy>")
  434. if start < 0 or end < 0:
  435. return []
  436. try:
  437. root = ET.fromstring(dump[start : end + len("</hierarchy>")])
  438. except ET.ParseError:
  439. return []
  440. return [node.attrib for node in root.iter("node")]
  441. READER_PAGE_TAG = "READER_PAGE "
  442. def extract_reader_pages(logcat: str) -> list[str]:
  443. # ReadView logs "READER_PAGE <one-line page text>" on every render (debug
  444. # build only). This is the device-independent reader signal — uiautomator
  445. # does not expose the ReadView node on all devices.
  446. pages = []
  447. for line in logcat.splitlines():
  448. index = line.find(READER_PAGE_TAG)
  449. if index >= 0:
  450. pages.append(line[index + len(READER_PAGE_TAG):].strip())
  451. return pages
  452. def reader_current_page(device: str) -> str:
  453. logcat = adb(device, "logcat", "-d", "-s", "LegadoDebug:I", timeout=20, check=False).stdout
  454. pages = extract_reader_pages(logcat)
  455. return pages[-1] if pages else ""
  456. def find_node_by_content_prefix(
  457. dump: str,
  458. prefix: str,
  459. package: str = PACKAGE,
  460. ) -> dict[str, str] | None:
  461. # The bookshelf item's label lives on a node whose clickable flag is false
  462. # (the clickable modifier sits on an ancestor). Match by content-desc and
  463. # tap the label's center; the clickable ancestor is under that point.
  464. candidates = [
  465. node
  466. for node in parse_ui_nodes(dump)
  467. if node.get("package") == package
  468. and node.get("content-desc", "").startswith(prefix)
  469. ]
  470. return candidates[0] if candidates else None
  471. def find_node_by_text(
  472. dump: str,
  473. text: str,
  474. package: str = PACKAGE,
  475. ) -> dict[str, str] | None:
  476. candidates = [
  477. node
  478. for node in parse_ui_nodes(dump)
  479. if node.get("package") == package and node.get("text") == text
  480. ]
  481. return candidates[0] if candidates else None
  482. def find_node_in_same_row(
  483. dump: str,
  484. anchor: dict[str, str],
  485. resource_id: str,
  486. ) -> dict[str, str] | None:
  487. anchor_bounds = parse_bounds(anchor)
  488. if anchor_bounds is None:
  489. return None
  490. _, anchor_top, _, anchor_bottom = anchor_bounds
  491. candidates = []
  492. for node in parse_ui_nodes(dump):
  493. if node.get("package") != PACKAGE or node.get("resource-id") != resource_id:
  494. continue
  495. bounds = parse_bounds(node)
  496. if bounds is None:
  497. continue
  498. _, top, _, bottom = bounds
  499. overlap = min(anchor_bottom, bottom) - max(anchor_top, top)
  500. if overlap > 0:
  501. candidates.append((overlap, node))
  502. return max(candidates, key=lambda item: item[0])[1] if candidates else None
  503. def parse_bounds(node: dict[str, str]) -> tuple[int, int, int, int] | None:
  504. match = re.fullmatch(r"\[(\d+),(\d+)]\[(\d+),(\d+)]", node.get("bounds", ""))
  505. return tuple(map(int, match.groups())) if match else None
  506. def node_center(node: dict[str, str]) -> tuple[int, int]:
  507. bounds = parse_bounds(node)
  508. if bounds is None:
  509. raise RuntimeError(f"invalid accessibility bounds: {node.get('bounds', '')}")
  510. left, top, right, bottom = bounds
  511. return (left + right) // 2, (top + bottom) // 2
  512. def wait_until_node_present(
  513. device: str,
  514. content_prefix: str,
  515. timeout_seconds: int,
  516. ) -> tuple[bool, str, dict[str, str] | None]:
  517. deadline = time.monotonic() + timeout_seconds
  518. latest = ""
  519. node = None
  520. while time.monotonic() < deadline:
  521. latest = ui_dump(device)
  522. node = find_node_by_content_prefix(latest, content_prefix)
  523. if node is not None and device_ready_for_ui(device):
  524. return True, latest, node
  525. time.sleep(0.5)
  526. return False, latest, node
  527. def wait_until_text_present(
  528. device: str,
  529. text: str,
  530. timeout_seconds: int,
  531. ) -> tuple[bool, str, dict[str, str] | None]:
  532. deadline = time.monotonic() + timeout_seconds
  533. latest = ""
  534. node = None
  535. while time.monotonic() < deadline:
  536. latest = ui_dump(device)
  537. node = find_node_by_text(latest, text)
  538. if node is not None and device_ready_for_ui(device):
  539. return True, latest, node
  540. time.sleep(0.25)
  541. return False, latest, node
  542. def find_node_by_class(dump: str, class_name: str) -> dict[str, str] | None:
  543. candidates = [
  544. node
  545. for node in parse_ui_nodes(dump)
  546. if node.get("package") == PACKAGE and node.get("class") == class_name
  547. ]
  548. return candidates[0] if candidates else None
  549. def find_node_containing_text(dump: str, text: str) -> dict[str, str] | None:
  550. candidates = [
  551. node
  552. for node in parse_ui_nodes(dump)
  553. if text in node.get("text", "")
  554. ]
  555. return candidates[0] if candidates else None
  556. def saved_theme_manifest(device: str, theme_name: str) -> tuple[str, dict[str, Any]] | None:
  557. result = adb(
  558. device,
  559. "exec-out",
  560. "run-as",
  561. PACKAGE,
  562. "find",
  563. "files/saved_themes",
  564. "-name",
  565. "manifest.json",
  566. "-type",
  567. "f",
  568. timeout=20,
  569. check=False,
  570. )
  571. for path in result.stdout.splitlines():
  572. manifest = adb(
  573. device,
  574. "exec-out",
  575. "run-as",
  576. PACKAGE,
  577. "cat",
  578. path.strip(),
  579. timeout=20,
  580. check=False,
  581. ).stdout
  582. try:
  583. data = json.loads(manifest)
  584. if data.get("name") == theme_name:
  585. return path.strip(), data
  586. except json.JSONDecodeError:
  587. continue
  588. return None
  589. def saved_theme_exists(device: str, theme_name: str) -> bool:
  590. return saved_theme_manifest(device, theme_name) is not None
  591. def saved_theme_has_fixture_asset(device: str, theme_name: str) -> bool:
  592. saved = saved_theme_manifest(device, theme_name)
  593. if saved is None:
  594. return False
  595. manifest_path, manifest = saved
  596. entry = (manifest.get("assets") or {}).get("background.light")
  597. if not isinstance(entry, str) or not entry:
  598. return False
  599. asset_path = f"{manifest_path.rsplit('/', 1)[0]}/{entry}"
  600. result = adb(
  601. device,
  602. "exec-out",
  603. "run-as",
  604. PACKAGE,
  605. "sha256sum",
  606. asset_path,
  607. timeout=20,
  608. check=False,
  609. )
  610. digest = result.stdout.split()
  611. expected = hashlib.sha256(THEME_ASSET_FIXTURE.read_bytes()).hexdigest()
  612. return bool(digest) and digest[0] == expected
  613. def wait_until_reader_ready(device: str, marker: str, timeout_seconds: int) -> tuple[bool, str, str]:
  614. deadline = time.monotonic() + timeout_seconds
  615. content = ""
  616. while time.monotonic() < deadline:
  617. content = reader_current_page(device)
  618. if marker in content and PACKAGE in window_state(device) and device_ready_for_ui(device):
  619. return True, content, content
  620. time.sleep(0.5)
  621. return False, content, content
  622. def wait_until_reader_content_changed(
  623. device: str,
  624. previous_content: str,
  625. timeout_seconds: int,
  626. ) -> tuple[bool, str, str]:
  627. deadline = time.monotonic() + timeout_seconds
  628. content = ""
  629. while time.monotonic() < deadline:
  630. content = reader_current_page(device)
  631. if content and content != previous_content:
  632. return True, content, content
  633. time.sleep(0.2)
  634. return False, content, content
  635. def resumed_activity(device: str) -> str:
  636. output = adb(device, "shell", "dumpsys", "activity", "activities", timeout=20, check=False).stdout
  637. match = re.search(r"topResumedActivity=.*?\s([\w.]+/[\w.$]+)\s", output)
  638. return match.group(1) if match else ""
  639. def wait_until_activity_resumed(
  640. device: str,
  641. activity: str,
  642. timeout_seconds: int,
  643. ) -> tuple[bool, str]:
  644. deadline = time.monotonic() + timeout_seconds
  645. resumed = ""
  646. component = f"{PACKAGE}/{activity}"
  647. while time.monotonic() < deadline:
  648. resumed = resumed_activity(device)
  649. if resumed == component and device_ready_for_ui(device):
  650. return True, resumed
  651. time.sleep(0.2)
  652. return False, resumed
  653. def application_pid(device: str) -> str | None:
  654. result = adb(device, "shell", "pidof", PACKAGE, timeout=10, check=False)
  655. return result.stdout.strip().split()[0] if result.returncode == 0 and result.stdout.strip() else None
  656. def screen_size(device: str) -> tuple[int, int]:
  657. output = adb(device, "shell", "wm", "size").stdout
  658. matches = re.findall(r"(\d+)x(\d+)", output)
  659. if not matches:
  660. raise RuntimeError(f"cannot determine screen size: {output.strip()}")
  661. width, height = matches[-1]
  662. return int(width), int(height)
  663. def capture_screenshot(device: str, path: Path) -> None:
  664. with path.open("wb") as output:
  665. result = subprocess.run(
  666. ["adb", "-s", device, "exec-out", "screencap", "-p"],
  667. cwd=PROJECT_ROOT,
  668. stdout=output,
  669. stderr=subprocess.PIPE,
  670. timeout=30,
  671. )
  672. if result.returncode != 0:
  673. path.unlink(missing_ok=True)
  674. raise RuntimeError(result.stderr.decode(errors="replace"))
  675. class ScreenRecorder:
  676. """Optional screenrecord wrapper for capturing transient UI (animations).
  677. Best-effort: any failure to start, stop, or pull leaves the run unaffected
  678. and simply produces no video artifact.
  679. """
  680. REMOTE = "/sdcard/legado-debug-transition.mp4"
  681. def __init__(self, device: str):
  682. self.device = device
  683. self.process: subprocess.Popen[bytes] | None = None
  684. self.saved: str | None = None
  685. self._stopped = False
  686. def start(self) -> None:
  687. adb(self.device, "shell", "rm", "-f", self.REMOTE, timeout=15, check=False)
  688. self.process = subprocess.Popen(
  689. ["adb", "-s", self.device, "shell", "screenrecord", "--time-limit", "60", self.REMOTE],
  690. cwd=PROJECT_ROOT,
  691. stdout=subprocess.DEVNULL,
  692. stderr=subprocess.DEVNULL,
  693. )
  694. time.sleep(0.5)
  695. def stop(self, run_dir: Path, name: str = "transition.mp4") -> str | None:
  696. if self.process is None or self._stopped:
  697. return self.saved
  698. self._stopped = True
  699. # SIGINT lets screenrecord finalize a playable mp4 before it exits.
  700. pids = adb(self.device, "shell", "pidof", "screenrecord", timeout=10, check=False).stdout.split()
  701. for pid in pids:
  702. adb(self.device, "shell", "kill", "-INT", pid, timeout=10, check=False)
  703. try:
  704. self.process.wait(timeout=15)
  705. except subprocess.TimeoutExpired:
  706. self.process.kill()
  707. pull = subprocess.run(
  708. ["adb", "-s", self.device, "pull", self.REMOTE, str(run_dir / name)],
  709. cwd=PROJECT_ROOT,
  710. capture_output=True,
  711. text=True,
  712. timeout=60,
  713. )
  714. adb(self.device, "shell", "rm", "-f", self.REMOTE, timeout=15, check=False)
  715. if pull.returncode == 0 and (run_dir / name).is_file():
  716. self.saved = name
  717. return self.saved
  718. def collect_logcat(
  719. device: str,
  720. run_dir: Path,
  721. app_pids: Sequence[str] = (),
  722. session_id: str | None = None,
  723. ) -> str:
  724. logcat = adb(device, "logcat", "-d", "-v", "threadtime", timeout=45, check=False).stdout
  725. (run_dir / "logcat.txt").write_text(logcat, encoding="utf-8")
  726. session_logcat = ""
  727. unique_pids = list(dict.fromkeys(pid for pid in app_pids if pid))
  728. for pid in unique_pids:
  729. pid_logcat = adb(
  730. device,
  731. "logcat",
  732. "-d",
  733. f"--pid={pid}",
  734. "-v",
  735. "threadtime",
  736. timeout=45,
  737. check=False,
  738. ).stdout
  739. session_logcat += f"--- pid={pid} ---\n{pid_logcat}"
  740. if session_id:
  741. session_lines = [line for line in logcat.splitlines() if f"[session={session_id}]" in line]
  742. for line in session_lines:
  743. if line not in session_logcat:
  744. session_logcat += line + "\n"
  745. (run_dir / "session-logcat.txt").write_text(session_logcat, encoding="utf-8")
  746. crash = extract_crash(logcat, PACKAGE, unique_pids)
  747. (run_dir / "crash.txt").write_text(crash, encoding="utf-8")
  748. return logcat
  749. def extract_crash(
  750. logcat: str,
  751. package: str = PACKAGE,
  752. app_pids: Sequence[str] = (),
  753. ) -> str:
  754. lines = logcat.splitlines()
  755. chunks = []
  756. for index, line in enumerate(lines):
  757. chunk = lines[index : index + 100]
  758. if f"ANR in {package}" in line:
  759. chunks.extend(chunk)
  760. elif "FATAL EXCEPTION:" in line and any(package in item for item in chunk[:10]):
  761. chunks.extend(chunk)
  762. elif "Fatal signal " in line and any(
  763. re.search(rf"\b{re.escape(pid)}\b", line) for pid in app_pids
  764. ):
  765. chunks.extend(chunk)
  766. if not chunks:
  767. return ""
  768. return "\n".join(chunks).rstrip() + "\n"
  769. def parse_failure(crash: str) -> dict[str, Any] | None:
  770. if not crash:
  771. return None
  772. if "ANR in" in crash:
  773. return {
  774. "category": "anr",
  775. "confidence": "high",
  776. "detectedSignals": ["anr"],
  777. "stacktraceArtifact": "crash.txt",
  778. }
  779. if "Fatal signal " in crash:
  780. return {
  781. "category": "native_crash",
  782. "confidence": "high",
  783. "detectedSignals": ["fatal_signal"],
  784. "stacktraceArtifact": "crash.txt",
  785. }
  786. exceptions = list(
  787. re.finditer(r"(Caused by: )?([\w.$]+(?:Exception|Error))(?:: ([^\n]+))?", crash)
  788. )
  789. caused_by = [match for match in exceptions if match.group(1)]
  790. exception = caused_by[-1] if caused_by else (exceptions[0] if exceptions else None)
  791. failure: dict[str, Any] = {
  792. "category": "uncaught_exception",
  793. "confidence": "high",
  794. "detectedSignals": ["fatal_exception"],
  795. "stacktraceArtifact": "crash.txt",
  796. }
  797. if exception:
  798. failure["exceptionType"] = exception.group(2).split(".")[-1]
  799. failure["exceptionConfidence"] = "medium" if exceptions else "low"
  800. if exception.group(3):
  801. failure["message"] = exception.group(3).strip()
  802. frame = re.search(
  803. r"at (io\.legado\.app\.[\w.$]+)\.([\w$<>]+)\(([^():]+):(\d+)\)",
  804. crash,
  805. )
  806. if frame:
  807. failure["suspectedFrame"] = {
  808. "class": frame.group(1),
  809. "method": frame.group(2),
  810. "file": frame.group(3),
  811. "line": int(frame.group(4)),
  812. "confidence": "medium",
  813. }
  814. return failure
  815. def sha256_text(value: str) -> str:
  816. return hashlib.sha256(value.encode("utf-8", errors="replace")).hexdigest()
  817. def make_summary(
  818. *,
  819. session_id: str,
  820. scenario: dict[str, Any],
  821. fixture: str,
  822. build: dict[str, Any],
  823. ready: bool,
  824. activity_visible: bool,
  825. content_changed: bool,
  826. action_count: int,
  827. failure: dict[str, Any] | None,
  828. ) -> tuple[dict[str, Any], int]:
  829. assertion_values = {
  830. "reader_ready": ready,
  831. "reader_activity_visible": activity_visible,
  832. "reader_content_changed": content_changed,
  833. "no_fatal_exception": failure is None,
  834. }
  835. return make_summary_from_assertions(
  836. session_id=session_id,
  837. scenario=scenario,
  838. fixture=fixture,
  839. build=build,
  840. assertion_values=assertion_values,
  841. action_count=action_count,
  842. failure=failure,
  843. )
  844. def make_summary_from_assertions(
  845. *,
  846. session_id: str,
  847. scenario: dict[str, Any],
  848. fixture: str,
  849. build: dict[str, Any],
  850. assertion_values: dict[str, bool],
  851. action_count: int,
  852. failure: dict[str, Any] | None,
  853. extra_artifacts: dict[str, str] | None = None,
  854. ) -> tuple[dict[str, Any], int]:
  855. assertions = [
  856. {"name": name, "passed": assertion_values[name]}
  857. for name in scenario["assertions"]
  858. ]
  859. if failure is not None:
  860. status, exit_code = "failed", EXIT_CRASH
  861. elif not all(item["passed"] for item in assertions):
  862. status, exit_code = "failed", EXIT_ASSERTION
  863. else:
  864. status, exit_code = "passed", 0
  865. summary: dict[str, Any] = {
  866. "schemaVersion": 1,
  867. "status": status,
  868. "exitCode": exit_code,
  869. "sessionId": session_id,
  870. "scenario": scenario["name"],
  871. "fixture": fixture,
  872. "build": build,
  873. "actions": {"performed": action_count},
  874. "assertions": assertions,
  875. "artifacts": {
  876. "metadata": "metadata.json",
  877. "logcat": "logcat.txt",
  878. "sessionLogcat": "session-logcat.txt",
  879. "crash": "crash.txt",
  880. },
  881. }
  882. if failure is not None:
  883. summary["failure"] = failure
  884. if extra_artifacts:
  885. summary["artifacts"].update(extra_artifacts)
  886. return summary, exit_code
  887. def error_summary(
  888. session_id: str,
  889. scenario_name: str,
  890. fixture: str,
  891. exit_code: int,
  892. category: str,
  893. message: str,
  894. build: dict[str, Any] | None = None,
  895. ) -> dict[str, Any]:
  896. summary: dict[str, Any] = {
  897. "schemaVersion": 1,
  898. "status": "failed",
  899. "exitCode": exit_code,
  900. "sessionId": session_id,
  901. "scenario": scenario_name,
  902. "fixture": fixture,
  903. "failure": {"category": category, "message": message},
  904. "artifacts": {"metadata": "metadata.json"},
  905. }
  906. if build is not None:
  907. summary["build"] = build
  908. return summary
  909. def cleanup_device(device: str) -> None:
  910. adb(device, "shell", "am", "force-stop", PACKAGE, timeout=20, check=False)
  911. # --------------------------------------------------------------------------- #
  912. # Capability registry: entries, actions, assertions.
  913. #
  914. # A scenario is fully described by data (JSON). Each domain action and each
  915. # assertion is a small handler registered here. Adding a bug scenario means
  916. # adding a handler + a JSON file, not editing execute() / validate_scenario().
  917. # Handlers only *record* raw observations into the Context; assertions are pure
  918. # reads of those observations.
  919. # --------------------------------------------------------------------------- #
  920. class Context:
  921. """Mutable per-run state shared across entry, actions, and assertions."""
  922. def __init__(
  923. self,
  924. device: str,
  925. run_dir: Path,
  926. scenario: dict[str, Any],
  927. fixture_data: dict[str, Any],
  928. metadata: dict[str, Any],
  929. action_repeat: int,
  930. ):
  931. self.device = device
  932. self.run_dir = run_dir
  933. self.scenario = scenario
  934. self.fixture_data = fixture_data
  935. self.metadata = metadata
  936. self.action_repeat = action_repeat
  937. self.app_pids: list[str] = []
  938. self.records: dict[str, Any] = {}
  939. self.state: dict[str, Any] = {}
  940. self.artifacts: dict[str, str] = {}
  941. self.action_count = 0
  942. self.assertion_values: dict[str, bool] = {}
  943. self.failure: dict[str, Any] | None = None
  944. def note_pid(self) -> None:
  945. pid = application_pid(self.device)
  946. if pid and pid not in self.app_pids:
  947. self.app_pids.append(pid)
  948. def screenshot(self, name: str, filename: str) -> None:
  949. capture_screenshot(self.device, self.run_dir / filename)
  950. self.artifacts[name] = filename
  951. class Entry:
  952. type: str = ""
  953. allowed_actions: set[str] = set()
  954. def prepare(self, ctx: Context) -> None:
  955. raise NotImplementedError
  956. def finalize(self, ctx: Context) -> None:
  957. raise NotImplementedError
  958. class Action:
  959. name: str = ""
  960. params: dict[str, Any] = {}
  961. def validate(self, action: dict[str, Any], index: int) -> None:
  962. pass
  963. def run(self, ctx: Context, action: dict[str, Any]) -> None:
  964. raise NotImplementedError
  965. def register_entry(name: str) -> Callable[[type], type]:
  966. def decorate(cls: type) -> type:
  967. instance = cls()
  968. instance.type = name
  969. ENTRIES[name] = instance
  970. return cls
  971. return decorate
  972. def register_action(name: str) -> Callable[[type], type]:
  973. def decorate(cls: type) -> type:
  974. instance = cls()
  975. instance.name = name
  976. ACTIONS[name] = instance
  977. return cls
  978. return decorate
  979. @register_entry("reader")
  980. class ReaderEntry(Entry):
  981. allowed_actions = {"turn_page"}
  982. def prepare(self, ctx: Context) -> None:
  983. ready, before_dump, before_content = wait_until_reader_ready(
  984. ctx.device,
  985. ctx.scenario["readyMarker"],
  986. ctx.scenario.get("readyTimeoutSeconds", 30),
  987. )
  988. ctx.note_pid()
  989. ctx.screenshot("beforeScreenshot", "before.png")
  990. ctx.records["reader_ready"] = ready
  991. ctx.records["reader_content_changed"] = False
  992. ctx.records["content_change_duration_ms"] = 0
  993. ctx.records["ui_before"] = before_dump
  994. ctx.records["ui_after"] = before_dump
  995. ctx.records["reader_content_before"] = before_content
  996. ctx.records["reader_content_after"] = before_content
  997. ctx.state["reader_content"] = before_content
  998. def finalize(self, ctx: Context) -> None:
  999. ctx.screenshot("afterScreenshot", "after.png")
  1000. windows = window_state(ctx.device)
  1001. # Presence of MainActivity in the window stack; the reader runs as a
  1002. # route inside MainActivity in this fork.
  1003. visible = PACKAGE in windows and MAIN_ACTIVITY in windows and device_ready_for_ui(ctx.device)
  1004. ctx.records["reader_activity_visible"] = visible
  1005. ctx.metadata.update(
  1006. {
  1007. "actionRepeat": ctx.action_repeat,
  1008. "uiBeforeSha256": sha256_text(ctx.records["ui_before"]),
  1009. "uiAfterSha256": sha256_text(ctx.records["ui_after"]),
  1010. "readerContentBeforeSha256": sha256_text(ctx.records["reader_content_before"]),
  1011. "readerContentAfterSha256": sha256_text(ctx.records["reader_content_after"]),
  1012. "contentChangeDurationMs": ctx.records["content_change_duration_ms"],
  1013. }
  1014. )
  1015. @register_entry("bookshelf")
  1016. class BookshelfEntry(Entry):
  1017. allowed_actions = {"open_fixture_book", "press_back"}
  1018. def prepare(self, ctx: Context) -> None:
  1019. book_name = ctx.fixture_data["book"]["name"]
  1020. ready, before_dump, book_node = wait_until_node_present(
  1021. ctx.device,
  1022. book_name,
  1023. ctx.scenario.get("readyTimeoutSeconds", 30),
  1024. )
  1025. ctx.note_pid()
  1026. ctx.screenshot("beforeScreenshot", "before.png")
  1027. ctx.records["bookshelf_ready"] = ready
  1028. ctx.records["reader_opened"] = False
  1029. ctx.records["returned_to_bookshelf"] = False
  1030. ctx.records["ui_before"] = before_dump
  1031. ctx.records["ui_after"] = before_dump
  1032. ctx.records["reader_dump"] = ""
  1033. ctx.records["reader_content"] = ""
  1034. ctx.state["book_name"] = book_name
  1035. ctx.state["book_node"] = book_node
  1036. ctx.state["returned_node"] = None
  1037. def finalize(self, ctx: Context) -> None:
  1038. ctx.screenshot("afterScreenshot", "after.png")
  1039. book_node = ctx.state.get("book_node")
  1040. returned_node = ctx.state.get("returned_node")
  1041. ctx.metadata.update(
  1042. {
  1043. "uiBeforeSha256": sha256_text(ctx.records["ui_before"]),
  1044. "readerUiSha256": sha256_text(ctx.records["reader_dump"]),
  1045. "uiAfterSha256": sha256_text(ctx.records["ui_after"]),
  1046. "readerContentSha256": sha256_text(ctx.records["reader_content"]),
  1047. "bookshelfItemBefore": book_node.get("content-desc") if book_node else None,
  1048. "bookshelfItemAfter": returned_node.get("content-desc") if returned_node else None,
  1049. }
  1050. )
  1051. @register_entry("source_manage")
  1052. class SourceManageEntry(Entry):
  1053. allowed_actions = {"open_fixture_source", "predictive_back"}
  1054. def prepare(self, ctx: Context) -> None:
  1055. activity_ready, resumed = wait_until_activity_resumed(
  1056. ctx.device,
  1057. SOURCE_MANAGE_ACTIVITY,
  1058. ctx.scenario.get("readyTimeoutSeconds", 30),
  1059. )
  1060. source_name = "Legado Debug Fixture"
  1061. dump = ui_dump(ctx.device)
  1062. source_node = find_node_by_text(dump, source_name)
  1063. edit_node = find_node_in_same_row(
  1064. dump,
  1065. source_node,
  1066. f"{PACKAGE}:id/iv_edit",
  1067. ) if source_node else None
  1068. ctx.note_pid()
  1069. ctx.screenshot("beforeScreenshot", "before.png")
  1070. ctx.records["source_manage_ready"] = activity_ready and source_node is not None and edit_node is not None
  1071. ctx.records["source_edit_opened"] = False
  1072. ctx.records["returned_to_source_manage"] = False
  1073. ctx.records["resumed_before"] = resumed
  1074. ctx.records["resumed_after"] = resumed
  1075. ctx.state["source_name"] = source_name
  1076. ctx.state["edit_node"] = edit_node
  1077. def finalize(self, ctx: Context) -> None:
  1078. ctx.screenshot("afterScreenshot", "after.png")
  1079. ctx.metadata.update(
  1080. {
  1081. "resumedBefore": ctx.records["resumed_before"],
  1082. "resumedAfter": ctx.records["resumed_after"],
  1083. }
  1084. )
  1085. @register_entry("theme_config")
  1086. class ThemeConfigEntry(Entry):
  1087. allowed_actions = {
  1088. "export_current_theme",
  1089. "open_theme_manage",
  1090. "save_current_theme",
  1091. "select_day_background",
  1092. }
  1093. def prepare(self, ctx: Context) -> None:
  1094. ready, dump, _ = wait_until_text_present(
  1095. ctx.device,
  1096. "主题模式",
  1097. ctx.scenario.get("readyTimeoutSeconds", 30),
  1098. )
  1099. ctx.note_pid()
  1100. ctx.screenshot("beforeScreenshot", "before.png")
  1101. ctx.records["theme_config_ready"] = ready
  1102. ctx.records["theme_manage_opened"] = False
  1103. ctx.records["theme_save_succeeded"] = False
  1104. ctx.records["theme_export_succeeded"] = False
  1105. ctx.records["theme_save_failed"] = False
  1106. ctx.records["theme_export_failed"] = False
  1107. ctx.records["theme_failure_feedback"] = False
  1108. ctx.records["theme_save_asset_included"] = False
  1109. ctx.records["theme_export_asset_included"] = False
  1110. ctx.records["theme_day_background_copied"] = False
  1111. ctx.records["ui_before"] = dump
  1112. ctx.records["ui_after"] = dump
  1113. def finalize(self, ctx: Context) -> None:
  1114. ctx.screenshot("afterScreenshot", "after.png")
  1115. ctx.metadata.update(
  1116. {
  1117. "uiBeforeSha256": sha256_text(ctx.records["ui_before"]),
  1118. "uiAfterSha256": sha256_text(ctx.records["ui_after"]),
  1119. "savedThemeName": ctx.state.get("theme_name"),
  1120. "exportedThemeName": ctx.state.get("export_name"),
  1121. }
  1122. )
  1123. @register_action("turn_page")
  1124. class TurnPage(Action):
  1125. params = {"direction": ["next", "previous"], "count": "1-100"}
  1126. def validate(self, action: dict[str, Any], index: int) -> None:
  1127. if action.get("direction") not in {"next", "previous"}:
  1128. raise ScenarioError(f"actions[{index}].direction must be next or previous")
  1129. count = action.get("count", 1)
  1130. if not isinstance(count, int) or count < 1 or count > 100:
  1131. raise ScenarioError(f"actions[{index}].count must be between 1 and 100")
  1132. def run(self, ctx: Context, action: dict[str, Any]) -> None:
  1133. if not ctx.records.get("reader_ready"):
  1134. return
  1135. width, height = screen_size(ctx.device)
  1136. direction = action["direction"]
  1137. count = action.get("count", 1) * ctx.action_repeat
  1138. x = round(width * (0.84 if direction == "next" else 0.16))
  1139. y = round(height * 0.5)
  1140. for _ in range(count):
  1141. adb(ctx.device, "shell", "input", "tap", str(x), str(y), timeout=10)
  1142. ctx.action_count += 1
  1143. time.sleep(0.4)
  1144. started = time.monotonic()
  1145. changed, after_dump, after_content = wait_until_reader_content_changed(
  1146. ctx.device,
  1147. ctx.state["reader_content"],
  1148. ctx.scenario.get("contentChangeTimeoutSeconds", 5),
  1149. )
  1150. ctx.records["content_change_duration_ms"] = round((time.monotonic() - started) * 1000)
  1151. if changed:
  1152. ctx.records["reader_content_changed"] = True
  1153. ctx.state["reader_content"] = after_content
  1154. ctx.records["reader_content_after"] = after_content
  1155. ctx.records["ui_after"] = after_dump
  1156. @register_action("open_fixture_book")
  1157. class OpenFixtureBook(Action):
  1158. def run(self, ctx: Context, action: dict[str, Any]) -> None:
  1159. book_node = ctx.state.get("book_node")
  1160. if not (ctx.records.get("bookshelf_ready") and book_node is not None):
  1161. return
  1162. x, y = node_center(book_node)
  1163. adb(ctx.device, "shell", "input", "tap", str(x), str(y), timeout=10)
  1164. ctx.action_count += 1
  1165. opened, reader_dump, reader_content = wait_until_reader_ready(
  1166. ctx.device,
  1167. ctx.scenario["readyMarker"],
  1168. ctx.scenario.get("readyTimeoutSeconds", 30),
  1169. )
  1170. ctx.records["reader_opened"] = opened
  1171. ctx.records["reader_dump"] = reader_dump
  1172. ctx.records["reader_content"] = reader_content
  1173. ctx.screenshot("readerScreenshot", "reader.png")
  1174. @register_action("press_back")
  1175. class PressBack(Action):
  1176. def run(self, ctx: Context, action: dict[str, Any]) -> None:
  1177. if not ctx.records.get("reader_opened"):
  1178. return
  1179. adb(ctx.device, "shell", "input", "keyevent", "BACK", timeout=10)
  1180. ctx.action_count += 1
  1181. returned, after_dump, returned_node = wait_until_node_present(
  1182. ctx.device,
  1183. ctx.state["book_name"],
  1184. ctx.scenario.get("readyTimeoutSeconds", 30),
  1185. )
  1186. ctx.records["returned_to_bookshelf"] = returned
  1187. ctx.records["ui_after"] = after_dump
  1188. ctx.state["returned_node"] = returned_node
  1189. @register_action("predictive_back")
  1190. class PredictiveBack(Action):
  1191. def run(self, ctx: Context, action: dict[str, Any]) -> None:
  1192. if not ctx.records.get("source_edit_opened"):
  1193. return
  1194. width, height = screen_size(ctx.device)
  1195. y = round(height * 0.5)
  1196. end_x = round(width * 0.45)
  1197. adb(
  1198. ctx.device,
  1199. "shell",
  1200. "input",
  1201. "swipe",
  1202. "1",
  1203. str(y),
  1204. str(end_x),
  1205. str(y),
  1206. "300",
  1207. timeout=10,
  1208. )
  1209. ctx.action_count += 1
  1210. returned, resumed = wait_until_activity_resumed(
  1211. ctx.device,
  1212. SOURCE_MANAGE_ACTIVITY,
  1213. ctx.scenario.get("readyTimeoutSeconds", 30),
  1214. )
  1215. dump = ui_dump(ctx.device)
  1216. source_present = find_node_by_text(dump, ctx.state["source_name"]) is not None
  1217. ctx.records["returned_to_source_manage"] = returned and source_present
  1218. ctx.records["resumed_after"] = resumed
  1219. @register_action("open_fixture_source")
  1220. class OpenFixtureSource(Action):
  1221. def run(self, ctx: Context, action: dict[str, Any]) -> None:
  1222. edit_node = ctx.state.get("edit_node")
  1223. if not (ctx.records.get("source_manage_ready") and edit_node is not None):
  1224. return
  1225. x, y = node_center(edit_node)
  1226. adb(ctx.device, "shell", "input", "tap", str(x), str(y), timeout=10)
  1227. ctx.action_count += 1
  1228. opened, _ = wait_until_activity_resumed(
  1229. ctx.device,
  1230. SOURCE_EDIT_ACTIVITY,
  1231. ctx.scenario.get("readyTimeoutSeconds", 30),
  1232. )
  1233. ctx.records["source_edit_opened"] = opened
  1234. ctx.screenshot("editScreenshot", "edit.png")
  1235. @register_action("open_theme_manage")
  1236. class OpenThemeManage(Action):
  1237. def run(self, ctx: Context, action: dict[str, Any]) -> None:
  1238. if not ctx.records.get("theme_config_ready"):
  1239. return
  1240. node = None
  1241. dump = ""
  1242. width, height = screen_size(ctx.device)
  1243. for _ in range(6):
  1244. dump = ui_dump(ctx.device)
  1245. node = find_node_by_text(dump, "主题管理")
  1246. if node is not None:
  1247. break
  1248. adb(
  1249. ctx.device,
  1250. "shell",
  1251. "input",
  1252. "swipe",
  1253. str(width // 2),
  1254. str(round(height * 0.84)),
  1255. str(width // 2),
  1256. str(round(height * 0.48)),
  1257. "300",
  1258. timeout=10,
  1259. )
  1260. time.sleep(0.4)
  1261. if node is None:
  1262. ctx.records["ui_after"] = dump
  1263. return
  1264. x, y = node_center(node)
  1265. adb(ctx.device, "shell", "input", "tap", str(x), str(y), timeout=10)
  1266. ctx.action_count += 1
  1267. opened, dump, _ = wait_until_text_present(
  1268. ctx.device,
  1269. "保存当前设置",
  1270. ctx.scenario.get("readyTimeoutSeconds", 30),
  1271. )
  1272. ctx.records["theme_manage_opened"] = opened
  1273. ctx.records["ui_after"] = dump
  1274. ctx.screenshot("manageScreenshot", "manage.png")
  1275. @register_action("select_day_background")
  1276. class SelectDayBackground(Action):
  1277. def run(self, ctx: Context, action: dict[str, Any]) -> None:
  1278. if not ctx.records.get("theme_config_ready"):
  1279. return
  1280. fixture = PROJECT_ROOT / "app" / "src" / "main" / "assets" / "web" / "uploadBook" / "img" / "close.png"
  1281. remote_fixture = "/sdcard/Download/DEBUG_THEME_BG.png"
  1282. remote_folder = f"/sdcard/Android/data/{PACKAGE}/files/backgroundImage"
  1283. adb(ctx.device, "shell", "rm", "-rf", remote_folder, timeout=10, check=False)
  1284. run_command(["adb", "-s", ctx.device, "push", str(fixture), remote_fixture], timeout=30)
  1285. adb(
  1286. ctx.device,
  1287. "shell",
  1288. "am",
  1289. "broadcast",
  1290. "-a",
  1291. "android.intent.action.MEDIA_SCANNER_SCAN_FILE",
  1292. "-d",
  1293. f"file://{remote_fixture}",
  1294. timeout=15,
  1295. check=False,
  1296. )
  1297. day_node = None
  1298. dump = ""
  1299. width, height = screen_size(ctx.device)
  1300. for _ in range(8):
  1301. dump = ui_dump(ctx.device)
  1302. day_node = find_node_by_text(dump, "白天")
  1303. if day_node is not None:
  1304. break
  1305. adb(
  1306. ctx.device,
  1307. "shell",
  1308. "input",
  1309. "swipe",
  1310. str(width // 2),
  1311. str(round(height * 0.84)),
  1312. str(width // 2),
  1313. str(round(height * 0.48)),
  1314. "300",
  1315. timeout=10,
  1316. )
  1317. time.sleep(0.4)
  1318. if day_node is None:
  1319. ctx.records["ui_after"] = dump
  1320. return
  1321. x, y = node_center(day_node)
  1322. adb(ctx.device, "shell", "input", "tap", str(x), str(y), timeout=10)
  1323. ctx.action_count += 1
  1324. deadline = time.monotonic() + 10
  1325. add_node = None
  1326. while time.monotonic() < deadline:
  1327. dump = ui_dump(ctx.device)
  1328. add_node = find_node_by_content_prefix(dump, "添加")
  1329. if add_node is not None:
  1330. break
  1331. time.sleep(0.2)
  1332. if add_node is None:
  1333. ctx.records["ui_after"] = dump
  1334. return
  1335. x, y = node_center(add_node)
  1336. adb(ctx.device, "shell", "input", "tap", str(x), str(y), timeout=10)
  1337. ctx.action_count += 1
  1338. filename_node = None
  1339. deadline = time.monotonic() + 5
  1340. while time.monotonic() < deadline:
  1341. dump = ui_dump(ctx.device)
  1342. filename_node = find_node_by_text(dump, "DEBUG_THEME_BG.png")
  1343. if filename_node is not None:
  1344. break
  1345. more_node = find_node_by_content_prefix(
  1346. dump,
  1347. "更多",
  1348. "com.google.android.photopicker",
  1349. )
  1350. if more_node is not None:
  1351. x, y = node_center(more_node)
  1352. adb(ctx.device, "shell", "input", "tap", str(x), str(y), timeout=10)
  1353. browse_node = None
  1354. browse_deadline = time.monotonic() + 5
  1355. while time.monotonic() < browse_deadline:
  1356. dump = ui_dump(ctx.device)
  1357. browse_node = find_node_by_text(
  1358. dump,
  1359. "浏览…",
  1360. "com.google.android.photopicker",
  1361. )
  1362. if browse_node is not None:
  1363. break
  1364. time.sleep(0.2)
  1365. if browse_node is not None:
  1366. x, y = node_center(browse_node)
  1367. adb(ctx.device, "shell", "input", "tap", str(x), str(y), timeout=10)
  1368. break
  1369. time.sleep(0.25)
  1370. if filename_node is None:
  1371. deadline = time.monotonic() + 15
  1372. download_opened = False
  1373. while time.monotonic() < deadline:
  1374. dump = ui_dump(ctx.device)
  1375. filename_node = find_node_by_text(
  1376. dump,
  1377. "DEBUG_THEME_BG.png",
  1378. "com.google.android.documentsui",
  1379. )
  1380. if filename_node is not None:
  1381. break
  1382. download_node = find_node_by_text(
  1383. dump,
  1384. "下载",
  1385. "com.google.android.documentsui",
  1386. )
  1387. if download_node is not None and not download_opened:
  1388. x, y = node_center(download_node)
  1389. adb(ctx.device, "shell", "input", "tap", str(x), str(y), timeout=10)
  1390. download_opened = True
  1391. elif download_opened:
  1392. adb(
  1393. ctx.device,
  1394. "shell",
  1395. "input",
  1396. "swipe",
  1397. str(width // 2),
  1398. str(round(height * 0.82)),
  1399. str(width // 2),
  1400. str(round(height * 0.40)),
  1401. "250",
  1402. timeout=10,
  1403. )
  1404. time.sleep(0.4)
  1405. if filename_node is None:
  1406. ctx.records["ui_after"] = dump
  1407. return
  1408. x, y = node_center(filename_node)
  1409. adb(ctx.device, "shell", "input", "tap", str(x), str(y), timeout=10)
  1410. ctx.action_count += 1
  1411. wait_until_activity_resumed(
  1412. ctx.device,
  1413. MAIN_ACTIVITY,
  1414. ctx.scenario.get("readyTimeoutSeconds", 30),
  1415. )
  1416. expected_hash = hashlib.sha256(fixture.read_bytes()).hexdigest()
  1417. copied_path = ""
  1418. deadline = time.monotonic() + ctx.scenario.get("readyTimeoutSeconds", 30)
  1419. while time.monotonic() < deadline:
  1420. result = adb(
  1421. ctx.device,
  1422. "shell",
  1423. "find",
  1424. remote_folder,
  1425. "-type",
  1426. "f",
  1427. timeout=10,
  1428. check=False,
  1429. )
  1430. candidates = [line.strip() for line in result.stdout.splitlines() if line.strip()]
  1431. for candidate in candidates:
  1432. digest = adb(
  1433. ctx.device,
  1434. "shell",
  1435. "sha256sum",
  1436. candidate,
  1437. timeout=10,
  1438. check=False,
  1439. ).stdout.split()
  1440. if digest and digest[0] == expected_hash:
  1441. copied_path = candidate
  1442. break
  1443. if copied_path:
  1444. break
  1445. time.sleep(0.25)
  1446. adb(ctx.device, "shell", "rm", "-f", remote_fixture, timeout=10, check=False)
  1447. ctx.records["theme_day_background_copied"] = bool(copied_path)
  1448. ctx.state["day_background_path"] = copied_path
  1449. ctx.records["ui_after"] = ui_dump(ctx.device)
  1450. ctx.screenshot("backgroundScreenshot", "background.png")
  1451. @register_action("save_current_theme")
  1452. class SaveCurrentTheme(Action):
  1453. params = {"namePrefix": "non-empty ASCII string"}
  1454. def validate(self, action: dict[str, Any], index: int) -> None:
  1455. prefix = action.get("namePrefix")
  1456. if not isinstance(prefix, str) or not re.fullmatch(r"[A-Za-z0-9_-]+", prefix):
  1457. raise ScenarioError(f"actions[{index}].namePrefix must be non-empty ASCII")
  1458. def run(self, ctx: Context, action: dict[str, Any]) -> None:
  1459. if not ctx.records.get("theme_manage_opened"):
  1460. return
  1461. theme_name = f"{action['namePrefix']}_{ctx.metadata['sessionId']}"
  1462. ctx.state["theme_name"] = theme_name
  1463. ready, _, save_current = wait_until_text_present(ctx.device, "保存当前设置", 10)
  1464. if not (ready and save_current):
  1465. return
  1466. x, y = node_center(save_current)
  1467. adb(ctx.device, "shell", "input", "tap", str(x), str(y), timeout=10)
  1468. ctx.action_count += 1
  1469. deadline = time.monotonic() + 10
  1470. edit = None
  1471. dump = ""
  1472. while time.monotonic() < deadline:
  1473. dump = ui_dump(ctx.device)
  1474. edit = find_node_by_class(dump, "android.widget.EditText")
  1475. if edit is not None:
  1476. break
  1477. time.sleep(0.2)
  1478. if edit is None:
  1479. ctx.records["ui_after"] = dump
  1480. return
  1481. x, y = node_center(edit)
  1482. adb(ctx.device, "shell", "input", "tap", str(x), str(y), timeout=10)
  1483. adb(ctx.device, "shell", "input", "text", theme_name, timeout=10)
  1484. dump = ui_dump(ctx.device)
  1485. confirm = find_node_by_text(dump, "保存")
  1486. if confirm is None:
  1487. ctx.records["ui_after"] = dump
  1488. return
  1489. if ctx.scenario.get("themeAsset") == "missing-content-uri":
  1490. arm_theme_content_failure(ctx.device)
  1491. x, y = node_center(confirm)
  1492. adb(ctx.device, "shell", "input", "tap", str(x), str(y), timeout=10)
  1493. ctx.action_count += 1
  1494. deadline = time.monotonic() + ctx.scenario.get("readyTimeoutSeconds", 30)
  1495. succeeded = False
  1496. failure_feedback = ""
  1497. while time.monotonic() < deadline:
  1498. if saved_theme_exists(ctx.device, theme_name):
  1499. succeeded = True
  1500. break
  1501. dump = ui_dump(ctx.device)
  1502. failure_node = find_node_containing_text(dump, "主题保存失败")
  1503. if failure_node is not None:
  1504. failure_feedback = failure_node.get("text", "")
  1505. break
  1506. time.sleep(0.25)
  1507. ctx.records["theme_save_succeeded"] = succeeded
  1508. ctx.records["theme_save_failed"] = not succeeded and bool(failure_feedback)
  1509. ctx.records["theme_failure_feedback"] = bool(failure_feedback)
  1510. if failure_feedback:
  1511. ctx.state["theme_failure_feedback"] = failure_feedback
  1512. if succeeded and ctx.scenario.get("themeAsset") == "valid-file":
  1513. ctx.records["theme_save_asset_included"] = saved_theme_has_fixture_asset(
  1514. ctx.device,
  1515. theme_name,
  1516. )
  1517. ctx.records["ui_after"] = ui_dump(ctx.device)
  1518. @register_action("export_current_theme")
  1519. class ExportCurrentTheme(Action):
  1520. params = {"namePrefix": "non-empty ASCII string"}
  1521. def validate(self, action: dict[str, Any], index: int) -> None:
  1522. prefix = action.get("namePrefix")
  1523. if not isinstance(prefix, str) or not re.fullmatch(r"[A-Za-z0-9_-]+", prefix):
  1524. raise ScenarioError(f"actions[{index}].namePrefix must be non-empty ASCII")
  1525. def run(self, ctx: Context, action: dict[str, Any]) -> None:
  1526. if not ctx.records.get("theme_manage_opened"):
  1527. return
  1528. export_name = f"{action['namePrefix']}_{ctx.metadata['sessionId']}.zip"
  1529. ctx.state["export_name"] = export_name
  1530. remote_path = f"/sdcard/Download/{export_name}"
  1531. adb(ctx.device, "shell", "rm", "-f", remote_path, timeout=10, check=False)
  1532. ready, _, export_current = wait_until_text_present(ctx.device, "导出当前主题", 10)
  1533. if not (ready and export_current):
  1534. return
  1535. x, y = node_center(export_current)
  1536. adb(ctx.device, "shell", "input", "tap", str(x), str(y), timeout=10)
  1537. ctx.action_count += 1
  1538. deadline = time.monotonic() + 15
  1539. filename_node = None
  1540. while time.monotonic() < deadline:
  1541. dump = ui_dump(ctx.device)
  1542. filename_node = next(
  1543. (
  1544. node
  1545. for node in parse_ui_nodes(dump)
  1546. if node.get("package") == "com.google.android.documentsui"
  1547. and node.get("class") == "android.widget.EditText"
  1548. ),
  1549. None,
  1550. )
  1551. if filename_node is not None:
  1552. break
  1553. time.sleep(0.25)
  1554. if filename_node is None:
  1555. return
  1556. x, y = node_center(filename_node)
  1557. adb(ctx.device, "shell", "input", "tap", str(x), str(y), timeout=10)
  1558. adb(ctx.device, "shell", "input", "keyevent", "KEYCODE_MOVE_END", timeout=10)
  1559. for _ in range(80):
  1560. adb(ctx.device, "shell", "input", "keyevent", "KEYCODE_DEL", timeout=10)
  1561. adb(ctx.device, "shell", "input", "text", export_name, timeout=10)
  1562. dump = ui_dump(ctx.device)
  1563. save_node = next(
  1564. (
  1565. node
  1566. for node in parse_ui_nodes(dump)
  1567. if node.get("package") == "com.google.android.documentsui"
  1568. and node.get("resource-id") == "android:id/button1"
  1569. ),
  1570. None,
  1571. )
  1572. if save_node is None:
  1573. ctx.records["ui_after"] = dump
  1574. return
  1575. if ctx.scenario.get("themeAsset") == "missing-content-uri":
  1576. arm_theme_content_failure(ctx.device)
  1577. x, y = node_center(save_node)
  1578. adb(ctx.device, "shell", "input", "tap", str(x), str(y), timeout=10)
  1579. ctx.action_count += 1
  1580. local_path = ctx.run_dir / "export.zip"
  1581. deadline = time.monotonic() + ctx.scenario.get("readyTimeoutSeconds", 30)
  1582. pulled = False
  1583. wait_until_activity_resumed(
  1584. ctx.device,
  1585. MAIN_ACTIVITY,
  1586. ctx.scenario.get("readyTimeoutSeconds", 30),
  1587. )
  1588. last_size = -1
  1589. stable_reads = 0
  1590. failure_feedback = ""
  1591. while time.monotonic() < deadline:
  1592. dump = ui_dump(ctx.device)
  1593. failure_node = find_node_containing_text(dump, "主题导出失败")
  1594. if failure_node is not None:
  1595. failure_feedback = failure_node.get("text", "")
  1596. size_result = adb(
  1597. ctx.device,
  1598. "shell",
  1599. "stat",
  1600. "-c",
  1601. "%s",
  1602. remote_path,
  1603. timeout=10,
  1604. check=False,
  1605. )
  1606. try:
  1607. size = int(size_result.stdout.strip())
  1608. except ValueError:
  1609. size = 0
  1610. stable_reads = stable_reads + 1 if size > 0 and size == last_size else 0
  1611. last_size = size
  1612. if stable_reads < 2:
  1613. time.sleep(0.25)
  1614. continue
  1615. pull = run_command(
  1616. ["adb", "-s", ctx.device, "pull", remote_path, str(local_path)],
  1617. timeout=30,
  1618. check=False,
  1619. )
  1620. if pull.returncode == 0 and local_path.is_file() and local_path.stat().st_size > 0:
  1621. pulled = True
  1622. break
  1623. time.sleep(0.5)
  1624. valid = False
  1625. asset_included = False
  1626. if pulled:
  1627. try:
  1628. with zipfile.ZipFile(local_path) as archive:
  1629. manifest = json.loads(archive.read(THEME_MANIFEST_PATH).decode("utf-8"))
  1630. valid = manifest.get("formatVersion") == 1 and isinstance(manifest.get("config"), dict)
  1631. entry = (manifest.get("assets") or {}).get("background.light")
  1632. if isinstance(entry, str) and entry in archive.namelist():
  1633. expected = hashlib.sha256(THEME_ASSET_FIXTURE.read_bytes()).hexdigest()
  1634. asset_included = hashlib.sha256(archive.read(entry)).hexdigest() == expected
  1635. except (OSError, KeyError, json.JSONDecodeError, zipfile.BadZipFile):
  1636. valid = False
  1637. adb(ctx.device, "shell", "rm", "-f", remote_path, timeout=10, check=False)
  1638. if valid:
  1639. ctx.artifacts["exportedTheme"] = "export.zip"
  1640. ctx.records["theme_export_succeeded"] = valid
  1641. ctx.records["theme_export_failed"] = not valid and bool(failure_feedback)
  1642. ctx.records["theme_failure_feedback"] = bool(failure_feedback)
  1643. if failure_feedback:
  1644. ctx.state["theme_failure_feedback"] = failure_feedback
  1645. ctx.records["theme_export_asset_included"] = asset_included
  1646. ctx.records["ui_after"] = ui_dump(ctx.device)
  1647. ASSERTIONS.update(
  1648. {
  1649. "reader_ready": lambda ctx: bool(ctx.records.get("reader_ready")),
  1650. "reader_activity_visible": lambda ctx: bool(ctx.records.get("reader_activity_visible")),
  1651. "reader_content_changed": lambda ctx: bool(ctx.records.get("reader_content_changed")),
  1652. "bookshelf_ready": lambda ctx: bool(ctx.records.get("bookshelf_ready")),
  1653. "reader_opened": lambda ctx: bool(ctx.records.get("reader_opened")),
  1654. "returned_to_bookshelf": lambda ctx: bool(ctx.records.get("returned_to_bookshelf")),
  1655. "source_manage_ready": lambda ctx: bool(ctx.records.get("source_manage_ready")),
  1656. "source_edit_opened": lambda ctx: bool(ctx.records.get("source_edit_opened")),
  1657. "returned_to_source_manage": lambda ctx: bool(ctx.records.get("returned_to_source_manage")),
  1658. "theme_config_ready": lambda ctx: bool(ctx.records.get("theme_config_ready")),
  1659. "theme_manage_opened": lambda ctx: bool(ctx.records.get("theme_manage_opened")),
  1660. "theme_save_succeeded": lambda ctx: bool(ctx.records.get("theme_save_succeeded")),
  1661. "theme_export_succeeded": lambda ctx: bool(ctx.records.get("theme_export_succeeded")),
  1662. "theme_day_background_copied": lambda ctx: bool(ctx.records.get("theme_day_background_copied")),
  1663. "theme_save_asset_included": lambda ctx: bool(ctx.records.get("theme_save_asset_included")),
  1664. "theme_export_asset_included": lambda ctx: bool(ctx.records.get("theme_export_asset_included")),
  1665. "theme_save_failed": lambda ctx: bool(ctx.records.get("theme_save_failed")),
  1666. "theme_export_failed": lambda ctx: bool(ctx.records.get("theme_export_failed")),
  1667. "theme_failure_feedback": lambda ctx: bool(ctx.records.get("theme_failure_feedback")),
  1668. "theme_open_input_stream_reached": lambda ctx: bool(ctx.records.get("theme_open_input_stream_reached")),
  1669. "theme_content_failure_armed": lambda ctx: bool(ctx.records.get("theme_content_failure_armed")),
  1670. "no_fatal_exception": lambda ctx: ctx.failure is None,
  1671. }
  1672. )
  1673. def build_capabilities() -> dict[str, Any]:
  1674. return {
  1675. "schemaVersion": 1,
  1676. "entries": {
  1677. name: {"allowedActions": sorted(handler.allowed_actions)}
  1678. for name, handler in sorted(ENTRIES.items())
  1679. },
  1680. "actions": {
  1681. name: {"params": handler.params}
  1682. for name, handler in sorted(ACTIONS.items())
  1683. },
  1684. "assertions": sorted(ASSERTIONS),
  1685. }
  1686. def execute(args: argparse.Namespace) -> int:
  1687. try:
  1688. scenario = load_scenario(args.scenario)
  1689. fixture = args.fixture or scenario["fixture"]
  1690. fixture_data = validate_fixture(fixture)
  1691. markers = {chapter["readyMarker"] for chapter in fixture_data["chapters"]}
  1692. if scenario["readyMarker"] not in markers:
  1693. raise ScenarioError("scenario readyMarker is not provided by the fixture")
  1694. if args.action_repeat < 1 or args.action_repeat > 100:
  1695. raise ScenarioError("--action-repeat must be between 1 and 100")
  1696. if scenario["entry"]["type"] == "bookshelf" and args.action_repeat != 1:
  1697. raise ScenarioError("--action-repeat is only supported by reader scenarios")
  1698. except ScenarioError as error:
  1699. print(json.dumps({"status": "failed", "exitCode": EXIT_SCENARIO, "error": str(error)}, ensure_ascii=False))
  1700. return EXIT_SCENARIO
  1701. try:
  1702. device = select_device(args.device)
  1703. except (RuntimeError, CommandError, subprocess.TimeoutExpired, OSError) as error:
  1704. session_id, run_dir, _ = create_session(args.scenario, fixture, args.device)
  1705. summary = error_summary(session_id, args.scenario, fixture, EXIT_ENVIRONMENT, "environment", str(error))
  1706. write_json(run_dir / "summary.json", summary)
  1707. print(run_dir / "summary.json")
  1708. return EXIT_ENVIRONMENT
  1709. session_id, run_dir, metadata = create_session(args.scenario, fixture, device)
  1710. device_state: dict[str, Any] | None = None
  1711. try:
  1712. device_state = prepare_device(device)
  1713. metadata["deviceStateBefore"] = device_state
  1714. write_json(run_dir / "metadata.json", metadata)
  1715. except (RuntimeError, CommandError, subprocess.TimeoutExpired, OSError) as error:
  1716. summary = error_summary(session_id, args.scenario, fixture, EXIT_ENVIRONMENT, "environment", str(error))
  1717. write_json(run_dir / "summary.json", summary)
  1718. print(run_dir / "summary.json")
  1719. return EXIT_ENVIRONMENT
  1720. build: dict[str, Any] = {"status": "not_started"}
  1721. if args.skip_build:
  1722. build = {"status": "skipped"}
  1723. else:
  1724. try:
  1725. build, _ = build_and_install(device, run_dir)
  1726. except (RuntimeError, CommandError, subprocess.TimeoutExpired) as error:
  1727. if isinstance(error, CommandError):
  1728. build = {
  1729. "status": "failed",
  1730. "artifact": "build.log" if (run_dir / "build.log").exists() else "install.log",
  1731. }
  1732. summary = error_summary(session_id, args.scenario, fixture, EXIT_BUILD, "build_or_install", str(error), build)
  1733. cleanup_device(device)
  1734. restore_device(device, device_state)
  1735. write_json(run_dir / "summary.json", summary)
  1736. print(run_dir / "summary.json")
  1737. return EXIT_BUILD
  1738. entry_handler = ENTRIES[scenario["entry"]["type"]]
  1739. ctx = Context(device, run_dir, scenario, fixture_data, metadata, args.action_repeat)
  1740. recorder = ScreenRecorder(device) if scenario.get("record") else None
  1741. try:
  1742. if entry_handler.type == "theme_config":
  1743. # Activity result contracts can leave their external picker task
  1744. # above Legado after a failed run. Close both implementations used
  1745. # by this device before launching a deterministic theme scenario.
  1746. for picker_package in (
  1747. "com.google.android.documentsui",
  1748. "com.google.android.photopicker",
  1749. ):
  1750. adb(
  1751. device,
  1752. "shell",
  1753. "am",
  1754. "force-stop",
  1755. picker_package,
  1756. timeout=20,
  1757. check=False,
  1758. )
  1759. preferences = prepare_theme_asset(device, scenario) if entry_handler.type == "theme_config" else scenario.get("preferences")
  1760. launch_fixture(device, fixture, entry_handler.type, session_id, preferences)
  1761. ctx.note_pid()
  1762. entry_handler.prepare(ctx)
  1763. if recorder is not None:
  1764. recorder.start()
  1765. for action in scenario["actions"]:
  1766. ACTIONS[action["type"]].run(ctx, action)
  1767. if recorder is not None:
  1768. time.sleep(0.5) # tail so the settle after the last action is captured
  1769. video = recorder.stop(run_dir)
  1770. if video:
  1771. ctx.artifacts["transition"] = video
  1772. entry_handler.finalize(ctx)
  1773. ctx.note_pid()
  1774. logcat = collect_logcat(device, run_dir, ctx.app_pids, session_id)
  1775. ctx.failure = parse_failure(extract_crash(logcat, PACKAGE, ctx.app_pids))
  1776. toast_signal = (
  1777. f"Toast already killed. pkg={PACKAGE}" in logcat
  1778. or f"pkg={PACKAGE}" in logcat and "enqueueToast" in logcat
  1779. )
  1780. open_input_stream_reached = "INJECTED_THEME_ASSET_OPEN" in logcat
  1781. failure_armed = "INJECTED_THEME_ASSET_FAILURE_ARMED" in logcat
  1782. ctx.records["theme_open_input_stream_reached"] = open_input_stream_reached
  1783. ctx.records["theme_content_failure_armed"] = failure_armed
  1784. if scenario.get("themeAsset") in {"missing-file", "missing-content-uri"}:
  1785. ctx.records["theme_failure_feedback"] = bool(
  1786. ctx.records.get("theme_failure_feedback") or toast_signal
  1787. )
  1788. if any(action["type"] == "save_current_theme" for action in scenario["actions"]):
  1789. ctx.records["theme_save_failed"] = (
  1790. not ctx.records.get("theme_save_succeeded")
  1791. and ctx.records["theme_failure_feedback"]
  1792. )
  1793. if any(action["type"] == "export_current_theme" for action in scenario["actions"]):
  1794. ctx.records["theme_export_failed"] = (
  1795. not ctx.records.get("theme_export_succeeded")
  1796. and ctx.records["theme_failure_feedback"]
  1797. )
  1798. metadata["themeOpenInputStreamReached"] = open_input_stream_reached
  1799. metadata["themeContentFailureArmed"] = failure_armed
  1800. metadata["themeFailureFeedbackObserved"] = bool(ctx.records.get("theme_failure_feedback"))
  1801. for name in scenario["assertions"]:
  1802. ctx.assertion_values[name] = ASSERTIONS[name](ctx)
  1803. metadata.update(
  1804. {
  1805. "finishedAt": dt.datetime.now().astimezone().isoformat(timespec="milliseconds"),
  1806. "appPids": ctx.app_pids,
  1807. }
  1808. )
  1809. write_json(run_dir / "metadata.json", metadata)
  1810. summary, exit_code = make_summary_from_assertions(
  1811. session_id=session_id,
  1812. scenario=scenario,
  1813. fixture=fixture,
  1814. build=build,
  1815. assertion_values=ctx.assertion_values,
  1816. action_count=ctx.action_count,
  1817. failure=ctx.failure,
  1818. extra_artifacts=ctx.artifacts,
  1819. )
  1820. except (RuntimeError, CommandError, subprocess.TimeoutExpired, OSError) as error:
  1821. try:
  1822. ctx.note_pid()
  1823. collect_logcat(device, run_dir, ctx.app_pids, session_id)
  1824. except Exception:
  1825. pass
  1826. summary = error_summary(
  1827. session_id,
  1828. args.scenario,
  1829. fixture,
  1830. EXIT_ENVIRONMENT,
  1831. "environment",
  1832. str(error),
  1833. build,
  1834. )
  1835. exit_code = EXIT_ENVIRONMENT
  1836. finally:
  1837. if recorder is not None:
  1838. recorder.stop(run_dir)
  1839. cleanup_device(device)
  1840. restore_device(device, device_state)
  1841. write_json(run_dir / "summary.json", summary)
  1842. print(run_dir / "summary.json")
  1843. return exit_code
  1844. def parse_args(argv: Sequence[str]) -> argparse.Namespace:
  1845. parser = argparse.ArgumentParser(description=__doc__)
  1846. subparsers = parser.add_subparsers(dest="command", required=True)
  1847. run_parser = subparsers.add_parser("run", help="build, install, and run one scenario")
  1848. run_parser.add_argument("scenario", help="scenario ID, for example reader/page-turn")
  1849. run_parser.add_argument("--device", help="adb device serial; optional when exactly one is ready")
  1850. run_parser.add_argument("--fixture", help="override the scenario fixture ID")
  1851. run_parser.add_argument("--action-repeat", type=int, default=1, help="repeat each domain action (default: 1)")
  1852. run_parser.add_argument(
  1853. "--skip-build",
  1854. action="store_true",
  1855. help="reuse the installed debug APK; skip Gradle build and install",
  1856. )
  1857. subparsers.add_parser("list", help="print supported entries, actions, and assertions")
  1858. return parser.parse_args(argv)
  1859. def main(argv: Sequence[str] | None = None) -> int:
  1860. args = parse_args(argv if argv is not None else sys.argv[1:])
  1861. if args.command == "run":
  1862. return execute(args)
  1863. if args.command == "list":
  1864. print(json.dumps(build_capabilities(), ensure_ascii=False, indent=2))
  1865. return 0
  1866. return EXIT_SCENARIO
  1867. if __name__ == "__main__":
  1868. raise SystemExit(main())