XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEToolBox

【WPF】XFE工具箱

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Diagnostics;
using System.IO;
using System.Reflection;
using XFEToolBox.Client.Utilities;

namespace XFEToolBox.Client.Wpf.Test;

public static class FileSearchRuntimeTests
{
    [Test]
    public static async Task RuntimeChoosesAnIsolatedScopeBeforeInitializingAndPersistsIt()
    {
        using var tree = new TestTree();
        var root = tree.Folder("scope");
        File.WriteAllText(Path.Combine(root, "local-report.txt"), "body");
        await using (var runtime = new FileSearchRuntime(tree.Cache))
        {
            await runtime.SetContentEnabledAsync(false);
            Ensure(runtime.Status is null, "关闭未启动的正文搜索不应启动所有磁盘扫描。");
            await runtime.SetScopeAsync(root);
            await runtime.RebuildAsync();
            var page = await runtime.SearchAsync("*", false, 100);
            Ensure(runtime.ScopePath == root && page.Items.Count == 2, "首次设置范围未限制为指定目录。");
            Ensure(page.Items.All(item => item.Entry.FullPath.StartsWith(root, StringComparison.OrdinalIgnoreCase)),
                "指定隔离目录时错误地扫描了默认本地磁盘。");
            Ensure(!Directory.Exists(Path.Combine(tree.Cache, "Content")), "未启用正文搜索却创建了正文数据库。");
        }
        await using var restored = new FileSearchRuntime(tree.Cache);
        await restored.InitializeAsync();
        await restored.RebuildAsync();
        Ensure(restored.ScopePath == root && (await restored.SearchAsync("local-report", false, 100)).Items.Count == 1,
            "重启后未恢复保存的搜索范围与索引。");
    }

    [Test]
    public static async Task RuntimeDisablingContentCancelsActiveIndexing()
    {
        using var tree = new TestTree();
        var root = tree.Folder("scope");
        var largeText = string.Concat(Enumerable.Repeat("indexedcontent needle abcdefghijklmnopqrstuvwxyz 0123456789\n", 9000));
        for (var i = 0; i < 6; i++) File.WriteAllText(Path.Combine(root, $"large{i}.txt"), largeText);
        await using var runtime = new FileSearchRuntime(tree.Cache);
        await runtime.SetScopeAsync(root);
        await runtime.RebuildAsync();
        await runtime.SetContentEnabledAsync(true);
        await UntilAsync(() => runtime.ContentStatus?.IsIndexing == true, "正文索引未在启用后开始。", TimeSpan.FromSeconds(10));
        var watch = Stopwatch.StartNew();
        await runtime.SetContentEnabledAsync(false);
        Ensure(watch.Elapsed < TimeSpan.FromSeconds(3) && runtime.ContentStatus?.IsIndexing == false,
            "关闭正文开关后仍在读取/索引文件。");
        Ensure((await runtime.SearchAsync("indexedcontent", true, 100)).Items.Count == 0,
            "关闭正文开关后仍然使用正文结果。");
        File.WriteAllText(Path.Combine(root, "later.txt"), "content-after-disable");
        await runtime.RebuildAsync();
        await Task.Delay(2500);
        Ensure(runtime.ContentStatus?.IsIndexing == false &&
            (await runtime.SearchAsync("content-after-disable", true, 100)).Items.Count == 0,
            "关闭正文开关后磁盘变更再次启动了正文读取。");
    }

    [Test]
    public static async Task RuntimeNeverShowsOldScopeContentDuringReconciliation()
    {
        using var tree = new TestTree();
        var first = tree.Folder("first");
        var second = tree.Folder("second");
        File.WriteAllText(Path.Combine(first, "source.txt"), "privatemarker");
        File.WriteAllText(Path.Combine(second, "source.txt"), "secondmarker");
        await using var runtime = new FileSearchRuntime(tree.Cache);
        await runtime.SetScopeAsync(first);
        await runtime.RebuildAsync();
        await runtime.SetContentEnabledAsync(true);
        await UntilAsync(() => runtime.ContentStatus is { IsIndexing: false, IndexedCount: 1 }, "首个范围正文索引未完成。");
        Ensure((await runtime.SearchAsync("privatemarker", true, 100)).Items.Count == 1, "首个范围正文未检索到。");
        await runtime.SetScopeAsync(second);
        await runtime.RebuildAsync();
        Ensure((await runtime.SearchAsync("privatemarker", true, 100)).Items.Count == 0,
            "新范围正文尚未重建时泄露了旧范围缓存结果。");
        await UntilAsync(async () => (await runtime.SearchAsync("secondmarker", true, 100)).Items.Count == 1,
            "切换范围后正文索引没有自动刷新。");
    }

