Ricerca dei profili con suggerimenti e foto (#37)
«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:
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("mariorossi", 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));
|
||||
|
||||
Reference in new issue
Block a user