extracting-test-artifacts

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Extracting Test Artifacts — adb pull / push and run-as

提取测试产物 —— adb pull / push 与 run-as

This skill covers moving files between host and device, the path permission rules that decide whether a
pull
succeeds, and the
androidx.test:services
TestStorage
API for routing per-test artefacts. Capture-on-failure orchestration (when to pull what) lives in
../../automation/scripting-adb-for-ci/SKILL.md
.
本 skill 涵盖在主机与设备之间移动文件、决定
pull
是否成功的路径权限规则,以及用于按测试路由产物的
androidx.test:services
TestStorage
API。失败时捕获的编排(何时拉取哪些内容)位于
../../automation/scripting-adb-for-ci/SKILL.md
。

When to use this skill

何时使用此 skill

  • A test produces artefacts (screenshots, JSON, captured DBs) that need to land on CI as build outputs.
  • adb pull /data/data/com.example/databases/main.db
    fails with "Permission denied"; the developer doesn't know
    run-as
    exists.
  • A binary file (PNG, MP4, SQLite DB) arrives on the host with mangled bytes — the missing
    exec-out
    is the fix.
  • A push of a large APK or test data file is slow; the developer wants the modern compression flags (
    -z brotli
    ).
  • The test app writes screenshots to
    /sdcard/Android/data/com.example/files/screenshots/
    and the developer wants to know whether that's pullable on API 30+ (it is, when the package owns it).
  • The team is migrating from "write to /sdcard, pull on the host" to the modern AndroidX
    TestStorage
    API.
  • 某个测试生成了需要作为构建输出保存到 CI 上的产物(截图、JSON、捕获的数据库)。
  • adb pull /data/data/com.example/databases/main.db
    出现“Permission denied”,而开发者不知道可以使用
    run-as
    。
  • 二进制文件(PNG、MP4、SQLite DB)到达主机后字节被破坏;改用
    exec-out
    即可解决。
  • 推送大型 APK 或测试数据文件速度缓慢;开发者希望使用现代压缩标志(
    -z brotli
    )。
  • 测试应用将截图写入
    /sdcard/Android/data/com.example/files/screenshots/
    ,开发者想知道在 API 30+ 上是否可以拉取该文件(当包拥有该目录时可以)。
  • 团队正在从“写入
    /sdcard
    ,在主机上拉取”的模式迁移到现代 AndroidX
    TestStorage
    API。

When NOT to use this skill

何时不应使用此 skill

  • Capturing the screenshot or video that becomes the artefact. Use
    ../../capture/capturing-screenshots-and-screenrecord/SKILL.md
    .
  • Capturing logs to extract. Use
    ../../observability/extracting-logs-with-logcat/SKILL.md
    .
  • Installing or uninstalling APKs. Use
    ../../apps/installing-and-managing-apps/SKILL.md
    .
  • Driving the device (taps, key events). Use
    ../../control/injecting-input-and-state/SKILL.md
    .
  • The whole CI orchestration (when to pull, retries, parallelisation). Use
    ../../automation/scripting-adb-for-ci/SKILL.md
    .
  • 捕获作为产物的截图或视频。请使用
    ../../capture/capturing-screenshots-and-screenrecord/SKILL.md
    。
  • 捕获日志以供提取。请使用
    ../../observability/extracting-logs-with-logcat/SKILL.md
    。
  • 安装或卸载 APK。请使用
    ../../apps/installing-and-managing-apps/SKILL.md
    。
  • 驱动设备(点击、按键事件)。请使用
    ../../control/injecting-input-and-state/SKILL.md
    。
  • 完整的 CI 编排(何时拉取、重试、并行化)。请使用
    ../../automation/scripting-adb-for-ci/SKILL.md
    。

Prerequisites

前置条件

  • adb get-state
    returns
    device
    . See
    ../../devices/connecting-to-devices/SKILL.md
    .
  • For
    run-as
    : the target APK must be
    android:debuggable="true"
    in its merged manifest (the default
    debug
    build variant).
  • For
    -z brotli
    /
    zstd
    : platform-tools 30+ on the host and adbd ≥ Android 11 on the device.
  • For
    TestStorage
    :
    androidx.test:services
    and the
    -e useTestStorageService true
    argument to
    am instrument
    .
  • adb get-state
    返回
    device
    。请参阅
    ../../devices/connecting-to-devices/SKILL.md
    。
  • 对于
    run-as
    :目标 APK 的合并清单中必须包含
    android:debuggable="true"
    (默认的
    debug
    构建变体满足此条件)。
  • 对于
    -z brotli
    /
    zstd
    :主机上的 platform-tools 需为 30+,设备上的 adbd 需为 Android 11 或更高版本。
  • 对于
    TestStorage
    :需要
    androidx.test:services
    ,并向
    am instrument
    传入
    -e useTestStorageService true
    参数。

