printing-the-semantics-tree
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesePrinting the Semantics Tree — When a Finder Fails, Dump the Tree
打印 Semantics Tree——Finder 失败时转储树
onNodeWithTagThread.sleepprintToLogprintToStringonNodeWithTagThread.sleepprintToLogprintToStringWhen 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 and the developer is confused.
"…were found in the unmerged tree. If you really wanted to match against merged tree, use useUnmergedTree = true." - The developer is writing a custom matcher and needs direct access to a .
SemanticsNode - A test was fixed by adding — the underlying problem is a wrong tag, not a timing issue. Replace with this skill's pattern. See skydoves directive #7.
Thread.sleep
- 测试失败并出现 。
"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 - 测试通过添加 修复——底层问题是 tag 错误,而非时序问题。请改用本 skill 的模式。参见 skydoves 指令 #7。
Thread.sleep
When NOT to use this skill
何时不应使用此 skill
- The symptom is timing (animation has not finished, an idling resource is busy). Use or
../../synchronization/synchronizing-with-idle/SKILL.md.../../synchronization/testing-animations-deterministically/SKILL.md - The finder is wrong because the test searches by text instead of by tag. Fix with (skydoves directive #1).
../../finders/finding-nodes-by-tag-text-content/SKILL.md - 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 搜索。修复方式见 (skydoves 指令 #1)。
../../finders/finding-nodes-by-tag-text-content/SKILL.md - 诊断涉及无障碍违规,而不是节点查找。使用 。
../enabling-accessibility-checks/SKILL.md
Prerequisites
前置条件
- on
androidx.compose.ui:ui-testorandroidTestImplementation(the API lives intestImplementationso it is available in both source sets).commonMain - An active or
ComposeTestRule(no extra setup beyond the standard skeleton).ComposeUiTest
- 应位于
androidx.compose.ui:ui-test或androidTestImplementation中(该 API 位于testImplementation,因此两个 source set 中都可用)。commonMain - 已启用 或
ComposeTestRule(除标准骨架外无需额外设置)。ComposeUiTest
Workflow
工作流
- 1. When a finder fails, dump the merged tree first. Add the line right after (or right before the failing finder).
rule.setContent { … }
kotlin
rule.onRoot().printToLog("DEBUG")The signature is — full subtree by default for a single-node receiver. Cited at . View the output via .
fun SemanticsNodeInteraction.printToLog(tag: String, maxDepth: Int = Int.MAX_VALUE)compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/Output.kt:62-69adb 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 inside a ) only appear in the unmerged tree.
IconButton- 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:+ id + bounds + (optionally)
Node #.Tag: '<testTag>' -
Config entries are alphabetically sorted by key name.
-
and
AccessibilityActionvalues are summarized asFunction<*>.Actions = [keyName, …] -
values (e.g.
Unit,Disabled) are summarized asIsTraversalGroup.[Disabled, IsTraversalGroup, …] -
and
MergeDescendants = 'true'flags appear at the bottom of a node's block.ClearAndSetSemantics = 'true' -
4. Read the framework's built-in hint. Whenfinds 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
onNode(...). When the developer sees that, the fix is to flipcompose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/SemanticsNodeInteraction.kt:184-194on the failing finder. SeeuseUnmergedTree = truefor the merged/unmerged decision.../../finders/finding-nodes-by-tag-text-content/SKILL.md -
5. For custom matchers, use/
fetchSemanticsNodedirectly. These return the underlyingfetchSemanticsNodes(s) for direct introspection.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",
)Single-node signature: . Collection signature: .
fun fetchSemanticsNode(errorMessageOnFail: String? = null): SemanticsNodefun fetchSemanticsNodes(atLeastOneRootRequired: Boolean = true, errorMessageOnFail: String? = null): List<SemanticsNode>- 6. For collection finders, default is 0 (no children). Override when the developer wants the full subtree per match.
maxDepth
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 失败时,先转储合并后的树。 在 之后紧接下一行(或在失败的 Finder 之前)添加:
rule.setContent { … }
kotlin
rule.onRoot().printToLog("DEBUG")方法签名为 ——对于单节点 receiver,默认打印完整子树。代码位置:。可通过 查看输出。
fun SemanticsNodeInteraction.printToLog(tag: String, maxDepth: Int = Int.MAX_VALUE)compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/Output.kt:62-69adb logcat -s DEBUG- 2. 如果合并后的转储结果中没有预期节点,则转储未合并树。
kotlin
rule.onRoot(useUnmergedTree = true).printToLog("DEBUG")会合并子节点的 composable 的内部后代节点(例如 内的 )只会出现在未合并树中。
ButtonIcon- 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 " |-"-
首行包含、id、边界以及可选的
Node #。Tag: '<testTag>' -
Config 条目按 key 名称的字母顺序排列。
-
和
AccessibilityAction值会汇总为Function<*>。Actions = [keyName, …] -
值(例如
Unit、Disabled)会汇总为IsTraversalGroup。[Disabled, IsTraversalGroup, …] -
和
MergeDescendants = 'true'标志会出现在节点块的底部。ClearAndSetSemantics = 'true' -
4. 读取框架内置提示。 当在合并后的树中找不到匹配项,但同一 matcher 在未合并树中可以匹配时,错误消息会嵌入一个 "These nodes were found in the unmerged tree" 区块。代码位置:
onNode(...)。当开发者看到该提示时,应在失败的 Finder 上将compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/SemanticsNodeInteraction.kt:184-194。有关合并树与未合并树的选择,参见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): SemanticsNodefun fetchSemanticsNodes(atLeastOneRootRequired: Boolean = true, errorMessageOnFail: String? = null): List<SemanticsNode>- 6. 对于集合 Finder,默认 为 0(不包含子节点)。 当开发者需要查看每个匹配项的完整子树时,应覆盖此值。
maxDepth
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 reportPatterns
模式
Pattern: Thread.sleep
to "wait for the node" instead of dumping the tree
Thread.sleep模式:用 Thread.sleep
“等待节点”,而不是转储树
Thread.sleepkotlin
// 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模式:使用 fetchSemanticsNode
进行自定义断言
fetchSemanticsNodekotlin
// 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 (or the unmerged variant) the moment a finder fails. The default
rule.onRoot().printToLog("DEBUG")for a single-node receiver ismaxDepth, so the full subtree is printed without further configuration. Cited atInt.MAX_VALUE.Output.kt:43, 65 - MUST read the framework hint as a directive — flip
"…were found in the unmerged tree. If you really wanted to match against merged tree, use useUnmergedTree = true."on the failing finder. Cited atuseUnmergedTree = true.SemanticsNodeInteraction.kt:184-194 - MUST NOT add 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.
Thread.sleep(…) - MUST override to a non-zero value when calling
maxDepthon aprintToLog— the collection default isSemanticsNodeInteractionCollection(no children). Cited at0.Output.kt:85, 112 - PREFERRED: start the diagnosis with the merged tree, then escalate to only if the expected node is collapsed. Skydoves directive #2: keep
useUnmergedTree = trueby default.useUnmergedTree = false - PREFERRED: for custom matchers, prefer so the failure message identifies the test, not just the assertion line.
fetchSemanticsNode(errorMessageOnFail = "…")
- MUST 在 Finder 失败的那一刻,使用 (或未合并变体)转储 Semantics Tree。单节点 receiver 的默认
rule.onRoot().printToLog("DEBUG")为maxDepth,因此无需额外配置即可打印完整子树。代码位置:Int.MAX_VALUE。Output.kt:43, 65 - MUST 将框架提示 视为明确指令——在失败的 Finder 上切换为
"…were found in the unmerged tree. If you really wanted to match against merged tree, use useUnmergedTree = true."。代码位置:useUnmergedTree = true。SemanticsNodeInteraction.kt:184-194 - MUST NOT 添加 来“让树有时间加载”。Finder 失败属于结构性问题;延长墙钟时间不会生成节点。Skydoves 指令 #7。唯一合理的用途是等待截图或 RenderThread。
Thread.sleep(…) - MUST 对 调用
SemanticsNodeInteractionCollection时,将printToLog覆盖为非零值——集合默认值为maxDepth(不包含子节点)。代码位置:0。Output.kt:85, 112 - PREFERRED: 诊断时先从合并后的树开始,只有当预期节点被折叠时,才升级为 。Skydoves 指令 #2:默认保持
useUnmergedTree = true。useUnmergedTree = false - PREFERRED: 对于自定义 matcher,优先使用 ,使失败消息能够标识具体测试,而不只是显示断言所在行。
fetchSemanticsNode(errorMessageOnFail = "…")
Verification
验证
- When a finder fails, the test (or the agent's interactive debugging) emits at least one line for the relevant subtree.
printToLog("DEBUG") - No was added to fix a finder problem.
Thread.sleep - If the dump shows the node only under , the finder has been updated to pass that flag.
useUnmergedTree = true - If multiple matches were found, the finder has been narrowed (via ,
filterToOne, a parenthasAnyAncestor, etc.) — not by adding sleep or assert-attempts.testTag - Custom matchers use with a meaningful diagnostic message.
fetchSemanticsNode(errorMessageOnFail = "…") - In CI, the test logs include the dump output (developer collects logcat for the test process).
- Finder 失败时,测试(或 Agent 的交互式调试)会针对相关子树至少输出一行 。
printToLog("DEBUG") - 未添加 来修复 Finder 问题。
Thread.sleep - 如果转储结果仅在 下显示节点,则 Finder 已更新为传入该标志。
useUnmergedTree = true - 如果找到多个匹配项,则 Finder 已通过 、
filterToOne、父级hasAnyAncestor等方式收窄,而不是添加 sleep 或尝试断言。testTag - 自定义 matcher 使用 ,并提供有意义的诊断消息。
fetchSemanticsNode(errorMessageOnFail = "…") - 在 CI 中,测试日志包含转储输出(开发者会收集测试进程的 logcat)。
References
参考资料
- /
printToLogsource:printToStringcompose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/Output.kt:41-116 - Output grammar (rect, sorted config, actions, flags):
compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/Output.kt:135-296 - "Found in the unmerged tree" hint:
compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/SemanticsNodeInteraction.kt:178-194 - signature:
fetchSemanticsNode(s)compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/SemanticsNodeInteraction.kt - Semantics in Compose: https://developer.android.com/develop/ui/compose/accessibility/semantics
- Compose testing — finders: https://developer.android.com/develop/ui/compose/testing#finders
- Compose testing cheat sheet: https://developer.android.com/develop/ui/compose/testing-cheatsheet
- /
printToLog源码:printToStringcompose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/Output.kt:41-116 - 输出语法(矩形、排序后的 config、actions、flags):
compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/Output.kt:135-296 - “Found in the unmerged tree” 提示:
compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/SemanticsNodeInteraction.kt:178-194 - 方法签名:
fetchSemanticsNode(s)compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/SemanticsNodeInteraction.kt - Compose 中的 Semantics:https://developer.android.com/develop/ui/compose/accessibility/semantics
- Compose 测试——Finder:https://developer.android.com/develop/ui/compose/testing#finders
- Compose 测试速查表:https://developer.android.com/develop/ui/compose/testing-cheatsheet