Ricette fatte di richieste, un permesso per richiesta (#36, S3)
verifica / controlli (push) Successful in 22s
verifica / prove (push) Successful in 21m4s
verifica / installatore (push) Successful in 5m21s
verifica / immagine (push) Successful in 19m0s

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>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-17 12:10:54 +01:00
1 parent 4dcbd0b096
commit 63acae4e73
46 files changed
+3724 -136

No files matched your search

@@ -483,6 +483,7 @@ public sealed class HttpSiteRequesterTests
["profilo-altri"] = (V((CaseValues.Username, "luca.prova"), (CaseValues.Cursor, "c12")), "/dati/profilo/luca.prova/altri?dopo=c12&scheda=post"),
[TestSite.ProfileQuery] = (V((CaseValues.Username, "marta.prova")), "/dati/profilo/marta.prova?scheda=post"),
["taggati"] = (V((CaseValues.Username, "marta.prova")), "/dati/profilo/marta.prova?scheda=taggati"),
["reel"] = (V((CaseValues.Username, "luca.prova")), "/dati/profilo/luca.prova?scheda=reel"),
["post"] = (V((CaseValues.Code, code)), "/dati/post/" + code),
["storie"] = (V((CaseValues.Username, "marta.prova")), "/dati/storie/marta.prova"),
["evidenza"] = (V((CaseValues.HighlightId, highlight)), "/dati/evidenza/" + Uri.EscapeDataString(highlight)),
@@ -573,6 +573,8 @@ public sealed class ProfileSearchTests
return null;
}
public Signal? Report(Signal signal) => null;
}
private sealed class FakeBreaker : ICircuitBreaker
@@ -0,0 +1,217 @@
using Febe.Core.Abstractions;
using Febe.Core.Collection.Recipes;
using Febe.Core.Collection.Requests;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Storage;
using Febe.SitoDiProva;
using Febe.Tests.Collection.Support;
using Febe.Tests.Support;
using VirtualClock = Febe.Tests.Browser.TestSupport.VirtualClock;
namespace Febe.Tests.Collection;
/// <summary>
/// The recipes by requests (issue #36, S3) against the real test site on 127.0.0.1, through the HTTP site client, never
/// Instagram: what the site has comes into the archive without the page, one permit per request, and the stop cases of
/// the site stop the run.
/// </summary>
[TestClass]
[TestCategory(SyntheticSite.Category)]
public sealed class RequestRecipeSiteTests
{
private static readonly RequestCatalog Catalog = RequestCatalog.LoadTestSite();
[TestMethod]
public async Task TheCheckAndTheHistoryReadTheWholeGrid()
{
await using var site = await SyntheticSite.StartAsync();
await using var bed = await BedAsync(site);
var (id, posts) = Facts(site, "luca.prova", a => a.Posts.Count);
var luca = await bed.AddAccountAsync(id, "luca.prova", a => a with { State = AccountState.Backfilling });
var check = await bed.RunAsync(RecipeKind.ProfileCheck, luca.Id);
var history = await bed.RunAsync(RecipeKind.Backfill, luca.Id, maxPages: 10);
Assert.AreEqual(RecipeStatus.Completed, check.Status, check.Message);
Assert.AreEqual(RecipeStatus.Completed, history.Status, history.Message);
Assert.IsTrue(history.BackfillFinished, "The beginning of the profile was reached.");
Assert.AreEqual(0, bed.Page.Touched);
Assert.AreEqual(posts, (await bed.Db.Entries.ListByAccountAsync(luca.Id, new EntryListOptions { Kind = EntryKind.Post, Limit = 1000 })).Count);
Assert.IsNotNull((await bed.Db.Accounts.GetAsync(luca.Id))!.BackfillCompletedAt);
Assert.AreEqual(bed.Governor.Requests.Count, bed.Governor.Requests.Count(r => r.Kind is ActionKind.ProfileOpen or ActionKind.BackfillPage));
}
[TestMethod]
public async Task StoriesCollectionTaggedAndReelsComeWithoutThePage()
{
await using var site = await SyntheticSite.StartAsync();
await using var bed = await BedAsync(site);
var (martaId, _) = Facts(site, "marta.prova", a => 0);
string highlight;
int items;
lock (site.World.Gate)
{
var account = site.World.FindByUsername("marta.prova")!;
highlight = account.Highlights[0].Id;
items = account.Highlights[0].Items.Count;
}
var (lucaId, reels) = Facts(site, "luca.prova", a => a.Posts.Count(p => p.IsReel));
var marta = await bed.AddAccountAsync(martaId, "marta.prova", a => a with { ContentTypes = a.ContentTypes | ContentTypes.Tagged });
var luca = await bed.AddAccountAsync(lucaId, "luca.prova");
var stories = await bed.RunAsync(RecipeKind.AccountStories, marta.Id);
var check = await bed.RunAsync(RecipeKind.ProfileCheck, marta.Id);
var collection = await bed.RunAsync(RecipeKind.Highlight, marta.Id, highlightId: highlight);
var tagged = await bed.RunAsync(RecipeKind.Tagged, marta.Id);
var reel = await bed.RunAsync(RecipeKind.Reels, luca.Id);
foreach (var outcome in new[] { stories, check, collection, tagged, reel })
{
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
}
Assert.AreEqual(0, bed.Page.Touched);
Assert.IsTrue(stories.NewEntries > 0);
var stored = (await bed.Db.Highlights.FindAsync(marta.Id, highlight))!;
Assert.AreEqual(items, (await bed.Db.Highlights.ListItemsAsync(stored.Id)).Count, "Every content of the collection is linked, in its order.");
Assert.IsTrue((await bed.Db.Entries.ListByAccountAsync(marta.Id, new EntryListOptions { Kind = EntryKind.Tagged, Limit = 100 })).Count > 0);
Assert.AreEqual(reels, reel.NewEntries, "Every reel of the account, in one page.");
}
[TestMethod]
public async Task TheFollowingListIsReadToTheEndByItsCursors()
{
await using var site = await SyntheticSite.StartAsync();
await using var bed = await BedAsync(site);
int following;
lock (site.World.Gate)
{
following = site.World.Following.Count;
}
await bed.AddAccountAsync("1000", "alberto.prova", isMine: true);
var outcome = await bed.RunAsync(RecipeKind.FollowingList, maxPages: 10);
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
Assert.IsTrue(outcome.BackfillFinished, outcome.Message);
StringAssert.StartsWith(outcome.Message, $"Elenco dei seguiti letto: {following} profili");
Assert.AreEqual(0, bed.Page.Touched);
Assert.IsTrue(bed.Governor.Requests.All(r => r.Kind == ActionKind.FollowingListPage));
}
[TestMethod]
public async Task APrivateProfileAndAMissingOneAreUnreachable()
{
await using var site = await SyntheticSite.StartAsync();
await using var bed = await BedAsync(site);
var hidden = await bed.AddAccountAsync("1006", "riservato.prova");
var missing = await bed.AddAccountAsync(null, "nessuno.prova");
var first = await bed.RunAsync(RecipeKind.ProfileCheck, hidden.Id);
var second = await bed.RunAsync(RecipeKind.ProfileCheck, missing.Id);
Assert.AreEqual(RecipeStatus.AccountUnreachable, first.Status, first.Message);
Assert.AreEqual(UnreachableReason.PrivateNotFollowed, (await bed.Db.Accounts.GetAsync(hidden.Id))!.UnreachableReason);
Assert.AreEqual(RecipeStatus.AccountUnreachable, second.Status, second.Message);
Assert.AreEqual(UnreachableReason.NotFound, (await bed.Db.Accounts.GetAsync(missing.Id))!.UnreachableReason);
Assert.AreEqual(0, bed.Breaker.Signals.Count);
}
[TestMethod]
public async Task TheStoriesOfAPrivateProfileNotFollowedMakeItUnreachableAsByThePage()
{
await using var site = await SyntheticSite.StartAsync();
await using var bed = await BedAsync(site);
var hidden = await bed.AddAccountAsync("1006", "riservato.prova");
var outcome = await bed.RunAsync(RecipeKind.AccountStories, hidden.Id);
Assert.AreEqual(RecipeStatus.AccountUnreachable, outcome.Status, outcome.Message);
Assert.AreEqual(UnreachableReason.PrivateNotFollowed, (await bed.Db.Accounts.GetAsync(hidden.Id))!.UnreachableReason);
CollectionAssert.AreEqual(new[] { ActionKind.StoryView, ActionKind.ProfileOpen }, bed.Governor.Requests.Select(r => r.Kind).ToArray());
Assert.AreEqual(0, bed.Breaker.Signals.Count);
Assert.AreEqual(0, bed.Page.Touched);
}
[TestMethod]
public async Task TheGapBelowANewFirstPageIsFilledByTheNextPageUntilKnownPosts()
{
await using var site = await SyntheticSite.StartAsync();
await using var bed = await BedAsync(site);
var (id, _) = Facts(site, "luca.prova", a => 0);
var luca = await bed.AddAccountAsync(id, "luca.prova");
var first = await bed.RunAsync(RecipeKind.ProfileCheck, luca.Id);
var known = (await bed.Db.Entries.ListByAccountAsync(luca.Id, new EntryListOptions { Kind = EntryKind.Post, Limit = 1000 })).Count;
lock (site.World.Gate)
{
var account = site.World.FindByUsername("luca.prova")!;
for (var i = 0; i < 14; i++)
{
site.World.Publish(account, "foto", DateTimeOffset.UtcNow.AddMinutes(i));
}
}
var requestsBefore = bed.Governor.Requests.Count;
var second = await bed.RunAsync(RecipeKind.ProfileCheck, luca.Id);
Assert.AreEqual(RecipeStatus.Completed, first.Status, first.Message);
Assert.AreEqual(RecipeStatus.Completed, second.Status, second.Message);
Assert.AreEqual(14, second.NewEntries, "The first page and the two new posts of the page after it.");
Assert.AreEqual(known + 14, (await bed.Db.Entries.ListByAccountAsync(luca.Id, new EntryListOptions { Kind = EntryKind.Post, Limit = 1000 })).Count);
CollectionAssert.AreEqual(new[] { ActionKind.ProfileOpen, ActionKind.BackfillPage }, bed.Governor.Requests.Skip(requestsBefore).Select(r => r.Kind).ToArray(), "One page of the gap, then known posts.");
Assert.IsNull(await bed.Db.Settings.GetAsync($"raccolta.lacuna.{luca.Id.ToString(System.Globalization.CultureInfo.InvariantCulture)}.cursore"), "The gap is filled: no point left.");
Assert.AreEqual(0, bed.Page.Touched);
}
[TestMethod]
public async Task TooManyRequestsOfTheSiteStopTheRun()
{
await using var site = await SyntheticSite.StartAsync();
await using var bed = await BedAsync(site);
var (id, _) = Facts(site, "marta.prova", a => 0);
var marta = await bed.AddAccountAsync(id, "marta.prova");
site.Control.Set(StopMode.TooManyRequests);
var outcome = await bed.RunAsync(RecipeKind.ProfileCheck, marta.Id);
Assert.AreEqual(RecipeStatus.StoppedBySignal, outcome.Status, outcome.Message);
Assert.AreEqual(SignalLevel.Throttle, bed.Breaker.Signals.Single().Level);
Assert.AreEqual(1, bed.Governor.Requests.Count, "Nothing asked after the signal.");
}
[TestMethod]
public async Task WithoutASavedSessionTheRunStopsAsADisconnection()
{
await using var site = await SyntheticSite.StartAsync();
var clock = new VirtualClock(DateTimeOffset.UtcNow);
var requester = new HttpSiteRequester(Catalog, new InMemorySiteSession(null), HttpSiteRequesterOptions.TestSite(new Uri(site.SiteUrl + "/")), clock);
await using var bed = await RequestBed.CreateAsync(catalog: Catalog, requester: requester, clock: clock);
var (id, _) = Facts(site, "marta.prova", a => 0);
var marta = await bed.AddAccountAsync(id, "marta.prova");
var outcome = await bed.RunAsync(RecipeKind.ProfileCheck, marta.Id);
Assert.AreEqual(RecipeStatus.StoppedBySignal, outcome.Status, outcome.Message);
Assert.AreEqual(SignalLevel.Disconnect, bed.Breaker.Signals.Single().Level);
Assert.AreEqual(0, bed.Page.Touched, "Never a way back to the pages (rule 7).");
}
private static async Task<RequestBed> BedAsync(TestSite site)
{
var clock = new VirtualClock(DateTimeOffset.UtcNow);
var requester = new HttpSiteRequester(Catalog, new InMemorySiteSession(HttpSiteRequesterTests.Values()), HttpSiteRequesterOptions.TestSite(new Uri(site.SiteUrl + "/")), clock);
return await RequestBed.CreateAsync(catalog: Catalog, requester: requester, clock: clock);
}
private static (string Id, int Count) Facts(TestSite site, string username, Func<SiteAccount, int> count)
{
lock (site.World.Gate)
{
var account = site.World.FindByUsername(username)!;
return (account.Id, count(account));
}
}
}
@@ -0,0 +1,655 @@
using System.Globalization;
using System.Text.Json.Nodes;
using Febe.Core.Abstractions;
using Febe.Core.Collection;
using Febe.Core.Collection.Diagnostics;
using Febe.Core.Collection.Readers;
using Febe.Core.Collection.Recipes;
using Febe.Core.Collection.Requests;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Storage;
using Febe.Tests.Collection.Support;
using Febe.Tests.Support;
using VirtualClock = Febe.Tests.Browser.TestSupport.VirtualClock;
namespace Febe.Tests.Collection;
/// <summary>
/// The recipes by requests (issue #36, S3) on the cleaned samples of the test site, through the scripted site client:
/// the page is never touched, every request has its own permit in the category of its operation, the answers go to the
/// readers and the stop cases of §7.6 stop the run where it is.
/// </summary>
[TestClass]
public sealed class RequestRecipeTests
{
[TestMethod]
public async Task TheProfileCheckIsOneRequestThatGivesProfileGridAndCollections()
{
await using var bed = await RequestBed.CreateAsync();
var account = await bed.AddSampleAccountAsync();
var outcome = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
Assert.AreEqual(0, bed.Page.Touched, "The page is never touched.");
CollectionAssert.AreEqual(new[] { "ProvaProfiloQuery" }, bed.Scripted!.Sent.Select(s => s.Operation).ToArray());
CollectionAssert.AreEqual(new[] { ActionKind.ProfileOpen }, bed.Governor.Requests.Select(r => r.Kind).ToArray());
Assert.AreEqual(1, outcome.CountedActions);
Assert.AreEqual(12, (await bed.Db.Entries.ListByAccountAsync(account.Id, new EntryListOptions { Kind = EntryKind.Post, Limit = 100 })).Count);
Assert.AreEqual(2, (await bed.Db.Highlights.ListAsync(account.Id)).Count, "The collections came in the same answer.");
Assert.IsNotNull(await bed.Db.Settings.GetAsync($"raccolte.vassoio.{Id(account)}"));
var stored = (await bed.Db.Accounts.GetAsync(account.Id))!;
Assert.AreEqual("n17", stored.BackfillCursor, "The history starts from the cursor of the first page.");
}
[TestMethod]
public async Task ASecondCheckWithNothingNewAsksOnceMore()
{
await using var bed = await RequestBed.CreateAsync();
var account = await bed.AddSampleAccountAsync();
await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
var outcome = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
Assert.AreEqual(0, outcome.NewEntries);
Assert.AreEqual(2, bed.Scripted!.Sent.Count, "Known posts: no gap to fill.");
}
[TestMethod]
public async Task TheGapBelowANewFirstPageGoesOnByItsCursor()
{
await using var bed = await RequestBed.CreateAsync();
var account = await bed.AddSampleAccountAsync(a => a with { BackfillCursor = "c40", State = AccountState.Backfilling });
var outcome = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
var sent = bed.Scripted!.Sent;
CollectionAssert.AreEqual(new[] { "ProvaProfiloQuery", "profilo-altri" }, sent.Select(s => s.Operation).ToArray());
Assert.AreEqual("n17", sent[1].Values[CaseValues.Cursor]);
Assert.AreEqual("ndkwq.shzgd", sent[1].Values[CaseValues.Username]);
CollectionAssert.AreEqual(new[] { ActionKind.ProfileOpen, ActionKind.BackfillPage }, bed.Governor.Requests.Select(r => r.Kind).ToArray());
Assert.AreEqual("n17", await bed.Db.Settings.GetAsync($"raccolta.lacuna.{Id(account)}.cursore"), "The page after was not of the account: the point stays.");
Assert.AreEqual(1, bed.Clock.Delays.Count(d => d >= TimeSpan.FromSeconds(2)), "One wait between the two pages, none before the first request.");
}
[TestMethod]
public async Task TheHistoryStartsWithTheProfileAndGoesOnByRequests()
{
await using var bed = await RequestBed.CreateAsync();
var account = await bed.AddSampleAccountAsync(a => a with { State = AccountState.Backfilling });
var outcome = await bed.RunAsync(RecipeKind.Backfill, account.Id, maxPages: 3);
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
Assert.AreEqual(0, bed.Page.Touched);
CollectionAssert.AreEqual(new[] { "ProvaProfiloQuery", "profilo-altri" }, bed.Scripted!.Sent.Select(s => s.Operation).ToArray());
CollectionAssert.AreEqual(new[] { ActionKind.ProfileOpen, ActionKind.BackfillPage }, bed.Governor.Requests.Select(r => r.Kind).ToArray(), "The first page comes with the profile.");
Assert.AreEqual("n17", (await bed.Db.Accounts.GetAsync(account.Id))!.BackfillCursor);
}
[TestMethod]
public async Task AStoredCursorIsAskedForDirectly()
{
await using var bed = await RequestBed.CreateAsync();
var account = await bed.AddSampleAccountAsync(a => a with { BackfillCursor = "c24", State = AccountState.Backfilling });
await bed.RunAsync(RecipeKind.Backfill, account.Id);
var sent = bed.Scripted!.Sent.Single();
Assert.AreEqual("profilo-altri", sent.Operation);
Assert.AreEqual("c24", sent.Values[CaseValues.Cursor]);
Assert.AreEqual(ActionKind.BackfillPage, bed.Governor.Requests.Single().Kind);
}
[TestMethod]
public async Task TaggedAndReelsEndAtTheLastPageAndAreMarkedComplete()
{
await using var bed = await RequestBed.CreateAsync();
var marta = await bed.AddSampleAccountAsync(a => a with { ContentTypes = a.ContentTypes | ContentTypes.Tagged });
var reels = await bed.AddAccountAsync("6104", "lmxm.bgwrl");
var tagged = await bed.RunAsync(RecipeKind.Tagged, marta.Id);
var reel = await bed.RunAsync(RecipeKind.Reels, reels.Id);
Assert.AreEqual(RecipeStatus.Completed, tagged.Status, tagged.Message);
Assert.AreEqual(RecipeStatus.Completed, reel.Status, reel.Message);
Assert.AreEqual(0, bed.Page.Touched);
CollectionAssert.AreEqual(new[] { "taggati", "reel" }, bed.Scripted!.Sent.Select(s => s.Operation).ToArray());
CollectionAssert.AreEqual(new[] { ActionKind.BackfillPage, ActionKind.BackfillPage }, bed.Governor.Requests.Select(r => r.Kind).ToArray());
Assert.AreEqual(3, (await bed.Db.Entries.ListByAccountAsync(marta.Id, new EntryListOptions { Kind = EntryKind.Tagged, Limit = 100 })).Count);
Assert.AreEqual(6, (await bed.Db.Entries.ListByAccountAsync(reels.Id, new EntryListOptions { Kind = EntryKind.Post, Limit = 100 })).Count);
Assert.IsNotNull(await bed.Db.Settings.GetAsync($"raccolta.taggati.{Id(marta)}.completo"));
Assert.IsNotNull(await bed.Db.Settings.GetAsync($"raccolta.reel.{Id(reels)}.completo"));
}
[TestMethod]
public async Task TheStoriesOfAnAccountAreOneRequestWithoutTheMinimumOfTen()
{
await using var bed = await RequestBed.CreateAsync();
bed.Governor.ReportedRemaining = 1; // by the viewer the recipe would not even start
var account = await bed.AddSampleAccountAsync();
var outcome = await bed.RunAsync(RecipeKind.AccountStories, account.Id);
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
Assert.AreEqual(0, bed.Page.Touched);
Assert.AreEqual("storie", bed.Scripted!.Sent.Single().Operation);
Assert.AreEqual(ActionKind.StoryView, bed.Governor.Requests.Single().Kind, "One StoryView for all the stories of the answer.");
Assert.AreEqual(4, outcome.NewEntries);
Assert.AreEqual(4, (await bed.Db.Entries.ListByAccountAsync(account.Id, new EntryListOptions { Kind = EntryKind.Story, Limit = 100 })).Count);
Assert.IsNotNull((await bed.Db.Accounts.GetAsync(account.Id))!.LastStoriesCheckAt);
}
[TestMethod]
public async Task TheStoriesOfTwoAccountsInARowDoNotWaitBeforeTheirRequest()
{
// §6.3: the first request of a recipe does not wait, the Governor keeps the distance (unlike the viewer, which
// waits 1–4 s between two accounts).
await using var bed = await RequestBed.CreateAsync();
var first = await bed.AddSampleAccountAsync();
var second = await bed.AddAccountAsync("6666", "altra.prova");
Assert.AreEqual(RecipeStatus.Completed, (await bed.RunAsync(RecipeKind.AccountStories, first.Id)).Status);
var before = bed.Clock.Now;
await bed.RunAsync(RecipeKind.AccountStories, second.Id);
Assert.HasCount(2, bed.Scripted!.Sent);
Assert.AreEqual(before, bed.Clock.Now, "No wait between the two accounts.");
}
[TestMethod]
public async Task NoStoriesIsAQuietDayNotAnEmptyPage()
{
await using var bed = await RequestBed.CreateAsync();
var account = await bed.AddSampleAccountAsync();
bed.Scripted!.Then(ScriptedReply.NotFoundJson);
var outcome = await bed.RunAsync(RecipeKind.AccountStories, account.Id);
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
Assert.AreEqual(0, outcome.NewEntries);
Assert.IsNotNull((await bed.Db.Accounts.GetAsync(account.Id))!.LastStoriesCheckAt);
}
[TestMethod]
public async Task ACollectionNotKnownYetWaitsForTheProfileCheck()
{
await using var bed = await RequestBed.CreateAsync();
var account = await bed.AddSampleAccountAsync();
var outcome = await bed.RunAsync(RecipeKind.Highlight, account.Id, highlightId: "3688348931");
Assert.AreEqual(RecipeStatus.Completed, outcome.Status);
StringAssert.Contains(outcome.Message, "non è ancora nota");
Assert.AreEqual(0, bed.Scripted!.Sent.Count);
Assert.AreEqual(0, bed.Governor.Requests.Count);
}
[TestMethod]
public async Task AKnownCollectionIsReadByItsIdentifier()
{
await using var bed = await RequestBed.CreateAsync();
var account = await bed.AddSampleAccountAsync();
await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
var outcome = await bed.RunAsync(RecipeKind.Highlight, account.Id, highlightId: "3688348931");
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
var sent = bed.Scripted!.Sent[^1];
Assert.AreEqual("evidenza", sent.Operation);
Assert.AreEqual("3688348931", sent.Values[CaseValues.HighlightId]);
Assert.AreEqual(ActionKind.StoryView, bed.Governor.Requests[^1].Kind);
Assert.AreEqual(3, outcome.NewEntries);
var highlight = (await bed.Db.Highlights.FindAsync(account.Id, "3688348931"))!;
Assert.IsNotNull(highlight.LastCheckedAt);
}
[TestMethod]
public async Task ASinglePostIsAskedByItsCode()
{
await using var bed = await RequestBed.CreateAsync();
var account = await bed.AddSampleAccountAsync();
var entry = await AddPostAsync(bed, account, "6686720181", "TqwwCvG");
var outcome = await bed.RunAsync(RecipeKind.SinglePost, entryId: entry);
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
StringAssert.StartsWith(outcome.Message, "Post completato");
Assert.AreEqual("TqwwCvG", bed.Scripted!.Sent.Single().Values[CaseValues.Code]);
Assert.AreEqual(ActionKind.SinglePost, bed.Governor.Requests.Single().Kind);
}
[TestMethod]
public async Task APostWithoutCodeGoesByThePageWhenThePageCanRun()
{
await using var bed = await RequestBed.CreateAsync();
var account = await bed.AddSampleAccountAsync();
var entry = await AddPostAsync(bed, account, "6686720181", null);
var outcome = await bed.RunAsync(RecipeKind.SinglePost, entryId: entry);
Assert.AreEqual(0, bed.Scripted!.Sent.Count);
Assert.IsTrue(bed.Page.Touched > 0, "The page route was taken.");
Assert.AreEqual(RecipeStatus.Failed, outcome.Status, "The page of the bed refuses everything.");
Assert.IsTrue((await bed.EventCodesAsync()).Contains("richieste-valore-mancante"));
}
[TestMethod]
public async Task APostWithoutCodeWaitsWhenThePageCannotRun()
{
var map = new SiteMap("prova", new Dictionary<string, string?> { [SitePages.Profile] = "/profilo/{username}/" }, [], SiteTargets.All);
await using var bed = await RequestBed.CreateAsync(map);
var account = await bed.AddSampleAccountAsync();
var entry = await AddPostAsync(bed, account, "6686720181", null);
var outcome = await bed.RunAsync(RecipeKind.SinglePost, entryId: entry);
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, "Never NotConfigured: the engine would stop planning it.");
StringAssert.Contains(outcome.Message, "il codice del post");
Assert.AreEqual(0, bed.Page.Touched);
Assert.AreEqual(0, bed.Scripted!.Sent.Count);
}
[TestMethod]
public async Task TheFollowingListStoresItsCursorAndAsksForItNextTime()
{
await using var bed = await RequestBed.CreateAsync();
await bed.AddAccountAsync("17841400000000077", "alberto.prova", isMine: true);
var first = await bed.RunAsync(RecipeKind.FollowingList, maxPages: 1);
var second = await bed.RunAsync(RecipeKind.FollowingList, maxPages: 1);
Assert.AreEqual(RecipeStatus.Completed, first.Status, first.Message);
StringAssert.StartsWith(first.Message, "Letti 10 profili");
Assert.AreEqual(RecipeStatus.Completed, second.Status, second.Message);
var sent = bed.Scripted!.Sent;
Assert.IsFalse(sent[0].Values.ContainsKey(CaseValues.Cursor), "The first page without «dopo».");
Assert.AreEqual("b44", sent[1].Values[CaseValues.Cursor]);
Assert.AreEqual(0, bed.Page.Touched);
CollectionAssert.AreEqual(new[] { ActionKind.FollowingListPage, ActionKind.FollowingListPage }, bed.Governor.Requests.Select(r => r.Kind).ToArray());
}
[TestMethod]
[DataRow(ScriptedReply.TooManyRequests, SignalLevel.Throttle)]
[DataRow(ScriptedReply.RedirectToLogin, SignalLevel.Challenge)]
[DataRow(ScriptedReply.RedirectToChallenge, SignalLevel.Challenge)]
[DataRow(ScriptedReply.HtmlInsteadOfJson, SignalLevel.Challenge)]
[DataRow(ScriptedReply.MissingRootField, SignalLevel.Challenge)]
[DataRow(ScriptedReply.SessionCookieDeleted, SignalLevel.Challenge)]
public async Task AStopSignalInTheAnswerStopsTheRunWhereItIs(ScriptedReply reply, SignalLevel level)
{
await using var bed = await RequestBed.CreateAsync();
var account = await bed.AddSampleAccountAsync(a => a with { BackfillCursor = "c40", State = AccountState.Backfilling });
bed.Scripted!.Then(reply);
var outcome = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
Assert.AreEqual(RecipeStatus.StoppedBySignal, outcome.Status, outcome.Message);
Assert.AreEqual(1, bed.Scripted.Sent.Count, "No other request after the signal.");
Assert.AreEqual(level, bed.Breaker.Signals.Single().Level);
Assert.AreEqual(0, outcome.NewEntries);
Assert.AreEqual(0, bed.Page.Touched);
}
[TestMethod]
public async Task AProfileTheSiteDoesNotHaveMakesTheAccountUnreachable()
{
await using var bed = await RequestBed.CreateAsync();
var account = await bed.AddSampleAccountAsync();
bed.Scripted!.Then(ScriptedReply.NotFoundJson);
var outcome = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
Assert.AreEqual(RecipeStatus.AccountUnreachable, outcome.Status, outcome.Message);
var stored = (await bed.Db.Accounts.GetAsync(account.Id))!;
Assert.AreEqual(AccountState.Unreachable, stored.State);
Assert.AreEqual(UnreachableReason.NotFound, stored.UnreachableReason);
Assert.AreEqual(0, bed.Breaker.Signals.Count, "A «not found» is not a stop signal.");
}
[TestMethod]
[DataRow(ScriptedReply.ServerError500, "(500)")]
[DataRow(ScriptedReply.ServerError503, "(503)")]
[DataRow(ScriptedReply.Timeout, "nessuna risposta in tempo")]
[DataRow(ScriptedReply.Unreachable, "collegamento non riuscito")]
[DataRow(ScriptedReply.TooLarge, "risposta troppo grande")]
[DataRow(ScriptedReply.Broken, "risposta rovinata")]
public async Task AnErrorOfTheSiteFailsTheRunWithoutRetrying(ScriptedReply reply, string said)
{
await using var bed = await RequestBed.CreateAsync();
var account = await bed.AddSampleAccountAsync();
bed.Scripted!.Then(reply);
var outcome = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
Assert.AreEqual(RecipeStatus.Failed, outcome.Status, outcome.Message);
StringAssert.Contains(outcome.Message, said);
Assert.AreEqual(1, bed.Scripted.Sent.Count, "Never tried again in the run.");
Assert.IsTrue((await bed.EventCodesAsync()).Contains("ricetta-fallita"));
Assert.AreEqual(0, bed.Breaker.Signals.Count, "One error is an empty page, not a signal.");
}
[TestMethod]
public async Task ThreeEmptyAnswersInARowAreAThrottle()
{
await using var bed = await RequestBed.CreateAsync();
var account = await bed.AddSampleAccountAsync();
bed.Scripted!.Then(ScriptedReply.ServerError500, ScriptedReply.ServerError500, ScriptedReply.ServerError500);
await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
var third = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
Assert.AreEqual(RecipeStatus.StoppedBySignal, third.Status, third.Message);
Assert.AreEqual(SignalLevel.Throttle, bed.Breaker.Signals.Single().Level);
}
[TestMethod]
public async Task AnAnswerNoReaderKnowsIsAnUnrecognizedFormat()
{
await using var bed = await RequestBed.CreateAsync();
var account = await bed.AddSampleAccountAsync();
bed.Scripted!.Then(ScriptedReply.UnknownShape);
var outcome = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
Assert.AreEqual(RecipeStatus.UnrecognizedFormat, outcome.Status, outcome.Message);
Assert.IsTrue((await bed.EventCodesAsync()).Contains("formato-non-riconosciuto"));
}
[TestMethod]
public async Task ARefusedPermitSendsNothing()
{
await using var bed = await RequestBed.CreateAsync();
var account = await bed.AddSampleAccountAsync();
bed.Governor.Limit(ActionKind.ProfileOpen, 0);
var outcome = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
Assert.AreEqual(RecipeStatus.Denied, outcome.Status);
Assert.AreEqual(0, bed.Scripted!.Sent.Count);
}
[TestMethod]
public async Task TheGapWaitsWhenThePermitOfItsPageIsRefused()
{
await using var bed = await RequestBed.CreateAsync();
var account = await bed.AddSampleAccountAsync(a => a with { BackfillCursor = "c40", State = AccountState.Backfilling });
bed.Governor.Limit(ActionKind.BackfillPage, 0);
var outcome = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, "The check itself is done.");
Assert.AreEqual(1, bed.Scripted!.Sent.Count);
Assert.AreEqual("n17", await bed.Db.Settings.GetAsync($"raccolta.lacuna.{Id(account)}.cursore"));
}
[TestMethod]
public async Task WithoutTheSiteClientEveryRecipeGoesByThePage()
{
await using var bed = await RequestBed.CreateAsync(requests: false);
var account = await bed.AddSampleAccountAsync();
var outcome = await bed.RunAsync(RecipeKind.AccountStories, account.Id);
Assert.IsTrue(bed.Page.Touched > 0);
Assert.AreEqual(0, bed.Scripted!.Sent.Count);
Assert.AreEqual(RecipeStatus.Failed, outcome.Status);
}
[TestMethod]
public async Task TheFollowingSweepNeverGoesByRequests()
{
await using var bed = await RequestBed.CreateAsync();
Assert.IsFalse(bed.Runner.HasRequestRoute(RecipeKind.FollowingSweep));
Assert.IsNull(RecipeRunner.RequestOperations(RequestCatalog.LoadTestSite(), RecipeKind.FollowingSweep));
}
[TestMethod]
public async Task TheDiagnosticReportSeesTheRequestsByShapeOnly()
{
var clock = new VirtualClock(new DateTimeOffset(2026, 10, 13, 16, 0, 0, TimeSpan.Zero));
long? current = null;
using var diagnostics = new CollectionDiagnostics(clock, () => current) { SiteMap = SiteMap.LoadTestSite() };
await using var bed = await RequestBed.CreateAsync(diagnostics: diagnostics, clock: clock);
current = bed.Session.SessionId;
diagnostics.SessionStarted(bed.Session.SessionId, clock.Now, 1.0);
var account = await bed.AddSampleAccountAsync(a => a with { BackfillCursor = "c40", State = AccountState.Backfilling });
await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
await bed.RunAsync(RecipeKind.Highlight, account.Id, highlightId: "3688348931");
diagnostics.SessionEnded(bed.Session.SessionId, clock.Now, SessionOutcome.Completed, SessionStopCause.PlannedEnd, RecipeStatus.Completed);
using var stream = new MemoryStream();
DiagnosticReport.Write(stream, diagnostics.Collect(), new DiagnosticReportHeader("0.0.0-prove", "docker", clock.Now, TestZones.Rome));
var text = System.Text.Encoding.UTF8.GetString(stream.ToArray());
Assert.AreEqual(0, diagnostics.Faults);
StringAssert.Contains(text, "/api/graphql", "The request is there, by the shape of its path.");
StringAssert.Contains(text, "/api/{testo}/{testo}/{testo}", "The other requests too, by the shapes of their paths.");
foreach (var value in new[] { "ndkwq.shzgd", "3688348931", "n17", "c40", "5555", "TqwwCvG" })
{
Assert.IsFalse(text.Contains(value, StringComparison.Ordinal), $"«{value}» is in the report.");
}
}
[TestMethod]
public async Task StoriesNotFoundAskTheProfileAndArePlainlyNoStoriesForAPublicOne()
{
await using var bed = await RequestBed.CreateAsync();
var account = await bed.AddSampleAccountAsync();
for (var i = 0; i < 3; i++)
{
bed.Scripted!.Then(ScriptedReply.NotFoundJson);
var outcome = await bed.RunAsync(RecipeKind.AccountStories, account.Id);
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
}
CollectionAssert.AreEqual(new[] { "storie", "ProvaProfiloQuery", "storie", "ProvaProfiloQuery", "storie", "ProvaProfiloQuery" }, bed.Scripted!.Sent.Select(s => s.Operation).ToArray());
CollectionAssert.AreEqual(new[] { ActionKind.StoryView, ActionKind.ProfileOpen }, bed.Governor.Requests.Take(2).Select(r => r.Kind).ToArray(), "The profile says why, as by the page.");
Assert.AreEqual(0, bed.Breaker.Signals.Count, "Three «not found» of the stories are not three empty pages.");
var stored = (await bed.Db.Accounts.GetAsync(account.Id))!;
Assert.AreNotEqual(AccountState.Unreachable, stored.State);
Assert.IsNotNull(stored.LastStoriesCheckAt);
}
[TestMethod]
public async Task StoriesNotFoundOfAProfileNotFoundMakeTheAccountUnreachable()
{
await using var bed = await RequestBed.CreateAsync();
var account = await bed.AddSampleAccountAsync();
bed.Scripted!.Then(ScriptedReply.NotFoundJson, ScriptedReply.NotFoundJson);
var outcome = await bed.RunAsync(RecipeKind.AccountStories, account.Id);
Assert.AreEqual(RecipeStatus.AccountUnreachable, outcome.Status, outcome.Message);
Assert.AreEqual(UnreachableReason.NotFound, (await bed.Db.Accounts.GetAsync(account.Id))!.UnreachableReason);
}
[TestMethod]
public async Task AStoriesAnswerStartsTheCountOfEmptyPagesAgain()
{
await using var bed = await RequestBed.CreateAsync();
var account = await bed.AddSampleAccountAsync();
bed.Scripted!.Then(ScriptedReply.ServerError500, ScriptedReply.ServerError500);
await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
var stories = await bed.RunAsync(RecipeKind.AccountStories, account.Id);
bed.Scripted.Then(ScriptedReply.ServerError500);
var third = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
Assert.AreEqual(RecipeStatus.Completed, stories.Status, stories.Message);
Assert.AreEqual(RecipeStatus.Failed, third.Status, third.Message);
Assert.AreEqual(0, bed.Breaker.Signals.Count, "The stories in between were data: the count of empty pages started again.");
}
[TestMethod]
public async Task ASignalOnTheSecondPageOfTheHistoryKeepsThePointOfTheFirst()
{
await using var bed = await RequestBed.CreateAsync();
var account = await bed.AddSampleAccountAsync(a => a with { State = AccountState.Backfilling });
bed.Scripted!.Then(ScriptedReply.Sample, ScriptedReply.TooManyRequests);
var outcome = await bed.RunAsync(RecipeKind.Backfill, account.Id, maxPages: 3);
Assert.AreEqual(RecipeStatus.StoppedBySignal, outcome.Status, outcome.Message);
Assert.AreEqual(2, bed.Scripted.Sent.Count, "Nothing after the signal.");
Assert.AreEqual(SignalLevel.Throttle, bed.Breaker.Signals.Single().Level);
Assert.AreEqual("n17", (await bed.Db.Accounts.GetAsync(account.Id))!.BackfillCursor, "The point of the last page saved.");
Assert.AreEqual(12, (await bed.Db.Entries.ListByAccountAsync(account.Id, new EntryListOptions { Kind = EntryKind.Post, Limit = 100 })).Count);
}
[TestMethod]
public async Task ASignalOnThePageOfTheGapKeepsTheGapPoint()
{
await using var bed = await RequestBed.CreateAsync();
var account = await bed.AddSampleAccountAsync(a => a with { BackfillCursor = "c40", State = AccountState.Backfilling });
bed.Scripted!.Then(ScriptedReply.Sample, ScriptedReply.RedirectToLogin);
var outcome = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
Assert.AreEqual(RecipeStatus.StoppedBySignal, outcome.Status, outcome.Message);
Assert.AreEqual(2, bed.Scripted.Sent.Count);
Assert.AreEqual(SignalLevel.Challenge, bed.Breaker.Signals.Single().Level);
Assert.AreEqual("n17", await bed.Db.Settings.GetAsync($"raccolta.lacuna.{Id(account)}.cursore"));
Assert.AreEqual(12, (await bed.Db.Entries.ListByAccountAsync(account.Id, new EntryListOptions { Kind = EntryKind.Post, Limit = 100 })).Count, "The first page was saved before.");
}
[TestMethod]
public async Task ATrayOfItsOwnIsAskedOnceADayAfterTheFirstPage()
{
await using var bed = await RequestBed.CreateAsync(catalog: TrayOfItsOwn());
var account = await bed.AddSampleAccountAsync();
var first = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
var second = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
Assert.AreEqual(RecipeStatus.Completed, first.Status, first.Message);
Assert.AreEqual(RecipeStatus.Completed, second.Status, second.Message);
CollectionAssert.AreEqual(new[] { "ProvaProfiloQuery", "profilo", "ProvaProfiloQuery" }, bed.Scripted!.Sent.Select(s => s.Operation).ToArray());
CollectionAssert.AreEqual(new[] { ActionKind.ProfileOpen, ActionKind.ProfileOpen, ActionKind.ProfileOpen }, bed.Governor.Requests.Select(r => r.Kind).ToArray());
Assert.AreEqual(2, (await bed.Db.Highlights.ListAsync(account.Id)).Count);
}
[TestMethod]
public async Task AManualCheckAsksNoTrayForAnAccountThatDoesNotWantItsCollections()
{
await using var bed = await RequestBed.CreateAsync(catalog: TrayOfItsOwn());
var account = await bed.AddSampleAccountAsync(a => a with { ContentTypes = a.ContentTypes & ~ContentTypes.Highlights });
var outcome = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id, manual: true);
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
Assert.AreEqual("ProvaProfiloQuery", bed.Scripted!.Sent.Single().Operation);
}
[TestMethod]
public async Task ATrayRefusedOrFailedLosesNotTheFirstPage()
{
await using var refused = await RequestBed.CreateAsync(catalog: TrayOfItsOwn());
var one = await refused.AddSampleAccountAsync();
refused.Governor.Limit(ActionKind.ProfileOpen, 1);
var denied = await refused.RunAsync(RecipeKind.ProfileCheck, one.Id);
await using var failing = await RequestBed.CreateAsync(catalog: TrayOfItsOwn());
var two = await failing.AddSampleAccountAsync();
failing.Scripted!.Then(ScriptedReply.Sample, ScriptedReply.ServerError503);
var failed = await failing.RunAsync(RecipeKind.ProfileCheck, two.Id);
Assert.AreEqual(RecipeStatus.Completed, denied.Status, "The check is done; the list waits for the next one.");
Assert.IsNull(await refused.Db.Settings.GetAsync($"raccolte.vassoio.{Id(one)}"));
Assert.AreEqual(RecipeStatus.Failed, failed.Status, failed.Message);
foreach (var (bed, account) in new[] { (refused, one), (failing, two) })
{
Assert.AreEqual(12, (await bed.Db.Entries.ListByAccountAsync(account.Id, new EntryListOptions { Kind = EntryKind.Post, Limit = 100 })).Count, "The first page was saved before the list.");
}
}
[TestMethod]
public async Task ATrayTheReadersDoNotKnowIsAnUnrecognizedFormat()
{
await using var bed = await RequestBed.CreateAsync(catalog: TrayOfItsOwn());
var account = await bed.AddSampleAccountAsync();
bed.Scripted!.Then(ScriptedReply.Sample, ScriptedReply.UnknownShape);
var outcome = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
Assert.AreEqual(RecipeStatus.UnrecognizedFormat, outcome.Status, outcome.Message);
}
[TestMethod]
public async Task AStoredPointWithoutItsNextPageGoesByThePagesWhenTheyCanRun()
{
await using var bed = await RequestBed.CreateAsync();
var account = await bed.AddSampleAccountAsync(a => a with { ContentTypes = a.ContentTypes | ContentTypes.Tagged });
await bed.Db.Settings.SetAsync($"raccolta.taggati.{Id(account)}.cursore", "t12");
await bed.RunAsync(RecipeKind.Tagged, account.Id);
Assert.AreEqual(0, bed.Scripted!.Sent.Count);
Assert.IsTrue(bed.Page.Touched > 0, "The pages go on from the stored point.");
Assert.IsTrue((await bed.EventCodesAsync()).Contains("richieste-pagine-successive"));
}
[TestMethod]
public async Task AStoredPointWithoutItsNextPageStillReadsTheFirstPage()
{
var map = new SiteMap("prova", new Dictionary<string, string?> { [SitePages.Profile] = "/profilo/{username}/" }, [], SiteTargets.All);
await using var bed = await RequestBed.CreateAsync(map);
var account = await bed.AddSampleAccountAsync(a => a with { ContentTypes = a.ContentTypes | ContentTypes.Tagged });
await bed.Db.Settings.SetAsync($"raccolta.taggati.{Id(account)}.cursore", "t12");
var outcome = await bed.RunAsync(RecipeKind.Tagged, account.Id);
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
Assert.AreEqual(0, bed.Page.Touched);
var sent = bed.Scripted!.Sent.Single();
Assert.AreEqual("taggati", sent.Operation, "What is new on top is read.");
Assert.IsFalse(sent.Values.ContainsKey(CaseValues.Cursor));
Assert.AreEqual(3, (await bed.Db.Entries.ListByAccountAsync(account.Id, new EntryListOptions { Kind = EntryKind.Tagged, Limit = 100 })).Count);
Assert.IsNotNull(await bed.Db.Settings.GetAsync($"raccolta.taggati.{Id(account)}.completo"), "The whole tab fits in its first page: it is complete.");
}
/// <summary>The test site's catalog with the list of collections asked by an operation of its own (the shape of Instagram's).</summary>
private static RequestCatalog TrayOfItsOwn()
{
var file = JsonNode.Parse(SiteMap.ReadEmbeddedText("richieste.prova.json"))!.AsObject();
foreach (var operation in file["operations"]!.AsArray())
{
switch (operation!["name"]!.GetValue<string>())
{
case "ProvaProfiloQuery":
operation["roles"] = new JsonArray("profile", "posts");
break;
case "profilo":
operation["roles"] = new JsonArray("highlights");
break;
}
}
return RequestCatalog.Parse(file.ToJsonString(), "richieste.prova.json");
}
private static async Task<long> AddPostAsync(RequestBed bed, Account account, string instagramId, string? code)
{
var result = await bed.Db.Entries.AddAsync(
new Entry
{
AccountId = account.Id,
Kind = EntryKind.Post,
InstagramId = instagramId,
Code = code,
PublishedAt = bed.Clock.Now.AddDays(-3),
DiscoveredAt = bed.Clock.Now.AddDays(-3),
},
[]);
return result.Stored.Entry.Id;
}
private static string Id(Account account) => account.Id.ToString(CultureInfo.InvariantCulture);
}
@@ -0,0 +1,220 @@
using System.Text.Json.Nodes;
using Febe.Core.Abstractions;
using Febe.Core.Collection;
using Febe.Core.Collection.Readers;
using Febe.Core.Collection.Recipes;
using Febe.Core.Collection.Requests;
using Febe.Core.Engine;
using Febe.Tests.Collection.Support;
namespace Febe.Tests.Collection;
/// <summary>
/// Which recipe goes by requests (issue #36, S3): the roles of the catalog, checked when it loads; on Instagram none,
/// so nothing changes there; the configuration tells which recipes go by requests and a new role changes its fingerprint.
/// </summary>
[TestClass]
public sealed class RequestRoutingTests
{
[TestMethod]
public void OnInstagramNoRecipeGoesByRequests()
{
var instagram = RequestCatalog.LoadInstagram();
foreach (var kind in Enum.GetValues<RecipeKind>())
{
Assert.IsNull(RecipeRunner.RequestOperations(instagram, kind), $"{kind}: every operation of Instagram is still not configured.");
}
// The roles are written all the same, waiting for S4.
Assert.AreEqual("PolarisProfilePageContentQuery", instagram.HolderOf(RequestRole.Profile)?.Name);
Assert.AreEqual("PolarisProfilePostsQuery", instagram.HolderOf(RequestRole.Posts)?.Name);
Assert.IsNull(instagram.HolderOf(RequestRole.PostsNext), "The posts query of the HAR has no cursor.");
Assert.AreEqual(ActionKind.ProfileOpen, instagram.HolderOf(RequestRole.Posts)!.FirstPageCategory);
Assert.IsNull(instagram.HolderOf(RequestRole.Following), "No shapes of the following list yet.");
}
[TestMethod]
public async Task OnInstagramTheRunnerRefusesAsBefore()
{
var instagram = RequestCatalog.LoadInstagram();
var map = InstagramMap();
await using var withClient = await RequestBed.CreateAsync(map, instagram);
await using var without = await RequestBed.CreateAsync(map, instagram, requests: false);
foreach (var kind in Enum.GetValues<RecipeKind>())
{
Assert.IsFalse(withClient.Runner.HasRequestRoute(kind), kind.ToString());
Assert.AreEqual(without.Runner.NotConfiguredReason(kind), withClient.Runner.NotConfiguredReason(kind), kind.ToString());
}
}
[TestMethod]
public async Task TheEngineChecksTheBudgetOfTheFirstRequestOfTheRoute()
{
await using var byRequests = await RequestBed.CreateAsync();
await using var byPages = await RequestBed.CreateAsync(requests: false);
await using var instagram = await RequestBed.CreateAsync(InstagramMap(), RequestCatalog.LoadInstagram());
// Taggati and Reel by requests start with a page of the tab, not with the profile.
Assert.AreEqual(ActionKind.BackfillPage, byRequests.Runner.FirstCategory(RecipeKind.Tagged));
Assert.AreEqual(ActionKind.BackfillPage, byRequests.Runner.FirstCategory(RecipeKind.Reels));
foreach (var kind in Enum.GetValues<RecipeKind>())
{
Assert.AreEqual(CheckPolicy.CategoryOf(kind), byPages.Runner.FirstCategory(kind), kind.ToString());
Assert.AreEqual(CheckPolicy.CategoryOf(kind), instagram.Runner.FirstCategory(kind), $"{kind}: Instagram as before.");
if (kind is not (RecipeKind.Tagged or RecipeKind.Reels))
{
Assert.AreEqual(CheckPolicy.CategoryOf(kind), byRequests.Runner.FirstCategory(kind), kind.ToString());
}
}
}
[TestMethod]
public async Task ARecipeByRequestsNeedsNoPageOfTheMap()
{
var empty = new SiteMap("prova", new Dictionary<string, string?>(), [], SiteTargets.All);
await using var bed = await RequestBed.CreateAsync(empty);
Assert.IsNull(bed.Runner.NotConfiguredReason(RecipeKind.ProfileCheck));
Assert.IsNull(bed.Runner.NotConfiguredReason(RecipeKind.AccountStories));
Assert.IsNotNull(bed.Runner.NotConfiguredReason(RecipeKind.FollowingSweep), "The sweep needs the home page.");
}
[TestMethod]
public void OnTheTestSiteEveryRecipeButTheSweepGoesByRequests()
{
var prova = RequestCatalog.LoadTestSite();
string[]? Names(RecipeKind kind) => RecipeRunner.RequestOperations(prova, kind)?.Select(o => o.Name).ToArray();
CollectionAssert.AreEqual(new[] { "ProvaProfiloQuery", "profilo-altri" }, Names(RecipeKind.ProfileCheck));
CollectionAssert.AreEqual(new[] { "ProvaProfiloQuery", "profilo-altri" }, Names(RecipeKind.Backfill));
CollectionAssert.AreEqual(new[] { "taggati" }, Names(RecipeKind.Tagged), "No next pages of the tagged posts: their answer has them all.");
CollectionAssert.AreEqual(new[] { "reel" }, Names(RecipeKind.Reels));
CollectionAssert.AreEqual(new[] { "storie" }, Names(RecipeKind.AccountStories));
CollectionAssert.AreEqual(new[] { "evidenza" }, Names(RecipeKind.Highlight));
CollectionAssert.AreEqual(new[] { "post" }, Names(RecipeKind.SinglePost));
CollectionAssert.AreEqual(new[] { "seguiti" }, Names(RecipeKind.FollowingList), "One operation, the first page and the next.");
Assert.IsNull(Names(RecipeKind.FollowingSweep));
}
[TestMethod]
public void TheFirstPageOfTheGridCountsAsTheProfile()
{
var instagram = RequestCatalog.LoadInstagram();
var posts = instagram.HolderOf(RequestRole.Posts)!;
Assert.AreEqual(ActionKind.BackfillPage, posts.Category);
Assert.AreEqual(ActionKind.ProfileOpen, posts.CategoryFor(new SiteRequest(posts.Name, new Dictionary<string, string> { [CaseValues.AccountId] = "5555" })));
}
[TestMethod]
public void TheGuardWantsThePermitOfTheCategoryOfTheRequest()
{
// ProvaProfiloQuery counts as a profile; profilo-altri, with its cursor, as a page of history.
var prova = RequestCatalog.LoadTestSite();
var spent = new SpentPermits();
var next = new SiteRequest("profilo-altri", new Dictionary<string, string> { [CaseValues.Username] = "marta.prova", [CaseValues.Cursor] = "c12" });
var refusal = Assert.ThrowsExactly<SiteRequestRefusedException>(() => SiteRequestGuard.Check(prova, next, Permit.Grant(ActionKind.ProfileOpen, null), spent));
StringAssert.Contains(refusal.Message, "conta come");
Assert.AreEqual("profilo-altri", SiteRequestGuard.Check(prova, next, Permit.Grant(ActionKind.BackfillPage, null), spent).Name);
}
[TestMethod]
[DataRow("[\"seguiti-di-qualcuno\"]", "sconosciuto")]
[DataRow("[\"posts-next\"]", "va da una pagina alla successiva")]
[DataRow("[null]", "sconosciuto")]
public void ARoleThatCannotBeIsRefusedWhenTheCatalogLoads(string roles, string said)
{
var operation = Rest("post-in-piu", "/api/dati/post-in-piu/{code}");
operation["roles"] = JsonNode.Parse(roles);
StringAssert.Contains(Refuse(Alone(operation)), said);
}
[TestMethod]
public void AFirstPageRoleOnAnOperationThatAlwaysWantsACursorIsRefused()
{
var operation = Rest("altri-in-piu", "/api/dati/altri-in-piu");
operation["parameters"] = new JsonObject { ["dopo"] = "{cursor}" };
operation["roles"] = new JsonArray("posts");
StringAssert.Contains(Refuse(Alone(operation)), "prima pagina");
}
[TestMethod]
public void ARoleOfTwoOperationsIsRefused()
{
var file = JsonNode.Parse(SiteMap.ReadEmbeddedText("richieste.prova.json"))!.AsObject();
var second = Rest("post-due", "/api/dati/post-due/{code}");
second["roles"] = new JsonArray("post");
file["operations"]!.AsArray().Add(second);
StringAssert.Contains(Refuse(file.ToJsonString()), "un ruolo appartiene a una sola operazione");
}
[TestMethod]
public void ASearchHasNoRoleAndTheFirstPageCategoryIsOnlyForTheHistory()
{
var search = Rest("cerca-in-piu", "/api/dati/cerca-in-piu");
search["category"] = "ricerca";
search["parameters"] = new JsonObject { ["testo"] = "{search_text}" };
search["roles"] = new JsonArray("profile");
StringAssert.Contains(Refuse(Alone(search)), "una ricerca non ha ruoli");
var post = Rest("post-in-piu", "/api/dati/post-in-piu/{code}");
post["firstPageCategory"] = "profilo";
StringAssert.Contains(Refuse(Alone(post)), "solo per un'operazione della categoria «storico»");
var history = Rest("storico-in-piu", "/api/dati/storico-in-piu/{username}");
history["category"] = "storico";
history["firstPageCategory"] = "post";
StringAssert.Contains(Refuse(Alone(history)), "ammette solo «profilo»");
}
[TestMethod]
public void ARoleOfAnOperationNotConfiguredGivesNoRoute()
{
var file = JsonNode.Parse(SiteMap.ReadEmbeddedText("richieste.prova.json"))!.AsObject();
var stories = file["operations"]!.AsArray().Single(o => o!["name"]!.GetValue<string>() == "storie")!.AsObject();
stories["configured"] = false;
stories["reason"] = "prova";
var catalog = RequestCatalog.Parse(file.ToJsonString(), "richieste.prova.json");
Assert.IsNull(catalog.ForRole(RequestRole.Stories));
Assert.AreEqual("storie", catalog.HolderOf(RequestRole.Stories)?.Name);
Assert.IsNull(RecipeRunner.RequestOperations(catalog, RecipeKind.AccountStories));
}
[TestMethod]
public void TheConfigurationSaysWhichRecipesGoByRequests()
{
var vocabulary = ReaderVocabulary.LoadTestSite();
var empty = new SiteMap("prova", new Dictionary<string, string?>(), [], SiteTargets.All);
var without = CollectionConfiguration.Describe("prova", vocabulary, empty);
var with = CollectionConfiguration.Describe("prova", vocabulary, empty, RequestCatalog.LoadTestSite());
Assert.AreEqual(Enum.GetValues<RecipeKind>().Length, without.Blocked.Count, "Without pages nothing runs by the browser.");
CollectionAssert.AreEqual(new[] { RecipeKind.FollowingSweep }, with.Blocked.ToArray(), "Only the sweep needs the pages.");
CollectionAssert.Contains(with.Lines.ToList(), "Controllo del profilo: per richieste (ProvaProfiloQuery, profilo-altri).");
Assert.IsFalse(without.Lines.Any(l => l.Contains("per richieste", StringComparison.Ordinal)));
Assert.AreNotEqual(without.Fingerprint, with.Fingerprint, "A new route clears the suspensions too.");
Assert.AreEqual(without.Fingerprint, CollectionConfiguration.Describe("prova", vocabulary, empty, RequestCatalog.LoadInstagram()).Fingerprint, "No route: the fingerprint of before.");
Assert.AreEqual(0, CollectionConfiguration.Describe("prova", vocabulary, empty, RequestCatalog.LoadInstagram()).ByRequests.Count);
}
private static SiteMap InstagramMap() => SiteMap.LoadEmbedded("bersagli.instagram.json");
private static string Refuse(string json) =>
Assert.ThrowsExactly<InvalidDataException>(() => RequestCatalog.Parse(json, "richieste.prova.json")).Message;
private static string Alone(JsonObject operation) =>
new JsonObject { ["site"] = "prova", ["operations"] = new JsonArray(operation) }.ToJsonString();
private static JsonObject Rest(string name, string path) => new()
{
["name"] = name,
["kind"] = "rest",
["method"] = "GET",
["path"] = path,
["category"] = "post",
["configured"] = true,
["headers"] = new JsonObject { ["user-agent"] = "session:user_agent" },
["rootFields"] = new JsonArray("contenuto"),
["sample"] = "000005-post-serie",
};
}
@@ -0,0 +1,176 @@
using System.Collections.Concurrent;
using Febe.Core.Abstractions;
using Febe.Core.Collection;
using Febe.Core.Collection.Diagnostics;
using Febe.Core.Collection.Readers;
using Febe.Core.Collection.Recipes;
using Febe.Core.Collection.Requests;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Data;
using Febe.Tests.Support;
using RecordingBreaker = Febe.Tests.Browser.TestSupport.RecordingBreaker;
using VirtualClock = Febe.Tests.Browser.TestSupport.VirtualClock;
namespace Febe.Tests.Collection.Support;
/// <summary>
/// A page that must never be touched: the recipes by requests do not use it (issue #36, S3). Every call is counted
/// and fails.
/// </summary>
public sealed class NoPageDriver : IPageDriver
{
private int _touched;
/// <summary>Calls received (each one failed).</summary>
public int Touched => Volatile.Read(ref _touched);
public double WaitMultiplier => 1.0;
/// <summary>Counted, not failed: it comes before the run, where a failure would not be the run's.</summary>
public void BeginSession(double mood) => Interlocked.Increment(ref _touched);
public Task<PageLoad> OpenAsync(string path, CancellationToken ct) => Touch<PageLoad>();
public Task<string> CurrentPathAsync(CancellationToken ct) => Touch<string>();
public Task<bool> IsOnSiteAsync(CancellationToken ct) => Touch<bool>();
public Task<TargetCheck> FindAsync(string target, IReadOnlyDictionary<string, string>? parameters, CancellationToken ct) => Touch<TargetCheck>();
public Task<TargetCheck> ClickAsync(string target, IReadOnlyDictionary<string, string>? parameters, CancellationToken ct) => Touch<TargetCheck>();
public Task ScrollBurstAsync(CancellationToken ct) => Touch<bool>();
public Task WaitAfterLoadAsync(CancellationToken ct) => Touch<bool>();
public Task WaitAsync(TimeSpan duration, CancellationToken ct) => Touch<bool>();
public Task<bool> MaybeDistractionAsync(CancellationToken ct) => Touch<bool>();
public Task<bool?> HasSessionCookieAsync(CancellationToken ct) => Touch<bool?>();
public Task RestAsync(CancellationToken ct) => Touch<bool>();
private void Touch()
{
Interlocked.Increment(ref _touched);
throw new InvalidOperationException("La pagina è stata toccata da una ricetta per richieste.");
}
private Task<T> Touch<T>()
{
Touch();
return Task.FromResult<T>(default!);
}
}
/// <summary>
/// The recipes by requests without a browser (issue #36, S3): the runner of the test site's readers and map, with a
/// site client (<see cref="ScriptedRequester"/> by default) and a page that must never be touched.
/// </summary>
internal sealed class RequestBed : IAsyncDisposable
{
private readonly ConcurrentQueue<string> _warnings = new();
private RequestBed(TempFolder temp, FebeDatabase db, VirtualClock clock, NoPageDriver page, ISiteRequester requester, PermissiveGovernor governor, RecordingBreaker breaker, RecipeRunner runner, TestSession session)
{
Temp = temp;
Db = db;
Clock = clock;
Page = page;
Requester = requester;
Governor = governor;
Breaker = breaker;
Runner = runner;
Session = session;
}
public TempFolder Temp { get; }
public FebeDatabase Db { get; }
public VirtualClock Clock { get; }
public NoPageDriver Page { get; }
public ISiteRequester Requester { get; }
/// <summary>The scripted site client (null when the bed runs on another one).</summary>
public ScriptedRequester? Scripted => Requester as ScriptedRequester;
public PermissiveGovernor Governor { get; }
public RecordingBreaker Breaker { get; }
public RecipeRunner Runner { get; }
public TestSession Session { get; }
public IReadOnlyList<string> Warnings => [.. _warnings];
/// <param name="map">The map of the site; the test site's by default (every recipe could also go by the pages).</param>
/// <param name="catalog">The catalog; the test site's by default.</param>
/// <param name="requester">The site client; a <see cref="ScriptedRequester"/> on the cleaned samples by default.</param>
/// <param name="diagnostics">The recorder of the diagnostic report, when the test reads it.</param>
/// <param name="requests">False: no site client at all (every recipe by the page).</param>
public static async Task<RequestBed> CreateAsync(SiteMap? map = null, RequestCatalog? catalog = null, ISiteRequester? requester = null, CollectionDiagnostics? diagnostics = null, bool requests = true, VirtualClock? clock = null)
{
var temp = new TempFolder("ricette-richieste");
var db = await TestDatabase.OpenAsync(temp);
clock ??= new VirtualClock(new DateTimeOffset(2026, 10, 13, 16, 0, 0, TimeSpan.Zero));
catalog ??= RequestCatalog.LoadTestSite();
requester ??= new ScriptedRequester(catalog) { SessionCookie = "sessione_prova" };
var capture = new CaptureCollector(new ShapeReader(ReaderVocabulary.LoadTestSite()), clock) { Diagnostics = diagnostics };
var page = new NoPageDriver();
var breaker = new RecordingBreaker();
var governor = new PermissiveGovernor();
RequestBed? bed = null;
var runner = new RecipeRunner(new RecipeEnvironment
{
Driver = page,
Capture = capture,
Governor = governor,
Budget = governor,
Signals = new SignalDetector(SignalRules.LoadTestSite(), breaker, clock),
Storage = db,
SiteMap = map ?? SiteMap.LoadTestSite(),
Clock = clock,
Random = new SeededRandom(7),
Breaker = breaker,
Diagnostics = diagnostics,
Requests = requests
? new SiteRequestEnvironment(requester, catalog, new SiteAnswerSignals(SignalRules.LoadTestSite(), "sessione_prova"), Warn: m => bed?._warnings.Enqueue(m))
: null,
});
var session = new TestSession((await db.Sessions.StartAsync(clock.Now)).Id);
bed = new RequestBed(temp, db, clock, page, requester, governor, breaker, runner, session);
return bed;
}
/// <summary>The account of the samples: «numero» 5555 (marta.prova on the site, a fake name in the samples).</summary>
public Task<Account> AddSampleAccountAsync(Func<Account, Account>? change = null) => AddAccountAsync("5555", "ndkwq.shzgd", change);
public Task<Account> AddAccountAsync(string? instagramId, string username, Func<Account, Account>? change = null, bool isMine = false)
{
var account = Account.Create(username, StartingPoint.EverythingAndKeepUpdated, Clock.Now, TestZones.Rome, isMine: isMine) with
{
InstagramId = instagramId,
IsFollowed = !isMine,
};
return Db.Accounts.AddAsync(change is null ? account : change(account));
}
public Task<RecipeOutcome> RunAsync(RecipeKind kind, long? accountId = null, long? entryId = null, string? highlightId = null, int? maxPages = null, bool manual = false) =>
Runner.RunAsync(new RecipeRequest(kind, accountId, entryId, highlightId, maxPages, manual), Session, CancellationToken.None);
public async Task<IReadOnlyList<string>> EventCodesAsync() =>
[.. (await Db.Events.ListAsync(new Febe.Core.Storage.EventQuery())).Select(e => e.Code)];
public async ValueTask DisposeAsync()
{
(Requester as IDisposable)?.Dispose();
await Db.DisposeAsync();
Temp.Dispose();
}
}
@@ -29,6 +29,33 @@ public enum ScriptedReply
/// <summary>The sample, with the session cookie deleted by the site.</summary>
SessionCookieDeleted,
/// <summary>A 404 with the JSON of the test site («non-trovato»): the resource is not there (H19).</summary>
NotFoundJson,
/// <summary>A 500 with JSON: an error of the site.</summary>
ServerError500,
/// <summary>A 503 with JSON: the site is not available.</summary>
ServerError503,
/// <summary>No answer in time (<see cref="SiteUnreachableReason.Timeout"/>).</summary>
Timeout,
/// <summary>No connection (<see cref="SiteUnreachableReason.Unreachable"/>).</summary>
Unreachable,
/// <summary>An answer larger than allowed (<see cref="SiteUnreachableReason.TooLarge"/>).</summary>
TooLarge,
/// <summary>A body that cannot be decoded (<see cref="SiteUnreachableReason.Broken"/>).</summary>
Broken,
/// <summary>
/// A 200 with JSON that no reader recognizes (the body of the sample «forma-sconosciuta»), said to have the expected
/// fields: what a site that changed its format inside the same fields would send.
/// </summary>
UnknownShape,
}
/// <summary>
@@ -140,6 +167,23 @@ public sealed class ScriptedRequester : ISiteRequester
return new SiteAnswer(operation, 302, "text/html", ReadOnlyMemory<byte>.Empty, redirectTo: ChallengeLocation);
case ScriptedReply.HtmlInsteadOfJson:
return new SiteAnswer(operation, 200, "text/html; charset=utf-8", Encoding.UTF8.GetBytes("<!DOCTYPE html><html><head><title>Pagina</title></head><body></body></html>"));
case ScriptedReply.NotFoundJson:
return new SiteAnswer(operation, 404, "application/json", Encoding.UTF8.GetBytes("{\"errore\":\"non-trovato\"}"), rootFieldsPresent: false);
case ScriptedReply.ServerError500 or ScriptedReply.ServerError503:
return new SiteAnswer(operation, reply == ScriptedReply.ServerError500 ? 500 : 503, "application/json", Encoding.UTF8.GetBytes("{\"errore\":\"interno\"}"), rootFieldsPresent: false);
case ScriptedReply.Timeout or ScriptedReply.Unreachable or ScriptedReply.TooLarge or ScriptedReply.Broken:
var reason = reply switch
{
ScriptedReply.Timeout => SiteUnreachableReason.Timeout,
ScriptedReply.TooLarge => SiteUnreachableReason.TooLarge,
ScriptedReply.Broken => SiteUnreachableReason.Broken,
_ => SiteUnreachableReason.Unreachable,
};
throw new SiteUnreachableException($"«{operation.Name}» ({operation.PathShape}): nessuna risposta (prova).", reason);
case ScriptedReply.UnknownShape:
var unknown = Directory.EnumerateFiles(_samples, "*-forma-sconosciuta.json").Single();
var corpo = JsonNode.Parse(File.ReadAllText(unknown))!["corpo"]!;
return new SiteAnswer(operation, 200, "application/json", Encoding.UTF8.GetBytes(corpo.ToJsonString()), rootFieldsPresent: true);
}
var (mime, body) = Sample(operation);
@@ -41,6 +41,19 @@ public sealed class EngineSettingsTests
Assert.AreEqual(GesturePace.Slow, effective.Pace);
}
[TestMethod]
public void AStoryViewIsARequestOrAStoryShownAndItsBudgetsStayAsTheyWere()
{
// Issue #36, S3: by requests one StoryView brings every story of an account. The budgets do not change in S3,
// so that Instagram (still by the pages) and a saved «Su misura» behave as before; halving them is a question
// for Alberto when Instagram goes by requests (S4).
Assert.AreEqual(new Budget(50, 300), CautionProfile.Prudent.Budgets[ActionKind.StoryView]);
Assert.AreEqual(new Budget(80, 500), CautionProfile.Balanced.Budgets[ActionKind.StoryView]);
Assert.AreEqual(new Budget(120, 800), CautionProfile.Fast.Budgets[ActionKind.StoryView]);
Assert.AreEqual(new Budget(240, 1600), CautionProfile.Limits.MaxBudget(ActionKind.StoryView), "«Su misura» stays within twice «Rapido».");
Assert.IsTrue(CautionProfile.Prudent.Budgets[ActionKind.StoryView].PerHour >= new Febe.Core.Collection.Recipes.RecipeOptions().MinStoryBudget, "The viewer still has room for its minimum of stories.");
}
[TestMethod]
public void TheLimitsOfTheInterfaceAreEnforced()
{
@@ -37,6 +37,7 @@ public sealed class EngineSimulationTests
Assert.IsTrue(report.FollowedPosts.Count > 0 && report.Stories.Count > 0);
var text = report.ToText();
StringAssert.Contains(text, "Raccolta: per pagine");
StringAssert.Contains(text, "Sessioni");
StringAssert.Contains(text, "superamenti dei tetti: 0");
StringAssert.Contains(text, "Storico di 2.000 post");
@@ -159,6 +160,29 @@ public sealed class EngineSimulationTests
StringAssert.Contains(problem, "Durata non valida");
Assert.IsFalse(Febe.Server.SimulateCommand.TryParse(["--simula", "7g", "--profilo", "spericolato"], out _, out _, out problem));
StringAssert.Contains(problem, "Profilo sconosciuto");
Assert.AreEqual(SimulatedCollection.Pages, options.Collection, "By the pages unless asked.");
Assert.IsTrue(Febe.Server.SimulateCommand.TryParse(["--simula", "7g", "--raccolta", "richieste"], out options, out _, out _));
Assert.AreEqual(SimulatedCollection.Requests, options.Collection);
Assert.IsTrue(Febe.Server.SimulateCommand.TryParse(["--simula", "7g", "--raccolta", "PAGINE"], out options, out _, out _));
Assert.AreEqual(SimulatedCollection.Pages, options.Collection);
Assert.IsFalse(Febe.Server.SimulateCommand.TryParse(["--simula", "7g", "--raccolta", "browser"], out _, out _, out problem));
StringAssert.Contains(problem, "Raccolta sconosciuta");
Assert.IsFalse(Febe.Server.SimulateCommand.TryParse(["--simula", "7g", "--raccolta"], out _, out _, out problem));
StringAssert.Contains(problem, "pagine o richieste");
}
[TestMethod]
[DataRow(CautionProfileKind.Prudent)]
[DataRow(CautionProfileKind.Fast)]
public async Task ByRequestsEveryProfileRunsAWeekWithoutExceedingAnyBudget(CautionProfileKind profile)
{
var report = await SimulateAsync(new SimulationOptions { Days = 7, Profile = profile, Seed = 3, Collection = SimulatedCollection.Requests });
Assert.AreEqual(0, report.Overruns, string.Join('\n', report.OverrunDetails));
Assert.AreEqual(0, report.OverrunsOfFullBudgets);
Assert.AreEqual(SimulatedCollection.Requests, report.Collection);
Assert.IsTrue(report.Stories.Count > 0);
StringAssert.Contains(report.ToText(), "Raccolta: per richieste");
}
[TestMethod]
@@ -0,0 +1,303 @@
{
"descrittore": {
"indirizzo": "https://sito.esempio/v04262087535s0f2",
"host": "sito",
"stato": 200,
"tipo": "application/json",
"risorsa": "Fetch",
"nome": "jjrv"
},
"corpo": {
"profilo": {
"numero": "6104",
"nome": "lmxm.bgwrl",
"nome_visibile": "Cjtw dm vcgnm",
"riservato": false,
"seguito": true,
"pubblicazioni": 40,
"ritratto": [
{
"indirizzo": "https://cdn.esempio/p8855g33lq2s9v52.jpg",
"larghezza": 160,
"altezza": 160
},
{
"indirizzo": "https://cdn.esempio/nlq76dk085829116.jpg",
"larghezza": 320,
"altezza": 320
}
],
"ultima_storia": "2026-11-17T06:20:50Z"
},
"contenuti": [
{
"numero": "3307625433",
"sigla": "NwpTxtz",
"pubblicato": "2026-11-10T06:13:50Z",
"testo": "Bdx djbkzfsr hpm ktdf p ntrhtlsz (jlfwr 011)",
"fissato": false,
"autore": {
"numero": "6104",
"nome": "lmxm.bgwrl"
},
"filmati": [
{
"indirizzo": "https://cdn.esempio/1wd611jk1xg90749.mp4",
"larghezza": 360,
"altezza": 640,
"audio": true
},
{
"indirizzo": "https://cdn.esempio/d8079rp6gf80595g.mp4",
"larghezza": 720,
"altezza": 1280,
"audio": true
},
{
"indirizzo": "https://cdn.esempio/84631st7z73l008q.mp4",
"larghezza": 1080,
"altezza": 1920,
"audio": false
}
],
"foto": [
{
"indirizzo": "https://cdn.esempio/4f795888602n3h07.jpg",
"larghezza": 360,
"altezza": 640
},
{
"indirizzo": "https://cdn.esempio/3z5fh589r44m47zz.jpg",
"larghezza": 720,
"altezza": 1280
}
],
"durata": 2
},
{
"numero": "7636047358",
"sigla": "ggjzj36",
"pubblicato": "2026-10-27T21:53:50Z",
"testo": "Dkv xgbrknvm xdd ftdjs j ljmmhnwv (cvcpx 007)",
"fissato": false,
"autore": {
"numero": "6104",
"nome": "lmxm.bgwrl"
},
"filmati": [
{
"indirizzo": "https://cdn.esempio/224tf439x5s4c59k.mp4",
"larghezza": 360,
"altezza": 640,
"audio": true
},
{
"indirizzo": "https://cdn.esempio/69t401224hm89m1l.mp4",
"larghezza": 720,
"altezza": 1280,
"audio": true
},
{
"indirizzo": "https://cdn.esempio/44293bx83x1dw7f6.mp4",
"larghezza": 1080,
"altezza": 1920,
"audio": false
}
],
"foto": [
{
"indirizzo": "https://cdn.esempio/1mn2311sdc76p87h.jpg",
"larghezza": 360,
"altezza": 640
},
{
"indirizzo": "https://cdn.esempio/2f867265k4p5l0v5.jpg",
"larghezza": 720,
"altezza": 1280
}
],
"durata": 2
},
{
"numero": "9348053577",
"sigla": "Gwbqppb",
"pubblicato": "2026-10-14T10:49:50Z",
"testo": "Ztd nkjswztq xls zdhwt t gmbfq (sxsqw 417)",
"fissato": false,
"autore": {
"numero": "6104",
"nome": "lmxm.bgwrl"
},
"filmati": [
{
"indirizzo": "https://cdn.esempio/35704l4g0559r58q.mp4",
"larghezza": 360,
"altezza": 640,
"audio": true
},
{
"indirizzo": "https://cdn.esempio/1b587kf45j81gk4f.mp4",
"larghezza": 720,
"altezza": 1280,
"audio": true
},
{
"indirizzo": "https://cdn.esempio/g79397sdpfn50x0r.mp4",
"larghezza": 1080,
"altezza": 1920,
"audio": false
}
],
"foto": [
{
"indirizzo": "https://cdn.esempio/x4n2dx8673g342x1.jpg",
"larghezza": 360,
"altezza": 640
},
{
"indirizzo": "https://cdn.esempio/8985j1wr34x84849.jpg",
"larghezza": 720,
"altezza": 1280
}
],
"durata": 2
},
{
"numero": "4035845102",
"sigla": "M5H2bQT",
"pubblicato": "2026-10-01T00:35:50Z",
"testo": "Jwn kdfkwwfm lmr zpqbfcvm h bjktt (nlqnl 255)",
"fissato": false,
"autore": {
"numero": "6104",
"nome": "lmxm.bgwrl"
},
"filmati": [
{
"indirizzo": "https://cdn.esempio/8zh874cdcx04tff8.mp4",
"larghezza": 360,
"altezza": 640,
"audio": true
},
{
"indirizzo": "https://cdn.esempio/bfrk6607ldvk32n2.mp4",
"larghezza": 720,
"altezza": 1280,
"audio": true
},
{
"indirizzo": "https://cdn.esempio/55k9nq42k31jr893.mp4",
"larghezza": 1080,
"altezza": 1920,
"audio": false
}
],
"foto": [
{
"indirizzo": "https://cdn.esempio/16w43gtnlzm0q58x.jpg",
"larghezza": 360,
"altezza": 640
},
{
"indirizzo": "https://cdn.esempio/14vl6121g262v1nd.jpg",
"larghezza": 720,
"altezza": 1280
}
],
"durata": 2
},
{
"numero": "9155303648",
"sigla": "GzsddRB",
"pubblicato": "2026-09-17T15:37:50Z",
"testo": "Wjc pdhmvhnq tck zpnck l mbrnvzl (tqzsl 788)",
"fissato": false,
"autore": {
"numero": "6104",
"nome": "lmxm.bgwrl"
},
"filmati": [
{
"indirizzo": "https://cdn.esempio/6802c23jp6p19484.mp4",
"larghezza": 360,
"altezza": 640,
"audio": true
},
{
"indirizzo": "https://cdn.esempio/q0838jr29lq3lts4.mp4",
"larghezza": 720,
"altezza": 1280,
"audio": true
},
{
"indirizzo": "https://cdn.esempio/7n25023gxnh73rr6.mp4",
"larghezza": 1080,
"altezza": 1920,
"audio": false
}
],
"foto": [
{
"indirizzo": "https://cdn.esempio/838x1873s39ms1b6.jpg",
"larghezza": 360,
"altezza": 640
},
{
"indirizzo": "https://cdn.esempio/9002037p2f62b9f2.jpg",
"larghezza": 720,
"altezza": 1280
}
],
"durata": 2
},
{
"numero": "2197000011",
"sigla": "rNXQsSw",
"pubblicato": "2026-09-04T06:04:50Z",
"testo": "Bdr nkwchshs fxz mbcksz m vjcrnjtvj (zkmxc 371)",
"fissato": false,
"autore": {
"numero": "6104",
"nome": "lmxm.bgwrl"
},
"filmati": [
{
"indirizzo": "https://cdn.esempio/p3sg00r501w85896.mp4",
"larghezza": 360,
"altezza": 640,
"audio": true
},
{
"indirizzo": "https://cdn.esempio/87dn2d97x928m441.mp4",
"larghezza": 720,
"altezza": 1280,
"audio": true
},
{
"indirizzo": "https://cdn.esempio/9w92bz978k9r919t.mp4",
"larghezza": 1080,
"altezza": 1920,
"audio": false
}
],
"foto": [
{
"indirizzo": "https://cdn.esempio/1b8xkqt7l4jq0s70.jpg",
"larghezza": 360,
"altezza": 640
},
{
"indirizzo": "https://cdn.esempio/2r5c33rw538h5460.jpg",
"larghezza": 720,
"altezza": 1280
}
],
"durata": 2
}
],
"pagina": {
"altro": false,
"dopo": null
}
}
}
@@ -26,3 +26,7 @@ controllano forme, dimensioni, date e conteggi, non i valori.
| `000009-taggati` | scheda «Taggati» di un profilo |
| `000010-pagina-vuota` | pagina di dati vuota |
| `000011-forma-sconosciuta` | risposta di forma sconosciuta |
| `000012-reel` | scheda «Reel» di un profilo (tappa S3 di #36), scritto dopo gli altri con lo stesso percorso: i suoi valori finti non sono quelli degli altri campioni |
Del Reel non c'è la pagina successiva: nel sito di prova i reel di ogni account (al più 6) stanno nella prima pagina,
che ne porta 12, e `altro` è sempre falso. Per questo `richieste.prova.json` non ha un'operazione `reel-altri`.