完善 XPath 定位与控件监控体验
- 增加简明到深入的 XPath 定位教程 - 保留增量控件树刷新与可编辑 Path - 完善悬浮条条件选择和诊断 Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using pacs_win_uia.Models;
|
||||
using pacs_win_uia.Services;
|
||||
|
||||
namespace PacsWinUia.RegressionTests
|
||||
{
|
||||
internal static class FloatingConditionsTests
|
||||
{
|
||||
public static void Register(IList<KeyValuePair<string, Action>> tests)
|
||||
{
|
||||
tests.Add(new KeyValuePair<string, Action>("Floating conditions require all supplied clues and unique window", WindowConditions));
|
||||
tests.Add(new KeyValuePair<string, Action>("Floating display explains missing configuration before provider calls", InvalidConfiguration));
|
||||
}
|
||||
|
||||
private static void WindowConditions()
|
||||
{
|
||||
var first = new NativeWindowInfo(new IntPtr(1)) { ProcessName = "fixture", ClassName = "Host", Title = "测试窗口 A", IsVisible = true };
|
||||
var second = new NativeWindowInfo(new IntPtr(2)) { ProcessName = "fixture", ClassName = "Host", Title = "测试窗口 B", IsVisible = true };
|
||||
var windows = new List<NativeWindowInfo> { first, second };
|
||||
string error;
|
||||
Check.Same(first, FloatingBarManager.FindConditionWindow(windows, "Fixture.exe", "Host", "窗口 A", out error), "Friendly .exe process input not normalized");
|
||||
Check.Equal<string>(null, error, "Exact match error");
|
||||
Check.Equal<NativeWindowInfo>(null, FloatingBarManager.FindConditionWindow(windows, "fixture", "Host", "不存在", out error), "Wrong title fell back to process");
|
||||
Check.True(!string.IsNullOrEmpty(error), "Missing title diagnostic");
|
||||
Check.Equal<NativeWindowInfo>(null, FloatingBarManager.FindConditionWindow(windows, "fixture", null, null, out error), "Ambiguous windows silently chose first");
|
||||
Check.True(!string.IsNullOrEmpty(error), "Ambiguity diagnostic");
|
||||
Check.Equal<NativeWindowInfo>(null, FloatingBarManager.FindConditionWindow(windows, null, null, null, out error), "Empty clues matched a window");
|
||||
Check.Equal<NativeWindowInfo>(null, FloatingBarManager.FindConditionWindow(windows, null, "Host", "wrong", out error), "Class OR title bug returned");
|
||||
}
|
||||
|
||||
private static void InvalidConfiguration()
|
||||
{
|
||||
var bar = new FloatingBarDefinition { Enabled = false };
|
||||
var result = FloatingBarManager.CheckDisplayConditions(bar);
|
||||
Check.True(!result.CanShow && !string.IsNullOrWhiteSpace(result.Reason), "Disabled bar lacks reason");
|
||||
bar.Enabled = true;
|
||||
result = FloatingBarManager.CheckDisplayConditions(bar);
|
||||
Check.True(!result.CanShow && !string.IsNullOrWhiteSpace(result.Reason), "Empty buttons lack reason");
|
||||
bar.Buttons.Add(new FloatingButtonDefinition { Enabled = true, Label = "测试", Action = FloatingActionKind.PickControl });
|
||||
result = FloatingBarManager.CheckDisplayConditions(bar);
|
||||
Check.True(!result.CanShow && !string.IsNullOrWhiteSpace(result.Reason), "No anchor lacks reason");
|
||||
bar.ImportedCondition = new ControlMonitorDefinition { ControlPath = TreeFixture.MenuLegacy, ProcessName = "fixture" };
|
||||
result = FloatingBarManager.CheckDisplayConditions(bar);
|
||||
Check.True(!result.CanShow && result.Reason.IndexOf("path", StringComparison.OrdinalIgnoreCase) >= 0, "Old imported path lacks diagnostic");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using pacs_win_uia.Models;
|
||||
using pacs_win_uia.Services;
|
||||
|
||||
namespace PacsWinUia.RegressionTests
|
||||
{
|
||||
internal static class PersistenceTests
|
||||
{
|
||||
public static void Register(IList<KeyValuePair<string, Action>> tests)
|
||||
{
|
||||
tests.Add(new KeyValuePair<string, Action>("Store saves XPath without dynamic UIA fields and copies flags", StoreXPath));
|
||||
tests.Add(new KeyValuePair<string, Action>("Store reads legacy UiaPath definitions", StoreLegacy));
|
||||
tests.Add(new KeyValuePair<string, Action>("Settings missing refresh interval defaults to 300", SettingsDefault));
|
||||
tests.Add(new KeyValuePair<string, Action>("Floating JSON missing defaults differs from explicit disabled", FloatingDefaults));
|
||||
}
|
||||
|
||||
private static void StoreXPath()
|
||||
{
|
||||
using (var directory = new TemporaryDirectory())
|
||||
{
|
||||
string path = directory.File("control-monitors.json");
|
||||
var definition = new ControlMonitorDefinition
|
||||
{
|
||||
Id = "11111111-1111-1111-1111-111111111111",
|
||||
ControlPath = "/Window[@Name='设置']/Button[@Name='保存']",
|
||||
ContentKey = "xpath_save",
|
||||
SourceName = "Uia",
|
||||
RuntimeId = "dynamic-runtime-id",
|
||||
Value = "live-value-must-not-persist",
|
||||
UiaPathFromInnerWindow = true,
|
||||
Disabled = true,
|
||||
UiaPath = new List<ControlLocatorSegment>
|
||||
{
|
||||
new ControlLocatorSegment { ControlType = "ControlType.Button", Name = "stale legacy", Index = 4 }
|
||||
},
|
||||
ProcessName = "fixture",
|
||||
WindowClass = "RootClass",
|
||||
WindowTitleKeyword = "设置"
|
||||
};
|
||||
new ControlMonitorStore(path).Save(new[] { definition });
|
||||
string json = File.ReadAllText(path, Encoding.UTF8);
|
||||
Check.True(json.IndexOf("dynamic-runtime-id", StringComparison.Ordinal) < 0, "RuntimeId leaked into JSON");
|
||||
Check.True(json.IndexOf("live-value-must-not-persist", StringComparison.Ordinal) < 0, "Value leaked into JSON");
|
||||
Check.True(json.IndexOf("\"UiaPath\":", StringComparison.Ordinal) < 0, "UiaPath must not be persisted with XPath");
|
||||
Check.True(json.IndexOf("UiaPathFromInnerWindow", StringComparison.Ordinal) < 0, "Obsolete inner-window flag persisted");
|
||||
Check.True(json.IndexOf("Disabled", StringComparison.Ordinal) >= 0, "Disabled flag missing");
|
||||
IList<ControlMonitorDefinition> loaded = new ControlMonitorStore(path).Load();
|
||||
Check.Equal(1, loaded.Count, "Saved definition count");
|
||||
Check.Equal(definition.ControlPath, loaded[0].ControlPath, "XPath roundtrip");
|
||||
Check.True(loaded[0].Disabled && !loaded[0].Enabled, "Disabled flag roundtrip");
|
||||
Check.True(!loaded[0].UiaPathFromInnerWindow, "Obsolete inner-window flag survived XPath save");
|
||||
Check.Equal<string>(null, loaded[0].RuntimeId, "RuntimeId must remain runtime-only");
|
||||
Check.Equal<string>(null, loaded[0].Value, "Value must remain runtime-only");
|
||||
Check.True(loaded[0].UiaPath == null || loaded[0].UiaPath.Count == 0, "XPath must not restore stale UiaPath");
|
||||
}
|
||||
}
|
||||
|
||||
private static void StoreLegacy()
|
||||
{
|
||||
using (var directory = new TemporaryDirectory())
|
||||
{
|
||||
string path = directory.File("legacy.json");
|
||||
string json = "{\"Version\":1,\"Items\":[{"
|
||||
+ "\"Id\":\"22222222-2222-2222-2222-222222222222\","
|
||||
+ "\"ControlPath\":\"[Uia] Window:设置 > Button:保存\","
|
||||
+ "\"ContentKey\":\"legacy_save\","
|
||||
+ "\"Source\":\"Uia\",\"UiaPathFromInnerWindow\":true,\"Disabled\":true,"
|
||||
+ "\"UiaPath\":[{\"ControlType\":\"ControlType.Window\",\"Name\":\"设置\",\"Index\":0},"
|
||||
+ "{\"ControlType\":\"ControlType.Button\",\"Name\":\"保存\",\"Index\":0}]"
|
||||
+ "}]}";
|
||||
File.WriteAllText(path, json, new UTF8Encoding(false));
|
||||
IList<ControlMonitorDefinition> loaded = new ControlMonitorStore(path).Load();
|
||||
Check.Equal(1, loaded.Count, "Legacy definition count");
|
||||
ControlMonitorDefinition definition = loaded[0];
|
||||
Check.Equal("[Uia] Window:设置 > Button:保存", definition.ControlPath, "Legacy display path");
|
||||
Check.True(definition.Disabled && !definition.Enabled, "Legacy disabled flag");
|
||||
Check.True(ControlMonitorRules.ValidateField(definition, "ControlPath") != null, "Old path needs an editable validation error");
|
||||
bool rejected = false;
|
||||
try { new ControlMonitorStore(path).Save(loaded); }
|
||||
catch (InvalidDataException) { rejected = true; }
|
||||
Check.True(rejected, "Saving old path silently succeeded");
|
||||
Check.Equal(json, File.ReadAllText(path, Encoding.UTF8), "Failed save overwrote old file");
|
||||
definition.ControlPath = "/Window[1]//Button[@AutomationId='save']";
|
||||
new ControlMonitorStore(path).Save(loaded);
|
||||
Check.Equal(definition.ControlPath, new ControlMonitorStore(path).Load()[0].ControlPath, "Corrected XPath did not persist");
|
||||
}
|
||||
}
|
||||
|
||||
private static void FloatingDefaults()
|
||||
{
|
||||
using (var directory = new TemporaryDirectory())
|
||||
{
|
||||
string preferred = directory.File("floating-defaults.json");
|
||||
File.WriteAllText(preferred,
|
||||
"{\"Version\":1,\"FloatingButton\":{\"Bars\":[{\"Name\":\"missing-defaults\",\"Buttons\":[{\"Label\":\"test\"}]},{\"Name\":\"disabled\",\"Enabled\":false,\"Buttons\":[{\"Label\":\"off\",\"Enabled\":false}]}]}}",
|
||||
new UTF8Encoding(false));
|
||||
AppSettings settings = new AppSettingsStore(preferred, directory.File("fallback.json")).Load();
|
||||
Check.Equal(2, settings.FloatingButton.Bars.Count, "JSON bars disappeared");
|
||||
FloatingBarDefinition first = settings.FloatingButton.Bars[0];
|
||||
Check.True(first.Enabled && first.RequireWindowVisible, "Missing bar defaults were not initialized");
|
||||
Check.True(first.Buttons[0].Enabled, "Missing button enabled default");
|
||||
Check.True(!settings.FloatingButton.Bars[1].Enabled && !settings.FloatingButton.Bars[1].Buttons[0].Enabled,
|
||||
"Explicit disabled flags must not be overridden");
|
||||
new AppSettingsStore(preferred, directory.File("fallback.json")).Save(settings);
|
||||
Check.True(!new AppSettingsStore(preferred, directory.File("fallback.json")).Load().FloatingButton.Bars[1].Enabled,
|
||||
"Disabled bar changed after roundtrip");
|
||||
}
|
||||
}
|
||||
|
||||
private static void SettingsDefault()
|
||||
{
|
||||
using (var directory = new TemporaryDirectory())
|
||||
{
|
||||
string preferred = directory.File("settings.json");
|
||||
string fallback = directory.File("fallback-settings.json");
|
||||
File.WriteAllText(preferred, "{\"Version\":1,\"Ui\":{\"TreeMaxDepth\":12}}", new UTF8Encoding(false));
|
||||
AppSettings settings = new AppSettingsStore(preferred, fallback).Load();
|
||||
Check.Equal(AppSettings.DefaultRefreshIntervalMs, settings.Ui.TreeRefreshIntervalMs, "Missing Ui refresh interval");
|
||||
Check.True(settings.FloatingButton != null, "Missing FloatingButton section default");
|
||||
Check.Equal(AppSettings.DefaultRefreshIntervalMs, settings.FloatingButton.RefreshIntervalMs, "Missing floating refresh interval");
|
||||
Check.True(settings.Commands != null && settings.Ocr != null && settings.Read != null && settings.Screenshot != null,
|
||||
"Missing settings sections were not restored");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using pacs_win_uia.Models;
|
||||
using pacs_win_uia.Services;
|
||||
|
||||
namespace PacsWinUia.RegressionTests
|
||||
{
|
||||
internal static class Program
|
||||
{
|
||||
[STAThread]
|
||||
private static int Main()
|
||||
{
|
||||
Console.OutputEncoding = new UTF8Encoding(false);
|
||||
var tests = new List<KeyValuePair<string, Action>>();
|
||||
PathTests.Register(tests);
|
||||
PersistenceTests.Register(tests);
|
||||
TreeRefreshTests.Register(tests);
|
||||
FloatingConditionsTests.Register(tests);
|
||||
int passed = 0;
|
||||
foreach (var test in tests)
|
||||
{
|
||||
try
|
||||
{
|
||||
test.Value();
|
||||
passed++;
|
||||
Console.WriteLine("PASS " + test.Key);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
Console.WriteLine("FAIL " + test.Key);
|
||||
Console.WriteLine(exception);
|
||||
}
|
||||
}
|
||||
Console.WriteLine("RESULT total={0} passed={1} failed={2}", tests.Count, passed, tests.Count - passed);
|
||||
return passed == tests.Count ? 0 : 1;
|
||||
}
|
||||
}
|
||||
|
||||
internal static class Check
|
||||
{
|
||||
public static void True(bool condition, string message)
|
||||
{
|
||||
if (!condition) throw new InvalidOperationException(message);
|
||||
}
|
||||
|
||||
public static void Equal<T>(T expected, T actual, string message)
|
||||
{
|
||||
True(EqualityComparer<T>.Default.Equals(expected, actual),
|
||||
message + "; expected=" + expected + "; actual=" + actual);
|
||||
}
|
||||
|
||||
public static void Same(object expected, object actual, string message)
|
||||
{
|
||||
True(ReferenceEquals(expected, actual), message + "; node reference mismatch");
|
||||
}
|
||||
|
||||
public static void Matches(ControlTreeNode root, string path, params ControlTreeNode[] expected)
|
||||
{
|
||||
string error;
|
||||
IList<ControlTreeNode> actual = ControlPath.Select(root, path, out error);
|
||||
Equal<string>(null, error, "Select error: " + path);
|
||||
Equal(expected.Length, actual.Count, "Select count: " + path);
|
||||
for (int i = 0; i < expected.Length; i++) Same(expected[i], actual[i], "Select order: " + path);
|
||||
if (expected.Length == 1)
|
||||
{
|
||||
Same(expected[0], ControlPath.SelectUnique(root, path, out error), "SelectUnique: " + path);
|
||||
Equal<string>(null, error, "SelectUnique error: " + path);
|
||||
}
|
||||
}
|
||||
|
||||
public static void Rejected(ControlTreeNode root, string path)
|
||||
{
|
||||
string error;
|
||||
Equal(0, ControlPath.Select(root, path, out error).Count, "Rejected path returned nodes: " + path);
|
||||
True(!string.IsNullOrWhiteSpace(error), "Rejected path lacks error: " + path);
|
||||
Equal<ControlTreeNode>(null, ControlPath.SelectUnique(root, path, out error), "Rejected path uniquely resolved: " + path);
|
||||
True(!string.IsNullOrWhiteSpace(error), "Rejected unique path lacks error: " + path);
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class TemporaryDirectory : IDisposable
|
||||
{
|
||||
public TemporaryDirectory()
|
||||
{
|
||||
DirectoryPath = Path.Combine(Path.GetTempPath(), "pacs-win-uia-regression-" + Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(DirectoryPath);
|
||||
}
|
||||
|
||||
public string DirectoryPath { get; private set; }
|
||||
public string File(string name) { return Path.Combine(DirectoryPath, name); }
|
||||
public void Dispose() { Directory.Delete(DirectoryPath, true); }
|
||||
}
|
||||
|
||||
// Every node is an in-memory snapshot: no AutomationElement, HWND lookup, GUI or provider calls.
|
||||
internal sealed class TreeFixture
|
||||
{
|
||||
public const string BreadcrumbLegacy = "[Uia] Custom[PermanentNavigationView] > Group[PermanentNavigationViewBreadcrumbBar] > Button:个性化 > Text:个性化";
|
||||
public const string MenuLegacy = "[Uia] Window:设置 > Custom[PermanentNavigationView] > Window[PaneRoot] > Pane[MenuItemsScrollViewer] > Group[MenuItemsHost] > ListItem:个性化";
|
||||
public readonly ControlTreeNode Root;
|
||||
public readonly ControlTreeNode Navigation;
|
||||
public readonly ControlTreeNode BreadcrumbText;
|
||||
public readonly ControlTreeNode MenuItem;
|
||||
public readonly ControlTreeNode Duplicates;
|
||||
public readonly ControlTreeNode FirstDuplicate;
|
||||
public readonly ControlTreeNode SecondDuplicate;
|
||||
public readonly ControlTreeNode NameWithId;
|
||||
public readonly ControlTreeNode NameWithoutId;
|
||||
public readonly ControlTreeNode Nameless;
|
||||
public readonly ControlTreeNode EscapedName;
|
||||
public readonly ControlTreeNode EscapedId;
|
||||
|
||||
public TreeFixture()
|
||||
{
|
||||
Root = Node("Window", "设置", null, "RootClass");
|
||||
Navigation = Add(Root, Node("Custom", null, "PermanentNavigationView"));
|
||||
var breadcrumb = Add(Navigation, Node("Group", null, "PermanentNavigationViewBreadcrumbBar"));
|
||||
BreadcrumbText = Add(Add(breadcrumb, Node("Button", "个性化")), Node("Text", "个性化"));
|
||||
var paneRoot = Add(Navigation, Node("Window", null, "PaneRoot"));
|
||||
var scroll = Add(paneRoot, Node("Pane", null, "MenuItemsScrollViewer"));
|
||||
var host = Add(scroll, Node("Group", null, "MenuItemsHost"));
|
||||
MenuItem = Add(host, Node("ListItem", "个性化"));
|
||||
Add(host, Node("ListItem", "系统"));
|
||||
Duplicates = Add(Root, Node("Group", null, "Duplicates"));
|
||||
FirstDuplicate = Add(Duplicates, Node("Button", "重复", "same-id", "PrimaryButton"));
|
||||
Add(Duplicates, Node("Text", "同级异类型"));
|
||||
Add(Duplicates, Node("Button", "其他", "other-id", "OtherButton"));
|
||||
SecondDuplicate = Add(Duplicates, Node("Button", "重复", "same-id", "SecondaryButton"));
|
||||
NameWithId = Add(Duplicates, Node("Button", "混合名称", "has-id"));
|
||||
NameWithoutId = Add(Duplicates, Node("Button", "混合名称"));
|
||||
Nameless = Add(Duplicates, Node("Button"));
|
||||
Add(Duplicates, Node("Button"));
|
||||
EscapedName = Add(Root, Node("Text", "中文 '单引号' \"双引号\" /斜杠 > 大于 & < [括号]"));
|
||||
EscapedId = Add(Root, Node("Edit", "输入", "id'\"/ > 中文 & <", "class'\"/ > 中文 & <"));
|
||||
}
|
||||
|
||||
public static ControlTreeNode Node(string type, string name = null, string id = null, string className = null)
|
||||
{
|
||||
return new ControlTreeNode
|
||||
{
|
||||
Source = ControlTreeSource.Uia,
|
||||
Uia = new UiaElementInfo { ControlType = "ControlType." + type, Name = name, AutomationId = id, ClassName = className }
|
||||
};
|
||||
}
|
||||
|
||||
public static ControlTreeNode Add(ControlTreeNode parent, ControlTreeNode child)
|
||||
{
|
||||
parent.Children.Add(child);
|
||||
return child;
|
||||
}
|
||||
|
||||
public static IEnumerable<ControlTreeNode> All(ControlTreeNode root)
|
||||
{
|
||||
yield return root;
|
||||
foreach (ControlTreeNode child in root.Children)
|
||||
foreach (ControlTreeNode descendant in All(child)) yield return descendant;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="15.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||
<ProjectGuid>{734FCA9D-3071-48D1-91DF-C2A07B329512}</ProjectGuid>
|
||||
<OutputType>Exe</OutputType>
|
||||
<RootNamespace>PacsWinUia.RegressionTests</RootNamespace>
|
||||
<AssemblyName>RegressionTests</AssemblyName>
|
||||
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
|
||||
<OutputPath>bin\$(Configuration)\</OutputPath>
|
||||
<LangVersion>7.3</LangVersion>
|
||||
<Prefer32Bit>false</Prefer32Bit>
|
||||
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="System" />
|
||||
<Reference Include="System.Core" />
|
||||
<Reference Include="System.Drawing" />
|
||||
<Reference Include="System.Windows.Forms" />
|
||||
<Reference Include="System.Runtime.Serialization" />
|
||||
<Reference Include="System.Xml" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\pacs_win_uia\pacs_win_uia.csproj">
|
||||
<Project>{C74B0B3A-0FB4-47CB-9AE8-DC7E0D993202}</Project>
|
||||
<Name>pacs_win_uia</Name>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="Program.cs" />
|
||||
<Compile Include="PathTests.cs" />
|
||||
<Compile Include="PersistenceTests.cs" />
|
||||
<Compile Include="TreeRefreshTests.cs" />
|
||||
<Compile Include="FloatingConditionsTests.cs" />
|
||||
<Compile Include="..\..\src\pacs_win_uia\UI\ControlTreeReconciler.cs"><Link>ControlTreeReconciler.cs</Link></Compile>
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||
</Project>
|
||||
@@ -0,0 +1,117 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Windows.Forms;
|
||||
using pacs_win_uia.Models;
|
||||
using pacs_win_uia.UI;
|
||||
|
||||
namespace PacsWinUia.RegressionTests
|
||||
{
|
||||
internal static class TreeRefreshTests
|
||||
{
|
||||
public static void Register(IList<KeyValuePair<string, Action>> tests)
|
||||
{
|
||||
tests.Add(new KeyValuePair<string, Action>("Tree refresh retains native items when unchanged or renamed", RetainsItems));
|
||||
tests.Add(new KeyValuePair<string, Action>("Tree refresh applies only insert, remove and move differences", StructuralChanges));
|
||||
tests.Add(new KeyValuePair<string, Action>("Tree fallback identity ignores mutable Name", FallbackIdentity));
|
||||
}
|
||||
|
||||
private static ControlTreeReconciler.Item Item(string runtime, string name)
|
||||
{
|
||||
return new ControlTreeReconciler.Item
|
||||
{
|
||||
Model = new ControlTreeNode { Source = ControlTreeSource.Uia,
|
||||
Uia = new UiaElementInfo { ProcessId = 12345, RuntimeId = runtime,
|
||||
ControlType = "ControlType.Button", Name = name, ClassName = "StableClass" } },
|
||||
Text = name,
|
||||
ForeColor = System.Drawing.Color.Empty
|
||||
};
|
||||
}
|
||||
|
||||
private static void RetainsItems()
|
||||
{
|
||||
using (var tree = new TreeView())
|
||||
using (var update = new ControlTreeReconciler(tree))
|
||||
{
|
||||
tree.CreateControl();
|
||||
var matches = new List<TreeNode>();
|
||||
var root = Item("1", "root");
|
||||
root.Children.Add(Item("2", "before"));
|
||||
update.Apply(root, matches);
|
||||
TreeNode parent = tree.Nodes[0], child = parent.Nodes[0];
|
||||
parent.Expand();
|
||||
tree.SelectedNode = child;
|
||||
IntPtr handle = child.Handle;
|
||||
for (int i = 0; i < 40; i++)
|
||||
{
|
||||
var fresh = Item("1", "root");
|
||||
fresh.Children.Add(Item("2", i < 20 ? "before" : "after"));
|
||||
fresh.Children[0].Match = i >= 30;
|
||||
update.Apply(fresh, matches);
|
||||
Check.Same(parent, tree.Nodes[0], "Root was rebuilt");
|
||||
Check.Same(child, parent.Nodes[0], "Renamed item was rebuilt");
|
||||
Check.Equal(handle, child.Handle, "Native item handle changed");
|
||||
Check.Same(child, tree.SelectedNode, "Selection changed");
|
||||
Check.True(parent.IsExpanded, "Parent collapsed");
|
||||
Check.Same(fresh.Children[0].Model, child.Tag, "Tag not rebound to fresh snapshot");
|
||||
}
|
||||
Check.Equal("after", child.Text, "Updated text missing");
|
||||
Check.Equal(1, matches.Count, "Search matches not updated");
|
||||
}
|
||||
}
|
||||
|
||||
private static void StructuralChanges()
|
||||
{
|
||||
using (var tree = new TreeView())
|
||||
using (var update = new ControlTreeReconciler(tree))
|
||||
{
|
||||
tree.CreateControl();
|
||||
var matches = new List<TreeNode>();
|
||||
var root = Item("1", "root");
|
||||
root.Children.Add(Item("2", "A"));
|
||||
root.Children.Add(Item("3", "B"));
|
||||
root.Children.Add(Item("4", "C"));
|
||||
update.Apply(root, matches);
|
||||
TreeNode original = tree.Nodes[0], a = original.Nodes[0], b = original.Nodes[1], c = original.Nodes[2];
|
||||
original.Expand();
|
||||
tree.SelectedNode = b;
|
||||
var fresh = Item("1", "root");
|
||||
fresh.Children.Add(Item("4", "C"));
|
||||
fresh.Children.Add(Item("5", "inserted"));
|
||||
fresh.Children.Add(Item("3", "B renamed"));
|
||||
update.Apply(fresh, matches);
|
||||
Check.Same(original, tree.Nodes[0], "Root rebuilt on structural change");
|
||||
Check.Same(c, original.Nodes[0], "Moved C lost identity");
|
||||
Check.Same(b, original.Nodes[2], "Retained B lost identity");
|
||||
Check.Equal(3, original.Nodes.Count, "Insert/delete count");
|
||||
Check.True(a.TreeView == null, "Deleted A retained");
|
||||
Check.Same(b, tree.SelectedNode, "Selection lost after sibling reorder");
|
||||
Check.True(original.IsExpanded, "Expansion lost after reorder");
|
||||
var moved = Item("1", "root");
|
||||
var newParent = Item("6", "new parent");
|
||||
newParent.Children.Add(Item("3", "B moved"));
|
||||
moved.Children.Add(newParent);
|
||||
update.Apply(moved, matches);
|
||||
Check.Same(b, original.Nodes[0].Nodes[0], "Reparented item lost identity");
|
||||
Check.Same(b, tree.SelectedNode, "Selection lost after reparenting");
|
||||
}
|
||||
}
|
||||
|
||||
private static void FallbackIdentity()
|
||||
{
|
||||
using (var tree = new TreeView())
|
||||
using (var update = new ControlTreeReconciler(tree))
|
||||
{
|
||||
var matches = new List<TreeNode>();
|
||||
var root = Item(null, "old name");
|
||||
root.Children.Add(Item(null, "old child name"));
|
||||
update.Apply(root, matches);
|
||||
TreeNode parent = tree.Nodes[0], child = parent.Nodes[0];
|
||||
var fresh = Item(null, "new name");
|
||||
fresh.Children.Add(Item(null, "new child name"));
|
||||
update.Apply(fresh, matches);
|
||||
Check.Same(parent, tree.Nodes[0], "Fallback root depends on Name");
|
||||
Check.Same(child, parent.Nodes[0], "Fallback child depends on Name");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user