#!/usr/bin/env python3 """COMPUTATION lane for NextPlayer (package = argv[1]; NEVER a literal). This lane owns input -> output VALUE tests: a user feeds an input through the real UI path and the app DERIVES a specific value that we read back and assert against the value OBSERVED on the running original (never computed here, never read from source). It is the sole owner of jump_kind="value". The app is a video player, so its "computations" are: A) SEARCH FILTER COUNT (Home -> Search icon -> type a query -> the results screen shows a header "Videos (N)" / "Folders (N)" and the matching rows). The count and which rows appear are DERIVED from the query against the 3 fixture videos. Ground truth OBSERVED on the original: "beta" -> Videos (1), row beta_movie (alpha/gamma absent) "gamma" -> Videos (1), row gamma_reel "clip" -> Videos (1), row alpha_clip (matches alpha_clip's title) "movie" -> Videos (1), row beta_movie "a" -> Folders (1) + Videos (3), all three rows (substring in all) "_" -> Videos (3), all three rows, NO Folders header (folder name has no '_') "zzzznomatch" -> NO Videos/Folders header, none of the three rows The strongest, most robust value surface, so several variants live here. B) PLAYBACK-SPEED dialog (Player -> speed icon -> "Select playback speed"): a big current-value TextView, a chip grid (0.2 .. 4.0), and a -/+ stepper. OBSERVED: tapping the "2.0" chip sets the big value to "2.0", the "0.5" chip to "0.5"; the "+" stepper increments by 0.1. depth=3 (folder -> player -> dialog). The dialog opens at the app's REMEMBERED speed (Remember selections persists it), so chip tests assert the ABSOLUTE value (chip-independent of the start) and the stepper test asserts start + 0.1 read off the SAME dialog. C) FOLDER DURATION AGGREGATE (Home): the Download folder row shows a total duration badge derived from its 3 clips (00:05 + 00:08 + 00:03 = "00:16") and a "3 Videos" count chip. depth=0, a derived aggregate value. The speed VALUE, the search COUNT header, and the folder duration are all plain TEXT in the tree, so every core assertion is a rule (dump) assertion; VLM is used for exactly three rendered-property confirmations as OR-companions. Fixtures: the 3 sample videos (alpha_clip.mp4 / beta_movie.mp4 / gamma_reel.mp4) are authored into fixtures/ and mirrored to the device by push_fixtures() (called by run_suite()); every test reaches them through the picker, never a pushed path. """ import os import sys import time sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from android_testgen_kit import * # noqa: F403,E402 require_kit(1) # ── Ground-truth constants (strings/values OBSERVED on the running original) ───── FOLDER_NAME = "Download" VIDEO_TITLES = ("alpha_clip", "beta_movie", "gamma_reel") FIXTURE_VIDEOS = ("alpha_clip.mp4", "beta_movie.mp4", "gamma_reel.mp4") PLAYER_MARKER = "Play/Pause" # content-desc unique to the player SPEED_DIALOG_TITLE = "Select playback speed" FOLDER_TOTAL_DURATION = "00:16" # 00:05 + 00:08 + 00:03, observed FOLDER_COUNT_CHIP = "3 Videos" SPEED_STEP = 0.1 # observed "+"/"−" increment # ══════════════════════════════════════════════════════════════════════════════ # Setup / navigation helpers. Navigation helpers are named and_enter_* / # and_reach_* so an and_enter() call backs every declared depth>=1 (audit_depth). # ══════════════════════════════════════════════════════════════════════════════ def and_grant_media(): """Tap the runtime media-permission 'Allow all' if it is showing (no-op otherwise). restart_app() keeps the grant, so this is only a safety net.""" for label in ("Allow all", "While using the app", "Allow"): n = find_node_ci(ui(), label) if n: tap_node(n) settle("tap") return True return False def _home_ready(nodes): """True once the Home picker has actually rendered its media list.""" return bool(find_node(nodes, text=FOLDER_NAME)) or any( find_node(nodes, text=t) for t in VIDEO_TITLES) def home_ready(): """Mirror fixtures, restart (keeps the media grant), wait until Home actually rendered, return fresh Home nodes. Retries the launch once.""" push_fixtures() _ = [fixture_on_device(v) for v in FIXTURE_VIDEOS] # explicit dependency nodes = [] for _attempt in range(2): restart_app() if not wait_for_foreground(): continue and_grant_media() for _ in range(6): nodes = ui() if _home_ready(nodes): return nodes settle("dump") if _home_ready(nodes): break return nodes def tap_topbar(nodes, desc): """Tap a top-bar icon by content-desc. The desc node itself is not clickable — its parent View is — so tap the tightest clickable ancestor by bounds containment, falling back to the desc node's centre.""" target = find_node(nodes, content_desc=desc) if not target or "_bounds" not in target: return False tcx, tcy = target["_center"] best, best_area = None, None for n in nodes: if n.get("clickable") != "true" or "_bounds" not in n: continue x1, y1, x2, y2 = n["_bounds"] if x1 <= tcx <= x2 and y1 <= tcy <= y2: area = (x2 - x1) * (y2 - y1) if best_area is None or area < best_area: best, best_area = n, area return tap_node(best) if best else tap_node(target) def find_folder_row(nodes): """The TIGHTEST clickable node that contains the 'Download' label — the tappable row, never the full-screen root container. Falls back to the smallest bounded (non-full-screen) container, then to the label node itself.""" label = find_node(nodes, text=FOLDER_NAME) if not label or "_bounds" not in label: return None lx, ly = label["_center"] s = get_screen_info() clickable_best, clickable_area = None, None box_best, box_area = None, None for n in nodes: b = n.get("_bounds") if not b: continue x1, y1, x2, y2 = b if not (x1 <= lx <= x2 and y1 <= ly <= y2): continue w, h = x2 - x1, y2 - y1 if w < 200 or h < 60: continue # never the whole screen (the root container swallows every tap) if w >= s["width"] and h >= int(s["height"] * 0.8): continue area = w * h if n.get("clickable") == "true": if clickable_area is None or area < clickable_area: clickable_best, clickable_area = n, area if box_area is None or area < box_area: box_best, box_area = n, area return clickable_best or box_best or label def _headers(nodes): """Every 'Videos (N)' / 'Folders (N)' header string currently on screen.""" out = [] for n in find_by_class(nodes, "TextView"): t = n.get("text", "").strip() if t.startswith("Videos (") or t.startswith("Folders ("): out.append(t) return out def _videos_header(headers): for h in headers: if h.startswith("Videos ("): return h return "" def and_reach_search(nodes): """Home -> tap the Search top-bar icon -> Search screen (an EditText appears). Proves the jump and counts one surface. Returns fresh search nodes or []. The topbar tap occasionally lands before the icon is laid out, so it is retried (re-dumping Home between tries) until the search EditText appears.""" for _ in range(3): if not tap_topbar(nodes, "Search"): nodes = ui() continue settle("tap") after_nodes = ui() if find_by_class(after_nodes, "EditText"): and_enter("search") return after_nodes nodes = ui() if not find_node(nodes, content_desc="Search"): break # navigated elsewhere; bail return [] def run_search(query): """Home -> Search -> type `query` -> return (fresh result nodes, headers list). Retries the whole reach+type once, because the very first search after a fresh launch can miss the search-icon tap (observed as a lone transient flake).""" for _attempt in range(2): home = home_ready() snodes = and_reach_search(home) if snodes: eds = find_by_class(snodes, "EditText") if eds and type_text(eds[0], query): settle("keyboard") r = ui() return r, _headers(r) and_reset_depth() return None, [] # ── Player / speed-dialog helpers (depth family) ──────────────────────────────── def dump_center(nodes): """Centre of the CURRENT display in the dump's own (rotated) coordinate frame. The player is landscape but `wm size` still reports portrait, so get_screen_info() cannot be trusted there; the dump's root bounds are correct.""" maxx = max((b[2] for b in (n.get("_bounds") for n in nodes) if b), default=0) maxy = max((b[3] for b in (n.get("_bounds") for n in nodes) if b), default=0) return (maxx // 2, maxy // 2) if maxx and maxy else (0, 0) def raw_tap_node(node): """Tap a node's centre with a RAW `input tap`, bypassing tap_node's bounds check. In the landscape PlayerActivity, get_screen_info() reports the portrait size (wm size never rotates), so tap_node wrongly rejects any x beyond the portrait width — every chip/stepper in the landscape speed dialog. This taps the real (rotated) coordinate directly.""" if not node or "_center" not in node: return False x, y = node["_center"] adb_shell("input", "tap", int(x), int(y)) settle("tap") return True def reveal_player_controls(): """Tap the (rotated) centre until the auto-hiding controls are up. Returns fresh player nodes once 'Play/Pause' is present, else the last dump.""" for _ in range(8): nodes = ui() if find_node(nodes, content_desc=PLAYER_MARKER): return nodes cx, cy = dump_center(nodes) if not cx: break tap(cx, cy) time.sleep(0.25) return ui() def _loop_node(nodes): for n in nodes: if (n.get("content-desc", "") or "").startswith("Loop"): return n return None def _topright_icons(nodes): """The four top-right icon Buttons in the player, sorted left->right. Index 1 (2nd from left) is the playback-speed icon (observed).""" cx = dump_center(nodes)[0] btns = [n for n in nodes if "Button" in n.get("class", "") and "_bounds" in n and n["_bounds"][1] < 230 and n["_bounds"][0] > cx] btns.sort(key=lambda n: n["_bounds"][0]) return btns def and_enter_player(title="beta_movie"): """Home -> Download folder -> tap a video row -> PlayerActivity (autoplays). Enables Loop so the short clip keeps replaying (never exits mid-test), reveals the controls, and counts TWO surfaces (folder, player). Returns player nodes or [].""" home = home_ready() if not find_node(home, text=FOLDER_NAME): return [] # Open the folder and CONFIRM it opened (the video rows appear). The row tap can # miss on the first go, so retry from a fresh Home a couple of times. fnodes = [] for _ in range(3): folder = find_folder_row(home) or find_node(home, text=FOLDER_NAME) tap_node(folder) settle("tap") fnodes = ui() if find_node(fnodes, text=title) or find_node(fnodes, content_desc="Navigate up"): break home = home_ready() if not find_node(fnodes, text=title): return [] and_enter("folder") # surface 1 row = find_node(fnodes, text=title) before = and_showing(fnodes) tap_node(row) settle("launch") # PlayerActivity + autoplay import android_testgen_kit as _kit _kit._screen_info = None # invalidate wrong geometry pnodes = reveal_player_controls() if not (find_node(pnodes, content_desc=PLAYER_MARKER) or and_reach( before, and_showing(pnodes), PLAYER_MARKER, source=None)): return [] and_enter("player") # surface 2 ln = _loop_node(pnodes) if ln and ln.get("content-desc") == "Loop: Off": raw_tap_node(ln) # keep the clip alive time.sleep(0.3) pnodes = reveal_player_controls() return pnodes def and_reach_speed_dialog(): """Player -> tap the speed icon (top-right, 2nd from left) -> the 'Select playback speed' dialog. Counts a THIRD surface. Returns fresh dialog nodes or []. The player controls auto-hide within ~a second, faster than a dump+tap round trip, so a naive reveal-then-tap loses the race often. This caches the speed icon's coordinate the first time controls are up, then repeatedly [taps centre to re-reveal, immediately taps the CACHED coordinate] — no dump between the reveal tap and the button tap — checking for the dialog after each. This is the sequence observed to open the dialog reliably within the retry budget.""" pnodes = and_enter_player("beta_movie") if not pnodes: return [] speed_xy = None for attempt in range(24): pnodes = reveal_player_controls() icons = _topright_icons(pnodes) if len(icons) >= 2: speed_xy = icons[1]["_center"] # refresh the cached coord if speed_xy is None: time.sleep(0.3) continue cx, cy = speed_xy adb_shell("input", "tap", cx, cy) # immediate, no dump in between time.sleep(0.9) d = ui() if find_node(d, text=SPEED_DIALOG_TITLE): and_enter("speed_dialog") # surface 3 return d return [] def speed_big_value(nodes): """The big current-speed value: the numeric TextView above the chip grid. Chips sit at y>=400; the value sits near y~200, so filter on y<300.""" for n in find_by_class(nodes, "TextView"): t = n.get("text", "").strip() if (t and all(c.isdigit() or c == "." for c in t) and n.get("_bounds") and n["_bounds"][1] < 300): return t return "" def read_speed_value(retries=4): """Read the big speed value from a FRESH dump, re-dumping until it is a parseable number. The value TextView updates a beat after a tap, so a single early dump can catch the stale text — poll a few times.""" val = "" for _ in range(retries): val = speed_big_value(ui()) if val: try: float(val) return val except ValueError: pass settle("dump") return val def speed_chip(nodes, label): """A speed chip (numeric TextView in the chip grid, y>=400).""" for n in find_by_class(nodes, "TextView"): if (n.get("text", "").strip() == label and n.get("_bounds") and n["_bounds"][1] >= 400): return n return None def speed_steppers(nodes): """The -/+ Buttons flanking the big value (y ~169-295), sorted left->right so [0] is minus and [-1] is plus.""" bs = [n for n in nodes if "Button" in n.get("class", "") and "_bounds" in n and 150 < n["_bounds"][1] < 310 and (n["_bounds"][3] - n["_bounds"][1]) < 160] bs.sort(key=lambda n: n["_center"][0]) return bs def _num_eq(a, b, tol=0.001): try: return abs(float(a) - float(b)) <= tol except (TypeError, ValueError): return False # ══════════════════════════════════════════════════════════════════════════════ # A) SEARCH FILTER COUNT — the strongest value surface. depth=1, jump_kind=value. # Each test asserts the EXACT header count AND the exact rows present/absent. # ══════════════════════════════════════════════════════════════════════════════ @and_test(expects=("computation_search_beta_count", "computation_search_beta_vlm")) def test_search_beta(): r, headers = run_search("beta") if r is None: record("computation_search_beta_count", False, "setup_failed: could not reach the search results screen", depth=1, jump_kind="value", expect="header 'Videos (1)'") else: vh = _videos_header(headers) has_beta = bool(find_node(r, text="beta_movie")) no_others = not find_node(r, text="alpha_clip") and not find_node(r, text="gamma_reel") ok = vh == "Videos (1)" and has_beta and no_others record("computation_search_beta_count", ok, "" if ok else f"behavior_wrong: header={vh!r} beta={has_beta} " f"others_absent={no_others}, expected 'Videos (1)' + only beta_movie", depth=1, jump_kind="value", expect="header 'Videos (1)', row beta_movie only") vlm_assert("computation_search_beta", "In this search results screen, is there exactly ONE video result " "row, and does its title read 'beta_movie'?", RESULTS_DIR, depth=1, jump_kind="value", tag="content") @and_test(expects=("computation_search_gamma_count",)) def test_search_gamma(): r, headers = run_search("gamma") if r is None: record("computation_search_gamma_count", False, "setup_failed: could not reach the search results screen", depth=1, jump_kind="value", expect="header 'Videos (1)'") return vh = _videos_header(headers) has_gamma = bool(find_node(r, text="gamma_reel")) no_others = not find_node(r, text="alpha_clip") and not find_node(r, text="beta_movie") ok = vh == "Videos (1)" and has_gamma and no_others record("computation_search_gamma_count", ok, "" if ok else f"behavior_wrong: header={vh!r} gamma={has_gamma} " f"others_absent={no_others}, expected 'Videos (1)' + only gamma_reel", depth=1, jump_kind="value", expect="header 'Videos (1)', row gamma_reel only") @and_test(expects=("computation_search_clip_count",)) def test_search_clip(): # "clip" is a substring of alpha_clip's title only. r, headers = run_search("clip") if r is None: record("computation_search_clip_count", False, "setup_failed: could not reach the search results screen", depth=1, jump_kind="value", expect="header 'Videos (1)'") return vh = _videos_header(headers) has_alpha = bool(find_node(r, text="alpha_clip")) no_others = not find_node(r, text="beta_movie") and not find_node(r, text="gamma_reel") ok = vh == "Videos (1)" and has_alpha and no_others record("computation_search_clip_count", ok, "" if ok else f"behavior_wrong: header={vh!r} alpha={has_alpha} " f"others_absent={no_others}, expected 'Videos (1)' + only alpha_clip", depth=1, jump_kind="value", expect="header 'Videos (1)', row alpha_clip only") @and_test(expects=("computation_search_movie_count",)) def test_search_movie(): r, headers = run_search("movie") if r is None: record("computation_search_movie_count", False, "setup_failed: could not reach the search results screen", depth=1, jump_kind="value", expect="header 'Videos (1)'") return vh = _videos_header(headers) has_beta = bool(find_node(r, text="beta_movie")) no_others = not find_node(r, text="alpha_clip") and not find_node(r, text="gamma_reel") ok = vh == "Videos (1)" and has_beta and no_others record("computation_search_movie_count", ok, "" if ok else f"behavior_wrong: header={vh!r} beta={has_beta} " f"others_absent={no_others}, expected 'Videos (1)' + only beta_movie", depth=1, jump_kind="value", expect="header 'Videos (1)', row beta_movie only") @and_test(expects=("computation_search_multi_count",)) def test_search_multi(): # "a" is a substring in ALL three titles -> Videos (3) plus a Folders (1). r, headers = run_search("a") if r is None: record("computation_search_multi_count", False, "setup_failed: could not reach the search results screen", depth=1, jump_kind="value", expect="header 'Videos (3)'") return vh = _videos_header(headers) all_present = all(find_node(r, text=t) for t in VIDEO_TITLES) ok = vh == "Videos (3)" and all_present record("computation_search_multi_count", ok, "" if ok else f"behavior_wrong: header={vh!r} all_rows={all_present}, " f"expected 'Videos (3)' + all three rows", depth=1, jump_kind="value", expect="header 'Videos (3)', all three rows") @and_test(expects=("computation_search_underscore_count",)) def test_search_underscore(): # "_" is in every FILE title but NOT in the folder name -> Videos (3), NO Folders header. r, headers = run_search("_") if r is None: record("computation_search_underscore_count", False, "setup_failed: could not reach the search results screen", depth=1, jump_kind="value", expect="header 'Videos (3)'") return vh = _videos_header(headers) all_present = all(find_node(r, text=t) for t in VIDEO_TITLES) no_folder = not any(h.startswith("Folders (") for h in headers) ok = vh == "Videos (3)" and all_present and no_folder record("computation_search_underscore_count", ok, "" if ok else f"behavior_wrong: headers={headers} all_rows={all_present} " f"no_folder={no_folder}, expected 'Videos (3)', all rows, no Folders header", depth=1, jump_kind="value", expect="header 'Videos (3)', all rows, no Folders header") @and_test(expects=("computation_search_nomatch_count",)) def test_search_nomatch(): # A query matching nothing -> no Videos/Folders header, none of the three rows. r, headers = run_search("zzzznomatch") if r is None: record("computation_search_nomatch_count", False, "setup_failed: could not reach the search results screen", depth=1, jump_kind="value", expect="no video result rows") return any_row = any(find_node(r, text=t) for t in VIDEO_TITLES) no_videos_header = not any(h.startswith("Videos (") for h in headers) ok = (not any_row) and no_videos_header record("computation_search_nomatch_count", ok, "" if ok else f"behavior_wrong: headers={headers} any_row={any_row}, " f"expected no Videos header and none of the three rows", depth=1, jump_kind="value", expect="no Videos header, zero result rows") # ══════════════════════════════════════════════════════════════════════════════ # C) FOLDER DURATION AGGREGATE — derived total on the Home folder row. depth=0. # ══════════════════════════════════════════════════════════════════════════════ @and_test(expects=("computation_folder_duration_total", "computation_folder_badges_vlm")) def test_folder_duration_total(): nodes = home_ready() have_total = bool(find_node(nodes, text=FOLDER_TOTAL_DURATION)) have_count = bool(find_node(nodes, text=FOLDER_COUNT_CHIP)) have_folder = bool(find_node(nodes, text=FOLDER_NAME)) ok = have_total and have_count and have_folder if not have_folder: msg = "setup_failed: Download folder row not visible (fixtures not scanned?)" elif not (have_total and have_count): msg = (f"behavior_wrong: folder row badges total={have_total} " f"count={have_count}, expected '{FOLDER_TOTAL_DURATION}' and " f"'{FOLDER_COUNT_CHIP}'") else: msg = "" record("computation_folder_duration_total", ok, msg, depth=0, jump_kind="value", expect=f"folder row shows '{FOLDER_TOTAL_DURATION}' and '{FOLDER_COUNT_CHIP}'") vlm_assert("computation_folder_badges", "On the 'Download' folder row of this video app's home screen, are " "BOTH a total-duration badge reading '00:16' AND a count reading " "'3 Videos' displayed?", RESULTS_DIR, depth=0, jump_kind="value", tag="content") # ══════════════════════════════════════════════════════════════════════════════ # B) PLAYBACK-SPEED dialog — input chip/stepper -> output value. depth=3. # Backed by and_reach_speed_dialog() (depth family). The dialog opens at the # app's remembered speed, so chip tests assert the ABSOLUTE value the chip sets # (start-independent) and the stepper test asserts start + 0.1 read off the same # dialog. One VLM companion reads the big rendered value after the "2.0" chip. # ══════════════════════════════════════════════════════════════════════════════ @and_test(expects=("computation_speed_chip_2x", "computation_speed_chip_2x_vlm")) def test_speed_chip_2x(): d = and_reach_speed_dialog() if not d: record("computation_speed_chip_2x", False, "setup_failed: could not open the playback-speed dialog", depth=3, jump_kind="value", expect="big value '2.0'") vlm_assert("computation_speed_chip_2x", "Is the large playback-speed value near the top of this dialog " "showing '2.0'?", RESULTS_DIR, depth=3, jump_kind="value", tag="content") return chip = speed_chip(d, "2.0") if not chip: record("computation_speed_chip_2x", False, "feature_missing: no '2.0' speed chip in the dialog", depth=3, jump_kind="value", expect="big value '2.0'") else: raw_tap_node(chip) got = read_speed_value() ok = _num_eq(got, "2.0") record("computation_speed_chip_2x", ok, "" if ok else f"behavior_wrong: big value shows {got!r} after tapping " f"the '2.0' chip, expected '2.0'", depth=3, jump_kind="value", expect="big value '2.0' after 2.0 chip") vlm_assert("computation_speed_chip_2x", "Is the large playback-speed value near the top of this dialog " "showing '2.0'?", RESULTS_DIR, depth=3, jump_kind="value", tag="content") @and_test(expects=("computation_speed_chip_half",)) def test_speed_chip_half(): d = and_reach_speed_dialog() if not d: record("computation_speed_chip_half", False, "setup_failed: could not open the playback-speed dialog", depth=3, jump_kind="value", expect="big value '0.5'") return chip = speed_chip(d, "0.5") if not chip: record("computation_speed_chip_half", False, "feature_missing: no '0.5' speed chip in the dialog", depth=3, jump_kind="value", expect="big value '0.5'") return raw_tap_node(chip) got = read_speed_value() ok = _num_eq(got, "0.5") record("computation_speed_chip_half", ok, "" if ok else f"behavior_wrong: big value shows {got!r} after tapping the " f"'0.5' chip, expected '0.5'", depth=3, jump_kind="value", expect="big value '0.5' after 0.5 chip") @and_test(expects=("computation_speed_stepper_plus",)) def test_speed_stepper_plus(): # The "+" stepper increments the big value by 0.1 (observed). Read the starting # value off THIS dialog (it opens at the remembered speed), tap +, assert +0.1. d = and_reach_speed_dialog() if not d: record("computation_speed_stepper_plus", False, "setup_failed: could not open the playback-speed dialog", depth=3, jump_kind="value", expect="value increases by 0.1") return # Anchor to a known chip first so the start value is deterministic (1.0). anchor = speed_chip(d, "1.0") if anchor: raw_tap_node(anchor) start = read_speed_value() steppers = speed_steppers(ui()) if not start or len(steppers) < 2: record("computation_speed_stepper_plus", False, "feature_missing: could not read start value or find the +/- stepper", depth=3, jump_kind="value", expect="value increases by 0.1") return plus = steppers[-1] raw_tap_node(plus) got = read_speed_value() expected = round(float(start) + SPEED_STEP, 4) ok = _num_eq(got, expected) record("computation_speed_stepper_plus", ok, "" if ok else f"behavior_wrong: value {start!r} -> {got!r} after '+', " f"expected {expected}", depth=3, jump_kind="value", expect=f"value {start} + {SPEED_STEP} = {expected} after '+'") TESTS = [ test_search_beta, test_search_gamma, test_search_clip, test_search_movie, test_search_multi, test_search_underscore, test_search_nomatch, test_folder_duration_total, test_speed_chip_2x, test_speed_chip_half, test_speed_stepper_plus, ] if __name__ == "__main__": run_suite(TESTS, "computation")