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;
///
/// 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.
///
[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())
{
Assert.IsNull(full.NotConfiguredReason(kind), kind.ToString());
}
}
/// Tasks of a kind in the queue, whatever their state (cancelled ones included).
private static Task TasksAsync(EngineTestBed bed, EngineTaskKind kind) =>
bed.Db.ReadAsync(c => c.Command("SELECT COUNT(*) FROM task WHERE kind = @k").With("@k", kind.ToString()).ScalarInt64(), default);
/// A driver that fails the test if a refused recipe touches it.
private sealed class UntouchedDriver : IPageDriver
{
public double WaitMultiplier => 1;
public void BeginSession(double mood) => throw Touched();
public Task OpenAsync(string path, CancellationToken ct) => throw Touched();
public Task CurrentPathAsync(CancellationToken ct) => throw Touched();
public Task IsOnSiteAsync(CancellationToken ct) => throw Touched();
public Task FindAsync(string target, IReadOnlyDictionary? parameters, CancellationToken ct) => throw Touched();
public Task ClickAsync(string target, IReadOnlyDictionary? 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 MaybeDistractionAsync(CancellationToken ct) => throw Touched();
public Task HasSessionCookieAsync(CancellationToken ct) => throw Touched();
public Task RestAsync(CancellationToken ct) => throw Touched();
private static AssertFailedException Touched() => new("Una ricetta rifiutata ha toccato la pagina.");
}
}