Symmetric syntax

对称语法

"Unlike the
install
command, which only copies an APK file to a specific location, the
pull
and
push
commands let you copy arbitrary directories and files to any location in a device." — developer.android.com/tools/adb
adb pull <remote> [<local>]      # device → host (defaults to cwd)
adb push <local>  <remote>       # host   → device
“与只能将 APK 文件复制到特定位置的
install
命令不同,
pull
和
push
命令允许将任意目录和文件复制到设备中的任意位置。”——developer.android.com/tools/adb
adb pull <remote> [<local>]      # device → host (defaults to cwd)
adb push <local>  <remote>       # host   → device

Modern flags (platform-tools ≥ 30)

现代标志(platform-tools ≥ 30)

push [--sync] [-z ALGORITHM] [-Z] LOCAL... REMOTE
pull [-a]     [-z ALGORITHM] [-Z] REMOTE... LOCAL
FlagMeaning
-z <algo>
Enable compression.
<algo>
∈
any
/
none
/
brotli
/
lz4
/
zstd
.
any
lets adbd pick.
-Z
Disable compression.
--sync
(push only)
Only push files with different timestamps — fast incremental updates.
-a
(pull only)
Preserve file timestamp and mode.
-n
Dry-run.
-q
Suppress progress messages.
The legacy
adb pull -p
(show progress) is now a no-op — modern adb shows progress by default and
-q
silences it. Don't rely on
-p
in CI scripts.
push [--sync] [-z ALGORITHM] [-Z] LOCAL... REMOTE
pull [-a]     [-z ALGORITHM] [-Z] REMOTE... LOCAL
标志含义
-z <algo>
启用压缩。
<algo>
∈
any
/
none
/
brotli
/
lz4
/
zstd
。
any
表示由 adbd 选择。
-Z
禁用压缩。
--sync
(仅 push)
仅推送时间戳不同的文件,用于快速增量更新。
-a
(仅 pull)
保留文件时间戳和权限模式。
-n
空运行。
-q
禁止显示进度消息。
旧版的
adb pull -p
(显示进度)现在已不起作用——现代 adb 默认显示进度,可使用
-q
静默。不要在 CI 脚本中依赖
-p
。

Path permission rules

路径权限规则

This is the load-bearing table. Most "permission denied"
adb pull
failures come from misunderstanding it.
Pathadb shell writable?
pull
works?
/data/local/tmp/
YesYes
/sdcard/
(=
/storage/emulated/0/
)
Yes (scoped storage rules on API 30+)Yes
/data/data/<pkg>/
Only via
run-as <pkg>
(debuggable builds)
Only via
run-as
/sdcard/Android/data/<pkg>/files/
Package-owned, scoped storageYes for the owning package, and yes for
adb shell
(FUSE/sdcardfs bridge)
这是最关键的表格。大多数“Permission denied”类型的
adb pull
失败都源于对此规则的误解。
路径adb shell 可写?
pull
可用?
/data/local/tmp/
是是
/sdcard/
(=
/storage/emulated/0/
)
是(API 30+ 上遵循 scoped storage 规则)是
/data/data/<pkg>/
仅可通过
run-as <pkg>
(可调试构建)
仅可通过
run-as
/sdcard/Android/data/<pkg>/files/
归包所有,受 scoped storage 约束所属包可以使用,
adb shell
也可以使用(FUSE/sdcardfs bridge)

/data/local/tmp/

/data/local/tmp/

Readable/writable by the
shell
user that backs
adb
. No app-permission ceremony required. Use as the staging directory for everything: pushed APKs, test data, captured screenshots, JSON inputs, dexed instrumentation jars.
Caveat: your app runs as
u0_aXX
, not
shell
, so the app cannot read shell-written files unless you
chmod 0644
and the parent is world-readable.
/data/local/tmp/
itself is
0771
, so be deliberate when pushing files the app must read.
可由 adb 背后的
shell
用户读取和写入,无需申请应用权限。应将其作为所有内容的暂存目录:推送的 APK、测试数据、捕获的截图、JSON 输入以及经 dex 处理的 instrumentation jar。
注意:应用以
u0_aXX
而不是
shell
身份运行,因此除非执行
chmod 0644
并确保父目录可被全局读取,否则应用无法读取 shell 写入的文件。
/data/local/tmp/
本身的权限为
0771
,因此在推送应用必须读取的文件时应谨慎配置权限。

