完善 XPath 定位与控件监控体验

- 增加简明到深入的 XPath 定位教程
- 保留增量控件树刷新与可编辑 Path
- 完善悬浮条条件选择和诊断

Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
zimoyin
2026-10-13 13:00:10 +08:00
parent ec785c4fb6
commit f31b50bb36
51 changed files with 8491 additions and 1931 deletions
+204
View File
@@ -0,0 +1,204 @@
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)
{
tests.Add(new KeyValuePair<string, Action>("XPath attributes, contains, axes and positional predicates", XPathQueries));
tests.Add(new KeyValuePair<string, Action>("All nodes roundtrip with duplicate IDs and structural indices", AllNodesRoundtrip));
tests.Add(new KeyValuePair<string, Action>("Generated paths survive names changing on every ancestor", ChangingNames));
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));
tests.Add(new KeyValuePair<string, Action>("Old display and structured paths are not executed", RejectLegacy));
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));
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));
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");
}
}
}