using System.Collections.Concurrent; using Febe.Core.Abstractions; using Febe.Core.Collection.Readers; using Febe.Core.Collection.Search; using Febe.Core.Engine; using Febe.Tests.Engine.Support; using Febe.Tests.Support; namespace Febe.Tests.Engine; /// /// The service of the profile search (issue #37) over a scripted browser half: what the window sees while Alberto /// types, the remembered answers, the stops, and the rest page outside sessions. /// [TestClass] public sealed class ProfileSearchServiceTests { private const string Client = "0123456789abcdef"; private static readonly ProfileSearchOptions Fast = new() { EngineDebounce = TimeSpan.Zero, HoldWindow = TimeSpan.Zero, }; [TestMethod] public async Task WithoutTheBrowserOnlyTheLocalSuggestionsWork() { await using var bed = await EngineTestBed.CreateAsync(); await using var search = new ProfileSearchService(bed.Services, Fast); search.Start(); var view = search.Update(Client, "mario"); Assert.AreEqual(SearchState.Unavailable, view.State); StringAssert.Contains(view.Message!, "profili che segui"); Assert.AreEqual(Client, view.Owner); } [TestMethod] public async Task TextsThatAreNotTypedStayLocal() { await using var bed = await EngineTestBed.CreateAsync(); await using var search = new ProfileSearchService(bed.Services, Fast); var runner = new ScriptedSearch(bed.Services.PageTurns); search.Attach(runner, null); search.Start(); Assert.AreEqual(SearchState.LocalOnly, search.Update(Client, "m").State); Assert.AreEqual(SearchState.LocalOnly, search.Update(Client, "anna\nbea").State); Assert.AreEqual(SearchState.Refused, search.Update(Client, "anna\tbea").State); Assert.AreEqual(SearchState.Idle, search.Update(Client, string.Empty).State); await Task.Delay(100); Assert.AreEqual(0, runner.Steps, "nothing is typed on the site"); } [TestMethod] public async Task TheAnswerOfTheSiteBecomesTheViewAndIsRemembered() { await using var bed = await EngineTestBed.CreateAsync(); await using var search = new ProfileSearchService(bed.Services, Fast); var runner = new ScriptedSearch(bed.Services.PageTurns); search.Attach(runner, null); search.Start(); var first = search.Update(Client, "Mario"); Assert.AreEqual(SearchState.Waiting, first.State); await TestWait.UntilAsync(() => search.Current.State == SearchState.Ready, "the answer of the site"); var ready = search.Current; Assert.AreEqual("mario", ready.Text); CollectionAssert.AreEqual(new[] { "mario.rossi", "mario.bianchi" }, ready.Hits.Select(h => h.Username).ToArray()); Assert.IsTrue(ready.Version > first.Version); Assert.AreEqual("1", search.Known("@Mario.Rossi")!.InstagramId, "the server keeps the identifier for adding"); search.Update(Client, "luca"); await TestWait.UntilAsync(() => search.Current.State == SearchState.Empty, "an empty answer"); var steps = runner.Steps; var again = search.Update(Client, "mario"); Assert.AreEqual(SearchState.Ready, again.State, "a text seen a moment ago comes from Febe's memory"); Assert.HasCount(2, again.Hits); await Task.Delay(100); Assert.AreEqual(steps, runner.Steps, "no new step on the site"); } [TestMethod] public async Task AnotherWindowTakesTheSearchOverAndOnlyTheOwnerEndsIt() { await using var bed = await EngineTestBed.CreateAsync(); await using var search = new ProfileSearchService(bed.Services, Fast); search.Attach(new ScriptedSearch(bed.Services.PageTurns), null); search.Start(); search.Update(Client, "mario"); var other = search.Update("fedcba9876543210", "luca"); Assert.AreEqual("fedcba9876543210", other.Owner); search.End(Client); Assert.AreNotEqual(SearchState.Idle, search.Current.State, "the end of a window that no longer owns the search is ignored"); search.End("fedcba9876543210"); Assert.AreEqual(SearchState.Idle, search.Current.State); } [TestMethod] public async Task AStopOfTheBreakerStopsTheSearchAndTheGovernorsRefusalIsShown() { await using var bed = await EngineTestBed.CreateAsync(); await using var search = new ProfileSearchService(bed.Services, Fast); var runner = new ScriptedSearch(bed.Services.PageTurns); search.Attach(runner, null); search.Start(); runner.Next = new SearchStepResult(SearchOutcome.Denied, "mario", "Fuori dalla fascia oraria (prova).", Denial: Permit.Deny(ActionKind.ProfileSearch, null, DenialReason.OutsideActiveWindow, "Fuori dalla fascia oraria (prova).")); search.Update(Client, "mario"); await TestWait.UntilAsync(() => search.Current.State == SearchState.OutsideWindow, "the refusal of the Governor"); await bed.Breaker.ReportAsync(new Signal(SignalLevel.Challenge, "challenge-url", null, bed.Clock.Now)); await TestWait.UntilAsync(() => search.Current.State == SearchState.Stopped, "the stop of the breaker"); Assert.AreEqual(SearchState.Stopped, search.Update(Client, "anna").State, "no new step while the breaker is open"); } [TestMethod] public async Task OutsideSessionsThePageGoesToRestWhenTheDialogCloses() { await using var bed = await EngineTestBed.CreateAsync(); await using var search = new ProfileSearchService(bed.Services, Fast); var runner = new ScriptedSearch(bed.Services.PageTurns); search.Attach(runner, null); search.Start(); search.Update(Client, "mario"); await TestWait.UntilAsync(() => search.Current.State == SearchState.Ready, "the answer"); var ended = bed.Clock.Now; search.End(Client); await Task.Delay(100); Assert.AreEqual(0, runner.Rests, "not before the grace"); await TestWait.UntilAsync( () => { bed.Clock.Advance(TimeSpan.FromSeconds(1)); return runner.Rests == 1; }, "the rest page"); Assert.IsTrue(bed.Clock.Now - ended >= search.Options.EndGrace); Assert.IsNull(bed.Services.PageTurns.LastUser); } [TestMethod] public async Task DuringASessionTheSearchDoesNotRestThePage() { await using var bed = await EngineTestBed.CreateAsync(); await bed.BeginSessionAsync(); await using var search = new ProfileSearchService(bed.Services, Fast); var runner = new ScriptedSearch(bed.Services.PageTurns); search.Attach(runner, null); search.Start(); search.Update(Client, "mario"); await TestWait.UntilAsync(() => search.Current.State == SearchState.Ready, "the answer"); search.End(Client); bed.Clock.Advance(TimeSpan.FromMinutes(5)); await Task.Delay(100); Assert.AreEqual(0, runner.Rests, "the session rests the page when it ends"); } [TestMethod] public async Task TheSearchWaitsForTheEngineToGiveThePage() { await using var bed = await EngineTestBed.CreateAsync(); await using var search = new ProfileSearchService(bed.Services, Fast); var runner = new ScriptedSearch(bed.Services.PageTurns); search.Attach(runner, null); search.Start(); var engine = await bed.Services.PageTurns.TakeAsync(PageUser.Engine, CancellationToken.None); var view = search.Update(Client, "mario"); Assert.AreEqual(SearchState.Waiting, view.State); StringAssert.Contains(view.Message!, "raccolta"); await TestWait.UntilAsync(() => bed.Services.PageTurns.IsWaiting(PageUser.Search), "the search in the queue"); Assert.AreEqual(0, runner.Steps); await engine.DisposeAsync(); await TestWait.UntilAsync(() => search.Current.State == SearchState.Ready, "the step after the engine's"); } [TestMethod] public async Task ASessionThatEndsWhileTheSearchHoldsThePageLeavesTheRestToTheSearch() { await using var bed = await EngineTestBed.CreateAsync(); await bed.BeginSessionAsync(); await using var search = new ProfileSearchService(bed.Services, Fast); var turns = bed.Services.PageTurns; // Inside a session the page is the engine's: the real runner types on it without opening one. turns.NoteOpened(PageUser.Engine); var runner = new ScriptedSearch(turns) { OpensPage = false, Gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously) }; search.Attach(runner, null); search.Start(); search.Update(Client, "mario"); await TestWait.UntilAsync(() => turns.Holder == PageUser.Search && runner.Steps == 1, "the search holds the page"); Assert.AreEqual(PageUser.Engine, turns.LastUser, "the search did not open the page"); // The session ends now (EngineHost.EndSessionAsync): its rest is left to the search. bed.Runtime.CurrentSession = null; Assert.IsNull(await turns.TakeForRestAsync(CancellationToken.None)); Assert.IsTrue(turns.RestOwed); runner.Gate.SetResult(); await TestWait.UntilAsync(() => search.Current.State == SearchState.Ready, "the answer"); search.End(Client); await TestWait.UntilAsync( () => { bed.Clock.Advance(TimeSpan.FromSeconds(1)); return runner.Rests == 1; }, "the rest page, by the search"); Assert.IsFalse(turns.RestOwed); Assert.IsNull(turns.LastUser); } [TestMethod] public async Task ASearchStillQueuedAtTheEndOfASessionRestsThePageEvenIfTheDialogCloses() { await using var bed = await EngineTestBed.CreateAsync(); await bed.BeginSessionAsync(); await using var search = new ProfileSearchService(bed.Services, Fast); var turns = bed.Services.PageTurns; turns.NoteOpened(PageUser.Engine); var runner = new ScriptedSearch(turns) { OpensPage = false }; search.Attach(runner, null); search.Start(); var recipe = await turns.TakeAsync(PageUser.Engine, CancellationToken.None); search.Update(Client, "mario"); await TestWait.UntilAsync(() => turns.IsWaiting(PageUser.Search), "the search in the queue"); bed.Runtime.CurrentSession = null; Assert.IsNull(await turns.TakeForRestAsync(CancellationToken.None), "the search waits: the rest is left to it"); search.End(Client); await recipe.DisposeAsync(); await TestWait.UntilAsync( () => { bed.Clock.Advance(TimeSpan.FromSeconds(1)); return runner.Rests == 1; }, "the rest page, although the search never typed"); Assert.AreEqual(0, runner.Steps); Assert.IsFalse(turns.RestOwed); } [TestMethod] public async Task WithTheSearchAwayTheEngineRestsThePageItself() { await using var bed = await EngineTestBed.CreateAsync(); var turns = bed.Services.PageTurns; turns.NoteOpened(PageUser.Engine); var turn = await turns.TakeForRestAsync(CancellationToken.None); Assert.IsNotNull(turn); Assert.AreEqual(PageUser.Engine, turns.Holder); Assert.IsFalse(turns.RestOwed); await turn.DisposeAsync(); Assert.IsNull(turns.Holder); } [TestMethod] public async Task ThoseFoundLatelyAreRememberedAlsoAfterManyAnswers() { await using var bed = await EngineTestBed.CreateAsync(); await using var search = new ProfileSearchService(bed.Services, Fast); var runner = new ScriptedSearch(bed.Services.PageTurns) { Many = true }; search.Attach(runner, null); search.Start(); // 60 answers of 8 profiles each: more than the 400 profiles Febe remembers. for (var i = 0; i < 60; i++) { var text = $"p{i:D2}"; search.Update(Client, text); await TestWait.UntilAsync(() => search.Current.State == SearchState.Ready && search.Current.Text == text, "the answer for " + text); } for (var i = 0; i < 8; i++) { Assert.IsNotNull(search.Known($"p59.{i}"), "every profile of the last answer"); Assert.IsNotNull(search.Known($"p20.{i}"), "and of the ones before, up to 400 profiles"); } Assert.IsNull(search.Known("p00.0"), "the oldest go first"); } [TestMethod] public async Task TheSameTextWrittenAgainAfterAFailureIsTriedAgain() { await using var bed = await EngineTestBed.CreateAsync(); await using var search = new ProfileSearchService(bed.Services, Fast); var runner = new ScriptedSearch(bed.Services.PageTurns); search.Attach(runner, null); search.Start(); runner.Next = new SearchStepResult(SearchOutcome.FocusLost, "mario", "La casella «Cerca» di Instagram non è più attiva: riprova."); search.Update(Client, "mario"); await TestWait.UntilAsync(() => search.Current.State == SearchState.Failed, "the failure"); search.Update(Client, "mario "); await TestWait.UntilAsync(() => search.Current.State == SearchState.Ready, "the second try"); Assert.AreEqual(2, runner.Steps); } [TestMethod] public async Task OutsideTheWindowTheSearchResumesByItselfWhenTheWindowOpens() { await using var bed = await EngineTestBed.CreateAsync(); await using var search = new ProfileSearchService(bed.Services, Fast); var runner = new ScriptedSearch(bed.Services.PageTurns); search.Attach(runner, null); search.Start(); var opens = bed.Clock.Now + TimeSpan.FromMinutes(30); runner.Next = new SearchStepResult(SearchOutcome.Denied, "mario", "Fuori dalla fascia oraria (prova).", Denial: Permit.Deny(ActionKind.ProfileSearch, null, DenialReason.OutsideActiveWindow, "Fuori dalla fascia oraria (prova).", opens)); search.Update(Client, "mario"); await TestWait.UntilAsync(() => search.Current.State == SearchState.OutsideWindow, "the refusal"); Assert.AreEqual(opens, search.Current.RetryAfter); bed.Clock.Advance(TimeSpan.FromMinutes(31)); await TestWait.UntilAsync(() => search.Current.State == SearchState.Ready, "the search once the window opens"); } [TestMethod] public async Task DuringThePauseNothingIsTypedAndRiprendiResumesTheSearch() { await using var bed = await EngineTestBed.CreateAsync(); await using var search = new ProfileSearchService(bed.Services, Fast); var runner = new ScriptedSearch(bed.Services.PageTurns); search.Attach(runner, null); search.Start(); bed.Runtime.IsPaused = true; var paused = search.Update(Client, "mario"); Assert.AreEqual(SearchState.Stopped, paused.State); StringAssert.Contains(paused.Message!, "pausa"); await Task.Delay(100); Assert.AreEqual(0, runner.Steps); bed.Runtime.IsPaused = false; await TestWait.UntilAsync( () => { bed.Clock.Advance(TimeSpan.FromSeconds(1)); return search.Current.State == SearchState.Ready; }, "the search after «Riprendi»"); } /// A browser half that answers from a small list, at once. private sealed class ScriptedSearch(PageTurns turns) : IProfileSearchRunner { private static readonly (string Id, string Username)[] Profiles = [("1", "mario.rossi"), ("2", "mario.bianchi"), ("3", "anna.verdi")]; private readonly ConcurrentQueue _next = new(); private int _steps; private int _rests; /// Opens the page itself (outside sessions); false: types on the page the engine opened. public bool OpensPage { get; init; } = true; /// When set, every step waits for it before answering (the search holds the page meanwhile). public TaskCompletionSource? Gate { get; init; } /// Eight invented profiles «text.0» … «text.7» for every text. public bool Many { get; init; } public string? NotConfiguredReason => null; public double WaitMultiplier => 1; public int Steps => Volatile.Read(ref _steps); public int Rests => Volatile.Read(ref _rests); public SearchStepResult Next { set => _next.Enqueue(value); } public async Task SearchAsync(Func wanted, CancellationToken ct) { Interlocked.Increment(ref _steps); if (OpensPage) { turns.NoteOpened(PageUser.Search); } else { turns.NoteSearchUsedPage(); } if (Gate is { } gate) { await gate.Task.WaitAsync(ct); } if (_next.TryDequeue(out var scripted)) { return scripted; } var text = wanted(); if (text is null) { return new SearchStepResult(SearchOutcome.Interrupted, string.Empty, null); } List hits = Many ? [.. Enumerable.Range(0, 8).Select(i => new SearchProfile(i, new ProfileInfo { Id = $"{text}-{i}", Username = $"{text}.{i}" }, false))] : [.. Profiles .Where(p => p.Username.Contains(text, StringComparison.Ordinal)) .Select((p, i) => new SearchProfile(i, new ProfileInfo { Id = p.Id, Username = p.Username }, false))]; var answer = new SearchAnswer(hits); return new SearchStepResult(hits.Count == 0 ? SearchOutcome.Empty : SearchOutcome.Ready, text, null, answer); } public Task SettleAsync(CancellationToken ct) => Task.CompletedTask; public Task RestAsync(CancellationToken ct) { Interlocked.Increment(ref _rests); return Task.CompletedTask; } } }