/sdcard/

/sdcard/

Alias
/storage/emulated/0/
, sometimes
/storage/self/primary/
. Public/external storage. ADB's
shell
user retains FUSE/sdcardfs access on API 30+, so
adb push /sdcard/...
and
adb pull /sdcard/...
work for tests even after scoped storage tightening. App-side writes are gated through MediaStore on API 30+.
它是
/storage/emulated/0/
的别名,有时也称为
/storage/self/primary/
。这是公共存储或外部存储。即使 scoped storage 已收紧,ADB 的
shell
用户在 API 30+ 上仍可通过 FUSE/sdcardfs 访问,因此即使在 scoped storage 限制生效后,
adb push /sdcard/...
和
adb pull /sdcard/...
仍可用于测试。在 API 30+ 上,应用侧的写入受 MediaStore 限制。

/data/data/<pkg>/
—
run-as
only

/data/data/<pkg>/
—— 只能使用
run-as

Owned by the app's UID;
0700
on the dir itself. A bare
adb pull /data/data/com.example/...
fails on production user builds. Two viable paths:
  • run-as <pkg>
    on debuggable builds (most common).
  • adb root
    on
    userdebug
    /
    eng
    builds (covered briefly in
    ../../automation/scripting-adb-for-ci/SKILL.md
    ).
该目录归应用 UID 所有,目录本身的权限为
0700
。直接执行
adb pull /data/data/com.example/...
会在生产环境用户构建中失败。可采用以下两种方式:
  • 在可调试构建上使用
    run-as <pkg>
    (最常见)。
  • 在
    userdebug
    /
    eng
    构建上使用
    adb root
    (详见
    ../../automation/scripting-adb-for-ci/SKILL.md
    )。

/sdcard/Android/data/<pkg>/files/

/sdcard/Android/data/<pkg>/files/

The app's "external private" storage — written from the app via
Context.getExternalFilesDir(null)
. Readable from
adb shell
because it lives under FUSE-emulated SD card. The path of least resistance for "write artefact, pull from CI" on Android 11+:
bash
undefined
这是应用的“外部私有”存储,可通过
Context.getExternalFilesDir(null)
从应用写入。由于它位于 FUSE 模拟的 SD 卡下,因此可由
adb shell
读取。对于 Android 11+ 上“写入产物,再从 CI 拉取”的需求,这是阻力最小的路径:
bash
undefined

Inside the test app:

Inside the test app:

val out = File(context.getExternalFilesDir(null), "screenshots/fail.png")

```bash
val out = File(context.getExternalFilesDir(null), "screenshots/fail.png")

```bash

From CI:

From CI:

adb pull /sdcard/Android/data/com.example/files/screenshots/fail.png ./
undefined
adb pull /sdcard/Android/data/com.example/files/screenshots/fail.png ./
undefined

run-as
on debuggable builds

在可调试构建上使用
run-as

run-as <pkg>
is a setuid helper baked into Android since Gingerbread. It drops shell into the app's UID if and only if the APK has
android:debuggable="true"
in its merged manifest (the default for the
debug
build variant). Usage:
adb shell run-as <pkg> <cmd>
.
run-as <pkg>
是 Android 从 Gingerbread 起内置的 setuid 辅助程序。仅当 APK 的合并清单中包含
android:debuggable="true"
时,它才会将 shell 切换到应用的 UID(默认
debug
构建变体满足此条件)。用法:
adb shell run-as <pkg> <cmd>
。

Text-file grab

获取文本文件

bash
adb shell run-as com.example.app cat databases/main.db > main.db
This works for short text files. For binary files it can corrupt bytes via PTY translation (see
exec-out
below).
bash
adb shell run-as com.example.app cat databases/main.db > main.db
该方式适用于短文本文件。对于二进制文件,PTY 转换可能会破坏字节(请参阅下文的
exec-out
)。

Binary-clean grab via
exec-out
+
tar

通过
exec-out
+
tar
实现二进制无损获取

For directories, binary files, or anything with
\n
in the bytes, MUST use
exec-out
(binary-clean stdout) and pipe through
tar
:
bash
adb exec-out run-as com.example.app tar cf - databases/ \
  | tar xf - -C ./pulled
