Files
pacs_win_uia/tests/regression/PathTests.cs
T
zimoyin 66ab309939 给全部源码补中文注释,并新增代码导览
- 67 个 .cs 文件加中文注释:每个文件顶部说明职责/调用方/线程与节拍/
  已知限制/「要改什么就改哪里」,字段与方法逐条一行说明,复杂逻辑内插关键步骤
- 纯注释改动:脚本校验所有新增行都是注释、无非注释改动(仅 2 个文件的 BOM
  随新头部注释下移,文件仍以 BOM 开头)
- 新增 docs/代码导览.md:模块地图、「我要改 X 看哪个文件」对照表、易踩的坑、
  悬浮条显示规则、测试与验收指引
- 编译通过,回归测试 23/23 通过

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-10-13 15:44:15 +08:00

229 lines
15 KiB
C#

// =====================================================================================
// PathTests —— XPath 定位的解析 / 生成 / 转义 / 歧义 / 拒绝 回归。
//
// 覆盖范围:ControlPath 的 Select / SelectUnique / Build / PreparePaths / Quote /
// ValidateSyntax,以及 ControlLocatorBuilder 与 ControlLocatorService.ResolveFromTree
// 的端到端行为。
//
// 为什么这样测:全部跑在纯内存 ControlTreeNode 快照(TreeFixture)上,
// 不触碰真实 UIA / HWND / provider——UIA 自读本进程会崩溃,这里根本不需要它。
//
// 新增用例:在 Register(...) 的列表里加一行「用例名 → 委托」,再在本类实现一个
// private static void 方法;断言统一用 Check.Matches / Rejected / Equal / Same。
// =====================================================================================
using System;
using System.Collections.Generic;
using pacs_win_uia.Models;
using pacs_win_uia.Services;
namespace PacsWinUia.RegressionTests
{
internal static class PathTests
{
public static void Register(IList<KeyValuePair<string, Action>> tests)
{
// 防:XPath 属性 / contains / 轴 / 位置谓词解析回归。
tests.Add(new KeyValuePair<string, Action>("XPath attributes, contains, axes and positional predicates", XPathQueries));
// 防:重复 AutomationId 与结构序号导致路径不唯一、roundtrip 丢节点。
tests.Add(new KeyValuePair<string, Action>("All nodes roundtrip with duplicate IDs and structural indices", AllNodesRoundtrip));
// 防:祖先 Name 变化后生成路径失效(生成路径不得依赖可变的 Name)。
tests.Add(new KeyValuePair<string, Action>("Generated paths survive names changing on every ancestor", ChangingNames));
// 防:ClassName 兜底与「稳定祖先锚定」能力丢失。
tests.Add(new KeyValuePair<string, Action>("Class-qualified paths and stable ancestor anchors", ClassAndAnchor));
// 防:含单双引号 / 斜杠 / 中文的名称转义错误。
tests.Add(new KeyValuePair<string, Action>("XPath quoting for both quotes, slash and Chinese", Escaping));
// 防:旧显示格式 / 结构化旧路径被当作 XPath 执行。
tests.Add(new KeyValuePair<string, Action>("Old display and structured paths are not executed", RejectLegacy));
// 防:非法 / 标量 / 属性型 XPath 被静默接受。
tests.Add(new KeyValuePair<string, Action>("Invalid, scalar and attribute XPath rejected", RejectedPaths));
// 防:歧义路径被武断解析成第一个节点。
tests.Add(new KeyValuePair<string, Action>("Ambiguity never resolves to an arbitrary first node", AmbiguousPaths));
// 防:陈旧的 RuntimeId / locator 提示反过来覆盖当前 XPath。
tests.Add(new KeyValuePair<string, Action>("Changed XPath is authoritative over stale locator hints", AuthoritativeXPath));
// 防:根节点、外部节点、不完整快照等边界处理回归。
tests.Add(new KeyValuePair<string, Action>("Root, outsider and incomplete snapshot handling", RootAndIncomplete));
// 防:XPath 解析丢失 MSAA / Win32 载荷或来源标记。
tests.Add(new KeyValuePair<string, Action>("XPath resolution preserves MSAA and Win32 payloads", OtherSources));
}
private static void XPathQueries()
{
var f = new TreeFixture();
Check.Matches(f.Root, "/Window[1]", f.Root);
Check.Matches(f.Root, "//ListItem[@Name='个性化']", f.MenuItem);
Check.Matches(f.Root, "//*[@AutomationId='PermanentNavigationView']", f.Navigation);
Check.Matches(f.Root, "//Button[@ClassName='SecondaryButton']", f.SecondDuplicate);
Check.Matches(f.Root, "//Button[contains(@Name,'重') and @AutomationId='same-id']", f.FirstDuplicate, f.SecondDuplicate);
Check.Matches(f.Root, "//Button[@Name='重复'][2]", f.SecondDuplicate);
Check.Matches(f.Root, "(//Button[@AutomationId='same-id'])[1]", f.FirstDuplicate);
Check.Matches(f.Root, "//Group[@AutomationId='Duplicates']/Button[3]", f.SecondDuplicate);
Check.Matches(f.Root, "//Group[@AutomationId='PermanentNavigationViewBreadcrumbBar']/Button/Text", f.BreadcrumbText);
Check.Matches(f.Root, "//Group[@AutomationId='MenuItemsHost']/ListItem[1]", f.MenuItem);
Check.Rejected(f.Root, "//Button[@Name='重复'][0]");
Check.Rejected(f.Root, "/Window/ListItem[@Name='个性化']");
}
private static void AllNodesRoundtrip()
{
var f = new TreeFixture();
var builder = new ControlLocatorBuilder();
var window = new NativeWindowInfo(IntPtr.Zero) { ProcessName = "fixture", ClassName = "RootClass", Title = "设置" };
ControlPath.PreparePaths(f.Root);
var unique = new HashSet<string>(StringComparer.Ordinal);
foreach (ControlTreeNode node in TreeFixture.All(f.Root))
{
string path = ControlPath.Build(f.Root, node);
Check.True(path.StartsWith("/Window[1]", StringComparison.Ordinal), "Root must not depend on window title");
Check.True(path.IndexOf("@Name", StringComparison.Ordinal) < 0, "Generated path depends on a mutable Name");
Check.True(unique.Add(path), "Two nodes share a path: " + path);
Check.Matches(f.Root, path, node);
ControlLocatorBuildResult built = builder.BuildFromTree(f.Root, node, window);
Check.True(built.IsComplete, "Builder incomplete: " + built.Note);
Check.Equal(path, built.DisplayPath, "Builder path differs");
var resolved = ControlLocatorService.ResolveFromTree(new ControlMonitorDefinition { ControlPath = path, Source = ControlSourcePreference.Uia }, f.Root, IntPtr.Zero);
Check.True(resolved.Found, "Resolver failed: " + resolved.Error);
Check.Same(node, resolved.Node, "Resolver must return original node");
}
Check.True(f.FirstDuplicate.CanonicalPath.EndsWith("Button[@AutomationId='same-id'][1]", StringComparison.Ordinal), "Duplicate ID first ordinal");
Check.True(f.SecondDuplicate.CanonicalPath.EndsWith("Button[@AutomationId='same-id'][2]", StringComparison.Ordinal), "Duplicate ID second ordinal");
}
private static void ChangingNames()
{
var f = new TreeFixture();
var original = new Dictionary<ControlTreeNode, string>();
ControlPath.PreparePaths(f.Root);
foreach (ControlTreeNode node in TreeFixture.All(f.Root)) original.Add(node, node.CanonicalPath);
foreach (ControlTreeNode node in TreeFixture.All(f.Root)) node.Uia.Name = "动态患者/状态 '变化' \"中文\"";
ControlPath.PreparePaths(f.Root);
foreach (var item in original)
{
Check.Equal(item.Value, item.Key.CanonicalPath, "Name change invalidated path");
Check.Matches(f.Root, item.Value, item.Key);
}
Check.Rejected(f.Root, "//ListItem[@Name='个性化']");
}
private static void ClassAndAnchor()
{
var root = TreeFixture.Node("Window", "患者 A");
var page = TreeFixture.Add(root, TreeFixture.Node("Pane", "页码1", "stable-page"));
var target = TreeFixture.Add(page, TreeFixture.Node("Edit", "数量1", null, "PatientEditor"));
string path = ControlPath.Build(root, target);
Check.True(path.IndexOf("@ClassName='PatientEditor'", StringComparison.Ordinal) >= 0, "Class fallback absent");
root.Uia.Name = "患者 B";
page.Uia.Name = "页码2";
target.Uia.Name = "数量2";
Check.Matches(root, path, target);
// A descendant anchor survives insertion of a layout-only ancestor.
page.Children.Clear();
TreeFixture.Add(TreeFixture.Add(page, TreeFixture.Node("Group", "新布局")), target);
Check.Matches(root, "//*[@AutomationId='stable-page']//Edit[@ClassName='PatientEditor']", target);
Check.Rejected(root, path);
// Structure alone is not a semantic identity; duplicate candidates must remain ambiguous.
TreeFixture.Add(page, TreeFixture.Node("Edit", "相同类型", null, "PatientEditor"));
string error;
Check.Equal<ControlTreeNode>(null, ControlPath.SelectUnique(root,
"//*[@AutomationId='stable-page']//Edit[@ClassName='PatientEditor']", out error), "Anchor ambiguity guessed a node");
Check.True(!string.IsNullOrEmpty(error), "Ambiguity missing reason");
}
private static void Escaping()
{
var f = new TreeFixture();
Check.Matches(f.Root, "//Text[@Name=" + ControlPath.Quote(f.EscapedName.Uia.Name) + "]", f.EscapedName);
Check.Matches(f.Root, "//Edit[@AutomationId=" + ControlPath.Quote(f.EscapedId.Uia.AutomationId) +
" and @ClassName=" + ControlPath.Quote(f.EscapedId.Uia.ClassName) + "]", f.EscapedId);
Check.Matches(f.Root, ControlPath.Build(f.Root, f.EscapedId), f.EscapedId);
}
private static void RejectLegacy()
{
var f = new TreeFixture();
foreach (string path in new[] { TreeFixture.BreadcrumbLegacy, TreeFixture.MenuLegacy,
"[Uia] /Window[1]", "Group[Duplicates] > Button#2", "[MSAA] i3/o1", "[Win32] Class 0x123" })
{
Check.Rejected(f.Root, path);
var result = ControlLocatorService.ResolveFromTree(new ControlMonitorDefinition { ControlPath = path }, f.Root, IntPtr.Zero);
Check.True(!result.Found && !string.IsNullOrEmpty(result.Error), "Legacy resolver unexpectedly succeeded");
}
var structured = new ControlMonitorDefinition
{
ControlPath = "",
UiaPath = new List<ControlLocatorSegment> { new ControlLocatorSegment { ControlType = "ControlType.Custom", AutomationId = "PermanentNavigationView" } }
};
Check.True(!ControlLocatorService.ResolveFromTree(structured, f.Root, IntPtr.Zero).Found, "Structured old path must not execute");
}
private static void RejectedPaths()
{
var f = new TreeFixture();
foreach (string path in new[] { "//Button[@AutomationId='missing']", "//Button[", "/Window/@Name", "/", "", " ", "count(//Button)", "(1 + 1)", "true()" })
Check.Rejected(f.Root, path);
Check.Rejected(null, "/Window");
Check.Equal<string>(null, ControlPath.ValidateSyntax("//Edit[@ClassName='PatientEditor']"), "Valid syntax");
Check.True(ControlPath.ValidateSyntax("//Edit[") != null, "Broken syntax accepted");
Check.True(ControlPath.ValidateSyntax(TreeFixture.MenuLegacy) != null, "Legacy syntax accepted");
}
private static void AmbiguousPaths()
{
var f = new TreeFixture();
string path = "//Button[@AutomationId='same-id']";
Check.Matches(f.Root, path, f.FirstDuplicate, f.SecondDuplicate);
string error;
Check.Equal<ControlTreeNode>(null, ControlPath.SelectUnique(f.Root, path, out error), "Must not take first match");
Check.True(!string.IsNullOrWhiteSpace(error), "Ambiguity lacks reason");
Check.True(!ControlLocatorService.ResolveFromTree(new ControlMonitorDefinition { ControlPath = path }, f.Root, IntPtr.Zero).Found, "Resolver guessed ambiguity");
}
private static void AuthoritativeXPath()
{
var f = new TreeFixture();
var definition = new ControlMonitorDefinition
{
ControlPath = ControlPath.Build(f.Root, f.MenuItem), RuntimeId = "stale-runtime",
UiaPath = new List<ControlLocatorSegment> { new ControlLocatorSegment { ControlType = "ControlType.Text", Name = "个性化" } }
};
Check.Same(f.MenuItem, ControlLocatorService.ResolveFromTree(definition, f.Root, IntPtr.Zero).Node, "Old hint overrode XPath");
definition.ControlPath = "//ListItem[@Name='不存在']";
Check.True(!ControlLocatorService.ResolveFromTree(definition, f.Root, IntPtr.Zero).Found, "Missing XPath fell back");
definition.ControlPath = ControlPath.Build(f.Root, f.BreadcrumbText);
Check.Same(f.BreadcrumbText, ControlLocatorService.ResolveFromTree(definition, f.Root, IntPtr.Zero).Node, "Edited XPath ignored");
}
private static void RootAndIncomplete()
{
var f = new TreeFixture();
Check.Equal("/Window[1]", ControlPath.Build(f.Root, f.Root), "Root path");
Check.True(new ControlLocatorBuilder().BuildFromTree(f.Root, f.Root, null).IsComplete, "Root cannot save");
var outsider = TreeFixture.Node("Button", "外部");
Check.Equal<string>(null, ControlPath.Build(f.Root, outsider), "Outsider got a path");
string path = ControlPath.Build(f.Root, f.MenuItem);
f.Root.ChildrenComplete = false;
f.Root.ChildrenError = "fixture truncated";
Check.True(!new ControlLocatorBuilder().BuildFromTree(f.Root, f.MenuItem, null).IsComplete, "Incomplete builder claimed success");
Check.True(!ControlLocatorService.ResolveFromTree(new ControlMonitorDefinition { ControlPath = path }, f.Root, IntPtr.Zero).Found, "Incomplete resolution claimed uniqueness");
}
private static void OtherSources()
{
var win = new ControlTreeNode { Source = ControlTreeSource.Win32, Window = new NativeWindowInfo(IntPtr.Zero) { ClassName = "Host", Title = "动态标题" } };
var child = new ControlTreeNode { Source = ControlTreeSource.Win32, Window = new NativeWindowInfo(IntPtr.Zero) { ClassName = "Edit", Title = "动态输入" } };
win.Children.Add(child);
string path = ControlPath.Build(win, child);
Check.Matches(win, path, child);
var result = ControlLocatorService.ResolveFromTree(new ControlMonitorDefinition { Source = ControlSourcePreference.Win32, ControlPath = path }, win, IntPtr.Zero);
Check.True(result.Found && result.ResolvedSource == ControlTreeSource.Win32, "Win32 XPath source lost");
Check.Same(child, result.Node, "Win32 payload lost");
var msaa = new ControlTreeNode { Source = ControlTreeSource.Msaa, Msaa = new MsaaNodeInfo { Name = "动态根" } };
var item = new ControlTreeNode { Source = ControlTreeSource.Msaa, Msaa = new MsaaNodeInfo { Name = "动态项" } };
msaa.Children.Add(item);
path = ControlPath.Build(msaa, item);
result = ControlLocatorService.ResolveFromTree(new ControlMonitorDefinition { Source = ControlSourcePreference.Msaa, ControlPath = path }, msaa, IntPtr.Zero);
Check.True(result.Found && result.ResolvedSource == ControlTreeSource.Msaa, "MSAA XPath source lost");
Check.Same(item, result.Node, "MSAA payload lost");
}
}
}