using Khaemhat.Application.Search;
using Khaemhat.Application.Security;
using Khaemhat.Core.Security;
using Microsoft.Extensions.Logging.Abstractions;
namespace Khaemhat.Application.Tests;
/// The global search of SPEC ยง10.2 (issue #32, mockup 009).
[TestClass]
public sealed class GlobalSearchTests
{
private static readonly Actor Root = new("root", UserLevel.SuperUser, 1, null, null);
[TestMethod]
[DataRow(" fattura ", SearchScope.All, "fattura")]
[DataRow("> tema", SearchScope.Commands, "tema")]
[DataRow("#FT 12", SearchScope.Documents, "FT 12")]
[DataRow("@rossi", SearchScope.People, "rossi")]
[DataRow("", SearchScope.All, "")]
public void Query_ReadsThePrefix(string input, SearchScope scope, string text)
{
var query = SearchQuery.Parse(input);
Assert.AreEqual(scope, query.Scope);
Assert.AreEqual(text, query.Text);
}
[TestMethod]
public void Query_MatchesEveryWord_IgnoringCase()
{
var query = SearchQuery.Parse("iva liq");
Assert.IsTrue(query.Matches("Liquidazione IVA"));
Assert.IsFalse(query.Matches("Registri IVA"));
Assert.IsFalse(query.Matches(null));
Assert.IsTrue(SearchQuery.Parse(" ").Matches("qualsiasi"));
}
[TestMethod]
public async Task Search_AsksTheProvidersOfTheScope_AndLeavesOutTheOnesThatFail()
{
var search = new GlobalSearchService(
[new Provider([SearchScope.All], "Aiuto"), new Failing(), new Provider([SearchScope.All, SearchScope.Documents], "Documento")],
NullLogger.Instance);
var all = await search.SearchAsync(Root, SearchQuery.Parse("ab"));
Assert.HasCount(2 * GlobalSearchService.PerProvider, all);
CollectionAssert.AreEqual(new[] { "Aiuto ab", "Documento ab" }, all.Select(h => h.Title).Distinct().ToList());
CollectionAssert.AreEqual(new[] { "Documento ab" }, (await search.SearchAsync(Root, SearchQuery.Parse("#ab"))).Select(h => h.Title).Distinct().ToList());
Assert.IsEmpty(await search.SearchAsync(Root, SearchQuery.Parse("a")), "Too short.");
Assert.IsEmpty(await search.SearchAsync(Root, SearchQuery.Parse(">ab")), "Commands are not records.");
Assert.IsTrue(search.Covers(SearchScope.Documents));
Assert.IsFalse(search.Covers(SearchScope.People));
}
private sealed class Provider(SearchScope[] scopes, string title) : ISearchProvider
{
public IReadOnlyCollection Scopes => scopes;
public Task> SearchAsync(Actor actor, SearchQuery query, CancellationToken cancellationToken) =>
Task.FromResult>([.. Enumerable.Range(0, 20).Select(i => new SearchHit("g", "file", title + " " + query.Text, null, "x"))]);
}
private sealed class Failing : ISearchProvider
{
public IReadOnlyCollection Scopes => [SearchScope.All];
public Task> SearchAsync(Actor actor, SearchQuery query, CancellationToken cancellationToken) =>
throw new InvalidOperationException("broken");
}
}