printing-the-semantics-tree

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Printing the Semantics Tree — When a Finder Fails, Dump the Tree

打印 Semantics Tree——Finder 失败时转储树

onNodeWithTag
failures are structural — the tag is wrong, the matcher is on the merged tree but the tag is on a leaf, or the node is genuinely not composed yet. None of those are timing problems, so
Thread.sleep
does nothing. This skill teaches the agent to diagnose finder failures by dumping the semantics tree with
printToLog
/
printToString
and reading the framework's built-in "found in the unmerged tree" hint.
onNodeWithTag
失败属于结构性问题——tag 不正确、matcher 作用于合并后的树但 tag 实际位于叶节点上,或者节点确实尚未完成组合。这些都不是时序问题,因此
Thread.sleep
无效。本 skill 教 Agent 通过
printToLog
/
printToString
转储 Semantics Tree,并读取框架内置的 "found in the unmerged tree" 提示,来诊断 Finder 失败。

When to use this skill

何时使用此 skill

  • The test fails with
    "Failed: assertExists. Reason: Expected exactly '1' node but could not find any node that satisfies: …"
    .
  • The test fails with
    "Reason: Expected exactly '1' node but found 'N' nodes that satisfy: …"
    .
  • The error message ends with
    "…were found in the unmerged tree. If you really wanted to match against merged tree, use useUnmergedTree = true."
    and the developer is confused.
  • The developer is writing a custom matcher and needs direct access to a
    SemanticsNode
    .
  • A test was fixed by adding
    Thread.sleep
    — the underlying problem is a wrong tag, not a timing issue. Replace with this skill's pattern. See skydoves directive #7.
  • 测试失败并出现
    "Failed: assertExists. Reason: Expected exactly '1' node but could not find any node that satisfies: …"
    。
  • 测试失败并出现
    "Reason: Expected exactly '1' node but found 'N' nodes that satisfy: …"
    。
  • 错误消息以
    "…were found in the unmerged tree. If you really wanted to match against merged tree, use useUnmergedTree = true."
    结尾,而开发者对此感到困惑。
  • 开发者正在编写自定义 matcher,需要直接访问
    SemanticsNode
    。
  • 测试通过添加
    Thread.sleep
    修复——底层问题是 tag 错误,而非时序问题。请改用本 skill 的模式。参见 skydoves 指令 #7。

When NOT to use this skill

