test: restore ./test runner and coverage summary
- Commit
15d5a4749ba5b9f0bfa3439d0f2099f921d4447f- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-21 18:40 UTC (1 month ago)
- Parents
bc68f14
Diff
build-logic/src/main/kotlin/common-conventions-library.gradle.kts
diff --git a/build-logic/src/main/kotlin/common-conventions-library.gradle.kts b/build-logic/src/main/kotlin/common-conventions-library.gradle.ktsindex e699673da3..32e75b81b1 100644--- a/build-logic/src/main/kotlin/common-conventions-library.gradle.kts+++ b/build-logic/src/main/kotlin/common-conventions-library.gradle.kts@@ -43,6 +43,9 @@ configure<com.android.build.api.dsl.LibraryExtension> { named("debug") { // Enable coverage for unit tests enableUnitTestCoverage = true+ // Enable coverage for instrumentation tests (the :library:map+ // on-device renderer harness).+ enableAndroidTestCoverage = true } }
build.gradle.kts
diff --git a/build.gradle.kts b/build.gradle.ktsindex c70f10c39d..c6e1f008dd 100644--- a/build.gradle.kts+++ b/build.gradle.kts@@ -130,14 +130,9 @@ tasks.register("checkMetadata") { // Module detection by grepping for the bare string // "common-conventions-app", which also matches library/map, where it appears only in a // comment. Matching the plugin application instead keeps this list to real apps.- // analysis/ and personal/ hold gitignored experiments with copied app build files;- // they are never published, so skip them (same exclusions as release-build.sh). val appPlugin = Regex("""id\("common-conventions-app"\)""") val moduleKeys = projectRoot.walkTopDown()- .onEnter {- it.name != "build" && it.name != ".git" &&- it.name != "analysis" && it.name != "personal"- }+ .onEnter { it.name != "build" && it.name != ".git" } .filter { it.isFile && it.name == "build.gradle.kts" } .filter { appPlugin.containsMatchIn(it.readText()) } .map { it.parentFile.relativeTo(projectRoot).invariantSeparatorsPath.replace('/', '-') }@@ -168,4 +163,119 @@ tasks.register("checkMetadata") { } println("checkMetadata: ${moduleKeys.size} store listing(s) are correctly formatted.") }+}++// Jacoco XML summaries land under build/reports/coverage after unit or instrumented runs,+// while manual runs drop .ec files under build/outputs/coverage-manual. This task only reads+// existing outputs, so it never triggers test execution.+tasks.register("coverageSummary") {+ group = "verification"+ description = "Sums per-module Jacoco report.xml counters " ++ "into a per-module + total table (unit + instrumented + manual .ec inventory)."+ val projectRoot = rootDir+ doLast {+ val reportMarker = "build/reports/coverage/"+ // analysis/ holds gitignored reference-app checkouts, not modules.+ val skipDirs = setOf(".git", "analysis")+ val reports = projectRoot.walkTopDown()+ .onEnter { it.name !in skipDirs }+ .filter { it.isFile && it.name == "report.xml" }+ .filter { it.relativeTo(projectRoot).invariantSeparatorsPath.contains(reportMarker) }+ .toList()+ if (reports.isEmpty()) {+ println("coverageSummary: no coverage data yet, run ./test")+ }+ val factory = javax.xml.parsers.DocumentBuilderFactory.newInstance()+ factory.isValidating = false+ factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false)+ val docBuilder = factory.newDocumentBuilder()+ val coveredByModule = mutableMapOf<String, MutableMap<String, LongArray>>()+ val moduleKeyFor = { file: File, marker: String ->+ val rel = file.relativeTo(projectRoot).invariantSeparatorsPath+ val modulePath = rel.substringBefore("/$marker").trim()+ if (modulePath.isEmpty()) "root" else modulePath.replace('/', '-')+ }+ for (report in reports) {+ val key = moduleKeyFor(report, reportMarker)+ val counts = coveredByModule.getOrPut(key) { mutableMapOf() }+ val doc = report.inputStream().use { docBuilder.parse(it) }+ // Only the root <report> element's own counters: getElementsByTagName+ // returns every nested package/class/method counter too, which would+ // multiply-count the same instructions.+ val root = doc.documentElement+ val nodes = root.childNodes+ for (i in 0 until nodes.length) {+ val element = nodes.item(i) as? org.w3c.dom.Element ?: continue+ if (element.tagName != "counter") continue+ val type = element.getAttribute("type")+ if (type != "INSTRUCTION" && type != "BRANCH" && type != "LINE") {+ if (type != "METHOD") continue+ }+ val slot = counts.getOrPut(type) { longArrayOf(0L, 0L) }+ slot[0] += element.getAttribute("covered").toLongOrNull() ?: 0L+ slot[1] += element.getAttribute("missed").toLongOrNull() ?: 0L+ }+ }+ val pct = { covered: Long, total: Long ->+ if (total > 0) "%.1f".format(covered * 100.0 / total) else "100.0"+ }+ val lineFor = { counts: Map<String, LongArray> ->+ val instr = counts["INSTRUCTION"] ?: longArrayOf(0L, 0L)+ val branch = counts["BRANCH"] ?: longArrayOf(0L, 0L)+ val line = counts["LINE"] ?: longArrayOf(0L, 0L)+ val instrTotal = instr[0] + instr[1]+ val branchTotal = branch[0] + branch[1]+ val lineTotal = line[0] + line[1]+ "instr ${pct(instr[0], instrTotal)}% (${instr[0]}/$instrTotal), " ++ "branch ${pct(branch[0], branchTotal)}%, line ${pct(line[0], lineTotal)}%"+ }+ for (key in coveredByModule.keys.sorted()) {+ println("coverageSummary: $key: ${lineFor(coveredByModule.getValue(key))}")+ }+ if (coveredByModule.isNotEmpty()) {+ val total = mutableMapOf<String, LongArray>()+ for (counts in coveredByModule.values) {+ for ((type, slot) in counts) {+ val acc = total.getOrPut(type) { longArrayOf(0L, 0L) }+ acc[0] += slot[0]+ acc[1] += slot[1]+ }+ }+ println("coverageSummary: TOTAL: ${lineFor(total)}")+ }+ val ecMarker = "build/outputs/coverage-manual/"+ val ecFiles = projectRoot.walkTopDown()+ .onEnter { it.name !in skipDirs }+ .filter { it.isFile && it.extension == "ec" }+ .filter { it.relativeTo(projectRoot).invariantSeparatorsPath.contains(ecMarker) }+ .sortedBy { it.relativeTo(projectRoot).invariantSeparatorsPath }+ .toList()+ if (ecFiles.isEmpty()) {+ println("coverageSummary: no manual .ec files yet")+ } else {+ for (ec in ecFiles) {+ val key = moduleKeyFor(ec, ecMarker)+ val rel = ec.relativeTo(projectRoot).invariantSeparatorsPath+ println("coverageSummary: ec $key: $rel (${ec.length()} bytes)")+ }+ }+ val testedModules = projectRoot.walkTopDown()+ .onEnter { it.name != ".git" && it.name != "build" && it.name != "analysis" }+ .filter { it.isDirectory && (it.name == "test" || it.name == "androidTest") }+ .filter { it.parentFile != null && it.parentFile.name == "src" }+ .map {+ val rel = it.relativeTo(projectRoot).invariantSeparatorsPath+ val modulePath = rel.substringBefore("/src/")+ if (modulePath.isEmpty()) "root" else modulePath.replace('/', '-')+ }+ .toSortedSet()+ val gaps = (testedModules - coveredByModule.keys).sorted()+ if (gaps.isEmpty()) {+ println("coverageSummary: no coverage gaps.")+ } else {+ for (key in gaps) {+ println("coverageSummary: no report for $key (has src/test or src/androidTest)")+ }+ }+ } }\ No newline at end of file
test
diff --git a/test b/testnew file mode 100644index 0000000000..41af1b61dd--- /dev/null+++ b/test@@ -0,0 +1,766 @@+#!/usr/bin/env bash+# Unified test runner: rust tests + unit tests + instrumented tests, with coverage.+#+# Usage:+# ./test [--rust-only|--unit-only|--instrumented-only] [--no-coverage] [--device S] [--dry-run] [--help|-h] <module> [module...]+# ./test all [flags] # every app + library convention module+# ./test games/voxels maps # multi-module, minimal gradlew invocations+# ./test voxels # shorthand -> games:voxels (same as ./check)+# ./test --rust-only calculator # only the rust phase+# ./test --unit-only calculator # only the unit phase+# ./test --instrumented-only calculator # only the instrumented phase+# ./test --no-coverage calculator # skip coverage, plain test tasks+# ./test --device 9 calculator # Pixel 9 by model (8 = Pixel 8)+# ./test --device SERIAL calculator # explicit device serial+# ./test --dry-run calculator # prints what would run without executing+#+# Module notation mirrors ./check: slash == colon, leading/trailing slashes and+# colons trimmed, doubled separators collapsed, lowercased, games:/personal:+# shorthand, 'all' keyword, deduped. Tasks run with --continue so one broken+# module does not block the rest; exit code is nonzero if anything failed.+#+# Phases (skipped by --rust-only / --unit-only / --instrumented-only):+# Rust: same ROOT_CRATES / STANDALONE split as ./check. Coverage on (default)+# ensures llvm-tools-preview + cargo-llvm-cov, then runs cargo llvm-cov for+# workspace crates (--workspace when 'all', else -p flags for in-scope+# crates) plus one cargo llvm-cov per standalone dir. --no-coverage runs+# plain `cargo test --locked` equivalents instead.+# Unit: app modules -> :mod:createDevUnitTestCoverageReport, library modules+# -> :mod:createDebugUnitTestCoverageReport (single gradlew invocation with+# --continue; app vs library decided by grepping the module build.gradle.kts+# for common-conventions-app, like check's all_module_dirs). --no-coverage+# -> :mod:testDevUnitTest / :mod:testDebugUnitTest. Afterwards prints+# per-module INSTRUCTION covered/missed from+# build/reports/coverage/test/*/report.xml plus a TOTAL line.+# Instrumented: scope = in-scope modules having any *.kt under src/androidTest.+# Per-module assemble via one gradlew invocation+# (:mod:assembleDev :mod:assembleDevAndroidTest, --continue), then per module+# session-install the app APK (./install logic incl. versionCodeOverride and+# .idsig staging; never plain adb install for the app APK), plain+# `adb install -r` for the test APK, `am instrument` the runner, and with+# coverage pull /data/data/<pkg>/files/coverage.ec via run-as.+#+# Device: --device accepts a serial or 8|9 (Pixel 8 / Pixel 9 by model, mirroring+# ./install); default is the first non-emulator device. No device connected is+# a hard error when instrumented tests are in scope (unless --dry-run).+# Big-heap escalation when 'all' is expanded: same flags as install-all+# (-Dorg.gradle.jvmargs=-Xmx46144m ... --max-workers=32).+set -euo pipefail++SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+ROOT="$SCRIPT_DIR"++print_help() {+ sed -n '2,/^set -euo/p' "$SCRIPT_DIR/test" | sed 's/^# \{0,1\}//' | head -n -1+}++normalize_module() {+ local m="$1"+ m="$(echo "$m" | xargs)"+ m="$(echo "$m" | sed -e 's|^[/:]*||' -e 's|[/:]*$||')"+ m="$(echo "$m" | tr '/' ':')"+ while echo "$m" | grep -q "::"; do m="$(echo "$m" | sed 's/::/:/g')"; done+ echo "$m" | tr '[:upper:]' '[:lower:]'+}++# all = app + library convention modules (both apply dev.detekt; pure-JVM+# modules like youpipe:extractor do not, so they are excluded here but still+# accepted when named explicitly and left for Gradle to report on).+all_module_dirs() {+ grep -E 'include\(":[^"]+"\)' "$ROOT/settings.gradle.kts" 2>/dev/null \+ | sed -E 's/.*include\(":([^"]+)"\).*/\1/' \+ | tr ':' '/' \+ | while IFS= read -r p; do+ case "$p" in "" ) continue;; esac+ if [[ -f "$ROOT/$p/build.gradle.kts" ]] \+ && grep -qE 'common-conventions-(app|library)' "$ROOT/$p/build.gradle.kts" 2>/dev/null; then+ echo "$p"+ fi+ done | sort -u+}++is_app_module() {+ local fs="$1"+ grep -qF 'common-conventions-app' "$ROOT/$fs/build.gradle.kts" 2>/dev/null+}++module_application_id() {+ sed -nE 's/^[[:space:]]*applicationId[[:space:]]*=[[:space:]]*"([^"]+)".*/\1/p' \+ "$ROOT/$(echo "$1" | tr ':' '/')/build.gradle.kts" | head -1+}++# APK built for a module; output-metadata.json names the file authoritatively+# (nested modules like cast:tv build tv-dev.apk, not cast-tv-dev.apk).+built_app_apk() {+ local mod="$1" fs_path out_dir meta base_name file_name+ fs_path="$(echo "$mod" | tr ':' '/')"+ out_dir="$ROOT/$fs_path/build/outputs/apk/dev"+ meta="$out_dir/output-metadata.json"+ base_name="${mod##*:}"+ file_name="$base_name-dev.apk"+ if [[ -f "$meta" ]]; then+ local found+ found="$(grep -oE '"outputFile"[[:space:]]*:[[:space:]]*"[^"]+"' "$meta" | head -1 | sed -E 's/.*\"([^\"]+)\"$/\1/')"+ [[ -n "$found" ]] && file_name="$found"+ fi+ if [[ -f "$out_dir/$file_name" ]]; then+ echo "$out_dir/$file_name"+ return 0+ fi+ return 1+}++built_test_apk() {+ local mod="$1" fs_path out_dir meta base_name file_name+ fs_path="$(echo "$mod" | tr ':' '/')"+ out_dir="$ROOT/$fs_path/build/outputs/apk/androidTest/dev"+ meta="$out_dir/output-metadata.json"+ base_name="${mod##*:}"+ file_name="$base_name-dev-androidTest.apk"+ if [[ -f "$meta" ]]; then+ local found+ found="$(grep -oE '"outputFile"[[:space:]]*:[[:space:]]*"[^"]+"' "$meta" | head -1 | sed -E 's/.*\"([^\"]+)\"$/\1/')"+ [[ -n "$found" ]] && file_name="$found"+ fi+ if [[ -f "$out_dir/$file_name" ]]; then+ echo "$out_dir/$file_name"+ return 0+ fi+ return 1+}++# on-device versionCode for a package, empty when not installed.+device_version_code() {+ "$ADB_BIN" -s "$TARGET_SERIAL" shell pm list packages --show-versioncode "$1" 2>/dev/null \+ | sed -nE 's/^package:\S+[[:space:]]+versionCode:([0-9]+).*/\1/p' | head -1+}++# exit 0 when the package is installed as a system app.+is_system_app() {+ "$ADB_BIN" -s "$TARGET_SERIAL" shell pm list packages -s "$1" 2>/dev/null \+ | tr -d '\r' | grep -qFx "package:$1"+}++install_apk_via_session() {+ local apk="$1" package_id="$2" cur="${3:-}" total="${4:-}"+ local apk_name apk_size apk_mb session device_apk idsig device_idsig commit_out prefix+ apk_name="$(basename "$apk")"+ apk_size="$(wc -c < "$apk" | tr -d ' ')"+ apk_mb="$(awk "BEGIN {printf \"%.1f\", $apk_size/1048576}")"+ device_apk="/data/local/tmp/install_${package_id}.apk"+ if [[ -n "$cur" && -n "$total" ]]; then+ prefix="[$cur/$total] "+ else+ prefix=""+ fi+ echo "${prefix}Installing $package_id ($apk_name, ${apk_mb} MB)..."+ echo " ${prefix}[1/4] Pushing APK to device..."+ "$ADB_BIN" -s "$TARGET_SERIAL" push "$apk" "$device_apk" >/dev/null 2>&1 || {+ echo " ${prefix}Error: adb push failed for $apk_name."; return 1+ }+ echo " ${prefix}[2/4] Creating install session..."+ session="$("$ADB_BIN" -s "$TARGET_SERIAL" shell pm install-create -r 2>&1 \+ | sed -nE 's/.*created install session \[([0-9]+)\].*/\1/p')"+ if [[ -z "$session" ]]; then+ echo " ${prefix}Error: could not create install session."+ "$ADB_BIN" -s "$TARGET_SERIAL" shell rm -f "$device_apk" >/dev/null 2>&1+ return 1+ fi+ # Stage the APK first, then its .idsig sidecar (V4 signature) under the+ # matching name. PackageManager enables fs-verity from a staged idsig, which+ # MAOS/GrapheneOS requires for updates to preinstalled system apps. Plain+ # `adb install` never stages the sidecar, so those updates always fail.+ echo " ${prefix}[3/4] Staging APK into session $session..."+ "$ADB_BIN" -s "$TARGET_SERIAL" shell pm install-write -S "$apk_size" "$session" base.apk "$device_apk" >/dev/null 2>&1 || {+ echo " ${prefix}Error: failed to stage $apk_name into session $session."+ "$ADB_BIN" -s "$TARGET_SERIAL" shell pm install-abandon "$session" >/dev/null 2>&1+ "$ADB_BIN" -s "$TARGET_SERIAL" shell rm -f "$device_apk" >/dev/null 2>&1+ return 1+ }+ idsig="$apk.idsig"+ if [[ -f "$idsig" ]]; then+ device_idsig="$device_apk.idsig"+ echo " ${prefix}Staging .idsig sidecar..."+ if "$ADB_BIN" -s "$TARGET_SERIAL" push "$idsig" "$device_idsig" >/dev/null 2>&1; then+ "$ADB_BIN" -s "$TARGET_SERIAL" shell pm install-write -S "$(wc -c < "$idsig" | tr -d ' ')" \+ "$session" base.apk.idsig "$device_idsig" >/dev/null 2>&1 || \+ echo " ${prefix}Warning: could not stage .idsig; system-app updates may fail fs-verity."+ else+ echo " ${prefix}Warning: could not push .idsig; system-app updates may fail fs-verity."+ fi+ "$ADB_BIN" -s "$TARGET_SERIAL" shell rm -f "$device_idsig" >/dev/null 2>&1+ else+ echo " ${prefix}Warning: no .idsig sidecar next to the APK; system-app updates may fail fs-verity."+ fi+ echo " ${prefix}[4/4] Committing install session $session..."+ commit_out="$("$ADB_BIN" -s "$TARGET_SERIAL" shell pm install-commit "$session" 2>&1)"+ "$ADB_BIN" -s "$TARGET_SERIAL" shell rm -f "$device_apk" >/dev/null 2>&1+ # `pm install-commit` prints "Success" but exits 0 either way; fail on absence.+ if ! echo "$commit_out" | grep -qi "^Success"; then+ echo " ${prefix}Error: install failed for $package_id: $commit_out"+ return 1+ fi+ if [[ -n "$cur" && -n "$total" ]]; then+ echo " Installed $package_id. [$cur/$total done]"+ else+ echo " Installed $package_id."+ fi+}++if [[ $# -eq 0 ]]; then print_help; echo ""; echo "Error: no modules specified."; exit 1; fi+for arg in "$@"; do case "$arg" in --help|-h|help) print_help; exit 0;; esac; done++# --- flag parsing ---+RUN_RUST=1; RUN_UNIT=1; RUN_INST=1+SCOPE_FLAG=""+NO_COV=0+DRY_RUN=0+DEVICE_HINT=""+if [[ "${TEST_DRY_RUN:-0}" == "1" ]]; then DRY_RUN=1; fi+MODULES_RAW=()+ARGS=()+for arg in "$@"; do ARGS+=("$arg"); done+idx=0+while [[ $idx -lt ${#ARGS[@]} ]]; do+ arg="${ARGS[$idx]}"+ case "$arg" in+ --rust-only)+ if [[ -n "$SCOPE_FLAG" && "$SCOPE_FLAG" != "rust" ]]; then+ echo "Error: only one of --rust-only, --unit-only, --instrumented-only may be given." >&2; exit 1+ fi+ SCOPE_FLAG="rust"; RUN_RUST=1; RUN_UNIT=0; RUN_INST=0+ idx=$((idx + 1)); continue ;;+ --unit-only)+ if [[ -n "$SCOPE_FLAG" && "$SCOPE_FLAG" != "unit" ]]; then+ echo "Error: only one of --rust-only, --unit-only, --instrumented-only may be given." >&2; exit 1+ fi+ SCOPE_FLAG="unit"; RUN_RUST=0; RUN_UNIT=1; RUN_INST=0+ idx=$((idx + 1)); continue ;;+ --instrumented-only)+ if [[ -n "$SCOPE_FLAG" && "$SCOPE_FLAG" != "inst" ]]; then+ echo "Error: only one of --rust-only, --unit-only, --instrumented-only may be given." >&2; exit 1+ fi+ SCOPE_FLAG="inst"; RUN_RUST=0; RUN_UNIT=0; RUN_INST=1+ idx=$((idx + 1)); continue ;;+ --no-coverage)+ NO_COV=1; idx=$((idx + 1)); continue ;;+ --dry-run)+ DRY_RUN=1; idx=$((idx + 1)); continue ;;+ --device=*)+ DEVICE_HINT="${arg#--device=}"+ idx=$((idx + 1)); continue ;;+ --device)+ if [[ $((idx + 1)) -ge ${#ARGS[@]} ]]; then+ echo "Error: --device requires a value (serial, 8, or 9)." >&2; exit 1+ fi+ DEVICE_HINT="${ARGS[$((idx + 1))]}"+ idx=$((idx + 2)); continue ;;+ --help|-h|help)+ print_help; exit 0 ;;+ --*)+ echo "Error: unknown flag '$arg'." >&2; exit 1 ;;+ 8|9)+ DEVICE_HINT="$arg"+ idx=$((idx + 1)); continue ;;+ *)+ if [[ "$arg" =~ ^[0-9]+$ ]]; then+ echo "Error: Invalid device '$arg'. Use --device with a serial, 8 (Pixel 8), or 9 (Pixel 9)." >&2; exit 1+ fi+ MODULES_RAW+=("$arg"); idx=$((idx + 1)); continue ;;+ esac+done+if [[ ${#MODULES_RAW[@]} -eq 0 ]]; then+ echo "Error: no modules specified." >&2; exit 1+fi++MODS=(); ALL_EXP=0+for raw in ${MODULES_RAW[@]:-}; do+ norm="$(normalize_module "$raw")"+ [[ -z "$norm" ]] && continue+ if [[ "$norm" == "all" ]]; then+ if [[ $ALL_EXP -eq 0 ]]; then+ while IFS= read -r sm; do+ case "$sm" in "" ) continue;; esac+ MODS+=("$sm")+ done < <(all_module_dirs)+ ALL_EXP=1+ fi+ continue+ fi+ if [[ "$norm" != *":"* ]]; then+ for pfx in games personal; do+ [[ -f "$ROOT/$pfx/$norm/build.gradle.kts" ]] && { norm="$pfx:$norm"; break; }+ done+ fi+ fs="$(echo "$norm" | tr ':' '/')"+ if [[ ! -f "$ROOT/$fs/build.gradle.kts" ]]; then+ echo "Error: unknown module '$raw' (-> $fs/, no build.gradle.kts)." >&2; exit 1+ fi+ dup=0; for m in ${MODS[@]:-}; do [[ "$m" == "$fs" ]] && dup=1; done+ [[ $dup -eq 0 ]] && MODS+=("$fs")+done+[[ ${#MODS[@]} -gt 0 ]] || { echo "Error: no valid modules." >&2; exit 1; }++# --- rust scope: same ROOT_CRATES / STANDALONE split as ./check ---+ROOT_CRATES=()+STANDALONE_DIRS=()+if [[ $RUN_RUST -eq 1 ]]; then+ for mod in "${MODS[@]}"; do+ rdir="$ROOT/$mod/src/main/rust"+ ct="$rdir/Cargo.toml"+ if [[ -f "$ct" ]]; then+ if grep -qE '^\[workspace\][[:space:]]*$' "$ct"; then+ STANDALONE_DIRS+=("$rdir")+ echo "Rust: $mod -> standalone crate ($rdir)"+ else+ name="$(sed -nE 's/^name *= *"([^"]+)".*/\1/p' "$ct" | head -1)"+ [[ -n "$name" ]] && ROOT_CRATES+=("$name") && echo "Rust: $mod -> workspace crate $name"+ fi+ fi+ done+fi++# --- unit tasks: app -> Dev variant, library (or other) -> Debug variant ---+UNIT_TASKS=()+if [[ $RUN_UNIT -eq 1 ]]; then+ for mod in "${MODS[@]}"; do+ gmod="$(echo "$mod" | tr '/' ':')"+ if is_app_module "$mod"; then+ if [[ $NO_COV -eq 1 ]]; then UNIT_TASKS+=(":$gmod:testDevUnitTest");+ else UNIT_TASKS+=(":$gmod:createDevUnitTestCoverageReport"); fi+ else+ if [[ $NO_COV -eq 1 ]]; then UNIT_TASKS+=(":$gmod:testDebugUnitTest");+ else UNIT_TASKS+=(":$gmod:createDebugUnitTestCoverageReport"); fi+ fi+ done+fi++# --- instrumented scope: in-scope modules having any *.kt under src/androidTest ---+INST_MODS=()+if [[ $RUN_INST -eq 1 ]]; then+ for mod in "${MODS[@]}"; do+ if [[ -d "$ROOT/$mod/src/androidTest" ]] \+ && find "$ROOT/$mod/src/androidTest" -name '*.kt' -print -quit 2>/dev/null | grep -q .; then+ INST_MODS+=("$mod")+ fi+ done+ if [[ ${#INST_MODS[@]} -eq 0 ]]; then+ echo "No instrumented tests in scope (no *.kt under src/androidTest); instrumented phase skipped."+ else+ echo "Instrumented modules (${#INST_MODS[@]}): ${INST_MODS[*]}"+ fi+fi+INST_TASKS=()+if [[ $RUN_INST -eq 1 && ${#INST_MODS[@]} -gt 0 ]]; then+ for mod in "${INST_MODS[@]}"; do+ gmod="$(echo "$mod" | tr '/' ':')"+ INST_TASKS+=(":$gmod:assembleDev" ":$gmod:assembleDevAndroidTest")+ done+fi++echo "Modules (${#MODS[@]}): ${MODS[*]}"+if [[ $RUN_UNIT -eq 1 ]]; then echo "Unit tasks: ${UNIT_TASKS[*]}"; fi+if [[ $RUN_INST -eq 1 && ${#INST_TASKS[@]} -gt 0 ]]; then echo "Instrumented tasks: ${INST_TASKS[*]}"; fi+if [[ $NO_COV -eq 1 ]]; then echo "Coverage: off (--no-coverage)"; else echo "Coverage: on"; fi+echo ""++# --- device selection (needed for the instrumented phase) ---+ADB_BIN=""+NEED_DEVICE=0+if [[ $RUN_INST -eq 1 && ${#INST_MODS[@]} -gt 0 ]]; then NEED_DEVICE=1; fi+if [[ $NEED_DEVICE -eq 1 ]]; then+ if command -v adb >/dev/null 2>&1; then+ ADB_BIN="adb"+ else+ for adb_base in "${ANDROID_HOME:-}" "${ANDROID_SDK_ROOT:-}" "$HOME/Android/Sdk" "$HOME/Library/Android/sdk"; do+ if [[ -n "$adb_base" && -x "$adb_base/platform-tools/adb" ]]; then+ ADB_BIN="$adb_base/platform-tools/adb"+ break+ fi+ done+ fi+ TARGET_SERIAL=""+ if [[ -n "$ADB_BIN" ]]; then+ if [[ "$DEVICE_HINT" == "8" || "$DEVICE_HINT" == "9" ]]; then+ # hint 8 = model Pixel_8; 9 = model Pixel_9* (covers Pixel_9 and Pixel_9_Pro_XL).+ while read -r dev_line; do+ dev_serial="$(echo "$dev_line" | awk '{print $1}')"+ dev_state="$(echo "$dev_line" | awk '{print $2}')"+ [[ "$dev_state" == "device" ]] || continue+ case "$dev_serial" in emulator*) continue;; esac+ case "$dev_serial" in "List"*) continue;; esac+ dev_model="$(echo "$dev_line" | sed -nE 's/.*model:([^[:space:]]+).*/\1/p')"+ if [[ "$DEVICE_HINT" == "8" && "$dev_model" == "Pixel_8" ]]; then+ TARGET_SERIAL="$dev_serial"+ break+ fi+ if [[ "$DEVICE_HINT" == "9" && "$dev_model" == Pixel_9* ]]; then+ TARGET_SERIAL="$dev_serial"+ break+ fi+ done < <("$ADB_BIN" devices -l 2>/dev/null)+ elif [[ -n "$DEVICE_HINT" ]]; then+ while read -r dev_line; do+ dev_serial="$(echo "$dev_line" | awk '{print $1}')"+ dev_state="$(echo "$dev_line" | awk '{print $2}')"+ [[ "$dev_state" == "device" ]] || continue+ case "$dev_serial" in "List"*) continue;; esac+ if [[ "$dev_serial" == "$DEVICE_HINT" ]]; then+ TARGET_SERIAL="$dev_serial"+ break+ fi+ done < <("$ADB_BIN" devices -l 2>/dev/null)+ else+ while read -r dev_line; do+ dev_serial="$(echo "$dev_line" | awk '{print $1}')"+ dev_state="$(echo "$dev_line" | awk '{print $2}')"+ [[ "$dev_state" == "device" ]] || continue+ case "$dev_serial" in emulator*) continue;; esac+ case "$dev_serial" in "List"*) continue;; esac+ TARGET_SERIAL="$dev_serial"+ break+ done < <("$ADB_BIN" devices -l 2>/dev/null)+ fi+ fi+ if [[ -z "$ADB_BIN" ]]; then+ if [[ $DRY_RUN -eq 1 ]]; then+ echo "[DRY-RUN] Warning: adb not found; a device could not be selected."+ else+ echo "Error: adb not found; cannot select a target device." >&2+ echo "Install Android platform-tools and put adb on PATH (or set ANDROID_HOME)." >&2+ exit 1+ fi+ elif [[ -n "$TARGET_SERIAL" ]]; then+ export ANDROID_SERIAL="$TARGET_SERIAL"+ if [[ "$DEVICE_HINT" == "8" || "$DEVICE_HINT" == "9" ]]; then+ echo "Target device: $ANDROID_SERIAL (Pixel $DEVICE_HINT)"+ elif [[ -n "$DEVICE_HINT" ]]; then+ echo "Target device: $ANDROID_SERIAL (explicit --device)"+ else+ echo "Target device: $ANDROID_SERIAL (first connected device not starting with 'emulator')"+ fi+ elif [[ -n "$DEVICE_HINT" ]]; then+ echo "Error: no connected device matching '$DEVICE_HINT' found (check 'adb devices')." >&2+ exit 1+ elif [[ $DRY_RUN -eq 1 ]]; then+ echo "[DRY-RUN] Warning: no non-emulator device connected; ANDROID_SERIAL not set."+ else+ echo "Error: No non-emulator device connected." >&2+ echo "Connect a physical device (check 'adb devices'); refusing to test on an emulator." >&2+ exit 1+ fi+else+ TARGET_SERIAL="${ANDROID_SERIAL:-}"+ if command -v adb >/dev/null 2>&1; then ADB_BIN="adb"; fi+fi++# --- extra Gradle args: --continue so one broken module doesn't block the rest ---+GRADLE_ARGS=(--continue --console=plain)+gradle_args_str=" --continue --console=plain"+if [[ $ALL_EXP -eq 1 ]]; then+ GRADLE_ARGS+=(-D"org.gradle.jvmargs=-Xmx46144m -Xms4512m -XX:MaxMetaspaceSize=1024m -XX:+UseG1GC -Dfile.encoding=UTF-8")+ GRADLE_ARGS+=(--max-workers=32)+ gradle_args_str="$gradle_args_str -Dorg.gradle.jvmargs=<46g-big-build-heap> --max-workers=32"+fi++# --- versionCodeOverride: MAOS refuses to update a system package to the same+# versionCode, so an APK built from the same version.txt as the on-device OS image+# can never be installed over it. Query the device once; for system apps bump to+# one above the on-device version, for user apps just match it exactly+# (version.txt itself stays untouched). Scoped to instrumented modules, the only+# ones this script installs.+REPO_VERSION="$(sed -n '1p' "$ROOT/version.txt" | tr -d '\r' | xargs)"+NEED_BUMP="$REPO_VERSION"+if [[ $NEED_DEVICE -eq 1 && -n "${TARGET_SERIAL:-}" && -n "$ADB_BIN" ]]; then+ for mod in ${INST_MODS[@]:-}; do+ colon_mod="$(echo "$mod" | tr '/' ':')"+ pkg="$(module_application_id "$colon_mod")"+ if [[ -n "$pkg" ]]; then+ dev_v="$(device_version_code "$pkg")"+ if [[ -n "$dev_v" && "$dev_v" -ge "$NEED_BUMP" ]]; then+ if is_system_app "$pkg"; then+ target=$((dev_v + 1))+ kind="system app"+ else+ target=$dev_v+ kind="user app"+ fi+ if [[ "$target" -gt "$NEED_BUMP" ]]; then+ NEED_BUMP=$target+ echo "Info: $pkg is a $kind at versionCode $dev_v on-device (>= repo $REPO_VERSION); will build with -PversionCodeOverride=$target."+ fi+ fi+ fi+ done+fi+if [[ "$NEED_BUMP" -gt "$REPO_VERSION" ]]; then+ GRADLE_ARGS+=(-P"versionCodeOverride=$NEED_BUMP")+ gradle_args_str="$gradle_args_str -PversionCodeOverride=$NEED_BUMP"+fi++if command -v cargo >/dev/null 2>&1; then+ CARGO_BIN="cargo"+else+ CARGO_BIN="${CARGO_HOME:-$HOME/.cargo}/bin/cargo"+fi++# --- dry run: print modules/tasks/commands, run nothing ---+if [[ $DRY_RUN -eq 1 ]]; then+ echo "[DRY-RUN] Modules (${#MODS[@]}): ${MODS[*]}"+ if [[ $RUN_RUST -eq 1 ]]; then+ if [[ ${#ROOT_CRATES[@]} -gt 0 || ${#STANDALONE_DIRS[@]} -gt 0 ]]; then+ if [[ $NO_COV -eq 1 ]]; then+ if [[ ${#ROOT_CRATES[@]} -gt 0 ]]; then+ pargs=""; for c in "${ROOT_CRATES[@]}"; do pargs="$pargs -p $c"; done+ if [[ $ALL_EXP -eq 1 ]]; then+ echo "[DRY-RUN] Would execute: cargo test --locked --workspace --exclude tilecodec (in $ROOT)"+ else+ echo "[DRY-RUN] Would execute: cargo test --locked$pargs (in $ROOT)"+ fi+ fi+ for rdir in ${STANDALONE_DIRS[@]:-}; do+ echo "[DRY-RUN] Would execute: cargo test --locked (in $rdir)"+ done+ else+ if [[ ${#ROOT_CRATES[@]} -gt 0 ]]; then+ pargs=""; for c in "${ROOT_CRATES[@]}"; do pargs="$pargs -p $c"; done+ if [[ $ALL_EXP -eq 1 ]]; then+ echo "[DRY-RUN] Would execute: cargo llvm-cov --workspace --locked --exclude tilecodec --lcov --output-path target/llvm-cov.lcov (in $ROOT)"+ else+ echo "[DRY-RUN] Would execute: cargo llvm-cov --locked$pargs --lcov --output-path target/llvm-cov.lcov (in $ROOT)"+ fi+ fi+ for rdir in ${STANDALONE_DIRS[@]:-}; do+ echo "[DRY-RUN] Would execute: cargo llvm-cov --locked --lcov --output-path $rdir/llvm-cov.lcov (in $rdir)"+ done+ fi+ else+ echo "[DRY-RUN] Rust: no crates in scope; cargo steps skipped."+ fi+ else+ echo "[DRY-RUN] Rust phase skipped."+ fi+ if [[ $RUN_UNIT -eq 1 ]]; then+ echo "[DRY-RUN] Would execute: $SCRIPT_DIR/gradlew ${UNIT_TASKS[*]}$gradle_args_str"+ for mod in "${MODS[@]}"; do+ echo "[DRY-RUN] Would summarize unit coverage from $mod/build/reports/coverage/test/*/report.xml"+ done+ else+ echo "[DRY-RUN] Unit phase skipped."+ fi+ if [[ $RUN_INST -eq 1 ]]; then+ if [[ ${#INST_MODS[@]} -gt 0 ]]; then+ echo "[DRY-RUN] Would execute: $SCRIPT_DIR/gradlew ${INST_TASKS[*]}$gradle_args_str"+ for mod in "${INST_MODS[@]}"; do+ colon_mod="$(echo "$mod" | tr '/' ':')"+ pkg="$(module_application_id "$colon_mod")"+ [[ -z "$pkg" ]] && pkg="<applicationId from $mod/build.gradle.kts>"+ base="${mod##*/}"+ echo "[DRY-RUN] Would session-install $pkg from $mod/build/outputs/apk/dev/$base-dev.apk (or output-metadata.json outputFile)"+ echo "[DRY-RUN] Would run: adb install -r $mod/build/outputs/apk/androidTest/dev/$base-dev-androidTest.apk"+ if [[ $NO_COV -eq 1 ]]; then+ echo "[DRY-RUN] Would run: adb -s \${ANDROID_SERIAL:-<device>} shell am instrument -w -r $pkg.test/androidx.test.runner.AndroidJUnitRunner"+ else+ echo "[DRY-RUN] Would run: adb -s \${ANDROID_SERIAL:-<device>} shell am instrument -w -r -e coverage true -e coverageFilePath /data/data/$pkg/files/coverage.ec $pkg.test/androidx.test.runner.AndroidJUnitRunner"+ echo "[DRY-RUN] Would pull: adb exec-out run-as $pkg cat files/coverage.ec > $mod/build/outputs/coverage-manual/$pkg.ec"+ fi+ done+ else+ echo "[DRY-RUN] Instrumented phase skipped (nothing in scope)."+ fi+ else+ echo "[DRY-RUN] Instrumented phase skipped."+ fi+ exit 0+fi++RUST_RC=0+UNIT_RC=0+INST_RC=0++# --- rust phase ---+if [[ $RUN_RUST -eq 1 ]]; then+ if [[ ! -x "$CARGO_BIN" ]] && ! command -v "$CARGO_BIN" >/dev/null 2>&1; then+ echo "Error: cargo not found ($CARGO_BIN)." >&2; exit 1+ fi+ if [[ ${#ROOT_CRATES[@]} -eq 0 && ${#STANDALONE_DIRS[@]} -eq 0 ]]; then+ echo "No Rust crates in scope; cargo steps skipped."+ elif [[ $NO_COV -eq 1 ]]; then+ if [[ ${#ROOT_CRATES[@]} -gt 0 ]]; then+ echo ""+ CARGO_ARGS=()+ if [[ $ALL_EXP -eq 1 ]]; then+ CARGO_ARGS+=(--workspace --exclude tilecodec)+ else+ for c in "${ROOT_CRATES[@]}"; do CARGO_ARGS+=(-p "$c"); done+ fi+ echo "Running: cargo test --locked ${CARGO_ARGS[*]}"+ ( cd "$ROOT" && "$CARGO_BIN" test --locked "${CARGO_ARGS[@]}" ) || RUST_RC=$?+ [[ $RUST_RC -ne 0 ]] && echo "Warning: cargo test (workspace) reported failures (exit $RUST_RC)."+ fi+ for rdir in ${STANDALONE_DIRS[@]:-}; do+ echo ""+ echo "Running: cargo test --locked (in $rdir)"+ ( cd "$rdir" && "$CARGO_BIN" test --locked ) || RUST_RC=$?+ [[ $RUST_RC -ne 0 ]] && echo "Warning: cargo test ($rdir) reported failures (exit $RUST_RC)."+ done+ else+ echo ""+ echo "Ensuring rust coverage tools (llvm-tools-preview, cargo-llvm-cov)..."+ COV_TOOLS_OK=1+ if command -v rustup >/dev/null 2>&1; then+ rustup component add llvm-tools-preview >/dev/null 2>&1 || COV_TOOLS_OK=0+ else+ echo "Warning: rustup not found; assuming llvm-tools-preview is already installed."+ fi+ if ! "$CARGO_BIN" llvm-cov --version >/dev/null 2>&1; then+ "$CARGO_BIN" install cargo-llvm-cov --locked >/dev/null 2>&1 || COV_TOOLS_OK=0+ fi+ if [[ $COV_TOOLS_OK -eq 0 ]]; then+ echo "Warning: rust coverage tools unavailable (offline?); falling back to plain cargo test without coverage."+ if [[ ${#ROOT_CRATES[@]} -gt 0 ]]; then+ echo ""+ CARGO_ARGS=()+ if [[ $ALL_EXP -eq 1 ]]; then+ CARGO_ARGS+=(--workspace --exclude tilecodec)+ else+ for c in "${ROOT_CRATES[@]}"; do CARGO_ARGS+=(-p "$c"); done+ fi+ echo "Running: cargo test --locked ${CARGO_ARGS[*]}"+ ( cd "$ROOT" && "$CARGO_BIN" test --locked "${CARGO_ARGS[@]}" ) || RUST_RC=$?+ [[ $RUST_RC -ne 0 ]] && echo "Warning: cargo test (workspace) reported failures (exit $RUST_RC)."+ fi+ for rdir in ${STANDALONE_DIRS[@]:-}; do+ echo ""+ echo "Running: cargo test --locked (in $rdir)"+ ( cd "$rdir" && "$CARGO_BIN" test --locked ) || RUST_RC=$?+ [[ $RUST_RC -ne 0 ]] && echo "Warning: cargo test ($rdir) reported failures (exit $RUST_RC)."+ done+ else+ if [[ ${#ROOT_CRATES[@]} -gt 0 ]]; then+ echo ""+ COV_ARGS=()+ if [[ $ALL_EXP -eq 1 ]]; then+ COV_ARGS+=(--workspace --exclude tilecodec)+ else+ for c in "${ROOT_CRATES[@]}"; do COV_ARGS+=(-p "$c"); done+ fi+ echo "Running: cargo llvm-cov --locked ${COV_ARGS[*]} --lcov --output-path target/llvm-cov.lcov"+ ( cd "$ROOT" && "$CARGO_BIN" llvm-cov --locked "${COV_ARGS[@]}" --lcov --output-path target/llvm-cov.lcov ) || RUST_RC=$?+ [[ $RUST_RC -ne 0 ]] && echo "Warning: cargo llvm-cov (workspace) reported failures (exit $RUST_RC)."+ fi+ for rdir in ${STANDALONE_DIRS[@]:-}; do+ echo ""+ echo "Running: cargo llvm-cov --locked --lcov --output-path $rdir/llvm-cov.lcov (in $rdir)"+ ( cd "$rdir" && "$CARGO_BIN" llvm-cov --locked --lcov --output-path "$rdir/llvm-cov.lcov" ) || RUST_RC=$?+ [[ $RUST_RC -ne 0 ]] && echo "Warning: cargo llvm-cov ($rdir) reported failures (exit $RUST_RC)."+ done+ fi+ fi+fi++# --- unit phase: single gradlew invocation, then coverage summary ---+if [[ $RUN_UNIT -eq 1 ]]; then+ echo ""+ echo "Running: $SCRIPT_DIR/gradlew ${UNIT_TASKS[*]}$gradle_args_str"+ echo ""+ set +u+ "$SCRIPT_DIR/gradlew" "${UNIT_TASKS[@]}" "${GRADLE_ARGS[@]}" || UNIT_RC=$?+ set -u+ echo ""+ [[ $UNIT_RC -ne 0 ]] && echo "Warning: unit test tasks reported failures (exit $UNIT_RC)."+ if [[ $NO_COV -eq 0 ]]; then+ echo ""+ echo "Unit coverage (INSTRUCTION counters):"+ TOTAL_COV=0; TOTAL_MISS=0+ for mod in "${MODS[@]}"; do+ xml=""+ while IFS= read -r f; do+ case "$f" in "" ) continue;; esac+ xml="$f"; break+ done < <(find "$ROOT/$mod/build/reports/coverage/test" -maxdepth 2 -name report.xml 2>/dev/null | sort)+ if [[ -z "$xml" || ! -f "$xml" ]]; then+ echo " $mod: no coverage data (no tests?)"+ continue+ fi+ line="$(grep -oE '<counter type="INSTRUCTION"[^>]*>' "$xml" 2>/dev/null | head -1 || true)"+ missed="$(echo "$line" | sed -nE 's/.*missed="([0-9]+)".*/\1/p')"+ covered="$(echo "$line" | sed -nE 's/.*covered="([0-9]+)".*/\1/p')"+ if [[ -z "$missed" || -z "$covered" ]]; then+ echo " $mod: no coverage data (no tests?)"+ continue+ fi+ echo " $mod: covered=$covered missed=$missed"+ TOTAL_COV=$((TOTAL_COV + covered))+ TOTAL_MISS=$((TOTAL_MISS + missed))+ done+ echo " TOTAL: covered=$TOTAL_COV missed=$TOTAL_MISS"+ fi+fi++# --- instrumented phase: assemble, session-install, run, pull coverage ---+if [[ $RUN_INST -eq 1 && ${#INST_MODS[@]} -gt 0 ]]; then+ echo ""+ echo "Running: $SCRIPT_DIR/gradlew ${INST_TASKS[*]}$gradle_args_str"+ echo ""+ set +u+ "$SCRIPT_DIR/gradlew" "${INST_TASKS[@]}" "${GRADLE_ARGS[@]}" || INST_RC=$?+ set -u+ echo ""+ [[ $INST_RC -ne 0 ]] && echo "Warning: instrumented assemble reported failures (exit $INST_RC); installing whatever APKs exist."+ TOTAL=${#INST_MODS[@]}+ echo ""+ echo "Running instrumented tests on $TARGET_SERIAL ($TOTAL module(s))..."+ idx=0+ while [[ $idx -lt ${#INST_MODS[@]} ]]; do+ mod="${INST_MODS[$idx]}"+ colon_mod="$(echo "$mod" | tr '/' ':')"+ cur=$((idx + 1))+ pkg="$(module_application_id "$colon_mod")"+ if [[ -z "$pkg" ]]; then+ echo "[$cur/$TOTAL] Error: no applicationId found for :${colon_mod}."+ INST_RC=1+ idx=$((idx + 1))+ continue+ fi+ if apk="$(built_app_apk "$colon_mod")"; then+ install_apk_via_session "$apk" "$pkg" "$cur" "$TOTAL" || INST_RC=1+ else+ echo "[$cur/$TOTAL] Error: no app APK found for :${colon_mod} (assemble failed?)."+ INST_RC=1+ idx=$((idx + 1))+ continue+ fi+ if test_apk="$(built_test_apk "$colon_mod")"; then+ echo "[$cur/$TOTAL] Installing test APK for $pkg..."+ "$ADB_BIN" -s "$TARGET_SERIAL" install -r "$test_apk" >/dev/null 2>&1 || {+ echo "[$cur/$TOTAL] Error: test APK install failed for $pkg."+ INST_RC=1+ idx=$((idx + 1))+ continue+ }+ else+ echo "[$cur/$TOTAL] Error: no test APK found for :${colon_mod} (assemble failed?)."+ INST_RC=1+ idx=$((idx + 1))+ continue+ fi+ echo "[$cur/$TOTAL] Running instrumented tests for $pkg..."+ if [[ $NO_COV -eq 1 ]]; then+ "$ADB_BIN" -s "$TARGET_SERIAL" shell am instrument -w -r "$pkg.test/androidx.test.runner.AndroidJUnitRunner" || INST_RC=1+ else+ "$ADB_BIN" -s "$TARGET_SERIAL" shell am instrument -w -r -e coverage true -e coverageFilePath "/data/data/$pkg/files/coverage.ec" "$pkg.test/androidx.test.runner.AndroidJUnitRunner" || INST_RC=1+ ec_dir="$ROOT/$mod/build/outputs/coverage-manual"+ mkdir -p "$ec_dir"+ if "$ADB_BIN" -s "$TARGET_SERIAL" exec-out run-as "$pkg" cat files/coverage.ec > "$ec_dir/$pkg.ec" 2>/dev/null; then+ echo "[$cur/$TOTAL] Coverage pulled: $ec_dir/$pkg.ec"+ else+ echo "[$cur/$TOTAL] Warning: could not pull coverage.ec for $pkg."+ fi+ fi+ idx=$((idx + 1))+ done+fi++if [[ $RUST_RC -ne 0 || $UNIT_RC -ne 0 || $INST_RC -ne 0 ]]; then exit 1; fi+exit 0
test.bat
diff --git a/test.bat b/test.batnew file mode 100644index 0000000000..971381cc2e--- /dev/null+++ b/test.bat@@ -0,0 +1,1083 @@+<# :+@echo off+setlocal+where pwsh >nul 2>nul+if %errorlevel%==0 ( set "PSBIN=pwsh" ) else ( set "PSBIN=powershell" )+%PSBIN% -NoProfile -ExecutionPolicy Bypass -Command "$env:_BATROOT='%~dp0'; $env:_BATPATH='%~f0'; & ([scriptblock]::Create((Get-Content -Raw '%~f0'))) %*"+exit /b %errorlevel%+: end batch #>+# test.bat - Run Rust + unit + instrumented tests without installing apps.+# (PowerShell twin of ./test.)+# test.bat <module> [module...] # all three phases+# test.bat --rust-only <module> [module...] # cargo tests only+# test.bat --unit-only <module> [module...] # gradle unit tests only+# test.bat --instrumented-only [--device S] <module> # on-device tests only+# test.bat all [flags] # every app + library module+# test.bat --dry-run calculator # preview, runs nothing+#+# Module notation mirrors check.bat: slash == colon, games:/personal: shorthand,+# 'all' keyword, deduped. Tasks run with --continue so one broken module does not+# block the rest; exit code is nonzero if anything failed.+#+# RUST (skipped by --unit-only/--instrumented-only): workspace members together+# via -p from the repo root, standalone crates (own [workspace]) individually+# in their own dir. Coverage on (default) uses cargo llvm-cov; when coverage+# tools cannot be installed (for example offline) the step warns cleanly and+# falls back to plain cargo test. --no-coverage runs plain cargo test --locked.+#+# UNIT (skipped by --rust-only/--instrumented-only): app modules run+# :mod:createDevUnitTestCoverageReport, library modules run+# :mod:createDebugUnitTestCoverageReport (single gradlew invocation,+# --continue; app vs lib via common-conventions-app). --no-coverage runs+# :mod:testDevUnitTest / :mod:testDebugUnitTest instead. Afterwards each+# build/reports/coverage/test/*/report.xml is parsed as XML (counter type+# INSTRUCTION) printing per-module covered/missed plus a TOTAL.+#+# INSTRUMENTED (skipped by --rust-only/--unit-only): scope is the in-scope+# modules having any *.kt under src/androidTest. One gradlew invocation runs+# :mod:assembleDev :mod:assembleDevAndroidTest with --continue. Each app APK is+# session-installed (with .idsig sidecar, never plain adb install); each test+# APK uses plain adb install -r. Then am instrument runs the runner, with+# coverage pulled back to build/outputs/coverage-manual when enabled.+$ErrorActionPreference = 'Stop'++$TestRoot = if ($PSScriptRoot) { $PSScriptRoot } else { $env:_BATROOT.TrimEnd('\') }++function Show-TestHelp {+ @'+Usage:+ test.bat [--rust-only|--unit-only|--instrumented-only] [--no-coverage] [--device S] [--dry-run] [--help] <module> [module...]+ test.bat all [flags]+ test.bat calculator+ test.bat --unit-only calculator maps+ test.bat --rust-only games/voxels+ test.bat --instrumented-only --device 9 calculator+ test.bat --dry-run calculator++Module notation mirrors check.bat: slash == colon, games:/personal: shorthand,+'all' keyword, deduped. Tasks run with --continue so one broken module does not+block the rest; exit code is nonzero if anything failed.++Phases (all run unless one scope flag selects a single phase):+ RUST: workspace members together via -p from the repo root, standalone+ crates individually in their own dir. Coverage on (default) runs+ cargo llvm-cov --workspace --locked --exclude tilecodec --lcov+ --output-path target/llvm-cov.lcov (with -p flags for in-scope crates when+ not 'all') plus per standalone dir lcov. Missing coverage tools warn+ cleanly and fall back to plain cargo test. --no-coverage runs plain+ cargo test --locked equivalents.+ UNIT: app modules -> :mod:createDevUnitTestCoverageReport, library modules+ -> :mod:createDebugUnitTestCoverageReport (single gradlew invocation,+ --continue). --no-coverage -> :mod:testDevUnitTest / :mod:testDebugUnitTest.+ Afterwards each build/reports/coverage/test/*/report.xml is parsed as XML+ (counter type INSTRUCTION) printing per-module covered/missed + TOTAL.+ INSTRUMENTED: scope = in-scope modules having any *.kt under src/androidTest.+ One invocation runs :mod:assembleDev :mod:assembleDevAndroidTest with+ --continue, then each app APK is session-installed (with .idsig sidecar,+ never plain adb install), each test APK uses plain adb install -r, then+ am instrument runs <pkg>.test/androidx.test.runner.AndroidJUnitRunner with+ coverage pulled back to build/outputs/coverage-manual.++Device: --device S / --device=S selects a serial, or 8|9 for Pixel 8 / Pixel 9+ (bare 8|9 also accepted); default is the first non-emulator device. No device+ is a hard error for instrumented runs unless --dry-run.++When 'all' expands, Gradle uses the big-build heap (same as install.bat all).+--dry-run prints modules/tasks/commands and runs nothing.+'@+}++function Normalize-TestModule([string]$M) {+ $M = $M.Trim()+ $M = [regex]::Replace($M, '^[/:]+', '')+ $M = [regex]::Replace($M, '[/:]+$', '')+ $M = $M.Replace('/', ':')+ while ($M.Contains('::')) { $M = $M.Replace('::', ':') }+ return $M.ToLowerInvariant()+}++function Get-TestAllModuleDirs {+ $TestSettings = Join-Path $TestRoot 'settings.gradle.kts'+ $TestFound = @()+ if (-not (Test-Path -LiteralPath $TestSettings)) { return $TestFound }+ foreach ($TestLine in [System.IO.File]::ReadLines($TestSettings)) {+ if ($TestLine -match 'include\(":([^"]+)"\)') {+ $TestP = $Matches[1].Replace(':', '/')+ if (-not $TestP) { continue }+ $TestBuild = Join-Path $TestRoot "$TestP/build.gradle.kts"+ if ((Test-Path -LiteralPath $TestBuild) -and+ (Select-String -LiteralPath $TestBuild -Pattern 'common-conventions-(app|library)' -Quiet)) {+ $TestFound += $TestP+ }+ }+ }+ return @($TestFound | Sort-Object -Unique)+}++function Get-TestCargoBin {+ $TestCargoCmd = Get-Command cargo -ErrorAction SilentlyContinue+ if ($TestCargoCmd) { return $TestCargoCmd.Source }+ $TestCargoHome = if ($env:CARGO_HOME) { $env:CARGO_HOME } else { Join-Path $HOME '.cargo' }+ $TestCand = Join-Path $TestCargoHome 'bin/cargo'+ if (Test-Path -LiteralPath $TestCand -PathType Leaf) { return $TestCand }+ $TestCandExe = "$TestCand.exe"+ if (Test-Path -LiteralPath $TestCandExe -PathType Leaf) { return $TestCandExe }+ return ''+}++function Get-TestAdb {+ $TestAdbCmd = Get-Command adb -ErrorAction SilentlyContinue+ if ($TestAdbCmd) { return $TestAdbCmd.Source }+ $TestSdkBases = @()+ if ($env:ANDROID_HOME) { $TestSdkBases += $env:ANDROID_HOME }+ if ($env:ANDROID_SDK_ROOT) { $TestSdkBases += $env:ANDROID_SDK_ROOT }+ $TestSdkBases += (Join-Path $HOME 'Android/Sdk')+ $TestSdkBases += (Join-Path $HOME 'Library/Android/sdk')+ if ($env:LOCALAPPDATA) { $TestSdkBases += (Join-Path $env:LOCALAPPDATA 'Android/Sdk') }+ foreach ($TestBase in $TestSdkBases) {+ if (-not $TestBase) { continue }+ foreach ($TestName in @('platform-tools/adb', 'platform-tools/adb.exe')) {+ $TestCand = Join-Path $TestBase $TestName+ if (Test-Path -LiteralPath $TestCand -PathType Leaf) { return $TestCand }+ }+ }+ return ''+}++function Get-TestApplicationId([string]$Mod) {+ $TestBuild = Join-Path $TestRoot "$($Mod.Replace(':', '/'))/build.gradle.kts"+ if (-not (Test-Path -LiteralPath $TestBuild)) { return '' }+ foreach ($TestLine in [System.IO.File]::ReadLines($TestBuild)) {+ if ($TestLine -match '^\s*applicationId\s*=\s*"([^"]+)"') { return $Matches[1] }+ }+ return ''+}++function Get-TestBuiltApk([string]$Mod, [string]$VariantLc) {+ $TestFs = $Mod.Replace(':', '/')+ $TestOutDir = Join-Path $TestRoot "$TestFs/build/outputs/apk/$VariantLc"+ $TestMeta = Join-Path $TestOutDir 'output-metadata.json'+ $TestBaseName = ($Mod -split ':')[-1]+ $TestFileName = "$TestBaseName-$VariantLc.apk"+ if (Test-Path -LiteralPath $TestMeta -PathType Leaf) {+ try {+ $TestMetaText = [System.IO.File]::ReadAllText($TestMeta)+ $TestM = [regex]::Match($TestMetaText, '"outputFile"\s*:\s*"([^"]+)"')+ if ($TestM.Success -and $TestM.Groups[1].Value) { $TestFileName = $TestM.Groups[1].Value }+ } catch {+ Write-Output "Warning: could not read output-metadata.json for $Mod; using fallback name."+ }+ }+ $TestApk = Join-Path $TestOutDir $TestFileName+ if (Test-Path -LiteralPath $TestApk -PathType Leaf) { return $TestApk }+ return ''+}++function Get-TestAndroidTestApk([string]$Mod) {+ $TestFs = $Mod.Replace(':', '/')+ $TestDir = Join-Path $TestRoot "$TestFs/build/outputs/apk/androidTest/dev"+ if (-not (Test-Path -LiteralPath $TestDir)) { return '' }+ try {+ $TestApks = @(Get-ChildItem -LiteralPath $TestDir -Filter '*.apk' -File -ErrorAction SilentlyContinue | Sort-Object Name)+ } catch {+ return ''+ }+ if ($TestApks.Count -eq 0) { return '' }+ return $TestApks[0].FullName+}++function Test-ApkViaSession([string]$Apk, [string]$PackageId, [string]$AdbBin, [string]$Serial, [string]$Cur = '', [string]$Total = '') {+ $TestApkName = Split-Path -Leaf $Apk+ $TestApkSize = (Get-Item -LiteralPath $Apk).Length+ $TestApkMb = '{0:N1}' -f ($TestApkSize / 1MB)+ $TestDeviceApk = "/data/local/tmp/install_${PackageId}.apk"+ $TestPrefix = ''+ if ($Cur -and $Total) { $TestPrefix = "[$Cur/$Total] " }+ Write-Output "$TestPrefix Installing $PackageId ($TestApkName, ${TestApkMb} MB)..."+ Write-Output " $TestPrefix[1/4] Pushing APK to device..."+ $TestPrevPref = $ErrorActionPreference+ $ErrorActionPreference = 'Continue'+ try {+ & $AdbBin -s $Serial push $Apk $TestDeviceApk >$null 2>&1+ if ($LASTEXITCODE -ne 0) {+ Write-Output " $TestPrefix Error: adb push failed for $TestApkName."+ return $false+ }+ Write-Output " $TestPrefix[2/4] Creating install session..."+ $TestCreateOut = & $AdbBin -s $Serial shell pm install-create -r 2>&1+ $TestSession = ''+ $TestSm = [regex]::Match(($TestCreateOut -join "`n"), 'created install session \[([0-9]+)\]')+ if ($TestSm.Success) { $TestSession = $TestSm.Groups[1].Value }+ if (-not $TestSession) {+ Write-Output " $TestPrefix Error: could not create install session."+ & $AdbBin -s $Serial shell rm -f $TestDeviceApk >$null 2>&1+ return $false+ }+ Write-Output " $TestPrefix[3/4] Staging APK into session $TestSession..."+ & $AdbBin -s $Serial shell pm install-write -S $TestApkSize $TestSession base.apk $TestDeviceApk >$null 2>&1+ if ($LASTEXITCODE -ne 0) {+ Write-Output " $TestPrefix Error: failed to stage $TestApkName into session $TestSession."+ & $AdbBin -s $Serial shell pm install-abandon $TestSession >$null 2>&1+ & $AdbBin -s $Serial shell rm -f $TestDeviceApk >$null 2>&1+ return $false+ }+ $TestIdsig = "$Apk.idsig"+ if (Test-Path -LiteralPath $TestIdsig -PathType Leaf) {+ $TestDeviceIdsig = "$TestDeviceApk.idsig"+ Write-Output " $TestPrefix Staging .idsig sidecar..."+ & $AdbBin -s $Serial push $TestIdsig $TestDeviceIdsig >$null 2>&1+ if ($LASTEXITCODE -eq 0) {+ $TestIdsigSize = (Get-Item -LiteralPath $TestIdsig).Length+ & $AdbBin -s $Serial shell pm install-write -S $TestIdsigSize $TestSession base.apk.idsig $TestDeviceIdsig >$null 2>&1+ if ($LASTEXITCODE -ne 0) {+ Write-Output " $TestPrefix Warning: could not stage .idsig; system-app updates may fail fs-verity."+ }+ }+ else {+ Write-Output " $TestPrefix Warning: could not push .idsig; system-app updates may fail fs-verity."+ }+ & $AdbBin -s $Serial shell rm -f $TestDeviceIdsig >$null 2>&1+ }+ else {+ Write-Output " $TestPrefix Warning: no .idsig sidecar next to the APK; system-app updates may fail fs-verity."+ }+ Write-Output " $TestPrefix[4/4] Committing install session $TestSession..."+ $TestCommitOut = & $AdbBin -s $Serial shell pm install-commit $TestSession 2>&1+ & $AdbBin -s $Serial shell rm -f $TestDeviceApk >$null 2>&1+ if (-not (($TestCommitOut -join "`n") -match '(?im)^Success')) {+ Write-Output " $TestPrefix Error: install failed for ${PackageId}: $($TestCommitOut -join ' ')"+ return $false+ }+ if ($Cur -and $Total) {+ Write-Output " Installed $PackageId. [$Cur/$Total done]"+ }+ else {+ Write-Output " Installed $PackageId."+ }+ return $true+ } catch {+ Write-Output " $TestPrefix Warning: session install hit an error for $PackageId : $($_.Exception.Message)"+ return $false+ } finally {+ $ErrorActionPreference = $TestPrevPref+ }+}++if ($args.Count -eq 0) {+ Show-TestHelp+ Write-Output ''+ Write-Output 'Error: no modules specified.'+ exit 1+}+foreach ($TestA in $args) {+ if ($TestA -eq '--help' -or $TestA -eq '-h' -or $TestA -eq 'help') {+ Show-TestHelp+ exit 0+ }+}++$TestRustOnly = $false+$TestUnitOnly = $false+$TestInstrOnly = $false+$TestNoCoverage = $false+$TestDryRun = ($env:TEST_DRY_RUN -eq '1')+$TestDeviceHint = ''+$TestModulesRaw = @()+$TestIdx = 0+while ($TestIdx -lt $args.Count) {+ $TestArg = [string]$args[$TestIdx]+ $TestLc = $TestArg.ToLowerInvariant()+ if ($TestLc -eq '--rust-only') { $TestRustOnly = $true; $TestIdx++; continue }+ elseif ($TestLc -eq '--unit-only') { $TestUnitOnly = $true; $TestIdx++; continue }+ elseif ($TestLc -eq '--instrumented-only') { $TestInstrOnly = $true; $TestIdx++; continue }+ elseif ($TestLc -eq '--no-coverage') { $TestNoCoverage = $true; $TestIdx++; continue }+ elseif ($TestLc -eq '--dry-run') { $TestDryRun = $true; $TestIdx++; continue }+ elseif ($TestLc -eq '--help' -or $TestLc -eq '-h' -or $TestLc -eq 'help') {+ Show-TestHelp+ exit 0+ }+ elseif ($TestLc -eq '--device') {+ if ($TestIdx + 1 -ge $args.Count) {+ Write-Output 'Error: --device requires a value (serial, 8, or 9).'+ exit 1+ }+ $TestDeviceHint = [string]$args[$TestIdx + 1]+ $TestIdx += 2+ continue+ }+ elseif ($TestLc -like '--device=*') {+ $TestDeviceHint = $TestArg.Substring('--device='.Length)+ if (-not $TestDeviceHint) {+ Write-Output 'Error: --device requires a value (serial, 8, or 9).'+ exit 1+ }+ $TestIdx+++ continue+ }+ elseif ($TestLc -eq '8' -or $TestLc -eq '9') {+ $TestDeviceHint = $TestLc+ $TestIdx+++ continue+ }+ elseif ($TestLc -match '^[0-9]+$') {+ Write-Output "Error: Invalid device '$TestArg'. Use a serial, 8 (Pixel 8), or 9 (Pixel 9)."+ exit 1+ }+ elseif ($TestLc.StartsWith('--')) {+ Write-Output "Error: unknown flag '$TestArg'."+ Show-TestHelp+ exit 1+ }+ else {+ $TestModulesRaw += $TestArg+ $TestIdx+++ }+}++$TestScopeCount = 0+if ($TestRustOnly) { $TestScopeCount++ }+if ($TestUnitOnly) { $TestScopeCount++ }+if ($TestInstrOnly) { $TestScopeCount++ }+if ($TestScopeCount -gt 1) {+ Write-Output 'Error: --rust-only, --unit-only, and --instrumented-only are mutually exclusive.'+ exit 1+}++$TestMods = @()+$TestAllExpanded = $false+foreach ($TestRaw in $TestModulesRaw) {+ $TestNorm = Normalize-TestModule ([string]$TestRaw)+ if (-not $TestNorm) { continue }+ if ($TestNorm -eq 'all') {+ if (-not $TestAllExpanded) {+ foreach ($TestSm in (Get-TestAllModuleDirs)) {+ if ($TestSm -and ($TestMods -notcontains $TestSm)) { $TestMods += $TestSm }+ }+ $TestAllExpanded = $true+ }+ continue+ }+ if (-not $TestNorm.Contains(':')) {+ foreach ($TestPfx in @('games', 'personal')) {+ if (Test-Path -LiteralPath (Join-Path $TestRoot "$TestPfx/$TestNorm/build.gradle.kts")) {+ $TestNorm = "$TestPfx`:$TestNorm"+ break+ }+ }+ }+ $TestFs = $TestNorm.Replace(':', '/')+ if (-not (Test-Path -LiteralPath (Join-Path $TestRoot "$TestFs/build.gradle.kts"))) {+ [Console]::Error.WriteLine("Error: unknown module '$TestRaw' (-> $TestFs/, no build.gradle.kts).")+ exit 1+ }+ if ($TestMods -notcontains $TestFs) { $TestMods += $TestFs }+}+if ($TestMods.Count -eq 0) {+ [Console]::Error.WriteLine('Error: no valid modules.')+ exit 1+}++$RunRust = (-not $TestUnitOnly) -and (-not $TestInstrOnly)+$RunUnit = (-not $TestRustOnly) -and (-not $TestInstrOnly)+$RunInstr = (-not $TestRustOnly) -and (-not $TestUnitOnly)++$TestRootCrates = @()+$TestStandaloneDirs = @()+if ($RunRust) {+ foreach ($TestMod in $TestMods) {+ try {+ $TestRdir = Join-Path $TestRoot "$TestMod/src/main/rust"+ $TestCt = Join-Path $TestRdir 'Cargo.toml'+ if (Test-Path -LiteralPath $TestCt -PathType Leaf) {+ if (Select-String -LiteralPath $TestCt -Pattern '^\[workspace\]\s*$' -Quiet) {+ if ($TestStandaloneDirs -notcontains $TestRdir) { $TestStandaloneDirs += $TestRdir }+ }+ else {+ $TestName = $null+ foreach ($TestLine in [System.IO.File]::ReadLines($TestCt)) {+ if ($TestLine -match '^\s*name\s*=\s*"([^"]+)"') { $TestName = $Matches[1]; break }+ }+ if ($TestName -and ($TestRootCrates -notcontains $TestName)) { $TestRootCrates += $TestName }+ }+ }+ } catch {+ Write-Output "Warning: could not inspect Rust crate for $TestMod : $($_.Exception.Message)"+ }+ }+}++$TestUnitTasks = @()+$TestIsApp = @{}+if ($RunUnit) {+ foreach ($TestMod in $TestMods) {+ $TestGmod = $TestMod.Replace('/', ':')+ $TestBuildFile = Join-Path $TestRoot "$TestMod/build.gradle.kts"+ $TestApp = $false+ try {+ if ((Test-Path -LiteralPath $TestBuildFile) -and (Select-String -LiteralPath $TestBuildFile -Pattern 'common-conventions-app' -Quiet)) {+ $TestApp = $true+ }+ } catch {+ $TestApp = $false+ }+ $TestIsApp[$TestMod] = $TestApp+ if ($TestNoCoverage) {+ if ($TestApp) { $TestUnitTasks += ":${TestGmod}:testDevUnitTest" }+ else { $TestUnitTasks += ":${TestGmod}:testDebugUnitTest" }+ }+ else {+ if ($TestApp) { $TestUnitTasks += ":${TestGmod}:createDevUnitTestCoverageReport" }+ else { $TestUnitTasks += ":${TestGmod}:createDebugUnitTestCoverageReport" }+ }+ }+}++$TestInstrMods = @()+if ($RunInstr) {+ foreach ($TestMod in $TestMods) {+ try {+ $TestAtDir = Join-Path $TestRoot "$TestMod/src/androidTest"+ if (-not (Test-Path -LiteralPath $TestAtDir)) { continue }+ $TestKt = Get-ChildItem -LiteralPath $TestAtDir -Filter '*.kt' -Recurse -File -ErrorAction SilentlyContinue | Select-Object -First 1+ if ($TestKt) { $TestInstrMods += $TestMod }+ } catch {+ Write-Output "Warning: could not inspect androidTest for $TestMod : $($_.Exception.Message)"+ }+ }+}+$TestInstrTasks = @()+foreach ($TestMod in $TestInstrMods) {+ $TestGmod = $TestMod.Replace('/', ':')+ $TestInstrTasks += ":${TestGmod}:assembleDev"+ $TestInstrTasks += ":${TestGmod}:assembleDevAndroidTest"+}++$TestAdbBin = Get-TestAdb+$TestTargetSerial = ''+if ($TestAdbBin) {+ $TestPrevPref = $ErrorActionPreference+ $ErrorActionPreference = 'Continue'+ try {+ $TestDevLines = & $TestAdbBin devices -l 2>$null+ } catch {+ $TestDevLines = @()+ Write-Output 'Warning: adb devices query failed; continuing without a selected device.'+ }+ $ErrorActionPreference = $TestPrevPref+ foreach ($TestDevLine in @($TestDevLines)) {+ $TestParts = ([string]$TestDevLine -split '\s+')+ if ($TestParts.Count -lt 2) { continue }+ $TestDevSerial = $TestParts[0]+ $TestDevState = $TestParts[1]+ if ($TestDevState -ne 'device') { continue }+ if ($TestDevSerial -like 'emulator*') { continue }+ if ($TestDevSerial -eq 'List') { continue }+ if (-not $TestDeviceHint) {+ $TestTargetSerial = $TestDevSerial+ break+ }+ $TestDevModel = ''+ $TestModelM = [regex]::Match([string]$TestDevLine, 'model:([^\s]+)')+ if ($TestModelM.Success) { $TestDevModel = $TestModelM.Groups[1].Value }+ if (($TestDeviceHint -eq '8') -and ($TestDevModel -eq 'Pixel_8')) {+ $TestTargetSerial = $TestDevSerial+ break+ }+ if (($TestDeviceHint -eq '9') -and ($TestDevModel -like 'Pixel_9*')) {+ $TestTargetSerial = $TestDevSerial+ break+ }+ if (($TestDeviceHint -ne '8') -and ($TestDeviceHint -ne '9') -and ($TestDevSerial -eq $TestDeviceHint)) {+ $TestTargetSerial = $TestDevSerial+ break+ }+ }+}++$TestNeedsDevice = ($RunInstr -and ($TestInstrMods.Count -gt 0))+if ($TestNeedsDevice) {+ if (-not $TestAdbBin) {+ if ($TestDryRun) {+ Write-Output '[DRY-RUN] Warning: adb not found; a device could not be selected.'+ }+ else {+ Write-Output 'Error: adb not found; cannot select a target device.'+ Write-Output 'Install Android platform-tools and put adb on PATH (or set ANDROID_HOME).'+ exit 1+ }+ }+ elseif ($TestTargetSerial) {+ $env:ANDROID_SERIAL = $TestTargetSerial+ if ($TestDeviceHint -eq '8' -or $TestDeviceHint -eq '9') {+ Write-Output "Target device: $($env:ANDROID_SERIAL) (Pixel $TestDeviceHint)"+ }+ elseif ($TestDeviceHint) {+ Write-Output "Target device: $($env:ANDROID_SERIAL) (selected via --device)"+ }+ else {+ Write-Output "Target device: $($env:ANDROID_SERIAL) (first connected device not starting with 'emulator')"+ }+ }+ elseif ($TestDeviceHint) {+ Write-Output "Error: No connected device matching '$TestDeviceHint' found (check 'adb devices')."+ exit 1+ }+ elseif ($TestDryRun) {+ Write-Output '[DRY-RUN] Warning: no non-emulator device connected; ANDROID_SERIAL not set.'+ }+ else {+ Write-Output 'Error: No non-emulator device connected.'+ Write-Output "Connect a physical device (check 'adb devices'); refusing to test on an emulator."+ exit 1+ }+}+elseif ($TestTargetSerial) {+ $env:ANDROID_SERIAL = $TestTargetSerial+ Write-Output "Target device: $($env:ANDROID_SERIAL) (first connected device not starting with 'emulator')"+}++$TestGradleBase = @('--continue')+$TestGradleBaseStr = ' --continue'+if ($TestAllExpanded) {+ $TestGradleBase += '-Dorg.gradle.jvmargs=-Xmx46144m -Xms4512m -XX:MaxMetaspaceSize=1024m -XX:+UseG1GC -Dfile.encoding=UTF-8'+ $TestGradleBase += '--max-workers=32'+ $TestGradleBaseStr += ' -Dorg.gradle.jvmargs=<46g-big-build-heap> --max-workers=32'+}++$TestRepoVersion = 0+$TestNeedBump = 0+$TestVersionOverrideArg = ''+if ($TestNeedsDevice -and $TestTargetSerial -and (-not $TestDryRun)) {+ try {+ $TestRepoVersion = [int]([System.IO.File]::ReadLines((Join-Path $TestRoot 'version.txt')) | Select-Object -First 1).Trim()+ } catch {+ Write-Output 'Warning: could not read version.txt; skipping versionCodeOverride computation.'+ $TestRepoVersion = 0+ }+ if ($TestRepoVersion -gt 0) {+ $TestNeedBump = $TestRepoVersion+ $TestPrevPref = $ErrorActionPreference+ $ErrorActionPreference = 'Continue'+ try {+ foreach ($TestMod in $TestInstrMods) {+ try {+ $TestPkg = Get-TestApplicationId $TestMod+ if (-not $TestPkg) { continue }+ $TestListOut = & $TestAdbBin -s $TestTargetSerial shell pm list packages --show-versioncode $TestPkg 2>$null+ $TestDevV = 0+ foreach ($TestListLine in @($TestListOut)) {+ $TestVm = [regex]::Match([string]$TestListLine, 'versionCode:([0-9]+)')+ if ($TestVm.Success) { $TestDevV = [int]$TestVm.Groups[1].Value; break }+ }+ if (($TestDevV -gt 0) -and ($TestDevV -ge $TestNeedBump)) {+ $TestSysOut = & $TestAdbBin -s $TestTargetSerial shell pm list packages -s $TestPkg 2>$null+ $TestIsSystem = $false+ foreach ($TestSysLine in @($TestSysOut)) {+ if ([string]$TestSysLine.Trim() -eq "package:$TestPkg") { $TestIsSystem = $true; break }+ }+ if ($TestIsSystem) { $TestTarget = $TestDevV + 1; $TestKind = 'system app' }+ else { $TestTarget = $TestDevV; $TestKind = 'user app' }+ if ($TestTarget -gt $TestNeedBump) {+ $TestNeedBump = $TestTarget+ Write-Output "Info: $TestPkg is a $TestKind at versionCode $TestDevV on-device (>= repo $TestRepoVersion); will build with -PversionCodeOverride=$TestTarget."+ }+ }+ } catch {+ Write-Output "Warning: versionCode check failed for $TestMod; continuing without override for it."+ }+ }+ } finally {+ $ErrorActionPreference = $TestPrevPref+ }+ if ($TestNeedBump -gt $TestRepoVersion) {+ $TestVersionOverrideArg = "-PversionCodeOverride=$TestNeedBump"+ }+ }+}++$TestUnitArgs = @() + $TestGradleBase+$TestUnitArgsStr = $TestGradleBaseStr+$TestInstrArgs = @() + $TestGradleBase+$TestInstrArgsStr = $TestGradleBaseStr+if ($TestVersionOverrideArg) {+ $TestInstrArgs += $TestVersionOverrideArg+ $TestInstrArgsStr += " $TestVersionOverrideArg"+}++$TestGradlewBat = Join-Path $TestRoot 'gradlew.bat'+$TestGradlewSh = Join-Path $TestRoot 'gradlew'+$TestGradlewDisp = if (Test-Path -LiteralPath $TestGradlewBat) { $TestGradlewBat } else { $TestGradlewSh }++if ($TestDryRun) {+ Write-Output "Modules ($($TestMods.Count)): $($TestMods -join ' ')"+ if ($TestAllExpanded) { Write-Output '[DRY-RUN] all expanded: big-build heap args will be used.' }+ if ($TestDeviceHint) { Write-Output "[DRY-RUN] Device hint: $TestDeviceHint" }+ if ($TestTargetSerial) { Write-Output "[DRY-RUN] Target device: $TestTargetSerial" }+ Write-Output "[DRY-RUN] Coverage: $(if ($TestNoCoverage) { 'off (--no-coverage)' } else { 'on' })"+ Write-Output ''+ if ($RunRust) {+ if (($TestRootCrates.Count -eq 0) -and ($TestStandaloneDirs.Count -eq 0)) {+ Write-Output '[DRY-RUN] Rust: no crates in scope; cargo step skipped.'+ }+ else {+ if ($TestRootCrates.Count -gt 0) {+ $TestPFlags = @()+ foreach ($TestC in $TestRootCrates) { $TestPFlags += @('-p', $TestC) }+ if ($TestNoCoverage) {+ if ($TestAllExpanded) { Write-Output "[DRY-RUN] Would execute: cargo test --locked --workspace (in repo root)" }+ else { Write-Output "[DRY-RUN] Would execute: cargo test --locked $($TestPFlags -join ' ') (in repo root)" }+ }+ else {+ if ($TestAllExpanded) { Write-Output '[DRY-RUN] Would execute: cargo llvm-cov --workspace --locked --exclude tilecodec --lcov --output-path target/llvm-cov.lcov (in repo root)' }+ else { Write-Output "[DRY-RUN] Would execute: cargo llvm-cov --workspace --locked --exclude tilecodec $($TestPFlags -join ' ') --lcov --output-path target/llvm-cov.lcov (in repo root)" }+ }+ }+ foreach ($TestRdir in $TestStandaloneDirs) {+ if ($TestNoCoverage) { Write-Output "[DRY-RUN] Would execute: cargo test --locked (in $TestRdir)" }+ else { Write-Output "[DRY-RUN] Would execute: cargo llvm-cov --locked --lcov --output-path target/llvm-cov.lcov (in $TestRdir)" }+ }+ }+ Write-Output ''+ }+ if ($RunUnit) {+ Write-Output "[DRY-RUN] Unit tasks: $($TestUnitTasks -join ' ')"+ Write-Output "[DRY-RUN] Would execute: $TestGradlewDisp $($TestUnitTasks -join ' ')$TestUnitArgsStr"+ Write-Output '[DRY-RUN] Would parse: <module>/build/reports/coverage/test/*/report.xml (INSTRUCTION counters)'+ Write-Output ''+ }+ if ($RunInstr) {+ if ($TestInstrMods.Count -eq 0) {+ Write-Output '[DRY-RUN] Instrumented: no modules with src/androidTest *.kt in scope; step skipped.'+ }+ else {+ Write-Output "[DRY-RUN] Instrumented modules ($($TestInstrMods.Count)): $($TestInstrMods -join ' ')"+ Write-Output "[DRY-RUN] Would execute: $TestGradlewDisp $($TestInstrTasks -join ' ')$TestInstrArgsStr"+ foreach ($TestMod in $TestInstrMods) {+ $TestPkg = Get-TestApplicationId $TestMod+ $TestFs = $TestMod.Replace(':', '/')+ $TestAppApk = Get-TestBuiltApk $TestMod 'dev'+ $TestTApk = Get-TestAndroidTestApk $TestMod+ if ($TestAppApk) { Write-Output "[DRY-RUN] Would session-install $TestPkg from $TestAppApk (with .idsig sidecar)" }+ else { Write-Output "[DRY-RUN] Would session-install $TestPkg (APK expected after assembleDev in $TestFs/build/outputs/apk/dev)" }+ if ($TestTApk) { Write-Output "[DRY-RUN] Would run: adb install -r $TestTApk" }+ else { Write-Output "[DRY-RUN] Would run: adb install -r $TestFs/build/outputs/apk/androidTest/dev/<test-apk> (expected after assembleDevAndroidTest)" }+ if ($TestPkg) {+ if ($TestNoCoverage) { Write-Output "[DRY-RUN] Would run: adb -s <serial> shell am instrument -w -r $TestPkg.test/androidx.test.runner.AndroidJUnitRunner" }+ else {+ Write-Output "[DRY-RUN] Would run: adb -s <serial> shell am instrument -w -r -e coverage true -e coverageFilePath /data/data/$TestPkg/files/coverage.ec $TestPkg.test/androidx.test.runner.AndroidJUnitRunner"+ Write-Output "[DRY-RUN] Would pull: adb -s <serial> exec-out run-as $TestPkg cat files/coverage.ec -> $TestFs/build/outputs/coverage-manual/$TestPkg.ec"+ }+ }+ }+ }+ Write-Output ''+ }+ exit 0+}++Write-Output "Modules ($($TestMods.Count)): $($TestMods -join ' ')"+if ($RunUnit -and ($TestUnitTasks.Count -gt 0)) { Write-Output "Unit tasks: $($TestUnitTasks -join ' ')" }+if ($RunInstr -and ($TestInstrTasks.Count -gt 0)) { Write-Output "Instrumented tasks: $($TestInstrTasks -join ' ')" }+Write-Output ''++$TestFailures = 0++if ($RunRust) {+ if (($TestRootCrates.Count -eq 0) -and ($TestStandaloneDirs.Count -eq 0)) {+ Write-Output 'No Rust crates in scope; cargo step skipped.'+ }+ else {+ foreach ($TestRc in $TestRootCrates) { Write-Output "Rust: workspace crate $TestRc" }+ foreach ($TestRdir in $TestStandaloneDirs) { Write-Output "Rust: standalone crate ($TestRdir)" }+ $TestCargoBin = Get-TestCargoBin+ if (-not $TestCargoBin) {+ Write-Output 'Warning: cargo not found (install Rust or set CARGO_HOME); Rust step skipped.'+ $TestFailures+++ }+ else {+ $TestCovOk = (-not $TestNoCoverage)+ if ($TestCovOk) {+ try {+ $TestPrevPref = $ErrorActionPreference+ $ErrorActionPreference = 'Continue'+ try {+ & rustup component add llvm-tools-preview 2>&1 | Out-Null+ $TestRustupRc = $LASTEXITCODE+ } catch {+ $TestRustupRc = 1+ }+ if ($TestRustupRc -ne 0) { throw "rustup component add failed (exit $TestRustupRc)" }+ try {+ & $TestCargoBin install cargo-llvm-cov --locked 2>&1 | Out-Null+ $TestCovInstallRc = $LASTEXITCODE+ } catch {+ $TestCovInstallRc = 1+ }+ if ($TestCovInstallRc -ne 0) { throw "cargo install cargo-llvm-cov failed (exit $TestCovInstallRc)" }+ $ErrorActionPreference = $TestPrevPref+ } catch {+ Write-Output "Warning: coverage tools unavailable ($($_.Exception.Message)); running plain cargo test instead."+ $TestCovOk = $false+ $ErrorActionPreference = $TestPrevPref+ }+ }+ if ($TestCovOk) {+ if ($TestRootCrates.Count -gt 0) {+ Write-Output ''+ $TestPFlags = @()+ foreach ($TestC in $TestRootCrates) { $TestPFlags += @('-p', $TestC) }+ try {+ $TestPrevPref = $ErrorActionPreference+ $ErrorActionPreference = 'Continue'+ Push-Location -LiteralPath $TestRoot+ try {+ if ($TestAllExpanded) {+ Write-Output 'Running: cargo llvm-cov --workspace --locked --exclude tilecodec --lcov --output-path target/llvm-cov.lcov'+ & $TestCargoBin llvm-cov --workspace --locked --exclude tilecodec --lcov --output-path target/llvm-cov.lcov+ }+ else {+ Write-Output "Running: cargo llvm-cov --workspace --locked --exclude tilecodec $($TestPFlags -join ' ') --lcov --output-path target/llvm-cov.lcov"+ & $TestCargoBin llvm-cov --workspace --locked --exclude tilecodec @TestPFlags --lcov --output-path target/llvm-cov.lcov+ }+ $TestRc2 = $LASTEXITCODE+ } finally {+ Pop-Location+ $ErrorActionPreference = $TestPrevPref+ }+ if ($TestRc2 -ne 0) {+ Write-Output "Warning: cargo llvm-cov (workspace) reported failures (exit $TestRc2)."+ $TestFailures+++ }+ } catch {+ Write-Output "Warning: cargo llvm-cov (workspace) hit an error : $($_.Exception.Message)"+ $TestFailures+++ }+ }+ foreach ($TestRdir in $TestStandaloneDirs) {+ Write-Output ''+ Write-Output "Running: cargo llvm-cov --locked --lcov --output-path target/llvm-cov.lcov (in $TestRdir)"+ try {+ $TestPrevPref = $ErrorActionPreference+ $ErrorActionPreference = 'Continue'+ Push-Location -LiteralPath $TestRdir+ try {+ & $TestCargoBin llvm-cov --locked --lcov --output-path target/llvm-cov.lcov+ $TestRc2 = $LASTEXITCODE+ } finally {+ Pop-Location+ $ErrorActionPreference = $TestPrevPref+ }+ if ($TestRc2 -ne 0) {+ Write-Output "Warning: cargo llvm-cov ($TestRdir) reported failures (exit $TestRc2)."+ $TestFailures+++ }+ } catch {+ Write-Output "Warning: cargo llvm-cov ($TestRdir) hit an error : $($_.Exception.Message)"+ $TestFailures+++ }+ }+ }+ else {+ if ($TestRootCrates.Count -gt 0) {+ Write-Output ''+ $TestPFlags = @()+ foreach ($TestC in $TestRootCrates) { $TestPFlags += @('-p', $TestC) }+ try {+ $TestPrevPref = $ErrorActionPreference+ $ErrorActionPreference = 'Continue'+ Push-Location -LiteralPath $TestRoot+ try {+ if ($TestAllExpanded) {+ Write-Output 'Running: cargo test --locked --workspace'+ & $TestCargoBin test --locked --workspace+ }+ else {+ Write-Output "Running: cargo test --locked $($TestPFlags -join ' ')"+ & $TestCargoBin test --locked @TestPFlags+ }+ $TestRc2 = $LASTEXITCODE+ } finally {+ Pop-Location+ $ErrorActionPreference = $TestPrevPref+ }+ if ($TestRc2 -ne 0) {+ Write-Output "Warning: cargo test (workspace) reported failures (exit $TestRc2)."+ $TestFailures+++ }+ } catch {+ Write-Output "Warning: cargo test (workspace) hit an error : $($_.Exception.Message)"+ $TestFailures+++ }+ }+ foreach ($TestRdir in $TestStandaloneDirs) {+ Write-Output ''+ Write-Output "Running: cargo test --locked (in $TestRdir)"+ try {+ $TestPrevPref = $ErrorActionPreference+ $ErrorActionPreference = 'Continue'+ Push-Location -LiteralPath $TestRdir+ try {+ & $TestCargoBin test --locked+ $TestRc2 = $LASTEXITCODE+ } finally {+ Pop-Location+ $ErrorActionPreference = $TestPrevPref+ }+ if ($TestRc2 -ne 0) {+ Write-Output "Warning: cargo test ($TestRdir) reported failures (exit $TestRc2)."+ $TestFailures+++ }+ } catch {+ Write-Output "Warning: cargo test ($TestRdir) hit an error : $($_.Exception.Message)"+ $TestFailures+++ }+ }+ }+ }+ }+ Write-Output ''+}++if ($RunUnit) {+ Write-Output "Running unit tests: $($TestUnitTasks -join ' ')"+ $TestBashCmd = Get-Command bash -ErrorAction SilentlyContinue+ $TestUnitExit = 0+ try {+ $TestPrevPref = $ErrorActionPreference+ $ErrorActionPreference = 'Continue'+ try {+ if (Test-Path -LiteralPath $TestGradlewBat) {+ Write-Output "Running: $TestGradlewBat $($TestUnitTasks -join ' ')$TestUnitArgsStr"+ Write-Output ''+ & $TestGradlewBat @TestUnitTasks @TestUnitArgs+ $TestUnitExit = $LASTEXITCODE+ }+ elseif ($TestBashCmd -and (Test-Path -LiteralPath $TestGradlewSh)) {+ Write-Output "Running: $TestGradlewSh $($TestUnitTasks -join ' ')$TestUnitArgsStr"+ Write-Output ''+ & $TestBashCmd.Source $TestGradlewSh @TestUnitTasks @TestUnitArgs+ $TestUnitExit = $LASTEXITCODE+ }+ else {+ Write-Output 'Error: no Gradle wrapper found (gradlew.bat / gradlew).'+ $TestUnitExit = 1+ }+ } finally {+ $ErrorActionPreference = $TestPrevPref+ }+ } catch {+ Write-Output "Warning: unit-test invocation hit an error : $($_.Exception.Message)"+ $TestUnitExit = 1+ }+ Write-Output ''+ if ($TestUnitExit -ne 0) {+ Write-Output "Warning: unit tests reported failures (exit $TestUnitExit)."+ $TestFailures+++ }+ if (-not $TestNoCoverage) {+ $TestTotalCovered = 0+ $TestTotalMissed = 0+ foreach ($TestMod in $TestMods) {+ try {+ $TestCovBase = Join-Path $TestRoot "$TestMod/build/reports/coverage/test"+ if (-not (Test-Path -LiteralPath $TestCovBase)) {+ Write-Output "Warning: $TestMod no coverage data (no tests?)"+ continue+ }+ $TestReports = @(Get-ChildItem -Path $TestCovBase -Filter 'report.xml' -Recurse -File -ErrorAction SilentlyContinue)+ if ($TestReports.Count -eq 0) {+ Write-Output "Warning: $TestMod no coverage data (no tests?)"+ continue+ }+ $TestModCovered = 0+ $TestModMissed = 0+ foreach ($TestRep in $TestReports) {+ try {+ [xml]$TestXml = Get-Content -LiteralPath $TestRep.FullName+ $TestCounters = @($TestXml.report.counter | Where-Object { $_.type -eq 'INSTRUCTION' })+ if ($TestCounters.Count -gt 0) {+ $TestModCovered += [int]$TestCounters[0].covered+ $TestModMissed += [int]$TestCounters[0].missed+ }+ else {+ $TestNode = $TestXml.SelectSingleNode("//counter[@type='INSTRUCTION']")+ if ($TestNode) {+ $TestModCovered += [int]$TestNode.covered+ $TestModMissed += [int]$TestNode.missed+ }+ }+ } catch {+ Write-Output "Warning: could not parse $($TestRep.FullName); skipping it."+ }+ }+ Write-Output "Coverage $TestMod : covered $TestModCovered missed $TestModMissed"+ $TestTotalCovered += $TestModCovered+ $TestTotalMissed += $TestModMissed+ } catch {+ Write-Output "Warning: coverage parse failed for $TestMod; continuing."+ }+ }+ Write-Output "Coverage TOTAL : covered $TestTotalCovered missed $TestTotalMissed"+ }+ Write-Output ''+}++if ($RunInstr) {+ if ($TestInstrMods.Count -eq 0) {+ Write-Output 'No instrumented tests in scope (no src/androidTest *.kt); instrumented step skipped.'+ }+ else {+ Write-Output "Running instrumented assemble: $($TestInstrTasks -join ' ')"+ $TestBashCmd2 = Get-Command bash -ErrorAction SilentlyContinue+ $TestInstrBuildExit = 0+ try {+ $TestPrevPref = $ErrorActionPreference+ $ErrorActionPreference = 'Continue'+ try {+ if (Test-Path -LiteralPath $TestGradlewBat) {+ Write-Output "Running: $TestGradlewBat $($TestInstrTasks -join ' ')$TestInstrArgsStr"+ Write-Output ''+ & $TestGradlewBat @TestInstrTasks @TestInstrArgs+ $TestInstrBuildExit = $LASTEXITCODE+ }+ elseif ($TestBashCmd2 -and (Test-Path -LiteralPath $TestGradlewSh)) {+ Write-Output "Running: $TestGradlewSh $($TestInstrTasks -join ' ')$TestInstrArgsStr"+ Write-Output ''+ & $TestBashCmd2.Source $TestGradlewSh @TestInstrTasks @TestInstrArgs+ $TestInstrBuildExit = $LASTEXITCODE+ }+ else {+ Write-Output 'Error: no Gradle wrapper found (gradlew.bat / gradlew).'+ $TestInstrBuildExit = 1+ }+ } finally {+ $ErrorActionPreference = $TestPrevPref+ }+ } catch {+ Write-Output "Warning: instrumented assemble hit an error : $($_.Exception.Message)"+ $TestInstrBuildExit = 1+ }+ Write-Output ''+ if ($TestInstrBuildExit -ne 0) {+ Write-Output 'Warning: assemble reported failures; running instrumented tests for whatever APKs exist.'+ $TestFailures+++ }+ $TestTotal = $TestInstrMods.Count+ Write-Output ''+ Write-Output "Running instrumented tests for $TestTotal module(s) on $TestTargetSerial..."+ $TestCur = 0+ foreach ($TestMod in $TestInstrMods) {+ $TestCur+++ try {+ $TestPkg = Get-TestApplicationId $TestMod+ if (-not $TestPkg) {+ Write-Output "[$TestCur/$TestTotal] Error: no applicationId found for $TestMod."+ $TestFailures+++ continue+ }+ $TestAppApk = Get-TestBuiltApk $TestMod 'dev'+ if (-not $TestAppApk) {+ Write-Output "[$TestCur/$TestTotal] Error: no app APK found for $TestMod (assemble failed?)."+ $TestFailures+++ continue+ }+ $TestTApk = Get-TestAndroidTestApk $TestMod+ if (-not $TestTApk) {+ Write-Output "[$TestCur/$TestTotal] Error: no test APK found for $TestMod (assembleDevAndroidTest failed?)."+ $TestFailures+++ continue+ }+ if (-not (Test-ApkViaSession $TestAppApk $TestPkg $TestAdbBin $TestTargetSerial "$TestCur" "$TestTotal")) {+ $TestFailures+++ continue+ }+ Write-Output "[$TestCur/$TestTotal] Installing test APK for $TestPkg..."+ $TestPrevPref = $ErrorActionPreference+ $ErrorActionPreference = 'Continue'+ try {+ & $TestAdbBin -s $TestTargetSerial install -r $TestTApk 2>&1 | Out-Null+ $TestTestInstallRc = $LASTEXITCODE+ } catch {+ $TestTestInstallRc = 1+ } finally {+ $ErrorActionPreference = $TestPrevPref+ }+ if ($TestTestInstallRc -ne 0) {+ Write-Output "[$TestCur/$TestTotal] Error: test APK install failed for $TestPkg."+ $TestFailures+++ continue+ }+ $TestRunner = "$TestPkg.test/androidx.test.runner.AndroidJUnitRunner"+ $TestPrevPref = $ErrorActionPreference+ $ErrorActionPreference = 'Continue'+ try {+ if ($TestNoCoverage) {+ Write-Output "[$TestCur/$TestTotal] Running: am instrument -w -r $TestRunner"+ $TestInstrOut = & $TestAdbBin -s $TestTargetSerial shell am instrument -w -r $TestRunner 2>&1+ }+ else {+ $TestCovDevicePath = "/data/data/$TestPkg/files/coverage.ec"+ Write-Output "[$TestCur/$TestTotal] Running: am instrument -w -r -e coverage true $TestRunner"+ $TestInstrOut = & $TestAdbBin -s $TestTargetSerial shell am instrument -w -r -e coverage true -e coverageFilePath $TestCovDevicePath $TestRunner 2>&1+ }+ $TestInstrRc = $LASTEXITCODE+ $TestInstrText = ($TestInstrOut -join "`n")+ } catch {+ $TestInstrOut = @("$($_.Exception.Message)")+ $TestInstrText = ($TestInstrOut -join "`n")+ $TestInstrRc = 1+ } finally {+ $ErrorActionPreference = $TestPrevPref+ }+ $TestInstrFailed = $false+ if ($TestInstrRc -ne 0) { $TestInstrFailed = $true }+ if ($TestInstrText -match '(?im)^(FAILURES|INSTRUMENTATION_FAILED|INSTRUMENTATION_CODE:\s*0)') { $TestInstrFailed = $true }+ if ($TestInstrText -match '(?im)FAILURES!!!') { $TestInstrFailed = $true }+ Write-Output $TestInstrText+ if ($TestInstrFailed) {+ Write-Output "[$TestCur/$TestTotal] Error: instrumented tests failed for $TestPkg."+ $TestFailures+++ continue+ }+ if (-not $TestNoCoverage) {+ try {+ $TestFsPath = $TestMod.Replace(':', '/')+ $TestCovOutDir = Join-Path $TestRoot "$TestFsPath/build/outputs/coverage-manual"+ try { New-Item -ItemType Directory -Force -Path $TestCovOutDir >$null 2>&1 } catch { }+ $TestCovOutFile = Join-Path $TestCovOutDir "$TestPkg.ec"+ $TestPrevPref = $ErrorActionPreference+ $ErrorActionPreference = 'Continue'+ try {+ & $TestAdbBin -s $TestTargetSerial exec-out run-as $TestPkg cat files/coverage.ec > $TestCovOutFile 2>$null+ $TestPullRc = $LASTEXITCODE+ } catch {+ $TestPullRc = 1+ } finally {+ $ErrorActionPreference = $TestPrevPref+ }+ if (($TestPullRc -eq 0) -and (Test-Path -LiteralPath $TestCovOutFile -PathType Leaf)) {+ Write-Output "Coverage pulled: $TestCovOutFile"+ }+ else {+ Write-Output "Warning: could not pull coverage.ec for $TestPkg."+ }+ } catch {+ Write-Output "Warning: coverage pull failed for $TestPkg; continuing."+ }+ }+ Write-Output "[$TestCur/$TestTotal] Instrumented tests passed for $TestPkg."+ } catch {+ Write-Output "[$TestCur/$TestTotal] Warning: instrumented run hit an error for $TestMod : $($_.Exception.Message)"+ $TestFailures+++ }+ }+ }+ Write-Output ''+}++if ($TestFailures -gt 0) {+ Write-Output "Test complete: failures in $TestFailures step(s)."+ exit 1+}+Write-Output 'Test complete: all executed steps succeeded.'+exit 0