scripting-adb-for-ci
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseScripting adb For CI — Bash Idioms, Exit Codes, Fan-out
为 CI 编写 adb 脚本——Bash 惯用法、退出码与扇出
This skill is the connective tissue that turns the other ADB skills into a CI pipeline: exit-code propagation, retries, timeouts, parallel device fan-out, port forwarding, idempotent setup, capture-on-failure, and Test Orchestrator wiring. Each section cross-links to the skill that owns the underlying primitive.
此 skill 是将其他 ADB skills 接入 CI pipeline 的纽带:涵盖退出码传递、重试、超时、并行设备扇出、端口转发、幂等设置、失败时捕获,以及 Test Orchestrator 接入。每个章节都会交叉链接到负责底层原语的 skill。
When to use this skill
何时使用此 skill
- A CI job invokes and "passes" even when tests fail — it gates on
adb shell am instrument, but$?always exitsam instrument; the real status lives in0lines on stdout (andINSTRUMENTATION_STATUS_CODEis needed just to get that stdout at all).-w - The team has multiple physical devices on a single agent and wants to run sharded tests in parallel.
- and
adb forwardare confused — most teams have at least one bug from the opposite argument order.adb reverse - Transient /
error: device not foundfailures are not retried; the job fails on the first hiccup.error: closed - A script lacks cleanup so leaked port forwards or modified survive into the next run.
settings put global ... - The team wires Test Orchestrator with — the build silently fails to install the orchestrator APK.
androidTestImplementation
- CI job 调用 ,即使测试失败也会显示“通过”——它根据
adb shell am instrument设置门禁,但$?始终退出am instrument;真实状态位于 stdout 的0行中(而且必须使用INSTRUMENTATION_STATUS_CODE才能获得该 stdout)。-w - 团队在单个 agent 上连接了多台物理设备,希望并行运行分片测试。
- 团队混淆了 和
adb forward——多数团队至少存在一个因参数顺序相反而导致的 bug。adb reverse - 瞬时 /
error: device not found失败没有重试机制,job 会在首次小故障后直接失败。error: closed - 脚本缺少清理逻辑,导致残留的端口转发或被修改的 延续到下一次运行。
settings put global ... - 团队使用 接入 Test Orchestrator,导致构建无法静默安装 orchestrator APK。
androidTestImplementation
When NOT to use this skill
何时不使用此 skill
- The single primitive (logcat, screencap, pull, push, settings, input, am instrument) is not yet understood. Read the relevant sibling skill first.
- The CI itself (Gradle plugin, Firebase Test Lab cloud config). Use FTL's own docs for that layer.
- Compose / instrumentation test mechanics. Use and friends.
../../../compose/synchronization/synchronizing-with-idle/SKILL.md
- 尚未理解单个原语(logcat、screencap、pull、push、settings、input、am instrument)。请先阅读对应的同系列 skill。
- CI 本身(Gradle plugin、Firebase Test Lab 云配置)。这一层请使用 FTL 自身的文档。
- Compose / instrumentation test 机制。请使用 等相关文档。
../../../compose/synchronization/synchronizing-with-idle/SKILL.md
Prerequisites
前置条件
- Bash (zsh works for most of this; macOS users should for
brew install coreutilsif relying ongtimeout).timeout - Platform Tools 24+ on the host. On older toolchains exit codes are unreliable.
adb shell - Devices on API 24+ for reliable shell exit-code propagation. Pre-Nougat use a sentinel in stdout and grep on the host.
__ADB_RC=$?
- Bash(大多数场景也支持 zsh;macOS 用户如果依赖 ,应通过
timeout安装brew install coreutils)。gtimeout - 主机上的 Platform Tools 24+。在较旧的工具链中,的退出码不可靠。
adb shell - 设备为 API 24+,才能可靠地传递 shell 退出码。对于 Nougat 之前的版本,应在 stdout 中使用哨兵值 ,并在主机端执行 grep。
__ADB_RC=$?
Exit codes — what adb propagates
退出码——adb 会传递哪些退出码
| Operation | Behavior |
|---|---|
| |
| |
| Block until the state is reached, then exit |
| On platform-tools ≥ 24 and device adbd ≥ Android 7.0 (Nougat / API 24), the device-side command's exit code is propagated. Older devices always returned |
| Transport ID, NOT a timeout. Most common scripting confusion. |
| Always exits |
adb shell-xshell [-e ESCAPE] [-n] [-Tt] [-x] [COMMAND...]
-x: disable remote exit codes and stdout/stderr separationYou almost never want in CI. The default is what you want.
-x| 操作 | 行为 |
|---|---|
| 成功时为 |
| 成功时为 |
| 阻塞直到达到指定状态,然后退出 |
| 当 platform-tools ≥ 24 且设备端 adbd ≥ Android 7.0(Nougat / API 24)时,会传递设备端命令的退出码。较旧的设备无论结果如何始终返回 |
| 表示 Transport ID,而不是超时。这是脚本中最常见的混淆。 |
| 无论通过还是失败都始终退出 |
使用 可以禁用 的退出码传递:
-xadb shellshell [-e ESCAPE] [-n] [-Tt] [-x] [COMMAND...]
-x: disable remote exit codes and stdout/stderr separation在 CI 中几乎从不应使用 ;默认行为正是所需行为。
-xAndroidJUnitRunner status codes
AndroidJUnitRunner 状态码
am instrument -w -rINSTRUMENTATION_STATUS_CODE: <int>INSTRUMENTATION_CODE: <int>| Code | Symbolic name | Meaning |
|---|---|---|
| | Test started |
| | Test passed |
| | Unexpected error (process death, runner failure) |
| | Assertion failed |
| | |
| | JUnit |
Don't treat or as failures — they are skips; only and are failures. The trailing line is unrelated: it's an value ( = = no runner-level crash; = = runner died) and, like the shell (always ), it does not reflect test pass/fail. Grep stdout for per-test / (see the WRONG/RIGHT pattern below).
-3-4-1-2INSTRUMENTATION_CODEActivity.RESULT_*-1RESULT_OK0RESULT_CANCELED$?0INSTRUMENTATION_STATUS_CODE: -1-2am instrument -w -rINSTRUMENTATION_STATUS_CODE: <int>INSTRUMENTATION_CODE: <int>| 状态码 | 符号名称 | 含义 |
|---|---|---|
| | 测试已开始 |
| | 测试通过 |
| | 意外错误(进程死亡、runner 失败) |
| | 断言失败 |
| | 被 |
| | JUnit |
不要将 或 视为失败——它们表示跳过;只有 和 才是失败。末尾的 行与测试结果无关:它是一个 值( = = runner 级别没有崩溃; = = runner 已死亡),而且与 shell 的 (始终为 )一样,不会反映测试通过或失败。请在 stdout 中 grep 每个测试对应的 / (参见下方的错误/正确模式)。
-3-4-1-2INSTRUMENTATION_CODEActivity.RESULT_*-1RESULT_OK0RESULT_CANCELED$?0INSTRUMENTATION_STATUS_CODE: -1-2Port forwarding — adb forward
vs adb reverse
adb forwardadb reverse端口转发——adb forward
与 adb reverse
adb forwardadb reverseThe argument order is opposite. This is the most common scripting bug.
adb forward [--no-rebind] LOCAL REMOTE # host → device. LOCAL REMOTE
adb reverse [--no-rebind] REMOTE LOCAL # device → host. REMOTE LOCAL| Direction | Use case | Recipe |
|---|---|---|
| Host needs to drive a device-side service. | |
| Device needs to reach a local-only host service (CI runner, dev laptop). | |
Token grammar (from ):
adb help| Token | Where |
|---|---|
| Either side. |
| Linux abstract Unix domain socket. Used by Chrome DevTools / Stetho / Flipper. |
| Reserved Unix socket namespace. |
| Filesystem-backed Unix socket. |
| REMOTE only. Java Debug Wire Protocol for the given device-side pid. |
| REMOTE only. virtio-vsock (emulator). |
| Character device passthrough. |
| LOCAL only — listen on a pre-opened fd. |
Cleanup is the same surface: , , . Always remove what was added in a so re-runs on the same agent don't fail with "cannot bind: address already in use".
--list--remove--remove-alltrap两者的参数顺序相反。 这是脚本中最常见的 bug。
adb forward [--no-rebind] LOCAL REMOTE # host → device. LOCAL REMOTE
adb reverse [--no-rebind] REMOTE LOCAL # device → host. REMOTE LOCAL| 方向 | 使用场景 | 示例 |
|---|---|---|
| 主机需要访问设备端服务。 | |
| 设备需要访问仅限本机的主机服务(CI runner、开发笔记本)。 | |
Token 语法(来自 ):
adb help| Token | 所在位置 |
|---|---|
| 任一端均可。LOCAL 上的 |
| Linux 抽象 Unix domain socket。用于 Chrome DevTools / Stetho / Flipper。 |
| 保留的 Unix socket 命名空间。 |
| 基于文件系统的 Unix socket。 |
| 仅限 REMOTE。指定设备端 pid 的 Java Debug Wire Protocol。 |
| 仅限 REMOTE。virtio-vsock(模拟器)。 |
| 字符设备透传。 |
| 仅限 LOCAL——监听预先打开的 fd。 |
清理时使用同一组接口:、、。应始终在 中移除本次添加的内容,避免在同一 agent 上重新运行时因“cannot bind: address already in use”而失败。
--list--remove--remove-alltrapTimeouts — wrap with timeout
, not adb -t
timeoutadb -t超时——使用 timeout
包装器,而不是 adb -t
timeoutadb -tadb -t <transport-id>timeoutbash
timeout 60s adb -s emulator-5554 shell am instrument -w -r ...
echo $?adb -t <transport-id>timeoutbash
timeout 60s adb -s emulator-5554 shell am instrument -w -r ...
echo $?124 = timeout reached (process killed); 137 = had to escalate to SIGKILL.
124 = timeout reached (process killed); 137 = had to escalate to SIGKILL.
0 just means am instrument exited (it always does) — see the timeout pattern below for pass/fail parsing.
0 just means am instrument exited (it always does) — see the timeout pattern below for pass/fail parsing.
On macOS `timeout` is `gtimeout` from `coreutils` (`brew install coreutils`).
For background captures, set a max duration so a stuck job doesn't fill the disk:
```bash
( timeout 600s adb logcat -v threadtime > artifacts/logcat.txt ) &
LOGCAT_PID=$!
trap 'kill $LOGCAT_PID 2>/dev/null' EXIT
在 macOS 上,`timeout` 是 `coreutils` 提供的 `gtimeout`(`brew install coreutils`)。
对于后台捕获任务,应设置最大持续时间,避免卡住的 job 占满磁盘:
```bash
( timeout 600s adb logcat -v threadtime > artifacts/logcat.txt ) &
LOGCAT_PID=$!
trap 'kill $LOGCAT_PID 2>/dev/null' EXITRetries on transient errors
瞬时错误重试
The usual offenders: , , , . A + reconnect resolves most.
error: device 'XYZ' not founderror: closederror: protocol faulterror: device offlinekill-serverbash
retry() {
local n=0 max=3 delay=2
until "$@"; do
n=$((n+1))
[ "$n" -ge "$max" ] && return 1
echo "[retry] $* failed (attempt $n); restarting adb"
adb kill-server; adb start-server
sleep "$delay"
done
}
retry adb install -r app.apk
retry adb shell am instrument -w -r ...For retries specifically, also the test pkg first — otherwise transient state leaks across attempts. Note only re-runs on transport errors (the host binary exits non-zero); a genuine test failure leaves exiting , so it won't be retried — detect those by parsing the output, not by exit code.
am instrumentpm clearretryadbam instrument0常见诱因:、、、。执行 并重新连接通常可以解决大部分问题。
error: device 'XYZ' not founderror: closederror: protocol faulterror: device offlinekill-serverbash
retry() {
local n=0 max=3 delay=2
until "$@"; do
n=$((n+1))
[ "$n" -ge "$max" ] && return 1
echo "[retry] $* failed (attempt $n); restarting adb"
adb kill-server; adb start-server
sleep "$delay"
done
}
retry adb install -r app.apk
retry adb shell am instrument -w -r ...对于 的重试,还应先对测试包执行 ——否则瞬时状态会在多次尝试之间泄漏。注意, 只会重跑传输层错误(即 主机二进制返回非零);真实测试失败时 仍退出 ,因此不会触发重试——应通过解析输出检测,而不是依赖退出码。
am instrumentpm clearretryadbam instrument0Parallel device fan-out
并行设备扇出
bash
adb devices \
| tail -n +2 \
| awk '$2=="device"{print $1}' \
| xargs -I {} -P 4 adb -s {} <command>Key fragments:
- skips the
tail -n +2header.List of devices attached - filters out
awk '$2=="device"',unauthorized,offline, etc.recovery - runs 4 in parallel; tune to physical USB-hub count.
-P 4 - targets a serial.
adb -s {}is the env-var equivalent inside the spawned shells.$ANDROID_SERIAL
For tests with shared device-state (logcat clear, app install), serialise the prep then parallelise the run:
bash
SERIALS=$(adb devices | awk '$2=="device"{print $1}')
echo "$SERIALS" | xargs -I {} -P 0 adb -s {} install -r app-debug.apk
echo "$SERIALS" | xargs -I {} -P 0 adb -s {} install -r app-debug-androidTest.apkbash
adb devices \
| tail -n +2 \
| awk '$2=="device"{print $1}' \
| xargs -I {} -P 4 adb -s {} <command>关键片段:
- 跳过
tail -n +2标题行。List of devices attached - 过滤掉
awk '$2=="device"'、unauthorized、offline等状态。recovery - 表示并行运行 4 个任务;应根据物理 USB hub 的数量进行调整。
-P 4 - 用于指定目标设备序列号。
adb -s {}是派生 shell 中对应的环境变量形式。$ANDROID_SERIAL
对于会共享设备状态的测试(清理 logcat、安装应用),应先串行执行准备阶段,再并行运行测试:
bash
SERIALS=$(adb devices | awk '$2=="device"{print $1}')
echo "$SERIALS" | xargs -I {} -P 0 adb -s {} install -r app-debug.apk
echo "$SERIALS" | xargs -I {} -P 0 adb -s {} install -r app-debug-androidTest.apkDistribute shards across devices (one shard per device)
Distribute shards across devices (one shard per device)
i=0
for S in $SERIALS; do
adb -s "$S" logcat -c
adb -s "$S" shell am instrument -w -r
-e numShards $(echo "$SERIALS" | wc -l) -e shardIndex "$i"
com.example.test/androidx.test.runner.AndroidJUnitRunner
> "results-$S.txt" & i=$((i+1)) done wait
-e numShards $(echo "$SERIALS" | wc -l) -e shardIndex "$i"
com.example.test/androidx.test.runner.AndroidJUnitRunner
> "results-$S.txt" & i=$((i+1)) done wait
i=0
for S in $SERIALS; do
adb -s "$S" logcat -c
adb -s "$S" shell am instrument -w -r
-e numShards $(echo "$SERIALS" | wc -l) -e shardIndex "$i"
com.example.test/androidx.test.runner.AndroidJUnitRunner
> "results-$S.txt" & i=$((i+1)) done wait
-e numShards $(echo "$SERIALS" | wc -l) -e shardIndex "$i"
com.example.test/androidx.test.runner.AndroidJUnitRunner
> "results-$S.txt" & i=$((i+1)) done wait
am instrument always exits 0 — derive pass/fail from the captured output:
am instrument always exits 0 — derive pass/fail from the captured output:
if grep -qE '^INSTRUMENTATION_STATUS_CODE: -[12]$' results-*.txt; then
echo "test failures detected"; exit 1
fi
(`xargs -P 0` runs as many concurrently as there are inputs.)if grep -qE '^INSTRUMENTATION_STATUS_CODE: -[12]$' results-*.txt; then
echo "test failures detected"; exit 1
fi
(`xargs -P 0` 的并发数与输入数量相同。)Sharding via numShards
/ shardIndex
numShardsshardIndex通过 numShards
/ shardIndex
进行分片
numShardsshardIndex"If you need to parallelize the execution of your tests ... use theoption to specify the number of separate shards to create and the-e numShardsoption to specify which shard to run." — AndroidJUnitRunner docs.-e shardIndex
Distribution is hash-bucketed by test name — deterministic across runs given the same test set. Adding/removing tests reshuffles buckets.
“如果需要并行执行测试……请使用选项指定要创建的分片数量,并使用-e numShards选项指定要运行的分片。”——AndroidJUnitRunner 文档。-e shardIndex
分发方式会根据测试名称进行 hash 分桶——在测试集合保持不变时,每次运行的结果都是确定的。添加或移除测试会重新打乱各个分桶。
Per-device artefact paths
按设备划分的 artefact 路径
Always namespace by serial:
bash
artifact_dir() { echo "artifacts/${1//[:_]/-}"; }
for S in $(adb devices | awk '$2=="device"{print $1}'); do
D=$(artifact_dir "$S"); mkdir -p "$D"
adb -s "$S" logcat -d -v threadtime > "$D/logcat.txt"
adb -s "$S" shell screencap -p /sdcard/last.png
adb -s "$S" pull /sdcard/last.png "$D/last.png"
done始终使用序列号划分命名空间:
bash
artifact_dir() { echo "artifacts/${1//[:_]/-}"; }
for S in $(adb devices | awk '$2=="device"{print $1}'); do
D=$(artifact_dir "$S"); mkdir -p "$D"
adb -s "$S" logcat -d -v threadtime > "$D/logcat.txt"
adb -s "$S" shell screencap -p /sdcard/last.png
adb -s "$S" pull /sdcard/last.png "$D/last.png"
doneIdempotent setup + cleanup with trap
trap幂等设置与使用 trap
清理
trapNever assume clean state from a previous run. Bake cleanup into setup, and use to enforce teardown.
trap永远不要假设上次运行后仍处于干净状态。应将清理纳入设置流程,并使用 强制执行 teardown。
trapMinimal setup preamble
最小设置前导代码
bash
adb wait-for-device
adb shell input keyevent 82 # wake; no-op if already on
adb shell pm clear com.example.app # wipe app data + cache
adb shell pm clear com.example.app.test # wipe test process state
adb shell am force-stop com.example.appbash
adb wait-for-device
adb shell input keyevent 82 # wake; no-op if already on
adb shell pm clear com.example.app # wipe app data + cache
adb shell pm clear com.example.app.test # wipe test process state
adb shell am force-stop com.example.appHermetic animations
Hermetic animations
adb shell settings put global window_animation_scale 0
adb shell settings put global transition_animation_scale 0
adb shell settings put global animator_duration_scale 0
(See `../../control/injecting-input-and-state/SKILL.md` for the full `pm clear` vs `am force-stop` reasoning.)adb shell settings put global window_animation_scale 0
adb shell settings put global transition_animation_scale 0
adb shell settings put global animator_duration_scale 0
(有关 `pm clear` 与 `am force-stop` 的完整选型分析,请参阅 `../../control/injecting-input-and-state/SKILL.md`。)trap
cleanup
traptrap
清理
trapbash
cleanup() {
adb shell am force-stop com.example.app || true
adb shell pm clear com.example.app || true
adb uninstall com.example.app || true
adb forward --remove tcp:6100 || true
adb reverse --remove-all || true
adb shell settings put global window_animation_scale 1 || true
adb shell settings put global transition_animation_scale 1 || true
adb shell settings put global animator_duration_scale 1 || true
}
trap cleanup EXITEach step is — partial-state cleanup must never mask the original failure exit code.
|| truebash
cleanup() {
adb shell am force-stop com.example.app || true
adb shell pm clear com.example.app || true
adb uninstall com.example.app || true
adb forward --remove tcp:6100 || true
adb reverse --remove-all || true
adb shell settings put global window_animation_scale 1 || true
adb shell settings put global transition_animation_scale 1 || true
adb shell settings put global animator_duration_scale 1 || true
}
trap cleanup EXIT每个步骤都使用 ——部分状态清理失败绝不能掩盖原始的失败退出码。
|| trueCapture-on-failure
失败时捕获
bash
set +e
./gradlew connectedDebugAndroidTest
RC=$?
set -e
if [ "$RC" -ne 0 ]; then
mkdir -p artifacts
adb shell screencap -p /sdcard/fail.png
adb pull /sdcard/fail.png artifacts/fail.png
adb logcat -d -v threadtime > artifacts/logcat.txt
adb logcat -d -b crash -v threadtime > artifacts/crash.txt
adb logcat -d -b events -v descriptive > artifacts/events.txt
adb shell dumpsys activity > artifacts/dumpsys-activity.txt
fi
exit $RC(See and for the underlying primitives.)
../../capture/capturing-screenshots-and-screenrecord/SKILL.md../../observability/extracting-logs-with-logcat/SKILL.mdbash
set +e
./gradlew connectedDebugAndroidTest
RC=$?
set -e
if [ "$RC" -ne 0 ]; then
mkdir -p artifacts
adb shell screencap -p /sdcard/fail.png
adb pull /sdcard/fail.png artifacts/fail.png
adb logcat -d -v threadtime > artifacts/logcat.txt
adb logcat -d -b crash -v threadtime > artifacts/crash.txt
adb logcat -d -b events -v descriptive > artifacts/events.txt
adb shell dumpsys activity > artifacts/dumpsys-activity.txt
fi
exit $RC(有关底层原语,请参阅 和 。)
../../capture/capturing-screenshots-and-screenrecord/SKILL.md../../observability/extracting-logs-with-logcat/SKILL.mdTest Orchestrator wiring
Test Orchestrator 接入
"Android Test Orchestrator collects JUnit tests at the beginning of your test suite run, but it then executes each test separately, in its own instance of." — developer.android.com.Instrumentation
Each runs in its own invocation, so process state, statics, and singletons are reset between tests.
@TestInstrumentationApplication“Android Test Orchestrator 会在测试套件开始时收集 JUnit 测试,但随后在独立的实例中分别执行每个测试。”——developer.android.com。Instrumentation
每个 都在独立的 调用中运行,因此进程状态、静态变量和 单例会在测试之间重置。
@TestInstrumentationApplicationGradle wiring — androidTestUtil
, NOT androidTestImplementation
androidTestUtilandroidTestImplementationGradle 接入——使用 androidTestUtil
,而不是 androidTestImplementation
androidTestUtilandroidTestImplementationgradle
android {
defaultConfig {
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
testInstrumentationRunnerArguments clearPackageData: 'true'
}
testOptions {
execution 'ANDROIDX_TEST_ORCHESTRATOR'
}
}
dependencies {
androidTestImplementation 'androidx.test:runner:1.7.0'
androidTestUtil 'androidx.test:orchestrator:1.6.1' // NOT androidTestImplementation
}clearPackageData: 'true'pm clear <pkg>gradle
android {
defaultConfig {
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
testInstrumentationRunnerArguments clearPackageData: 'true'
}
testOptions {
execution 'ANDROIDX_TEST_ORCHESTRATOR'
}
}
dependencies {
androidTestImplementation 'androidx.test:runner:1.7.0'
androidTestUtil 'androidx.test:orchestrator:1.6.1' // NOT androidTestImplementation
}clearPackageData: 'true'pm clear <pkg>Direct ADB invocation (non-Gradle)
直接通过 ADB 调用(非 Gradle)
bash
adb install --force-queryable -r path/to/orchestrator-1.6.1.apk
adb install --force-queryable -r path/to/test-services-1.6.0.apk
adb shell 'CLASSPATH=$(pm path androidx.test.services) app_process / \
androidx.test.services.shellexecutor.ShellMain am instrument -w -e \
targetInstrumentation com.example.test/androidx.test.runner.AndroidJUnitRunner \
androidx.test.orchestrator/.AndroidTestOrchestrator'--force-queryablebindServicebash
adb install --force-queryable -r path/to/orchestrator-1.6.1.apk
adb install --force-queryable -r path/to/test-services-1.6.0.apk
adb shell 'CLASSPATH=$(pm path androidx.test.services) app_process / \
androidx.test.services.shellexecutor.ShellMain am instrument -w -e \
targetInstrumentation com.example.test/androidx.test.runner.AndroidJUnitRunner \
androidx.test.orchestrator/.AndroidTestOrchestrator'在 API 30+ 上需要使用 ,这样 Orchestrator 才能在包可见性规则下通过 绑定到目标应用。
--force-queryablebindServiceTradeoffs
取舍
- Pros: each test starts from a known-good ; one crash doesn't kill the rest of the run;
Applicationbetween tests is real, not "I cleaned up inpm clear".@After - Cons: per-test process spin-up adds ~1–2 s. A 500-test suite goes from ~5 minutes to ~15+ minutes. Reserve for integration suites where state leakage actually bites.
- 优点: 每个测试都从状态已知的 开始;单个测试崩溃不会终止其余测试;测试之间的
Application是真实执行的,而不是仅在pm clear中“清理”。@After - 缺点: 每个测试启动独立进程会增加约 1–2 秒。一个包含 500 个测试的套件可能从约 5 分钟增加到 15 分钟以上。仅在状态泄漏确实会造成问题时,将其用于集成测试套件。
Patterns
模式
Pattern: WRONG — gating CI on am instrument
's exit code
am instrument模式:错误——根据 am instrument
的退出码设置 CI 门禁
am instrumentbash
undefinedbash
undefinedWRONG
WRONG
adb shell am instrument -w -r com.example.test/androidx.test.runner.AndroidJUnitRunner
RC=$?
[ "$RC" -eq 0 ] && echo "tests passed" || echo "tests failed (rc=$RC)"
adb shell am instrument -w -r com.example.test/androidx.test.runner.AndroidJUnitRunner
RC=$?
[ "$RC" -eq 0 ] && echo "tests passed" || echo "tests failed (rc=$RC)"
WRONG because: am instrument calls System.exit(0) (AOSP Instrument.java) and AndroidJUnitRunner's
WRONG because: am instrument calls System.exit(0) (AOSP Instrument.java) and AndroidJUnitRunner's
finish() reports RESULT_OK regardless. $? is 0 even when tests fail — with OR without -w.
finish() reports RESULT_OK regardless. $? is 0 even when tests fail — with OR without -w.
```bash
```bashRIGHT — keep -w (so stdout is complete) and -r (raw, parseable), then parse the stream
RIGHT — keep -w (so stdout is complete) and -r (raw, parseable), then parse the stream
adb shell am instrument -w -r com.example.test/androidx.test.runner.AndroidJUnitRunner
| tee instrument.log
| tee instrument.log
adb shell am instrument -w -r com.example.test/androidx.test.runner.AndroidJUnitRunner
| tee instrument.log
| tee instrument.log
-1 = error, -2 = failure; -3 (ignored) and -4 (assumption failure) are skips, not failures.
-1 = error, -2 = failure; -3 (ignored) and -4 (assumption failure) are skips, not failures.
if grep -qE '^INSTRUMENTATION_STATUS_CODE: -[12]$' instrument.log; then
echo "tests failed"; exit 1
fi
echo "tests passed"
undefinedif grep -qE '^INSTRUMENTATION_STATUS_CODE: -[12]$' instrument.log; then
echo "tests failed"; exit 1
fi
echo "tests passed"
undefinedPattern: WRONG — confusing adb forward
and adb reverse
argument order
adb forwardadb reverse模式:错误——混淆 adb forward
和 adb reverse
的参数顺序
adb forwardadb reversebash
undefinedbash
undefinedWRONG — copy/pasted the forward syntax for reverse
WRONG — copy/pasted the forward syntax for reverse
adb reverse tcp:8080 tcp:8080 # ambiguous (works because both are tcp:8080)
adb reverse tcp:9000 tcp:8080 # this means: device port 9000 → host port 8080
adb reverse tcp:8080 tcp:8080 # ambiguous (works because both are tcp:8080)
adb reverse tcp:9000 tcp:8080 # this means: device port 9000 → host port 8080
Developer expected: host service on 8080 reachable as 9000 on device.
Developer expected: host service on 8080 reachable as 9000 on device.
WRONG because: reverse argument order is REMOTE LOCAL. The device tries to dial 8080 on
WRONG because: reverse argument order is REMOTE LOCAL. The device tries to dial 8080 on
the host, but the dev meant to expose the local 8080 to the device on port 9000.
the host, but the dev meant to expose the local 8080 to the device on port 9000.
```bash
```bashRIGHT — adb reverse REMOTE LOCAL
RIGHT — adb reverse REMOTE LOCAL
Expose host service on 8080 to the device as 9000:
Expose host service on 8080 to the device as 9000:
adb reverse tcp:9000 tcp:8080
adb reverse tcp:9000 tcp:8080
In the app code: open a connection to localhost:9000 — it terminates at the host's :8080.
In the app code: open a connection to localhost:9000 — it terminates at the host's :8080.
Or, simpler, identical port:
Or, simpler, identical port:
adb reverse tcp:8080 tcp:8080 # device 8080 ⇆ host 8080
undefinedadb reverse tcp:8080 tcp:8080 # device 8080 ⇆ host 8080
undefinedPattern: WRONG — androidTestImplementation
for the orchestrator APK
androidTestImplementation模式:错误——使用 androidTestImplementation
引入 orchestrator APK
androidTestImplementationgradle
// WRONG
dependencies {
androidTestImplementation 'androidx.test:orchestrator:1.6.1'
}
// WRONG because: the orchestrator is a SEPARATE APK, not a library. androidTestImplementation
// merges it into the test APK's classpath, which AGP rejects (or silently ignores). The
// correct configuration is androidTestUtil, which AGP installs as an additional APK.gradle
// RIGHT
dependencies {
androidTestImplementation 'androidx.test:runner:1.7.0'
androidTestUtil 'androidx.test:orchestrator:1.6.1'
}gradle
// WRONG
dependencies {
androidTestImplementation 'androidx.test:orchestrator:1.6.1'
}
// WRONG because: the orchestrator is a SEPARATE APK, not a library. androidTestImplementation
// merges it into the test APK's classpath, which AGP rejects (or silently ignores). The
// correct configuration is androidTestUtil, which AGP installs as an additional APK.gradle
// RIGHT
dependencies {
androidTestImplementation 'androidx.test:runner:1.7.0'
androidTestUtil 'androidx.test:orchestrator:1.6.1'
}Pattern: timeout an instrumentation invocation
模式:为 instrumentation 调用设置超时
bash
timeout 600s adb shell am instrument -w -r \
com.example.test/androidx.test.runner.AndroidJUnitRunner | tee instrument.log
RC=${PIPESTATUS[0]} # exit of `timeout`, not `tee`
case "$RC" in
124) echo "timed out at 600s"; exit 124 ;;
137) echo "timed out and had to be SIGKILLed"; exit 137 ;;
esacbash
timeout 600s adb shell am instrument -w -r \
com.example.test/androidx.test.runner.AndroidJUnitRunner | tee instrument.log
RC=${PIPESTATUS[0]} # exit of `timeout`, not `tee`
case "$RC" in
124) echo "timed out at 600s"; exit 124 ;;
137) echo "timed out and had to be SIGKILLed"; exit 137 ;;
esacRC is 0 whether tests passed or failed (am instrument always exits 0); pass/fail comes from the stream:
RC is 0 whether tests passed or failed (am instrument always exits 0); pass/fail comes from the stream:
if grep -qE '^INSTRUMENTATION_STATUS_CODE: -[12]$' instrument.log; then
echo "failed"; exit 1
fi
echo "passed"
undefinedif grep -qE '^INSTRUMENTATION_STATUS_CODE: -[12]$' instrument.log; then
echo "failed"; exit 1
fi
echo "passed"
undefinedPattern: retry-with-server-bounce
模式:通过重启 server 进行重试
bash
retry adb -s "$SERIAL" install -r app-debug.apk
retry adb -s "$SERIAL" shell am instrument -w -r \
-e clearPackageData true \
com.example.test/androidx.test.runner.AndroidJUnitRunnerThe helper bounces the adb server on transient failure (see "Retries on transient errors" above).
retrybash
retry adb -s "$SERIAL" install -r app-debug.apk
retry adb -s "$SERIAL" shell am instrument -w -r \
-e clearPackageData true \
com.example.test/androidx.test.runner.AndroidJUnitRunnerretryPattern: parallel sharded fan-out with per-device artefacts
模式:并行分片扇出并按设备保存 artefact
bash
SERIALS=( $(adb devices | awk '$2=="device"{print $1}') )
N=${#SERIALS[@]}
mkdir -p artifacts
pids=()
for i in "${!SERIALS[@]}"; do
S="${SERIALS[$i]}"
D="artifacts/${S//[:_]/-}"
mkdir -p "$D"
(
adb -s "$S" logcat -c
adb -s "$S" shell pm clear com.example.app
adb -s "$S" shell am instrument -w -r \
-e numShards "$N" -e shardIndex "$i" \
com.example.test/androidx.test.runner.AndroidJUnitRunner \
> "$D/results.txt"
# am instrument exits 0 regardless — pass/fail is in the captured stream.
if grep -qE '^INSTRUMENTATION_STATUS_CODE: -[12]$' "$D/results.txt"; then
adb -s "$S" shell screencap -p /sdcard/fail.png
adb -s "$S" pull /sdcard/fail.png "$D/fail.png"
adb -s "$S" logcat -d -v threadtime > "$D/logcat.txt"
exit 1
fi
) &
pids+=($!)
done
rc=0
for p in "${pids[@]}"; do wait "$p" || rc=1; done # fail the job if any shard failed
exit $rcbash
SERIALS=( $(adb devices | awk '$2=="device"{print $1}') )
N=${#SERIALS[@]}
mkdir -p artifacts
pids=()
for i in "${!SERIALS[@]}"; do
S="${SERIALS[$i]}"
D="artifacts/${S//[:_]/-}"
mkdir -p "$D"
(
adb -s "$S" logcat -c
adb -s "$S" shell pm clear com.example.app
adb -s "$S" shell am instrument -w -r \
-e numShards "$N" -e shardIndex "$i" \
com.example.test/androidx.test.runner.AndroidJUnitRunner \
> "$D/results.txt"
# am instrument exits 0 regardless — pass/fail is in the captured stream.
if grep -qE '^INSTRUMENTATION_STATUS_CODE: -[12]$' "$D/results.txt"; then
adb -s "$S" shell screencap -p /sdcard/fail.png
adb -s "$S" pull /sdcard/fail.png "$D/fail.png"
adb -s "$S" logcat -d -v threadtime > "$D/logcat.txt"
exit 1
fi
) &
pids+=($!)
done
rc=0
for p in "${pids[@]}"; do wait "$p" || rc=1; done # fail the job if any shard failed
exit $rcMandatory rules
强制规则
- MUST pass to
-w -rso the shell waits for the runner and emits raw, parseable output. Withoutam instrumentthe shell returns before any output is produced.-w - MUST NOT gate CI on from
$?— it callsam instrumentregardless of test outcome (with or withoutSystem.exit(0)). Detect failures by grepping stdout for-w(error) andINSTRUMENTATION_STATUS_CODE: -1(failure).-2 - MUST distinguish IGNORED and
-3ASSUMPTION_FAILURE from real failures when parsing-4.INSTRUMENTATION_STATUS_CODEand-1are the failure codes.-2 - MUST remember that is
adb forward(host first) andLOCAL REMOTEisadb reverse(device first). The argument orders are opposite.REMOTE LOCAL - MUST wrap long-running adb commands with (or
timeout <N>son macOS).gtimeouthas no built-in timeout flag —adbis transport ID, not timeout.adb -t - MUST use , not
androidTestUtil("androidx.test:orchestrator:1.6.1"). The orchestrator is a separate APK, not a library.androidTestImplementation - MUST retry transient adb errors (,
device not found,closed) with a boundedprotocol faulthelper that callsretrybetween attempts.adb kill-server; adb start-server - MUST install a that removes port forwards (
trap cleanup EXIT,adb forward --remove-all), restores animation scales, andadb reverse --remove-alls the app under test. Each steppm clearso cleanup never masks the test exit code.|| true - MUST (not just
pm clear <pkg>) before each test run. Seeam force-stop.../../control/injecting-input-and-state/SKILL.md - MUST NOT rely on exit-code propagation on devices below API 24. Use a sentinel
adb shellin stdout for older targets, or pin minSdk for the test infra.__ADB_RC=$? - MUST NOT confuse with
adb -t <transport-id>. They share zero semantics.timeout - MUST NOT parallelise without serialising the install / setup phase — concurrent to the same device race.
adb install - PREFERRED: Test Orchestrator + for hermetic isolation; pair with
clearPackageData: 'true'for routed artefacts (seeuseTestStorageService: 'true').../../transfer/extracting-test-artifacts/SKILL.md - PREFERRED: namespace artefacts by serial () so
artifacts/${SERIAL//[:_]/-}/in CI captures everything cleanly.archive artifacts/**/*
- 必须对 传入
am instrument,使 shell 等待 runner 并输出原始、可解析的结果。不使用-w -r时,shell 会在产生任何输出之前返回。-w - 禁止根据 的
am instrument设置 CI 门禁——无论测试结果如何,它都会调用$?(是否使用System.exit(0)均如此)。应通过在 stdout 中查找-w(错误)和INSTRUMENTATION_STATUS_CODE: -1(失败)来检测失败。-2 - 必须在解析 时区分
INSTRUMENTATION_STATUS_CODEIGNORED 和-3ASSUMPTION_FAILURE 与真实失败。-4和-1才是失败状态码。-2 - 必须记住 的顺序是
adb forward(主机在前),而LOCAL REMOTE的顺序是adb reverse(设备在前)。两者的参数顺序相反。REMOTE LOCAL - 必须使用 (macOS 上使用
timeout <N>s)包装长时间运行的 adb 命令。gtimeout没有内置的超时标志——adb表示 transport ID,而不是 timeout。adb -t - 必须使用 ,而不是
androidTestUtil("androidx.test:orchestrator:1.6.1")。Orchestrator 是独立的 APK,而不是库。androidTestImplementation - 必须使用有次数上限的 helper 重试瞬时 adb 错误(
retry、device not found、closed),并在尝试之间调用protocol fault。adb kill-server; adb start-server - 必须安装 ,用于移除端口转发(
trap cleanup EXIT、adb forward --remove-all)、恢复动画缩放设置,并执行adb reverse --remove-all清理被测应用。每个步骤都应使用pm clear,确保清理不会掩盖测试退出码。|| true - 必须在每次测试运行前执行 ,而不能只使用
pm clear <pkg>。请参阅am force-stop。../../control/injecting-input-and-state/SKILL.md - 禁止依赖 API 24 以下设备上的 退出码传递。对于较旧的目标设备,应在 stdout 中使用哨兵值
adb shell,或在测试基础设施中固定 minSdk。__ADB_RC=$? - 禁止混淆 与
adb -t <transport-id>。两者没有任何语义关联。timeout - 禁止在未串行化安装/设置阶段的情况下进行并行化——对同一台设备并发执行 会产生竞态。
adb install - 首选: 使用 Test Orchestrator 配合 实现隔离式测试;结合
clearPackageData: 'true'路由 artefact(请参阅useTestStorageService: 'true')。../../transfer/extracting-test-artifacts/SKILL.md - 首选: 使用序列号划分 artefact 命名空间(),确保 CI 中的
artifacts/${SERIAL//[:_]/-}/能够整齐地收集所有文件。archive artifacts/**/*
Verification
验证
- Every invocation in scripts/Gradle has
am instrument, and no script branches on its-w -ras a pass/fail signal — failures are detected by parsing$?/INSTRUMENTATION_STATUS_CODE: -1from stdout.-2 - and
adb forwardappear with arguments in the documented order; CI passes a smoke test that the host can reach the device service and vice versa.adb reverse - (not
androidTestUtil('androidx.test:orchestrator:...')) —androidTestImplementationshows the orchestrator../gradlew :app:dependencies --configuration androidTestUtil - is installed in the top-level CI script.
trap cleanup EXIT - All long-running adb commands are wrapped with .
timeout - CI run completes 50 iterations without a "leaked port forward" or "previous run's animation scale" flake.
- Status-code parsing treats and
-3as skips, not failures.-4 - Per-device artefact directories are namespaced by serial; CI artefact archive shows them in the expected layout.
- Retry helper bounces between attempts on transient errors.
adb kill-server; adb start-server
- 脚本/Gradle 中的每次 调用都使用了
am instrument,且没有脚本将其-w -r作为通过/失败信号——失败是通过解析 stdout 中的$?/INSTRUMENTATION_STATUS_CODE: -1检测的。-2 - 和
adb forward的参数均采用文档规定的顺序;CI 通过冒烟测试,验证主机可以访问设备服务,反之亦然。adb reverse - 使用 ,而不是
androidTestUtil('androidx.test:orchestrator:...')——androidTestImplementation显示 orchestrator。./gradlew :app:dependencies --configuration androidTestUtil - 顶层 CI 脚本中安装了 。
trap cleanup EXIT - 所有长时间运行的 adb 命令都使用了 包装。
timeout - CI 连续运行 50 次后,没有出现“leaked port forward”或“previous run's animation scale”类不稳定问题。
- 状态码解析将 和
-3视为跳过,而不是失败。-4 - 每台设备的 artefact 目录均按序列号划分命名空间;CI artefact 归档结果符合预期布局。
- Retry helper 会在瞬时错误发生时,在尝试之间执行 。
adb kill-server; adb start-server
References
参考资料
- developer.android.com/tools/adb — /
forwardsyntax, transport, server.reverse - developer.android.com/studio/test/command-line — ,
am instrument -w -r/-e numShards, AndroidJUnitRunner arguments, output dirs.-e shardIndex - developer.android.com/training/testing/instrumented-tests — Test Orchestrator overview.
- developer.android.com/reference/android/app/Instrumentation — constants (
REPORT_VALUE_RESULT_*,OK = 0,START = 1,ERROR = -1).FAILURE = -2 - firebase.google.com/docs/test-lab/android/command-line — Firebase Test Lab CI exit codes (pass,
0test failure,10indeterminate,15incompatible,18infra error).20 - Research note — full bash idioms, exit-code propagation matrix, port-forward token grammar, parallel fan-out, retries, capture-on-failure, Test Orchestrator wiring.
tasks/research/A3-adb-observability-automation.md - Research note —
tasks/research/A2-adb-shell-commands.mdarguments, status codes, AndroidJUnitRunneram instrument/-3extensions.-4 - Sibling skill: — server / daemon /
../../architecture/understanding-adb-architecture/SKILL.md.adb kill-server - Sibling skill: — device states,
../../devices/connecting-to-devices/SKILL.md.wait-for-device - Sibling skill: —
../../devices/connecting-over-wifi/SKILL.md/adb pairfor headless CI.adb connect - Sibling skill: —
../../apps/installing-and-managing-apps/SKILL.md/pm install/pm uninstall.pm clear - Sibling skill: —
../../tests/running-instrumented-tests-via-adb/SKILL.mddeep dive.am instrument -w -r - Sibling skill: — hermetic preamble (animations to 0,
../../control/injecting-input-and-state/SKILL.md,pm clear).am force-stop - Sibling skill: —
../../capture/capturing-screenshots-and-screenrecord/SKILL.md/screencapcapture-on-failure.screenrecord - Sibling skill: —
../../observability/extracting-logs-with-logcat/SKILL.mdcapture-on-failure.logcat -d - Sibling skill: —
../../transfer/extracting-test-artifacts/SKILL.md/pull/push/run-as.TestStorage - Cross-set: — runner internals.
../../../instrumentation/runner/running-instrumented-tests-with-androidjunit4/SKILL.md - Cross-set: — Activity scenarios under instrumentation.
../../../instrumentation/scenarios/launching-activities-with-activityscenario/SKILL.md - Cross-set: — when to invest in CI orchestration vs simpler tooling.
../../../fundamentals/strategies/applying-testing-strategies/SKILL.md
- developer.android.com/tools/adb——/
forward语法、transport、server。reverse - developer.android.com/studio/test/command-line——、
am instrument -w -r/-e numShards、AndroidJUnitRunner 参数、输出目录。-e shardIndex - developer.android.com/training/testing/instrumented-tests——Test Orchestrator 概览。
- developer.android.com/reference/android/app/Instrumentation——常量(
REPORT_VALUE_RESULT_*、OK = 0、START = 1、ERROR = -1)。FAILURE = -2 - firebase.google.com/docs/test-lab/android/command-line——Firebase Test Lab CI 退出码(通过、
0测试失败、10结果不确定、15不兼容、18基础设施错误)。20 - 研究笔记 ——完整的 Bash 惯用法、退出码传递矩阵、端口转发 token 语法、并行扇出、重试、失败时捕获、Test Orchestrator 接入。
tasks/research/A3-adb-observability-automation.md - 研究笔记 ——
tasks/research/A2-adb-shell-commands.md参数、状态码、AndroidJUnitRunner 的am instrument/-3扩展。-4 - 同系列 skill:——server / daemon /
../../architecture/understanding-adb-architecture/SKILL.md。adb kill-server - 同系列 skill:——设备状态、
../../devices/connecting-to-devices/SKILL.md。wait-for-device - 同系列 skill:——用于无头 CI 的
../../devices/connecting-over-wifi/SKILL.md/adb pair。adb connect - 同系列 skill:——
../../apps/installing-and-managing-apps/SKILL.md/pm install/pm uninstall。pm clear - 同系列 skill:——深入讲解
../../tests/running-instrumented-tests-via-adb/SKILL.md。am instrument -w -r - 同系列 skill:——隔离式前导代码(将动画设为 0、
../../control/injecting-input-and-state/SKILL.md、pm clear)。am force-stop - 同系列 skill:——通过
../../capture/capturing-screenshots-and-screenrecord/SKILL.md/screencap在失败时捕获。screenrecord - 同系列 skill:——通过
../../observability/extracting-logs-with-logcat/SKILL.md在失败时捕获。logcat -d - 同系列 skill:——
../../transfer/extracting-test-artifacts/SKILL.md/pull/push/run-as。TestStorage - Cross-set:——runner 内部机制。
../../../instrumentation/runner/running-instrumented-tests-with-androidjunit4/SKILL.md - Cross-set:——使用 ActivityScenario 进行 instrumentation 测试。
../../../instrumentation/scenarios/launching-activities-with-activityscenario/SKILL.md - Cross-set:——何时值得投入 CI 编排,何时采用更简单的工具。
../../../fundamentals/strategies/applying-testing-strategies/SKILL.md