using System.Text;
using XFEToolBox.Client.Core.Search;
namespace XFEToolBox.Test;
public static class FileContentSearchTests
{
[Test]
public static void ContentIndexSupportsTextEncodingsAndSkipsBinary() => Run(async fixture =>
{
var utf8 = fixture.Write("utf8.txt", "alpha 中文 omega");
var utf16 = fixture.Write("utf16.cs", "class Unicode { /* 中文 */ }", Encoding.Unicode);
var utf32 = fixture.Write("utf32.md", "中文 documentation", Encoding.UTF32);
var binary = fixture.PathFor("binary.txt");
File.WriteAllBytes(binary, [0x50, 0x4b, 0, 1, 2, 3, 0xff, 0xfe]);
var unsupported = fixture.Write("unsupported.pdf", "中文");
await using var service = new FileContentSearchService(fixture.Cache);
Assert(!Directory.Exists(fixture.Cache), "构造正文服务不应创建缓存或读取磁盘。");
await service.EnsureIndexAsync(Entries(utf8, utf16, utf32, binary, unsupported));
var result = await service.SearchAsync("中文");
Assert(result.TotalMatches == 3, "UTF-8/16/32 或双字符正文搜索遗漏结果。");
Assert(result.Items.All(match => match.ContentMatch && match.Snippet?.Contains("中文") == true), "正文结果缺少摘要或标记。");
Assert(service.Status is { IsIndexing: false, IndexedCount: 3, SkippedCount: 2, Error: null }, "正文索引跳过数量不正确。");
});
[Test]
public static void ContentIndexUsesWildcardsAndExactVerification() => Run(async fixture =>
{
var yes = fixture.Write("match.txt", "start alpha-middle-omega end");
var no = fixture.Write("wrong-order.txt", "omega then alpha");
var one = fixture.Write("one.txt", "alphaXomega");
await using var service = new FileContentSearchService(fixture.Cache);
await service.EnsureIndexAsync(Entries(yes, no, one));
Assert((await service.SearchAsync("alpha*omega")).TotalMatches == 2, "FTS 候选未经过通配符顺序验证。");
var question = await service.SearchAsync("alpha?omega");
Assert(question.TotalMatches == 1 && question.Items[0].Entry.FullPath == one, "问号通配符没有限定一个字符。");
var page = await service.SearchAsync("alpha", 1, 1);
Assert(page.TotalMatches == 3 && page.Items.Count == 1, "正文分页或总数不正确。");
});
[Test]
public static void ContentIndexPersistsAndReconcilesChangedAndDeletedFiles() => Run(async fixture =>
{
var changed = fixture.Write("changed.txt", "oldneedle");
var removed = fixture.Write("removed.txt", "oldneedle");
var snapshot = Entries(changed, removed);
await using (var first = new FileContentSearchService(fixture.Cache))
{
await first.EnsureIndexAsync(snapshot);
Assert((await first.SearchAsync("oldneedle")).TotalMatches == 2, "初始正文索引失败。");
}
await using var second = new FileContentSearchService(fixture.Cache);
// A locked but unchanged source remains searchable through the persisted cache.
using (var locked = new FileStream(changed, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
await second.EnsureIndexAsync(snapshot);
Assert((await second.SearchAsync("oldneedle")).TotalMatches == 2, "重启后重新读取了未修改的源文件。");
}
File.WriteAllText(changed, "replacement needle with different length", new UTF8Encoding(false));
File.Delete(removed);
Assert((await second.SearchAsync("oldneedle")).TotalMatches == 2, "搜索请求不应读取源文件。");
await second.EnsureIndexAsync(Entries(changed));
Assert((await second.SearchAsync("oldneedle")).TotalMatches == 0, "增量刷新没有清除旧正文和删除文件。");
Assert((await second.SearchAsync("replacement")).TotalMatches == 1, "增量刷新没有索引修改后的正文。");
Assert((await second.SearchAsync("needle")).TotalMatches == 1, "FTS 更新丢失了修改前后共有的词元。");
});
[Test]
public static void ContentIndexLimitsSizesAndSafelyQuotesFtsParameters() => Run(async fixture =>
{
var literal = fixture.Write("quoted.txt", "prefix O'Reilly quote\"symbol suffix");
var oversized = fixture.Write("oversized.txt", new string('a', 1000));
await using var service = new FileContentSearchService(fixture.Cache, 128);
await service.EnsureIndexAsync(Entries(literal, oversized));
Assert(service.Status.IndexedCount == 1 && service.Status.SkippedCount == 1, "大小限制没有计入跳过数量。");
Assert((await service.SearchAsync("\"O'Reilly\"")).TotalMatches == 1, "FTS 特殊字符没有安全参数化。");
Assert((await service.SearchAsync("suffix")).TotalMatches == 1, "特殊字符查询损坏了正文索引。");
});
[Test]
public static void ContentIndexHandlesUnicodeCaseOnlyRenames() => Run(async fixture =>
{
var original = fixture.Write("ärger.txt", "oldbodymarker");
await using var service = new FileContentSearchService(fixture.Cache);
await service.EnsureIndexAsync(Entries(original));
var renamed = fixture.PathFor("ÄRGER.txt");
File.Move(original, renamed);
File.WriteAllText(renamed, "replacementbodymarker with a different length");
await service.EnsureIndexAsync(Entries(renamed));
Assert((await service.SearchAsync("oldbodymarker")).TotalMatches == 0 &&
(await service.SearchAsync("replacementbodymarker")).TotalMatches == 1,
"Unicode 大小写重命名在 SQLite 中保留了重复正文缓存。");
});
[Test]
public static void ContentIndexPreservesMetadataBranchesAndCancellation() => Run(async fixture =>
{
var cs = fixture.Write("code.cs", "beta needle");
var txt = fixture.Write("text.txt", "alpha needle");
await using var service = new FileContentSearchService(fixture.Cache);
await service.EnsureIndexAsync(Entries(cs, txt));
Assert((await service.SearchAsync("ext:cs needle")).TotalMatches == 1, "正文搜索未应用扩展名过滤。");
Assert((await service.SearchAsync("ext:cs alpha | ext:txt beta")).TotalMatches == 0,
"正文匹配和元数据匹配错误地跨越 OR 分支组合。");
using var cancellation = new CancellationTokenSource();
cancellation.Cancel();
try
{
await service.SearchAsync("needle", cancellationToken: cancellation.Token);
throw new InvalidOperationException("已取消的正文查询仍然执行。");
}
catch (OperationCanceledException) { }
});
private static FileSearchEntry[] Entries(params string[] paths) => paths.Select(path => new FileSearchEntry(path, false)).ToArray();
private static void Assert(bool condition, string message)
{
if (!condition) throw new InvalidOperationException(message);
}
private static void Run(Func<Fixture, Task> test)
{
using var fixture = new Fixture();
test(fixture).GetAwaiter().GetResult();
}
private sealed class Fixture : IDisposable
{
private readonly string root = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "XFEToolBox-ContentSearch-" + Guid.NewGuid().ToString("N"));
public Fixture() => Directory.CreateDirectory(root);
public string Cache => System.IO.Path.Combine(root, "cache");
public string PathFor(string name) => System.IO.Path.Combine(root, name);
public string Write(string name, string text, Encoding? encoding = null)
{
var path = PathFor(name);
File.WriteAllText(path, text, encoding ?? new UTF8Encoding(false));
return path;
}
public void Dispose() => Directory.Delete(root, true);
}
}
using System.Text;
using XFEToolBox.Client.Core.Search;
namespace XFEToolBox.Test;
public static class FileContentSearchTests
{
[Test]
public static void ContentIndexSupportsTextEncodingsAndSkipsBinary() => Run(async fixture =>
{
var utf8 = fixture.Write("utf8.txt", "alpha 中文 omega");
var utf16 = fixture.Write("utf16.cs", "class Unicode { /* 中文 */ }", Encoding.Unicode);
var utf32 = fixture.Write("utf32.md", "中文 documentation", Encoding.UTF32);
var binary = fixture.PathFor("binary.txt");
File.WriteAllBytes(binary, [0x50, 0x4b, 0, 1, 2, 3, 0xff, 0xfe]);
var unsupported = fixture.Write("unsupported.pdf", "中文");
await using var service = new FileContentSearchService(fixture.Cache);
Assert(!Directory.Exists(fixture.Cache), "构造正文服务不应创建缓存或读取磁盘。");
await service.EnsureIndexAsync(Entries(utf8, utf16, utf32, binary, unsupported));
var result = await service.SearchAsync("中文");
Assert(result.TotalMatches == 3, "UTF-8/16/32 或双字符正文搜索遗漏结果。");
Assert(result.Items.All(match => match.ContentMatch && match.Snippet?.Contains("中文") == true), "正文结果缺少摘要或标记。");
Assert(service.Status is { IsIndexing: false, IndexedCount: 3, SkippedCount: 2, Error: null }, "正文索引跳过数量不正确。");
});
[Test]
public static void ContentIndexUsesWildcardsAndExactVerification() => Run(async fixture =>
{
var yes = fixture.Write("match.txt", "start alpha-middle-omega end");
var no = fixture.Write("wrong-order.txt", "omega then alpha");
var one = fixture.Write("one.txt", "alphaXomega");
await using var service = new FileContentSearchService(fixture.Cache);
await service.EnsureIndexAsync(Entries(yes, no, one));
Assert((await service.SearchAsync("alpha*omega")).TotalMatches == 2, "FTS 候选未经过通配符顺序验证。");
var question = await service.SearchAsync("alpha?omega");
Assert(question.TotalMatches == 1 && question.Items[0].Entry.FullPath == one, "问号通配符没有限定一个字符。");
var page = await service.SearchAsync("alpha", 1, 1);
Assert(page.TotalMatches == 3 && page.Items.Count == 1, "正文分页或总数不正确。");
});
[Test]
public static void ContentIndexPersistsAndReconcilesChangedAndDeletedFiles() => Run(async fixture =>
{
var changed = fixture.Write("changed.txt", "oldneedle");
var removed = fixture.Write("removed.txt", "oldneedle");
var snapshot = Entries(changed, removed);
await using (var first = new FileContentSearchService(fixture.Cache))
{
await first.EnsureIndexAsync(snapshot);
Assert((await first.SearchAsync("oldneedle")).TotalMatches == 2, "初始正文索引失败。");
}
await using var second = new FileContentSearchService(fixture.Cache);
// A locked but unchanged source remains searchable through the persisted cache.
using (var locked = new FileStream(changed, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
await second.EnsureIndexAsync(snapshot);
Assert((await second.SearchAsync("oldneedle")).TotalMatches == 2, "重启后重新读取了未修改的源文件。");
}
File.WriteAllText(changed, "replacement needle with different length", new UTF8Encoding(false));
File.Delete(removed);
Assert((await second.SearchAsync("oldneedle")).TotalMatches == 2, "搜索请求不应读取源文件。");
await second.EnsureIndexAsync(Entries(changed));
Assert((await second.SearchAsync("oldneedle")).TotalMatches == 0, "增量刷新没有清除旧正文和删除文件。");
Assert((await second.SearchAsync("replacement")).TotalMatches == 1, "增量刷新没有索引修改后的正文。");
Assert((await second.SearchAsync("needle")).TotalMatches == 1, "FTS 更新丢失了修改前后共有的词元。");
});
[Test]
public static void ContentIndexLimitsSizesAndSafelyQuotesFtsParameters() => Run(async fixture =>
{
var literal = fixture.Write("quoted.txt", "prefix O'Reilly quote\"symbol suffix");
var oversized = fixture.Write("oversized.txt", new string('a', 1000));
await using var service = new FileContentSearchService(fixture.Cache, 128);
await service.EnsureIndexAsync(Entries(literal, oversized));
Assert(service.Status.IndexedCount == 1 && service.Status.SkippedCount == 1, "大小限制没有计入跳过数量。");
Assert((await service.SearchAsync("\"O'Reilly\"")).TotalMatches == 1, "FTS 特殊字符没有安全参数化。");
Assert((await service.SearchAsync("suffix")).TotalMatches == 1, "特殊字符查询损坏了正文索引。");
});
[Test]
public static void ContentIndexHandlesUnicodeCaseOnlyRenames() => Run(async fixture =>
{
var original = fixture.Write("ärger.txt", "oldbodymarker");
await using var service = new FileContentSearchService(fixture.Cache);
await service.EnsureIndexAsync(Entries(original));
var renamed = fixture.PathFor("ÄRGER.txt");
File.Move(original, renamed);
File.WriteAllText(renamed, "replacementbodymarker with a different length");
await service.EnsureIndexAsync(Entries(renamed));
Assert((await service.SearchAsync("oldbodymarker")).TotalMatches == 0 &&
(await service.SearchAsync("replacementbodymarker")).TotalMatches == 1,
"Unicode 大小写重命名在 SQLite 中保留了重复正文缓存。");
});
[Test]
public static void ContentIndexPreservesMetadataBranchesAndCancellation() => Run(async fixture =>
{
var cs = fixture.Write("code.cs", "beta needle");
var txt = fixture.Write("text.txt", "alpha needle");
await using var service = new FileContentSearchService(fixture.Cache);
await service.EnsureIndexAsync(Entries(cs, txt));
Assert((await service.SearchAsync("ext:cs needle")).TotalMatches == 1, "正文搜索未应用扩展名过滤。");
Assert((await service.SearchAsync("ext:cs alpha | ext:txt beta")).TotalMatches == 0,
"正文匹配和元数据匹配错误地跨越 OR 分支组合。");
using var cancellation = new CancellationTokenSource();
cancellation.Cancel();
try
{
await service.SearchAsync("needle", cancellationToken: cancellation.Token);
throw new InvalidOperationException("已取消的正文查询仍然执行。");
}
catch (OperationCanceledException) { }
});
private static FileSearchEntry[] Entries(params string[] paths) => paths.Select(path => new FileSearchEntry(path, false)).ToArray();
private static void Assert(bool condition, string message)
{
if (!condition) throw new InvalidOperationException(message);
}
private static void Run(Func<Fixture, Task> test)
{
using var fixture = new Fixture();
test(fixture).GetAwaiter().GetResult();
}
private sealed class Fixture : IDisposable
{
private readonly string root = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "XFEToolBox-ContentSearch-" + Guid.NewGuid().ToString("N"));
public Fixture() => Directory.CreateDirectory(root);
public string Cache => System.IO.Path.Combine(root, "cache");
public string PathFor(string name) => System.IO.Path.Combine(root, name);
public string Write(string name, string text, Encoding? encoding = null)
{
var path = PathFor(name);
File.WriteAllText(path, text, encoding ?? new UTF8Encoding(false));
return path;
}
public void Dispose() => Directory.Delete(root, true);
}
}