    [Test]
    public static async Task RuntimeContentLoadMoreCanCrossTheSqliteBatchLimit()
    {
        using var tree = new TestTree();
        var root = tree.Folder("scope");
        const int count = 1005;
        for (var i = 0; i < count; i++) File.WriteAllText(Path.Combine(root, $"item{i:0000}.txt"), "bodyonlymarker");
        await using var runtime = new FileSearchRuntime(tree.Cache);
        await runtime.SetScopeAsync(root);
        await runtime.RebuildAsync();
        await runtime.SetContentEnabledAsync(true);
        await UntilAsync(() => runtime.ContentStatus is { IsIndexing: false, IndexedCount: count },
            "正文分页测试的索引未完成。", TimeSpan.FromSeconds(15));
        var first = await runtime.SearchAsync("bodyonlymarker", true, 1000);
        Ensure(first.Items.Count == 1000 && first.HasMore, "首批正文结果错误地隐藏后续页。");
        var all = await runtime.SearchAsync("bodyonlymarker", true, 1200);
        Ensure(all.Items.Count == count && !all.HasMore &&
            all.Items.Select(item => item.Entry.FullPath).Distinct(StringComparer.OrdinalIgnoreCase).Count() == count,
            "加载更多受单次 SQLite 1000 条限制,或分页重复/遗漏。");
    }

    [Test]
    public static async Task RuntimeRefreshesTheFinalMutationAfterWriteDebouncing()
    {
        using var tree = new TestTree();
        var root = tree.Folder("scope");
        var path = Path.Combine(root, "source.txt");
        File.WriteAllText(path, "initialmarker");
        await using var runtime = new FileSearchRuntime(tree.Cache);
        await runtime.SetScopeAsync(root);
        await runtime.RebuildAsync();
        await runtime.SetContentEnabledAsync(true);
        await UntilAsync(() => runtime.ContentStatus is { IsIndexing: false, IndexedCount: 1 }, "初始正文索引未完成。");
        for (var i = 0; i < 5; i++)
        {
            File.WriteAllText(path, "intermediatemarker " + i);
            await Task.Delay(200);
        }
        File.WriteAllText(path, "finalmutationmarker");
        await UntilAsync(async () => (await runtime.SearchAsync("finalmutationmarker", true, 100)).Items.Count == 1,
            "节流循环丢失了最后一次正文变更。", TimeSpan.FromSeconds(18));
        Ensure((await runtime.SearchAsync("initialmarker", true, 100)).Items.Count == 0, "最终刷新没有移除旧正文。");
    }

    [Test]
    public static async Task RuntimeSerializesScopeChangesAndDisposalAndToleratesLateExitSignal()
    {
        using var tree = new TestTree();
        var first = tree.Folder("first");
        var second = tree.Folder("second");
        File.WriteAllText(Path.Combine(first, "one.txt"), "one");
        var runtime = new FileSearchRuntime(tree.Cache);
        await runtime.SetScopeAsync(first);
        var change = runtime.SetScopeAsync(second);
        var dispose = runtime.DisposeAsync().AsTask();
        await Task.WhenAll(change, dispose);
        await runtime.DisposeAsync();
        // App.RequestExit awaits disposal; WPF OnExit then calls the synchronous stop hook again.
        typeof(FileSearchRuntime).GetMethod("RequestStop", BindingFlags.NonPublic | BindingFlags.Instance)!.Invoke(runtime, null);
        Ensure(runtime.Status is null, "释放后仍然保留活动的磁盘索引。");
    }

    private static async Task UntilAsync(Func<bool> ready, string message, TimeSpan? timeout = null) =>
        await UntilAsync(() => Task.FromResult(ready()), message, timeout);

    private static async Task UntilAsync(Func<Task<bool>> ready, string message, TimeSpan? timeout = null)
    {
        var watch = Stopwatch.StartNew();
        while (watch.Elapsed < (timeout ?? TimeSpan.FromSeconds(10)))
        {
            if (await ready()) return;
            await Task.Delay(25);
        }
        throw new InvalidOperationException(message);
    }

    private static void Ensure(bool condition, string message)
    {
        if (!condition) throw new InvalidOperationException(message);
    }

    private sealed class TestTree : IDisposable
    {
        private readonly string root = Path.Combine(Path.GetTempPath(), "XFEToolBox-FileSearchRuntime-" + Guid.NewGuid().ToString("N"));
        public TestTree() => Directory.CreateDirectory(root);
        public string Cache => Path.Combine(root, "cache");
        public string Folder(string name) => Directory.CreateDirectory(Path.Combine(root, name)).FullName;
        public void Dispose() => Directory.Delete(root, true);
    }
}