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:
Claude committed 2026-10-13 21:22:52 +00:00
1 parent dc4d1fc738
commit 69dbc7acf9
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);
}
}
}
+123
View File
@@ -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);
}
}
+117
View File
@@ -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 }));
}
}
+184
View File
@@ -0,0 +1,184 @@
using System.Text.RegularExpressions;
namespace Febe.Tests.Docs;
/// <summary>
/// The user guide (docs/guida, published as the wiki of the repository): every page exists, every link between pages
/// points to a page that exists, and the guide says everything spec §15 lists under «Che cosa la guida deve dire per
/// forza», on the pages where Alberto looks for it.
/// </summary>
[TestClass]
public sealed partial class GuideTests
{
/// <summary>The pages of the wiki, without «.md».</summary>
public static readonly string[] Pages =
[
"Home",
"Installazione-Docker-e-Unraid",
"Installazione-Windows",
"Primo-collegamento",
"Account-e-impostazioni",
"Libreria",
"Importazione",
"Limiti-e-comportamento",
"Attivita-e-arresti",
"Avvisi-e-Telegram",
"Copie-e-ricostruzione",
"Sicurezza-e-riservatezza",
"Problemi-comuni",
"Ipotesi-da-verificare",
"Sviluppo",
];
/// <summary>
/// The mandatory points of spec §15: (point, pages that must say it, phrases that must all be there). Phrases are
/// compared without case, emphasis and line breaks.
/// </summary>
public static IEnumerable<object[]> MandatoryPoints =>
[
["rischio per l'account e condizioni d'uso", new[] { "Home" }, new[] { "contro le condizioni d'uso di Instagram", "la limitazione o la chiusura dell'account" }],
["che cosa fa Febe per ridurre il rischio", new[] { "Home" }, new[] { "che cosa fa febe per ridurre il rischio", "tetti giornalieri e orari", "al primo segnale di instagram si ferma" }],
["che cosa Febe non fa", new[] { "Home" }, new[] { "che cosa febe non fa", "non risolve captcha", "non usa proxy", "azzerare il rischio" }],
["le storie aperte da Febe risultano viste", new[] { "Home", "Account-e-impostazioni", "Sicurezza-e-riservatezza" }, new[] { "le storie aperte da febe risultano viste" }],
["contenitore e desktop non insieme sullo stesso account", new[] { "Home", "Installazione-Docker-e-Unraid", "Installazione-Windows", "Primo-collegamento", "Sicurezza-e-riservatezza" }, new[] { "non vanno usati insieme sullo stesso account" }],
["chi ha la cartella dei dati o una copia ha la sessione", new[] { "Primo-collegamento", "Sicurezza-e-riservatezza" }, new[] { "chi ha la cartella dei dati, o una sua copia, ha la sessione di instagram" }],
["l'interfaccia Docker non va esposta su Internet", new[] { "Sicurezza-e-riservatezza" }, new[] { "non esporre mai l'interfaccia docker su internet", "vpn", "https" }],
["in Docker la password di Instagram passa dal server", new[] { "Primo-collegamento", "Sicurezza-e-riservatezza" }, new[] { "la password di instagram passa dal server" }],
["il compromesso sulla sandbox di Chromium", new[] { "Installazione-Docker-e-Unraid", "Sicurezza-e-riservatezza" }, new[] { "sandbox", "seccomp", "febe_senza_sandbox=1", "compromesso" }],
["che cosa fare dopo una verifica o un rallentamento", new[] { "Attivita-e-arresti" }, new[] { "che cosa fare dopo una verifica", "che cosa fare dopo un rallentamento", "completa la verifica a mano", "riprendi", "tre rallentamenti in sette giorni" }],
["dove sono le copie del database e come si ricostruisce", new[] { "Copie-e-ricostruzione" }, new[] { "/dati/copie", "%localappdata%\\febe\\copie", "febe-aaaa-mm-gg.sqlite", "ricostruisci il database dalla libreria", "_febe.jsonl" }],
["esportazione CSV dell'elenco (§4.8)", new[] { "Libreria" }, new[] { "esporta l'elenco", "`;`", "utf-8 con bom" }],
["Telegram: BotFather e identificativo della chat (§13.3)", new[] { "Avvisi-e-Telegram" }, new[] { "@botfather", "/newbot", "getupdates", "\"chat\":{\"id\":", "invia una prova" }],
["pagina sui problemi comuni (M8)", new[] { "Problemi-comuni" }, new[] { "formato non riconosciuto", "disco quasi pieno", "no usable sandbox", "manca la password dell'interfaccia" }],
["ipotesi H1–H11 e S1–S6", new[] { "Ipotesi-da-verificare" }, new[] { "| h1 |", "| h11 |", "| s1 |", "| s6 |", "account di prova" }],
];
public static string GuideFolder()
{
var folder = new DirectoryInfo(AppContext.BaseDirectory);
while (folder is not null && !File.Exists(Path.Combine(folder.FullName, "Febe.slnx")))
{
folder = folder.Parent;
}
if (folder is null)
{
Assert.Inconclusive("Radice del repository non trovata.");
}
var guide = Path.Combine(folder.FullName, "docs", "guida");
var isCheckout = Directory.Exists(Path.Combine(folder.FullName, ".git")) || File.Exists(Path.Combine(folder.FullName, ".git"));
if (!Directory.Exists(guide) && !isCheckout)
{
// The build of the Docker image copies the sources without docs/ (see .dockerignore).
Assert.Inconclusive("Questa copia del repository non ha docs/ (costruzione dell'immagine Docker).");
}
Assert.IsTrue(Directory.Exists(guide), guide);
return guide;
}
[TestMethod]
public void EveryPageExistsWithATitle()
{
var guide = GuideFolder();
foreach (var page in Pages)
{
var path = Path.Combine(guide, page + ".md");
Assert.IsTrue(File.Exists(path), $"manca la pagina {page}");
var first = File.ReadLines(path).First();
StringAssert.StartsWith(first, "# ", $"{page}: la prima riga è il titolo");
}
Assert.IsTrue(File.Exists(Path.Combine(guide, "_Sidebar.md")), "manca _Sidebar.md");
var unknown = Directory.EnumerateFiles(guide, "*.md")
.Select(Path.GetFileNameWithoutExtension)
.Where(name => name != "_Sidebar" && !Pages.Contains(name))
.ToList();
Assert.IsEmpty(unknown, "pagine non elencate in GuideTests.Pages: " + string.Join(", ", unknown));
}
[TestMethod]
public void EveryWikiLinkPointsToAnExistingPage()
{
var guide = GuideFolder();
var problems = new List<string>();
var linkedFrom = new Dictionary<string, HashSet<string>>(StringComparer.Ordinal);
foreach (var file in Directory.EnumerateFiles(guide, "*.md"))
{
var name = Path.GetFileNameWithoutExtension(file);
var targets = new HashSet<string>(StringComparer.Ordinal);
// Code is not a link: «`[Testo](Nome-Pagina)`» explains the format.
var text = InlineCode().Replace(FencedCode().Replace(File.ReadAllText(file), string.Empty), string.Empty);
foreach (Match match in Link().Matches(text))
{
var target = match.Groups["target"].Value;
if (target.StartsWith("http://", StringComparison.Ordinal) || target.StartsWith("https://", StringComparison.Ordinal) || target.StartsWith("mailto:", StringComparison.Ordinal))
{
continue;
}
if (!WikiPage().IsMatch(target))
{
problems.Add($"{name}: «{target}» non è il nome di una pagina del wiki (niente .md, cartelle o ancore)");
}
else if (!File.Exists(Path.Combine(guide, target + ".md")) || target == "_Sidebar")
{
problems.Add($"{name}: «{target}» non esiste");
}
targets.Add(target);
}
linkedFrom[name] = targets;
}
Assert.IsEmpty(problems, string.Join("\n", problems));
var fromSidebar = linkedFrom["_Sidebar"];
var fromHome = linkedFrom["Home"];
foreach (var page in Pages)
{
Assert.Contains(page, fromSidebar, $"la barra laterale non porta a {page}");
if (page != "Home")
{
Assert.Contains(page, fromHome, $"l'indice della pagina iniziale non porta a {page}");
}
}
}
[TestMethod]
[DynamicData(nameof(MandatoryPoints))]
public void TheGuideSaysWhatTheSpecificationRequires(string point, string[] pages, string[] phrases)
{
var guide = GuideFolder();
foreach (var page in pages)
{
var text = Normalize(File.ReadAllText(Path.Combine(guide, page + ".md")));
var missing = phrases.Where(p => !text.Contains(Normalize(p), StringComparison.Ordinal)).ToList();
Assert.IsEmpty(missing, $"«{point}»: in {page} mancano: {string.Join(" | ", missing)}");
}
}
/// <summary>Lower case, typographic apostrophes as plain ones, no emphasis, one space for any run of blanks.</summary>
public static string Normalize(string text)
{
ArgumentNullException.ThrowIfNull(text);
var plain = text.Replace("**", string.Empty, StringComparison.Ordinal).Replace('’', '\'').ToLowerInvariant();
return Blanks().Replace(plain, " ");
}
[GeneratedRegex(@"(?<!!)\[[^\]]*\]\((?<target>[^)\s]+)\)")]
private static partial Regex Link();
[GeneratedRegex(@"^_?[A-Za-z0-9]+(-[A-Za-z0-9]+)*$")]
private static partial Regex WikiPage();
[GeneratedRegex(@"\s+")]
private static partial Regex Blanks();
[GeneratedRegex(@"^```.*?^```", RegexOptions.Singleline | RegexOptions.Multiline)]
private static partial Regex FencedCode();
[GeneratedRegex(@"`[^`\n]*`")]
private static partial Regex InlineCode();
}
+34 -1
View File
@@ -7,6 +7,7 @@ using Febe.Core.Domain;
using Febe.Core.Library;
using Febe.Core.Storage;
using Febe.SitoDiProva;
using Febe.Tests.Alerts.Support;
using Febe.Tests.Server.Support;
using Febe.Web.Connection;
@@ -38,7 +39,9 @@ public sealed partial class ServerEndToEndTests
public async Task TheRealServerCollectsFromTheTestSiteStopsAtTheVerificationAndShowsTheBrowser()
{
var ct = TestContext.CancellationToken;
await using var bed = await ServerTestBed.StartAsync();
var telegram = new FakeTelegramHandler();
var disk = new FakeFreeSpaceProbe();
await using var bed = await ServerTestBed.StartAsync(telegram: telegram, freeSpace: disk);
var server = bed.Server;
Assert.IsEmpty(server.Problems);
await server.Running.WaitAsync(TimeSpan.FromSeconds(60), ct);
@@ -130,6 +133,11 @@ public sealed partial class ServerEndToEndTests
// The site asks for a verification: at its next action toward the site the engine stops and the banner appears
// in /api/engine. Usually still in the first session (two accounts to read in full); if that session already
// ended, in the next one, after the minimum pause (20 minutes at 10×: two real minutes).
// Alerts on Telegram (M8): token and chat set from Impostazioni ▸ Notifiche; the composition sends through the fake.
const string token = "4839574812:AAF-gettoneDelServerDiProva_123";
var events = """{"verification":true,"disconnection":true,"throttle":true,"backfillDone":true,"diskLow":true,"unknownFormat":true}""";
await bed.JsonAsync(HttpMethod.Put, "/api/settings/notifications", $$"""{"events":{{events}},"windows":false,"telegramChatId":"42","telegramToken":"{{token}}","removeTelegramToken":false}""");
var servedBefore = bed.Site.Control.CdnFilesServed;
bed.Site.Control.Set(StopMode.Challenge);
await ServerTestBed.WaitUntilAsync(
@@ -144,6 +152,24 @@ public sealed partial class ServerEndToEndTests
Assert.AreEqual(ConnectionState.VerificationRequired, (await connection.GetStatusAsync(ct)).State);
TestContext.WriteLine($"CDN: {servedBefore} file prima del fermo, {bed.Site.Control.CdnFilesServed} adesso.");
// The same stop reached Telegram, with the Italian text, and the «Avvisi» list of Attività.
await ServerTestBed.WaitUntilAsync(
() => Task.FromResult(telegram.Requests.Any(r => r.Text.StartsWith("Febe · Instagram chiede una verifica\n", StringComparison.Ordinal))),
TimeSpan.FromSeconds(20),
"il messaggio Telegram della verifica");
var message = telegram.Requests.First(r => r.Text.StartsWith("Febe · Instagram chiede una verifica", StringComparison.Ordinal));
Assert.AreEqual($"/bot{token}/sendMessage", message.Uri.AbsolutePath);
Assert.AreEqual("42", message.ChatId);
StringAssert.Contains(message.Text, "premi «Riprendi»");
var alerts = await bed.JsonAsync(HttpMethod.Get, "/api/alerts");
Assert.IsTrue(alerts.GetProperty("items").EnumerateArray().Any(i => i.GetProperty("kind").GetString() == "verification"));
foreach (var file in Directory.EnumerateFiles(server.Data!.Logs))
{
var log = await ReadSharedAsync(file, ct);
Assert.DoesNotContain(token, log, file);
Assert.DoesNotContain("api.telegram.org", log, file);
}
// The remote view: meta first, then JPEG frames; Alberto is driving while it is open.
using (var socket = await bed.OpenRemoteViewAsync(ct))
{
@@ -262,4 +288,11 @@ public sealed partial class ServerEndToEndTests
[GeneratedRegex(@"^(post|storie|evidenza/[^/]+|taggati)/(\d{4}/)?\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}_[^_/]+_\d+\.(jpg|mp4)$")]
private static partial Regex NamePattern();
private static async Task<string> ReadSharedAsync(string path, CancellationToken ct)
{
await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
using var reader = new StreamReader(stream);
return await reader.ReadToEndAsync(ct);
}
}
@@ -4,6 +4,7 @@ using System.Text;
using System.Text.Json;
using Febe.Browser.Hosting;
using Febe.Core.Abstractions;
using Febe.Core.Alerts;
using Febe.Core.Library;
using Febe.Server;
using Febe.SitoDiProva;
@@ -56,7 +57,7 @@ internal sealed class ServerTestBed : IAsyncDisposable
public static string? UnavailableReason() => RealBrowser.UnavailableReason();
public static async Task<ServerTestBed> StartAsync(bool autoLogin = false, double factor = 10)
public static async Task<ServerTestBed> StartAsync(bool autoLogin = false, double factor = 10, HttpMessageHandler? telegram = null, IFreeSpaceProbe? freeSpace = null)
{
var temp = new TempFolder("server");
var site = await TestSite.StartAsync(new TestSiteOptions());
@@ -86,7 +87,7 @@ internal sealed class ServerTestBed : IAsyncDisposable
FebeServer server;
try
{
server = await FebeServer.StartAsync(options, new ServerHooks { Clock = clock, Random = new SeededRandom(20261013), Console = TextWriter.Null });
server = await FebeServer.StartAsync(options, new ServerHooks { Clock = clock, Random = new SeededRandom(20261013), Console = TextWriter.Null, TelegramHandler = telegram, FreeSpace = freeSpace });
}
catch
{
+2 -2
View File
@@ -178,8 +178,8 @@ public sealed class SettingsApiTests
var (testStatus, test) = await server.SendJsonAsync(HttpMethod.Post, "/api/settings/notifications/test", new { channel = "telegram" });
Assert.AreEqual(HttpStatusCode.OK, testStatus);
Assert.IsFalse(test.Bool("sent"), "the Telegram sender arrives with M8");
Assert.AreEqual(TelegramNotAvailableYet.Text, test.Str("message"));
Assert.IsFalse(test.Bool("sent"), "without a composition nothing leaves (no network in tests and in the demo)");
Assert.AreEqual(NoTelegramSender.Text, test.Str("message"));
var (windowsStatus, _) = await server.SendJsonAsync(HttpMethod.Post, "/api/settings/notifications/test", new { channel = "windows" });
Assert.AreEqual(HttpStatusCode.BadRequest, windowsStatus);