using System.Net; using System.Text.Json; using Febe.Core.Abstractions; using Febe.Core.Alerts; using Febe.Core.Domain; using Febe.Core.Engine; using Febe.Core.Storage; using Febe.Tests.Alerts.Support; using Febe.Tests.Engine.Support; using Febe.Tests.Web.Support; using Microsoft.Extensions.DependencyInjection; namespace Febe.Tests.Alerts; /// /// The alerts of spec §13.3 (milestone M8): a stop reaches the strip of the interface, the Windows notification and /// Telegram; throttles, backfills, unknown formats and full disks are alerts too; the same alert is not repeated; /// the bot token never leaves the request to Telegram. Telegram is always a fake handler: never the real API. /// [TestClass] public sealed class AlertServiceTests { private static readonly DateTimeOffset Morning = EngineTestBed.Local(2026, 10, 14, 6, 0); public TestContext TestContext { get; set; } = null!; /// M8, «Fatto quando»: un arresto simulato produce striscia, notifica e messaggio. [TestMethod] public async Task AStopForVerificationProducesTheStripTheNotificationAndTheTelegramMessage() { await using var bed = await AlertBed.CreateAsync(); await using var host = new EngineHost(bed.Engine.Services, new ScriptedRunner(bed.Engine.Governor, bed.Engine.Clock)); await using var web = await WebTestServer.StartAsync(services: s => { s.AddSingleton(bed.Engine.Db); s.AddSingleton(bed.Engine.Clock); s.AddSingleton(host.Monitor); }); await bed.ReportAsync(SignalLevel.Challenge, "challenge-url"); // The strip of the interface: what the page reads from /api/engine (mockup 11). var engine = await web.GetJsonAsync("/api/engine"); var snapshot = engine.GetProperty("snapshot"); Assert.AreEqual("StoppedForVerification", snapshot.Str("mode")); var banner = snapshot.GetProperty("banner"); Assert.AreEqual("Error", banner.Str("level")); Assert.AreEqual("Instagram chiede una verifica", banner.Str("title")); Assert.IsTrue(banner.Bool("needsResume")); StringAssert.Contains(banner.Str("message"), "«Riprendi»"); // The Windows notification, through the shell of the desktop. var notification = bed.Shell.Notifications.Single(); Assert.AreEqual("Instagram chiede una verifica", notification.Title); Assert.AreEqual( "Ho fermato tutto alle 12:00 e non riparto da solo. Che cosa fare: apri Febe, poi il browser di Febe («Apri il browser»), completa la verifica a mano e premi «Riprendi».", notification.Message); // One HTTPS POST to the Bot API, JSON, with the chat and the Italian text. var request = bed.Telegram.Requests.Single(); Assert.AreEqual(HttpMethod.Post, request.Method); Assert.AreEqual($"https://api.telegram.org/bot{AlertBed.Token}/sendMessage", request.Uri.AbsoluteUri); Assert.AreEqual("application/json", request.ContentType); Assert.AreEqual(AlertBed.Chat, request.ChatId); Assert.AreEqual("Febe · Instagram chiede una verifica\n" + notification.Message, request.Text); // The «Avvisi» list of Attività has the line too. var alerts = await web.GetJsonAsync("/api/alerts"); var item = alerts.GetProperty("items").EnumerateArray().Single(); Assert.AreEqual("verification", item.Str("kind")); Assert.AreEqual("error", item.Str("level")); Assert.AreEqual("Instagram chiede una verifica", item.Str("title")); Assert.AreEqual(AlertOutcomeKind.Sent, bed.Outcomes.Single().Kind); StringAssert.Contains(bed.Log.All, "Avviso «Instagram chiede una verifica» inviato: notifica di Windows, Telegram."); var written = await bed.EverythingWrittenAsync(); Assert.DoesNotContain(AlertBed.Token, written); Assert.DoesNotContain("api.telegram.org", written); } [TestMethod] public async Task ADisconnectionSaysToLogInAgain() { await using var bed = await AlertBed.CreateAsync(windows: false); await bed.ReportAsync(SignalLevel.Disconnect, "cookie-mancante"); Assert.IsEmpty(bed.Shell.Notifications, "Windows notifications switched off"); var text = bed.Telegram.Requests.Single().Text; StringAssert.StartsWith(text, "Febe · Instagram ha chiuso la sessione\n"); StringAssert.Contains(text, "non provo a rientrare"); StringAssert.Contains(text, "accedi a mano e premi «Riprendi»"); } [TestMethod] public async Task AThrottleStopAndItsEndAreTwoAlerts() { await using var bed = await AlertBed.CreateAsync(); await using var host = new EngineHost(bed.Engine.Services, new ScriptedRunner(bed.Engine.Governor, bed.Engine.Clock)); await bed.ReportAsync(SignalLevel.Throttle, "http-429"); var banner = (await host.Monitor.GetSnapshotAsync()).Banner!; Assert.AreEqual(BannerLevel.Warning, banner.Level); Assert.AreEqual("Instagram ha chiesto di rallentare", banner.Title); var stop = bed.Telegram.Requests.Single().Text; StringAssert.StartsWith(stop, "Febe · Instagram ha chiesto di rallentare\n"); StringAssert.Contains(stop, "mi fermo per 1 ora: riparto verso le 13:00"); StringAssert.Contains(stop, "Non devi fare nulla: riparto da solo."); // After the hour the breaker reopens by itself: «…e ripresa». bed.Engine.Clock.Advance(TimeSpan.FromHours(1)); Assert.AreEqual(BreakerStatus.Closed, bed.Engine.Breaker.State.Status); await bed.Engine.Breaker.FlushAsync(); await bed.Alerts.FlushAsync(); Assert.HasCount(2, bed.Telegram.Requests); var end = bed.Telegram.Requests[1].Text; StringAssert.StartsWith(end, "Febe · Fine del fermo per rallentamento\n"); StringAssert.Contains(end, "tetti dimezzati"); Assert.AreEqual("Fine del fermo per rallentamento", bed.Shell.Notifications[1].Title); Assert.IsNull((await host.Monitor.GetSnapshotAsync()).Banner, "the strip goes away by itself"); } [TestMethod] public async Task TheBackfillOfAnAccountCompletedIsAnAlertOfItsOwn() { await using var bed = await AlertBed.CreateAsync(start: Morning); var engine = bed.Engine; var account = await engine.AddAccountAsync("storico.demo", followed: true, state: AccountState.Backfilling, postCount: 30); var runner = new ScriptedRunner(engine.Governor, engine.Clock) { Script = r => r.Kind == RecipeKind.Backfill && r.AccountId == account.Id ? new RecipeOutcome(RecipeStatus.Completed, 1, 12) { BackfillFinished = true } : null, }; engine.Start(runner); await engine.RunUntilAsync(Morning.AddHours(14)); await engine.StopAsync(); await bed.Alerts.FlushAsync(); var backfill = bed.Telegram.Requests.Select(r => r.Text).Where(t => t.StartsWith("Febe · Storico completato\n", StringComparison.Ordinal)).ToList(); Assert.HasCount(1, backfill); StringAssert.Contains(backfill[0], "Storico di @storico.demo completato"); Assert.AreEqual(account.Id, bed.Outcomes.Single(o => o.Alert.Kind == AlertKind.BackfillDone).Alert.AccountId); // Another account is another alert; the same account again within a day is not. var other = await engine.AddAccountAsync("altro.demo", followed: true); await bed.WriteEventAsync(EventSeverity.Success, EngineEventCodes.BackfillCompleted, "Storico di @altro.demo completato: 3 post in libreria.", other.Id); await bed.WriteEventAsync(EventSeverity.Success, EngineEventCodes.BackfillCompleted, "Storico di @storico.demo completato: 30 post in libreria.", account.Id); Assert.AreEqual(2, bed.Telegram.Requests.Count(r => r.Text.Contains("Storico completato", StringComparison.Ordinal))); Assert.AreEqual(AlertOutcomeKind.Repeated, bed.Outcomes[^1].Kind); } [TestMethod] public async Task UnknownFormatsAlertOnceAndTheSuspendedRecipeAgain() { await using var bed = await AlertBed.CreateAsync(start: Morning); var engine = bed.Engine; await engine.AddAccountAsync("strano.demo", followed: false, Frequency.High); var runner = new ScriptedRunner(engine.Governor, engine.Clock) { Script = r => r.Kind == RecipeKind.ProfileCheck ? new RecipeOutcome(RecipeStatus.UnrecognizedFormat, 1, 0) : null, }; engine.Start(runner); await engine.RunUntilAsync(Morning.AddDays(2)); await engine.StopAsync(); await bed.Alerts.FlushAsync(); var events = await engine.Db.Events.ListAsync(new EventQuery { Codes = [EngineEventCodes.FormatUnrecognized] }); Assert.IsGreaterThanOrEqualTo(2, events.Count, "several unknown formats in the timeline"); var texts = bed.Telegram.Requests.Select(r => r.Text).ToList(); var formats = texts.Where(t => t.StartsWith("Febe · Formato non riconosciuto\n", StringComparison.Ordinal)).ToList(); Assert.HasCount(1, formats, "one message within six hours, however many times it happens"); StringAssert.Contains(formats[0], "Formato non riconosciuto durante il controllo del profilo di @strano.demo"); StringAssert.Contains(formats[0], "serve un campione nuovo con la sonda"); Assert.IsTrue(bed.Outcomes.Any(o => o.Alert.Kind == AlertKind.UnknownFormat && o.Kind == AlertOutcomeKind.Repeated)); var suspended = texts.Single(t => t.StartsWith("Febe · Ricetta sospesa\n", StringComparison.Ordinal)); StringAssert.Contains(suspended, "modalità sonda"); } [TestMethod] public async Task ADiskAlmostFullIsCheckedWithThresholdsAndRemindedOnceADay() { await using var bed = await AlertBed.CreateAsync(windows: false); const long GB = FakeFreeSpaceProbe.GB; // 60 GB free of 1 TB: 6%, above both thresholds. bed.Disk.Set(AlertBed.LibraryFolder, 60 * GB, 1000 * GB); Assert.IsEmpty((await bed.Alerts.CheckDiskSpaceAsync()).Low); // 40 GB of 1 TB: under 5%. bed.Disk.Set(AlertBed.LibraryFolder, 40 * GB, 1000 * GB); var check = await bed.Alerts.CheckDiskSpaceAsync(); await bed.Alerts.FlushAsync(); Assert.AreEqual("libreria", check.Key); var first = bed.Telegram.Requests.Single().Text; Assert.AreEqual( "Febe · Disco quasi pieno\nSul disco della libreria restano 40 GB liberi su 1.000 GB (4%). Continuo a lavorare, ma con il disco pieno gli scaricamenti non riusciranno. Che cosa fare: libera spazio su quel disco o sposta la cartella su un disco più capiente (guida, «Problemi comuni»).", first); var timeline = await bed.Engine.Db.Events.ListAsync(new EventQuery { Codes = [AlertEventCodes.DiskLow] }); Assert.AreEqual(EventSeverity.Warning, timeline.Single().Severity, "visible in Attività as a warning line"); // The same state a quarter of an hour later: no new line, no new message. bed.Engine.Clock.Advance(TimeSpan.FromMinutes(15)); await bed.Alerts.CheckDiskSpaceAsync(); await bed.Alerts.FlushAsync(); Assert.HasCount(1, bed.Telegram.Requests); // The Data folder too (a small disk: 9 GB free of 120 GB is under 10 GB): a new set, a new alert. bed.Disk.Set(AlertBed.DataFolder, 9 * GB, 120 * GB); check = await bed.Alerts.CheckDiskSpaceAsync(); await bed.Alerts.FlushAsync(); Assert.AreEqual("libreria+dati", check.Key); Assert.HasCount(2, bed.Telegram.Requests); StringAssert.Contains(bed.Telegram.Requests[1].Text, "sul disco della cartella dei dati restano 9 GB liberi su 120 GB (7,5%)"); StringAssert.Contains(bed.Telegram.Requests[1].Text, "il database non può più salvare nulla"); // A day later, still full: reminded once. bed.Engine.Clock.Advance(TimeSpan.FromHours(24)); await bed.Alerts.CheckDiskSpaceAsync(); await bed.Alerts.CheckDiskSpaceAsync(); await bed.Alerts.FlushAsync(); Assert.HasCount(3, bed.Telegram.Requests); // Space freed, then only the Data folder full: a new set, a new alert. bed.Disk.Set(AlertBed.LibraryFolder, 500 * GB, 1000 * GB); bed.Disk.Set(AlertBed.DataFolder, 80 * GB, 120 * GB); Assert.IsEmpty((await bed.Alerts.CheckDiskSpaceAsync()).Low); bed.Engine.Clock.Advance(TimeSpan.FromHours(1)); bed.Disk.Set(AlertBed.DataFolder, 2 * GB, 120 * GB); await bed.Alerts.CheckDiskSpaceAsync(); await bed.Alerts.FlushAsync(); Assert.HasCount(4, bed.Telegram.Requests); StringAssert.StartsWith(bed.Telegram.Requests[3].Text, "Febe · Disco quasi pieno\nSul disco della cartella dei dati restano 2 GB"); // Flapping around the threshold: a new line in Attività each time, no new message within the interval. bed.Disk.Set(AlertBed.DataFolder, 12 * GB, 120 * GB); Assert.IsEmpty((await bed.Alerts.CheckDiskSpaceAsync()).Low); bed.Engine.Clock.Advance(TimeSpan.FromHours(1)); bed.Disk.Set(AlertBed.DataFolder, 9 * GB, 120 * GB); await bed.Alerts.CheckDiskSpaceAsync(); await bed.Alerts.FlushAsync(); Assert.HasCount(4, bed.Telegram.Requests); Assert.AreEqual(AlertOutcomeKind.Repeated, bed.Outcomes[^1].Kind); Assert.HasCount(5, await bed.Engine.Db.Events.ListAsync(new EventQuery { Codes = [AlertEventCodes.DiskLow] })); } [TestMethod] public async Task TwoFoldersOnTheSameDiskAreNamedTogether() { var space = new FreeSpace(3 * FakeFreeSpaceProbe.GB, 200 * FakeFreeSpaceProbe.GB); var check = new DiskCheck([(WatchedFolder.Library("/l"), space), (WatchedFolder.Data("/d"), space)], []); StringAssert.StartsWith(check.Describe(), "Sul disco della libreria e della cartella dei dati restano 3 GB liberi su 200 GB (1,5%)."); Assert.IsTrue(DiskThresholds.Default.IsLow(new FreeSpace(9 * FakeFreeSpaceProbe.GB, 10_000 * FakeFreeSpaceProbe.GB))); Assert.IsFalse(DiskThresholds.Default.IsLow(new FreeSpace(11 * FakeFreeSpaceProbe.GB, 100 * FakeFreeSpaceProbe.GB))); Assert.IsTrue(DiskThresholds.Default.IsLow(new FreeSpace(49 * FakeFreeSpaceProbe.GB, 1000 * FakeFreeSpaceProbe.GB))); await Task.CompletedTask; } [TestMethod] public void TheRealProbeMeasuresAnyFolderEvenOneNotYetCreated() { var probe = new DriveFreeSpaceProbe(); var here = probe.Measure(AppContext.BaseDirectory); Assert.IsNotNull(here); Assert.IsGreaterThan(0L, here.TotalBytes); Assert.IsTrue(here.AvailableBytes >= 0 && here.AvailableBytes <= here.TotalBytes); var missing = probe.Measure(Path.Combine(AppContext.BaseDirectory, "non-ancora", "creata")); Assert.AreEqual(here.TotalBytes, missing?.TotalBytes, "the nearest existing folder is measured"); Assert.IsNull(probe.Measure(string.Empty)); } [TestMethod] public async Task TheDiskIsWatchedPeriodicallyOnTheClock() { await using var bed = await AlertBed.CreateAsync(windows: false); bed.Disk.Set(AlertBed.DataFolder, 1 * FakeFreeSpaceProbe.GB, 100 * FakeFreeSpaceProbe.GB); using var cts = new CancellationTokenSource(); var clock = bed.Engine.Clock; var watch = bed.Alerts.WatchDiskSpaceAsync(cts.Token); await WaitAsync(() => clock.PendingTimers > 0); Assert.IsEmpty(bed.Telegram.Requests, "the first check comes a minute after the start"); clock.Advance(TimeSpan.FromMinutes(1)); await WaitAsync(() => bed.Telegram.Requests.Count == 1); StringAssert.Contains(bed.Telegram.Requests[0].Text, "cartella dei dati"); await cts.CancelAsync(); await watch; } [TestMethod] public async Task TheSameStopFlappingIsNotRepeatedButComesBackAfterTheInterval() { await using var bed = await AlertBed.CreateAsync(); await bed.ReportAsync(SignalLevel.Challenge); Assert.IsTrue(await bed.Engine.Breaker.ResumeAsync()); bed.Engine.Clock.Advance(TimeSpan.FromMinutes(10)); await bed.ReportAsync(SignalLevel.Challenge); Assert.HasCount(1, bed.Telegram.Requests, "a verification ten minutes after the first one is not sent again"); Assert.HasCount(1, bed.Shell.Notifications); Assert.AreEqual(AlertOutcomeKind.Repeated, bed.Outcomes[^1].Kind); StringAssert.Contains(bed.Log.All, "non ripetuto"); Assert.AreEqual(2, (await bed.Engine.Db.Events.ListAsync(new EventQuery { Codes = [EngineEventCodes.ChallengeStop] })).Count, "the interface still shows both"); // Half an hour after the first one, the alert goes out again. Assert.IsTrue(await bed.Engine.Breaker.ResumeAsync()); bed.Engine.Clock.Advance(TimeSpan.FromMinutes(25)); await bed.ReportAsync(SignalLevel.Challenge); Assert.HasCount(2, bed.Telegram.Requests); // A disconnection is another kind: not held back by the verification. Assert.IsTrue(await bed.Engine.Breaker.ResumeAsync()); await bed.ReportAsync(SignalLevel.Disconnect); Assert.HasCount(3, bed.Telegram.Requests); } [TestMethod] public async Task ARestartDoesNotSendTheSameAlertAgain() { await using var bed = await AlertBed.CreateAsync(); await bed.ReportAsync(SignalLevel.Challenge); Assert.HasCount(1, bed.Telegram.Requests); // A new alert service on the same database (a restart of the program), ten minutes later. bed.Alerts.Dispose(); var outcomes = new List(); using var again = new AlertService(bed.Engine.Db.Settings, bed.Engine.Clock, bed.Engine.Services.Events, [new TelegramAlertChannel(bed.Client)]).Attach(); again.Handled += (_, o) => outcomes.Add(o); bed.Engine.Clock.Advance(TimeSpan.FromMinutes(10)); Assert.IsTrue(await bed.Engine.Breaker.ResumeAsync()); await bed.Engine.Breaker.ReportAsync(new Signal(SignalLevel.Challenge, "di-nuovo", null, bed.Engine.Clock.Now)); await bed.Engine.Breaker.FlushAsync(); await again.FlushAsync(); Assert.HasCount(1, bed.Telegram.Requests); Assert.AreEqual(AlertOutcomeKind.Repeated, outcomes.Single().Kind); } [TestMethod] public async Task SwitchesAndMissingChannelsKeepAlertsInTheInterfaceOnly() { await using (var bed = await AlertBed.CreateAsync(events: AlertEvents.All with { Verification = false })) { await bed.ReportAsync(SignalLevel.Challenge); Assert.IsEmpty(bed.Telegram.Requests); Assert.IsEmpty(bed.Shell.Notifications); Assert.AreEqual(AlertOutcomeKind.NotWanted, bed.Outcomes.Single().Kind); Assert.AreEqual(1, (await bed.Engine.Db.Events.ListAsync(new EventQuery { Codes = AlertCatalog.Codes })).Count, "still in Attività"); } await using (var bed = await AlertBed.CreateAsync(telegram: false, windows: false)) { await bed.ReportAsync(SignalLevel.Challenge); Assert.IsEmpty(bed.Telegram.Requests); Assert.AreEqual(AlertOutcomeKind.NoChannel, bed.Outcomes.Single().Kind); } } [TestMethod] public async Task AFailedChannelIsAnEventWithoutTheTokenAndTheOtherChannelStillWorks() { await using var bed = await AlertBed.CreateAsync(); bed.Telegram.Fail(HttpStatusCode.Unauthorized, "Unauthorized"); await bed.ReportAsync(SignalLevel.Challenge); Assert.HasCount(1, bed.Shell.Notifications, "the Windows notification does not depend on Telegram"); var failure = (await bed.Engine.Db.Events.ListAsync(new EventQuery { Codes = [AlertEventCodes.DeliveryFailed] })).Single(); Assert.AreEqual(EventSeverity.Warning, failure.Severity); Assert.AreEqual( "L'avviso «Instagram chiede una verifica» non è arrivato (Telegram): Telegram non riconosce il gettone del bot: copialo di nuovo per intero dal messaggio di BotFather. Lo trovi comunque qui in Febe; controlla Impostazioni ▸ Notifiche e usa «Invia una prova».", failure.Message); // A second failure within the hour is logged but not written again in the timeline. bed.Engine.Clock.Advance(TimeSpan.FromMinutes(40)); Assert.IsTrue(await bed.Engine.Breaker.ResumeAsync()); await bed.ReportAsync(SignalLevel.Throttle); Assert.HasCount(1, await bed.Engine.Db.Events.ListAsync(new EventQuery { Codes = [AlertEventCodes.DeliveryFailed] })); Assert.AreEqual(2, bed.Log.Lines.Count(l => l.Level == AlertLogLevel.Warning && l.Message.Contains("non inviato (Telegram)", StringComparison.Ordinal))); // The shell failing is recorded the same way. bed.Shell.Throws = true; bed.Telegram.Respond = null; bed.Engine.Clock.Advance(TimeSpan.FromHours(2)); await bed.ReportAsync(SignalLevel.Throttle); var failures = await bed.Engine.Db.Events.ListAsync(new EventQuery { Codes = [AlertEventCodes.DeliveryFailed] }); StringAssert.Contains(failures[0].Message, "(notifica di Windows): Windows non ha mostrato la notifica"); var written = await bed.EverythingWrittenAsync(); Assert.DoesNotContain(AlertBed.Token, written); Assert.DoesNotContain("tokendiprova", written); Assert.DoesNotContain("api.telegram.org", written); } [TestMethod] public async Task ATelegramErrorThatNamesTheAddressNeverLeaksIt() { await using var bed = await AlertBed.CreateAsync(); bed.Telegram.Respond = (request, _) => throw new HttpRequestException($"Connessione rifiutata verso {request.Uri.AbsoluteUri}"); await bed.ReportAsync(SignalLevel.Disconnect); var failure = (await bed.Engine.Db.Events.ListAsync(new EventQuery { Codes = [AlertEventCodes.DeliveryFailed] })).Single(); StringAssert.Contains(failure.Message, "Telegram non è raggiungibile"); var written = await bed.EverythingWrittenAsync(); Assert.DoesNotContain(AlertBed.Token, written); Assert.DoesNotContain("api.telegram.org", written); Assert.DoesNotContain("tokendiprova", bed.Outcomes.Single().ToString()); Assert.DoesNotContain(AlertBed.Token, (await AlertSettingsStore.LoadAsync(bed.Engine.Db.Settings)).ToString()); // «Invia una prova» answers the same way, without the address. var test = await new TelegramAlertChannel(bed.Client).SendTelegramTestAsync(await AlertSettingsStore.LoadAsync(bed.Engine.Db.Settings), CancellationToken.None); Assert.IsFalse(test.Sent); Assert.DoesNotContain(AlertBed.Token, test.Message); StringAssert.StartsWith(test.Message, "Nessun messaggio è partito. Telegram non è raggiungibile"); } [TestMethod] public async Task ASlowTelegramTimesOut() { await using var bed = await AlertBed.CreateAsync(windows: false, telegramTimeout: TimeSpan.FromMilliseconds(300)); bed.Telegram.Respond = async (_, ct) => { await Task.Delay(TimeSpan.FromSeconds(30), ct); return FakeTelegramHandler.Answer(HttpStatusCode.OK, """{"ok":true}"""); }; var started = DateTime.UtcNow; await bed.ReportAsync(SignalLevel.Challenge); Assert.IsLessThan(TimeSpan.FromSeconds(10), DateTime.UtcNow - started); Assert.AreEqual(AlertOutcomeKind.Failed, bed.Outcomes.Single().Kind); StringAssert.Contains(bed.Outcomes.Single().Deliveries.Single().Delivery.Problem!, "non ha risposto entro"); } private async Task WaitAsync(Func condition) { var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(10); while (!condition()) { Assert.IsLessThan(deadline, DateTime.UtcNow, "condizione non raggiunta"); await Task.Delay(20, TestContext.CancellationToken); } } }