Ricerca dei profili con suggerimenti e foto (#37)
verifica / controlli (push) Successful in 20s
verifica / prove (push) Failing after 19m40s
verifica / installatore (push) Skipped
verifica / immagine (push) Skipped

«Aggiungi account» ha una sola casella: mentre Alberto scrive compaiono
subito i suggerimenti locali, poi i profili di Instagram con la foto, come
chiesto in #37. Il browser di Febe scrive nella casella «Cerca» di Instagram
con tasti veri da una mappa chiusa (mai Invio, Tab o Esc), controlla prima
il fuoco, legge la risposta della pagina e non clicca mai un risultato.

La ricerca ha una categoria propria nel Governatore, con tetti larghi che
non consumano quelli della raccolta, e si dà il turno con il motore
sull'unica pagina; a fine sessione la pagina torna comunque al riposo. Le
foto passano dal CDN con un permesso ciascuna e restano solo in memoria.

Le risposte di Alberto del 15 novembre (controllo del fuoco, turni, evento
requestWillBeSent, niente foto dei seguiti per ora) sono in §6.1 e in
docs/decisioni.md. Su Instagram vero la ricerca parte quando i bersagli
search-open e search-box saranno raccolti dal vivo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-15 16:30:03 +01:00
1 parent 5e417c666d
commit 9941a2fa1f
98 files changed
+8021 -229

No files matched your search

@@ -8,6 +8,7 @@ using Febe.Core.Collection.Downloads;
using Febe.Core.Collection.Privacy;
using Febe.Core.Collection.Readers;
using Febe.Core.Collection.Recipes;
using Febe.Core.Collection.Search;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.SitoDiProva;
@@ -179,12 +180,20 @@ public sealed class DiagnosticPrivacyTests
diagnostics.DownloadSettled(new DownloadProgress(1, 2, 3, EntryKind.Story, DownloadStep.Retried) { Cause = DownloadCauses.Of(404) });
diagnostics.DownloadSettled(new DownloadProgress(1, 2, 3, EntryKind.Story, DownloadStep.Failed) { Cause = "https://cdn.esempio/marta.prova.jpg" });
// The profile search (issue #37): outcomes only, and a name where an outcome is expected becomes «altro».
diagnostics.SearchStepEnded(SearchOutcome.Ready);
diagnostics.SearchStepEnded(SearchOutcome.Empty);
diagnostics.SearchPhotoSettled("scaricata");
diagnostics.SearchPhotoSettled("marta.prova");
var text = Export(diagnostics.Collect(), clock);
Assert.AreEqual(0, diagnostics.Faults);
using var report = JsonDocument.Parse(text);
Assert.AreEqual(1, report.RootElement.GetProperty("sessioni").GetArrayLength());
Assert.AreEqual(1, report.RootElement.GetProperty("fuoriSessione").GetArrayLength());
StringAssert.Contains(text, "\"structure\"", "The unknown shape is there, by its keys.");
StringAssert.Contains(text, "\"searchSteps\"", "The steps of the search are there, by outcome.");
StringAssert.Contains(text, "\"altro\"", "An odd fate of a search photo becomes «altro».");
foreach (var hiddenMap in new[] { "{data:{counts:{#},node:{tags:{#:[]},edges:{seen:{#:{pk,seen}}},items:[{#:{pk}}]}}}" })
{
StringAssert.Contains(text, hiddenMap, "The maps are there, without their names.");
@@ -457,11 +466,12 @@ internal static partial class ReportLeaks
}
values.UnionWith(CdpResourceTypes);
values.UnionWith(CollectionDiagnostics.SearchPhotoOutcomes);
foreach (var type in new[]
{
typeof(SessionOutcome), typeof(SessionStopCause), typeof(RecipeStatus), typeof(RecipeKind), typeof(SignalLevel), typeof(ActionKind),
typeof(DenialReason), typeof(EntryKind), typeof(DownloadStep), typeof(BodyDropReason), typeof(HostKind), typeof(TargetCheckStatus),
typeof(SaveOutcome),
typeof(SaveOutcome), typeof(SearchOutcome),
})
{
values.UnionWith(Enum.GetNames(type));
@@ -478,7 +488,7 @@ internal static partial class ReportLeaks
"count", "resourceType", "mime", "status", "bytes", "maxBytes", "recognized", "empty", "unrelated", "unrecognized", "notSite",
"notRead", "contents", "profiles", "dropped", "reason", "structure", "verdict", "target", "kind", "signal", "actions",
"newEntries", "level", "code", "action", "saves", "files", "skipped", "step", "requests", "ok", "cdn", "error", "cause", "late",
"righeRovinate", "erroriRegistratore", "fileIlleggibili", "sessioniSenzaFine",
"righeRovinate", "erroriRegistratore", "fileIlleggibili", "sessioniSenzaFine", "searchSteps", "searchPhotos",
];
private static IEnumerable<string> Literals(SiteMap map) =>
@@ -70,6 +70,8 @@ public sealed class InstagramReaderTests
Vocabulary.Profile.IsFollowed, Vocabulary.Profile.PostCount, Vocabulary.Profile.Picture, Vocabulary.Profile.LatestStoryAt,
Vocabulary.Highlight.Id, Vocabulary.Highlight.Title, Vocabulary.Highlight.Owner, Vocabulary.Highlight.Items, Vocabulary.Highlight.Cover,
Vocabulary.Page.HasMore, Vocabulary.Page.Cursor, Vocabulary.Viewer,
Vocabulary.Search.Root, Vocabulary.Search.Items, Vocabulary.Search.Position, Vocabulary.Search.Profile, Vocabulary.Search.Id, Vocabulary.Search.Username,
Vocabulary.Search.DisplayName, Vocabulary.Search.Picture, Vocabulary.Search.Verified,
};
foreach (var path in concepts.SelectMany(c => c.Paths))
{
@@ -328,7 +330,9 @@ public sealed class InstagramReaderTests
{
var search = ReadSample("ricerca-profili");
Assert.AreEqual(ReadShape.Recognized, search.Shape);
Assert.AreEqual(5, search.Profiles.Count);
// Issue #37: the profiles of a search answer are results of the search, not followed or seen profiles.
Assert.AreEqual(0, search.Profiles.Count);
Assert.HasCount(5, search.Search!.Hits);
Assert.AreEqual(0, search.Contents.Count);
var suggested = ReadSample("profili-suggeriti");
@@ -0,0 +1,827 @@
using System.Text.Json;
using System.Text.Json.Nodes;
using Febe.Browser.Cdp;
using Febe.Browser.Gestures;
using Febe.Browser.Targets;
using Febe.Core.Abstractions;
using Febe.Core.Collection;
using Febe.Core.Collection.Readers;
using Febe.Core.Collection.Recipes;
using Febe.Core.Collection.Search;
using Febe.Core.Engine;
using Febe.Tests.Collection.Support;
namespace Febe.Tests.Collection;
/// <summary>
/// The profile search on the site (issue #37): the text rules, the closed key map, the reader of the answer, the
/// capture's own buffer, the step on a fake page with a search box, and the photo cache. Nothing here contacts a site.
/// </summary>
[TestClass]
public sealed class ProfileSearchTests
{
private static readonly DateTimeOffset Start = new(2026, 11, 15, 11, 0, 0, TimeSpan.Zero);
// ------------------------------------------------------------------------------------------------ text rules
[TestMethod]
[DataRow("mario", "mario")]
[DataRow(" @Mario.Rossi ", "mario.rossi")]
[DataRow("Niccolò", "niccolo")]
[DataRow("mario rossi", "mario rossi")]
[DataRow("https://www.instagram.com/mario_rossi/", "mario_rossi")]
[DataRow("instagram.com/Mario_Rossi?igsh=x", "mario_rossi")]
public void ATypableTextIsCleanedAsTheSiteWouldTypeIt(string raw, string typed)
{
var query = SearchText.Normalize(raw);
Assert.AreEqual(SearchQueryKind.Typable, query.Kind);
Assert.AreEqual(typed, query.Typed);
}
[TestMethod]
[DataRow("mario\nrossi", SearchQueryKind.SeveralNames)]
[DataRow("mario\r", SearchQueryKind.SeveralNames)]
[DataRow("mario, rossi", SearchQueryKind.SeveralNames)]
[DataRow("a;b", SearchQueryKind.SeveralNames)]
[DataRow("instagram.com/a instagram.com/b", SearchQueryKind.SeveralNames)]
[DataRow("mario\trossi", SearchQueryKind.Refused)]
[DataRow("mario​rossi", SearchQueryKind.Refused)]
[DataRow("m", SearchQueryKind.LocalOnly)]
[DataRow("mario-rossi", SearchQueryKind.LocalOnly)]
[DataRow("mario+", SearchQueryKind.LocalOnly)]
[DataRow("instagram.com/p/ABC123/", SearchQueryKind.LocalOnly)]
[DataRow(" ", SearchQueryKind.Empty)]
[DataRow("", SearchQueryKind.Empty)]
public void TextsFebeNeverTypesStayLocal(string raw, SearchQueryKind kind)
{
var query = SearchText.Normalize(raw);
Assert.AreEqual(kind, query.Kind);
Assert.AreEqual(string.Empty, query.Typed, "nothing to type");
}
[TestMethod]
public void AtMostFortyCharactersAreTyped()
{
Assert.AreEqual(SearchQueryKind.Typable, SearchText.Normalize(new string('a', 40)).Kind);
Assert.AreEqual(SearchQueryKind.LocalOnly, SearchText.Normalize(new string('a', 41)).Kind);
}
[TestMethod]
public void EveryTypableTextHasAKeyForEachCharacterAndNothingElseDoes()
{
foreach (var c in "abcdefghijklmnopqrstuvwxyz0123456789._ ")
{
Assert.IsNotNull(SearchKeyMap.For(c), $"«{c}»");
}
foreach (var c in "\n\r\t\u001bA-@#é+/\\'\"")
{
Assert.IsNull(SearchKeyMap.For(c), $"U+{(int)c:X4} must have no key");
}
Assert.IsTrue(SearchKeyMap.CanType(SearchText.Normalize("Mario Rossi_92.").Typed));
var underscore = SearchKeyMap.For('_')!;
Assert.AreEqual("Minus", underscore.Code);
}
// ------------------------------------------------------------------------------------------------- the reader
[TestMethod]
public void TheSearchAnswerOfTheCleanedSampleGivesFiveProfilesInOrder()
{
var reader = new ShapeReader(ReaderVocabulary.LoadInstagram());
using var document = JsonDocument.Parse(File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "campioni", "instagram", "000002-ricerca-profili.json")));
var body = document.RootElement.GetProperty("corpo");
var result = reader.Read(body);
Assert.AreEqual(ReadShape.Recognized, result.Shape);
Assert.IsNotNull(result.Search);
Assert.AreEqual(0, result.Profiles.Count, "search results are not followed profiles");
Assert.AreEqual(0, result.Contents.Count);
var hits = result.Search.Hits;
Assert.HasCount(5, hits);
CollectionAssert.AreEqual(new[] { 0, 1, 2, 3, 4 }, hits.Select(h => h.Position).ToArray());
var users = body.GetProperty("data").GetProperty("xdt_api__v1__fbsearch__topsearch_connection").GetProperty("users").EnumerateArray().ToList();
for (var i = 0; i < hits.Count; i++)
{
var user = users[i].GetProperty("user");
Assert.AreEqual(user.GetProperty("pk").GetString(), hits[i].Profile.Id);
Assert.AreEqual(user.GetProperty("username").GetString(), hits[i].Profile.Username);
Assert.AreEqual(user.GetProperty("profile_pic_url").GetString(), hits[i].Profile.Picture?.Url);
Assert.IsFalse(hits[i].IsVerified);
}
}
[TestMethod]
public void AnEmptyAnswerIsAnAnswerAndTheTestSiteReadsTheSameShape()
{
var instagram = new ShapeReader(ReaderVocabulary.LoadInstagram());
var empty = instagram.Read(Parse("""{"data":{"xdt_api__v1__fbsearch__topsearch_connection":{"hashtags":[],"places":[],"users":[]}},"extensions":{"is_final":true}}"""));
Assert.AreEqual(ReadShape.Recognized, empty.Shape);
Assert.IsNotNull(empty.Search);
Assert.HasCount(0, empty.Search.Hits);
var prova = new ShapeReader(ReaderVocabulary.LoadTestSite());
var answer = prova.Read(Answer(("1", "mario.rossi"), ("2", "maria.bianchi")));
Assert.IsNotNull(answer.Search);
CollectionAssert.AreEqual(new[] { "mario.rossi", "maria.bianchi" }, answer.Search.Hits.Select(h => h.Profile.Username).ToArray());
Assert.AreEqual(0, answer.Profiles.Count);
}
[TestMethod]
public void TheVocabularyOfTheSearchComesFromTheRealSample()
{
var search = ReaderVocabulary.LoadInstagram().Search;
Assert.IsTrue(search.IsSet);
var text = File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "campioni", "instagram", "000002-ricerca-profili.json"));
foreach (var key in new[] { search.Root, search.Items, search.Position, search.Profile, search.Id, search.Username, search.DisplayName, search.Picture, search.Verified }.SelectMany(k => k.Paths))
{
StringAssert.Contains(text, $"\"{key}\"", $"«{key}» non compare nel campione ripulito della ricerca.");
}
}
[TestMethod]
public void SearchAnswersGoToTheirOwnBufferNotToTheRecipes()
{
var clock = new InstantClock(Start);
var capture = new CaptureCollector(new ShapeReader(ReaderVocabulary.LoadTestSite()), clock);
var mark = capture.Mark();
var searchMark = capture.SearchMark();
capture.Accept(Descriptor("r1", clock), Answer(("1", "mario.rossi")));
Assert.HasCount(0, capture.Since(mark), "a recipe never sees a search answer");
Assert.HasCount(1, capture.SearchSince(searchMark));
Assert.IsNotNull(capture.LastArrivalAt);
}
[TestMethod]
public void RecordsOfTheSearchNeverPrintNamesOrTexts()
{
var hit = new SearchHit(0, "12345678901", "segreto.nome", "Nome Segreto", true, "0123456789abcdef0123456789abcdef", true);
var view = new SearchView(3, "aaaaaaaaaaaaaaaa", "segreto", SearchState.Ready, null, [hit], null);
var query = SearchText.Normalize("segreto.nome");
var step = new SearchStepResult(SearchOutcome.Ready, "segreto.nome", null);
var photo = new SearchPhotoRequest("12345678901", new Uri("https://cdn.esempio/segreto.jpg?firma=abc"));
foreach (var text in new[] { hit.ToString(), view.ToString(), query.ToString(), step.ToString(), photo.ToString() })
{
foreach (var secret in new[] { "segreto", "Segreto", "12345678901", "0123456789abcdef", "firma", "aaaaaaaa" })
{
Assert.IsFalse(text.Contains(secret, StringComparison.Ordinal), $"«{text}» prints «{secret}»");
}
}
}
[TestMethod]
public void TheFocusCheckIsAReadOnlyScriptThatNeverReturnsTheText()
{
var map = TargetMap.LoadEmbedded("bersagli.prova.json");
var expression = TargetResolver.BuildFocusExpression(map.Get(SiteTargets.SearchBox));
ReadOnlyScriptGuard.EnsureReadOnly(expression);
StringAssert.Contains(expression, "value.length");
StringAssert.Contains(expression, "return { found: true, focused: inBox, length, atEnd }", "the answer holds a length, never the text");
}
// ------------------------------------------------------------------------------------------- one search step
[TestMethod]
public async Task AStepOpensTheSiteTypesTheTextAndReadsTheLatestAnswer()
{
var bed = new StepBed();
bed.Site.Profiles = [("1", "mario.rossi"), ("2", "mario.bianchi"), ("3", "luca.verdi")];
var result = await bed.Runner.SearchAsync(() => "mario", CancellationToken.None);
Assert.AreEqual(SearchOutcome.Ready, result.Outcome, result.Message);
Assert.AreEqual("mario", result.Typed);
CollectionAssert.AreEqual(new[] { "mario.rossi", "mario.bianchi" }, result.Answer!.Hits.Select(h => h.Profile.Username).ToArray(), "the answer for the whole text, not for a prefix");
Assert.AreEqual("mario", bed.Site.Box);
Assert.AreEqual(1, bed.Site.Opened, "the home page, once");
CollectionAssert.AreEqual(new[] { SiteTargets.SearchOpen, SiteTargets.SearchBox }, bed.Site.Clicks, "only «Cerca» and the box: never a result");
Assert.AreEqual(3, bed.Governor.Granted(ActionKind.ProfileSearch), "home, focus, one burst");
Assert.AreEqual(PageUser.Search, bed.Turns.LastUser);
Assert.AreEqual(0, bed.Site.EnterPressed);
}
[TestMethod]
public async Task ANewTextKeepsTheCommonPrefixAndErasesOnlyTheRest()
{
var bed = new StepBed();
bed.Site.Profiles = [("1", "mario.rossi"), ("2", "matteo.neri")];
Assert.AreEqual(SearchOutcome.Ready, (await bed.Runner.SearchAsync(() => "mario", CancellationToken.None)).Outcome);
var keys = bed.Site.Keys;
var result = await bed.Runner.SearchAsync(() => "mat", CancellationToken.None);
Assert.AreEqual(SearchOutcome.Ready, result.Outcome, result.Message);
Assert.AreEqual("mat", bed.Site.Box);
Assert.AreEqual(keys + 3 + 1, bed.Site.Keys, "three Backspaces and one letter");
Assert.AreEqual(1, bed.Site.Opened, "the page is still the site: no new home");
CollectionAssert.AreEqual(new[] { "matteo.neri" }, result.Answer!.Hits.Select(h => h.Profile.Username).ToArray());
}
[TestMethod]
public async Task ATextInTheBoxThatFebeDidNotTypeIsErasedFirst()
{
var bed = new StepBed();
bed.Site.Profiles = [("1", "anna.blu")];
Assert.AreEqual(SearchOutcome.Ready, (await bed.Runner.SearchAsync(() => "anna", CancellationToken.None)).Outcome);
bed.Site.Box = "qualcosa";
var result = await bed.Runner.SearchAsync(() => "anna", CancellationToken.None);
Assert.AreEqual(SearchOutcome.Ready, result.Outcome, result.Message);
Assert.AreEqual("anna", bed.Site.Box);
}
[TestMethod]
public async Task NoProfileIsEmptyAndNoAnswerIsNotEmpty()
{
var bed = new StepBed();
bed.Site.Profiles = [("1", "mario.rossi")];
var empty = await bed.Runner.SearchAsync(() => "zzz", CancellationToken.None);
Assert.AreEqual(SearchOutcome.Empty, empty.Outcome);
Assert.AreEqual(0, bed.Signals.EmptyPages, "an empty search is not an empty page");
bed.Site.Answers = false;
var none = await bed.Runner.SearchAsync(() => "mario", CancellationToken.None);
Assert.AreEqual(SearchOutcome.NoAnswer, none.Outcome);
}
[TestMethod]
public async Task WithoutTheSessionCookieTheStepStopsAsADisconnection()
{
var bed = new StepBed();
bed.Site.Cookie = false;
var result = await bed.Runner.SearchAsync(() => "mario", CancellationToken.None);
Assert.AreEqual(SearchOutcome.NotConnected, result.Outcome);
Assert.AreEqual(1, bed.Signals.MissingCookie);
Assert.AreEqual(0, bed.Site.Opened);
Assert.AreEqual(0, bed.Governor.Granted(ActionKind.ProfileSearch));
}
[TestMethod]
public async Task ARefusalOfTheGovernorStopsBeforeAnyGesture()
{
var bed = new StepBed();
bed.Governor.Limit(ActionKind.ProfileSearch, 0);
var result = await bed.Runner.SearchAsync(() => "mario", CancellationToken.None);
Assert.AreEqual(SearchOutcome.Denied, result.Outcome);
Assert.AreEqual(DenialReason.HourlyBudgetReached, result.Denial!.Reason);
Assert.AreEqual(0, bed.Site.Opened);
Assert.AreEqual(0, bed.Site.Keys);
}
[TestMethod]
public async Task KeysThatDoNotReachTheBoxAreReported()
{
var bed = new StepBed();
bed.Site.IgnoreKeys = true;
var result = await bed.Runner.SearchAsync(() => "mario", CancellationToken.None);
Assert.AreEqual(SearchOutcome.KeysNotReceived, result.Outcome);
StringAssert.Contains(result.Message!, "non riceve i tasti");
}
[TestMethod]
public async Task AlbertoAtTheBrowserOrAnOpenBreakerTouchNothing()
{
var bed = new StepBed();
bed.Driving = true;
Assert.AreEqual(SearchOutcome.NotPossible, (await bed.Runner.SearchAsync(() => "mario", CancellationToken.None)).Outcome);
bed.Driving = false;
bed.Breaker.Current = new BreakerState(BreakerStatus.Throttled, Start.AddHours(1), null, null);
Assert.AreEqual(SearchOutcome.Stopped, (await bed.Runner.SearchAsync(() => "mario", CancellationToken.None)).Outcome);
Assert.AreEqual(0, bed.Site.Opened);
Assert.AreEqual(0, bed.Governor.Requests.Count);
}
[TestMethod]
public async Task OnInstagramTheSearchWaitsForItsTargets()
{
var bed = new StepBed(SiteMap.LoadInstagram());
var result = await bed.Runner.SearchAsync(() => "mario", CancellationToken.None);
Assert.AreEqual(SearchOutcome.NotConfigured, result.Outcome);
StringAssert.Contains(result.Message!, "«Cerca»");
Assert.AreEqual(0, bed.Site.Opened);
Assert.AreEqual(0, bed.Governor.Requests.Count);
}
[TestMethod]
public async Task ATextNoLongerWantedStopsBetweenTwoKeys()
{
var bed = new StepBed();
var wanted = "mariarosa";
bed.Site.OnKey = box =>
{
if (box.Length == 3)
{
wanted = null!;
}
};
var result = await bed.Runner.SearchAsync(() => wanted, CancellationToken.None);
Assert.AreEqual(SearchOutcome.Interrupted, result.Outcome);
Assert.AreEqual("mar", bed.Site.Box);
}
[TestMethod]
public async Task AnswersToTheTextsBeforeTheLastKeyAreNeverTakenForTheTextEvenWhenTheyArriveLater()
{
var bed = new StepBed();
bed.Site.Profiles = [("1", "marta.prova"), ("2", "mario.rossi"), ("3", "matteo.neri"), ("4", "luca.martini")];
// The page asks for every text without waiting, and the shorter the text the later its answer comes
// (the «disordine» of the test site): «m», «ma», «mar» and «mart» answer after «marta».
bed.Site.Disorder = true;
var result = await bed.Runner.SearchAsync(() => "marta", CancellationToken.None);
Assert.AreEqual(SearchOutcome.Ready, result.Outcome, result.Message);
Assert.AreEqual(5, bed.Site.Requests, "one request for each text the box held");
CollectionAssert.AreEqual(new[] { "marta.prova" }, result.Answer!.Hits.Select(h => h.Profile.Username).ToArray(), "the answer to «marta», not to a prefix");
// Later answers to the prefixes do not change what the next step takes either.
bed.Clock.Advance(TimeSpan.FromSeconds(5));
await bed.Clock.Delay(TimeSpan.Zero, CancellationToken.None);
var again = await bed.Runner.SearchAsync(() => "marta", CancellationToken.None);
CollectionAssert.AreEqual(new[] { "marta.prova" }, again.Answer!.Hits.Select(h => h.Profile.Username).ToArray());
}
[TestMethod]
public async Task ATextThePageAnswersFromItsMemoryUsesTheAnswerReadBeforeOnThatPage()
{
var bed = new StepBed();
bed.Site.Profiles = [("1", "marta.prova"), ("2", "mario.rossi")];
bed.Site.Memory = true;
Assert.AreEqual(SearchOutcome.Ready, (await bed.Runner.SearchAsync(() => "marta", CancellationToken.None)).Outcome);
Assert.AreEqual(SearchOutcome.Ready, (await bed.Runner.SearchAsync(() => "mar", CancellationToken.None)).Outcome);
var requests = bed.Site.Requests;
var back = await bed.Runner.SearchAsync(() => "marta", CancellationToken.None);
Assert.AreEqual(requests, bed.Site.Requests, "the page sends no request for a text it has already searched");
Assert.AreEqual(SearchOutcome.Ready, back.Outcome, back.Message);
CollectionAssert.AreEqual(new[] { "marta.prova" }, back.Answer!.Hits.Select(h => h.Profile.Username).ToArray());
}
[TestMethod]
public async Task OnThePageOfTheEngineTheNextLetterIsTheOnlyKeyUntilTheEngineOpensAnotherPage()
{
var bed = new StepBed();
bed.Site.Profiles = [("1", "maria.blu")];
// A session: the engine opened the page, the search types on it between two engine actions.
await bed.Site.OpenAsync("/", CancellationToken.None);
bed.Turns.NoteOpened(PageUser.Engine);
Assert.AreEqual(SearchOutcome.Ready, (await bed.Runner.SearchAsync(() => "mar", CancellationToken.None)).Outcome);
Assert.AreEqual(PageUser.Engine, bed.Turns.LastUser, "the search did not open a page");
var keys = bed.Site.Keys;
Assert.AreEqual(SearchOutcome.Ready, (await bed.Runner.SearchAsync(() => "mari", CancellationToken.None)).Outcome);
Assert.AreEqual(keys + 1, bed.Site.Keys, "one letter: what Febe typed on this page still holds");
// The engine opens another page: the box is gone, and Febe's record with it.
await bed.Site.OpenAsync("/marta.prova/", CancellationToken.None);
bed.Turns.NoteOpened(PageUser.Engine);
keys = bed.Site.Keys;
Assert.AreEqual(SearchOutcome.Ready, (await bed.Runner.SearchAsync(() => "maria", CancellationToken.None)).Outcome);
Assert.AreEqual(keys + 5, bed.Site.Keys, "the whole text in the new box, nothing erased");
Assert.AreEqual("maria", bed.Site.Box);
}
[TestMethod]
public async Task TheFocusIsLookedAtAgainAfterThePermitRightBeforeTheFirstKey()
{
var bed = new StepBed();
bed.Site.Profiles = [("1", "mario.rossi")];
Assert.AreEqual(SearchOutcome.Ready, (await bed.Runner.SearchAsync(() => "mar", CancellationToken.None)).Outcome);
var keys = bed.Site.Keys;
// While the Governor makes the burst wait, something takes the focus away from the box.
bed.Governor.OnRequest = kind =>
{
if (kind == ActionKind.ProfileSearch)
{
bed.Site.Focused = false;
}
};
var result = await bed.Runner.SearchAsync(() => "mario", CancellationToken.None);
Assert.AreEqual(SearchOutcome.FocusLost, result.Outcome);
Assert.AreEqual(keys, bed.Site.Keys, "not one key without the focus in the box");
}
[TestMethod]
public async Task TheRestPageIsSkippedAfterAVerification()
{
var bed = new StepBed();
await bed.Runner.SearchAsync(() => "mario", CancellationToken.None);
bed.Breaker.Current = new BreakerState(BreakerStatus.Challenge, null, null, null);
await bed.Runner.RestAsync(CancellationToken.None);
Assert.AreEqual(0, bed.Site.Rested);
bed.Breaker.Current = BreakerState.Normal;
await bed.Runner.RestAsync(CancellationToken.None);
Assert.AreEqual(1, bed.Site.Rested);
}
// ---------------------------------------------------------------------------------------------- photo cache
[TestMethod]
public void ThePhotoCacheIsBoundedAndANewPictureReplacesTheOld()
{
var clock = new InstantClock(Start);
var cache = new SearchPhotoCache(clock, new ProfileSearchOptions { MaxPhotos = 2, MaxPhotoBytes = 1000 });
var a = cache.Put("1", "f1", new byte[100]);
StringAssert.Matches(a, new System.Text.RegularExpressions.Regex("^[0-9a-f]{32}$"));
var b = cache.Put("2", "f2", new byte[100]);
Assert.IsTrue(cache.TryOpen(a, out var stream));
stream.Dispose();
cache.Put("3", "f3", new byte[100]);
Assert.IsFalse(cache.TryOpen(b, out _), "the least recently used goes first");
Assert.IsTrue(cache.TryOpen(a, out var again));
again.Dispose();
var replaced = cache.Put("1", "f9", new byte[50]);
Assert.IsFalse(cache.TryOpen(a, out _));
Assert.AreEqual(replaced, cache.KeyOf("1"));
Assert.IsTrue(cache.Has("1", "f9"));
Assert.IsFalse(cache.Has("1", "f1"));
clock.Advance(TimeSpan.FromDays(4));
Assert.IsNull(cache.KeyOf("1"), "photos expire");
Assert.AreEqual(0, cache.Count);
}
[TestMethod]
public void TheFileHashLeavesTheSignatureOut()
{
var one = SearchPhotoCache.FileHash(new Uri("https://cdn.esempio/v/t51/123_n.jpg?stp=a&oh=1"));
var two = SearchPhotoCache.FileHash(new Uri("https://cdn.esempio/v/t51/123_n.jpg?stp=b&oh=2"));
var other = SearchPhotoCache.FileHash(new Uri("https://cdn.esempio/v/t51/456_n.jpg?stp=a&oh=1"));
Assert.AreEqual(one, two);
Assert.AreNotEqual(one, other);
}
// ------------------------------------------------------------------------------------------------ support
private static JsonElement Parse(string json)
{
using var document = JsonDocument.Parse(json);
return document.RootElement.Clone();
}
private static JsonElement Answer(params (string Id, string Username)[] users)
{
var list = new JsonArray();
for (var i = 0; i < users.Length; i++)
{
list.Add(new JsonObject
{
["position"] = i,
["user"] = new JsonObject
{
["username"] = users[i].Username,
["is_verified"] = false,
["full_name"] = "Nome " + i,
["pk"] = users[i].Id,
["profile_pic_url"] = $"https://cdn.prova/foto/{users[i].Id}_n.jpg?firma=x",
["id"] = users[i].Id,
},
});
}
var body = new JsonObject
{
["data"] = new JsonObject
{
["xdt_api__v1__fbsearch__topsearch_connection"] = new JsonObject { ["hashtags"] = new JsonArray(), ["places"] = new JsonArray(), ["users"] = list },
},
["extensions"] = new JsonObject { ["is_final"] = true },
};
return Parse(body.ToJsonString());
}
private static ResponseDescriptor Descriptor(string id, IClock clock) =>
new(id, HostKind.Site, "http://127.0.0.1:5000/dati/cerca", "127.0.0.1:5000", "/dati/cerca", 200, "application/json", "Fetch", false, clock.Now);
/// <summary>A clock whose waits pass at once and run what falls due meanwhile (answers arrive while the step waits).</summary>
private sealed class InstantClock(DateTimeOffset start) : IClock
{
private readonly List<(DateTimeOffset At, Action Action)> _due = [];
public DateTimeOffset Now { get; private set; } = start;
public TimeZoneInfo LocalZone => TimeZoneInfo.Utc;
public void After(TimeSpan delay, Action action) => _due.Add((Now + delay, action));
public void Advance(TimeSpan time) => Now += time;
public Task Delay(TimeSpan time, CancellationToken ct)
{
ct.ThrowIfCancellationRequested();
if (time > TimeSpan.Zero)
{
Now += time;
}
foreach (var item in _due.Where(d => d.At <= Now).ToList())
{
_due.Remove(item);
item.Action();
}
return Task.CompletedTask;
}
}
private sealed class FakeSignals : IStopSignals
{
public int EmptyPages { get; private set; }
public int MissingCookie { get; private set; }
public event EventHandler<Signal>? SignalRaised
{
add { }
remove { }
}
public Signal? ObserveEmptyPage(string? url = null)
{
EmptyPages++;
return null;
}
public void ObserveNonEmptyPage()
{
}
public Signal? ObserveSessionCookie(bool present)
{
if (!present)
{
MissingCookie++;
}
return null;
}
}
private sealed class FakeBreaker : ICircuitBreaker
{
public BreakerState Current { get; set; } = BreakerState.Normal;
public BreakerState State => Current;
public void Report(Signal signal)
{
}
}
/// <summary>A page of the site with a «Cerca» button, a box, and answers that come 300 ms after each key.</summary>
private sealed class SearchSite(InstantClock clock, CaptureCollector capture) : IPageDriver, ISearchInput
{
private int _answers;
public bool OnSite { get; set; }
public bool PanelOpen { get; set; }
public bool Focused { get; set; }
public string Box { get; set; } = string.Empty;
public bool? Cookie { get; set; } = true;
public bool Answers { get; set; } = true;
public bool IgnoreKeys { get; set; }
/// <summary>The page asks for every text at once (no wait), and shorter texts are answered later.</summary>
public bool Disorder { get; set; }
/// <summary>The page answers a text it has already searched on this page from its memory, without a request.</summary>
public bool Memory { get; set; }
/// <summary>Requests the page sent for the search.</summary>
public int Requests { get; private set; }
private readonly HashSet<string> _memory = new(StringComparer.Ordinal);
public int EnterPressed { get; }
public (string Id, string Username)[] Profiles { get; set; } = [];
public Action<string>? OnKey { get; set; }
public int Opened { get; private set; }
public int Rested { get; private set; }
public int Keys { get; private set; }
public List<string> Clicks { get; } = [];
public double WaitMultiplier => 1;
public void BeginSession(double mood)
{
}
public Task<PageLoad> OpenAsync(string path, CancellationToken ct)
{
Opened++;
OnSite = true;
PanelOpen = false;
Focused = false;
Box = string.Empty;
_memory.Clear();
return Task.FromResult(new PageLoad(true, path, null));
}
public Task<string> CurrentPathAsync(CancellationToken ct) => Task.FromResult(OnSite ? "/" : string.Empty);
public Task<bool> IsOnSiteAsync(CancellationToken ct) => Task.FromResult(OnSite);
public Task<TargetCheck> FindAsync(string target, IReadOnlyDictionary<string, string>? parameters, CancellationToken ct) =>
Task.FromResult(new TargetCheck(target, TargetCheckStatus.Found, 1, string.Empty));
public Task<TargetCheck> ClickAsync(string target, IReadOnlyDictionary<string, string>? parameters, CancellationToken ct)
{
Clicks.Add(target);
var ok = target switch
{
SiteTargets.SearchOpen when OnSite => PanelOpen = true,
SiteTargets.SearchBox when PanelOpen => Focused = true,
_ => false,
};
return Task.FromResult(new TargetCheck(target, ok ? TargetCheckStatus.Clicked : TargetCheckStatus.NotFound, ok ? 1 : 0, string.Empty));
}
public Task ScrollBurstAsync(CancellationToken ct) => throw new AssertFailedException("the search never scrolls");
public Task WaitAfterLoadAsync(CancellationToken ct) => clock.Delay(TimeSpan.FromSeconds(1), ct);
public Task WaitAsync(TimeSpan duration, CancellationToken ct) => clock.Delay(duration, ct);
public Task<bool> MaybeDistractionAsync(CancellationToken ct) => Task.FromResult(false);
public Task<bool?> HasSessionCookieAsync(CancellationToken ct) => Task.FromResult(Cookie);
public Task RestAsync(CancellationToken ct)
{
Rested++;
OnSite = false;
return Task.CompletedTask;
}
public Task<SearchFocus> FocusAsync(CancellationToken ct) =>
Task.FromResult(PanelOpen ? new SearchFocus(true, Focused, Focused ? Box.Length : null, true) : SearchFocus.None);
public Task EndKeyAsync(CancellationToken ct) => Task.CompletedTask;
public async Task EraseAsync(int count, Action? beforeKey, CancellationToken ct)
{
for (var i = 0; i < count; i++)
{
beforeKey?.Invoke();
Keys++;
if (Focused && !IgnoreKeys && Box.Length > 0)
{
Box = Box[..^1];
Answer();
}
await clock.Delay(TimeSpan.FromMilliseconds(110), ct);
}
}
public async Task<int> TypeAsync(Func<int, CancellationToken, ValueTask<char?>> next, CancellationToken ct)
{
var typed = 0;
while (await next(typed, ct) is { } c)
{
Assert.IsNotNull(SearchKeyMap.For(c), "only keys of the map");
Keys++;
typed++;
if (Focused && !IgnoreKeys)
{
Box += c;
Answer();
}
OnKey?.Invoke(Box);
await clock.Delay(TimeSpan.FromMilliseconds(110), ct);
}
return typed;
}
private void Answer()
{
if (!Answers)
{
return;
}
var text = Box;
var id = "s" + _answers++;
if (Disorder)
{
// No wait: a request for every text at once, the shorter ones answered later.
var order = Start();
clock.After(TimeSpan.FromMilliseconds(300 + (Math.Max(0, 8 - text.Length) * 250)), () => Reply(id, text, order));
return;
}
clock.After(TimeSpan.FromMilliseconds(300), () =>
{
// The site's debounce: only the answer for what the box holds then.
if (text != Box)
{
return;
}
if (Memory)
{
if (!_memory.Add(text))
{
// Shown from the page's memory: no request.
return;
}
var order = Start();
clock.After(TimeSpan.FromMilliseconds(200), () => Reply(id, text, order));
return;
}
Requests++;
var users = Profiles.Where(p => p.Username.Contains(text, StringComparison.Ordinal)).ToArray();
capture.Accept(Descriptor(id, clock), ProfileSearchTests.Answer(users));
});
}
/// <summary>The page starts a request: the capture learns its order, as from Network.requestWillBeSent.</summary>
private long Start()
{
Requests++;
((IResponseObserver)capture).OnRequestStarted(Requests);
return Requests;
}
private void Reply(string id, string text, long order)
{
var users = Profiles.Where(p => p.Username.Contains(text, StringComparison.Ordinal)).ToArray();
capture.Accept(Descriptor(id, clock) with { RequestOrder = order }, ProfileSearchTests.Answer(users));
}
}
private sealed class StepBed
{
public StepBed(SiteMap? map = null)
{
Clock = new InstantClock(Start);
Capture = new CaptureCollector(new ShapeReader(ReaderVocabulary.LoadTestSite()), Clock);
Site = new SearchSite(Clock, Capture);
Runner = new ProfileSearchRunner(
Site,
Site,
Capture,
map ?? SiteMap.LoadTestSite(),
Governor,
Signals,
Breaker,
Clock,
new SeededRandom(3),
Turns,
ProfileSearchOptions.Default,
() => Driving);
}
public InstantClock Clock { get; }
public CaptureCollector Capture { get; }
public SearchSite Site { get; }
public PermissiveGovernor Governor { get; } = new();
public FakeSignals Signals { get; } = new();
public FakeBreaker Breaker { get; } = new();
public PageTurns Turns { get; } = new();
public bool Driving { get; set; }
public ProfileSearchRunner Runner { get; }
}
}
@@ -0,0 +1,149 @@
using Febe.Core.Abstractions;
using Febe.Core.Collection.Readers;
using Febe.Core.Collection.Recipes;
using Febe.Core.Collection.Search;
using Febe.Core.Engine;
using Febe.Tests.Collection.Support;
using Febe.Tests.Support;
namespace Febe.Tests.Collection;
/// <summary>
/// The profile search (issue #37) against the local test site, with a real Chromium on a private Xvfb display: the
/// panel «Cerca», typing with key events, the answers in the shape of the cleaned sample, the photos from the CDN, and
/// the rest page. Never Instagram.
/// </summary>
[TestClass]
[TestCategory(SyntheticSite.Category)]
[DoNotParallelize]
public sealed class SearchIntegrationTests
{
private static SharedChromium? s_chromium;
private static string? s_unavailable;
private static SharedChromium Chromium => s_chromium ?? throw new InvalidOperationException("Browser non avviato.");
[ClassInitialize]
public static async Task StartAsync(TestContext context)
{
s_unavailable = SharedChromium.UnavailableReason();
if (s_unavailable is null)
{
s_chromium = await SharedChromium.StartAsync();
}
}
[ClassCleanup]
public static async Task StopAsync()
{
if (s_chromium is not null)
{
await s_chromium.DisposeAsync();
s_chromium = null;
}
}
[TestInitialize]
public void RequireBrowser()
{
if (s_unavailable is not null)
{
Assert.Inconclusive(s_unavailable);
}
}
[TestMethod]
[Timeout(90_000, CooperativeCancellation = true)]
public async Task TheSearchTypesInTheSitesBoxAndReadsItsAnswerWithoutOpeningAResult()
{
await using var h = await CollectionHarness.CreateAsync(Chromium);
var first = await h.Search.SearchAsync(() => "marta", CancellationToken.None);
Assert.AreEqual(SearchOutcome.Ready, first.Outcome, first.Message);
Assert.AreEqual("marta.prova", first.Answer!.Hits[0].Profile.Username);
Assert.AreEqual("/", await h.CurrentPathAsync(), "the page stays the home page: no result is opened");
Assert.AreEqual(PageUser.Search, h.Turns.LastUser);
Assert.IsTrue(h.Governor.Granted(ActionKind.ProfileSearch) >= 3, "every gesture after a permit");
Assert.AreEqual(0, h.Site.Control.RecentSearchWrites, "Enter is never pressed and no result is clicked");
// Alberto keeps typing: «marta» → «ma»: three Backspaces, the same box, a wider answer.
var second = await h.Search.SearchAsync(() => "ma", CancellationToken.None);
Assert.AreEqual(SearchOutcome.Ready, second.Outcome, second.Message);
Assert.IsTrue(second.Answer!.Hits.Count >= 1);
var none = await h.Search.SearchAsync(() => "zzzz", CancellationToken.None);
Assert.AreEqual(SearchOutcome.Empty, none.Outcome, none.Message);
await h.Search.RestAsync(CancellationToken.None);
Assert.IsFalse(await h.Driver.IsOnSiteAsync(CancellationToken.None), "back to the rest page");
}
[TestMethod]
[Timeout(90_000, CooperativeCancellation = true)]
public async Task ThePhotosOfTheResultsComeFromTheCdnIntoMemory()
{
await using var h = await CollectionHarness.CreateAsync(Chromium);
var result = await h.Search.SearchAsync(() => "prova", CancellationToken.None);
Assert.AreEqual(SearchOutcome.Ready, result.Outcome, result.Message);
var queue = h.Pipeline.SearchPhotos!;
queue.Enqueue(result.Answer!.Hits.Take(3).Select(x => new SearchPhotoRequest(x.Profile.Id, new Uri(x.Profile.Picture!.Url))));
await TestWait.UntilAsync(() => h.SearchPhotos.Count == 3, "three photos in memory");
var key = h.SearchPhotos.KeyOf(result.Answer.Hits[0].Profile.Id)!;
Assert.IsTrue(h.SearchPhotos.TryOpen(key, out var stream));
using (stream)
{
var head = new byte[2];
Assert.AreEqual(2, stream.Read(head));
CollectionAssert.AreEqual(new byte[] { 0xFF, 0xD8 }, head, "a JPEG");
}
Assert.IsTrue(h.DataBudget.Used > 0, "the bytes count in the daily data budget");
}
[TestMethod]
[Timeout(120_000, CooperativeCancellation = true)]
public async Task OutOfOrderAnswersAndThePagesMemoryStillGiveTheAnswerToTheWholeText()
{
await using var h = await CollectionHarness.CreateAsync(Chromium);
// «ricerca/disordine»: shorter texts are answered later; «ricerca/memoria»: the page sends no request for a
// text it has already searched. Both are read when the page loads: the first step opens the home page.
h.Site.Control.SearchDisorder = true;
h.Site.Control.SearchMemory = true;
var first = await h.Search.SearchAsync(() => "marta", CancellationToken.None);
Assert.AreEqual(SearchOutcome.Ready, first.Outcome, first.Message);
Assert.IsTrue(first.Answer!.Hits.All(Matches), "only profiles that match «marta», never the answer to a prefix");
Assert.AreEqual(SearchOutcome.Ready, (await h.Search.SearchAsync(() => "ma", CancellationToken.None)).Outcome);
var back = await h.Search.SearchAsync(() => "marta", CancellationToken.None);
Assert.AreEqual(SearchOutcome.Ready, back.Outcome, back.Message);
CollectionAssert.AreEqual(
first.Answer.Hits.Select(x => x.Profile.Username).ToArray(),
back.Answer!.Hits.Select(x => x.Profile.Username).ToArray(),
"the page shows «marta» from its memory: Febe gives the answer it read on this page");
Assert.AreEqual(0, h.Site.Control.RecentSearchWrites);
static bool Matches(SearchProfile hit) =>
hit.Profile.Username.Contains("marta", StringComparison.Ordinal)
|| (hit.Profile.DisplayName ?? string.Empty).Contains("marta", StringComparison.OrdinalIgnoreCase);
}
[TestMethod]
[Timeout(120_000, CooperativeCancellation = true)]
public async Task ARecipeAfterASearchStillWorks()
{
await using var h = await CollectionHarness.CreateAsync(Chromium);
var marta = await h.AddAccountAsync("marta.prova");
Assert.AreEqual(SearchOutcome.Ready, (await h.Search.SearchAsync(() => "luca", CancellationToken.None)).Outcome);
var check = await h.RunAsync(RecipeKind.ProfileCheck, marta.Id);
Assert.AreEqual(RecipeStatus.Completed, check.Status, check.Message);
Assert.AreEqual(PageUser.Engine, h.Turns.LastUser);
Assert.IsFalse(h.Turns.SearchTouchedPage);
}
}
@@ -82,9 +82,13 @@ public sealed class PermissiveGovernor : IGovernor, IBudgetView
/// <summary>After <paramref name="grants"/> granted requests of <paramref name="kind"/>, the next ones are refused.</summary>
public void Limit(ActionKind kind, int grants) => _limits[kind] = grants;
/// <summary>Runs at every request, before the answer (a test changes the page while the permit is asked).</summary>
public Action<ActionKind>? OnRequest { get; set; }
public Task<Permit> RequestAsync(ActionKind kind, long? accountId, CancellationToken ct)
{
_requests.Enqueue((kind, accountId));
OnRequest?.Invoke(kind);
if (_limits.TryGetValue(kind, out var limit) && Granted(kind) >= limit)
{
return Task.FromResult(Permit.Deny(kind, accountId, DenialReason.HourlyBudgetReached, "Tetto orario raggiunto (prova)."));
@@ -12,6 +12,7 @@ using Febe.Core.Collection.Diagnostics;
using Febe.Core.Collection.Downloads;
using Febe.Core.Collection.Readers;
using Febe.Core.Collection.Recipes;
using Febe.Core.Collection.Search;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.SitoDiProva;
@@ -131,7 +132,16 @@ internal sealed class CollectionHarness : IAsyncDisposable
/// <summary>The recorder of the diagnostic report, when asked for: what the page does goes to <see cref="Session"/>.</summary>
public CollectionDiagnostics? Diagnostics { get; private set; }
public static async Task<CollectionHarness> CreateAsync(SharedChromium chromium, RecipeOptions? options = null, double factor = 10, bool diagnostics = false)
/// <summary>The turns of the page shared by the recipes and the profile search (issue #37).</summary>
public PageTurns Turns { get; } = new();
/// <summary>The photos of the profile search, in memory.</summary>
public SearchPhotoCache SearchPhotos { get; private set; } = null!;
/// <summary>The browser half of the profile search.</summary>
public ProfileSearchRunner Search => Pipeline.Search!;
public static async Task<CollectionHarness> CreateAsync(SharedChromium chromium, RecipeOptions? options = null, double factor = 10, bool diagnostics = false, ProfileSearchOptions? search = null)
{
var site = await SyntheticSite.StartAsync();
var temp = new TempFolder("raccolta");
@@ -143,8 +153,13 @@ internal sealed class CollectionHarness : IAsyncDisposable
harness.Diagnostics = new CollectionDiagnostics(clock, () => harness.Session.SessionId);
}
var searchOptions = search ?? new ProfileSearchOptions { AnswerTimeout = TimeSpan.FromSeconds(30) };
harness.SearchPhotos = new SearchPhotoCache(clock, searchOptions);
harness.Pipeline = await CollectionPipeline.StartAsync(new CollectionPipelineOptions
{
PageTurns = harness.Turns,
SearchOptions = searchOptions,
SearchPhotos = harness.SearchPhotos,
Cdp = chromium.Cdp,
Site = CollectionSite.TestSite(site.SiteHost, site.CdnHost),
Storage = library.Db,
@@ -232,6 +232,28 @@ public sealed partial class SyntheticSiteSeedTests
Assert.IsEmpty(hidden.Contents);
}
[TestMethod]
[Timeout(30_000, CooperativeCancellation = true)]
public async Task TheSearchOfTheSiteAnswersInTheShapeOfTheCleanedSample()
{
// Issue #37: the same keys as 000002-ricerca-profili, read by the same search vocabulary as Instagram's.
await using var site = await SyntheticSite.StartAsync();
var answer = await ReadAsync(site, "/dati/cerca?testo=" + Uri.EscapeDataString("Marta"));
Assert.IsNotNull(answer.Search);
Assert.AreEqual("marta.prova", answer.Search.Hits[0].Profile.Username);
Assert.AreEqual("1001", answer.Search.Hits[0].Profile.Id);
Assert.IsNotNull(answer.Search.Hits[0].Profile.Picture, "a photo on the CDN of the site");
Assert.IsEmpty(answer.Profiles, "search results are not followed profiles");
var all = await ReadAsync(site, "/dati/cerca?testo=prova");
Assert.IsTrue(all.Search!.Hits.Count is > 1 and <= DataApi.SearchSize);
Assert.IsFalse(all.Search.Hits.Any(h => h.Profile.Username == "alberto.prova"), "the connected account is not a result");
CollectionAssert.AreEqual(Enumerable.Range(0, all.Search.Hits.Count).ToArray(), all.Search.Hits.Select(h => h.Position).ToArray());
var none = await ReadAsync(site, "/dati/cerca?testo=qqqzzz");
Assert.HasCount(0, none.Search!.Hits);
}
private async Task<ReadResult> ReadAsync(TestSite site, string pathAndQuery)
{
var result = Reader.Read(await site.GetDataAsync(pathAndQuery, TestContext.CancellationToken));
@@ -0,0 +1,225 @@
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Tests.Engine.Support;
namespace Febe.Tests.Engine;
/// <summary>The profile search in the engine (issue #37): its own Governor category and the turns of the page.</summary>
[TestClass]
public sealed class ProfileSearchEngineTests
{
[TestMethod]
public async Task ASearchStepNeedsNoSessionAndIsLoggedWithoutOne()
{
await using var bed = await EngineTestBed.CreateAsync();
var permit = await bed.Governor.RequestAsync(ActionKind.ProfileSearch, null, CancellationToken.None);
Assert.IsTrue(permit.Granted, permit.Message);
var logged = await bed.Db.ActionLog.ListAsync(bed.Clock.Now.AddMinutes(-1), bed.Clock.Now.AddMinutes(1));
Assert.HasCount(1, logged);
Assert.AreEqual(ActionKind.ProfileSearch, logged[0].Category);
Assert.IsNull(logged[0].SessionId);
Assert.IsNull(logged[0].AccountId);
}
[TestMethod]
public async Task InsideASessionTheSearchIsNotAnActionOfTheSession()
{
await using var bed = await EngineTestBed.CreateAsync();
var session = await bed.BeginSessionAsync();
Assert.IsTrue((await bed.Governor.RequestAsync(ActionKind.ProfileSearch, null, CancellationToken.None)).Granted);
Assert.AreEqual(0, session.ActionCount, "a search step does not count toward the session's actions");
var logged = await bed.Db.ActionLog.ListAsync(bed.Clock.Now.AddMinutes(-1), bed.Clock.Now.AddMinutes(1));
Assert.IsNull(logged.Single().SessionId);
}
[TestMethod]
public async Task OutsideTheWindowTheSearchDoesNotOpenTheSite()
{
await using var bed = await EngineTestBed.CreateAsync(EngineTestBed.Local(2026, 10, 14, 3, 0));
var permit = await bed.Governor.RequestAsync(ActionKind.ProfileSearch, null, CancellationToken.None);
Assert.AreEqual(DenialReason.OutsideActiveWindow, permit.Reason);
StringAssert.Contains(permit.Message!, "Fuori dalla fascia oraria");
StringAssert.Contains(permit.Message!, "profili che segui");
Assert.IsNotNull(permit.RetryAfter);
}
[TestMethod]
public async Task EveryStopOfTheBreakerStopsTheSearch()
{
await using var bed = await EngineTestBed.CreateAsync();
await bed.Breaker.ReportAsync(new Signal(SignalLevel.Throttle, "http-429", null, bed.Clock.Now));
var permit = await bed.Governor.RequestAsync(ActionKind.ProfileSearch, null, CancellationToken.None);
Assert.AreEqual(DenialReason.BreakerOpen, permit.Reason);
}
[TestMethod]
public async Task AlbertoAtTheBrowserAndThePauseStopTheSearch()
{
var driving = true;
await using var bed = await EngineTestBed.CreateAsync(userIsDriving: () => driving);
var atBrowser = await bed.Governor.RequestAsync(ActionKind.ProfileSearch, null, CancellationToken.None);
Assert.AreEqual(DenialReason.UserIsDriving, atBrowser.Reason);
StringAssert.Contains(atBrowser.Message!, "ricerca su Instagram");
driving = false;
bed.Runtime.IsPaused = true;
Assert.AreEqual(DenialReason.Paused, (await bed.Governor.RequestAsync(ActionKind.ProfileSearch, null, CancellationToken.None)).Reason);
}
[TestMethod]
public async Task TheSearchHasItsOwnBudgetThatDoesNotTouchTheCollection()
{
await using var bed = await EngineTestBed.CreateAsync();
bed.Clock.AutoAdvance = true;
var homeBefore = await bed.Governor.RemainingAsync(ActionKind.Home);
var profileBefore = await bed.Governor.RemainingAsync(ActionKind.ProfileOpen);
for (var i = 0; i < 5; i++)
{
Assert.IsTrue((await bed.Governor.RequestAsync(ActionKind.ProfileSearch, null, CancellationToken.None)).Granted);
}
Assert.AreEqual(homeBefore, await bed.Governor.RemainingAsync(ActionKind.Home));
Assert.AreEqual(profileBefore, await bed.Governor.RemainingAsync(ActionKind.ProfileOpen));
Assert.AreEqual(240 - 5, await bed.Governor.RemainingAsync(ActionKind.ProfileSearch), "«Prudente»: 240 search steps per hour");
}
[TestMethod]
public void TheSearchBudgetsAreWideButBelowTwiceRapido()
{
var prudent = CautionProfile.Prudent.Budgets[ActionKind.ProfileSearch];
var balanced = CautionProfile.Balanced.Budgets[ActionKind.ProfileSearch];
var fast = CautionProfile.Fast.Budgets[ActionKind.ProfileSearch];
Assert.IsTrue(prudent.PerHour <= balanced.PerHour && balanced.PerHour <= fast.PerHour);
Assert.IsTrue(prudent.PerDay <= balanced.PerDay && balanced.PerDay <= fast.PerDay);
Assert.IsTrue(prudent.PerHour > CautionProfile.Fast.Budgets[ActionKind.ProfileOpen].PerHour, "wide: typing a name takes several steps");
}
[TestMethod]
public async Task HalvedBudgetsAfterAThrottleApplyToTheSearchToo()
{
await using var bed = await EngineTestBed.CreateAsync();
await bed.Breaker.ReportAsync(new Signal(SignalLevel.Throttle, "http-429", null, bed.Clock.Now));
bed.Clock.Advance(TimeSpan.FromHours(1));
var budgets = bed.Governor.GetEffectiveBudgets(bed.Clock.Now);
Assert.AreEqual(new Budget(120, 600), budgets.Budgets[ActionKind.ProfileSearch]);
}
[TestMethod]
public async Task TheSearchKeepsItsOwnSpacingAndAGapFromTheEngineBothWays()
{
await using var bed = await EngineTestBed.CreateAsync();
await bed.BeginSessionAsync();
var spacing = bed.Governor.SearchSpacing;
Assert.IsTrue((await bed.Governor.RequestAsync(ActionKind.ProfileSearch, null, CancellationToken.None)).Granted);
var again = await bed.Governor.EvaluateAsync(ActionKind.ProfileSearch, null);
Assert.AreEqual(DenialReason.MinimumSpacing, again.Reason, "the search's own spacing");
// The engine right after a search step waits the crossing gap, not its own 4 s spacing.
var engine = await bed.Governor.EvaluateAsync(ActionKind.Home, null);
Assert.AreEqual(DenialReason.MinimumSpacing, engine.Reason);
Assert.AreEqual(bed.Clock.Now + spacing, engine.RetryAfter);
bed.Clock.Advance(spacing);
Assert.IsTrue((await bed.Governor.RequestAsync(ActionKind.Home, null, CancellationToken.None)).Granted);
// And the search right after an engine action waits the same gap.
var search = await bed.Governor.EvaluateAsync(ActionKind.ProfileSearch, null);
Assert.AreEqual(DenialReason.MinimumSpacing, search.Reason);
Assert.AreEqual(bed.Clock.Now + spacing, search.RetryAfter);
}
[TestMethod]
public async Task TheEngineSpacingIgnoresTheSearchSteps()
{
await using var bed = await EngineTestBed.CreateAsync();
await bed.BeginSessionAsync();
Assert.IsTrue((await bed.Governor.RequestAsync(ActionKind.Home, null, CancellationToken.None)).Granted);
var home = bed.Clock.Now;
bed.Clock.Advance(TimeSpan.FromSeconds(2));
Assert.IsTrue((await bed.Governor.RequestAsync(ActionKind.ProfileSearch, null, CancellationToken.None)).Granted);
Assert.AreEqual(home, await bed.Db.ActionLog.GetLastActionAtAsync(null), "the engine's last action is not a search step");
Assert.AreEqual(bed.Clock.Now, await bed.Db.ActionLog.GetLastActionAtAsync(ActionKind.ProfileSearch));
}
// ---------------------------------------------------------------------------------------------- page turns
[TestMethod]
public async Task TurnsAreGivenInOrderOneAtATime()
{
var turns = new PageTurns();
var engine = await turns.TakeAsync(PageUser.Engine, CancellationToken.None);
Assert.AreEqual(PageUser.Engine, turns.Holder);
var searchTask = turns.TakeAsync(PageUser.Search, CancellationToken.None).AsTask();
Assert.IsFalse(searchTask.IsCompleted);
Assert.IsTrue(turns.IsWaiting(PageUser.Search));
await engine.DisposeAsync();
var search = await searchTask.WaitAsync(TimeSpan.FromSeconds(5));
Assert.AreEqual(PageUser.Search, turns.Holder);
search.Dispose();
Assert.IsNull(turns.Holder);
await turns.WhenFreeAsync(CancellationToken.None).WaitAsync(TimeSpan.FromSeconds(5));
}
[TestMethod]
public async Task TheEngineYieldsOnlyWhenTheSearchWaits()
{
var turns = new PageTurns();
var engine = await turns.TakeAsync(PageUser.Engine, CancellationToken.None);
Assert.IsFalse(await turns.YieldAsync(engine, CancellationToken.None), "nobody waits: no yield");
var searchTask = turns.TakeAsync(PageUser.Search, CancellationToken.None).AsTask();
var yieldTask = turns.YieldAsync(engine, CancellationToken.None).AsTask();
var search = await searchTask.WaitAsync(TimeSpan.FromSeconds(5));
Assert.IsFalse(yieldTask.IsCompleted, "the engine waits for the search step");
await search.DisposeAsync();
Assert.IsTrue(await yieldTask.WaitAsync(TimeSpan.FromSeconds(5)));
Assert.AreSame(engine, turns.EngineTurn);
engine.Dispose();
}
[TestMethod]
public async Task ACancelledWaitLeavesTheQueue()
{
var turns = new PageTurns();
var engine = await turns.TakeAsync(PageUser.Engine, CancellationToken.None);
using var cts = new CancellationTokenSource();
var waiting = turns.TakeAsync(PageUser.Search, cts.Token).AsTask();
await cts.CancelAsync();
await Assert.ThrowsAsync<OperationCanceledException>(async () => await waiting);
Assert.IsFalse(turns.IsWaiting(PageUser.Search));
engine.Dispose();
Assert.IsNull(turns.Holder);
}
[TestMethod]
public void TheSearchMarksThePageAndARestClearsIt()
{
var turns = new PageTurns();
var rested = 0;
turns.Rested += () => rested++;
turns.NoteOpened(PageUser.Search);
Assert.AreEqual(PageUser.Search, turns.LastUser);
Assert.IsTrue(turns.SearchTouchedPage);
turns.NoteOpened(PageUser.Engine);
Assert.IsFalse(turns.SearchTouchedPage);
turns.NoteSearchUsedPage();
Assert.IsTrue(turns.SearchTouchedPage);
turns.NoteRested();
Assert.IsNull(turns.LastUser);
Assert.IsFalse(turns.SearchTouchedPage);
Assert.AreEqual(1, rested);
}
}
@@ -0,0 +1,432 @@
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;
/// <summary>
/// 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.
/// </summary>
[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»");
}
/// <summary>A browser half that answers from a small list, at once.</summary>
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<SearchStepResult> _next = new();
private int _steps;
private int _rests;
/// <summary>Opens the page itself (outside sessions); false: types on the page the engine opened.</summary>
public bool OpensPage { get; init; } = true;
/// <summary>When set, every step waits for it before answering (the search holds the page meanwhile).</summary>
public TaskCompletionSource? Gate { get; init; }
/// <summary>Eight invented profiles «text.0» … «text.7» for every text.</summary>
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<SearchStepResult> SearchAsync(Func<string?> 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<SearchProfile> 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;
}
}
}
+45
View File
@@ -260,6 +260,51 @@ public sealed class DemoTests
Assert.IsFalse(string.IsNullOrWhiteSpace(body.RootElement.Str("message")));
}
[TestMethod]
public async Task TheSearchOfTheDemoFindsProfilesWithDrawnPhotos()
{
var origin = $"{Demo.Address.Scheme}://{Demo.Address.Authority}";
async Task<JsonElement> PostAsync(string text, string scene = "normale")
{
using var request = new HttpRequestMessage(HttpMethod.Post, $"/api/ricerca?scena={scene}")
{
Content = new StringContent(JsonSerializer.Serialize(new { client = "0123456789abcdef", text }), System.Text.Encoding.UTF8, "application/json"),
};
request.Headers.Add("Origin", origin);
using var response = await Client.SendAsync(request);
var body = await response.Content.ReadAsStringAsync();
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, body);
return JsonDocument.Parse(body).RootElement.Clone();
}
Assert.AreEqual("solo-locale", (await PostAsync("m")).Str("state"));
Assert.AreEqual("cerca", (await PostAsync("marta")).Str("state"));
JsonElement view = default;
await TestWait.UntilAsync(
async () =>
{
view = await GetAsync("/api/ricerca?client=0123456789abcdef");
return view.Str("state") == "pronta" && view.Items("hits").All(h => h.Bool("photoReady"));
},
"the demo answer with its photos");
var hits = view.Items("hits").ToList();
Assert.IsTrue(hits.Count is > 0 and <= 6);
Assert.IsTrue(hits.Any(h => h.Str("username") == "marta.demo"), "a demo account whose name holds the text");
Assert.IsTrue(hits.Any(h => h.GetProperty("accountId").ValueKind == JsonValueKind.Number), "already in Febe");
using var photo = await Client.GetAsync($"/api/ricerca/foto/{hits[0].Str("photo")}");
Assert.AreEqual(HttpStatusCode.OK, photo.StatusCode);
Assert.AreEqual("image/jpeg", photo.Content.Headers.ContentType?.MediaType);
Assert.AreEqual("ferma", (await PostAsync("luca", "fermo")).Str("state"));
Assert.AreEqual("non-pronto", (await PostAsync("luca", "scollegato")).Str("state"));
// «alvolante»: Alberto uses the browser; the engine says so and the search on Instagram is not possible.
var driving = await PostAsync("luca", "alvolante");
Assert.AreEqual("non-possibile", driving.Str("state"));
StringAssert.Contains(driving.Str("message"), "Stai usando il browser");
Assert.AreEqual("UserDriving", (await GetAsync("/api/engine?scena=alvolante")).GetProperty("snapshot").Str("mode"));
}
[TestMethod]
public async Task TheEditionCanBeChosenByAddress()
{
@@ -0,0 +1,273 @@
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Text.Json;
using Febe.Core.Abstractions;
using Febe.Core.Collection.Search;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Tests.Support;
using Febe.Tests.Web.Support;
using Febe.Web.Engine;
using Microsoft.Extensions.DependencyInjection;
namespace Febe.Tests.Web;
/// <summary>
/// The «Aggiungi account» dialog with its one search box (issue #37), in a real headless Chromium against a test server
/// with a scripted search: the profiles Alberto follows show at once, Instagram's results come after and merge without
/// doubles, photos swap in when Febe has them, the keyboard adds a row, Esc closes only the list, pasting several names
/// fills «Da aggiungere», and while Alberto drives the browser the dialog says so. The page only ever asks Febe.
/// </summary>
[TestClass]
[DoNotParallelize]
public sealed class ProfileSearchInterfaceTests
{
private const string Box = "document.querySelector('.aggiungi input[role=combobox]')";
[TestMethod]
public async Task FollowedProfilesShowAtOnceThenInstagramsResultsWithTheirPhotos()
{
var search = new ScriptedSearch();
await using var server = await WebTestServer.StartAsync(services: s => s.AddSingleton<IProfileSearch>(search));
await SeedAsync(server);
await using var ui = await UiBrowser.StartAsync();
await ui.AddInitScriptAsync(UiBrowser.Requests);
await OpenDialogAsync(ui, server);
// Instagram's answer waits: the followed profiles and the accounts in Febe are there before it.
await ui.EvalAsync("window.__hold('/api/ricerca')");
await TypeAsync(ui, "mar");
await ui.WaitAsync("window.__started['/api/ricerca'] >= 1", "testo mandato a Febe");
await ui.WaitAsync(Rows("@marta.rossi") + " === 1 && " + Rows("@mario.bianchi") + " === 1 && " + Rows("@marco.archivio") + " === 1", "suggerimenti locali subito");
Assert.AreEqual(0, (await ui.EvalAsync("window.__done['/api/ricerca'] || 0")).GetInt32(), "the local rows came before the answer");
StringAssert.Contains(await TextAsync(ui, ".suggerimenti"), "Cerco su Instagram");
StringAssert.Contains(await TextAsync(ui, ".suggerimenti"), "Già in Febe");
await ui.EvalAsync("window.__release('/api/ricerca')");
await ui.WaitForAsync(() => search.Texts.Contains("mar"), "testo arrivato al server");
search.Answer(
new SearchHit(0, "11", "marta.rossi", "Marta Rossi", false, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", false),
new SearchHit(1, "99", "mara.nuova", "Mara Nuova", true, "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", false));
await ui.WaitAsync(Rows("@mara.nuova") + " === 1", "risultato di Instagram");
Assert.AreEqual(1, (await ui.EvalAsync(Rows("@marta.rossi"))).GetInt32(), "a followed profile found on Instagram is shown once");
StringAssert.Contains(await TextAsync(ui, ".suggerimenti"), "Da Instagram");
// The photo replaces the initials once Febe has it.
search.PhotosReady();
await ui.WaitAsync(
"[...document.querySelectorAll('.suggerimenti [role=option]')].some((r) => r.textContent.includes('@mara.nuova') && [...r.querySelectorAll('.av img')].some((i) => i.complete && i.naturalWidth > 0))",
"foto del risultato");
// Keyboard: down to the Instagram result, Enter adds it; Esc closes the list and not the dialog.
for (var i = 0; i < 8; i++)
{
var current = await ui.EvalAsync($"(() => {{ const id = {Box}.getAttribute('aria-activedescendant'); return id ? document.getElementById(id).textContent : ''; }})()");
if (current.GetString()!.Contains("@mara.nuova", StringComparison.Ordinal))
{
break;
}
await KeyAsync(ui, "ArrowDown");
}
await KeyAsync(ui, "Enter");
await ui.WaitAsync("document.querySelector('.aggiungi .scelti').textContent.includes('@mara.nuova')", "aggiunto a «Da aggiungere»");
await KeyAsync(ui, "Escape");
await ui.WaitAsync("document.querySelector('.suggerimenti').hidden && document.querySelector('.aggiungi') !== null", "solo l'elenco chiuso");
// The page asked only Febe: every resource (fetches and photos) on its own address, the search by POST and polls.
Assert.IsTrue((await ui.EvalAsync("performance.getEntriesByType('resource').every((e) => new URL(e.name).origin === location.origin)")).GetBoolean());
var asked = await ui.AskedAsync("/api/ricerca");
Assert.IsTrue(asked.All(r => r == "POST /api/ricerca" || r.StartsWith("GET /api/ricerca?client=", StringComparison.Ordinal)), string.Join(", ", asked));
// Added with the identifier of the result the server holds.
await ui.EvalAsync("document.querySelector('.aggiungi footer .btn.primo').click()");
await ui.WaitAsync("document.querySelector('.aggiungi') === null", "dialogo chiuso dopo l'aggiunta");
var added = await server.Db.Accounts.FindByUsernameAsync("mara.nuova");
Assert.AreEqual("99", added?.InstagramId);
await ui.WaitForAsync(() => search.Ended > 0, "ricerca chiusa con il dialogo");
}
[TestMethod]
public async Task PastedNamesGoToTheListWhileATypedNameIsSearched()
{
var search = new ScriptedSearch();
await using var server = await WebTestServer.StartAsync(services: s => s.AddSingleton<IProfileSearch>(search));
await SeedAsync(server);
await using var ui = await UiBrowser.StartAsync();
await ui.AddInitScriptAsync(UiBrowser.Requests);
await OpenDialogAsync(ui, server);
await ui.EvalAsync($$"""
(() => {
const data = new DataTransfer();
data.setData('text/plain', 'uno.nome\n@due.nome, instagram.com/tre.nome/\nmarta.rossi');
{{Box}}.focus();
{{Box}}.dispatchEvent(new ClipboardEvent('paste', { clipboardData: data, bubbles: true, cancelable: true }));
return true;
})()
""");
await ui.WaitAsync("['@uno.nome', '@due.nome', '@tre.nome', '@marta.rossi'].every((n) => document.querySelector('.aggiungi .scelti').textContent.includes(n))", "nomi incollati da aggiungere");
Assert.AreEqual("Aggiungi 4 account", (await TextAsync(ui, ".aggiungi footer .btn.primo")).Trim());
Assert.HasCount(1, await ui.AskedAsync("POST /api/accounts/parse"));
Assert.IsEmpty(await ui.AskedAsync("POST /api/ricerca"), "several names are never searched on Instagram");
// A name with a space is a search, not two names.
await TypeAsync(ui, "mario rossi");
await ui.WaitForAsync(() => search.Texts.Contains("mario rossi"), "ricerca di «mario rossi»");
Assert.IsFalse(search.Texts.Any(t => t.Contains('\n', StringComparison.Ordinal) || t.Contains(',', StringComparison.Ordinal)));
// The × takes a name away.
await ui.EvalAsync("document.querySelector('.aggiungi .scelti .voce.scelto button').click()");
await ui.WaitAsync("document.querySelector('.aggiungi footer .btn.primo').textContent.trim() === 'Aggiungi 3 account'", "un nome tolto");
}
[TestMethod]
public async Task WhileAlbertoUsesTheBrowserTheDialogSaysSoAndLocalSuggestionsWork()
{
var search = new ScriptedSearch { State = SearchState.NotPossible, Message = "Stai usando il browser di Febe: la ricerca su Instagram riprende quando hai finito." };
await using var server = await WebTestServer.StartAsync(services: s =>
{
s.AddSingleton<IProfileSearch>(search);
s.AddSingleton<IEngineMonitor>(new DrivingMonitor());
});
await SeedAsync(server);
await using var ui = await UiBrowser.StartAsync();
await ui.AddInitScriptAsync(UiBrowser.Requests);
await OpenDialogAsync(ui, server);
await ui.WaitAsync("document.querySelector('.stato') !== null && document.querySelector('.stato').textContent.includes('Stai usando il browser')", "motore al volante");
await ui.EvalAsync("window.__hold('/api/ricerca')");
await TypeAsync(ui, "mar");
await ui.WaitAsync(Rows("@marta.rossi") + " === 1", "suggerimenti locali");
await ui.WaitAsync("document.querySelector('.suggerimenti').textContent.includes('Stai usando il browser di Febe')", "avviso subito, prima della risposta");
await ui.EvalAsync("window.__release('/api/ricerca')");
await ui.WaitAsync("window.__done['/api/ricerca'] >= 1", "risposta arrivata");
await ui.WaitAsync($"document.querySelector('.suggerimenti .stato-remoto').textContent === {JsonSerializer.Serialize(search.Message)}", "messaggio del server");
Assert.AreEqual(1, (await ui.EvalAsync(Rows("@marta.rossi"))).GetInt32());
}
// ------------------------------------------------------------------------------------------ helpers
private static async Task SeedAsync(WebTestServer server)
{
await server.Db.Following.UpsertAsync(
[
new FollowingRecord { InstagramId = "11", Username = "marta.rossi", DisplayName = "Marta Rossi", IsPrivate = true, Position = 0, ReadAt = server.Clock.Now },
new FollowingRecord { InstagramId = "12", Username = "mario.bianchi", DisplayName = "Mario Bianchi", Position = 1, ReadAt = server.Clock.Now },
new FollowingRecord { InstagramId = "13", Username = "luca.verdi", DisplayName = "Luca Verdi", Position = 2, ReadAt = server.Clock.Now },
]);
await server.Db.Accounts.AddAsync(Make.Account("marco.archivio") with { InstagramId = "14", DisplayName = "Marco" });
}
private static async Task OpenDialogAsync(UiBrowser ui, WebTestServer server)
{
await ui.OpenAsync(new Uri(server.Address, "/account?dialogo=aggiungi"));
await ui.WaitAsync($"{Box} !== null && document.querySelector('.aggiungi .scelti-testa .btn.collegamento').textContent.includes('(3)')", "dialogo con l'elenco dei seguiti");
}
private static Task TypeAsync(UiBrowser ui, string text) =>
ui.EvalAsync($"(() => {{ const b = {Box}; b.focus(); b.value = {JsonSerializer.Serialize(text)}; b.dispatchEvent(new Event('input', {{ bubbles: true }})); return true; }})()");
private static Task KeyAsync(UiBrowser ui, string key) =>
ui.EvalAsync($"{Box}.dispatchEvent(new KeyboardEvent('keydown', {{ key: {JsonSerializer.Serialize(key)}, bubbles: true, cancelable: true }}))");
private static string Rows(string text) =>
$"[...document.querySelectorAll('.suggerimenti [role=option]')].filter((r) => r.querySelector('b') && r.querySelector('b').textContent === {JsonSerializer.Serialize(text)}).length";
private static async Task<string> TextAsync(UiBrowser ui, string selector) =>
(await ui.EvalAsync($"document.querySelector({JsonSerializer.Serialize(selector)}).textContent")).GetString() ?? string.Empty;
/// <summary>A search the test drives: the state of the next texts, then the answer and the photos when it says.</summary>
private sealed class ScriptedSearch : IProfileSearch
{
private readonly Lock _gate = new();
private SearchView _view = SearchView.Initial;
public SearchState State { get; init; } = SearchState.Searching;
public string? Message { get; init; }
public List<string> Texts { get; } = [];
public int Ended { get; private set; }
public SearchView Current
{
get
{
lock (_gate)
{
return _view;
}
}
}
public SearchView Update(string client, string text)
{
lock (_gate)
{
Texts.Add(text);
var query = SearchText.Normalize(text);
_view = new SearchView(_view.Version + 1, client, query.Typed, query.Kind == SearchQueryKind.Typable ? State : SearchState.LocalOnly, Message, [], null);
return _view;
}
}
public void Answer(params SearchHit[] hits)
{
lock (_gate)
{
_view = _view with { Version = _view.Version + 1, State = SearchState.Ready, Hits = hits };
}
}
public void PhotosReady()
{
lock (_gate)
{
_view = _view with { Version = _view.Version + 1, Hits = [.. _view.Hits.Select(h => h with { PhotoReady = true })] };
}
}
public void End(string client)
{
lock (_gate)
{
Ended++;
}
}
public SearchHit? Known(string username)
{
lock (_gate)
{
return _view.Hits.FirstOrDefault(h => h.Username == username);
}
}
public bool TryOpenPhoto(string key, [NotNullWhen(true)] out Stream? stream)
{
lock (_gate)
{
stream = _view.Hits.Any(h => h.PhotoReady && h.PhotoKey == key)
? new MemoryStream(Febe.Web.Demo.DemoImages.Render(Febe.Web.Demo.DemoSubject.Portrait, 7, 32, 32))
: null;
return stream is not null;
}
}
}
/// <summary>An engine while Alberto uses the browser.</summary>
private sealed class DrivingMonitor : IEngineMonitor
{
public Task<EngineSnapshot> GetSnapshotAsync(CancellationToken ct = default) =>
Task.FromResult(SnapshotParts.Build(new ManualClock(Make.T0), EngineMode.UserDriving, "Stai usando il browser", ["Il motore resta fermo finché non hai finito."], "Stai usando il browser", CautionProfile.Prudent));
public async IAsyncEnumerable<EngineNotification> SubscribeAsync([EnumeratorCancellation] CancellationToken ct = default)
{
await Task.Delay(Timeout.Infinite, ct);
yield break;
}
}
}
+144
View File
@@ -0,0 +1,144 @@
using System.Diagnostics.CodeAnalysis;
using System.Net;
using Febe.Core.Collection.Search;
using Febe.Core.Domain;
using Febe.Tests.Support;
using Febe.Tests.Web.Support;
using Microsoft.Extensions.DependencyInjection;
namespace Febe.Tests.Web;
/// <summary>
/// The API of the profile search (issue #37): what the window sends, what it reads, the photos from Febe's memory,
/// the local suggestions with the accounts not followed, and adding a found profile with its identifier.
/// </summary>
[TestClass]
public sealed class SearchApiTests
{
private const string Client = "0123456789abcdef";
[TestMethod]
public async Task WithoutTheEngineTheSearchSaysOnlyLocalSuggestionsWork()
{
await using var server = await WebTestServer.StartAsync();
var (status, view) = await server.SendJsonAsync(HttpMethod.Post, "/api/ricerca", new { client = Client, text = "mario" });
Assert.AreEqual(HttpStatusCode.OK, status);
Assert.AreEqual("non-pronto", view.Str("state"));
Assert.IsTrue(view.Bool("mine"));
StringAssert.Contains(view.Str("message"), "profili che segui");
Assert.AreEqual("non-pronto", (await server.GetJsonAsync($"/api/ricerca?client={Client}")).Str("state"));
Assert.IsFalse((await server.GetJsonAsync("/api/ricerca?client=fedcba9876543210")).Bool("mine"));
}
[TestMethod]
public async Task BadRequestsAreRefused()
{
await using var server = await WebTestServer.StartAsync();
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/ricerca", new { client = "x", text = "mario" })).Status);
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/ricerca", new { client = Client, text = new string('a', 61) })).Status);
Assert.AreEqual(HttpStatusCode.NotFound, (await server.SendJsonAsync(HttpMethod.Get, "/api/ricerca/foto/nonunachiave")).Status);
Assert.AreEqual(HttpStatusCode.NotFound, (await server.SendJsonAsync(HttpMethod.Get, "/api/ricerca/foto/0123456789abcdef0123456789abcdef")).Status);
using var end = server.Request(HttpMethod.Post, "/api/ricerca/fine", new { client = Client });
using var ended = await server.Client.SendAsync(end);
Assert.AreEqual(HttpStatusCode.NoContent, ended.StatusCode);
// Without the Origin of the interface a page of another site cannot make Febe type.
using var foreign = server.Request(HttpMethod.Post, "/api/ricerca", new { client = Client, text = "mario" }, origin: "http://altro.esempio");
using var refused = await server.Client.SendAsync(foreign);
Assert.AreNotEqual(HttpStatusCode.OK, refused.StatusCode);
}
[TestMethod]
public async Task HitsAreEnrichedWithWhatFebeKnowsAndPhotosComeFromMemory()
{
var fake = new FixedSearch();
await using var server = await WebTestServer.StartAsync(services: s => s.AddSingleton<IProfileSearch>(fake));
var renamed = await server.Db.Accounts.AddAsync(Make.Account("vecchio.nome") with { InstagramId = "100" });
await server.Db.Following.UpsertAsync([new FollowingRecord { InstagramId = "200", Username = "seguito.uno", ReadAt = server.Clock.Now }]);
var (_, view) = await server.SendJsonAsync(HttpMethod.Post, "/api/ricerca", new { client = Client, text = "nome" });
Assert.AreEqual("pronta", view.Str("state"));
var hits = view.Items("hits").ToList();
Assert.HasCount(3, hits);
Assert.AreEqual(renamed.Id, hits[0].Long("accountId"), "found by identifier under its new name");
Assert.IsTrue(hits[1].Bool("followed"));
Assert.AreEqual(System.Text.Json.JsonValueKind.Null, hits[2].GetProperty("accountId").ValueKind);
Assert.IsTrue(hits[2].Bool("photoReady"));
using var photo = await server.Client.GetAsync($"/api/ricerca/foto/{hits[2].Str("photo")}");
Assert.AreEqual(HttpStatusCode.OK, photo.StatusCode);
Assert.AreEqual("image/jpeg", photo.Content.Headers.ContentType?.MediaType);
Assert.IsTrue(photo.Headers.CacheControl?.NoStore == true, "the photos stay in Febe's memory, never on the disk of the viewer's browser");
}
[TestMethod]
public async Task TheLocalSuggestionsAlsoHoldTheAccountsNotFollowed()
{
await using var server = await WebTestServer.StartAsync();
var added = await server.Db.Accounts.AddAsync(Make.Account("aggiunto.per.nome"));
await server.Db.Following.UpsertAsync([new FollowingRecord { InstagramId = "200", Username = "seguito.uno", ReadAt = server.Clock.Now }]);
var following = await server.GetJsonAsync("/api/following");
Assert.AreEqual(1, following.Int("total"), "the count is of the followed profiles");
var profiles = following.Items("profiles").ToList();
Assert.HasCount(2, profiles);
Assert.IsTrue(profiles[0].Bool("followed"));
Assert.AreEqual("200", profiles[0].Str("instagramId"));
Assert.AreEqual("aggiunto.per.nome", profiles[1].Str("username"));
Assert.IsFalse(profiles[1].Bool("followed"));
Assert.AreEqual(added.Id, profiles[1].Long("accountId"));
}
[TestMethod]
public async Task AFoundProfileIsAddedWithItsIdentifierAndARenamedOneIsReported()
{
var fake = new FixedSearch();
await using var server = await WebTestServer.StartAsync(services: s => s.AddSingleton<IProfileSearch>(fake));
await server.Db.Accounts.AddAsync(Make.Account("vecchio.nome") with { InstagramId = "100" });
var (status, result) = await server.SendJsonAsync(HttpMethod.Post, "/api/accounts", new { usernames = new[] { "nuovo.nome", "senza.nome" }, start = "newOnly" });
Assert.AreEqual(HttpStatusCode.OK, status);
Assert.AreEqual(1, result.Int("added"));
StringAssert.Contains(result.Str("message"), "con un altro nome");
var account = await server.Db.Accounts.FindByUsernameAsync("senza.nome");
Assert.AreEqual("300", account!.InstagramId);
Assert.AreEqual("Senza Nome", account.DisplayName);
Assert.IsNull(await server.Db.Accounts.FindByUsernameAsync("nuovo.nome"), "the same profile is not added twice");
}
/// <summary>A search that always shows the same three results.</summary>
private sealed class FixedSearch : IProfileSearch
{
private const string PhotoKey = "abcdefabcdefabcdefabcdefabcdef12";
private static readonly SearchHit[] Hits =
[
new(0, "100", "nuovo.nome", "Nuovo Nome", false, null, false),
new(1, "200", "seguito.uno", null, false, null, false),
new(2, "300", "senza.nome", "Senza Nome", true, PhotoKey, true),
];
public SearchView Current { get; private set; } = SearchView.Initial;
public SearchView Update(string client, string text) =>
Current = new SearchView(Current.Version + 1, client, text, SearchState.Ready, null, Hits, null);
public void End(string client)
{
}
public SearchHit? Known(string username) => Hits.FirstOrDefault(h => h.Username == username);
public bool TryOpenPhoto(string key, [NotNullWhen(true)] out Stream? stream)
{
stream = key == PhotoKey ? new MemoryStream(Febe.Web.Demo.DemoImages.Render(Febe.Web.Demo.DemoSubject.Portrait, 1, 32, 32)) : null;
return stream is not null;
}
}
}
+1 -1
View File
@@ -139,7 +139,7 @@ public sealed class SettingsApiTests
Assert.AreEqual(20, rules.Int("maxWindowHours"));
var current = limits.GetProperty("current");
var kinds = current.Items("budgets").Select(b => b.Str("kind")).ToList();
CollectionAssert.AreEqual(new[] { "Home", "ProfileOpen", "StoryView", "BackfillPage", "SinglePost", "FollowingListPage" }, kinds, "every row of the table of §7.5");
CollectionAssert.AreEqual(new[] { "Home", "ProfileOpen", "StoryView", "BackfillPage", "SinglePost", "FollowingListPage", "ProfileSearch" }, kinds, "every row of the table of §7.5");
CollectionAssert.AreEqual(new[] { "1 ora", "6 ore", "24 ore" }, limits.Items("stops").Select(s => s.GetString()).ToArray());
object Body(Func<Dictionary<string, object?>, Dictionary<string, object?>> edit, string profile = "custom")