The
tar cf -
produces an archive on stdout; the local
tar xf -
extracts it into
./pulled/
. No intermediate file, no PTY translation, works for arbitrary binary content.
对于目录、二进制文件或任何内容字节中包含
\n
的文件,必须使用
exec-out
(无损二进制标准输出)并通过
tar
管道传输:
bash
adb exec-out run-as com.example.app tar cf - databases/ \
  | tar xf - -C ./pulled
tar cf -
会在标准输出上生成归档;本地
tar xf -
会将归档解压到
./pulled/
。该方式无需中间文件,不会发生 PTY 转换,并且适用于任意二进制内容。

Single-file binary grab

获取单个二进制文件

bash
adb exec-out run-as com.example.app cat databases/main.db > main.db
exec-out
keeps stdout binary-clean.
bash
adb exec-out run-as com.example.app cat databases/main.db > main.db
exec-out
可保持标准输出中的二进制数据完整无损。

Listing

列出文件

bash
adb shell run-as com.example.app ls -lR files/
bash
adb shell run-as com.example.app ls -lR files/

Three things
run-as
cannot do

run-as
无法完成的三件事

  1. Work on release / non-debuggable builds. Will print "Package is not debuggable".
  2. Switch to a system UID (only the target package's UID).
  3. Cross profile boundaries by itself. Use
    --user N
    if needed.
  1. 无法在 release 或不可调试构建上运行。此时会输出“Package is not debuggable”。
  2. 无法切换到 system UID,只能使用目标包的 UID。
  3. 无法自行跨越 profile 边界;如有需要,请使用
    --user N
    。

Common test-artefact paths

常见测试产物路径

PathOrigin
app/build/outputs/connected_android_test_additional_output/<flavor><Variant>/connected/<deviceId>/
Gradle's standard "additional output" sink. The instrumentation runner pulls anything declared via
androidx.test:runner
arg
additionalTestOutputDir
.
app/build/outputs/androidTest-results/connected/<flavor><Variant>/TEST-*.xml
JUnit-style XML test results — ingested directly by Jenkins/GHA/etc.
app/build/reports/androidTests/connected/
HTML test report.
(See developer.android.com/studio/test/command-line: HTML at
module/build/reports/androidTests/connected/
, XML at
module/build/outputs/androidTest-results/connected/
.)
路径来源
app/build/outputs/connected_android_test_additional_output/<flavor><Variant>/connected/<deviceId>/
Gradle 标准的“additional output”接收目录。instrumentation runner 会拉取通过
androidx.test:runner
参数
additionalTestOutputDir
声明的所有内容。
app/build/outputs/androidTest-results/connected/<flavor><Variant>/TEST-*.xml
JUnit 风格的 XML 测试结果,可由 Jenkins/GHA 等系统直接读取。
app/build/reports/androidTests/connected/
HTML 测试报告。
(请参阅 developer.android.com/studio/test/command-line:HTML 位于
module/build/reports/androidTests/connected/
,XML 位于
module/build/outputs/androidTest-results/connected/
。)

Modern artefact API —
TestStorage

现代产物 API ——
TestStorage

The legacy pattern is "write to
/sdcard/...
, pull from CI script". The modern pattern routes through
androidx.test.services.storage.TestStorage
and a
useTestStorageService
flag.
旧模式是“写入
/sdcard/...
,再通过 CI 脚本拉取”。现代模式通过
androidx.test.services.storage.TestStorage
和
useTestStorageService
标志进行路由。

Wiring

配置

kotlin
// dependencies
androidTestImplementation("androidx.test:runner:1.7.0")
androidTestUtil("androidx.test.services:test-services:1.6.0")
kotlin
// am instrument args (or Gradle: testInstrumentationRunnerArguments)
adb shell am instrument -w -r \
  -e useTestStorageService true \
  com.example.test/androidx.test.runner.AndroidJUnitRunner
kotlin
// dependencies
androidTestImplementation("androidx.test:runner:1.7.0")
androidTestUtil("androidx.test.services:test-services:1.6.0")
kotlin
// am instrument args (or Gradle: testInstrumentationRunnerArguments)
adb shell am instrument -w -r \
  -e useTestStorageService true \
  com.example.test/androidx.test.runner.AndroidJUnitRunner

In-test usage

在测试中使用

kotlin
val storage = androidx.test.platform.io.PlatformTestStorageRegistry.getInstance()
storage.openOutputFile("screenshots/fail-${test.methodName}.png").use { out ->
    out.write(pngBytes)
}
kotlin
val storage = androidx.test.platform.io.PlatformTestStorageRegistry.getInstance()
storage.openOutputFile("screenshots/fail-${test.methodName}.png").use { out ->
    out.write(pngBytes)
}

What
TestStorage
solves

TestStorage
解决的问题

  • Output files land in a TestStorageService-managed directory rather than
    /sdcard/
    proper.
  • Gradle's
    connectedAndroidTest
    automatically pulls them into
    app/build/outputs/connected_android_test_additional_output/
    .
  • Per-test artefact namespacing happens through the runner, not via hand-rolled
    Class.method
    filename mangling.
  • Compatible with Test Orchestrator's
    clearPackageData: 'true'
    — the storage service holds artefacts even though the test app is wiped between tests.
For non-Gradle pipelines, the storage backs onto the same FS layout, addressable as
/sdcard/googletest/test_outputfiles/...
for legacy compatibility.
  • 输出文件会进入 TestStorageService 管理的目录,而不是直接位于
    /sdcard/
    下。
  • Gradle 的
    connectedAndroidTest
    会自动将它们拉取到
    app/build/outputs/connected_android_test_additional_output/
    。
  • 按测试划分产物命名空间由 runner 处理,无需自行拼接
    Class.method
    文件名。
  • 兼容 Test Orchestrator 的
    clearPackageData: 'true'
    ;即使测试应用在测试之间被清除,storage service 仍会保留产物。
对于非 Gradle 流水线,storage 会使用相同的文件系统布局,并且仍可通过
/sdcard/googletest/test_outputfiles/...
访问,以保持向后兼容。

Patterns

模式

Pattern: WRONG —
adb pull /data/data/<pkg>/...
on a debuggable build

模式:错误 —— 在可调试构建上执行
adb pull /data/data/<pkg>/...

bash
undefined
bash
undefined

WRONG

WRONG

adb pull /data/data/com.example/databases/main.db
adb pull /data/data/com.example/databases/main.db

adb: error: failed to stat remote object '/data/data/com.example/databases/main.db': Permission denied

adb: error: failed to stat remote object '/data/data/com.example/databases/main.db': Permission denied

WRONG because: /data/data/<pkg>/ is owned by the app UID with mode 0700. The shell user

WRONG because: /data/data/<pkg>/ is owned by the app UID with mode 0700. The shell user

cannot traverse it. run-as solves this on debuggable builds.

cannot traverse it. run-as solves this on debuggable builds.


```bash

```bash

RIGHT — run-as + exec-out + cat for a binary-clean grab

RIGHT — run-as + exec-out + cat for a binary-clean grab

adb exec-out run-as com.example cat databases/main.db > main.db file main.db # → "SQLite 3.x database"

Or for a directory:

```bash
adb exec-out run-as com.example tar cf - databases/ | tar xf - -C ./pulled
adb exec-out run-as com.example cat databases/main.db > main.db file main.db # → "SQLite 3.x database"

或者处理目录:

```bash
adb exec-out run-as com.example tar cf - databases/ | tar xf - -C ./pulled

Pattern: WRONG —
adb shell run-as <pkg> cat <binary>
for binary files

模式:错误 —— 对二进制文件使用
adb shell run-as <pkg> cat <binary>

bash
undefined
bash
undefined

WRONG (on Windows / certain CI hosts)

WRONG (on Windows / certain CI hosts)

adb shell run-as com.example cat databases/main.db > main.db
adb shell run-as com.example cat databases/main.db > main.db

WRONG because:
adb shell
allocates a PTY and translates LF to CRLF on stdout. SQLite

WRONG because:
adb shell
allocates a PTY and translates LF to CRLF on stdout. SQLite

headers and other binary content get corrupted. The pulled DB fails to open.

headers and other binary content get corrupted. The pulled DB fails to open.


```bash

```bash

RIGHT — exec-out is binary-clean

RIGHT — exec-out is binary-clean

adb exec-out run-as com.example cat databases/main.db > main.db
undefined
adb exec-out run-as com.example cat databases/main.db > main.db
undefined

Pattern: writing artefacts in-app, pulling from CI

模式:在应用内写入产物,并从 CI 拉取

kotlin
// In production / test code
val out = File(context.getExternalFilesDir(null), "captures/${name}.png")
out.outputStream().use { it.write(bitmapBytes) }
bash
undefined
kotlin
// In production / test code
val out = File(context.getExternalFilesDir(null), "captures/${name}.png")
out.outputStream().use { it.write(bitmapBytes) }
bash
undefined

CI script

CI script

adb pull /sdcard/Android/data/com.example/files/captures/ ./artifacts/

This works on API 30+ without `run-as` because `/sdcard/Android/data/<pkg>/files/` is the package's own external-private dir. Both the app and `adb shell` (FUSE bridge) can read it.
adb pull /sdcard/Android/data/com.example/files/captures/ ./artifacts/

该方式在 API 30+ 上无需 `run-as` 即可工作,因为 `/sdcard/Android/data/<pkg>/files/` 是包自己的外部私有目录。应用和 `adb shell`(通过 FUSE bridge)都可以读取该目录。

Pattern: fast incremental push of large test data

模式:快速增量推送大型测试数据

bash
adb push --sync -z brotli ./fixtures/ /sdcard/fixtures/
--sync
skips files with matching timestamps;
-z brotli
compresses the wire bytes. For a fixtures dir with hundreds of unchanged files, the second push transfers nothing.
bash
adb push --sync -z brotli ./fixtures/ /sdcard/fixtures/
--sync
会跳过时间戳相同的文件;
-z brotli
会压缩传输数据。对于包含数百个未变更文件的 fixtures 目录,第二次推送不会传输任何内容。

Pattern: capture-on-failure with
TestStorage

模式:使用
TestStorage
实现失败时捕获

kotlin
class CaptureOnFailureRule : TestWatcher() {
    override fun failed(e: Throwable, description: Description) {
        val storage = PlatformTestStorageRegistry.getInstance()
        val name = "${description.className}.${description.methodName}"
        storage.openOutputFile("captures/$name.png").use { out ->
            out.write(captureScreenshotPng())
        }
    }
}
After
connectedAndroidTest
, the artefact lands in
app/build/outputs/connected_android_test_additional_output/<flavor><Variant>/connected/<device>/captures/<name>.png
automatically.
kotlin
class CaptureOnFailureRule : TestWatcher() {
    override fun failed(e: Throwable, description: Description) {
        val storage = PlatformTestStorageRegistry.getInstance()
        val name = "${description.className}.${description.methodName}"
        storage.openOutputFile("captures/$name.png").use { out ->
            out.write(captureScreenshotPng())
        }
    }
}
执行
connectedAndroidTest
后,产物会自动出现在
app/build/outputs/connected_android_test_additional_output/<flavor><Variant>/connected/<device>/captures/<name>.png
。

Mandatory rules

强制规则

  • MUST use
    adb exec-out run-as <pkg> cat <path>
    (not
    adb shell run-as ...
    ) for binary file grabs. PTY translation corrupts binary on Windows and some CI hosts.
  • MUST use
    adb exec-out run-as <pkg> tar cf - <dir> | tar xf -
    for directory grabs from
    /data/data/<pkg>/
    . There is no
    adb pull
    equivalent that works through
    run-as
    .
  • MUST verify the build is debuggable before scripting
    run-as
    . On a release APK,
    run-as
    exits non-zero with "Package is not debuggable".
  • MUST prefer
    /sdcard/Android/data/<pkg>/files/
    (via
    Context.getExternalFilesDir(null)
    ) over arbitrary
    /sdcard/<dir>/
    for app-written test artefacts on API 30+. The latter is gated by MediaStore for app writes.
  • MUST prefer
    TestStorage
    (
    -e useTestStorageService true
    +
    androidx.test:services
    ) over hand-rolled
    /sdcard/...
    paths for new test infrastructure. It namespaces per-test artefacts and integrates with Gradle's
    connected_android_test_additional_output/
    sink.
  • MUST NOT rely on
    adb pull -p
    (show progress) — it is a legacy no-op on platform-tools 30+. Use the default progress meter (or
    -q
    to silence).
  • MUST NOT assume
    adb pull
    of
    /data/data/<pkg>/...
    works without
    run-as
    . It does not, even on debuggable builds —
    pull
    is a
    shell
    -user operation.
  • PREFERRED:
    --sync -z brotli
    for repeated pushes of large fixture sets. Brotli + timestamp-skip is dramatically faster on slow USB 2.0 cables.
  • PREFERRED: Test Orchestrator +
    clearPackageData: 'true'
    +
    useTestStorageService: 'true'
    for hermetic test isolation with retained artefacts.
  • 对于二进制文件获取,必须使用
    adb exec-out run-as <pkg> cat <path>
    ,而不是
    adb shell run-as ...
    。在 Windows 和部分 CI 主机上,PTY 转换会破坏二进制数据。
  • 从
    /data/data/<pkg>/
    获取目录时,必须使用
    adb exec-out run-as <pkg> tar cf - <dir> | tar xf -
    。不存在可通过
    run-as
    使用的等效
    adb pull
    命令。
  • 在脚本中使用
    run-as
    前,必须验证构建是否可调试。在 release APK 上,
    run-as
    会以非零状态退出,并输出“Package is not debuggable”。
  • 在 API 30+ 上,为应用写入的测试产物时,必须优先使用
    /sdcard/Android/data/<pkg>/files/
    (通过
    Context.getExternalFilesDir(null)
    ),而不是任意
    /sdcard/<dir>/
    路径。后者的应用写入受 MediaStore 限制。
  • 对于新的测试基础设施,必须优先使用
    TestStorage
    (
    -e useTestStorageService true
    +
    androidx.test:services
    ),而不是自行拼接
    /sdcard/...
    路径。它能够按测试划分产物命名空间,并与 Gradle 的
    connected_android_test_additional_output/
    接收目录集成。
  • 不得依赖
    adb pull -p
    (显示进度);在 platform-tools 30+ 上它已是旧版空操作。请使用默认进度条,或使用
    -q
    禁止输出。
  • 不得假设无需
    run-as
    即可对
    /data/data/<pkg>/...
    执行
    adb pull
    。即使在可调试构建上也无法执行,因为
    pull
    是以
    shell
    用户身份进行的操作。
  • 推荐:重复推送大型 fixture 集合时使用
    --sync -z brotli
    。在较慢的 USB 2.0 线缆上,Brotli 加时间戳跳过可显著提升速度。
  • 推荐:使用 Test Orchestrator +
    clearPackageData: 'true'
    +
    useTestStorageService: 'true'
    ,实现保留产物的密封式测试隔离。

Verification

验证

  • No script invokes
    adb pull /data/data/<pkg>/...
    directly. All such pulls go through
    run-as
    .
  • Binary-file pulls use
    adb exec-out
    , not
    adb shell
    .
  • All app-written test artefacts target
    Context.getExternalFilesDir(...)
    (lands at
    /sdcard/Android/data/<pkg>/files/
    ), not
    /sdcard/<arbitrary>/
    .
  • CI archives
    app/build/outputs/connected_android_test_additional_output/**/*
    for the modern artefact API.
  • Repeated pushes of the same fixture dir use
    adb push --sync
    so unchanged files are skipped.
  • file
    reports the correct binary type for every pulled artefact (no CRLF corruption).
  • Release APKs have no test code paths that try to
    adb pull
    from
    /data/data/<pkg>/...
    — those would fail.
  • 没有脚本直接调用
    adb pull /data/data/<pkg>/...
    。所有此类拉取操作都通过
    run-as
    完成。
  • 二进制文件拉取使用
    adb exec-out
    ,而不是
    adb shell
    。
  • 所有由应用写入的测试产物都指向
    Context.getExternalFilesDir(...)
    (位于
    /sdcard/Android/data/<pkg>/files/
    ),而不是
    /sdcard/<任意目录>/
    。
  • CI 会归档
    app/build/outputs/connected_android_test_additional_output/**/*
    ,以收集现代产物 API 生成的文件。
  • 重复推送同一 fixture 目录时使用
    adb push --sync
    ,从而跳过未变更的文件。
  • file
    为每个拉取的产物报告正确的二进制类型,不存在 CRLF 损坏。
  • Release APK 中不存在尝试从
    /data/data/<pkg>/...
    执行
    adb pull
    的测试代码路径,因为这些操作会失败。

References

参考资料

  • developer.android.com/tools/adb —
    pull
    /
    push
    syntax, "let you copy arbitrary directories and files to any location in a device" quote.
  • developer.android.com/studio/test/command-line — Gradle output dir conventions: HTML at
    module/build/reports/androidTests/connected/
    , XML at
    module/build/outputs/androidTest-results/connected/
    .
  • developer.android.com/training/data-storage/app-specific —
    Context.getExternalFilesDir()
    and the API-30+ scoped-storage rules.
  • developer.android.com/reference/androidx/test/services/storage/TestStorage — the modern artefact API.
  • developer.android.com/reference/androidx/test/platform/io/PlatformTestStorageRegistry — host-side handle.
  • Research note
    tasks/research/A3-adb-observability-automation.md
    — full pull/push surface, path permission rules, run-as patterns, scoped storage on Android 11+, TestStorage wiring.
  • Sibling skill:
    ../../architecture/understanding-adb-architecture/SKILL.md
    — server / daemon, exec-out vs shell.
  • Sibling skill:
    ../../devices/connecting-to-devices/SKILL.md
    —
    adb get-state
    , multi-device targeting.
  • Sibling skill:
    ../../devices/connecting-over-wifi/SKILL.md
    — wireless transport.
  • Sibling skill:
    ../../apps/installing-and-managing-apps/SKILL.md
    —
    pm install
    and the debuggable-build flag.
  • Sibling skill:
    ../../tests/running-instrumented-tests-via-adb/SKILL.md
    —
    am instrument
    arguments including
    useTestStorageService
    .
  • Sibling skill:
    ../../control/injecting-input-and-state/SKILL.md
    — driving the scenario that produces the artefact.
  • Sibling skill:
    ../../capture/capturing-screenshots-and-screenrecord/SKILL.md
    — producing PNG / MP4 to pull.
  • Sibling skill:
    ../../observability/extracting-logs-with-logcat/SKILL.md
    — pulling rotated log files via
    adb shell logcat -f
    +
    adb pull
    .
  • Sibling skill:
    ../../automation/scripting-adb-for-ci/SKILL.md
    — full CI orchestration.
  • Cross-set:
    ../../../instrumentation/runner/running-instrumented-tests-with-androidjunit4/SKILL.md
    —
    TestWatcher
    rules wired to
    TestStorage
    .
  • Cross-set:
    ../../../instrumentation/scenarios/launching-activities-with-activityscenario/SKILL.md
    — Activity-driven scenarios that emit artefacts.
  • Cross-set:
    ../../../fundamentals/strategies/applying-testing-strategies/SKILL.md
    — when artefacts are the right observability layer.
  • developer.android.com/tools/adb ——
    pull
    /
    push
    语法,以及“允许将任意目录和文件复制到设备中的任意位置”这句话。
  • developer.android.com/studio/test/command-line —— Gradle 输出目录约定:HTML 位于
    module/build/reports/androidTests/connected/
    ,XML 位于
    module/build/outputs/androidTest-results/connected/
    。
  • developer.android.com/training/data-storage/app-specific ——
    Context.getExternalFilesDir()
    和 API 30+ scoped storage 规则。
  • developer.android.com/reference/androidx/test/services/storage/TestStorage —— 现代产物 API。
  • developer.android.com/reference/androidx/test/platform/io/PlatformTestStorageRegistry —— 宿主端句柄。
  • 研究说明
    tasks/research/A3-adb-observability-automation.md
    —— 完整的 pull/push 功能范围、路径权限规则、run-as 模式、Android 11+ scoped storage 和 TestStorage 配置。
  • 同级 skill:
    ../../architecture/understanding-adb-architecture/SKILL.md
    —— server/daemon、exec-out 与 shell 的区别。
  • 同级 skill:
    ../../devices/connecting-to-devices/SKILL.md
    ——
    adb get-state
    和多设备定向。
  • 同级 skill:
    ../../devices/connecting-over-wifi/SKILL.md
    —— 无线传输。
  • 同级 skill:
    ../../apps/installing-and-managing-apps/SKILL.md
    ——
    pm install
    和可调试构建标志。
  • 同级 skill:
    ../../tests/running-instrumented-tests-via-adb/SKILL.md
    ——
    am instrument
    参数,包括
    useTestStorageService
    。
  • 同级 skill:
    ../../control/injecting-input-and-state/SKILL.md
    —— 驱动生成产物的测试场景。
  • 同级 skill:
    ../../capture/capturing-screenshots-and-screenrecord/SKILL.md
    —— 生成可供拉取的 PNG/MP4。
  • 同级 skill:
    ../../observability/extracting-logs-with-logcat/SKILL.md
    —— 通过
    adb shell logcat -f
    +
    adb pull
    拉取轮转日志文件。
  • 同级 skill:
    ../../automation/scripting-adb-for-ci/SKILL.md
    —— 完整的 CI 编排。
  • 跨集合:
    ../../../instrumentation/runner/running-instrumented-tests-with-androidjunit4/SKILL.md
    —— 接入
    TestStorage
    的
    TestWatcher
    规则。
  • 跨集合:
    ../../../instrumentation/scenarios/launching-activities-with-activityscenario/SKILL.md
    —— 生成产物的 Activity 驱动场景。
  • 跨集合:
    ../../../fundamentals/strategies/applying-testing-strategies/SKILL.md
    —— 确定何时应使用产物作为可观测性层。