Instagram: Febe legge le risposte vere (campioni dal HAR del 21/10)
verifica / controlli (push) Successful in 2m10s
verifica / prove (push) Successful in 26m16s
verifica / installatore (push) Successful in 5m39s
verifica / immagine (push) Successful in 28m39s

Febe non estraeva nulla da Instagram per due motivi. Instagram manda i
dati di storie e raccolte (GraphQL) come text/javascript, e la cattura
leggeva solo le risposte dichiarate JSON: le scartava tutte. E i file di
Instagram (lettori, bersagli) erano scheletri, quindi le ricette si
rifiutavano di girare.

Alberto ha mandato un HAR del suo browser e una guida. La guida descrive
richieste costruite a mano, vietate dalle regole 2-4, e un formato che
nel HAR non compare: non si usa. Dal HAR si è letta solo la forma; le
risposte utili sono diventate campioni grezzi fuori dal repository,
ripuliti e verificati con febe-sonda (tests/Febe.Tests/campioni/instagram).

Che cosa cambia:
- la cattura legge le risposte text/javascript chieste dalla pagina (mai
  gli script) e ogni blocco JSON incorporato nel documento della pagina,
  e avvisa quando un corpo atteso non arriverà;
- le risposte che non parlano di contenuti (promozioni, «storia vista»)
  si ignorano invece di valere come formato non riconosciuto;
- lettori.instagram.json è confermato, con sole chiavi presenti nei
  campioni; identificativi delle raccolte nella forma dell'indirizzo;
- bersagli.instagram.json ha le pagine viste nel traffico vero; i
  bersagli restano vuoti (H11): storie, raccolte, Taggati e Reel
  aspettano lo script tools/bersagli/raccogli-bersagli.js;
- le ricette del profilo reggono dati in risposte diverse e prendono la
  paginazione solo dalla risposta che porta i loro post; l'elenco dei
  seguiti scarta i profili suggeriti; «Tu» si riconosce anche dal solo
  identificativo dell'account collegato;
- il visualizzatore delle raccolte conta i contenuti (l'indirizzo non
  cambia), chiede il permesso prima di ogni contenuto e si chiude sempre;
- una ricetta che la configurazione non lascia girare è «Da configurare»:
  non è un guasto, non si sospende, non si pianifica; le sospensioni
  dovute ai file vecchi si azzerano una volta al cambio dei file;
- la barra laterale dice «Collegato» dal cookie di sessione; i «Post
  singolo» per gli indirizzi scaduti non vengono più annullati;
- febe-sonda da-har; la ripulitura tiene latest_reel_media e mette un
  riempitivo neutro sotto le chiavi simili a segreti (gitleaks).

Prove su Windows: 783 superate, 76 saltate (Chromium e Xvfb, nella CI).
Nulla è stato provato contro Instagram. Dettagli e decisioni in
docs/stato.md e docs/decisioni.md (righe del 25 ottobre).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-10-25 14:22:16 +01:00
1 parent b3a7c31e5a
commit 31bbbf8bb7
69 files changed
+9184 -453

No files matched your search

