Files
Alby96andClaude Opus 5.5 63acae4e73
verifica / controlli (push) Successful in 22s
verifica / prove (push) Successful in 21m4s
verifica / installatore (push) Successful in 5m21s
verifica / immagine (push) Successful in 19m0s
Ricette fatte di richieste, un permesso per richiesta (#36, S3)
Otto ricette (controllo del profilo, storico, taggati, reel, storie di un
account, raccolta in evidenza, post singolo, elenco dei seguiti) hanno una
strada per richieste dirette accanto a quella con il browser. Ci vanno solo
se ogni ruolo che servono è un'operazione configurata di richieste.<sito>.json:
con Instagram nessuna lo è e Febe non costruisce il client del sito, quindi il
comportamento con Instagram non cambia fino a S4.

Ogni richiesta prende il suo permesso dal Governatore nella categoria di ciò
che chiede (la prima pagina dei post conta come profilo); i segnali delle
risposte vanno all'interruttore e fermano la ricetta prima di ogni altra
richiesta. Se manca un valore o la pagina successiva, la ricetta torna alle
pagine per quella volta e il motore controlla tutti e due i tetti. I tetti non
cambiano: il dimezzamento delle storie viste è tolto perché toccava anche il
browser e i «Su misura» salvati, e resta una domanda per Alberto prima di S4.

Il simulatore ha --raccolta pagine|richieste con il costo delle operazioni
separate di Instagram: sei simulazioni di 30 giorni senza superamenti.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 12:10:54 +01:00

830 lines
33 KiB
C#
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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;
}
public Signal? Report(Signal signal) => 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; }
}
}