Rifiniture (M8): avvisi su striscia, notifiche di Windows e Telegram con controllo dello spazio su disco; «Esporta l'elenco» della libreria; avvisi e ricette sospese in Attività; guida per il wiki in docs/guida
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
50 files changed
+3980
-28
No files matched your search
@@ -0,0 +1,440 @@
|
||||
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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class AlertServiceTests
|
||||
{
|
||||
private static readonly DateTimeOffset Morning = EngineTestBed.Local(2026, 10, 14, 6, 0);
|
||||
|
||||
public TestContext TestContext { get; set; } = null!;
|
||||
|
||||
/// <summary>M8, «Fatto quando»: un arresto simulato produce striscia, notifica e messaggio.</summary>
|
||||
[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<IFebeStorage>(bed.Engine.Db);
|
||||
s.AddSingleton<IClock>(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, fino alle 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<AlertOutcome>();
|
||||
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<bool> condition)
|
||||
{
|
||||
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(10);
|
||||
while (!condition())
|
||||
{
|
||||
Assert.IsLessThan(deadline, DateTime.UtcNow, "condizione non raggiunta");
|
||||
await Task.Delay(20, TestContext.CancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
using System.Net;
|
||||
using Febe.Core.Alerts;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Tests.Alerts.Support;
|
||||
using Febe.Tests.Engine.Support;
|
||||
using Febe.Tests.Web.Part2Support;
|
||||
using Febe.Tests.Web.Support;
|
||||
using Febe.Web.Engine;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Febe.Tests.Alerts;
|
||||
|
||||
/// <summary>The interface side of the alerts: «Invia una prova» with the real Telegram channel (fake handler), the «Avvisi» list of Attività.</summary>
|
||||
[TestClass]
|
||||
public sealed class AlertsApiTests
|
||||
{
|
||||
private const string Token = "987654321:AAHgettoneDaNonRimandareMai_42";
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheTestButtonSendsOneMessageThroughTheRealChannel()
|
||||
{
|
||||
var handler = new FakeTelegramHandler();
|
||||
using var client = new TelegramClient(handler);
|
||||
await using var server = await WebTestServer.StartAsync(services: s => s.AddSingleton<IAlertTestSender>(new TelegramAlertChannel(client)));
|
||||
var events = new { verification = true, disconnection = true, throttle = true, backfillDone = true, diskLow = true, unknownFormat = true };
|
||||
var (saveStatus, saveText) = await server.SendTextAsync(HttpMethod.Put, "/api/settings/notifications",
|
||||
new { events, windows = false, telegramChatId = "123456", telegramToken = Token, removeTelegramToken = false });
|
||||
Assert.AreEqual(HttpStatusCode.OK, saveStatus, saveText);
|
||||
|
||||
var settings = await server.GetJsonAsync("/api/settings/notifications");
|
||||
Assert.IsTrue(settings.Bool("telegramAvailable"), "the page no longer says that Telegram is missing");
|
||||
|
||||
var (status, text) = await server.SendTextAsync(HttpMethod.Post, "/api/settings/notifications/test", new { channel = "telegram" });
|
||||
Assert.AreEqual(HttpStatusCode.OK, status, text);
|
||||
StringAssert.Contains(text, "\"sent\":true");
|
||||
Assert.DoesNotContain(Token, text);
|
||||
var request = handler.Requests.Single();
|
||||
Assert.AreEqual("123456", request.ChatId);
|
||||
Assert.AreEqual(TelegramAlertChannel.TestText, request.Text);
|
||||
|
||||
// Telegram refuses: the page gets the reason, never the token or the address.
|
||||
handler.Fail(HttpStatusCode.BadRequest, "Bad Request: chat not found");
|
||||
(status, text) = await server.SendTextAsync(HttpMethod.Post, "/api/settings/notifications/test", new { channel = "telegram" });
|
||||
Assert.AreEqual(HttpStatusCode.OK, status);
|
||||
StringAssert.Contains(text, "\"sent\":false");
|
||||
StringAssert.Contains(text, "non trova la chat");
|
||||
Assert.DoesNotContain(Token, text);
|
||||
Assert.DoesNotContain("api.telegram.org", text);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AMalformedTokenIsRefusedWhenSaved()
|
||||
{
|
||||
await using var server = await Part2.StartAsync();
|
||||
var events = new { verification = true, disconnection = true, throttle = true, backfillDone = true, diskLow = true, unknownFormat = true };
|
||||
var (status, text) = await server.SendTextAsync(HttpMethod.Put, "/api/settings/notifications",
|
||||
new { events, windows = false, telegramChatId = "123456", telegramToken = "123:abc/../altro", removeTelegramToken = false });
|
||||
Assert.AreEqual(HttpStatusCode.BadRequest, status);
|
||||
StringAssert.Contains(text, "BotFather");
|
||||
Assert.DoesNotContain("altro", text);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheAlertsListOfAttivitaHasOnlyAlertsAndFailedDeliveries()
|
||||
{
|
||||
await using var server = await WebTestServer.StartAsync();
|
||||
var now = server.Clock.Now;
|
||||
async Task Add(TimeSpan ago, EventSeverity severity, string code, string message) =>
|
||||
await server.Db.Events.AppendAsync(new EventRecord { At = now - ago, Severity = severity, Code = code, Message = message });
|
||||
|
||||
await Add(TimeSpan.FromDays(20), EventSeverity.Error, EngineEventCodes.ChallengeStop, "troppo vecchio");
|
||||
await Add(TimeSpan.FromHours(5), EventSeverity.Success, EngineEventCodes.BackfillCompleted, "Storico di @marta.demo completato: 120 post in libreria.");
|
||||
await Add(TimeSpan.FromHours(4), EventSeverity.Info, "ricetta.ProfileCheck", "@marta.demo: nessuna novità");
|
||||
await Add(TimeSpan.FromHours(3), EventSeverity.Warning, AlertEventCodes.DiskLow, "Sul disco della libreria restano 8 GB liberi.");
|
||||
await Add(TimeSpan.FromHours(2), EventSeverity.Warning, AlertEventCodes.DeliveryFailed, "L'avviso «Disco quasi pieno» non è arrivato (Telegram): Telegram non è raggiungibile.");
|
||||
await Add(TimeSpan.FromHours(1), EventSeverity.Warning, EngineEventCodes.ThrottleStop, "Instagram ha chiesto di rallentare (segnale http-429).");
|
||||
|
||||
var list = await server.GetJsonAsync("/api/alerts");
|
||||
Assert.AreEqual(14, list.Int("days"));
|
||||
var items = list.GetProperty("items").EnumerateArray().ToList();
|
||||
CollectionAssert.AreEqual(
|
||||
new[] { "throttleStop", "deliveryFailed", "diskLow", "backfillDone" },
|
||||
items.Select(i => i.Str("kind")).ToArray());
|
||||
CollectionAssert.AreEqual(
|
||||
new[] { "Instagram ha chiesto di rallentare", "Avviso non inviato", "Disco quasi pieno", "Storico completato" },
|
||||
items.Select(i => i.Str("title")).ToArray());
|
||||
CollectionAssert.AreEqual(new[] { "warning", "warning", "warning", "success" }, items.Select(i => i.Str("level")).ToArray());
|
||||
Assert.AreEqual("Sul disco della libreria restano 8 GB liberi.", items[2].Str("message"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ASuspendedRecipeIsShownAndReactivatedFromAttivita()
|
||||
{
|
||||
var morning = EngineTestBed.Local(2026, 10, 14, 6, 0);
|
||||
await using var bed = await EngineTestBed.CreateAsync(morning);
|
||||
await bed.AddAccountAsync("strano.demo", followed: false, Frequency.High);
|
||||
var runner = new ScriptedRunner(bed.Governor, bed.Clock)
|
||||
{
|
||||
Script = r => r.Kind == RecipeKind.ProfileCheck ? new RecipeOutcome(RecipeStatus.UnrecognizedFormat, 1, 0) : null,
|
||||
};
|
||||
var host = bed.Start(runner);
|
||||
await bed.RunUntilAsync(morning.AddDays(2));
|
||||
await using var server = await WebTestServer.StartAsync(services: s =>
|
||||
{
|
||||
s.AddSingleton(host.Monitor);
|
||||
s.AddSingleton<IEngineControl>(new EngineHostControl(host));
|
||||
});
|
||||
|
||||
var suspended = (await server.GetJsonAsync("/api/engine")).GetProperty("snapshot").GetProperty("suspendedRecipes").EnumerateArray().Single();
|
||||
Assert.AreEqual("ProfileCheck", suspended.Str("recipe"));
|
||||
Assert.AreEqual("Il controllo del profilo", suspended.Str("name"));
|
||||
|
||||
var (status, text) = await server.SendTextAsync(HttpMethod.Post, "/api/engine/recipes/ProfileCheck/resume");
|
||||
Assert.AreEqual(HttpStatusCode.OK, status, text);
|
||||
StringAssert.Contains(text, "\"resumed\":true");
|
||||
Assert.IsFalse(host.SuspendedRecipes.ContainsKey(RecipeKind.ProfileCheck));
|
||||
(status, text) = await server.SendTextAsync(HttpMethod.Post, "/api/engine/recipes/ProfileCheck/resume");
|
||||
StringAssert.Contains(text, "\"resumed\":false");
|
||||
(status, _) = await server.SendTextAsync(HttpMethod.Post, "/api/engine/recipes/Inventata/resume");
|
||||
Assert.AreEqual(HttpStatusCode.BadRequest, status);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Alerts;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Storage;
|
||||
using Febe.Tests.Engine.Support;
|
||||
using Febe.Web.Native;
|
||||
|
||||
namespace Febe.Tests.Alerts.Support;
|
||||
|
||||
/// <summary>
|
||||
/// The engine's services on a temporary database and a virtual clock (<see cref="EngineTestBed"/>), with an
|
||||
/// <see cref="AlertService"/> listening to them: a fake desktop shell, a fake Telegram, a fake free-space probe on two
|
||||
/// folders. Telegram and Windows notifications are switched on unless asked otherwise.
|
||||
/// </summary>
|
||||
internal sealed class AlertBed : IAsyncDisposable
|
||||
{
|
||||
public const string Token = "4839574812:AAF-tokendiprova_SegretoDaNonMostrare";
|
||||
public const string Chat = "-100123456";
|
||||
public const string LibraryFolder = "/prova/libreria";
|
||||
public const string DataFolder = "/prova/dati";
|
||||
|
||||
private AlertBed(EngineTestBed engine, AlertService alerts, FakeNativeShell shell, FakeTelegramHandler telegram, FakeFreeSpaceProbe disk, AlertLogRecorder log, TelegramClient client)
|
||||
{
|
||||
Engine = engine;
|
||||
Alerts = alerts;
|
||||
Shell = shell;
|
||||
Telegram = telegram;
|
||||
Disk = disk;
|
||||
Log = log;
|
||||
Client = client;
|
||||
}
|
||||
|
||||
public EngineTestBed Engine { get; }
|
||||
|
||||
public AlertService Alerts { get; }
|
||||
|
||||
public FakeNativeShell Shell { get; }
|
||||
|
||||
public FakeTelegramHandler Telegram { get; }
|
||||
|
||||
public FakeFreeSpaceProbe Disk { get; }
|
||||
|
||||
public AlertLogRecorder Log { get; }
|
||||
|
||||
public TelegramClient Client { get; }
|
||||
|
||||
public List<AlertOutcome> Outcomes { get; } = [];
|
||||
|
||||
public static async Task<AlertBed> CreateAsync(bool telegram = true, bool windows = true, AlertEvents? events = null, TimeSpan? telegramTimeout = null, DateTimeOffset? start = null)
|
||||
{
|
||||
var engine = await EngineTestBed.CreateAsync(start);
|
||||
await AlertSettingsStore.SaveAsync(engine.Db.Settings, new AlertSettings(events ?? AlertEvents.All, windows, telegram ? Chat : null, telegram ? Token : null));
|
||||
var shell = new FakeNativeShell();
|
||||
var handler = new FakeTelegramHandler();
|
||||
var disk = new FakeFreeSpaceProbe();
|
||||
var log = new AlertLogRecorder();
|
||||
var client = new TelegramClient(handler, telegramTimeout);
|
||||
var alerts = new AlertService(
|
||||
engine.Db.Settings,
|
||||
engine.Clock,
|
||||
engine.Services.Events,
|
||||
[new NativeShellAlertChannel(shell), new TelegramAlertChannel(client)],
|
||||
new AlertServiceOptions
|
||||
{
|
||||
Folders = [WatchedFolder.Library(LibraryFolder), WatchedFolder.Data(DataFolder)],
|
||||
FreeSpace = disk,
|
||||
Log = log.Write,
|
||||
}).Attach();
|
||||
var bed = new AlertBed(engine, alerts, shell, handler, disk, log, client);
|
||||
alerts.Handled += (_, outcome) =>
|
||||
{
|
||||
lock (bed.Outcomes)
|
||||
{
|
||||
bed.Outcomes.Add(outcome);
|
||||
}
|
||||
};
|
||||
return bed;
|
||||
}
|
||||
|
||||
/// <summary>Reports a signal through the circuit breaker and waits for its incident, its event and its alert.</summary>
|
||||
public async Task ReportAsync(SignalLevel level, string code = "segnale-prova")
|
||||
{
|
||||
await Engine.Breaker.ReportAsync(new Signal(level, code, "https://sito.prova/x", Engine.Clock.Now));
|
||||
await Engine.Breaker.FlushAsync();
|
||||
await Alerts.FlushAsync();
|
||||
}
|
||||
|
||||
/// <summary>Writes a timeline event as the engine does and waits for its alert.</summary>
|
||||
public async Task WriteEventAsync(EventSeverity severity, string code, string message, long? accountId = null)
|
||||
{
|
||||
await Engine.Services.Events.WriteAsync(severity, code, message, accountId);
|
||||
await Alerts.FlushAsync();
|
||||
}
|
||||
|
||||
/// <summary>Everything the bed recorded that leaves Febe or stays on disk: log lines, events, alert texts.</summary>
|
||||
public async Task<string> EverythingWrittenAsync()
|
||||
{
|
||||
var events = await Engine.Db.Events.ListAsync(new EventQuery { Limit = 1000 });
|
||||
var settings = await Engine.Db.Settings.GetAllAsync();
|
||||
return string.Join(
|
||||
"\n",
|
||||
new[] { Log.All }
|
||||
.Concat(events.Select(e => e.Code + " " + e.Message))
|
||||
.Concat(Shell.Notifications.Select(n => n.Title + " " + n.Message))
|
||||
.Concat(Telegram.Requests.Select(r => r.Body))
|
||||
.Concat(Outcomes.SelectMany(o => o.Deliveries.Select(d => d.Delivery.Problem ?? string.Empty)))
|
||||
.Concat(settings.Where(s => s.Key != AlertSettingKeys.TelegramToken).Select(s => s.Key + "=" + s.Value)));
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
Alerts.Dispose();
|
||||
Client.Dispose();
|
||||
await Engine.DisposeAsync();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Febe.Core.Alerts;
|
||||
using Febe.Web.Native;
|
||||
|
||||
namespace Febe.Tests.Alerts.Support;
|
||||
|
||||
/// <summary>A request that reached the fake Telegram.</summary>
|
||||
/// <param name="Method">HTTP method.</param>
|
||||
/// <param name="Uri">Full address (it contains the token: tests check it here, nowhere else).</param>
|
||||
/// <param name="ContentType">Media type of the body.</param>
|
||||
/// <param name="Body">The JSON body.</param>
|
||||
internal sealed record TelegramRequest(HttpMethod Method, Uri Uri, string? ContentType, string Body)
|
||||
{
|
||||
public string ChatId => JsonDocument.Parse(Body).RootElement.GetProperty("chat_id").GetString()!;
|
||||
|
||||
public string Text => JsonDocument.Parse(Body).RootElement.GetProperty("text").GetString()!;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Telegram's Bot API, faked: records every request and answers with <see cref="Respond"/> (by default
|
||||
/// <c>200 {"ok":true}</c>). Never touches the network: the real api.telegram.org is never contacted from tests.
|
||||
/// </summary>
|
||||
internal sealed class FakeTelegramHandler : HttpMessageHandler
|
||||
{
|
||||
private readonly ConcurrentQueue<TelegramRequest> _requests = new();
|
||||
|
||||
public Func<TelegramRequest, CancellationToken, Task<HttpResponseMessage>>? Respond { get; set; }
|
||||
|
||||
public IReadOnlyList<TelegramRequest> Requests => [.. _requests];
|
||||
|
||||
public static HttpResponseMessage Answer(HttpStatusCode status, string json) =>
|
||||
new(status) { Content = new StringContent(json, Encoding.UTF8, "application/json") };
|
||||
|
||||
/// <summary>Answers with <paramref name="status"/> and the usual error body of the Bot API.</summary>
|
||||
public void Fail(HttpStatusCode status, string description) =>
|
||||
Respond = (_, _) => Task.FromResult(Answer(status, $$"""{"ok":false,"error_code":{{(int)status}},"description":"{{description}}"}"""));
|
||||
|
||||
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
var body = request.Content is null ? string.Empty : await request.Content.ReadAsStringAsync(cancellationToken);
|
||||
var recorded = new TelegramRequest(request.Method, request.RequestUri!, request.Content?.Headers.ContentType?.MediaType, body);
|
||||
_requests.Enqueue(recorded);
|
||||
return Respond is { } respond
|
||||
? await respond(recorded, cancellationToken)
|
||||
: Answer(HttpStatusCode.OK, """{"ok":true,"result":{"message_id":1}}""");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The desktop shell, faked: it can notify and records the notifications.</summary>
|
||||
internal sealed class FakeNativeShell(bool canNotify = true) : INativeShell
|
||||
{
|
||||
private readonly ConcurrentQueue<(string Title, string Message)> _notifications = new();
|
||||
|
||||
public IReadOnlyList<(string Title, string Message)> Notifications => [.. _notifications];
|
||||
|
||||
public bool Throws { get; set; }
|
||||
|
||||
public bool CanPickFolder => false;
|
||||
|
||||
public bool CanShowInFolder => false;
|
||||
|
||||
public bool CanOpenUrl => false;
|
||||
|
||||
public bool CanNotify { get; } = canNotify;
|
||||
|
||||
public bool SupportsAutostart => false;
|
||||
|
||||
public Task<string?> PickFolderAsync(string title, string? initialFolder, CancellationToken ct) => Task.FromResult<string?>(null);
|
||||
|
||||
public Task<bool> ShowInFolderAsync(string fullPath, CancellationToken ct) => Task.FromResult(false);
|
||||
|
||||
public Task<bool> OpenUrlAsync(Uri address, CancellationToken ct) => Task.FromResult(false);
|
||||
|
||||
public Task NotifyAsync(string title, string message, CancellationToken ct)
|
||||
{
|
||||
if (Throws)
|
||||
{
|
||||
throw new InvalidOperationException("notifiche spente");
|
||||
}
|
||||
|
||||
_notifications.Enqueue((title, message));
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task<bool> GetAutostartAsync(CancellationToken ct) => Task.FromResult(false);
|
||||
|
||||
public Task SetAutostartAsync(bool enabled, CancellationToken ct) => Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>Free space by folder, as the test decides.</summary>
|
||||
internal sealed class FakeFreeSpaceProbe : IFreeSpaceProbe
|
||||
{
|
||||
private readonly ConcurrentDictionary<string, FreeSpace?> _spaces = new(StringComparer.Ordinal);
|
||||
|
||||
public const long GB = 1024L * 1024 * 1024;
|
||||
|
||||
public void Set(string folder, long availableBytes, long totalBytes) => _spaces[folder] = new FreeSpace(availableBytes, totalBytes);
|
||||
|
||||
public void Unmeasurable(string folder) => _spaces[folder] = null;
|
||||
|
||||
public FreeSpace? Measure(string folder) => _spaces.TryGetValue(folder, out var space) ? space : new FreeSpace(500 * GB, 1000 * GB);
|
||||
}
|
||||
|
||||
/// <summary>The log lines of the alert service.</summary>
|
||||
internal sealed class AlertLogRecorder
|
||||
{
|
||||
private readonly ConcurrentQueue<(AlertLogLevel Level, string Message)> _lines = new();
|
||||
|
||||
public IReadOnlyList<(AlertLogLevel Level, string Message)> Lines => [.. _lines];
|
||||
|
||||
public string All => string.Join("\n", _lines.Select(l => l.Message));
|
||||
|
||||
public void Write(AlertLogLevel level, string message) => _lines.Enqueue((level, message));
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
using Febe.Core.Alerts;
|
||||
using Febe.Tests.Alerts.Support;
|
||||
|
||||
namespace Febe.Tests.Alerts;
|
||||
|
||||
/// <summary>The one call Febe makes to Telegram (spec §13.3), against a fake handler: never the real API.</summary>
|
||||
[TestClass]
|
||||
public sealed class TelegramClientTests
|
||||
{
|
||||
private const string Token = "123456789:AAEgettoneDiProva_moltoLungo-123";
|
||||
|
||||
[TestMethod]
|
||||
public async Task OnePostWithJsonToTheBotAddress()
|
||||
{
|
||||
var handler = new FakeTelegramHandler();
|
||||
using var client = new TelegramClient(handler);
|
||||
var result = await client.SendMessageAsync(" " + Token + " ", " 42 ", "Febe · Prova\nRiga «due» con accenti: è così", CancellationToken.None);
|
||||
|
||||
Assert.IsTrue(result.Sent, result.Message);
|
||||
var request = handler.Requests.Single();
|
||||
Assert.AreEqual(HttpMethod.Post, request.Method);
|
||||
Assert.AreEqual("https", request.Uri.Scheme);
|
||||
Assert.AreEqual("api.telegram.org", request.Uri.Host);
|
||||
Assert.AreEqual($"/bot{Token}/sendMessage", request.Uri.AbsolutePath);
|
||||
Assert.AreEqual("application/json", request.ContentType);
|
||||
using var body = JsonDocument.Parse(request.Body);
|
||||
Assert.AreEqual("42", body.RootElement.GetProperty("chat_id").GetString());
|
||||
Assert.AreEqual("Febe · Prova\nRiga «due» con accenti: è così", body.RootElement.GetProperty("text").GetString());
|
||||
Assert.IsTrue(body.RootElement.GetProperty("disable_web_page_preview").GetBoolean());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(HttpStatusCode.BadRequest, "Bad Request: chat not found", TelegramOutcome.ChatNotFound, "non trova la chat")]
|
||||
[DataRow(HttpStatusCode.BadRequest, "Bad Request: message text is empty", TelegramOutcome.Rejected, "ha rifiutato il messaggio")]
|
||||
[DataRow(HttpStatusCode.Unauthorized, "Unauthorized", TelegramOutcome.InvalidToken, "non riconosce il gettone")]
|
||||
[DataRow(HttpStatusCode.NotFound, "Not Found", TelegramOutcome.InvalidToken, "non riconosce il gettone")]
|
||||
[DataRow(HttpStatusCode.Forbidden, "Forbidden: bot was blocked by the user", TelegramOutcome.Forbidden, "premi «Avvia»")]
|
||||
[DataRow(HttpStatusCode.TooManyRequests, "Too Many Requests: retry after 30", TelegramOutcome.RateLimited, "aspettare")]
|
||||
[DataRow(HttpStatusCode.BadGateway, "Bad Gateway", TelegramOutcome.ServerError, "riprova più tardi")]
|
||||
public async Task EveryRefusalHasItsItalianReason(HttpStatusCode status, string description, TelegramOutcome outcome, string words)
|
||||
{
|
||||
var handler = new FakeTelegramHandler();
|
||||
handler.Fail(status, description);
|
||||
using var client = new TelegramClient(handler);
|
||||
var result = await client.SendMessageAsync(Token, "42", "x", CancellationToken.None);
|
||||
Assert.AreEqual(outcome, result.Outcome);
|
||||
StringAssert.Contains(result.Message, words);
|
||||
Assert.DoesNotContain(description, result.Message, "Telegram's own answer is never passed on");
|
||||
Assert.DoesNotContain(Token, result.Message);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AnAnswerWithoutOkIsNotASend()
|
||||
{
|
||||
var handler = new FakeTelegramHandler { Respond = (_, _) => Task.FromResult(FakeTelegramHandler.Answer(HttpStatusCode.OK, """{"ok":false}""")) };
|
||||
using var client = new TelegramClient(handler);
|
||||
Assert.AreEqual(TelegramOutcome.ServerError, (await client.SendMessageAsync(Token, "42", "x", CancellationToken.None)).Outcome);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(null, "42", TelegramOutcome.NotConfigured)]
|
||||
[DataRow(Token, "", TelegramOutcome.NotConfigured)]
|
||||
[DataRow("123456789", "42", TelegramOutcome.MalformedToken)]
|
||||
[DataRow("123:abc/../../altro?x=1", "42", TelegramOutcome.MalformedToken)]
|
||||
[DataRow("123456789:AAE con spazi dentro", "42", TelegramOutcome.MalformedToken)]
|
||||
public async Task NothingLeavesWithoutAWellFormedTokenAndAChat(string? token, string chat, TelegramOutcome outcome)
|
||||
{
|
||||
var handler = new FakeTelegramHandler();
|
||||
using var client = new TelegramClient(handler);
|
||||
var result = await client.SendMessageAsync(token, chat, "x", CancellationToken.None);
|
||||
Assert.AreEqual(outcome, result.Outcome);
|
||||
Assert.IsEmpty(handler.Requests);
|
||||
Assert.IsFalse(TelegramClient.IsValidToken(token) && outcome == TelegramOutcome.MalformedToken);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ALongTextIsShortened()
|
||||
{
|
||||
var handler = new FakeTelegramHandler();
|
||||
using var client = new TelegramClient(handler);
|
||||
await client.SendMessageAsync(Token, "42", new string('a', 10_000), CancellationToken.None);
|
||||
Assert.AreEqual(TelegramClient.MaxTextLength + 1, handler.Requests.Single().Text.Length);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ACancellationOfTheCallerIsNotATimeout()
|
||||
{
|
||||
var handler = new FakeTelegramHandler
|
||||
{
|
||||
Respond = async (_, ct) =>
|
||||
{
|
||||
await Task.Delay(TimeSpan.FromSeconds(30), ct);
|
||||
return FakeTelegramHandler.Answer(HttpStatusCode.OK, """{"ok":true}""");
|
||||
},
|
||||
};
|
||||
using var client = new TelegramClient(handler);
|
||||
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(200));
|
||||
await Assert.ThrowsAsync<OperationCanceledException>(() => client.SendMessageAsync(Token, "42", "x", cts.Token), "the caller is stopping: no failure to report");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheTestMessageSaysWhereToLook()
|
||||
{
|
||||
var handler = new FakeTelegramHandler();
|
||||
using var client = new TelegramClient(handler);
|
||||
var channel = new TelegramAlertChannel(client);
|
||||
var settings = new AlertSettings(AlertEvents.All, false, "42", Token);
|
||||
var result = await channel.SendTelegramTestAsync(settings, CancellationToken.None);
|
||||
Assert.IsTrue(result.Sent);
|
||||
StringAssert.Contains(result.Message, "controlla la chat del bot");
|
||||
Assert.AreEqual(TelegramAlertChannel.TestText, handler.Requests.Single().Text);
|
||||
Assert.IsTrue(channel.IsEnabled(settings));
|
||||
Assert.IsFalse(channel.IsEnabled(settings with { TelegramChatId = null }));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user