何时不应使用此 skill

  • The symptom is timing (animation has not finished, an idling resource is busy). Use
    ../../synchronization/synchronizing-with-idle/SKILL.md
    or
    ../../synchronization/testing-animations-deterministically/SKILL.md
    .
  • The finder is wrong because the test searches by text instead of by tag. Fix with
    ../../finders/finding-nodes-by-tag-text-content/SKILL.md
    (skydoves directive #1).
  • The diagnosis involves accessibility violations rather than node lookup. Use
    ../enabling-accessibility-checks/SKILL.md
    .
  • 症状属于时序问题(动画尚未结束,空闲资源仍在忙碌)。使用
    ../../synchronization/synchronizing-with-idle/SKILL.md
    或
    ../../synchronization/testing-animations-deterministically/SKILL.md
    。
  • Finder 错误是因为测试按文本而非 tag 搜索。修复方式见
    ../../finders/finding-nodes-by-tag-text-content/SKILL.md
    (skydoves 指令 #1)。
  • 诊断涉及无障碍违规,而不是节点查找。使用
    ../enabling-accessibility-checks/SKILL.md
    。

Prerequisites

前置条件

  • androidx.compose.ui:ui-test
    on
    androidTestImplementation
    or
    testImplementation
    (the API lives in
    commonMain
    so it is available in both source sets).
  • An active
    ComposeTestRule
    or
    ComposeUiTest
    (no extra setup beyond the standard skeleton).
  • androidx.compose.ui:ui-test
    应位于
    androidTestImplementation
    或
    testImplementation
    中(该 API 位于
    commonMain
    ,因此两个 source set 中都可用)。
  • 已启用
    ComposeTestRule
    或
    ComposeUiTest
    (除标准骨架外无需额外设置)。

Workflow

工作流

  • 1. When a finder fails, dump the merged tree first. Add the line right after
    rule.setContent { … }
    (or right before the failing finder).
kotlin
rule.onRoot().printToLog("DEBUG")
The signature is
fun SemanticsNodeInteraction.printToLog(tag: String, maxDepth: Int = Int.MAX_VALUE)
— full subtree by default for a single-node receiver. Cited at
compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/Output.kt:62-69
. View the output via
adb logcat -s DEBUG
.
  • 2. If the merged dump does not show the expected node, dump the unmerged tree.
kotlin
rule.onRoot(useUnmergedTree = true).printToLog("DEBUG")
Inner descendants of merging composables (e.g. an
Icon
inside a
Button
) only appear in the unmerged tree.
  • 3. Read the output grammar. The format is fixed by
    Output.kt:135-296
    :
Node #<id> at (l=<L>, t=<T>, r=<R>, b=<B>)px, Tag: '<tag>'
  <Sorted ConfigKey> = '<value>'
  ...
  [<FlagKey1>, <FlagKey2>]            // keys whose value is Unit
  Actions = [<ActionKey1>, ...]        // AccessibilityActions and Function values
  MergeDescendants = 'true'            // when isMergingSemanticsOfDescendants
  ClearAndSetSemantics = 'true'        // when isClearingSemantics
   |-Node #<childId> at (...)px        // children indented with " |-"
  • Top line:
    Node #
    + id + bounds + (optionally)
    Tag: '<testTag>'
    .
  • Config entries are alphabetically sorted by key name.
  • AccessibilityAction
    and
    Function<*>
    values are summarized as
    Actions = [keyName, …]
    .
  • Unit
    values (e.g.
    Disabled
    ,
    IsTraversalGroup
    ) are summarized as
    [Disabled, IsTraversalGroup, …]
    .
  • MergeDescendants = 'true'
    and
    ClearAndSetSemantics = 'true'
    flags appear at the bottom of a node's block.
  • 4. Read the framework's built-in hint. When
    onNode(...)
    finds zero matches in the merged tree but the same matcher would have matched in the unmerged tree, the error message embeds a "These nodes were found in the unmerged tree" block. Cited at
    compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/SemanticsNodeInteraction.kt:184-194
    . When the developer sees that, the fix is to flip
    useUnmergedTree = true
    on the failing finder. See
    ../../finders/finding-nodes-by-tag-text-content/SKILL.md
    for the merged/unmerged decision.
  • 5. For custom matchers, use
    fetchSemanticsNode
    /
    fetchSemanticsNodes
    directly.
    These return the underlying
    SemanticsNode
    (s) for direct introspection.
kotlin
val node = rule.onNodeWithTag("title").fetchSemanticsNode()
assertThat(node.config[SemanticsProperties.Text]).isNotEmpty()

val all = rule.onAllNodesWithTag("row").fetchSemanticsNodes(
    atLeastOneRootRequired = true,
    errorMessageOnFail = "expected at least one row",
)
Single-node signature:
fun fetchSemanticsNode(errorMessageOnFail: String? = null): SemanticsNode
. Collection signature:
fun fetchSemanticsNodes(atLeastOneRootRequired: Boolean = true, errorMessageOnFail: String? = null): List<SemanticsNode>
.
  • 6. For collection finders, default
    maxDepth
    is 0 (no children).
    Override when the developer wants the full subtree per match.
kotlin
rule.onAllNodesWithTag("row").printToLog("DEBUG", maxDepth = Int.MAX_VALUE)
Cited at
Output.kt:83-116
.
  • 7. Capture the dump as a String for assertion-based debugging. Useful in CI logs.
kotlin
val tree = rule.onRoot(useUnmergedTree = true).printToString()
println(tree) // or attach to a test report
  • 1. Finder 失败时,先转储合并后的树。 在
    rule.setContent { … }
    之后紧接下一行(或在失败的 Finder 之前)添加:
kotlin
rule.onRoot().printToLog("DEBUG")
方法签名为
fun SemanticsNodeInteraction.printToLog(tag: String, maxDepth: Int = Int.MAX_VALUE)
——对于单节点 receiver,默认打印完整子树。代码位置:
compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/Output.kt:62-69
。可通过
adb logcat -s DEBUG
查看输出。
  • 2. 如果合并后的转储结果中没有预期节点,则转储未合并树。
kotlin
rule.onRoot(useUnmergedTree = true).printToLog("DEBUG")
会合并子节点的 composable 的内部后代节点(例如
Button
内的
Icon
)只会出现在未合并树中。
  • 3. 读取输出语法。 格式由
    Output.kt:135-296
    固定:
Node #<id> at (l=<L>, t=<T>, r=<R>, b=<B>)px, Tag: '<tag>'
  <Sorted ConfigKey> = '<value>'
  ...
  [<FlagKey1>, <FlagKey2>]            // keys whose value is Unit
  Actions = [<ActionKey1>, ...]        // AccessibilityActions and Function values
  MergeDescendants = 'true'            // when isMergingSemanticsOfDescendants
  ClearAndSetSemantics = 'true'        // when isClearingSemantics
   |-Node #<childId> at (...)px        // children indented with " |-"
  • 首行包含
    Node #
    、id、边界以及可选的
    Tag: '<testTag>'
    。
  • Config 条目按 key 名称的字母顺序排列。
  • AccessibilityAction
    和
    Function<*>
    值会汇总为
    Actions = [keyName, …]
    。
  • Unit
    值(例如
    Disabled
    、
    IsTraversalGroup
    )会汇总为
    [Disabled, IsTraversalGroup, …]
    。
  • MergeDescendants = 'true'
    和
    ClearAndSetSemantics = 'true'
    标志会出现在节点块的底部。
  • 4. 读取框架内置提示。 当
    onNode(...)
    在合并后的树中找不到匹配项,但同一 matcher 在未合并树中可以匹配时,错误消息会嵌入一个 "These nodes were found in the unmerged tree" 区块。代码位置:
    compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/SemanticsNodeInteraction.kt:184-194
    。当开发者看到该提示时,应在失败的 Finder 上将
    useUnmergedTree = true
    。有关合并树与未合并树的选择,参见
    ../../finders/finding-nodes-by-tag-text-content/SKILL.md
    。
  • 5. 对于自定义 matcher,直接使用
    fetchSemanticsNode
    /
    fetchSemanticsNodes
    。
    这些方法返回底层的
    SemanticsNode
    ,便于直接检查。
kotlin
val node = rule.onNodeWithTag("title").fetchSemanticsNode()
assertThat(node.config[SemanticsProperties.Text]).isNotEmpty()

val all = rule.onAllNodesWithTag("row").fetchSemanticsNodes(
    atLeastOneRootRequired = true,
    errorMessageOnFail = "expected at least one row",
)
单节点方法签名:
fun fetchSemanticsNode(errorMessageOnFail: String? = null): SemanticsNode
。集合方法签名:
fun fetchSemanticsNodes(atLeastOneRootRequired: Boolean = true, errorMessageOnFail: String? = null): List<SemanticsNode>
。
  • 6. 对于集合 Finder,默认
    maxDepth
    为 0(不包含子节点)。
    当开发者需要查看每个匹配项的完整子树时,应覆盖此值。
kotlin
rule.onAllNodesWithTag("row").printToLog("DEBUG", maxDepth = Int.MAX_VALUE)
代码位置:
Output.kt:83-116
。
  • 7. 将转储结果捕获为 String,以便基于断言进行调试。 这在 CI 日志中很有用。
kotlin
val tree = rule.onRoot(useUnmergedTree = true).printToString()
println(tree) // or attach to a test report

Patterns

模式

Pattern:
Thread.sleep
to "wait for the node" instead of dumping the tree

模式:用
Thread.sleep
“等待节点”,而不是转储树

kotlin
// WRONG
@Test
fun appears() {
    rule.setContent { MyScreen() }
    Thread.sleep(2000)                                    // hide the symptom
    rule.onNodeWithTag("submit").assertIsDisplayed()      // still fails
}
// WRONG because: Thread.sleep desyncs from MainTestClock and does not advance composition.
// If the node is missing, more wall time will not produce it. The cause is structural.
// Skydoves directive #7: Thread.sleep is a smell.
kotlin
// RIGHT
@Test
fun appears() {
    rule.setContent { MyScreen() }
    rule.onRoot(useUnmergedTree = true).printToLog("DEBUG")   // see what's actually present
    rule.onNodeWithTag("submit").assertIsDisplayed()
}
kotlin
// WRONG
@Test
fun appears() {
    rule.setContent { MyScreen() }
    Thread.sleep(2000)                                    // hide the symptom
    rule.onNodeWithTag("submit").assertIsDisplayed()      // still fails
}
// WRONG because: Thread.sleep desyncs from MainTestClock and does not advance composition.
// If the node is missing, more wall time will not produce it. The cause is structural.
// Skydoves directive #7: Thread.sleep is a smell.
kotlin
// RIGHT
@Test
fun appears() {
    rule.setContent { MyScreen() }
    rule.onRoot(useUnmergedTree = true).printToLog("DEBUG")   // see what's actually present
    rule.onNodeWithTag("submit").assertIsDisplayed()
}

Pattern: "found in the unmerged tree" hint

模式:“found in the unmerged tree” 提示

kotlin
// WRONG — the test ignores the framework hint
@Test
fun iconExists() {
    rule.setContent { Button(onClick = {}) { Icon(Icons.Default.Add, modifier = Modifier.testTag("add-icon")) } }
    rule.onNodeWithTag("add-icon").assertExists()
    // AssertionError: ... 0 matches.
    // These nodes were found in the unmerged tree:
    //   Node #4 ... Tag: 'add-icon'
    // If you really wanted to match against merged tree, use useUnmergedTree = true.
}
// WRONG because: a Button merges descendants. The Icon's tag is collapsed into the Button
// node in the merged tree. The error message names the fix in plain English.
kotlin
// RIGHT
@Test
fun iconExists() {
    rule.setContent { Button(onClick = {}) { Icon(Icons.Default.Add, modifier = Modifier.testTag("add-icon")) } }
    rule.onNodeWithTag("add-icon", useUnmergedTree = true).assertExists()
}
kotlin
// WRONG — the test ignores the framework hint
@Test
fun iconExists() {
    rule.setContent { Button(onClick = {}) { Icon(Icons.Default.Add, modifier = Modifier.testTag("add-icon")) } }
    rule.onNodeWithTag("add-icon").assertExists()
    // AssertionError: ... 0 matches.
    // These nodes were found in the unmerged tree:
    //   Node #4 ... Tag: 'add-icon'
    // If you really wanted to match against merged tree, use useUnmergedTree = true.
}
// WRONG because: a Button merges descendants. The Icon's tag is collapsed into the Button
// node in the merged tree. The error message names the fix in plain English.
kotlin
// RIGHT
@Test
fun iconExists() {
    rule.setContent { Button(onClick = {}) { Icon(Icons.Default.Add, modifier = Modifier.testTag("add-icon")) } }
    rule.onNodeWithTag("add-icon", useUnmergedTree = true).assertExists()
}

Pattern: ambiguous "found 3 nodes" — disambiguate via dump

模式:“found 3 nodes” 匹配歧义——通过转储消除歧义

kotlin
// WRONG
rule.onNodeWithTag("row").assertIsDisplayed()
// AssertionError: Reason: Expected exactly '1' node but found '3' nodes that satisfy:
// (TestTag = 'row')
kotlin
// RIGHT — dump first, then narrow the matcher
rule.onAllNodesWithTag("row").printToLog("DEBUG", maxDepth = Int.MAX_VALUE)
// Read the dump to find a stable disambiguator (e.g. parent tag, contentDescription),
// then narrow:
rule.onAllNodesWithTag("row")
    .filterToOne(hasAnyAncestor(hasTestTag("section-completed")))
    .assertIsDisplayed()
kotlin
// WRONG
rule.onNodeWithTag("row").assertIsDisplayed()
// AssertionError: Reason: Expected exactly '1' node but found '3' nodes that satisfy:
// (TestTag = 'row')
kotlin
// RIGHT — dump first, then narrow the matcher
rule.onAllNodesWithTag("row").printToLog("DEBUG", maxDepth = Int.MAX_VALUE)
// Read the dump to find a stable disambiguator (e.g. parent tag, contentDescription),
// then narrow:
rule.onAllNodesWithTag("row")
    .filterToOne(hasAnyAncestor(hasTestTag("section-completed")))
    .assertIsDisplayed()

Pattern:
fetchSemanticsNode
for custom assertions

模式:使用
fetchSemanticsNode
进行自定义断言

kotlin
// RIGHT
@Test
fun rowConfigContainsCustomKey() {
    rule.setContent { /* … */ }
    val node = rule.onNodeWithTag("row").fetchSemanticsNode("missing 'row'")
    val custom: String? = node.config.getOrNull(MyCustomKey)
    assertThat(custom).isEqualTo("expected")
}
kotlin
// RIGHT
@Test
fun rowConfigContainsCustomKey() {
    rule.setContent { /* … */ }
    val node = rule.onNodeWithTag("row").fetchSemanticsNode("missing 'row'")
    val custom: String? = node.config.getOrNull(MyCustomKey)
    assertThat(custom).isEqualTo("expected")
}

Mandatory rules

强制规则

  • MUST dump the semantics tree with
    rule.onRoot().printToLog("DEBUG")
    (or the unmerged variant) the moment a finder fails. The default
    maxDepth
    for a single-node receiver is
    Int.MAX_VALUE
    , so the full subtree is printed without further configuration. Cited at
    Output.kt:43, 65
    .
  • MUST read the framework hint
    "…were found in the unmerged tree. If you really wanted to match against merged tree, use useUnmergedTree = true."
    as a directive — flip
    useUnmergedTree = true
    on the failing finder. Cited at
    SemanticsNodeInteraction.kt:184-194
    .
  • MUST NOT add
    Thread.sleep(…)
    to "give the tree time to load". A finder failure is structural; more wall time does not produce the node. Skydoves directive #7. The single legitimate use is screenshot/RenderThread waits.
  • MUST override
    maxDepth
    to a non-zero value when calling
    printToLog
    on a
    SemanticsNodeInteractionCollection
    — the collection default is
    0
    (no children). Cited at
    Output.kt:85, 112
    .
  • PREFERRED: start the diagnosis with the merged tree, then escalate to
    useUnmergedTree = true
    only if the expected node is collapsed. Skydoves directive #2: keep
    useUnmergedTree = false
    by default.
  • PREFERRED: for custom matchers, prefer
    fetchSemanticsNode(errorMessageOnFail = "…")
    so the failure message identifies the test, not just the assertion line.
  • MUST 在 Finder 失败的那一刻,使用
    rule.onRoot().printToLog("DEBUG")
    (或未合并变体)转储 Semantics Tree。单节点 receiver 的默认
    maxDepth
    为
    Int.MAX_VALUE
    ,因此无需额外配置即可打印完整子树。代码位置:
    Output.kt:43, 65
    。
  • MUST 将框架提示
    "…were found in the unmerged tree. If you really wanted to match against merged tree, use useUnmergedTree = true."
    视为明确指令——在失败的 Finder 上切换为
    useUnmergedTree = true
    。代码位置:
    SemanticsNodeInteraction.kt:184-194
    。
  • MUST NOT 添加
    Thread.sleep(…)
    来“让树有时间加载”。Finder 失败属于结构性问题;延长墙钟时间不会生成节点。Skydoves 指令 #7。唯一合理的用途是等待截图或 RenderThread。
  • MUST 对
    SemanticsNodeInteractionCollection
    调用
    printToLog
    时,将
    maxDepth
    覆盖为非零值——集合默认值为
    0
    (不包含子节点)。代码位置:
    Output.kt:85, 112
    。
  • PREFERRED: 诊断时先从合并后的树开始,只有当预期节点被折叠时,才升级为
    useUnmergedTree = true
    。Skydoves 指令 #2:默认保持
    useUnmergedTree = false
    。
  • PREFERRED: 对于自定义 matcher,优先使用
    fetchSemanticsNode(errorMessageOnFail = "…")
    ,使失败消息能够标识具体测试,而不只是显示断言所在行。

Verification

验证

  • When a finder fails, the test (or the agent's interactive debugging) emits at least one
    printToLog("DEBUG")
    line for the relevant subtree.
  • No
    Thread.sleep
    was added to fix a finder problem.
  • If the dump shows the node only under
    useUnmergedTree = true
    , the finder has been updated to pass that flag.
  • If multiple matches were found, the finder has been narrowed (via
    filterToOne
    ,
    hasAnyAncestor
    , a parent
    testTag
    , etc.) — not by adding sleep or assert-attempts.
  • Custom matchers use
    fetchSemanticsNode(errorMessageOnFail = "…")
    with a meaningful diagnostic message.
  • In CI, the test logs include the dump output (developer collects logcat for the test process).
  • Finder 失败时,测试(或 Agent 的交互式调试)会针对相关子树至少输出一行
    printToLog("DEBUG")
    。
  • 未添加
    Thread.sleep
    来修复 Finder 问题。
  • 如果转储结果仅在
    useUnmergedTree = true
    下显示节点,则 Finder 已更新为传入该标志。
  • 如果找到多个匹配项,则 Finder 已通过
    filterToOne
    、
    hasAnyAncestor
    、父级
    testTag
    等方式收窄,而不是添加 sleep 或尝试断言。
  • 自定义 matcher 使用
    fetchSemanticsNode(errorMessageOnFail = "…")
    ,并提供有意义的诊断消息。
  • 在 CI 中,测试日志包含转储输出(开发者会收集测试进程的 logcat)。

References

参考资料