Files
zimoyin 44fb305dc4 所有配置文件统一放到 exe 同目录
- control-monitors.json 从 %LocalAppData%\pacs_win_uia\ 改到 exe 同目录
  (settings.json / out.json / 截图与 OCR 目录本来就是 exe 同目录,现在一致)
- 首次读取时把旧位置的监控配置复制过来(只复制不删除),并记日志;
  exe 目录不可写时退化为直接读旧文件,保存会明确报错,不会丢配置
- ControlMonitorStore.GetDefaultFilePath()/GetLegacyFilePath() 公开,
  Program 的 --read-saved 与设置页「关于」都改用同一套路径
- 回归新增用例:默认配置与设置文件都必须在 exe 同目录、旧路径与当前路径必须不同
- 实测(隔离宿主):默认路径=exe 同目录;旧位置有 1 条配置被复制过来并能正常读出

测试 24/24 通过,
2026-10-13 16:18:57 +08:00

172 lines
11 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// =====================================================================================
// PersistenceTests —— 监控条目与设置的持久化 / 迁移 / 缺省值 回归。
//
// 覆盖范围:ControlMonitorStore 的 Save/Load(XPath 不落盘动态字段、拒绝旧格式写入)、
// AppSettingsStore 的 Load/Save(旧 UiaPath 读取、缺失区段与刷新间隔缺省值、
// 悬浮条 Enabled/RequireWindowVisible 的“缺省启用 vs 显式停用”区分)。
//
// 为什么这样测:全部在临时目录里读写 JSON 文件、用内存对象断言,不涉及 UIA / GUI;
// 每个用例用 TemporaryDirectory 隔离,绝不读写真实用户配置。
//
// 新增用例:加到 Register(...) 列表并实现 private static void 方法,断言走 Check.*。
// =====================================================================================
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)
{
// 防:RuntimeId/Value 等动态字段被写进 JSON、Obsolete 标志残留、Disabled 未落盘。
tests.Add(new KeyValuePair<string, Action>("Store saves XPath without dynamic UIA fields and copies flags", StoreXPath));
// 防:旧 UiaPath 定义被读入后又被静默改写/覆盖旧文件,或修正后不持久化。
tests.Add(new KeyValuePair<string, Action>("Store reads legacy UiaPath definitions", StoreLegacy));
// 防:设置缺省刷新间隔不再是 300ms,或缺失的区段未被补全。
tests.Add(new KeyValuePair<string, Action>("Settings missing refresh interval defaults to 300", SettingsDefault));
// 防:默认配置文件又跑回 %LocalAppData%(需求:所有配置都在 exe 同级别)。
tests.Add(new KeyValuePair<string, Action>("Default monitor config lives next to the exe", DefaultConfigLocation));
// 防:悬浮条缺省启用被误判为显式停用(或反之)。
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");
}
}
// 默认配置必须在 exe 同目录;旧位置只作为一次性迁移来源保留。
// 这里只断言路径本身,不读写磁盘——绝不能在测试里碰用户真实的配置文件。
private static void DefaultConfigLocation()
{
string expectedDirectory = Path.GetDirectoryName(typeof(ControlMonitorStore).Assembly.Location);
string defaultPath = ControlMonitorStore.GetDefaultFilePath();
Check.Equal(expectedDirectory, Path.GetDirectoryName(defaultPath), "Default config is not next to the exe");
Check.Equal("control-monitors.json", Path.GetFileName(defaultPath), "Default config file name");
Check.True(Path.IsPathRooted(defaultPath), "Default config path must be absolute");
string preferred = new AppSettingsStore().PreferredPath;
Check.Equal(expectedDirectory, Path.GetDirectoryName(preferred), "Settings file is not next to the exe");
string legacy = ControlMonitorStore.GetLegacyFilePath();
if (legacy != null)
{
Check.True(!string.Equals(legacy, defaultPath, StringComparison.OrdinalIgnoreCase),
"Legacy and current config paths must differ");
Check.True(legacy.IndexOf("pacs_win_uia", StringComparison.OrdinalIgnoreCase) >= 0,
"Legacy path should stay inside pacs_win_uia");
}
}
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");
}
}
}
}