Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
main ▾

Modern-Apps.git / test

test924 lines · 39.7 KiBRaw
1#!/usr/bin/env bash
2# Unified test runner: rust tests + unit tests + instrumented tests, with coverage.
3#
4# Usage:
5# ./test [--rust-only|--unit-only|--instrumented-only] [--no-coverage] [--device S] [--emulator] [--dry-run] [--help|-h] <module> [module...]
6# ./test all [flags] # every app + library convention module
7# ./test games/voxels maps # multi-module, minimal gradlew invocations
8# ./test voxels # shorthand -> games:voxels (same as ./check)
9# ./test --rust-only calculator # only the rust phase
10# ./test --unit-only calculator # only the unit phase
11# ./test --instrumented-only calculator # only the instrumented phase
12# ./test --no-coverage calculator # skip coverage, plain test tasks
13# ./test --device 9 calculator # Pixel 9 by model (8 = Pixel 8)
14# ./test --device SERIAL calculator # explicit device serial (physical or emulator)
15# ./test --emulator calculator # boot/use the Medium_Phone emulator (this is the default)
16# ./test --dry-run calculator # prints what would run without executing
17#
18# Module notation mirrors ./check: slash == colon, leading/trailing slashes and
19# colons trimmed, doubled separators collapsed, lowercased, games:/personal:
20# shorthand, 'all' keyword, deduped. Tasks run with --continue so one broken
21# module does not block the rest; exit code is nonzero if anything failed.
22#
23# Phases (skipped by --rust-only / --unit-only / --instrumented-only):
24# Rust: same ROOT_CRATES / STANDALONE split as ./check. Coverage on (default)
25# ensures llvm-tools-preview + cargo-llvm-cov, then runs cargo llvm-cov for
26# workspace crates (--workspace when 'all', else -p flags for in-scope
27# crates) plus one cargo llvm-cov per standalone dir. --no-coverage runs
28# plain `cargo test --locked` equivalents instead.
29# Unit: app modules -> :mod:createMergedCoverageReport (which runs
30# :mod:testDevUnitTest first), library modules -> the same merged task for the
31# debug variant (runs :mod:testDebugUnitTest first); single gradlew invocation
32# with --continue; app vs library decided by grepping the module build.gradle.kts
33# for common-conventions-app, like check's all_module_dirs. --no-coverage
34# -> :mod:testDevUnitTest / :mod:testDebugUnitTest. Afterwards prints
35# per-module INSTRUCTION covered/missed/percent from the MERGED report
36# build/reports/coverage/merged/report.xml (falling back to the unit-only
37# build/reports/coverage/test/*/report.xml when no merged report exists) plus
38# a TOTAL line. Percentages come from the report-level counter, which is the
39# LAST <counter type="INSTRUCTION"> in JaCoCo XML.
40# Instrumented: scope = in-scope modules having any *.kt under src/androidTest.
41# Apps assemble :mod:assembleDev :mod:assembleDevAndroidTest, libraries
42# :mod:assembleDebug :mod:assembleDebugAndroidTest (single gradlew invocation
43# with --continue), then per module: apps session-install the app APK (./install
44# logic incl. versionCodeOverride and .idsig staging; never plain adb install
45# for the app APK), libraries skip straight to the test APK; plain
46# `adb install -r` for the test APK, `am instrument` the runner, and with
47# coverage pull /data/data/<pkg>/files/coverage.ec via run-as into
48# build/outputs/coverage-manual/ (consumed by the merged report on the next run).
49#
50# Device: without --device, instrumented tests ALWAYS run on the Medium_Phone
51# emulator (SDK $ANDROID_SDK_ROOT or /Users/vayun/devmate-android-toolchain/android-sdk),
52# booted headless (-no-window -no-audio -no-boot-anim) when not already running;
53# a physical device is never used unless --device names it explicitly. --device
54# accepts a serial or 8|9 (Pixel 8 / Pixel 9 by model, mirroring ./install).
55# --emulator is accepted for explicitness and means the same as the default.
56# Concurrency: the unit phase is lock-free, but emulator boot plus the whole
57# install+instrument loop run under a mkdir-based lock in $TMPDIR, so concurrent
58# `./test --instrumented-only <different modules>` runs serialize instead of
59# colliding on the single emulator.
60# Big-heap escalation when 'all' is expanded: same flags as install-all
61# (-Dorg.gradle.jvmargs=-Xmx46144m ... --max-workers=32).
62set -euo pipefail
63
64SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
65ROOT="$SCRIPT_DIR"
66
67print_help() {
68 sed -n '2,/^set -euo/p' "$SCRIPT_DIR/test" | sed 's/^# \{0,1\}//' | head -n -1
69}
70
71normalize_module() {
72 local m="$1"
73 m="$(echo "$m" | xargs)"
74 m="$(echo "$m" | sed -e 's|^[/:]*||' -e 's|[/:]*$||')"
75 m="$(echo "$m" | tr '/' ':')"
76 while echo "$m" | grep -q "::"; do m="$(echo "$m" | sed 's/::/:/g')"; done
77 echo "$m" | tr '[:upper:]' '[:lower:]'
78}
79
80# all = app + library convention modules (both apply dev.detekt; pure-JVM
81# modules like youpipe:extractor do not, so they are excluded here but still
82# accepted when named explicitly and left for Gradle to report on).
83all_module_dirs() {
84 grep -E 'include\(":[^"]+"\)' "$ROOT/settings.gradle.kts" 2>/dev/null \
85 | sed -E 's/.*include\(":([^"]+)"\).*/\1/' \
86 | tr ':' '/' \
87 | while IFS= read -r p; do
88 case "$p" in "" ) continue;; esac
89 if [[ -f "$ROOT/$p/build.gradle.kts" ]] \
90 && grep -qE 'common-conventions-(app|library)' "$ROOT/$p/build.gradle.kts" 2>/dev/null; then
91 echo "$p"
92 fi
93 done | sort -u
94}
95
96is_app_module() {
97 local fs="$1"
98 grep -qF 'id("common-conventions-app")' "$ROOT/$fs/build.gradle.kts" 2>/dev/null
99}
100
101module_application_id() {
102 sed -nE 's/^[[:space:]]*applicationId[[:space:]]*=[[:space:]]*"([^"]+)".*/\1/p' \
103 "$ROOT/$(echo "$1" | tr ':' '/')/build.gradle.kts" | head -1
104}
105
106# APK built for an app module; output-metadata.json names the file authoritatively
107# (nested modules like cast:tv build tv-dev.apk, not cast-tv-dev.apk). VARIANT is
108# dev (apps) or debug (libraries).
109built_app_apk() {
110 local mod="$1" variant="$2" fs_path out_dir meta base_name file_name
111 fs_path="$(echo "$mod" | tr ':' '/')"
112 out_dir="$ROOT/$fs_path/build/outputs/apk/$variant"
113 meta="$out_dir/output-metadata.json"
114 base_name="${mod##*:}"
115 file_name="$base_name-$variant.apk"
116 if [[ -f "$meta" ]]; then
117 local found
118 found="$(grep -oE '"outputFile"[[:space:]]*:[[:space:]]*"[^"]+"' "$meta" | head -1 | sed -E 's/.*\"([^\"]+)\"$/\1/')"
119 [[ -n "$found" ]] && file_name="$found"
120 fi
121 if [[ -f "$out_dir/$file_name" ]]; then
122 echo "$out_dir/$file_name"
123 return 0
124 fi
125 return 1
126}
127
128built_test_apk() {
129 local mod="$1" variant="$2" fs_path out_dir meta base_name file_name
130 fs_path="$(echo "$mod" | tr ':' '/')"
131 out_dir="$ROOT/$fs_path/build/outputs/apk/androidTest/$variant"
132 meta="$out_dir/output-metadata.json"
133 base_name="${mod##*:}"
134 file_name="$base_name-$variant-androidTest.apk"
135 if [[ -f "$meta" ]]; then
136 local found
137 found="$(grep -oE '"outputFile"[[:space:]]*:[[:space:]]*"[^"]+"' "$meta" | head -1 | sed -E 's/.*\"([^\"]+)\"$/\1/')"
138 [[ -n "$found" ]] && file_name="$found"
139 fi
140 if [[ -f "$out_dir/$file_name" ]]; then
141 echo "$out_dir/$file_name"
142 return 0
143 fi
144 return 1
145}
146
147# Test-package id for a library module: the namespace is computed in
148# common-conventions-library (com.vayunmathur + dotted path, dashes stripped) and the
149# androidTest APK appends .test.
150library_test_package() {
151 local dotted
152 dotted="$(echo "$1" | tr '/' '.')"
153 dotted="$(echo "$dotted" | tr -d '-')"
154 echo "com.vayunmathur.$dotted.test"
155}
156
157# on-device versionCode for a package, empty when not installed.
158device_version_code() {
159 "$ADB_BIN" -s "$TARGET_SERIAL" shell pm list packages --show-versioncode "$1" 2>/dev/null \
160 | sed -nE 's/^package:\S+[[:space:]]+versionCode:([0-9]+).*/\1/p' | head -1
161}
162
163# exit 0 when the package is installed as a system app.
164is_system_app() {
165 "$ADB_BIN" -s "$TARGET_SERIAL" shell pm list packages -s "$1" 2>/dev/null \
166 | tr -d '\r' | grep -qFx "package:$1"
167}
168
169install_apk_via_session() {
170 local apk="$1" package_id="$2" cur="${3:-}" total="${4:-}"
171 local apk_name apk_size apk_mb session device_apk idsig device_idsig commit_out prefix
172 apk_name="$(basename "$apk")"
173 apk_size="$(wc -c < "$apk" | tr -d ' ')"
174 apk_mb="$(awk "BEGIN {printf \"%.1f\", $apk_size/1048576}")"
175 device_apk="/data/local/tmp/install_${package_id}.apk"
176 if [[ -n "$cur" && -n "$total" ]]; then
177 prefix="[$cur/$total] "
178 else
179 prefix=""
180 fi
181 echo "${prefix}Installing $package_id ($apk_name, ${apk_mb} MB)..."
182 echo " ${prefix}[1/4] Pushing APK to device..."
183 "$ADB_BIN" -s "$TARGET_SERIAL" push "$apk" "$device_apk" >/dev/null 2>&1 || {
184 echo " ${prefix}Error: adb push failed for $apk_name."; return 1
185 }
186 echo " ${prefix}[2/4] Creating install session..."
187 session="$("$ADB_BIN" -s "$TARGET_SERIAL" shell pm install-create -r 2>&1 \
188 | sed -nE 's/.*created install session \[([0-9]+)\].*/\1/p')"
189 if [[ -z "$session" ]]; then
190 echo " ${prefix}Error: could not create install session."
191 "$ADB_BIN" -s "$TARGET_SERIAL" shell rm -f "$device_apk" >/dev/null 2>&1
192 return 1
193 fi
194 # Stage the APK first, then its .idsig sidecar (V4 signature) under the
195 # matching name. PackageManager enables fs-verity from a staged idsig, which
196 # MAOS/GrapheneOS requires for updates to preinstalled system apps. Plain
197 # `adb install` never stages the sidecar, so those updates always fail.
198 echo " ${prefix}[3/4] Staging APK into session $session..."
199 "$ADB_BIN" -s "$TARGET_SERIAL" shell pm install-write -S "$apk_size" "$session" base.apk "$device_apk" >/dev/null 2>&1 || {
200 echo " ${prefix}Error: failed to stage $apk_name into session $session."
201 "$ADB_BIN" -s "$TARGET_SERIAL" shell pm install-abandon "$session" >/dev/null 2>&1
202 "$ADB_BIN" -s "$TARGET_SERIAL" shell rm -f "$device_apk" >/dev/null 2>&1
203 return 1
204 }
205 idsig="$apk.idsig"
206 if [[ -f "$idsig" ]]; then
207 device_idsig="$device_apk.idsig"
208 echo " ${prefix}Staging .idsig sidecar..."
209 if "$ADB_BIN" -s "$TARGET_SERIAL" push "$idsig" "$device_idsig" >/dev/null 2>&1; then
210 "$ADB_BIN" -s "$TARGET_SERIAL" shell pm install-write -S "$(wc -c < "$idsig" | tr -d ' ')" \
211 "$session" base.apk.idsig "$device_idsig" >/dev/null 2>&1 || \
212 echo " ${prefix}Warning: could not stage .idsig; system-app updates may fail fs-verity."
213 else
214 echo " ${prefix}Warning: could not push .idsig; system-app updates may fail fs-verity."
215 fi
216 "$ADB_BIN" -s "$TARGET_SERIAL" shell rm -f "$device_idsig" >/dev/null 2>&1
217 else
218 echo " ${prefix}Warning: no .idsig sidecar next to the APK; system-app updates may fail fs-verity."
219 fi
220 echo " ${prefix}[4/4] Committing install session $session..."
221 commit_out="$("$ADB_BIN" -s "$TARGET_SERIAL" shell pm install-commit "$session" 2>&1)"
222 "$ADB_BIN" -s "$TARGET_SERIAL" shell rm -f "$device_apk" >/dev/null 2>&1
223 # `pm install-commit` prints "Success" but exits 0 either way; fail on absence.
224 if ! echo "$commit_out" | grep -qi "^Success"; then
225 echo " ${prefix}Error: install failed for $package_id: $commit_out"
226 return 1
227 fi
228 if [[ -n "$cur" && -n "$total" ]]; then
229 echo " Installed $package_id. [$cur/$total done]"
230 else
231 echo " Installed $package_id."
232 fi
233}
234
235if [[ $# -eq 0 ]]; then print_help; echo ""; echo "Error: no modules specified."; exit 1; fi
236for arg in "$@"; do case "$arg" in --help|-h|help) print_help; exit 0;; esac; done
237
238# --- flag parsing ---
239RUN_RUST=1; RUN_UNIT=1; RUN_INST=1
240SCOPE_FLAG=""
241NO_COV=0
242DRY_RUN=0
243DEVICE_HINT=""
244if [[ "${TEST_DRY_RUN:-0}" == "1" ]]; then DRY_RUN=1; fi
245MODULES_RAW=()
246ARGS=()
247for arg in "$@"; do ARGS+=("$arg"); done
248idx=0
249while [[ $idx -lt ${#ARGS[@]} ]]; do
250 arg="${ARGS[$idx]}"
251 case "$arg" in
252 --rust-only)
253 if [[ -n "$SCOPE_FLAG" && "$SCOPE_FLAG" != "rust" ]]; then
254 echo "Error: only one of --rust-only, --unit-only, --instrumented-only may be given." >&2; exit 1
255 fi
256 SCOPE_FLAG="rust"; RUN_RUST=1; RUN_UNIT=0; RUN_INST=0
257 idx=$((idx + 1)); continue ;;
258 --unit-only)
259 if [[ -n "$SCOPE_FLAG" && "$SCOPE_FLAG" != "unit" ]]; then
260 echo "Error: only one of --rust-only, --unit-only, --instrumented-only may be given." >&2; exit 1
261 fi
262 SCOPE_FLAG="unit"; RUN_RUST=0; RUN_UNIT=1; RUN_INST=0
263 idx=$((idx + 1)); continue ;;
264 --instrumented-only)
265 if [[ -n "$SCOPE_FLAG" && "$SCOPE_FLAG" != "inst" ]]; then
266 echo "Error: only one of --rust-only, --unit-only, --instrumented-only may be given." >&2; exit 1
267 fi
268 SCOPE_FLAG="inst"; RUN_RUST=0; RUN_UNIT=0; RUN_INST=1
269 idx=$((idx + 1)); continue ;;
270 --no-coverage)
271 NO_COV=1; idx=$((idx + 1)); continue ;;
272 --emulator)
273 USE_EMULATOR=1; idx=$((idx + 1)); continue ;;
274 --dry-run)
275 DRY_RUN=1; idx=$((idx + 1)); continue ;;
276 --device=*)
277 DEVICE_HINT="${arg#--device=}"
278 idx=$((idx + 1)); continue ;;
279 --device)
280 if [[ $((idx + 1)) -ge ${#ARGS[@]} ]]; then
281 echo "Error: --device requires a value (serial, 8, or 9)." >&2; exit 1
282 fi
283 DEVICE_HINT="${ARGS[$((idx + 1))]}"
284 idx=$((idx + 2)); continue ;;
285 --help|-h|help)
286 print_help; exit 0 ;;
287 --*)
288 echo "Error: unknown flag '$arg'." >&2; exit 1 ;;
289 8|9)
290 DEVICE_HINT="$arg"
291 idx=$((idx + 1)); continue ;;
292 *)
293 if [[ "$arg" =~ ^[0-9]+$ ]]; then
294 echo "Error: Invalid device '$arg'. Use --device with a serial, 8 (Pixel 8), or 9 (Pixel 9)." >&2; exit 1
295 fi
296 MODULES_RAW+=("$arg"); idx=$((idx + 1)); continue ;;
297 esac
298done
299if [[ ${#MODULES_RAW[@]} -eq 0 ]]; then
300 echo "Error: no modules specified." >&2; exit 1
301fi
302
303MODS=(); ALL_EXP=0
304for raw in ${MODULES_RAW[@]:-}; do
305 norm="$(normalize_module "$raw")"
306 [[ -z "$norm" ]] && continue
307 if [[ "$norm" == "all" ]]; then
308 if [[ $ALL_EXP -eq 0 ]]; then
309 while IFS= read -r sm; do
310 case "$sm" in "" ) continue;; esac
311 MODS+=("$sm")
312 done < <(all_module_dirs)
313 ALL_EXP=1
314 fi
315 continue
316 fi
317 if [[ "$norm" != *":"* ]]; then
318 for pfx in games personal; do
319 [[ -f "$ROOT/$pfx/$norm/build.gradle.kts" ]] && { norm="$pfx:$norm"; break; }
320 done
321 fi
322 fs="$(echo "$norm" | tr ':' '/')"
323 if [[ ! -f "$ROOT/$fs/build.gradle.kts" ]]; then
324 echo "Error: unknown module '$raw' (-> $fs/, no build.gradle.kts)." >&2; exit 1
325 fi
326 dup=0; for m in ${MODS[@]:-}; do [[ "$m" == "$fs" ]] && dup=1; done
327 [[ $dup -eq 0 ]] && MODS+=("$fs")
328done
329[[ ${#MODS[@]} -gt 0 ]] || { echo "Error: no valid modules." >&2; exit 1; }
330
331# --- rust scope: same ROOT_CRATES / STANDALONE split as ./check ---
332ROOT_CRATES=()
333STANDALONE_DIRS=()
334if [[ $RUN_RUST -eq 1 ]]; then
335 for mod in "${MODS[@]}"; do
336 rdir="$ROOT/$mod/src/main/rust"
337 ct="$rdir/Cargo.toml"
338 if [[ -f "$ct" ]]; then
339 if grep -qE '^\[workspace\][[:space:]]*$' "$ct"; then
340 STANDALONE_DIRS+=("$rdir")
341 echo "Rust: $mod -> standalone crate ($rdir)"
342 else
343 name="$(sed -nE 's/^name *= *"([^"]+)".*/\1/p' "$ct" | head -1)"
344 [[ -n "$name" ]] && ROOT_CRATES+=("$name") && echo "Rust: $mod -> workspace crate $name"
345 fi
346 fi
347 done
348fi
349
350# --- unit tasks: merged coverage report per module (runs the unit tests first);
351# app -> Dev variant, library (or other) -> Debug variant (decided inside the
352# convention plugin, so both spellings are the same task name) ---
353UNIT_TASKS=()
354if [[ $RUN_UNIT -eq 1 ]]; then
355 for mod in "${MODS[@]}"; do
356 gmod="$(echo "$mod" | tr '/' ':')"
357 if [[ $NO_COV -eq 1 ]]; then
358 if is_app_module "$mod"; then UNIT_TASKS+=(":$gmod:testDevUnitTest");
359 else UNIT_TASKS+=(":$gmod:testDebugUnitTest"); fi
360 else
361 UNIT_TASKS+=(":$gmod:createMergedCoverageReport")
362 fi
363 done
364fi
365
366# --- instrumented scope: in-scope modules having any *.kt under src/androidTest ---
367INST_MODS=()
368if [[ $RUN_INST -eq 1 ]]; then
369 for mod in "${MODS[@]}"; do
370 if [[ -d "$ROOT/$mod/src/androidTest" ]] \
371 && find "$ROOT/$mod/src/androidTest" -name '*.kt' -print -quit 2>/dev/null | grep -q .; then
372 INST_MODS+=("$mod")
373 fi
374 done
375 if [[ ${#INST_MODS[@]} -eq 0 ]]; then
376 echo "No instrumented tests in scope (no *.kt under src/androidTest); instrumented phase skipped."
377 else
378 echo "Instrumented modules (${#INST_MODS[@]}): ${INST_MODS[*]}"
379 fi
380fi
381INST_TASKS=()
382if [[ $RUN_INST -eq 1 && ${#INST_MODS[@]} -gt 0 ]]; then
383 for mod in "${INST_MODS[@]}"; do
384 gmod="$(echo "$mod" | tr '/' ':')"
385 if is_app_module "$mod"; then
386 INST_TASKS+=(":$gmod:assembleDev" ":$gmod:assembleDevAndroidTest")
387 else
388 INST_TASKS+=(":$gmod:assembleDebug" ":$gmod:assembleDebugAndroidTest")
389 fi
390 done
391fi
392
393echo "Modules (${#MODS[@]}): ${MODS[*]}"
394if [[ $RUN_UNIT -eq 1 ]]; then echo "Unit tasks: ${UNIT_TASKS[*]}"; fi
395if [[ $RUN_INST -eq 1 && ${#INST_TASKS[@]} -gt 0 ]]; then echo "Instrumented tasks: ${INST_TASKS[*]}"; fi
396if [[ $NO_COV -eq 1 ]]; then echo "Coverage: off (--no-coverage)"; else echo "Coverage: on"; fi
397echo ""
398
399# --- device selection (needed for the instrumented phase) ---
400# Without --device, instrumented tests ALWAYS run on the Medium_Phone emulator:
401# never pick a physical device implicitly. --device with a serial/8/9 still selects
402# a physical device (or a specific emulator) explicitly.
403ADB_BIN=""
404EMULATOR_BIN=""
405EMULATOR_SERIAL=""
406EMULATOR_AVD="${EMULATOR_AVD:-Medium_Phone}"
407# SDK location: env first, then the checked-in toolchain path, then PATH lookup.
408ANDROID_SDK_DIR=""
409for sdk_base in "${ANDROID_HOME:-}" "${ANDROID_SDK_ROOT:-}" "$HOME/Android/Sdk" "$HOME/Library/Android/sdk" "/Users/vayun/devmate-android-toolchain/android-sdk"; do
410 if [[ -n "$sdk_base" && -d "$sdk_base/platform-tools" ]]; then
411 ANDROID_SDK_DIR="$sdk_base"
412 break
413 fi
414done
415if [[ -n "$ANDROID_SDK_DIR" && -x "$ANDROID_SDK_DIR/platform-tools/adb" ]]; then
416 ADB_BIN="$ANDROID_SDK_DIR/platform-tools/adb"
417elif command -v adb >/dev/null 2>&1; then
418 ADB_BIN="adb"
419fi
420if [[ -n "$ANDROID_SDK_DIR" && -x "$ANDROID_SDK_DIR/emulator/emulator" ]]; then
421 EMULATOR_BIN="$ANDROID_SDK_DIR/emulator/emulator"
422elif command -v emulator >/dev/null 2>&1; then
423 EMULATOR_BIN="emulator"
424fi
425
426# mkdir-based emulator lock (macOS has no flock): serializes emulator boot and the
427# install+instrument loop across concurrent ./test runs. Lock-free unit phase is
428# unaffected. Stale locks (owner pid dead) are broken and retried.
429EMULATOR_LOCK_DIR="${TMPDIR:-/tmp}/modern-apps-test-emulator.lock"
430LOCK_HELD=0
431acquire_emulator_lock() {
432 local owner
433 while true; do
434 if mkdir "$EMULATOR_LOCK_DIR" 2>/dev/null; then
435 echo $$ > "$EMULATOR_LOCK_DIR/pid"
436 LOCK_HELD=1
437 return 0
438 fi
439 owner="$(cat "$EMULATOR_LOCK_DIR/pid" 2>/dev/null || echo "")"
440 if [[ -n "$owner" ]] && ! kill -0 "$owner" 2>/dev/null; then
441 echo "Warning: breaking stale emulator lock (owner pid $owner dead)."
442 rm -rf "$EMULATOR_LOCK_DIR"
443 continue
444 fi
445 sleep 2
446 done
447}
448release_emulator_lock() {
449 if [[ $LOCK_HELD -eq 1 ]]; then
450 rm -rf "$EMULATOR_LOCK_DIR"
451 LOCK_HELD=0
452 fi
453}
454
455# Boot the emulator headless if no emulator is online yet; sets EMULATOR_SERIAL.
456# The AVD is arm64, like the host, so no -PemulatorAbi is needed.
457ensure_emulator_running() {
458 [[ -n "$ADB_BIN" ]] || { echo "Error: adb not found; cannot drive the emulator." >&2; return 1; }
459 local serial
460 serial="$("$ADB_BIN" devices 2>/dev/null | awk '$2=="device" && $1 ~ /^emulator-/ {print $1; exit}')"
461 if [[ -n "$serial" ]]; then
462 EMULATOR_SERIAL="$serial"
463 echo "Emulator already running: $EMULATOR_SERIAL"
464 return 0
465 fi
466 [[ -n "$EMULATOR_BIN" ]] || { echo "Error: emulator binary not found (SDK dir: ${ANDROID_SDK_DIR:-<none>})." >&2; return 1; }
467 echo "Booting emulator AVD $EMULATOR_AVD headless..."
468 "$EMULATOR_BIN" -avd "$EMULATOR_AVD" -no-window -no-audio -no-boot-anim -read-only >/dev/null 2>&1 &
469 local waited=0
470 while [[ $waited -lt 300 ]]; do
471 sleep 5
472 waited=$((waited + 5))
473 serial="$("$ADB_BIN" devices 2>/dev/null | awk '$2=="device" && $1 ~ /^emulator-/ {print $1; exit}')"
474 [[ -z "$serial" ]] && continue
475 if [[ "$("$ADB_BIN" -s "$serial" shell getprop sys.boot_completed 2>/dev/null | tr -d '\r')" == "1" ]]; then
476 EMULATOR_SERIAL="$serial"
477 echo "Emulator booted: $EMULATOR_SERIAL (${waited}s)"
478 return 0
479 fi
480 done
481 echo "Error: emulator $EMULATOR_AVD did not finish booting within 300s." >&2
482 return 1
483}
484
485NEED_DEVICE=0
486if [[ $RUN_INST -eq 1 && ${#INST_MODS[@]} -gt 0 ]]; then NEED_DEVICE=1; fi
487if [[ $NEED_DEVICE -eq 1 ]]; then
488 TARGET_SERIAL=""
489 if [[ -n "$DEVICE_HINT" ]]; then
490 # Explicit device: serial match, or 8|9 Pixel-by-model (physical or emulator,
491 # mirroring ./install). Physical devices are only ever used this way.
492 if [[ -z "$ADB_BIN" ]]; then
493 echo "Error: adb not found; cannot select a target device." >&2
494 echo "Install Android platform-tools and put adb on PATH (or set ANDROID_HOME)." >&2
495 exit 1
496 fi
497 if [[ "$DEVICE_HINT" == "8" || "$DEVICE_HINT" == "9" ]]; then
498 # hint 8 = model Pixel_8; 9 = model Pixel_9* (covers Pixel_9 and Pixel_9_Pro_XL).
499 while read -r dev_line; do
500 dev_serial="$(echo "$dev_line" | awk '{print $1}')"
501 dev_state="$(echo "$dev_line" | awk '{print $2}')"
502 [[ "$dev_state" == "device" ]] || continue
503 case "$dev_serial" in emulator*) continue;; esac
504 case "$dev_serial" in "List"*) continue;; esac
505 dev_model="$(echo "$dev_line" | sed -nE 's/.*model:([^[:space:]]+).*/\1/p')"
506 if [[ "$DEVICE_HINT" == "8" && "$dev_model" == "Pixel_8" ]]; then
507 TARGET_SERIAL="$dev_serial"
508 break
509 fi
510 if [[ "$DEVICE_HINT" == "9" && "$dev_model" == Pixel_9* ]]; then
511 TARGET_SERIAL="$dev_serial"
512 break
513 fi
514 done < <("$ADB_BIN" devices -l 2>/dev/null)
515 elif [[ -n "$DEVICE_HINT" ]]; then
516 while read -r dev_line; do
517 dev_serial="$(echo "$dev_line" | awk '{print $1}')"
518 dev_state="$(echo "$dev_line" | awk '{print $2}')"
519 [[ "$dev_state" == "device" ]] || continue
520 case "$dev_serial" in "List"*) continue;; esac
521 if [[ "$dev_serial" == "$DEVICE_HINT" ]]; then
522 TARGET_SERIAL="$dev_serial"
523 break
524 fi
525 done < <("$ADB_BIN" devices -l 2>/dev/null)
526 fi
527 fi
528 if [[ -z "$ADB_BIN" ]]; then
529 if [[ $DRY_RUN -eq 1 ]]; then
530 echo "[DRY-RUN] Warning: adb not found; a device could not be selected."
531 else
532 echo "Error: adb not found; cannot select a target device." >&2
533 echo "Install Android platform-tools and put adb on PATH (or set ANDROID_HOME)." >&2
534 exit 1
535 fi
536 elif [[ -n "$TARGET_SERIAL" ]]; then
537 export ANDROID_SERIAL="$TARGET_SERIAL"
538 if [[ "$DEVICE_HINT" == "8" || "$DEVICE_HINT" == "9" ]]; then
539 echo "Target device: $ANDROID_SERIAL (Pixel $DEVICE_HINT)"
540 else
541 echo "Target device: $ANDROID_SERIAL (explicit --device)"
542 fi
543 elif [[ $DRY_RUN -eq 1 ]]; then
544 echo "[DRY-RUN] Would ensure the $EMULATOR_AVD emulator is running (boot headless if needed)."
545 TARGET_SERIAL="<emulator>"
546 else
547 # Default path: emulator (never a physical device without --device). The lock
548 # serializes boot + install/instrument against concurrent ./test runs; the trap
549 # below releases it on exit. Lock-free unit phase already ran (or was skipped), so
550 # holding the lock from here to the end of the instrumented phase is correct.
551 acquire_emulator_lock
552 trap release_emulator_lock EXIT
553 ensure_emulator_running || exit 1
554 TARGET_SERIAL="$EMULATOR_SERIAL"
555 export ANDROID_SERIAL="$TARGET_SERIAL"
556 echo "Target device: $ANDROID_SERIAL (emulator $EMULATOR_AVD)"
557 fi
558else
559 TARGET_SERIAL="${ANDROID_SERIAL:-}"
560 if [[ -z "$ADB_BIN" ]] && command -v adb >/dev/null 2>&1; then ADB_BIN="adb"; fi
561fi
562
563# --- extra Gradle args: --continue so one broken module doesn't block the rest ---
564GRADLE_ARGS=(--continue --console=plain)
565gradle_args_str=" --continue --console=plain"
566if [[ $ALL_EXP -eq 1 ]]; then
567 GRADLE_ARGS+=(-D"org.gradle.jvmargs=-Xmx46144m -Xms4512m -XX:MaxMetaspaceSize=1024m -XX:+UseG1GC -Dfile.encoding=UTF-8")
568 GRADLE_ARGS+=(--max-workers=32)
569 gradle_args_str="$gradle_args_str -Dorg.gradle.jvmargs=<46g-big-build-heap> --max-workers=32"
570fi
571
572# --- versionCodeOverride: MAOS refuses to update a system package to the same
573# versionCode, so an APK built from the same version.txt as the on-device OS image
574# can never be installed over it. Query the device once; for system apps bump to
575# one above the on-device version, for user apps just match it exactly
576# (version.txt itself stays untouched). Scoped to instrumented modules, the only
577# ones this script installs.
578REPO_VERSION="$(sed -n '1p' "$ROOT/version.txt" | tr -d '\r' | xargs)"
579NEED_BUMP="$REPO_VERSION"
580if [[ $NEED_DEVICE -eq 1 && -n "${TARGET_SERIAL:-}" && -n "$ADB_BIN" ]]; then
581 for mod in ${INST_MODS[@]:-}; do
582 colon_mod="$(echo "$mod" | tr '/' ':')"
583 pkg="$(module_application_id "$colon_mod")"
584 if [[ -n "$pkg" ]]; then
585 dev_v="$(device_version_code "$pkg")"
586 if [[ -n "$dev_v" && "$dev_v" -ge "$NEED_BUMP" ]]; then
587 if is_system_app "$pkg"; then
588 target=$((dev_v + 1))
589 kind="system app"
590 else
591 target=$dev_v
592 kind="user app"
593 fi
594 if [[ "$target" -gt "$NEED_BUMP" ]]; then
595 NEED_BUMP=$target
596 echo "Info: $pkg is a $kind at versionCode $dev_v on-device (>= repo $REPO_VERSION); will build with -PversionCodeOverride=$target."
597 fi
598 fi
599 fi
600 done
601fi
602if [[ "$NEED_BUMP" -gt "$REPO_VERSION" ]]; then
603 GRADLE_ARGS+=(-P"versionCodeOverride=$NEED_BUMP")
604 gradle_args_str="$gradle_args_str -PversionCodeOverride=$NEED_BUMP"
605fi
606
607if command -v cargo >/dev/null 2>&1; then
608 CARGO_BIN="cargo"
609else
610 CARGO_BIN="${CARGO_HOME:-$HOME/.cargo}/bin/cargo"
611fi
612
613# --- dry run: print modules/tasks/commands, run nothing ---
614if [[ $DRY_RUN -eq 1 ]]; then
615 echo "[DRY-RUN] Modules (${#MODS[@]}): ${MODS[*]}"
616 if [[ $RUN_RUST -eq 1 ]]; then
617 if [[ ${#ROOT_CRATES[@]} -gt 0 || ${#STANDALONE_DIRS[@]} -gt 0 ]]; then
618 if [[ $NO_COV -eq 1 ]]; then
619 if [[ ${#ROOT_CRATES[@]} -gt 0 ]]; then
620 pargs=""; for c in "${ROOT_CRATES[@]}"; do pargs="$pargs -p $c"; done
621 if [[ $ALL_EXP -eq 1 ]]; then
622 echo "[DRY-RUN] Would execute: cargo test --locked --workspace --exclude tilecodec (in $ROOT)"
623 else
624 echo "[DRY-RUN] Would execute: cargo test --locked$pargs (in $ROOT)"
625 fi
626 fi
627 for rdir in ${STANDALONE_DIRS[@]:-}; do
628 echo "[DRY-RUN] Would execute: cargo test --locked (in $rdir)"
629 done
630 else
631 if [[ ${#ROOT_CRATES[@]} -gt 0 ]]; then
632 pargs=""; for c in "${ROOT_CRATES[@]}"; do pargs="$pargs -p $c"; done
633 if [[ $ALL_EXP -eq 1 ]]; then
634 echo "[DRY-RUN] Would execute: cargo llvm-cov --workspace --locked --exclude tilecodec --lcov --output-path target/llvm-cov.lcov (in $ROOT)"
635 else
636 echo "[DRY-RUN] Would execute: cargo llvm-cov --locked$pargs --lcov --output-path target/llvm-cov.lcov (in $ROOT)"
637 fi
638 fi
639 for rdir in ${STANDALONE_DIRS[@]:-}; do
640 echo "[DRY-RUN] Would execute: cargo llvm-cov --locked --lcov --output-path $rdir/llvm-cov.lcov (in $rdir)"
641 done
642 fi
643 else
644 echo "[DRY-RUN] Rust: no crates in scope; cargo steps skipped."
645 fi
646 else
647 echo "[DRY-RUN] Rust phase skipped."
648 fi
649 if [[ $RUN_UNIT -eq 1 ]]; then
650 echo "[DRY-RUN] Would execute: $SCRIPT_DIR/gradlew ${UNIT_TASKS[*]}$gradle_args_str"
651 for mod in "${MODS[@]}"; do
652 echo "[DRY-RUN] Would summarize merged coverage from $mod/build/reports/coverage/merged/report.xml (fall back to $mod/build/reports/coverage/test/*/report.xml)"
653 done
654 else
655 echo "[DRY-RUN] Unit phase skipped."
656 fi
657 if [[ $RUN_INST -eq 1 ]]; then
658 if [[ ${#INST_MODS[@]} -gt 0 ]]; then
659 echo "[DRY-RUN] Would execute: $SCRIPT_DIR/gradlew ${INST_TASKS[*]}$gradle_args_str"
660 if [[ -z "$DEVICE_HINT" ]]; then
661 echo "[DRY-RUN] Would ensure the $EMULATOR_AVD emulator is running (boot headless if needed), under the emulator lock."
662 fi
663 for mod in "${INST_MODS[@]}"; do
664 colon_mod="$(echo "$mod" | tr '/' ':')"
665 base="${mod##*/}"
666 if is_app_module "$mod"; then
667 variant="dev"
668 pkg="$(module_application_id "$colon_mod")"
669 [[ -z "$pkg" ]] && pkg="<applicationId from $mod/build.gradle.kts>"
670 echo "[DRY-RUN] Would session-install $pkg from $mod/build/outputs/apk/$variant/$base-$variant.apk (or output-metadata.json outputFile)"
671 test_pkg="$pkg.test"
672 else
673 variant="debug"
674 test_pkg="$(library_test_package "$mod")"
675 echo "[DRY-RUN] Would install test APK only (library has no app APK): $mod/build/outputs/apk/androidTest/$variant/$base-$variant-androidTest.apk"
676 fi
677 echo "[DRY-RUN] Would run: adb install -r $mod/build/outputs/apk/androidTest/$variant/$base-$variant-androidTest.apk"
678 if [[ $NO_COV -eq 1 ]]; then
679 echo "[DRY-RUN] Would run: adb -s \${ANDROID_SERIAL:-<device>} shell am instrument -w -r $test_pkg/androidx.test.runner.AndroidJUnitRunner"
680 else
681 echo "[DRY-RUN] Would run: adb -s \${ANDROID_SERIAL:-<device>} shell am instrument -w -r -e coverage true -e coverageFilePath /data/data/$test_pkg/files/coverage.ec $test_pkg/androidx.test.runner.AndroidJUnitRunner"
682 echo "[DRY-RUN] Would pull: adb exec-out run-as $test_pkg cat files/coverage.ec > $mod/build/outputs/coverage-manual/$test_pkg.ec"
683 fi
684 done
685 else
686 echo "[DRY-RUN] Instrumented phase skipped (nothing in scope)."
687 fi
688 else
689 echo "[DRY-RUN] Instrumented phase skipped."
690 fi
691 exit 0
692fi
693
694RUST_RC=0
695UNIT_RC=0
696INST_RC=0
697
698# --- rust phase ---
699if [[ $RUN_RUST -eq 1 ]]; then
700 if [[ ! -x "$CARGO_BIN" ]] && ! command -v "$CARGO_BIN" >/dev/null 2>&1; then
701 echo "Error: cargo not found ($CARGO_BIN)." >&2; exit 1
702 fi
703 # cargo include_bytes!s the SPIR-V that :mod:compileShaders writes to build/spirv.
704 SHADER_TASKS=()
705 for mod in "${MODS[@]}"; do
706 [[ -d "$ROOT/$mod/src/main/rust/shaders" ]] && SHADER_TASKS+=(":$(echo "$mod" | tr '/' ':'):compileShaders")
707 done
708 if [[ ${#SHADER_TASKS[@]} -gt 0 ]]; then
709 echo "Running: $SCRIPT_DIR/gradlew ${SHADER_TASKS[*]}"
710 "$SCRIPT_DIR/gradlew" "${SHADER_TASKS[@]}" --console=plain || RUST_RC=$?
711 fi
712 if [[ ${#ROOT_CRATES[@]} -eq 0 && ${#STANDALONE_DIRS[@]} -eq 0 ]]; then
713 echo "No Rust crates in scope; cargo steps skipped."
714 elif [[ $NO_COV -eq 1 ]]; then
715 if [[ ${#ROOT_CRATES[@]} -gt 0 ]]; then
716 echo ""
717 CARGO_ARGS=()
718 if [[ $ALL_EXP -eq 1 ]]; then
719 CARGO_ARGS+=(--workspace --exclude tilecodec)
720 else
721 for c in "${ROOT_CRATES[@]}"; do CARGO_ARGS+=(-p "$c"); done
722 fi
723 echo "Running: cargo test --locked ${CARGO_ARGS[*]}"
724 ( cd "$ROOT" && "$CARGO_BIN" test --locked "${CARGO_ARGS[@]}" ) || RUST_RC=$?
725 [[ $RUST_RC -ne 0 ]] && echo "Warning: cargo test (workspace) reported failures (exit $RUST_RC)."
726 fi
727 for rdir in ${STANDALONE_DIRS[@]:-}; do
728 echo ""
729 echo "Running: cargo test --locked (in $rdir)"
730 ( cd "$rdir" && "$CARGO_BIN" test --locked ) || RUST_RC=$?
731 [[ $RUST_RC -ne 0 ]] && echo "Warning: cargo test ($rdir) reported failures (exit $RUST_RC)."
732 done
733 else
734 echo ""
735 echo "Ensuring rust coverage tools (llvm-tools-preview, cargo-llvm-cov)..."
736 COV_TOOLS_OK=1
737 if command -v rustup >/dev/null 2>&1; then
738 rustup component add llvm-tools-preview >/dev/null 2>&1 || COV_TOOLS_OK=0
739 else
740 echo "Warning: rustup not found; assuming llvm-tools-preview is already installed."
741 fi
742 if ! "$CARGO_BIN" llvm-cov --version >/dev/null 2>&1; then
743 "$CARGO_BIN" install cargo-llvm-cov --locked >/dev/null 2>&1 || COV_TOOLS_OK=0
744 fi
745 if [[ $COV_TOOLS_OK -eq 0 ]]; then
746 echo "Warning: rust coverage tools unavailable (offline?); falling back to plain cargo test without coverage."
747 if [[ ${#ROOT_CRATES[@]} -gt 0 ]]; then
748 echo ""
749 CARGO_ARGS=()
750 if [[ $ALL_EXP -eq 1 ]]; then
751 CARGO_ARGS+=(--workspace --exclude tilecodec)
752 else
753 for c in "${ROOT_CRATES[@]}"; do CARGO_ARGS+=(-p "$c"); done
754 fi
755 echo "Running: cargo test --locked ${CARGO_ARGS[*]}"
756 ( cd "$ROOT" && "$CARGO_BIN" test --locked "${CARGO_ARGS[@]}" ) || RUST_RC=$?
757 [[ $RUST_RC -ne 0 ]] && echo "Warning: cargo test (workspace) reported failures (exit $RUST_RC)."
758 fi
759 for rdir in ${STANDALONE_DIRS[@]:-}; do
760 echo ""
761 echo "Running: cargo test --locked (in $rdir)"
762 ( cd "$rdir" && "$CARGO_BIN" test --locked ) || RUST_RC=$?
763 [[ $RUST_RC -ne 0 ]] && echo "Warning: cargo test ($rdir) reported failures (exit $RUST_RC)."
764 done
765 else
766 if [[ ${#ROOT_CRATES[@]} -gt 0 ]]; then
767 echo ""
768 COV_ARGS=()
769 if [[ $ALL_EXP -eq 1 ]]; then
770 COV_ARGS+=(--workspace --exclude tilecodec)
771 else
772 for c in "${ROOT_CRATES[@]}"; do COV_ARGS+=(-p "$c"); done
773 fi
774 echo "Running: cargo llvm-cov --locked ${COV_ARGS[*]} --lcov --output-path target/llvm-cov.lcov"
775 ( cd "$ROOT" && "$CARGO_BIN" llvm-cov --locked "${COV_ARGS[@]}" --lcov --output-path target/llvm-cov.lcov ) || RUST_RC=$?
776 [[ $RUST_RC -ne 0 ]] && echo "Warning: cargo llvm-cov (workspace) reported failures (exit $RUST_RC)."
777 fi
778 for rdir in ${STANDALONE_DIRS[@]:-}; do
779 echo ""
780 echo "Running: cargo llvm-cov --locked --lcov --output-path $rdir/llvm-cov.lcov (in $rdir)"
781 ( cd "$rdir" && "$CARGO_BIN" llvm-cov --locked --lcov --output-path "$rdir/llvm-cov.lcov" ) || RUST_RC=$?
782 [[ $RUST_RC -ne 0 ]] && echo "Warning: cargo llvm-cov ($rdir) reported failures (exit $RUST_RC)."
783 done
784 fi
785 fi
786fi
787
788# --- unit phase: single gradlew invocation, then coverage summary ---
789if [[ $RUN_UNIT -eq 1 ]]; then
790 echo ""
791 echo "Running: $SCRIPT_DIR/gradlew ${UNIT_TASKS[*]}$gradle_args_str"
792 echo ""
793 set +u
794 "$SCRIPT_DIR/gradlew" "${UNIT_TASKS[@]}" "${GRADLE_ARGS[@]}" || UNIT_RC=$?
795 set -u
796 echo ""
797 [[ $UNIT_RC -ne 0 ]] && echo "Warning: unit test tasks reported failures (exit $UNIT_RC)."
798 if [[ $NO_COV -eq 0 ]]; then
799 echo ""
800 echo "Coverage (MERGED report when present, else unit-only; INSTRUCTION counters):"
801 TOTAL_COV=0; TOTAL_MISS=0
802 for mod in "${MODS[@]}"; do
803 xml=""; kind=""
804 if [[ -f "$ROOT/$mod/build/reports/coverage/merged/report.xml" ]]; then
805 xml="$ROOT/$mod/build/reports/coverage/merged/report.xml"
806 kind="merged"
807 else
808 while IFS= read -r f; do
809 case "$f" in "" ) continue;; esac
810 xml="$f"; kind="unit"; break
811 done < <(find "$ROOT/$mod/build/reports/coverage/test" -maxdepth 2 -name report.xml 2>/dev/null | sort)
812 fi
813 if [[ -z "$xml" || ! -f "$xml" ]]; then
814 echo " $mod: no coverage data (no tests?)"
815 continue
816 fi
817 # report-level totals are the last counters in JaCoCo XML
818 line="$(grep -oE '<counter type="INSTRUCTION"[^>]*>' "$xml" 2>/dev/null | tail -1 || true)"
819 missed="$(echo "$line" | sed -nE 's/.*missed="([0-9]+)".*/\1/p')"
820 covered="$(echo "$line" | sed -nE 's/.*covered="([0-9]+)".*/\1/p')"
821 if [[ -z "$missed" || -z "$covered" ]]; then
822 echo " $mod: no coverage data (no tests?)"
823 continue
824 fi
825 total=$((covered + missed))
826 if [[ $total -gt 0 ]]; then pct="$(awk "BEGIN {printf \"%.1f\", 100*$covered/$total}")"; else pct="100.0"; fi
827 echo " $mod [$kind]: $pct% (covered=$covered missed=$missed)"
828 TOTAL_COV=$((TOTAL_COV + covered))
829 TOTAL_MISS=$((TOTAL_MISS + missed))
830 done
831 grand=$((TOTAL_COV + TOTAL_MISS))
832 if [[ $grand -gt 0 ]]; then total_pct="$(awk "BEGIN {printf \"%.1f\", 100*$TOTAL_COV/$grand}")"; else total_pct="100.0"; fi
833 echo " TOTAL: $total_pct% (covered=$TOTAL_COV missed=$TOTAL_MISS)"
834 fi
835fi
836
837# --- instrumented phase: assemble, session-install, run, pull coverage ---
838# Runs under the emulator lock acquired during device selection (default path), so
839# concurrent ./test runs serialize their install+instrument loops. UD lock is NOT held
840# when --device selected an explicit device: several agents may share one physical
841# device only if they coordinate elsewhere (the lock is emulator-scoped by design).
842if [[ $RUN_INST -eq 1 && ${#INST_MODS[@]} -gt 0 ]]; then
843 echo ""
844 echo "Running: $SCRIPT_DIR/gradlew ${INST_TASKS[*]}$gradle_args_str"
845 echo ""
846 set +u
847 "$SCRIPT_DIR/gradlew" "${INST_TASKS[@]}" "${GRADLE_ARGS[@]}" || INST_RC=$?
848 set -u
849 echo ""
850 [[ $INST_RC -ne 0 ]] && echo "Warning: instrumented assemble reported failures (exit $INST_RC); installing whatever APKs exist."
851 TOTAL=${#INST_MODS[@]}
852 echo ""
853 echo "Running instrumented tests on $TARGET_SERIAL ($TOTAL module(s))..."
854 idx=0
855 while [[ $idx -lt ${#INST_MODS[@]} ]]; do
856 mod="${INST_MODS[$idx]}"
857 colon_mod="$(echo "$mod" | tr '/' ':')"
858 cur=$((idx + 1))
859 idx=$((idx + 1))
860 if is_app_module "$mod"; then
861 variant="dev"
862 pkg="$(module_application_id "$colon_mod")"
863 if [[ -z "$pkg" ]]; then
864 echo "[$cur/$TOTAL] Error: no applicationId found for :${colon_mod}."
865 INST_RC=1; continue
866 fi
867 test_pkg="$pkg.test"
868 if apk="$(built_app_apk "$colon_mod" "$variant")"; then
869 install_apk_via_session "$apk" "$pkg" "$cur" "$TOTAL" || { INST_RC=1; continue; }
870 else
871 echo "[$cur/$TOTAL] Error: no app APK found for :${colon_mod} (assemble failed?)."
872 INST_RC=1; continue
873 fi
874 else
875 # Library: the androidTest APK carries the library code and instruments itself.
876 variant="debug"
877 test_pkg="$(library_test_package "$mod")"
878 pkg="$test_pkg"
879 fi
880 if test_apk="$(built_test_apk "$colon_mod" "$variant")"; then
881 echo "[$cur/$TOTAL] Installing test APK $test_pkg..."
882 "$ADB_BIN" -s "$TARGET_SERIAL" install -r -t "$test_apk" >/dev/null 2>&1 || {
883 echo "[$cur/$TOTAL] Error: test APK install failed for $test_pkg."
884 INST_RC=1; continue
885 }
886 else
887 echo "[$cur/$TOTAL] Error: no test APK found for :${colon_mod} (assemble failed?)."
888 INST_RC=1; continue
889 fi
890 # Clean state per module: wipe the app's data before instrumenting so the
891 # designated FullE2eTest starts from a fresh-install first screen. This
892 # must happen here, not inside the test: the instrumentation runs in the
893 # app process, so a `pm clear` from the test would kill the test itself.
894 if is_app_module "$mod"; then
895 "$ADB_BIN" -s "$TARGET_SERIAL" shell pm clear "$pkg" >/dev/null 2>&1 || true
896 fi
897 echo "[$cur/$TOTAL] Running instrumented tests ($test_pkg)..."
898 inst_args=(-w -r)
899 if [[ $NO_COV -eq 0 ]]; then
900 inst_args+=(-e coverage true -e coverageFilePath "/data/data/$pkg/files/coverage.ec")
901 fi
902 inst_out="$("$ADB_BIN" -s "$TARGET_SERIAL" shell am instrument "${inst_args[@]}" "$test_pkg/androidx.test.runner.AndroidJUnitRunner" 2>&1)" || INST_RC=1
903 echo "$inst_out" | grep -E "^(OK \(|FAILURES!!!|Tests run:|INSTRUMENTATION_FAILED|INSTRUMENTATION_RESULT: shortMsg|Process crashed)" | sed "s/^/[$cur\/$TOTAL] /"
904 # am instrument exits 0 even when tests fail or the process crashes.
905 if ! echo "$inst_out" | grep -qE "^OK \(" || echo "$inst_out" | grep -qE "FAILURES!!!|INSTRUMENTATION_FAILED|Process crashed"; then
906 echo "[$cur/$TOTAL] Error: instrumented tests failed for $test_pkg. Failure details:"
907 echo "$inst_out" | grep -E -A15 "^INSTRUMENTATION_STATUS: stack=|^INSTRUMENTATION_RESULT|Process crashed" | head -60
908 INST_RC=1
909 fi
910 if [[ $NO_COV -eq 0 ]]; then
911 ec_dir="$ROOT/$mod/build/outputs/coverage-manual"
912 mkdir -p "$ec_dir"
913 if "$ADB_BIN" -s "$TARGET_SERIAL" exec-out run-as "$pkg" cat files/coverage.ec > "$ec_dir/$pkg.ec" 2>/dev/null && [[ -s "$ec_dir/$pkg.ec" ]]; then
914 echo "[$cur/$TOTAL] Coverage pulled: $ec_dir/$pkg.ec (fold in with :${colon_mod}:createMergedCoverageReport)"
915 else
916 rm -f "$ec_dir/$pkg.ec"
917 echo "[$cur/$TOTAL] Warning: could not pull coverage.ec for $pkg."
918 fi
919 fi
920 done
921fi
922
923if [[ $RUST_RC -ne 0 || $UNIT_RC -ne 0 || $INST_RC -ne 0 ]]; then exit 1; fi
924exit 0