runner.py 83 KB

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