@@ -0,0 +1,151 @@
using Febe.Core.Collection;
using Febe.Core.Collection.Readers;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Storage;
using Febe.Tests.Engine.Support;
using Febe.Tests.Support;
namespace Febe.Tests.Engine;
/// <summary>
/// The collection configuration in use (reader vocabulary and target map of the site, as loaded): what the log says of
/// it, the copies in the Data folder that hide newer embedded files, and the suspensions counted against other files,
/// cleared once when it changes.
/// </summary>
[TestClass]
public sealed class CollectionConfigurationTests
{
private static readonly DateTimeOffset Morning = EngineTestBed.Local(2026, 10, 14, 6, 0);
[TestMethod]
public async Task AChangedCollectionConfigurationLiftsTheSuspensionsOfTheOldFilesOnce()
{
await using var bed = await EngineTestBed.CreateAsync(Morning);
await bed.AddAccountAsync("strano.demo", followed: false, Frequency.High);
// What the first Instagram files left in Alberto's database: suspended recipes and failures counted.
var since = Morning.AddDays(-3).ToUnixTimeMilliseconds();
await bed.Db.Settings.SetAsync(EngineSettingKeys.SuspendedRecipes, $"AccountStories={since};ProfileCheck={since}");
await bed.Db.Settings.SetAsync(EngineSettingKeys.RecipeFailures, "AccountStories=3;Backfill=2;ProfileCheck=3");
var runner = new ScriptedRunner(bed.Governor, bed.Clock);
var changed = false;
var host = await bed.StartAsync(runner, async h => changed = await h.ApplyCollectionConfigurationAsync("impronta-1"));
Assert.IsTrue(changed, "The first start that knows the configuration counts as a change.");
Assert.IsEmpty(host.SuspendedRecipes);
Assert.IsNull(await bed.Db.Settings.GetAsync(EngineSettingKeys.SuspendedRecipes));
Assert.IsNull(await bed.Db.Settings.GetAsync(EngineSettingKeys.RecipeFailures));
Assert.AreEqual("impronta-1", await bed.Db.Settings.GetAsync(EngineSettingKeys.CollectionConfiguration));
var line = (await bed.Db.Events.ListAsync(new EventQuery())).Single(e => e.Code == EngineEventCodes.CollectionConfigurationChanged);
Assert.AreEqual("La configurazione della raccolta è cambiata: le ricette sospese ripartono («Le storie», «Il controllo del profilo»).", line.Message);
Assert.AreEqual(EventSeverity.Info, line.Severity);
await bed.RunUntilAsync(Morning.AddDays(1));
Assert.IsTrue(runner.Runs.Any(r => r.Request.Kind == RecipeKind.ProfileCheck && r.Status == RecipeStatus.Completed), "The recipe runs again.");
Assert.IsFalse(await host.ApplyCollectionConfigurationAsync("impronta-1"), "Same files: nothing to do.");
// A restart with the same files changes nothing; new files with nothing to clear say nothing.
await bed.ReopenAsync(8);
var again = true;
var reopened = await bed.StartAsync(new ScriptedRunner(bed.Governor, bed.Clock), async h => again = await h.ApplyCollectionConfigurationAsync("impronta-1"));
Assert.IsFalse(again);
Assert.IsTrue(await reopened.ApplyCollectionConfigurationAsync("impronta-2"));
Assert.AreEqual("impronta-2", await bed.Db.Settings.GetAsync(EngineSettingKeys.CollectionConfiguration));
Assert.AreEqual(1, (await bed.Db.Events.ListAsync(new EventQuery())).Count(e => e.Code == EngineEventCodes.CollectionConfigurationChanged));
}
[TestMethod]
public async Task FailuresAloneAreClearedWithTheirOwnLine()
{
await using var bed = await EngineTestBed.CreateAsync(Morning);
await bed.Db.Settings.SetAsync(EngineSettingKeys.RecipeFailures, "ProfileCheck=2");
var host = new EngineHost(bed.Services, new ScriptedRunner(bed.Governor, bed.Clock));
await using (host)
{
Assert.IsTrue(await host.ApplyCollectionConfigurationAsync("impronta"));
}
Assert.IsNull(await bed.Db.Settings.GetAsync(EngineSettingKeys.RecipeFailures));
var line = (await bed.Db.Events.ListAsync(new EventQuery())).Single(e => e.Code == EngineEventCodes.CollectionConfigurationChanged);
Assert.AreEqual("La configurazione della raccolta è cambiata: i problemi delle ricette contati finora non valgono più.", line.Message);
}
[TestMethod]
public void TheEmbeddedFilesAreDescribedWithoutTheirContentAndFingerprinted()
{
var configuration = CollectionConfiguration.Describe("prova", ReaderVocabulary.LoadTestSite(), SiteMap.LoadTestSite());
Assert.IsFalse(configuration.VocabularyFile.IsOverride);
Assert.IsFalse(configuration.MapFile.IsOverride);
Assert.IsEmpty(configuration.Blocked);
Assert.IsEmpty(configuration.Warnings);
CollectionAssert.AreEqual(
new[]
{
"Vocabolario dei lettori per «prova»: il file incorporato in Febe (lettori.prova.json), confermato.",
"Mappa dei bersagli per «prova»: il file incorporato in Febe (bersagli.prova.json), tutte le voci compilate.",
"Con questa configurazione tutte le ricette possono girare.",
},
configuration.Lines.ToArray());
Assert.MatchesRegex("^[0-9a-f]{64}$", configuration.Fingerprint);
Assert.AreEqual(configuration.Fingerprint, CollectionConfiguration.Describe("prova", ReaderVocabulary.LoadTestSite(), SiteMap.LoadTestSite()).Fingerprint);
}
[TestMethod]
public void ACopyInTheDataFolderIsNamedAndOneThatHidesABetterEmbeddedFileIsAWarning()
{
using var folder = new TempFolder("configurazione");
var vocabularyText = SiteMap.ReadEmbeddedText("lettori.prova.json");
var mapText = SiteMap.ReadEmbeddedText("bersagli.prova.json");
var embedded = CollectionConfiguration.Describe("prova", ReaderVocabulary.LoadTestSite(), SiteMap.LoadTestSite());
// The same map with other line endings is the same configuration.
var mapPath = folder.Combine("bersagli.prova.json");
File.WriteAllText(mapPath, mapText.Contains("\r\n", StringComparison.Ordinal) ? mapText.Replace("\r\n", "\n", StringComparison.Ordinal) : mapText.Replace("\n", "\r\n", StringComparison.Ordinal));
var sameMap = Loaded(folder, "prova");
Assert.IsTrue(sameMap.MapFile.IsOverride);
Assert.AreEqual(mapPath, sameMap.MapFile.OverridePath);
Assert.AreEqual(embedded.Fingerprint, sameMap.Fingerprint);
Assert.IsEmpty(sameMap.Warnings);
StringAssert.Contains(sameMap.Lines[1], $"la copia nella cartella dei dati ({mapPath})");
// A stale vocabulary, still a hypothesis, hides the confirmed embedded one: every recipe would be refused.
var vocabularyPath = folder.Combine("lettori.prova.json");
File.WriteAllText(vocabularyPath, vocabularyText.Replace("\"confermato\"", "\"ipotesi\"", StringComparison.Ordinal));
var stale = Loaded(folder, "prova");
Assert.AreNotEqual(embedded.Fingerprint, stale.Fingerprint);
CollectionAssert.AreEqual(Enum.GetValues<RecipeKind>(), stale.Blocked.ToArray());
Assert.HasCount(1, stale.Warnings);
StringAssert.Contains(stale.Warnings[0], vocabularyPath);
StringAssert.Contains(stale.Warnings[0], "è ancora un'ipotesi, mentre quello incorporato in Febe è confermato");
StringAssert.EndsWith(stale.Lines[0], ", ipotesi.");
StringAssert.StartsWith(stale.Lines[2], "Con questa configurazione non possono girare 9 ricette su 9: Giro dei seguiti, ");
// A map that lacks what the embedded one has leaves recipes still that could run.
File.Delete(vocabularyPath);
File.WriteAllText(mapPath, """{ "site": "prova", "pages": { "home": "/" } }""");
var poor = Loaded(folder, "prova");
CollectionAssert.Contains(poor.Blocked.ToArray(), RecipeKind.ProfileCheck);
CollectionAssert.DoesNotContain(poor.Blocked.ToArray(), RecipeKind.FollowingSweep);
Assert.HasCount(1, poor.Warnings);
StringAssert.Contains(poor.Warnings[0], $"La mappa dei bersagli in {mapPath} lascia ferme ricette che con quella incorporata in Febe potrebbero girare (");
StringAssert.Contains(poor.Warnings[0], "Controllo del profilo");
// Never what is in the files.
var note = ReaderVocabulary.LoadTestSite().Note!;
foreach (var text in stale.Lines.Concat(stale.Warnings).Concat(poor.Lines).Concat(poor.Warnings))
{
Assert.IsFalse(text.Contains(note, StringComparison.Ordinal), text);
Assert.IsFalse(text.Contains("/profilo/", StringComparison.Ordinal), text);
}
}
/// <summary>The files loaded as the collection pipeline loads them: the Data-folder copy when it exists.</summary>
private static CollectionConfiguration Loaded(TempFolder folder, string site)
{
var vocabulary = ReaderVocabulary.LoadOrEmbedded(folder.Combine($"lettori.{site}.json"), $"lettori.{site}.json");
var map = SiteMap.LoadOrEmbedded(folder.Combine($"bersagli.{site}.json"), $"bersagli.{site}.json");
return CollectionConfiguration.Describe(site, vocabulary, map);
}
}
@@ -607,4 +607,28 @@ public sealed class EngineHostTests
Assert.HasCount(foodLooks, Looks("17900000002"));
Assert.IsTrue(Looks("17900000001").Count > travelLooks);
}
[TestMethod]
public async Task ASinglePostQueuedByTheCollectionRunsInsteadOfBeingCancelledByTheQueue()
{
await using var bed = await EngineTestBed.CreateAsync(Morning);
var account = await bed.AddAccountAsync("uno.demo", followed: true);
var paused = await bed.AddAccountAsync("due.demo", followed: true, state: AccountState.Paused);
// As CollectionWriter.QueueSinglePostAsync queues it for an address that expired (spec §6.5 point 5).
EngineTask SinglePost(Account a, string entryId) =>
new() { Kind = EngineTaskKind.SinglePost, AccountId = a.Id, Payload = entryId, DueAt = Morning, CreatedAt = Morning };
var refresh = await bed.Db.Tasks.EnqueueAsync(SinglePost(account, "41"));
var held = await bed.Db.Tasks.EnqueueAsync(SinglePost(paused, "42"));
var runner = new ScriptedRunner(bed.Governor, bed.Clock);
bed.Start(runner);
await bed.RunUntilAsync(Morning.AddDays(1));
var runs = runner.Runs.Where(r => r.Request.Kind == RecipeKind.SinglePost).ToList();
Assert.HasCount(1, runs, "The expired address is refreshed once, on the account that may be contacted.");
Assert.AreEqual(41L, runs[0].Request.EntryId);
Assert.AreEqual(account.Id, runs[0].Request.AccountId);
Assert.AreEqual(EngineTaskState.Done, (await bed.Db.Tasks.GetAsync(refresh.Id))!.State);
Assert.AreEqual(EngineTaskState.Cancelled, (await bed.Db.Tasks.GetAsync(held.Id))!.State, "«In pausa»: not contacted.");
}
}
@@ -0,0 +1,253 @@
using Febe.Core.Abstractions;
using Febe.Core.Collection;
using Febe.Core.Collection.Readers;
using Febe.Core.Collection.Recipes;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Storage;
using Febe.Data;
using Febe.Tests.Browser.TestSupport;
using Febe.Tests.Collection.Support;
using Febe.Tests.Engine.Support;
using Febe.Tests.Support;
namespace Febe.Tests.Engine;
/// <summary>
/// A recipe the files of the site do not let run (target map or reader vocabulary incomplete) is a state of the
/// configuration, not a failure (spec §6.4): never counted towards suspension, not planned, said once per process.
/// </summary>
[TestClass]
public sealed class NotConfiguredRecipeTests
{
private const string ProfileReason = "«Controllo del profilo» non può girare su instagram: la mappa dei bersagli non è ancora compilata (mancano pagina «profile»).";
private const string SweepReason = "«Giro dei seguiti» non può girare su instagram: la mappa dei bersagli non è ancora compilata (mancano pagina «home»).";
private const string ListReason = "«Elenco dei seguiti» non può girare su instagram: la mappa dei bersagli non è ancora compilata (mancano pagina «following»).";
private const string StoriesReason = "«Storie di un account» non può girare su instagram: la mappa dei bersagli non è ancora compilata (mancano bersaglio «profile-story-ring»).";
private static readonly DateTimeOffset Morning = EngineTestBed.Local(2026, 10, 14, 6, 0);
[TestMethod]
public async Task ARecipeTheConfigurationDoesNotLetRunIsNotPlannedNotCountedAndSaidOnce()
{
await using var bed = await EngineTestBed.CreateAsync(Morning);
var account = await bed.AddAccountAsync("lontano.demo", followed: false, Frequency.High);
var runner = new ScriptedRunner(bed.Governor, bed.Clock) { NotConfigured = k => k == RecipeKind.ProfileCheck ? ProfileReason : null };
var host = bed.Start(runner);
await bed.RunUntilAsync(Morning.AddDays(2));
Assert.IsFalse(runner.Runs.Any(r => r.Request.Kind == RecipeKind.ProfileCheck), "Never run: it would only be refused.");
Assert.IsFalse((await bed.Db.Tasks.ListPendingAsync(1000)).Any(t => t.Kind == EngineTaskKind.ProfileCheck), "Nor planned.");
Assert.IsEmpty(host.SuspendedRecipes);
Assert.IsNull(await bed.Db.Settings.GetAsync(EngineSettingKeys.RecipeFailures), "No failure counted.");
var events = await bed.Db.Events.ListAsync(new EventQuery());
var said = events.Where(e => e.Code == EngineEventCodes.RecipeNotConfigured).ToList();
Assert.HasCount(1, said, "Once per recipe and process, not at every session.");
Assert.AreEqual(ProfileReason + SessionComposer.NotConfiguredTail, said[0].Message);
Assert.AreEqual(EventSeverity.Warning, said[0].Severity);
Assert.IsFalse(events.Any(e => e.Code is EngineEventCodes.RecipeSuspended or EngineEventCodes.TargetNotFound or EngineEventCodes.FormatUnrecognized));
Assert.IsGreaterThan(1, events.Count(e => e.Code == EngineEventCodes.SessionEnded), "Several sessions went by.");
// «Controlla ora» says why at once instead of queueing a check that cannot run.
var check = await host.CheckNowAsync(account.Id);
Assert.AreEqual(CheckNowStatus.Refused, check.Status);
Assert.AreEqual(ProfileReason + " Il controllo non parte.", check.Message);
}
[TestMethod]
public async Task WithoutTheSweepFollowedStoriesAreCheckedOneByOneAndACommandThatCannotRunIsDropped()
{
await using var bed = await EngineTestBed.CreateAsync(Morning);
await bed.AddAccountAsync("vicina.demo", followed: true);
var runner = new ScriptedRunner(bed.Governor, bed.Clock)
{
NotConfigured = k => k switch
{
RecipeKind.FollowingSweep => SweepReason,
RecipeKind.FollowingList => ListReason,
_ => null,
},
};
var host = bed.Start(runner);
await bed.RunUntilAsync(Morning.AddDays(1));
Assert.IsFalse(runner.Runs.Any(r => r.Request.Kind == RecipeKind.FollowingSweep));
Assert.IsFalse((await bed.Db.Tasks.ListPendingAsync(1000)).Any(t => t.Kind == EngineTaskKind.FollowingSweep), "The sweep is not shown in the queue.");
Assert.IsTrue(runner.Runs.Any(r => r.Request.Kind == RecipeKind.AccountStories), "No sweep covers the stories bar: they are checked explicitly.");
await host.RequestFollowingListAsync();
await bed.RunForAsync(TimeSpan.FromHours(8));
Assert.IsFalse(runner.Runs.Any(r => r.Request.Kind == RecipeKind.FollowingList));
Assert.IsFalse((await bed.Db.Tasks.ListPendingAsync(1000)).Any(t => t.Kind == EngineTaskKind.FollowingList), "Alberto's command is dropped, not left waiting for ever.");
var said = (await bed.Db.Events.ListAsync(new EventQuery())).Where(e => e.Code == EngineEventCodes.RecipeNotConfigured).Select(e => e.Message).ToList();
Assert.AreEqual(1, said.Count(m => m.StartsWith(SweepReason, StringComparison.Ordinal)));
Assert.AreEqual(1, said.Count(m => m.StartsWith(ListReason, StringComparison.Ordinal)));
Assert.AreEqual(1, said.Count(m => m == $"La tua richiesta (l'elenco dei profili che segui) è annullata: {ListReason}"));
Assert.IsEmpty(host.SuspendedRecipes);
}
[TestMethod]
public async Task WhileTheStoriesCannotRunAProfileNotFollowedIsVisitedOnlyForItsPosts()
{
await using var bed = await EngineTestBed.CreateAsync(Morning);
var account = await bed.AddAccountAsync("lontana.demo", followed: false, Frequency.Low);
var runner = new ScriptedRunner(bed.Governor, bed.Clock) { NotConfigured = k => k == RecipeKind.AccountStories ? StoriesReason : null };
bed.Start(runner);
await bed.RunUntilAsync(Morning.AddDays(4));
// «Bassa»: the profile every 12 hours or so, never sooner than 0.6 × 12 h. A visit that also served the stories
// would come at the story interval instead (a third of the window, about 5 hours), and collect nothing more.
var visits = runner.Runs.Where(r => r.Request.Kind == RecipeKind.ProfileCheck && r.Status == RecipeStatus.Completed).Select(r => r.At).ToList();
Assert.IsGreaterThan(2, visits.Count, "The profile is still checked for its posts.");
for (var i = 1; i < visits.Count; i++)
{
Assert.IsTrue(visits[i] - visits[i - 1] >= TimeSpan.FromHours(7), $"Visit after {visits[i] - visits[i - 1]}.");
}
Assert.IsFalse(runner.Runs.Any(r => r.Request.Kind == RecipeKind.AccountStories));
Assert.IsNull((await bed.Db.Accounts.GetAsync(account.Id))!.NextStoriesCheckAt, "Story times stay as they are, for when the stories can run.");
var said = (await bed.Db.Events.ListAsync(new EventQuery())).Where(e => e.Code == EngineEventCodes.RecipeNotConfigured).ToList();
Assert.HasCount(1, said);
Assert.AreEqual(StoriesReason + SessionComposer.NotConfiguredTail, said[0].Message);
}
[TestMethod]
public async Task TheStoriesBarQueuesNoStoryCheckTheConfigurationDoesNotLetRun()
{
await using var bed = await EngineTestBed.CreateAsync(Morning);
var account = await bed.AddAccountAsync("vicina.demo", followed: true);
var runner = new ScriptedRunner(bed.Governor, bed.Clock)
{
FlaggedStories = [account.Id],
NotConfigured = k => k == RecipeKind.AccountStories ? StoriesReason : null,
};
bed.Start(runner);
await bed.RunUntilAsync(Morning.AddDays(1));
Assert.IsGreaterThan(1, runner.Runs.Count(r => r.Request.Kind == RecipeKind.FollowingSweep && r.Status == RecipeStatus.Completed), "Several sweeps flagged the account.");
Assert.IsFalse(runner.Runs.Any(r => r.Request.Kind == RecipeKind.AccountStories));
Assert.AreEqual(0L, await TasksAsync(bed, EngineTaskKind.AccountStories), "No story check queued: none waits in the Coda, none is cancelled at the next session.");
var said = (await bed.Db.Events.ListAsync(new EventQuery())).Where(e => e.Code == EngineEventCodes.RecipeNotConfigured).ToList();
Assert.HasCount(1, said, "Said once, not at every sweep.");
Assert.AreEqual(StoriesReason + SessionComposer.NotConfiguredTail, said[0].Message);
}
[TestMethod]
public async Task ARefusalOfTheRunnerIsNotAFailureAndIsNotTriedAgainInTheProcess()
{
await using var bed = await EngineTestBed.CreateAsync(Morning);
await bed.AddAccountAsync("strano.demo", followed: false, Frequency.High);
var runner = new ScriptedRunner(bed.Governor, bed.Clock)
{
Script = r => r.Kind == RecipeKind.ProfileCheck ? new RecipeOutcome(RecipeStatus.NotConfigured, 0, 0, ProfileReason) : null,
};
var host = bed.Start(runner);
await bed.RunUntilAsync(Morning.AddDays(3));
// Three unrecognized formats suspend the recipe in two days (EngineHostTests); a refusal never does.
Assert.AreEqual(1, runner.Runs.Count(r => r.Request.Kind == RecipeKind.ProfileCheck));
Assert.IsEmpty(host.SuspendedRecipes);
Assert.IsNull(await bed.Db.Settings.GetAsync(EngineSettingKeys.RecipeFailures));
Assert.IsFalse((await bed.Db.Tasks.ListPendingAsync(1000)).Any(t => t.Kind == EngineTaskKind.ProfileCheck));
var events = await bed.Db.Events.ListAsync(new EventQuery());
Assert.IsFalse(events.Any(e => e.Code is EngineEventCodes.RecipeSuspended or EngineEventCodes.FormatUnrecognized or EngineEventCodes.TargetNotFound or EngineEventCodes.RecipeFailed));
Assert.AreEqual(0, events.Count(e => e.Code == EngineEventCodes.RecipeNotConfigured), "The runner said it; the engine does not say it again.");
var line = events.Single(e => e.Code == EngineEventCodes.RecipePrefix + RecipeKind.ProfileCheck);
StringAssert.EndsWith(line.Message, "Configurazione della raccolta incompleta");
var snapshot = await host.Monitor.GetSnapshotAsync();
Assert.IsTrue(snapshot.RecentActions.Any(a => a.Badge == "Da configurare"));
}
[TestMethod]
public async Task TheRunnerRefusesBeforeDoingAnythingAndSaysItOncePerRecipe()
{
using var temp = new TempFolder("non-configurata");
await using var db = await TestDatabase.OpenAsync(temp);
var clock = new VirtualClock();
var governor = new PermissiveGovernor();
var session = new TestSession((await db.Sessions.StartAsync(clock.Now)).Id);
RecipeEnvironment Environment(SiteMap map, ReaderVocabulary vocabulary) => new()
{
Driver = new UntouchedDriver(),
Capture = new CaptureCollector(new ShapeReader(vocabulary), clock),
Governor = governor,
Signals = new SignalDetector(SignalRules.LoadDefault(), new RecordingBreaker(), clock),
Storage = db,
SiteMap = map,
Clock = clock,
Random = new SeededRandom(1),
};
var empty = SiteMap.Parse("""{ "site": "vuoto", "pages": { "home": "" } }""", "bersagli.vuoto.json");
var runner = new RecipeRunner(Environment(empty, ReaderVocabulary.LoadTestSite()));
StringAssert.Contains(runner.NotConfiguredReason(RecipeKind.FollowingSweep), "pagina «home»");
for (var i = 0; i < 3; i++)
{
var sweep = await runner.RunAsync(new RecipeRequest(RecipeKind.FollowingSweep), session, CancellationToken.None);
Assert.AreEqual(RecipeStatus.NotConfigured, sweep.Status);
Assert.AreEqual(runner.NotConfiguredReason(RecipeKind.FollowingSweep), sweep.Message);
Assert.AreEqual(0, sweep.CountedActions);
}
var profile = await runner.RunAsync(new RecipeRequest(RecipeKind.ProfileCheck, 1), session, CancellationToken.None);
Assert.AreEqual(RecipeStatus.NotConfigured, profile.Status);
StringAssert.Contains(profile.Message, "la mappa dei bersagli non è ancora compilata");
var lines = (await db.Events.ListAsync(new EventQuery())).Where(e => e.Code == "mappa-incompleta").ToList();
Assert.HasCount(2, lines, "One line per recipe, not one per run.");
Assert.IsTrue(lines.All(e => e.Severity == EventSeverity.Warning && e.Message.EndsWith(SessionComposer.NotConfiguredTail, StringComparison.Ordinal)));
// A vocabulary that is only a hypothesis refuses every recipe the same way.
var hypothesis = new RecipeRunner(Environment(SiteMap.LoadTestSite(), ReaderVocabulary.LoadTestSite() with { Status = VocabularyStatus.Hypothesis }));
var readers = await hypothesis.RunAsync(new RecipeRequest(RecipeKind.FollowingSweep), session, CancellationToken.None);
Assert.AreEqual(RecipeStatus.NotConfigured, readers.Status);
Assert.IsTrue((await db.Events.ListAsync(new EventQuery())).Any(e => e.Code == "lettori-incompleti"));
Assert.AreEqual(0, governor.Requests.Count, "No permit asked, no gesture, no page.");
// The test site's own files let every recipe run.
var full = new RecipeRunner(Environment(SiteMap.LoadTestSite(), ReaderVocabulary.LoadTestSite()));
foreach (var kind in Enum.GetValues<RecipeKind>())
{
Assert.IsNull(full.NotConfiguredReason(kind), kind.ToString());
}
}
/// <summary>Tasks of a kind in the queue, whatever their state (cancelled ones included).</summary>
private static Task<long> TasksAsync(EngineTestBed bed, EngineTaskKind kind) =>
bed.Db.ReadAsync(c => c.Command("SELECT COUNT(*) FROM task WHERE kind = @k").With("@k", kind.ToString()).ScalarInt64(), default);
/// <summary>A driver that fails the test if a refused recipe touches it.</summary>
private sealed class UntouchedDriver : IPageDriver
{
public double WaitMultiplier => 1;
public void BeginSession(double mood) => throw Touched();
public Task<PageLoad> OpenAsync(string path, CancellationToken ct) => throw Touched();
public Task<string> CurrentPathAsync(CancellationToken ct) => throw Touched();
public Task<bool> IsOnSiteAsync(CancellationToken ct) => throw Touched();
public Task<TargetCheck> FindAsync(string target, IReadOnlyDictionary<string, string>? parameters, CancellationToken ct) => throw Touched();
public Task<TargetCheck> ClickAsync(string target, IReadOnlyDictionary<string, string>? parameters, CancellationToken ct) => throw Touched();
public Task ScrollBurstAsync(CancellationToken ct) => throw Touched();
public Task WaitAfterLoadAsync(CancellationToken ct) => throw Touched();
public Task WaitAsync(TimeSpan duration, CancellationToken ct) => throw Touched();
public Task<bool> MaybeDistractionAsync(CancellationToken ct) => throw Touched();
public Task<bool?> HasSessionCookieAsync(CancellationToken ct) => throw Touched();
public Task RestAsync(CancellationToken ct) => throw Touched();
private static AssertFailedException Touched() => new("Una ricetta rifiutata ha toccato la pagina.");
}
}
@@ -130,6 +130,19 @@ internal sealed class EngineTestBed : IAsyncDisposable
return _host;
}
/// <summary>
/// Like <see cref="Start"/>, with <paramref name="beforeLoop"/> run on the host before its loop, as the composition
/// does at start-up (<see cref="EngineHost.ApplyCollectionConfigurationAsync"/>).
/// </summary>
public async Task<EngineHost> StartAsync(IRecipeRunner runner, Func<EngineHost, Task> beforeLoop)
{
_host = new EngineHost(Services, runner);
await beforeLoop(_host);
_loopCts = new CancellationTokenSource();
_loop = _host.RunAsync(_loopCts.Token);
return _host;
}
public EngineHost Host => _host ?? throw new InvalidOperationException("Engine not started.");
/// <summary>Advances virtual time to <paramref name="target"/>, letting the engine run.</summary>
@@ -31,6 +31,9 @@ internal sealed class ScriptedRunner(IGovernor governor, IClock clock) : IRecipe
/// <summary>Accounts the stories bar flags in every sweep.</summary>
public IReadOnlyList<long> FlaggedStories { get; set; } = [];
/// <summary>What the runner says of the configuration of the site (null: every recipe can run).</summary>
public Func<RecipeKind, string?>? NotConfigured { get; set; }
public int Rests { get; private set; }
public IReadOnlyList<RunRecord> Runs
@@ -74,6 +77,8 @@ internal sealed class ScriptedRunner(IGovernor governor, IClock clock) : IRecipe
return outcome;
}
public string? NotConfiguredReason(RecipeKind kind) => NotConfigured?.Invoke(kind);
public Task RestAsync(CancellationToken ct)
{
Rests++;