M3 Motore: Governatore con tetti da action_log, interruttore con fermi 1/6/24 ore e ripresa manuale, fascia giornaliera spostata a caso e salvata, sessioni con pause log-normali e pavimento, composizione delle sessioni sulla coda persistente, «Controlla ora» con conferma fuori fascia, cruscotto per l'interfaccia e calcolatore «Con queste impostazioni», simulazione con orologio virtuale e comando --simula; prove del motore e dell'interruttore

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
Claude committed 2026-10-13 17:33:28 +00:00
1 parent e2c987873b
commit 346d5ca075
38 files changed
+9308

No files matched your search

@@ -0,0 +1,120 @@
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Tests.Engine.Support;
namespace Febe.Tests.Engine;
[TestClass]
public sealed class AccountPlanCalculatorTests
{
private static Account Make(string name, bool followed, Frequency frequency = Frequency.Normal, AccountState state = AccountState.UpToDate, int? posts = null, long id = 0) =>
Account.Create(name, StartingPoint.EverythingAndKeepUpdated, EngineTestBed.Noon, EngineTestBed.Zone) with
{
Id = id,
IsFollowed = followed,
Frequency = frequency,
State = state,
PostCount = posts,
};
[TestMethod]
public void AProfileNotFollowedIsCheckedEveryThreeHoursAtNormalFrequency()
{
var estimate = AccountPlanCalculator.Calculate(new AccountPlanInput
{
Account = Make("studio.lumen.demo", followed: false) with { ContentTypes = ContentTypes.PostPhotos | ContentTypes.PostVideos },
Profile = CautionProfile.Prudent with { GradualStart = false },
});
Assert.AreEqual(TimeSpan.FromHours(3), estimate.ProfileCheckWanted);
Assert.IsTrue(estimate.ProfileCheckEvery!.Value.TotalHours is > 2.9 and < 3.3);
Assert.IsFalse(estimate.OverBudget);
Assert.AreEqual(100, estimate.DailyProfileBudget);
var posts = estimate.Lines.Single(l => l.Title == "Nuovi post").Text;
StringAssert.Contains(posts, "ogni 3 ore circa");
StringAssert.Contains(posts, "tra le 7:30 e le 23:30");
Assert.AreEqual("spente.", estimate.Lines.Single(l => l.Title == "Storie").Text);
Assert.IsEmpty(estimate.Warnings);
}
[TestMethod]
public void FollowedProfilesAreDiscoveredByTheSweepAndStoriesGetThreeChecksADay()
{
var estimate = AccountPlanCalculator.Calculate(new AccountPlanInput
{
Account = Make("marta.demo", followed: true, Frequency.Low),
Profile = CautionProfile.Prudent,
});
StringAssert.Contains(estimate.Lines.Single(l => l.Title == "Nuovi post").Text, "giro dei profili che segui");
StringAssert.Contains(estimate.Lines.Single(l => l.Title == "Nuovi post").Text, "20–90 minuti");
Assert.IsTrue(estimate.StoryInterval <= TimeSpan.FromHours(16) / 3);
Assert.IsTrue(estimate.StoryChecksPerDay >= 3);
StringAssert.Contains(estimate.Lines.Single(l => l.Title == "Storie").Text, "almeno 3 volte al giorno");
Assert.IsTrue(estimate.Warnings.Any(w => w.Contains("avvio graduale", StringComparison.Ordinal)));
}
[TestMethod]
public void TheBackfillEstimateUsesThePostCountWhenKnown()
{
var profile = CautionProfile.Prudent with { GradualStart = false };
var known = AccountPlanCalculator.Calculate(new AccountPlanInput
{
Account = Make("storico.demo", followed: true, state: AccountState.Backfilling, posts: 2000) with { BackfillCompletedAt = null },
Profile = profile,
ArchivedPosts = 500,
});
Assert.AreEqual(1500, known.BackfillRemainingPosts);
Assert.AreEqual(5, known.BackfillDays, "1.500 posts at 300 a day.");
StringAssert.Contains(known.Lines.Single(l => l.Title == "Storico").Text, "mancano 1.500 post, servono circa 5 giorni");
var unknown = AccountPlanCalculator.Calculate(new AccountPlanInput
{
Account = Make("nuovo.demo", followed: true, state: AccountState.Backfilling) with { BackfillCompletedAt = null },
Profile = profile,
});
Assert.IsNull(unknown.BackfillDays);
StringAssert.Contains(unknown.Lines.Single(l => l.Title == "Storico").Text, "non è ancora noto");
// Shared with other accounts in backfill, within the daily budget of history pages (100 × 12 posts).
var others = Enumerable.Range(1, 7).Select(i => Make($"altro{i}.demo", true, state: AccountState.Backfilling, id: i) with { BackfillCompletedAt = null }).ToList();
var shared = AccountPlanCalculator.Calculate(new AccountPlanInput
{
Account = Make("storico.demo", followed: true, state: AccountState.Backfilling, posts: 2000, id: 100) with { BackfillCompletedAt = null },
OtherAccounts = others,
Profile = profile,
});
Assert.AreEqual(14, shared.BackfillDays, "2.000 posts at 150 a day (1.200 shared by 8 accounts).");
}
[TestMethod]
public void TooManyAccountsMakeTheChecksSparserWithAWarning()
{
var others = Enumerable.Range(1, 40).Select(i => Make($"pubblico{i}.demo", false, Frequency.High, id: i)).ToList();
var estimate = AccountPlanCalculator.Calculate(new AccountPlanInput
{
Account = Make("studio.demo", followed: false, id: 500),
OtherAccounts = others,
Profile = CautionProfile.Prudent with { GradualStart = false },
});
Assert.IsTrue(estimate.OverBudget);
Assert.IsTrue(estimate.TotalProfileOpensPerDay > 100);
Assert.IsTrue(estimate.ProfileCheckEvery > estimate.ProfileCheckWanted, "Sparser, not forced.");
Assert.IsTrue(estimate.Warnings.Any(w => w.Contains("si diradano", StringComparison.Ordinal)));
Assert.IsTrue(estimate.ShareOfDailyBudget < 0.1);
}
[TestMethod]
public void AccountsThatAreNotContactedCostNothing()
{
var estimate = AccountPlanCalculator.Calculate(new AccountPlanInput
{
Account = Make("archivio.demo", followed: false, state: AccountState.ArchiveOnly),
Profile = CautionProfile.Prudent,
});
Assert.IsFalse(estimate.Contacted);
Assert.AreEqual(0, estimate.ProfileOpensPerDay);
StringAssert.Contains(estimate.Lines[0].Text, "Solo archivio");
}
}
@@ -0,0 +1,165 @@
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Storage;
using Febe.Tests.Engine.Support;
namespace Febe.Tests.Engine;
[TestClass]
public sealed class CircuitBreakerTests
{
private static Signal Throttle(DateTimeOffset at) => new(SignalLevel.Throttle, "http-429", "https://sito.prova/api", at);
[TestMethod]
public async Task ThrottlesStopOneSixAndTwentyFourHoursThenHalveTheBudgets()
{
await using var bed = await EngineTestBed.CreateAsync();
var breaker = bed.Breaker;
var t0 = bed.Clock.Now;
await breaker.ReportAsync(Throttle(t0));
Assert.AreEqual(BreakerStatus.Throttled, breaker.State.Status);
Assert.AreEqual(t0 + TimeSpan.FromHours(1), breaker.State.Until);
Assert.IsFalse(breaker.State.AllowsSiteActions);
bed.Clock.Advance(TimeSpan.FromHours(1));
Assert.AreEqual(BreakerStatus.Closed, breaker.State.Status);
Assert.AreEqual(t0 + TimeSpan.FromHours(1) + TimeSpan.FromHours(48), breaker.State.HalvedBudgetsUntil);
bed.Clock.Advance(TimeSpan.FromHours(1));
await breaker.ReportAsync(Throttle(bed.Clock.Now));
Assert.AreEqual(bed.Clock.Now + TimeSpan.FromHours(6), breaker.State.Until, "Second within 24 hours: 6 hours.");
bed.Clock.Advance(TimeSpan.FromHours(7));
Assert.IsTrue(breaker.State.AllowsSiteActions);
await breaker.ReportAsync(Throttle(bed.Clock.Now));
Assert.AreEqual(bed.Clock.Now + TimeSpan.FromHours(24), breaker.State.Until, "Third within 24 hours: 24 hours.");
bed.Clock.Advance(TimeSpan.FromHours(24));
Assert.IsTrue(breaker.State.AllowsSiteActions);
await breaker.FlushAsync();
var incidents = await bed.Db.Incidents.ListAsync(t0, bed.Clock.Now.AddSeconds(1));
Assert.HasCount(3, incidents);
Assert.IsTrue(incidents.All(i => i.Level == SignalLevel.Throttle && i.Signal == "http-429" && i.Url == "https://sito.prova/api"));
Assert.AreEqual(t0 + TimeSpan.FromHours(1), incidents[0].StoppedUntil);
Assert.AreEqual(incidents[0].StoppedUntil, incidents[0].ResolvedAt);
Assert.IsTrue(incidents.All(i => i.ResolvedAt is not null));
Assert.HasCount(0, await bed.Db.Incidents.ListOpenAsync());
var events = await bed.Db.Events.ListAsync(new EventQuery());
Assert.AreEqual(3, events.Count(e => e.Code == EngineEventCodes.ThrottleStop));
Assert.IsTrue(events.Any(e => e.Code == EngineEventCodes.ThrottleEnd));
}
[TestMethod]
public async Task AThrottleDuringAStopDoesNotEscalateIt()
{
await using var bed = await EngineTestBed.CreateAsync();
await bed.Breaker.ReportAsync(Throttle(bed.Clock.Now));
var until = bed.Breaker.State.Until;
bed.Clock.Advance(TimeSpan.FromMinutes(10));
await bed.Breaker.ReportAsync(Throttle(bed.Clock.Now));
Assert.AreEqual(until, bed.Breaker.State.Until);
await bed.Breaker.FlushAsync();
Assert.HasCount(1, await bed.Db.Incidents.ListAsync(bed.Clock.Now.AddDays(-1), bed.Clock.Now.AddDays(1)));
}
[TestMethod]
[DataRow(SignalLevel.Challenge, BreakerStatus.Challenge, EngineEventCodes.ChallengeStop)]
[DataRow(SignalLevel.Disconnect, BreakerStatus.Disconnected, EngineEventCodes.DisconnectStop)]
public async Task VerificationAndDisconnectionNeverRestartAlone(SignalLevel level, BreakerStatus status, string code)
{
await using var bed = await EngineTestBed.CreateAsync(gradualStart: true);
await bed.Breaker.ReportAsync(new Signal(level, "segnale-prova", "https://sito.prova/x", bed.Clock.Now));
Assert.AreEqual(status, bed.Breaker.State.Status);
bed.Clock.Advance(TimeSpan.FromDays(5));
Assert.AreEqual(status, bed.Breaker.State.Status);
Assert.IsFalse(bed.Breaker.State.AllowsSiteActions);
var open = await bed.Db.Incidents.ListOpenAsync();
Assert.HasCount(1, open);
Assert.AreEqual(level, open[0].Level);
Assert.IsNull(open[0].StoppedUntil);
var resumedAt = bed.Clock.Now;
Assert.IsTrue(await bed.Breaker.ResumeAsync());
Assert.AreEqual(BreakerStatus.Closed, bed.Breaker.State.Status);
Assert.HasCount(0, await bed.Db.Incidents.ListOpenAsync());
// The resume starts the gradual start again, persisted.
Assert.AreEqual(resumedAt, bed.Runtime.RampStart);
Assert.AreEqual(resumedAt.ToUnixTimeMilliseconds(), await bed.Db.Settings.GetInt64Async(EngineSettingKeys.RampStart));
Assert.AreEqual(0.5, bed.Governor.GetEffectiveBudgets(bed.Clock.Now).Factor, 1e-9);
var events = await bed.Db.Events.ListAsync(new EventQuery());
Assert.IsTrue(events.Any(e => e.Code == code && e.Severity == EventSeverity.Error));
Assert.IsTrue(events.Any(e => e.Code == EngineEventCodes.Resumed));
}
[TestMethod]
public async Task AThrottleStopCannotBeShortenedByResume()
{
await using var bed = await EngineTestBed.CreateAsync();
await bed.Breaker.ReportAsync(Throttle(bed.Clock.Now));
Assert.IsFalse(await bed.Breaker.ResumeAsync());
Assert.AreEqual(BreakerStatus.Throttled, bed.Breaker.State.Status);
}
[TestMethod]
public async Task TheStateIsRestoredFromTheDatabase()
{
await using var bed = await EngineTestBed.CreateAsync();
await bed.Breaker.ReportAsync(Throttle(bed.Clock.Now));
var until = bed.Breaker.State.Until;
await bed.Breaker.FlushAsync();
var restarted = await bed.ReopenAsync(seed: 99);
Assert.AreEqual(BreakerStatus.Throttled, restarted.Breaker.State.Status);
Assert.AreEqual(until, restarted.Breaker.State.Until);
bed.Clock.Advance(TimeSpan.FromHours(2));
await restarted.Breaker.ReportAsync(new Signal(SignalLevel.Challenge, "challenge-url", null, bed.Clock.Now));
var again = await bed.ReopenAsync(seed: 100);
Assert.AreEqual(BreakerStatus.Challenge, again.Breaker.State.Status);
Assert.IsNotNull(again.Breaker.State.HalvedBudgetsUntil, "The halving of the earlier throttle is restored too.");
// The expired throttle was resolved; resuming the verification leaves nothing open.
bed.Clock.Advance(TimeSpan.FromHours(1));
Assert.IsTrue(await again.Breaker.ResumeAsync());
Assert.HasCount(0, await bed.Db.Incidents.ListOpenAsync());
}
[TestMethod]
public async Task ThreeThrottlesInSevenDaysProposeAMorePrudentProfile()
{
await using var bed = await EngineTestBed.CreateAsync(profile: CautionProfileKind.Fast);
for (var i = 0; i < 3; i++)
{
await bed.Breaker.ReportAsync(Throttle(bed.Clock.Now));
bed.Clock.Advance(TimeSpan.FromDays(2));
_ = bed.Breaker.State;
}
await bed.Breaker.FlushAsync();
var proposals = (await bed.Db.Events.ListAsync(new EventQuery())).Where(e => e.Code == EngineEventCodes.ProposeMorePrudence).ToList();
Assert.HasCount(1, proposals);
StringAssert.Contains(proposals[0].Message, "«Equilibrato»");
}
[TestMethod]
public async Task TwoThrottlesInSevenDaysAreNotYetAProposal()
{
await using var bed = await EngineTestBed.CreateAsync();
await bed.Breaker.ReportAsync(Throttle(bed.Clock.Now));
bed.Clock.Advance(TimeSpan.FromDays(8));
_ = bed.Breaker.State;
await bed.Breaker.ReportAsync(Throttle(bed.Clock.Now));
bed.Clock.Advance(TimeSpan.FromDays(2));
_ = bed.Breaker.State;
await bed.Breaker.ReportAsync(Throttle(bed.Clock.Now));
await bed.Breaker.FlushAsync();
Assert.IsFalse((await bed.Db.Events.ListAsync(new EventQuery())).Any(e => e.Code == EngineEventCodes.ProposeMorePrudence));
}
}
@@ -0,0 +1,93 @@
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Tests.Engine.Support;
namespace Febe.Tests.Engine;
[TestClass]
public sealed class DayPlannerTests
{
[TestMethod]
public async Task TheWindowMovesEveryDayWithinTheJitterAndNotUniformly()
{
await using var bed = await EngineTestBed.CreateAsync();
var planner = bed.Services.Planner;
var profile = CautionProfile.Prudent;
var day = new DateOnly(2026, 10, 14);
var starts = new List<double>();
for (var i = 0; i < 300; i++)
{
var d = day.AddDays(i);
var window = await planner.GetWindowAsync(d);
Assert.IsNotNull(window);
var baseStart = LocalCalendar.FromLocal(d.ToDateTime(profile.WindowStart), EngineTestBed.Zone);
var baseEnd = LocalCalendar.FromLocal(d.ToDateTime(profile.WindowEnd), EngineTestBed.Zone);
var shiftStart = (window!.Start - baseStart).TotalMinutes;
var shiftEnd = (window.End - baseEnd).TotalMinutes;
Assert.IsTrue(Math.Abs(shiftStart) <= 40, $"start shift {shiftStart}");
Assert.IsTrue(Math.Abs(shiftEnd) <= 40, $"end shift {shiftEnd}");
starts.Add(shiftStart);
}
Assert.IsTrue(starts.Distinct().Count() > 250, "Every day has its own shift.");
// A normal shape: far more draws in the central half than a uniform draw would give (50%).
var central = starts.Count(s => Math.Abs(s) <= 20) / (double)starts.Count;
Assert.IsTrue(central > 0.62, $"central share {central}");
}
[TestMethod]
public async Task TheDailyShiftIsNotRedrawnAfterARestart()
{
await using var bed = await EngineTestBed.CreateAsync();
var day = new DateOnly(2026, 10, 20);
var before = await bed.Services.Planner.GetWindowAsync(day);
var restarted = await bed.ReopenAsync(seed: 12345);
var after = await restarted.Planner.GetWindowAsync(day);
Assert.AreEqual(before, after);
}
[TestMethod]
public async Task AWindowMayEndAfterMidnight()
{
await using var bed = await EngineTestBed.CreateAsync(profile: CautionProfileKind.Fast);
var day = new DateOnly(2026, 10, 14);
var window = await bed.Services.Planner.GetWindowAsync(day);
Assert.IsNotNull(window);
Assert.AreEqual(day.AddDays(1), LocalCalendar.Today(window!.End, EngineTestBed.Zone), "06:30–00:30 ends on the next day.");
// Ten minutes before the end, after midnight, the instant belongs to the window of the previous day.
var lateNight = window.End - TimeSpan.FromMinutes(10);
var found = await bed.Services.Planner.GetWindowAtAsync(lateNight);
Assert.AreEqual(window, found);
Assert.IsNull(await bed.Services.Planner.GetWindowAtAsync(window.End + TimeSpan.FromMinutes(10)));
}
[TestMethod]
public async Task InactiveDaysHaveNoWindow()
{
var weekdays = new HashSet<DayOfWeek> { DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday };
await using var bed = await EngineTestBed.CreateAsync(settings: new EngineSettings { GradualStart = false, ActiveDays = weekdays });
var saturday = new DateOnly(2026, 10, 17);
Assert.IsNull(await bed.Services.Planner.GetWindowAsync(saturday));
var next = await bed.Services.Planner.GetNextWindowAsync(LocalCalendar.StartOfDay(saturday, EngineTestBed.Zone).AddHours(12));
Assert.AreEqual(new DateOnly(2026, 10, 19), next!.Day);
}
[TestMethod]
public void WindowsAreComputedAcrossDaylightSavingTime()
{
// 25 October 2026: clocks go back in Rome at 3:00; the window is still 07:30–23:30 local time.
var profile = CautionProfile.Prudent with { WindowJitter = TimeSpan.Zero };
var window = DayPlanner.Compute(new DateOnly(2026, 10, 25), profile, 42, EngineTestBed.Zone);
Assert.AreEqual(new TimeOnly(7, 30), TimeOnly.FromDateTime(LocalCalendar.ToLocal(window.Start, EngineTestBed.Zone)));
Assert.AreEqual(new TimeOnly(23, 30), TimeOnly.FromDateTime(LocalCalendar.ToLocal(window.End, EngineTestBed.Zone)));
Assert.AreEqual(TimeSpan.FromHours(16), window.Length);
// 28 March 2027: clocks go forward at 2:00; a window from 22:00 to 6:00 loses that hour.
var night = profile with { WindowStart = new TimeOnly(22, 0), WindowEnd = new TimeOnly(6, 0) };
var spring = DayPlanner.Compute(new DateOnly(2027, 3, 27), night, 42, EngineTestBed.Zone);
Assert.AreEqual(TimeSpan.FromHours(7), spring.Length);
}
}
+473
View File
@@ -0,0 +1,473 @@
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Storage;
using Febe.Tests.Engine.Support;
namespace Febe.Tests.Engine;
[TestClass]
public sealed class EngineHostTests
{
private static readonly DateTimeOffset Morning = EngineTestBed.Local(2026, 10, 14, 6, 0);
private static async Task<IReadOnlyList<SessionRecord>> SessionsAsync(EngineTestBed bed) =>
await bed.Db.Sessions.ListAsync(bed.Clock.Now.AddDays(-30), bed.Clock.Now.AddDays(1));
[TestMethod]
public async Task SessionsStayInsideTheWindowAndRespectThePauseFloor()
{
await using var bed = await EngineTestBed.CreateAsync(Morning);
await bed.AddAccountAsync("uno.demo", followed: false, Frequency.High);
await bed.AddAccountAsync("due.demo", followed: true);
var runner = new ScriptedRunner(bed.Governor, bed.Clock);
bed.Start(runner);
await bed.RunUntilAsync(Morning.AddDays(2));
var sessions = await SessionsAsync(bed);
Assert.IsTrue(sessions.Count > 20, $"{sessions.Count} sessions");
for (var i = 1; i < sessions.Count; i++)
{
var pause = sessions[i].StartedAt - sessions[i - 1].EndedAt!.Value;
Assert.IsTrue(pause >= TimeSpan.FromMinutes(20), $"pause of {pause}");
}
foreach (var session in sessions)
{
Assert.IsNotNull(await bed.Services.Planner.GetWindowAtAsync(session.StartedAt), $"session at {session.StartedAt:O}");
}
Assert.HasCount(0, await BudgetAudit.OutsideWindowAsync(bed.Db, bed.Services.Planner, Morning, bed.Clock.Now));
Assert.HasCount(0, await BudgetAudit.OverrunsAsync(bed.Db, bed.Runtime.Profile, EngineTestBed.Zone, Morning, bed.Clock.Now));
Assert.AreEqual(sessions.Count(s => s.EndedAt is not null), runner.Rests, "Every session ends on the empty page.");
// The first session comes 2–10 minutes after the start, but not before the window.
var window = await bed.Services.Planner.GetWindowAsync(new DateOnly(2026, 10, 14));
Assert.IsTrue(sessions[0].StartedAt >= window!.Start);
}
[TestMethod]
public async Task TheFirstSessionComesTwoToTenMinutesAfterTheStart()
{
await using var bed = await EngineTestBed.CreateAsync(EngineTestBed.Noon);
await bed.AddAccountAsync("uno.demo", followed: true);
bed.Start(new ScriptedRunner(bed.Governor, bed.Clock));
await bed.RunForAsync(TimeSpan.FromMinutes(30));
var first = (await SessionsAsync(bed))[0].StartedAt - EngineTestBed.Noon;
Assert.IsTrue(first >= TimeSpan.FromMinutes(2) && first <= TimeSpan.FromMinutes(10), $"first session after {first}");
}
[TestMethod]
public async Task ARestartResetsNoCountsAndDoesNotShortenPauses()
{
// 60 profiles a day, and no hourly limit in the way: demand is far above it.
var custom = CautionProfile.Prudent with
{
Budgets = new Dictionary<ActionKind, Budget>(CautionProfile.Prudent.Budgets) { [ActionKind.ProfileOpen] = new Budget(60, 60) },
};
await using var bed = await EngineTestBed.CreateAsync(Morning, settings: new EngineSettings { GradualStart = false }.WithCustomValues(custom));
for (var i = 0; i < 30; i++)
{
await bed.AddAccountAsync($"pubblico{i}.demo", followed: false, Frequency.High, types: ContentTypes.PostPhotos | ContentTypes.PostVideos);
}
await bed.AddAccountAsync("seguito.demo", followed: true);
bed.Start(new ScriptedRunner(bed.Governor, bed.Clock));
var window = await bed.Services.Planner.GetWindowAsync(new DateOnly(2026, 10, 14));
await bed.RunUntilAsync(window!.Start + TimeSpan.FromMinutes(70));
var openedBefore = await bed.Db.ActionLog.SumAsync(ActionKind.ProfileOpen, Morning, bed.Clock.Now);
Assert.IsTrue(openedBefore is > 0 and < 60, $"{openedBefore} profiles opened before the restart");
await bed.StopAsync();
var plannedNext = DateTimeOffset.FromUnixTimeMilliseconds((await bed.Db.Settings.GetInt64Async(EngineSettingKeys.NextSession))!.Value);
var lastEnd = (await SessionsAsync(bed)).Max(s => s.EndedAt!.Value);
var restartAt = bed.Clock.Now + TimeSpan.FromMinutes(1);
bed.Clock.AdvanceTo(restartAt);
await bed.ReopenAsync(seed: 4242);
bed.Start(new ScriptedRunner(bed.Governor, bed.Clock));
await bed.RunUntilAsync(EngineTestBed.Local(2026, 10, 15, 0, 0));
var after = (await SessionsAsync(bed)).Where(s => s.StartedAt >= restartAt).ToList();
Assert.IsNotEmpty(after);
Assert.IsTrue(after[0].StartedAt >= plannedNext, "Not earlier than the session planned before the restart.");
Assert.IsTrue(after[0].StartedAt - lastEnd >= TimeSpan.FromMinutes(20), "The pause floor holds across the restart.");
Assert.IsTrue(after[0].StartedAt - restartAt >= TimeSpan.FromMinutes(2));
// Demand is far above the budget: the day ends exactly at the daily budget, counting the morning before the restart.
var openedToday = await bed.Db.ActionLog.SumAsync(ActionKind.ProfileOpen, Morning, bed.Clock.Now);
Assert.AreEqual(60L, openedToday);
Assert.HasCount(0, await BudgetAudit.OverrunsAsync(bed.Db, bed.Runtime.Profile, EngineTestBed.Zone, Morning, bed.Clock.Now));
}
[TestMethod]
public async Task RepeatedRestartsDoNotProduceMoreSessions()
{
await using var bed = await EngineTestBed.CreateAsync(Morning);
await bed.AddAccountAsync("uno.demo", followed: true);
var seed = 500;
for (var hour = 0; hour < 18; hour++)
{
bed.Start(new ScriptedRunner(bed.Governor, bed.Clock));
await bed.RunForAsync(TimeSpan.FromMinutes(59));
await bed.StopAsync();
await bed.ReopenAsync(++seed);
}
var sessions = await SessionsAsync(bed);
for (var i = 1; i < sessions.Count; i++)
{
Assert.IsTrue(sessions[i].StartedAt - sessions[i - 1].EndedAt!.Value >= TimeSpan.FromMinutes(20));
}
// A program that stays on makes at most 16 h / 20 min sessions in a window; restarts every hour stay well below.
Assert.IsTrue(sessions.Count <= 48, $"{sessions.Count} sessions");
}
[TestMethod]
public async Task MostSessionsOpenWithTheSweepAndAccountsComeInRandomOrder()
{
await using var bed = await EngineTestBed.CreateAsync(Morning);
for (var i = 0; i < 8; i++)
{
await bed.AddAccountAsync($"pubblico{i}.demo", followed: false, Frequency.High, types: ContentTypes.PostPhotos | ContentTypes.PostVideos);
}
await bed.AddAccountAsync("seguito.demo", followed: true);
var runner = new ScriptedRunner(bed.Governor, bed.Clock);
bed.Start(runner);
await bed.RunUntilAsync(Morning.AddDays(3));
var bySession = runner.Runs.GroupBy(r => r.SessionId).ToList();
var openedWithSweep = bySession.Count(g => g.First().Request.Kind == RecipeKind.FollowingSweep) / (double)bySession.Count;
Assert.IsTrue(openedWithSweep is > 0.75 and < 0.99, $"sweep first in {openedWithSweep:P0} of sessions");
var orders = bySession
.Select(g => string.Join(",", g.Where(r => r.Request.Kind == RecipeKind.ProfileCheck).Select(r => r.Request.AccountId)))
.Where(o => o.Contains(',', StringComparison.Ordinal))
.ToList();
Assert.IsTrue(orders.Distinct().Count() > orders.Count / 2, "The order of the accounts changes from session to session.");
// About one session in three stops after sweep and stories even with profile checks due.
var withChecks = bySession.Count(g => g.Any(r => r.Request.Kind == RecipeKind.ProfileCheck)) / (double)bySession.Count;
Assert.IsTrue(withChecks is > 0.45 and < 0.85, $"{withChecks:P0} of sessions with profile checks");
}
[TestMethod]
public async Task BackfillWaitsWhileTheAccountHasMoreThanSixtyFilesToDownload()
{
await using var bed = await EngineTestBed.CreateAsync(Morning);
var account = await bed.AddAccountAsync("storico.demo", followed: true, state: AccountState.Backfilling, postCount: 3000);
for (var i = 0; i < 61; i++)
{
await bed.Db.Entries.AddAsync(
new Entry { AccountId = account.Id, Kind = EntryKind.Post, InstagramId = "attesa" + i, PublishedAt = Morning.AddDays(-400 + i), DiscoveredAt = Morning.AddDays(-1) },
[new Media { Position = 1, Kind = MediaKind.Photo, State = MediaState.ToDownload }]);
}
var runner = new ScriptedRunner(bed.Governor, bed.Clock);
bed.Start(runner);
await bed.RunUntilAsync(Morning.AddDays(1));
Assert.IsFalse(runner.Runs.Any(r => r.Request.Kind == RecipeKind.Backfill));
Assert.IsTrue((await bed.Db.Events.ListAsync(new EventQuery())).Any(e => e.Code == EngineEventCodes.BackfillWaiting && e.AccountId == account.Id));
// Down to 60 waiting files: the backfill goes on.
var pending = await bed.Db.Media.ListPendingDownloadsAsync(10);
await bed.Db.Media.MarkStoredAsync(pending[0].Media.Id, new StoredFile("post/a.jpg", 10, new string('a', 64)), MediaState.Downloaded, bed.Clock.Now);
await bed.RunUntilAsync(Morning.AddDays(2));
Assert.IsTrue(runner.Runs.Any(r => r.Request.Kind == RecipeKind.Backfill && r.Request.AccountId == account.Id));
}
[TestMethod]
public async Task BackfillWaitsWhenTheDataBudgetIsReached()
{
await using var bed = await EngineTestBed.CreateAsync(Morning);
await bed.AddAccountAsync("storico.demo", followed: true, state: AccountState.Backfilling, postCount: 3000);
await bed.Governor.RecordAsync(4L * 1024 * 1024 * 1024, null, CancellationToken.None);
var runner = new ScriptedRunner(bed.Governor, bed.Clock);
bed.Start(runner);
await bed.RunUntilAsync(EngineTestBed.Local(2026, 10, 15, 0, 0));
Assert.IsFalse(runner.Runs.Any(r => r.Request.Kind == RecipeKind.Backfill));
await bed.RunUntilAsync(EngineTestBed.Local(2026, 10, 15, 23, 0));
Assert.IsTrue(runner.Runs.Any(r => r.Request.Kind == RecipeKind.Backfill));
}
[TestMethod]
public async Task BackfillAlternatesAmongAccountsAndPausesAfterTheSingleDownload()
{
await using var bed = await EngineTestBed.CreateAsync(Morning);
var first = await bed.AddAccountAsync("primo.demo", followed: true, state: AccountState.Backfilling, postCount: 500);
var second = await bed.AddAccountAsync("secondo.demo", followed: true, state: AccountState.Backfilling, postCount: 500);
await bed.Db.Accounts.UpdateAsync((await bed.Db.Accounts.GetAsync(second.Id))! with { KeepUpdated = false });
var runner = new ScriptedRunner(bed.Governor, bed.Clock);
var backfills = 0;
DateTimeOffset? finishedAt = null;
runner.Script = request =>
{
if (request.Kind != RecipeKind.Backfill || request.AccountId != second.Id || ++backfills < 3)
{
return null;
}
finishedAt = bed.Clock.Now;
return new RecipeOutcome(RecipeStatus.Completed, 1, 12) { BackfillFinished = true };
};
bed.Start(runner);
await bed.RunUntilAsync(Morning.AddDays(1));
var sequence = runner.Runs.Where(r => r.Request.Kind == RecipeKind.Backfill).Select(r => r.Request.AccountId!.Value).Take(4).ToList();
CollectionAssert.AreEqual(new[] { first.Id, second.Id, first.Id, second.Id }, sequence, "One account per session, alternating.");
Assert.IsTrue(runner.Runs.GroupBy(r => r.SessionId).All(g => g.Count(r => r.Request.Kind == RecipeKind.Backfill) <= 1));
var finished = await bed.Db.Accounts.GetAsync(second.Id);
Assert.AreEqual(AccountState.Paused, finished!.State, "«Tieni aggiornato» off: one download, then paused.");
Assert.IsNotNull(finished.BackfillCompletedAt);
Assert.IsTrue((await bed.Db.Events.ListAsync(new EventQuery())).Any(e => e.Code == EngineEventCodes.BackfillCompleted));
Assert.IsFalse(runner.Runs.Any(r => r.Request.AccountId == second.Id && r.At > finishedAt), "A paused account is not contacted.");
}
[TestMethod]
public async Task ThreeUnrecognizedFormatsInARowSuspendTheRecipe()
{
await using var bed = await EngineTestBed.CreateAsync(Morning);
var account = 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.UnrecognizedFormat, 1, 0) : null,
};
var host = bed.Start(runner);
await bed.RunUntilAsync(Morning.AddDays(2));
Assert.AreEqual(3, runner.Runs.Count(r => r.Request.Kind == RecipeKind.ProfileCheck));
Assert.IsTrue(host.SuspendedRecipes.ContainsKey(RecipeKind.ProfileCheck));
var events = await bed.Db.Events.ListAsync(new EventQuery());
Assert.AreEqual(3, events.Count(e => e.Code == EngineEventCodes.FormatUnrecognized));
Assert.IsTrue(events.Any(e => e.Code == EngineEventCodes.RecipeSuspended && e.Severity == EventSeverity.Error));
Assert.IsTrue((await bed.Db.Accounts.GetAsync(account.Id))!.Notices.HasFlag(AccountNotices.UnrecognizedFormat));
var snapshot = await host.Monitor.GetSnapshotAsync();
Assert.HasCount(1, snapshot.SuspendedRecipes);
runner.Script = null;
Assert.IsTrue(await host.ResumeRecipeAsync(RecipeKind.ProfileCheck));
await bed.RunUntilAsync(Morning.AddDays(3));
Assert.IsTrue(runner.Runs.Any(r => r.Request.Kind == RecipeKind.ProfileCheck && r.Status == RecipeStatus.Completed));
}
[TestMethod]
public async Task AnUnreachableAccountIsNotContactedAnyMore()
{
await using var bed = await EngineTestBed.CreateAsync(Morning);
var account = await bed.AddAccountAsync("sparito.demo", followed: false, Frequency.High);
var runner = new ScriptedRunner(bed.Governor, bed.Clock)
{
Script = r => r.AccountId == account.Id ? new RecipeOutcome(RecipeStatus.AccountUnreachable, 1, 0) : null,
};
bed.Start(runner);
await bed.RunUntilAsync(Morning.AddDays(1));
Assert.AreEqual(1, runner.Runs.Count(r => r.Request.AccountId == account.Id));
Assert.AreEqual(AccountState.Unreachable, (await bed.Db.Accounts.GetAsync(account.Id))!.State);
Assert.IsTrue((await bed.Db.Events.ListAsync(new EventQuery())).Any(e => e.Code == EngineEventCodes.AccountUnreachable));
}
[TestMethod]
public async Task AThrottleClosesTheSessionAtOnceAndStopsForAnHour()
{
await using var bed = await EngineTestBed.CreateAsync(Morning);
await bed.AddAccountAsync("uno.demo", followed: false, Frequency.High);
await bed.AddAccountAsync("due.demo", followed: false, Frequency.High);
var runner = new ScriptedRunner(bed.Governor, bed.Clock);
DateTimeOffset? throttledAt = null;
runner.AfterGrant = r =>
{
if (throttledAt is null && r.Kind == RecipeKind.ProfileCheck)
{
throttledAt = bed.Clock.Now;
bed.Breaker.Report(new Signal(SignalLevel.Throttle, "http-429", null, bed.Clock.Now));
}
};
bed.Start(runner);
await bed.RunUntilAsync(Morning.AddDays(1));
Assert.IsNotNull(throttledAt);
var sessions = await SessionsAsync(bed);
var stopped = sessions.Single(s => s.StartedAt <= throttledAt && s.EndedAt >= throttledAt);
Assert.AreEqual(SessionOutcome.Throttled, stopped.Outcome);
Assert.IsTrue(stopped.EndedAt - throttledAt < TimeSpan.FromSeconds(30), "The session closes at once.");
var during = await bed.Db.ActionLog.ListAsync(throttledAt.Value.AddMilliseconds(1), throttledAt.Value + TimeSpan.FromHours(1));
Assert.HasCount(0, during.Where(a => a.Category != ActionKind.DataDownload).ToList());
Assert.IsTrue(sessions.Any(s => s.StartedAt > throttledAt.Value + TimeSpan.FromHours(1)), "It starts again by itself.");
}
[TestMethod]
public async Task AfterAVerificationNothingStartsUntilResumeWhichRestartsTheGradualStart()
{
await using var bed = await EngineTestBed.CreateAsync(Morning, gradualStart: true);
await bed.AddAccountAsync("uno.demo", followed: false, Frequency.High);
var runner = new ScriptedRunner(bed.Governor, bed.Clock);
var challenged = false;
runner.AfterGrant = r =>
{
if (!challenged)
{
challenged = true;
bed.Breaker.Report(new Signal(SignalLevel.Challenge, "challenge-url", "https://sito.prova/challenge", bed.Clock.Now));
}
};
var host = bed.Start(runner);
await bed.RunUntilAsync(Morning.AddDays(3));
Assert.IsTrue(challenged);
Assert.AreEqual(1, runner.Runs.Count, "Nothing after the verification signal.");
Assert.AreEqual(0, runner.Rests, "The page is left as it is.");
var snapshot = await host.Monitor.GetSnapshotAsync();
Assert.AreEqual(EngineMode.StoppedForVerification, snapshot.Mode);
Assert.IsNotNull(snapshot.Banner);
Assert.AreEqual(BannerLevel.Error, snapshot.Banner!.Level);
var resume = await host.ResumeAsync();
Assert.IsTrue(resume.Resumed);
Assert.AreEqual(0.5, bed.Governor.GetEffectiveBudgets(bed.Clock.Now).Factor, 1e-9);
await bed.RunForAsync(TimeSpan.FromHours(6));
Assert.IsTrue(runner.Runs.Count > 1, "Work goes on after «Riprendi».");
}
[TestMethod]
public async Task PauseStopsEverythingUntilResume()
{
await using var bed = await EngineTestBed.CreateAsync(Morning);
await bed.AddAccountAsync("uno.demo", followed: true);
var runner = new ScriptedRunner(bed.Governor, bed.Clock);
var host = bed.Start(runner);
await bed.RunUntilAsync(EngineTestBed.Local(2026, 10, 14, 10, 0));
await host.PauseAsync();
var count = runner.Runs.Count;
await bed.RunUntilAsync(EngineTestBed.Local(2026, 10, 14, 20, 0));
Assert.AreEqual(count, runner.Runs.Count);
Assert.AreEqual(EngineMode.Paused, (await host.Monitor.GetSnapshotAsync()).Mode);
Assert.IsTrue(await bed.Db.Settings.GetBoolAsync(EngineSettingKeys.Paused, false));
await host.ResumeAsync();
await bed.RunUntilAsync(EngineTestBed.Local(2026, 10, 14, 22, 0));
Assert.IsTrue(runner.Runs.Count > count);
}
[TestMethod]
public async Task WhileAlbertoUsesTheBrowserTheEngineDoesNotAct()
{
var driving = false;
await using var bed = await EngineTestBed.CreateAsync(Morning, userIsDriving: () => driving);
await bed.AddAccountAsync("uno.demo", followed: true);
var runner = new ScriptedRunner(bed.Governor, bed.Clock);
var host = bed.Start(runner);
await bed.RunUntilAsync(EngineTestBed.Local(2026, 10, 14, 10, 0));
driving = true;
host.NotifyUserDrivingChanged();
var count = runner.Runs.Count;
await bed.RunUntilAsync(EngineTestBed.Local(2026, 10, 14, 14, 0));
Assert.AreEqual(count, runner.Runs.Count);
Assert.AreEqual(EngineMode.UserDriving, (await host.Monitor.GetSnapshotAsync()).Mode);
driving = false;
host.NotifyUserDrivingChanged();
await bed.RunUntilAsync(EngineTestBed.Local(2026, 10, 14, 16, 0));
Assert.IsTrue(runner.Runs.Count > count);
}
[TestMethod]
public async Task WithoutAnInstagramSessionNothingStarts()
{
var connected = false;
await using var bed = await EngineTestBed.CreateAsync(Morning, isConnected: () => connected);
await bed.AddAccountAsync("uno.demo", followed: true);
var runner = new ScriptedRunner(bed.Governor, bed.Clock);
var host = bed.Start(runner);
await bed.RunUntilAsync(EngineTestBed.Local(2026, 10, 14, 14, 0));
Assert.IsEmpty(runner.Runs);
Assert.AreEqual(EngineMode.NotConnected, (await host.Monitor.GetSnapshotAsync()).Mode);
connected = true;
await bed.RunUntilAsync(EngineTestBed.Local(2026, 10, 14, 16, 0));
Assert.IsNotEmpty(runner.Runs);
}
[TestMethod]
public async Task CheckNowOutsideTheWindowNeedsConfirmationAndRunsOnlyThatCheck()
{
var night = EngineTestBed.Local(2026, 10, 14, 1, 0);
await using var bed = await EngineTestBed.CreateAsync(night);
var asked = await bed.AddAccountAsync("chiesto.demo", followed: false);
await bed.AddAccountAsync("altro.demo", followed: false, Frequency.High);
await bed.AddAccountAsync("seguito.demo", followed: true);
var runner = new ScriptedRunner(bed.Governor, bed.Clock);
var host = bed.Start(runner);
await bed.RunForAsync(TimeSpan.FromMinutes(20));
Assert.IsEmpty(runner.Runs, "Nothing at night on the engine's initiative.");
var first = await host.CheckNowAsync(asked.Id);
Assert.AreEqual(CheckNowStatus.NeedsConfirmation, first.Status);
Assert.IsNotNull(first.ConfirmationToken);
StringAssert.Contains(first.Message, "fuori dalla fascia");
Assert.AreEqual(CheckNowStatus.NeedsConfirmation, (await host.CheckNowAsync(asked.Id, "gettone-sbagliato")).Status);
var confirmed = await host.CheckNowAsync(asked.Id, first.ConfirmationToken);
Assert.AreEqual(CheckNowStatus.Queued, confirmed.Status);
await bed.RunForAsync(TimeSpan.FromHours(2));
Assert.IsNotEmpty(runner.Runs);
Assert.IsTrue(runner.Runs.All(r => r.Request.AccountId == asked.Id), "Only the confirmed check.");
Assert.IsTrue(runner.Runs.Any(r => r.Request.Kind == RecipeKind.ProfileCheck && r.Request.Manual));
Assert.HasCount(1, runner.Runs.Select(r => r.SessionId).Distinct().ToList());
var actions = await bed.Db.ActionLog.ListAsync(night, bed.Clock.Now);
Assert.IsTrue(actions.All(a => a.AccountId == asked.Id));
// The token was used: a second check needs a new confirmation.
Assert.AreEqual(CheckNowStatus.NeedsConfirmation, (await host.CheckNowAsync(asked.Id, first.ConfirmationToken)).Status);
// Normal work waits for the window.
var window = await bed.Services.Planner.GetWindowAsync(new DateOnly(2026, 10, 14));
await bed.RunUntilAsync(window!.Start + TimeSpan.FromHours(2));
Assert.IsTrue(runner.Runs.Where(r => r.Request.AccountId != asked.Id).All(r => r.At >= window.Start));
Assert.IsTrue(runner.Runs.Any(r => r.Request.AccountId != asked.Id));
}
[TestMethod]
public async Task CheckNowInsideTheWindowGoesOnTopOfTheQueueButAfterThePauseFloor()
{
await using var bed = await EngineTestBed.CreateAsync(Morning);
var asked = await bed.AddAccountAsync("chiesto.demo", followed: true, Frequency.Low);
var runner = new ScriptedRunner(bed.Governor, bed.Clock);
var host = bed.Start(runner);
await bed.RunUntilAsync(EngineTestBed.Local(2026, 10, 14, 12, 0));
var before = runner.Runs.Count(r => r.Request.Manual);
var askedAt = bed.Clock.Now;
var result = await host.CheckNowAsync(asked.Id);
Assert.AreEqual(CheckNowStatus.Queued, result.Status);
StringAssert.Contains(result.Message, "cima alla coda");
await bed.RunForAsync(TimeSpan.FromMinutes(45));
var manual = runner.Runs.Where(r => r.Request.Manual).ToList();
Assert.AreEqual(before + 2, manual.Count, "Profile check and stories, on request.");
var session = (await SessionsAsync(bed)).Single(s => s.Id == manual[^1].SessionId);
var previous = (await SessionsAsync(bed)).Where(s => s.EndedAt <= session.StartedAt).Max(s => s.EndedAt!.Value);
Assert.IsTrue(session.StartedAt - previous >= TimeSpan.FromMinutes(20));
if (session.StartedAt >= askedAt)
{
Assert.IsTrue(runner.Runs.First(r => r.SessionId == session.Id).Request.Manual, "First thing of the session.");
}
}
[TestMethod]
public async Task CheckNowWithTheBudgetExhaustedIsRefused()
{
await using var bed = await EngineTestBed.CreateAsync(Morning);
var asked = await bed.AddAccountAsync("chiesto.demo", followed: false);
for (var i = 0; i < 100; i++)
{
await bed.Db.ActionLog.AppendAsync(new ActionLogRecord { At = Morning.AddSeconds(i), Category = ActionKind.ProfileOpen });
}
var host = bed.Start(new ScriptedRunner(bed.Governor, bed.Clock));
await bed.RunUntilAsync(EngineTestBed.Local(2026, 10, 14, 12, 0));
var result = await host.CheckNowAsync(asked.Id);
Assert.AreEqual(CheckNowStatus.Refused, result.Status);
StringAssert.Contains(result.Message, "tetto giornaliero");
}
}
@@ -0,0 +1,127 @@
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Tests.Engine.Support;
namespace Febe.Tests.Engine;
[TestClass]
public sealed class EngineMonitorTests
{
[TestMethod]
public async Task AtNightTheMonitorSaysWhenWorkResumes()
{
var night = EngineTestBed.Local(2026, 10, 14, 2, 0);
await using var bed = await EngineTestBed.CreateAsync(night);
await bed.AddAccountAsync("marta.demo", followed: true);
var host = bed.Start(new ScriptedRunner(bed.Governor, bed.Clock));
await bed.RunForAsync(TimeSpan.FromMinutes(15));
var snapshot = await host.Monitor.GetSnapshotAsync();
Assert.AreEqual(EngineMode.OutsideWindow, snapshot.Mode);
Assert.AreEqual("Fuori fascia", snapshot.Headline);
StringAssert.Contains(snapshot.SidebarLine, "Riprende verso le ");
var window = await bed.Services.Planner.GetWindowAsync(new DateOnly(2026, 10, 14));
Assert.AreEqual(window!.Start, snapshot.ResumesAround);
Assert.IsNull(snapshot.Banner);
Assert.IsTrue(snapshot.Today.Spans.Any(s => s.Kind == StripSpanKind.OutsideWindow && s.Start == snapshot.Today.Start));
Assert.IsTrue(snapshot.Today.Spans.Any(s => s.Kind == StripSpanKind.PlannedSession && s.Indicative));
Assert.IsTrue(snapshot.Queue.All(q => q.When.StartsWith("verso le", StringComparison.Ordinal)));
Assert.AreEqual(4, snapshot.MainBudgets.Count);
CollectionAssert.AreEqual(
new[] { ActionKind.ProfileOpen, ActionKind.StoryView, ActionKind.BackfillPage, ActionKind.DataDownload },
snapshot.MainBudgets.Select(b => b.Kind).ToArray());
Assert.AreEqual(Enum.GetValues<ActionKind>().Length, snapshot.AllBudgets.Count);
Assert.AreEqual("Profili aperti", snapshot.ProfilesOpenedToday.Label);
Assert.AreEqual("di 100", snapshot.ProfilesOpenedToday.LimitText);
}
[TestMethod]
public async Task DuringTheDayTheStripShowsSessionsRestsAndTheSummary()
{
await using var bed = await EngineTestBed.CreateAsync(EngineTestBed.Local(2026, 10, 14, 6, 0));
await bed.AddAccountAsync("marta.demo", followed: true);
await bed.AddAccountAsync("luca.demo", followed: false, Frequency.High);
var host = bed.Start(new ScriptedRunner(bed.Governor, bed.Clock));
await bed.RunUntilAsync(EngineTestBed.Local(2026, 10, 14, 15, 0));
var snapshot = await host.Monitor.GetSnapshotAsync();
Assert.IsTrue(snapshot.Mode is EngineMode.Resting or EngineMode.InSession);
Assert.IsTrue(snapshot.Today.Spans.Count(s => s.Kind is StripSpanKind.Session or StripSpanKind.CurrentSession) >= 5);
Assert.IsTrue(snapshot.Today.Spans.Any(s => s.Kind == StripSpanKind.Rest));
StringAssert.Contains(snapshot.Today.Summary, "sessioni");
StringAssert.Contains(snapshot.Today.Summary, "nessun rallentamento");
Assert.IsNotEmpty(snapshot.RecentActions);
Assert.IsTrue(snapshot.RecentActions.Any(a => a.Title == "Giro dei profili che segui" || a.Title.StartsWith('@')));
if (snapshot.Mode == EngineMode.Resting)
{
Assert.AreEqual("In ascolto", snapshot.Headline);
StringAssert.StartsWith(snapshot.Details[0], "Riprende verso le ");
}
var profiles = snapshot.ProfilesOpenedToday;
Assert.IsTrue(profiles.UsedToday > 0);
StringAssert.StartsWith(profiles.Note, "In questa ora ");
}
[TestMethod]
public async Task AThrottleShowsAnAmberStripAndSuspendsTheQueue()
{
await using var bed = await EngineTestBed.CreateAsync();
await bed.AddAccountAsync("marta.demo", followed: true);
var host = bed.Start(new ScriptedRunner(bed.Governor, bed.Clock));
await bed.RunForAsync(TimeSpan.FromMinutes(1));
await bed.Breaker.ReportAsync(new Signal(SignalLevel.Throttle, "http-429", null, bed.Clock.Now));
var snapshot = await host.Monitor.GetSnapshotAsync();
Assert.AreEqual(EngineMode.Throttled, snapshot.Mode);
Assert.AreEqual(BannerLevel.Warning, snapshot.Banner!.Level);
StringAssert.Contains(snapshot.Banner.Message, "tetti dimezzati");
Assert.IsTrue(snapshot.Queue.All(q => q.Suspended && q.When == "Sospeso"));
Assert.IsTrue(snapshot.Today.Spans.Any(s => s.Kind == StripSpanKind.Throttle));
StringAssert.StartsWith(snapshot.ProfilesOpenedToday.Note, "Fermo dalle ");
StringAssert.Contains(snapshot.ReductionNote!, "Tetti dimezzati");
}
[TestMethod]
public async Task TheEventStreamDeliversTimelineLines()
{
await using var bed = await EngineTestBed.CreateAsync();
var host = bed.Start(new ScriptedRunner(bed.Governor, bed.Clock));
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(20));
var received = new List<EngineNotification>();
var reading = Task.Run(async () =>
{
await foreach (var notification in host.Monitor.SubscribeAsync(cts.Token))
{
received.Add(notification);
if (notification.Kind == EngineNotificationKind.Event && notification.Event!.Code == EngineEventCodes.Paused)
{
break;
}
}
});
await Task.Delay(100);
await host.PauseAsync();
await reading;
Assert.IsTrue(received.Any(n => n.Event?.Code == EngineEventCodes.Paused));
StringAssert.Contains(received.Last().Event!.Message, "Riprendi");
}
[TestMethod]
public void ItalianTextUsesDotsCommasAndVersoLe()
{
Assert.AreEqual("7.682", ItalianText.Number(7682));
Assert.AreEqual("1.234.567", ItalianText.Number(1234567));
Assert.AreEqual("1,3 GB", ItalianText.Bytes((long)(1.3 * 1024 * 1024 * 1024)));
Assert.AreEqual("0,5", ItalianText.Decimal(0.5));
var zone = EngineTestBed.Zone;
var now = EngineTestBed.Local(2026, 10, 14, 12, 0);
Assert.AreEqual("verso le 15:30", ItalianText.Around(EngineTestBed.Local(2026, 10, 14, 15, 30), now, zone));
Assert.AreEqual("domani verso le 7:42", ItalianText.Around(EngineTestBed.Local(2026, 10, 15, 7, 42), now, zone));
Assert.AreEqual("verso l'1:05", ItalianText.Around(EngineTestBed.Local(2026, 10, 14, 13, 5).AddHours(12), now.AddHours(12), zone));
Assert.AreEqual("1 ora e 20 minuti", ItalianText.Duration(TimeSpan.FromMinutes(80)));
Assert.AreEqual("ogni 75 minuti", ItalianText.Every(TimeSpan.FromMinutes(75)));
Assert.AreEqual("ogni 3 ore", ItalianText.Every(TimeSpan.FromHours(3)));
}
}
@@ -0,0 +1,95 @@
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Data;
using Febe.Tests.Support;
namespace Febe.Tests.Engine;
[TestClass]
public sealed class EngineSettingsTests
{
[TestMethod]
public async Task SettingsAreStoredAndReadBackWithACustomProfile()
{
using var folder = new TempFolder("impostazioni");
await using var db = await FebeDatabase.OpenAsync(folder.Combine("dati"));
Assert.AreEqual(CautionProfileKind.Prudent, (await EngineSettingsStore.LoadAsync(db.Settings)).ProfileKind, "«Prudente» is the default.");
var custom = CautionProfile.Balanced with
{
PauseMin = TimeSpan.FromMinutes(15),
WindowStart = new TimeOnly(8, 0),
WindowEnd = new TimeOnly(0, 30),
Budgets = new Dictionary<ActionKind, Budget>(CautionProfile.Balanced.Budgets) { [ActionKind.ProfileOpen] = new Budget(18, 150) },
};
var settings = new EngineSettings { Pace = GesturePace.Slow, GradualStart = false, ActiveDays = new HashSet<DayOfWeek> { DayOfWeek.Monday, DayOfWeek.Saturday } }
.WithCustomValues(custom);
await EngineSettingsStore.SaveAsync(db.Settings, settings);
var loaded = await EngineSettingsStore.LoadAsync(db.Settings);
Assert.AreEqual(CautionProfileKind.Custom, loaded.ProfileKind);
Assert.AreEqual(GesturePace.Slow, loaded.Pace);
Assert.IsFalse(loaded.GradualStart);
CollectionAssert.AreEquivalent(new[] { DayOfWeek.Monday, DayOfWeek.Saturday }, loaded.ActiveDays.ToArray());
var effective = loaded.EffectiveProfile;
Assert.AreEqual(CautionProfileKind.Custom, effective.Kind);
Assert.AreEqual(TimeSpan.FromMinutes(15), effective.PauseMin);
Assert.AreEqual(new TimeOnly(0, 30), effective.WindowEnd);
Assert.AreEqual(new Budget(18, 150), effective.Budgets[ActionKind.ProfileOpen]);
Assert.AreEqual(CautionProfile.Balanced.DataPerDayBytes, effective.DataPerDayBytes);
Assert.AreEqual(GesturePace.Slow, effective.Pace);
}
[TestMethod]
public void TheLimitsOfTheInterfaceAreEnforced()
{
var bad = CautionProfile.Fast with
{
PauseMin = TimeSpan.FromMinutes(4),
SessionMax = TimeSpan.FromMinutes(31),
WindowStart = new TimeOnly(5, 0),
WindowEnd = new TimeOnly(2, 0),
Budgets = new Dictionary<ActionKind, Budget>(CautionProfile.Fast.Budgets) { [ActionKind.StoryView] = new Budget(241, 800) },
DataPerDayBytes = CautionProfile.Limits.MaxDataPerDayBytes + 1,
};
var errors = CautionProfileRules.Validate(bad);
Assert.IsTrue(errors.Any(e => e.Contains("5 minuti", StringComparison.Ordinal)));
Assert.IsTrue(errors.Any(e => e.Contains("30 minuti", StringComparison.Ordinal)));
Assert.IsTrue(errors.Any(e => e.Contains("20 ore", StringComparison.Ordinal)));
Assert.IsTrue(errors.Any(e => e.Contains("storie viste", StringComparison.Ordinal)));
Assert.IsTrue(errors.Any(e => e.Contains("dati scaricati", StringComparison.Ordinal)));
Assert.HasCount(0, CautionProfileRules.Validate(CautionProfile.Fast));
Assert.HasCount(0, CautionProfileRules.Validate(CautionProfile.Prudent));
Assert.HasCount(0, CautionProfileRules.Validate(CautionProfile.Balanced));
Assert.AreEqual(TimeSpan.FromHours(18), CautionProfileRules.WindowLength(new TimeOnly(6, 30), new TimeOnly(0, 30)));
}
[TestMethod]
public async Task InvalidSettingsAreNotStored()
{
using var folder = new TempFolder("impostazioni");
await using var db = await FebeDatabase.OpenAsync(folder.Combine("dati"));
var settings = new EngineSettings().WithCustomValues(CautionProfile.Prudent with { PauseMin = TimeSpan.FromMinutes(1) });
var error = await Assert.ThrowsAsync<ArgumentException>(() => EngineSettingsStore.SaveAsync(db.Settings, settings));
StringAssert.Contains(error.Message, "pausa minima");
Assert.IsNull(await db.Settings.GetAsync(EngineSettingKeys.Profile));
}
[TestMethod]
public void TheCustomProfileSurvivesTheJsonRoundTrip()
{
var custom = CautionProfile.Fast with { Kind = CautionProfileKind.Custom, WindowJitter = TimeSpan.FromMinutes(25), RampUpDays = 10 };
var decoded = CautionProfileCodec.TryDecode(CautionProfileCodec.Encode(custom));
Assert.IsNotNull(decoded);
Assert.AreEqual(custom.WindowJitter, decoded!.WindowJitter);
Assert.AreEqual(10, decoded.RampUpDays);
foreach (var (kind, budget) in custom.Budgets)
{
Assert.AreEqual(budget, decoded.Budgets[kind]);
}
Assert.IsNull(CautionProfileCodec.TryDecode("{non è json"));
Assert.IsNull(CautionProfileCodec.TryDecode("{}"));
}
}
@@ -0,0 +1,174 @@
using System.Text;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Simulation;
using Febe.Core.Storage;
using Febe.Data;
using Febe.Tests.Support;
namespace Febe.Tests.Engine;
[TestClass]
public sealed class EngineSimulationTests
{
private static async Task<SimulationReport> SimulateAsync(SimulationOptions options)
{
using var folder = new TempFolder("simula");
return await EngineSimulation.RunAsync(options, async ct => await FebeDatabase.OpenAsync(folder.Combine("dati"), ct));
}
[TestMethod]
[DataRow(CautionProfileKind.Prudent)]
[DataRow(CautionProfileKind.Balanced)]
[DataRow(CautionProfileKind.Fast)]
public async Task EveryProfileRunsAWeekWithoutExceedingAnyBudget(CautionProfileKind profile)
{
var report = await SimulateAsync(new SimulationOptions { Days = 7, Profile = profile, Seed = 3 });
Assert.AreEqual(0, report.Overruns, string.Join("\n", report.OverrunDetails));
Assert.AreEqual(0, report.OverrunsOfFullBudgets);
Assert.AreEqual(0, report.ActionsOutsideWindow);
Assert.AreEqual(0, report.PauseFloorViolations);
Assert.IsTrue(report.ShortestPause >= CautionProfile.For(profile).PauseMin);
Assert.IsTrue(report.SessionStartCv >= 0.35, $"CV {report.SessionStartCv}");
Assert.IsTrue(report.SessionsPerDayMean > 5);
Assert.IsTrue(report.BackfillStored > 0);
Assert.IsTrue(report.FollowedPosts.Count > 0 && report.Stories.Count > 0);
var text = report.ToText();
StringAssert.Contains(text, "Sessioni");
StringAssert.Contains(text, "superamenti dei tetti: 0");
StringAssert.Contains(text, "Storico di 2.000 post");
var csv = report.ToCsv();
Assert.HasCount(report.Days.Count + 1, csv.Split('\n', StringSplitOptions.RemoveEmptyEntries));
StringAssert.StartsWith(csv, "giorno;sessioni;");
}
[TestMethod]
public async Task HeavyDemandSmallDataBudgetAndFrequentThrottlesStillExceedNothing()
{
var custom = CautionProfile.Prudent with
{
Kind = CautionProfileKind.Custom,
DataPerDayBytes = 150L * 1024 * 1024,
Budgets = new Dictionary<ActionKind, Budget>(CautionProfile.Prudent.Budgets) { [ActionKind.StoryView] = new Budget(10, 40) },
};
var report = await SimulateAsync(new SimulationOptions
{
Days = 5,
Seed = 11,
Settings = new EngineSettings().WithCustomValues(custom),
World = new SimulatedWorldOptions
{
Seed = 11,
FollowedAccounts = 15,
NotFollowedAccounts = 25,
MeanPostsPerDay = 1.5,
StoryAccountShare = 1,
HistoricalPosts = 3000,
ThrottleProbabilityPerAction = 0.004,
FrequencyOf = _ => Frequency.High,
},
});
Assert.AreEqual(0, report.Overruns, string.Join("\n", report.OverrunDetails));
Assert.AreEqual(0, report.ActionsOutsideWindow);
Assert.AreEqual(0, report.PauseFloorViolations);
Assert.IsNotEmpty(report.Throttles);
var data = report.CategoryTotals.Single(c => c.Kind == ActionKind.DataDownload);
// Gradual start and throttles halve it: under pressure means near half of the full budget at least.
Assert.IsTrue(data.MaxPerDay > data.DailyLimit * 0.45, "The data budget was really under pressure.\n" + report.ToText());
Assert.IsTrue(data.MaxPerDay <= data.DailyLimit);
var stories = report.CategoryTotals.Single(c => c.Kind == ActionKind.StoryView);
Assert.IsTrue(stories.MaxPerDay <= 40);
var profiles = report.CategoryTotals.Single(c => c.Kind == ActionKind.ProfileOpen);
Assert.IsTrue(profiles.WorstHour >= 6, "The hourly profile budget (halved at first) was reached.");
Assert.IsTrue(profiles.WorstHour <= 12 && profiles.MaxPerDay <= 100);
}
[TestMethod]
[DataRow(true)]
[DataRow(false)]
public async Task WithStoriesOnEveryAccountGetsAtLeastThreeStoryChecksADay(bool sweepCoversFollowedStories)
{
var report = await SimulateAsync(new SimulationOptions
{
Days = 4,
Seed = 5,
Engine = EngineOptions.Default with { SweepCoversFollowedStories = sweepCoversFollowedStories },
World = new SimulatedWorldOptions
{
Seed = 5,
FollowedAccounts = 3,
NotFollowedAccounts = 3,
StoryAccountShare = 1,
HistoricalPosts = 0,
ThrottleProbabilityPerAction = 0,
FrequencyOf = i => i % 2 == 0 ? Frequency.Low : Frequency.Normal,
},
});
var stats = report.World;
foreach (var day in report.Days.Skip(1))
{
foreach (var account in report.WorldAccounts)
{
var explicitChecks = stats.StoryChecks.GetValueOrDefault((account.Id, day.Day));
var bySweep = account.Followed && sweepCoversFollowedStories ? stats.Sweeps.GetValueOrDefault(day.Day) : 0;
Assert.IsTrue(explicitChecks + bySweep >= 3, $"{account.Username} on {day.Day}: {explicitChecks} checks, {bySweep} sweeps");
}
}
Assert.AreEqual(0, report.MissedStories);
}
[TestMethod]
public async Task TheSameSeedGivesTheSameSimulation()
{
var first = await SimulateAsync(new SimulationOptions { Days = 2, Seed = 9 });
var second = await SimulateAsync(new SimulationOptions { Days = 2, Seed = 9 });
Assert.AreEqual(first.SessionCount, second.SessionCount);
Assert.AreEqual(first.VirtualEvents, second.VirtualEvents);
CollectionAssert.AreEqual(first.Days.Select(d => d.Actions[ActionKind.ProfileOpen]).ToList(), second.Days.Select(d => d.Actions[ActionKind.ProfileOpen]).ToList());
}
[TestMethod]
public async Task TheCsvIsUtf8WithBomAndSemicolons()
{
var report = await SimulateAsync(new SimulationOptions { Days = 1, Seed = 2 });
using var folder = new TempFolder("csv");
var path = folder.Combine("resoconto.csv");
await report.WriteCsvAsync(path);
var bytes = await File.ReadAllBytesAsync(path);
CollectionAssert.AreEqual(new byte[] { 0xEF, 0xBB, 0xBF }, bytes.Take(3).ToArray());
var text = Encoding.UTF8.GetString(bytes, 3, bytes.Length - 3);
StringAssert.Contains(text, "minuti di attività");
Assert.IsTrue(text.Split('\n')[1].Split(';').Length > 10);
}
[TestMethod]
public void TheCommandLineIsParsed()
{
Assert.IsTrue(Febe.Server.SimulateCommand.TryParse(["--simula", "30g", "--profilo", "equilibrato", "--csv", "x.csv", "--seme", "4"], out var options, out var csv, out _));
Assert.AreEqual(30, options.Days);
Assert.AreEqual(CautionProfileKind.Balanced, options.Profile);
Assert.AreEqual("x.csv", csv);
Assert.AreEqual(4, options.Seed);
Assert.IsFalse(Febe.Server.SimulateCommand.TryParse(["--simula", "trenta"], out _, out _, out var problem));
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");
}
[TestMethod]
public async Task TheCommandPrintsTheItalianReport()
{
using var output = new StringWriter();
using var error = new StringWriter();
var code = await Febe.Server.SimulateCommand.RunAsync(["--simula", "1g", "--profilo", "rapido"], output, error);
Assert.AreEqual(0, code, error.ToString());
StringAssert.Contains(output.ToString(), "profilo «Rapido»");
Assert.AreEqual(2, await Febe.Server.SimulateCommand.RunAsync(["--simula", "0g"], output, error));
}
}
+320
View File
@@ -0,0 +1,320 @@
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Tests.Engine.Support;
namespace Febe.Tests.Engine;
[TestClass]
public sealed class GovernorTests
{
[TestMethod]
public async Task GrantsInsideTheWindowDuringASessionAndRecordsTheAction()
{
await using var bed = await EngineTestBed.CreateAsync();
var account = await bed.AddAccountAsync("marta.demo", followed: false);
var session = await bed.BeginSessionAsync();
var permit = await bed.Governor.RequestAsync(ActionKind.ProfileOpen, account.Id, CancellationToken.None);
Assert.IsTrue(permit.Granted, permit.Message);
var logged = await bed.Db.ActionLog.ListAsync(bed.Clock.Now.AddMinutes(-1), bed.Clock.Now.AddMinutes(1));
Assert.HasCount(1, logged);
Assert.AreEqual(ActionKind.ProfileOpen, logged[0].Category);
Assert.AreEqual(account.Id, logged[0].AccountId);
Assert.AreEqual(session.SessionId, logged[0].SessionId);
Assert.AreEqual(1, session.ActionCount);
}
[TestMethod]
public async Task RefusesWithoutASession()
{
await using var bed = await EngineTestBed.CreateAsync();
var permit = await bed.Governor.RequestAsync(ActionKind.Home, null, CancellationToken.None);
Assert.IsFalse(permit.Granted);
Assert.AreEqual(DenialReason.NoSession, permit.Reason);
Assert.IsFalse(string.IsNullOrWhiteSpace(permit.Message));
Assert.HasCount(0, await bed.Db.ActionLog.ListAsync(bed.Clock.Now.AddDays(-1), bed.Clock.Now.AddDays(1)));
}
[TestMethod]
public async Task RefusesOutsideTheWindowWithTheNextWindowAsRetryTime()
{
await using var bed = await EngineTestBed.CreateAsync(EngineTestBed.Local(2026, 10, 14, 3, 0));
await bed.BeginSessionAsync();
var permit = await bed.Governor.RequestAsync(ActionKind.Home, null, CancellationToken.None);
Assert.AreEqual(DenialReason.OutsideActiveWindow, permit.Reason);
Assert.IsNotNull(permit.RetryAfter);
var window = await bed.Services.Planner.GetWindowAsync(new DateOnly(2026, 10, 14));
Assert.AreEqual(window!.Start, permit.RetryAfter);
StringAssert.Contains(permit.Message!, "verso le");
}
[TestMethod]
public async Task TheBreakerIsCheckedFirst()
{
await using var bed = await EngineTestBed.CreateAsync(EngineTestBed.Local(2026, 10, 14, 3, 0));
await bed.Breaker.ReportAsync(new Signal(SignalLevel.Challenge, "challenge-url", "https://sito.prova/challenge", bed.Clock.Now));
// Outside the window and without a session too: the breaker comes first.
var permit = await bed.Governor.RequestAsync(ActionKind.Home, null, CancellationToken.None);
Assert.AreEqual(DenialReason.BreakerOpen, permit.Reason);
StringAssert.Contains(permit.Message!, "verifica");
}
[TestMethod]
public async Task PauseAndAlbertoAtTheBrowserRefuse()
{
var driving = false;
await using var bed = await EngineTestBed.CreateAsync(userIsDriving: () => driving);
await bed.BeginSessionAsync();
bed.Runtime.IsPaused = true;
Assert.AreEqual(DenialReason.Paused, (await bed.Governor.RequestAsync(ActionKind.Home, null, CancellationToken.None)).Reason);
bed.Runtime.IsPaused = false;
driving = true;
Assert.AreEqual(DenialReason.UserIsDriving, (await bed.Governor.RequestAsync(ActionKind.Home, null, CancellationToken.None)).Reason);
driving = false;
Assert.IsTrue((await bed.Governor.RequestAsync(ActionKind.Home, null, CancellationToken.None)).Granted);
}
[TestMethod]
public async Task TheHourlyBudgetIsARolling60MinuteWindow()
{
await using var bed = await EngineTestBed.CreateAsync();
bed.Clock.AutoAdvance = true;
await bed.BeginSessionAsync();
var first = bed.Clock.Now;
// «Prudente»: 4 home pages per hour.
for (var i = 0; i < 4; i++)
{
Assert.IsTrue((await bed.Governor.RequestAsync(ActionKind.Home, null, CancellationToken.None)).Granted);
}
var denied = await bed.Governor.RequestAsync(ActionKind.Home, null, CancellationToken.None);
Assert.AreEqual(DenialReason.HourlyBudgetReached, denied.Reason);
Assert.AreEqual(first + TimeSpan.FromHours(1), denied.RetryAfter);
StringAssert.Contains(denied.Message!, "tetto orario");
// Other categories go on.
Assert.IsTrue((await bed.Governor.RequestAsync(ActionKind.StoryView, null, CancellationToken.None)).Granted);
bed.Clock.AdvanceTo(first + TimeSpan.FromHours(1));
Assert.IsTrue((await bed.Governor.RequestAsync(ActionKind.Home, null, CancellationToken.None)).Granted);
}
[TestMethod]
public async Task TheDailyBudgetUsesTheLocalCalendarDayAndComesFromTheDatabase()
{
await using var bed = await EngineTestBed.CreateAsync();
var account = await bed.AddAccountAsync("luca.demo", followed: false);
var morning = EngineTestBed.Local(2026, 10, 14, 8, 0);
for (var i = 0; i < 100; i++)
{
await bed.Db.ActionLog.AppendAsync(new ActionLogRecord { At = morning.AddSeconds(i * 20), Category = ActionKind.ProfileOpen, AccountId = account.Id });
}
// Yesterday's actions do not count today.
await bed.Db.ActionLog.AppendAsync(new ActionLogRecord { At = morning.AddDays(-1), Category = ActionKind.StoryView });
await bed.BeginSessionAsync();
var denied = await bed.Governor.RequestAsync(ActionKind.ProfileOpen, account.Id, CancellationToken.None);
Assert.AreEqual(DenialReason.DailyBudgetReached, denied.Reason);
Assert.IsTrue(denied.RetryAfter >= EngineTestBed.Local(2026, 10, 15, 0, 0));
StringAssert.Contains(denied.Message!, "domani");
var events = await bed.Db.Events.ListAsync(new Febe.Core.Storage.EventQuery());
Assert.IsTrue(events.Any(e => e.Code == EngineEventCodes.BudgetReached));
}
[TestMethod]
[DataRow(GesturePace.Natural, 4000)]
[DataRow(GesturePace.Brisk, 3000)]
[DataRow(GesturePace.Slow, 5400)]
public async Task TheMinimumSpacingIsWaitedAndScaledByThePace(GesturePace pace, int spacingMs)
{
await using var bed = await EngineTestBed.CreateAsync(settings: new EngineSettings { GradualStart = false, Pace = pace });
bed.Clock.AutoAdvance = true;
await bed.BeginSessionAsync();
Assert.IsTrue((await bed.Governor.RequestAsync(ActionKind.StoryView, null, CancellationToken.None)).Granted);
var evaluation = await bed.Governor.EvaluateAsync(ActionKind.StoryView, null);
Assert.AreEqual(DenialReason.MinimumSpacing, evaluation.Reason);
Assert.IsTrue((await bed.Governor.RequestAsync(ActionKind.StoryView, null, CancellationToken.None)).Granted);
var log = await bed.Db.ActionLog.ListAsync(bed.Clock.Now.AddHours(-1), bed.Clock.Now.AddSeconds(1));
Assert.HasCount(2, log);
Assert.AreEqual(TimeSpan.FromMilliseconds(spacingMs), log[1].At - log[0].At);
}
[TestMethod]
public async Task TheAccountBackfillLimitCountsPostsDiscoveredToday()
{
await using var bed = await EngineTestBed.CreateAsync();
var account = await bed.AddAccountAsync("storico.demo", followed: true, state: AccountState.Backfilling, backfillPerDay: 24);
for (var i = 0; i < 24; i++)
{
await bed.Db.Entries.AddAsync(
new Entry { AccountId = account.Id, Kind = EntryKind.Post, InstagramId = "p" + i, PublishedAt = bed.Clock.Now.AddDays(-100 - i), DiscoveredAt = bed.Clock.Now.AddMinutes(-30) },
[new Media { Position = 1, Kind = MediaKind.Photo }]);
}
await bed.BeginSessionAsync();
var denied = await bed.Governor.RequestAsync(ActionKind.BackfillPage, account.Id, CancellationToken.None);
Assert.AreEqual(DenialReason.AccountLimitReached, denied.Reason);
StringAssert.Contains(denied.Message!, "@storico.demo");
// Other categories of the same account are not limited by the backfill limit.
Assert.IsTrue((await bed.Governor.RequestAsync(ActionKind.ProfileOpen, account.Id, CancellationToken.None)).Granted);
}
[TestMethod]
public async Task AccountsThatMustNotBeContactedAreRefused()
{
await using var bed = await EngineTestBed.CreateAsync();
var archive = await bed.AddAccountAsync("archivio.demo", followed: false, state: AccountState.ArchiveOnly);
var paused = await bed.AddAccountAsync("pausa.demo", followed: false, state: AccountState.Paused);
var session = await bed.BeginSessionAsync();
Assert.AreEqual(DenialReason.AccountNotContactable, (await bed.Governor.RequestAsync(ActionKind.ProfileOpen, archive.Id, CancellationToken.None)).Reason);
Assert.AreEqual(DenialReason.AccountNotContactable, (await bed.Governor.RequestAsync(ActionKind.ProfileOpen, paused.Id, CancellationToken.None)).Reason);
// «Controlla ora» on a paused account is allowed; on an archive-only one never.
session.ManualAccountId = paused.Id;
Assert.IsTrue((await bed.Governor.RequestAsync(ActionKind.ProfileOpen, paused.Id, CancellationToken.None)).Granted);
session.ManualAccountId = archive.Id;
bed.Clock.Advance(TimeSpan.FromSeconds(10));
Assert.AreEqual(DenialReason.AccountNotContactable, (await bed.Governor.RequestAsync(ActionKind.ProfileOpen, archive.Id, CancellationToken.None)).Reason);
}
[TestMethod]
public async Task AConfirmedManualCheckOutsideTheWindowAllowsOnlyThatAccount()
{
await using var bed = await EngineTestBed.CreateAsync(EngineTestBed.Local(2026, 10, 14, 2, 0));
var asked = await bed.AddAccountAsync("chiesto.demo", followed: false);
var other = await bed.AddAccountAsync("altro.demo", followed: false);
await bed.BeginSessionAsync(outsideWindowAccountId: asked.Id);
Assert.IsTrue((await bed.Governor.RequestAsync(ActionKind.ProfileOpen, asked.Id, CancellationToken.None)).Granted);
bed.Clock.Advance(TimeSpan.FromSeconds(10));
Assert.AreEqual(DenialReason.OutsideActiveWindow, (await bed.Governor.RequestAsync(ActionKind.ProfileOpen, other.Id, CancellationToken.None)).Reason);
Assert.AreEqual(DenialReason.OutsideActiveWindow, (await bed.Governor.RequestAsync(ActionKind.Home, null, CancellationToken.None)).Reason);
}
[TestMethod]
public void TheGradualStartGoesFromHalfToFullLinearly()
{
var profile = CautionProfile.Prudent;
var start = EngineTestBed.Noon;
Assert.AreEqual(0.5, BudgetLimits.GradualStartFactor(profile, start, start), 1e-9);
Assert.AreEqual(0.75, BudgetLimits.GradualStartFactor(profile, start, start.AddDays(3.5)), 1e-9);
Assert.AreEqual(1.0, BudgetLimits.GradualStartFactor(profile, start, start.AddDays(7)), 1e-9);
Assert.AreEqual(1.0, BudgetLimits.GradualStartFactor(profile with { GradualStart = false }, start, start), 1e-9);
var budgets = BudgetLimits.Compute(profile, start, null, start);
Assert.AreEqual(BudgetReduction.GradualStart, budgets.Reduction);
Assert.AreEqual(new Budget(6, 50), budgets.Budgets[ActionKind.ProfileOpen]);
Assert.AreEqual(2L * 1024 * 1024 * 1024, budgets.DataPerDayBytes);
Assert.AreEqual(150, budgets.BackfillPostsPerAccountPerDay);
}
[TestMethod]
public void TheStrongestReductionWinsNeverTheProduct()
{
var profile = CautionProfile.Prudent;
var start = EngineTestBed.Noon;
var now = start.AddDays(2);
var halvedUntil = now.AddHours(10);
var both = BudgetLimits.Compute(profile, start, halvedUntil, now);
Assert.AreEqual(0.5, both.Factor, 1e-9, "Halved (0.5) is stronger than the ramp at day 2 (0.64): 0.5, not 0.32.");
Assert.AreEqual(BudgetReduction.HalvedAfterThrottle, both.Reduction);
Assert.AreEqual(new Budget(6, 50), both.Budgets[ActionKind.ProfileOpen]);
var rampOnly = BudgetLimits.Compute(profile, start, halvedUntil, halvedUntil);
Assert.AreEqual(0.5 + (0.5 * (2 + (10.0 / 24)) / 7), rampOnly.Factor, 1e-9);
Assert.AreEqual(BudgetReduction.GradualStart, rampOnly.Reduction);
var none = BudgetLimits.Compute(profile, start, halvedUntil, start.AddDays(8));
Assert.AreEqual(1, none.Factor);
Assert.AreEqual(BudgetReduction.None, none.Reduction);
}
[TestMethod]
public async Task HalvedBudgetsApplyAfterAThrottle()
{
await using var bed = await EngineTestBed.CreateAsync();
await bed.Breaker.ReportAsync(new Signal(SignalLevel.Throttle, "http-429", null, bed.Clock.Now));
bed.Clock.Advance(TimeSpan.FromHours(1));
var budgets = bed.Governor.GetEffectiveBudgets(bed.Clock.Now);
Assert.AreEqual(BudgetReduction.HalvedAfterThrottle, budgets.Reduction);
Assert.AreEqual(new Budget(2, 15), budgets.Budgets[ActionKind.Home]);
bed.Clock.Advance(TimeSpan.FromHours(48));
Assert.AreEqual(BudgetReduction.None, bed.Governor.GetEffectiveBudgets(bed.Clock.Now).Reduction);
}
[TestMethod]
public async Task TheDataBudgetIsDailyInBytesAndWorksDuringAStop()
{
await using var bed = await EngineTestBed.CreateAsync();
var full = 4L * 1024 * 1024 * 1024;
Assert.AreEqual(full, await bed.Governor.RemainingTodayAsync(CancellationToken.None));
// After a throttle the data budget is halved too.
await bed.Breaker.ReportAsync(new Signal(SignalLevel.Throttle, "http-429", null, bed.Clock.Now));
Assert.AreEqual(full / 2, await bed.Governor.RemainingTodayAsync(CancellationToken.None));
await bed.Governor.RecordAsync((full / 2) - 1000, null, CancellationToken.None);
Assert.AreEqual(1000L, await bed.Governor.RemainingTodayAsync(CancellationToken.None));
// Queued downloads may complete during a stop: the data budget does not look at the breaker.
Assert.IsTrue((await bed.Governor.RequestAsync(ActionKind.DataDownload, null, CancellationToken.None)).Granted);
await bed.Governor.RecordAsync(1000, null, CancellationToken.None);
var denied = await bed.Governor.RequestAsync(ActionKind.DataDownload, null, CancellationToken.None);
Assert.AreEqual(DenialReason.DailyBudgetReached, denied.Reason);
Assert.AreEqual(0L, await bed.Governor.RemainingTodayAsync(CancellationToken.None));
bed.Clock.AdvanceTo(EngineTestBed.Local(2026, 10, 15, 0, 0));
Assert.IsTrue(await bed.Governor.RemainingTodayAsync(CancellationToken.None) > 0);
}
[TestMethod]
public async Task RemainingSaysHowMuchRoomIsLeft()
{
await using var bed = await EngineTestBed.CreateAsync();
bed.Clock.AutoAdvance = true;
await bed.BeginSessionAsync();
Assert.AreEqual(50L, await bed.Governor.RemainingAsync(ActionKind.StoryView));
for (var i = 0; i < 45; i++)
{
await bed.Governor.RequestAsync(ActionKind.StoryView, null, CancellationToken.None);
}
Assert.AreEqual(5L, await bed.Governor.RemainingAsync(ActionKind.StoryView), "Not room for ten stories in this hour.");
}
[TestMethod]
public async Task BudgetsTurnAmberFrom80Percent()
{
await using var bed = await EngineTestBed.CreateAsync();
bed.Clock.AutoAdvance = true;
await bed.BeginSessionAsync();
for (var i = 0; i < 3; i++)
{
await bed.Governor.RequestAsync(ActionKind.Home, null, CancellationToken.None);
}
var statuses = await bed.Governor.GetBudgetStatusAsync();
var home = statuses.Single(s => s.Kind == ActionKind.Home);
Assert.AreEqual(3L, home.UsedLastHour);
Assert.IsFalse(home.IsAmber, "3 of 4 is 75%.");
await bed.Governor.RequestAsync(ActionKind.Home, null, CancellationToken.None);
home = (await bed.Governor.GetBudgetStatusAsync()).Single(s => s.Kind == ActionKind.Home);
Assert.IsTrue(home.IsAmber);
Assert.IsTrue(home.HourlyReached);
Assert.IsFalse(statuses.Single(s => s.Kind == ActionKind.StoryView).IsAmber);
}
}
@@ -0,0 +1,71 @@
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Storage;
namespace Febe.Tests.Engine.Support;
/// <summary>
/// Independent check of the budgets from <c>action_log</c>: at every action, the rolling hour and the local day so far
/// must stay within the profile's full limits (reductions only make them lower).
/// </summary>
internal static class BudgetAudit
{
private static readonly TimeSpan Hour = TimeSpan.FromMinutes(60);
public static async Task<IReadOnlyList<string>> OverrunsAsync(IFebeStorage storage, CautionProfile profile, TimeZoneInfo zone, DateTimeOffset from, DateTimeOffset to)
{
var actions = await storage.ActionLog.ListAsync(from, to);
var problems = new List<string>();
foreach (var kind in Enum.GetValues<ActionKind>())
{
var list = actions.Where(a => a.Category == kind).OrderBy(a => a.At).ThenBy(a => a.Id).ToList();
var first = 0;
long hour = 0;
long day = 0;
DateOnly? current = null;
foreach (var action in list)
{
hour += action.Amount;
while (list[first].At <= action.At - Hour)
{
hour -= list[first].Amount;
first++;
}
var today = LocalCalendar.Today(action.At, zone);
if (today != current)
{
current = today;
day = 0;
}
day += action.Amount;
var over = kind == ActionKind.DataDownload
? day > profile.DataPerDayBytes
: hour > profile.Budgets[kind].PerHour || day > profile.Budgets[kind].PerDay;
if (over)
{
problems.Add($"{kind} at {action.At:O}: hour {hour}, day {day}");
}
}
}
return problems;
}
/// <summary>Actions (data excluded) that fall outside the active window of their day.</summary>
public static async Task<IReadOnlyList<ActionLogRecord>> OutsideWindowAsync(IFebeStorage storage, DayPlanner planner, DateTimeOffset from, DateTimeOffset to)
{
var outside = new List<ActionLogRecord>();
foreach (var action in (await storage.ActionLog.ListAsync(from, to)).Where(a => a.Category != ActionKind.DataDownload))
{
if (await planner.GetWindowAtAsync(action.At) is null)
{
outside.Add(action);
}
}
return outside;
}
}
@@ -0,0 +1,172 @@
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Simulation;
using Febe.Data;
using Febe.Tests.Support;
namespace Febe.Tests.Engine.Support;
/// <summary>
/// A temporary database, a virtual clock in Rome's zone and the engine services on top, with a fixed seed.
/// <see cref="ReopenAsync"/> builds new engine objects on the same database, as a restart of the program does.
/// </summary>
internal sealed class EngineTestBed : IAsyncDisposable
{
private readonly TempFolder _folder;
private EngineHost? _host;
private CancellationTokenSource? _loopCts;
private Task? _loop;
private EngineTestBed(TempFolder folder, FebeDatabase db, VirtualClock clock, EngineServices services, EngineOptions options, int seed)
{
_folder = folder;
Db = db;
Clock = clock;
Services = services;
Options = options;
Seed = seed;
}
public static TimeZoneInfo Zone => SimulationZones.Rome;
/// <summary>Wednesday 14 October 2026 at 12:00 in Rome: inside every profile's window whatever the daily shift.</summary>
public static DateTimeOffset Noon { get; } = Local(2026, 10, 14, 12, 0);
public FebeDatabase Db { get; }
public VirtualClock Clock { get; }
public EngineServices Services { get; private set; }
public EngineOptions Options { get; }
public int Seed { get; }
public Governor Governor => Services.Governor;
public CircuitBreaker Breaker => Services.Breaker;
public EngineRuntime Runtime => Services.Runtime;
public static DateTimeOffset Local(int year, int month, int day, int hour, int minute) =>
LocalCalendar.FromLocal(new DateTime(year, month, day, hour, minute, 0), Zone);
/// <summary>A bed with the given profile; the gradual start is off unless asked, so budgets are the profile's.</summary>
public static async Task<EngineTestBed> CreateAsync(
DateTimeOffset? start = null,
CautionProfileKind profile = CautionProfileKind.Prudent,
bool gradualStart = false,
int seed = 7,
EngineOptions? options = null,
EngineSettings? settings = null,
Func<bool>? userIsDriving = null,
Func<bool>? isConnected = null)
{
var folder = new TempFolder("motore");
var db = await FebeDatabase.OpenAsync(folder.Combine("dati"));
var clock = new VirtualClock(start ?? Noon, Zone);
settings ??= new EngineSettings { ProfileKind = profile, GradualStart = gradualStart };
await EngineSettingsStore.SaveAsync(db.Settings, settings);
options ??= EngineOptions.Default;
var services = await EngineServices.CreateAsync(db, clock, new SeededRandom(seed), options, userIsDriving, isConnected);
return new EngineTestBed(folder, db, clock, services, options, seed);
}
/// <summary>New engine objects on the same database (a restart), with a different random stream.</summary>
public async Task<EngineServices> ReopenAsync(int seed, Func<bool>? userIsDriving = null)
{
await StopAsync();
Services = await EngineServices.CreateAsync(Db, Clock, new SeededRandom(seed), Options, userIsDriving);
return Services;
}
public async Task<Account> AddAccountAsync(
string username,
bool followed,
Frequency frequency = Frequency.Normal,
AccountState state = AccountState.UpToDate,
ContentTypes? types = null,
int? postCount = null,
int? backfillPerDay = null)
{
var account = Account.Create(username, StartingPoint.EverythingAndKeepUpdated, Clock.Now, Zone, Runtime.Profile) with
{
InstagramId = "77" + ((uint)username.GetHashCode(StringComparison.Ordinal)).ToString(System.Globalization.CultureInfo.InvariantCulture),
IsFollowed = followed,
Frequency = frequency,
State = state,
BackfillCompletedAt = state == AccountState.Backfilling ? null : Clock.Now,
PostCount = postCount,
};
if (types is { } t)
{
account = account with { ContentTypes = t };
}
if (backfillPerDay is { } perDay)
{
account = account with { Limits = account.Limits with { BackfillPostsPerDay = perDay } };
}
return await Db.Accounts.AddAsync(account);
}
/// <summary>A session as the engine opens it, for testing the Governor alone.</summary>
public async Task<SessionContext> BeginSessionAsync(long? outsideWindowAccountId = null)
{
var record = await Db.Sessions.StartAsync(Clock.Now);
var session = new SessionContext(record.Id, 1, Clock.Now, Clock.Now + TimeSpan.FromMinutes(10), outsideWindowAccountId);
Runtime.CurrentSession = session;
return session;
}
/// <summary>Starts the engine loop on the virtual clock (no time passes until <see cref="RunUntilAsync"/>).</summary>
public EngineHost Start(IRecipeRunner runner)
{
_host = new EngineHost(Services, runner);
_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>
public Task RunUntilAsync(DateTimeOffset target) =>
_loop is null ? Task.Run(() => Clock.AdvanceTo(target)) : Clock.RunUntilAsync(target, CancellationToken.None, _loop);
public Task RunForAsync(TimeSpan span) => RunUntilAsync(Clock.Now + span);
/// <summary>Stops the loop as a shutdown would (a session in progress ends interrupted).</summary>
public async Task StopAsync()
{
if (_loop is null)
{
return;
}
await _loopCts!.CancelAsync();
try
{
await _loop;
}
catch (OperationCanceledException)
{
}
await _host!.DisposeAsync();
_loopCts.Dispose();
_loop = null;
_loopCts = null;
_host = null;
await Breaker.FlushAsync();
}
public async ValueTask DisposeAsync()
{
await StopAsync();
await Db.DisposeAsync();
_folder.Dispose();
}
}
@@ -0,0 +1,101 @@
using Febe.Core.Abstractions;
using Febe.Core.Engine;
namespace Febe.Tests.Engine.Support;
/// <summary>A recipe run seen by <see cref="ScriptedRunner"/>.</summary>
internal sealed record RunRecord(DateTimeOffset At, RecipeRequest Request, long SessionId, RecipeStatus Status);
/// <summary>
/// A recipe runner for engine tests: asks the Governor for one counted action like the real recipes (stories:
/// none, as if no story was active), spends a little virtual time and completes, unless <see cref="Script"/> says
/// otherwise. Records every run.
/// </summary>
internal sealed class ScriptedRunner(IGovernor governor, IClock clock) : IRecipeRunner
{
private readonly Lock _gate = new();
private readonly List<RunRecord> _runs = [];
/// <summary>Forced outcome for a request (null: default behaviour). Runs before the Governor is asked.</summary>
public Func<RecipeRequest, RecipeOutcome?>? Script { get; set; }
/// <summary>Called after the counted action was granted (e.g. to report a signal).</summary>
public Action<RecipeRequest>? AfterGrant { get; set; }
/// <summary>Accounts the stories bar flags in every sweep.</summary>
public IReadOnlyList<long> FlaggedStories { get; set; } = [];
public int Rests { get; private set; }
public IReadOnlyList<RunRecord> Runs
{
get
{
lock (_gate)
{
return [.. _runs];
}
}
}
public async Task<RecipeOutcome> RunAsync(RecipeRequest request, ISessionContext session, CancellationToken ct)
{
RecipeOutcome outcome;
try
{
outcome = Script?.Invoke(request) ?? await DefaultAsync(request, ct);
}
catch (OperationCanceledException)
{
lock (_gate)
{
_runs.Add(new RunRecord(clock.Now, request, session.SessionId, RecipeStatus.Cancelled));
}
throw;
}
lock (_gate)
{
_runs.Add(new RunRecord(clock.Now, request, session.SessionId, outcome.Status));
}
return outcome;
}
public Task RestAsync(CancellationToken ct)
{
Rests++;
return Task.CompletedTask;
}
private async Task<RecipeOutcome> DefaultAsync(RecipeRequest request, CancellationToken ct)
{
if (request.Kind == RecipeKind.AccountStories)
{
await clock.Delay(TimeSpan.FromSeconds(2), ct);
return new RecipeOutcome(RecipeStatus.Completed, 0, 0);
}
var kind = CheckPolicy.CategoryOf(request.Kind);
var pages = request.Kind == RecipeKind.Backfill ? Math.Max(1, request.MaxPages ?? 1) : 1;
var counted = 0;
for (var i = 0; i < pages; i++)
{
var permit = await governor.RequestAsync(kind, request.AccountId, ct);
if (!permit.Granted)
{
return new RecipeOutcome(counted > 0 ? RecipeStatus.Completed : RecipeStatus.Denied, counted, 0);
}
counted++;
AfterGrant?.Invoke(request);
await clock.Delay(TimeSpan.FromSeconds(5), ct);
}
return new RecipeOutcome(RecipeStatus.Completed, counted, 0)
{
AccountsWithStories = request.Kind == RecipeKind.FollowingSweep ? FlaggedStories : [],
};
}
}
@@ -0,0 +1,93 @@
using Febe.Core.Simulation;
namespace Febe.Tests.Engine;
[TestClass]
public sealed class VirtualClockTests
{
private static readonly DateTimeOffset Start = new(2026, 10, 14, 10, 0, 0, TimeSpan.Zero);
[TestMethod]
public async Task DelaysCompleteOnlyWhenTimeReachesThem()
{
var clock = new VirtualClock(Start);
var late = clock.Delay(TimeSpan.FromMinutes(10), CancellationToken.None);
var early = clock.Delay(TimeSpan.FromMinutes(5), CancellationToken.None);
Assert.AreEqual(2, clock.PendingTimers);
Assert.IsFalse(early.IsCompleted);
clock.Advance(TimeSpan.FromMinutes(6));
await early;
Assert.IsFalse(late.IsCompleted);
Assert.AreEqual(Start.AddMinutes(6), clock.Now);
clock.Advance(TimeSpan.FromMinutes(10));
await late;
Assert.AreEqual(0, clock.PendingTimers);
}
[TestMethod]
public async Task ACancelledDelayLeavesTheQueue()
{
var clock = new VirtualClock(Start);
using var cts = new CancellationTokenSource();
var delay = clock.Delay(TimeSpan.FromHours(1), cts.Token);
Assert.AreEqual(1, clock.PendingTimers);
await cts.CancelAsync();
Assert.AreEqual(0, clock.PendingTimers);
await Assert.ThrowsAsync<TaskCanceledException>(() => delay);
}
[TestMethod]
public async Task RunUntilJumpsFromTimerToTimerWhileTheActorWaits()
{
var clock = new VirtualClock(Start);
var seen = new List<DateTimeOffset>();
using var cts = new CancellationTokenSource();
async Task Actor()
{
for (var i = 0; i < 5; i++)
{
await Task.Yield();
await clock.Delay(TimeSpan.FromMinutes(30), cts.Token);
seen.Add(clock.Now);
}
await clock.Delay(TimeSpan.FromDays(10), cts.Token);
}
var actor = Actor();
await clock.RunUntilAsync(Start.AddHours(2), CancellationToken.None, actor);
Assert.AreEqual(Start.AddHours(2), clock.Now);
CollectionAssert.AreEqual(new[] { Start.AddMinutes(30), Start.AddMinutes(60), Start.AddMinutes(90), Start.AddMinutes(120) }, seen);
await clock.RunUntilAsync(Start.AddHours(3), CancellationToken.None, actor);
Assert.HasCount(5, seen);
await cts.CancelAsync();
await Assert.ThrowsAsync<TaskCanceledException>(() => actor);
}
[TestMethod]
public async Task AFailingActorStopsTheRun()
{
var clock = new VirtualClock(Start);
async Task Actor()
{
await clock.Delay(TimeSpan.FromMinutes(1), CancellationToken.None);
throw new InvalidOperationException("guasto");
}
var actor = Actor();
await Assert.ThrowsAsync<InvalidOperationException>(() => clock.RunUntilAsync(Start.AddHours(1), CancellationToken.None, actor));
}
[TestMethod]
public async Task AutoAdvanceMovesTimeAtOnceAndRoundsToMilliseconds()
{
var clock = new VirtualClock(Start) { AutoAdvance = true };
await clock.Delay(TimeSpan.FromTicks(1), CancellationToken.None);
Assert.AreEqual(Start.AddMilliseconds(1), clock.Now);
await clock.Delay(TimeSpan.FromSeconds(4), CancellationToken.None);
Assert.AreEqual(Start.AddMilliseconds(4001), clock.Now);
}
}