Interfaccia, parte 2: Attività, Impostazioni, collegamento, Importa, doppioni, primo avvio ed errori di configurazione

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 20:27:34 +00:00
1 parent 0515776b04
commit d614050ee5
90 files changed
+7825 -49

No files matched your search

@@ -0,0 +1,123 @@
using Febe.Core.Domain;
using Febe.Core.Library;
using Febe.Tests.Support;
namespace Febe.Tests.Library;
/// <summary>
/// The review of probable duplicates found after a download (spec §9.5): nothing is decided in advance, both files stay
/// until Alberto chooses, and only his choice removes a file (rule 12) — the whole entry when it had one file (remembered,
/// so it is not downloaded again), only that position for a series.
/// </summary>
[TestClass]
public sealed class DownloadDuplicateReviewTests
{
private static readonly int[] Scenes = [100, 237, 391];
private static async Task<(TestLibrary Lib, Account Account, EntryWithMedia Older, EntryWithMedia Newer)> TwoSimilarAsync(TempFolder temp, bool newerIsSeries = false)
{
var lib = await TestLibrary.CreateAsync(temp);
var account = await lib.Db.Accounts.AddAsync(Make.Account("doppie.prova"));
var older = await lib.SaveAsync(account, Make.Entry(account.Id, "100", Make.T0 - TimeSpan.FromDays(3)), [TestFile.Photo(1, 41, 1080, 1350)]);
IReadOnlyList<TestFile> files = newerIsSeries
? [TestFile.Photo(1, 41, 720, 900), TestFile.Photo(2, 77, 1080, 1080)]
: [TestFile.Photo(1, 41, 720, 900)];
var newer = await lib.SaveAsync(account, Make.Entry(account.Id, "200", Make.T0), files);
return (lib, account, older, newer);
}
private static DownloadDuplicateReview Review(TestLibrary lib) => new(lib.Db, lib.Layout, lib.Journal, lib.Clock, lib.Thumbnails, lib.Index);
[TestMethod]
public async Task ThePairWaitsWithNothingDecidedAndBothFilesStay()
{
using var temp = new TempFolder("doppioni");
var (lib, account, older, newer) = await TwoSimilarAsync(temp);
await using var _ = lib;
var review = Review(lib);
Assert.AreEqual(1, await review.CountPendingAsync());
var cases = await review.ListAsync();
Assert.HasCount(1, cases);
var c = cases[0];
Assert.AreEqual(DuplicateDecision.Pending, c.Pair.Decision);
Assert.AreEqual(older.Media[0].Id, c.Existing.MediaId);
Assert.AreEqual(newer.Media[0].Id, c.Candidate.MediaId);
Assert.IsFalse(c.CandidateIsLarger, "the file already there has more pixels");
Assert.AreEqual("doppie.prova", c.Existing.Username);
Assert.IsTrue(File.Exists(lib.Layout.FullPath(account, older.Media[0].RelativePath!)));
Assert.IsTrue(File.Exists(lib.Layout.FullPath(account, newer.Media[0].RelativePath!)));
var result = await review.DecideAsync(c.Pair.Id, DuplicateDecision.KeepBoth);
Assert.AreEqual(1, result.Decided);
Assert.AreEqual(0, result.FilesRemoved);
Assert.AreEqual(0, await review.CountPendingAsync());
Assert.IsTrue(File.Exists(lib.Layout.FullPath(account, newer.Media[0].RelativePath!)), "«Tienili entrambi» removes nothing");
await Assert.ThrowsExactlyAsync<KeyNotFoundException>(() => review.DecideAsync(9999, DuplicateDecision.KeepBoth));
await Assert.ThrowsExactlyAsync<ArgumentException>(() => review.DecideAsync(c.Pair.Id, DuplicateDecision.Pending));
}
[TestMethod]
public async Task KeepTheLargerRemovesTheSmallerEntryAndRemembersIt()
{
using var temp = new TempFolder("doppioni");
var (lib, account, older, newer) = await TwoSimilarAsync(temp);
await using var _ = lib;
var review = Review(lib);
var c = (await review.ListAsync())[0];
var result = await review.DecideAsync(c.Pair.Id, DuplicateDecision.KeepLarger);
Assert.AreEqual(1, result.FilesRemoved);
Assert.IsEmpty(result.Problems);
Assert.IsTrue(File.Exists(lib.Layout.FullPath(account, older.Media[0].RelativePath!)), "the larger stays");
Assert.IsFalse(File.Exists(lib.Layout.FullPath(account, newer.Media[0].RelativePath!)), "the smaller goes, by Alberto's choice");
var entry = await lib.Db.Entries.GetAsync(newer.Entry.Id);
Assert.AreEqual(EntryState.Deleted, entry!.State, "remembered: it is not downloaded again");
Assert.AreEqual(DuplicateDecision.KeepLarger, (await lib.Db.Duplicates.GetAsync(c.Pair.Id))!.Decision);
}
[TestMethod]
public async Task AFileOfASeriesLeavesOnlyItsPosition()
{
using var temp = new TempFolder("doppioni");
var (lib, account, older, newer) = await TwoSimilarAsync(temp, newerIsSeries: true);
await using var _ = lib;
var review = Review(lib);
var c = (await review.ListAsync()).Single(x => x.Candidate.EntryId == newer.Entry.Id);
Assert.AreEqual(2, c.Candidate.FilesInEntry);
var result = await review.DecideAsync(c.Pair.Id, DuplicateDecision.KeepExisting);
Assert.AreEqual(1, result.FilesRemoved);
var stored = (await lib.Db.Entries.GetWithMediaAsync(newer.Entry.Id))!;
Assert.AreNotEqual(EntryState.Deleted, stored.Entry.State, "the entry stays with its other file");
Assert.AreEqual(MediaState.Deleted, stored.Media.Single(m => m.Position == 1).State);
Assert.IsFalse(File.Exists(lib.Layout.FullPath(account, newer.Media.Single(m => m.Position == 1).RelativePath!)));
Assert.IsTrue(File.Exists(lib.Layout.FullPath(account, newer.Media.Single(m => m.Position == 2).RelativePath!)));
Assert.IsTrue(File.Exists(lib.Layout.FullPath(account, older.Media[0].RelativePath!)));
// The journal received the entry again with only the file that remains: a rebuild keeps the choice.
var journal = await File.ReadAllLinesAsync(AccountJournal.PathFor(lib.Layout.AccountFolder(account)));
var last = journal.Last(l => l.Contains("\"200\"", StringComparison.Ordinal));
StringAssert.Contains(last, newer.Media.Single(m => m.Position == 2).RelativePath!);
Assert.DoesNotContain(newer.Media.Single(m => m.Position == 1).RelativePath!, last);
}
[TestMethod]
public async Task OneChoiceCanGoToEveryPendingPair()
{
using var temp = new TempFolder("doppioni");
var lib = await TestLibrary.CreateAsync(temp);
await using var _ = lib;
var account = await lib.Db.Accounts.AddAsync(Make.Account("molte.prova"));
for (var i = 0; i < 3; i++)
{
await lib.SaveAsync(account, Make.Entry(account.Id, $"a{i}", Make.T0 - TimeSpan.FromDays(10 + i)), [TestFile.Photo(1, Scenes[i], 1080, 1350)]);
await lib.SaveAsync(account, Make.Entry(account.Id, $"b{i}", Make.T0 - TimeSpan.FromDays(i)), [TestFile.Photo(1, Scenes[i], 640, 800)]);
}
var review = Review(lib);
Assert.AreEqual(3, await review.CountPendingAsync());
var first = (await review.ListAsync())[0];
var result = await review.DecideAsync(first.Pair.Id, DuplicateDecision.KeepExisting, applyToAllPending: true);
Assert.AreEqual(3, result.Decided);
Assert.AreEqual(3, result.FilesRemoved);
Assert.AreEqual(0, await review.CountPendingAsync());
}
}
+117
View File
@@ -0,0 +1,117 @@
using System.Net;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Library;
using Febe.Tests.Support;
using Febe.Tests.Web.Part2Support;
using Febe.Tests.Web.Support;
using Febe.Web.Engine;
using Microsoft.Extensions.DependencyInjection;
namespace Febe.Tests.Web;
/// <summary>
/// What the Attività page reads beside the engine snapshot (spec §7.6, §7.9, §9.5): the stops of the last days with the
/// advice after three throttles, the still frame of the browser, and the review of probable duplicates after a download.
/// </summary>
[TestClass]
public sealed class ActivityApiTests
{
[TestMethod]
public async Task TheStopsOfTheLastDaysWithTheAdviceAfterThreeThrottles()
{
await using var server = await Part2.StartAsync();
Assert.AreEqual(0, (await server.GetJsonAsync("/api/engine/incidents")).GetProperty("items").GetArrayLength());
var now = server.Clock.Now;
for (var i = 1; i <= 3; i++)
{
var at = now - TimeSpan.FromDays(i);
var incident = await server.Db.Incidents.OpenAsync(new Incident { At = at, Level = SignalLevel.Throttle, Signal = "http-429", Url = "https://www.instagram.com/x/?firmato=1", StoppedUntil = at + TimeSpan.FromHours(1) });
await server.Db.Incidents.ResolveAsync(incident.Id, at + TimeSpan.FromHours(1));
}
await server.Db.Incidents.OpenAsync(new Incident { At = now - TimeSpan.FromMinutes(5), Level = SignalLevel.Challenge, Signal = "challenge-url", Url = "https://www.instagram.com/challenge/" });
var list = await server.GetJsonAsync("/api/engine/incidents");
var items = list.Items("items").ToList();
Assert.HasCount(4, items);
Assert.AreEqual("challenge", items[0].Str("level"), "newest first");
Assert.IsTrue(items[0].Bool("open"));
Assert.AreEqual("Verifica richiesta", items[0].Str("title"));
Assert.AreEqual("https://www.instagram.com/x/", items[1].Str("url"), "addresses without their query string");
Assert.AreEqual(3, list.Int("throttlesLastWeek"));
StringAssert.Contains(list.Str("advice"), "profilo più prudente");
}
[TestMethod]
public async Task ThePreviewIsAFrameWhenTheShellHasOne()
{
await using (var none = await Part2.StartAsync())
{
var empty = await none.GetJsonAsync("/api/browser/preview");
Assert.IsFalse(empty.Bool("hasFrame"));
var (status, _, _) = await none.GetAsync("/api/browser/preview/frame");
Assert.AreEqual(HttpStatusCode.NotFound, status);
}
var jpeg = TestFile.PhotoBytes(5, 320, 180);
var preview = new FixedPreview(new BrowserFrame(jpeg, "https://www.instagram.com/stories/marta.prova/?segreto=1", Make.T0));
await using var server = await Part2.StartAsync(services: s => s.AddSingleton<IBrowserPreview>(preview));
var dto = await server.GetJsonAsync("/api/browser/preview");
Assert.IsTrue(dto.Bool("hasFrame"));
Assert.AreEqual("https://www.instagram.com/stories/marta.prova/", dto.Str("url"));
using var response = await server.Client.GetAsync(dto.Str("frame"));
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
Assert.AreEqual("image/jpeg", response.Content.Headers.ContentType?.MediaType);
Assert.AreEqual("no-store", response.Headers.CacheControl?.ToString());
CollectionAssert.AreEqual(jpeg, await response.Content.ReadAsByteArrayAsync());
}
[TestMethod]
public async Task ProbableDuplicatesAfterADownloadWaitForAlbertoAndHisChoiceIsApplied()
{
await using var server = await Part2.StartAsync();
var index = new PerceptualHashIndex();
var journal = new AccountJournal(server.Clock);
var ingest = new LibraryIngest(server.Db, server.Library.Layout, LibraryNaming.Default, journal, server.Clock, server.Library.Thumbnails, index);
var account = await server.Db.Accounts.AddAsync(Make.Account("doppia.prova"));
async Task<EntryWithMedia> SaveAsync(string id, DateTimeOffset at, int width, int height)
{
var added = await server.Db.Entries.AddAsync(Make.Entry(account.Id, id, at), [Make.Photo(1)]);
var bytes = TestFile.PhotoBytes(61, width, height);
await ingest.SaveMediaAsync(account, added.Stored.Entry, added.Stored.Media[0], new MediaContent { Content = new MemoryStream(bytes), Extension = ".jpg" });
await ingest.AppendJournalAsync(added.Stored.Entry.Id);
return (await server.Db.Entries.GetWithMediaAsync(added.Stored.Entry.Id))!;
}
var older = await SaveAsync("1", Make.T0 - TimeSpan.FromDays(2), 1080, 1350);
var newer = await SaveAsync("2", Make.T0, 720, 900);
var counts = await server.GetJsonAsync("/api/duplicates/count");
Assert.AreEqual(1, counts.Int("download"));
Assert.AreEqual(0, counts.Int("import"));
var page = await server.GetJsonAsync("/api/duplicates");
var c = page.Items("cases").Single();
Assert.AreEqual("pending", c.Str("decision"), "nothing is chosen in advance");
Assert.AreEqual("visuallySimilar", c.Str("reason"));
Assert.IsFalse(c.Bool("candidateIsLarger"));
StringAssert.StartsWith(c.GetProperty("existing").Str("image"), "/api/thumbnails/");
Assert.AreEqual(1080, c.GetProperty("existing").Int("width"));
var (badStatus, _) = await server.SendJsonAsync(HttpMethod.Post, $"/api/duplicates/{c.Long("pairId")}", new { decision = "pending", applyToAll = false });
Assert.AreEqual(HttpStatusCode.BadRequest, badStatus);
var (status, result) = await server.SendJsonAsync(HttpMethod.Post, $"/api/duplicates/{c.Long("pairId")}", new { decision = "keepLarger", applyToAll = false });
Assert.AreEqual(HttpStatusCode.OK, status);
Assert.AreEqual(1, result.Int("filesRemoved"));
Assert.AreEqual(0, result.Int("pending"));
Assert.IsTrue(File.Exists(server.Library.Layout.FullPath(account, older.Media[0].RelativePath!)));
Assert.IsFalse(File.Exists(server.Library.Layout.FullPath(account, newer.Media[0].RelativePath!)));
Assert.AreEqual(EntryState.Deleted, (await server.Db.Entries.GetAsync(newer.Entry.Id))!.State);
var (missing, _) = await server.SendJsonAsync(HttpMethod.Post, $"/api/duplicates/{c.Long("pairId") + 50}", new { decision = "keepBoth", applyToAll = false });
Assert.AreEqual(HttpStatusCode.NotFound, missing);
}
private sealed class FixedPreview(BrowserFrame frame) : IBrowserPreview
{
public Task<BrowserFrame?> GetLatestAsync(CancellationToken ct) => Task.FromResult<BrowserFrame?>(frame);
}
}
+102
View File
@@ -0,0 +1,102 @@
using System.Net;
using Febe.Tests.Web.Part2Support;
using Febe.Tests.Web.Support;
using Febe.Web.Connection;
using Microsoft.Extensions.DependencyInjection;
namespace Febe.Tests.Web;
/// <summary>
/// The link to Instagram over <see cref="IConnectionService"/> (Connection/PROTOCOLLO.md, spec §4.1): the default
/// «browser non disponibile» when the composition registers none, a registered service used as it is, the Origin
/// check on the commands (§13.1), and the configuration problems of <c>/api/capabilities</c> (§8.2, §11).
/// </summary>
[TestClass]
public sealed class ConnectionApiTests
{
[TestMethod]
public async Task WithoutAServiceTheBrowserIsUnavailableAndCommandsSaySo()
{
await using var server = await Part2.StartAsync();
var status = await server.GetJsonAsync("/api/connection");
Assert.AreEqual("browserUnavailable", status.Str("state"));
Assert.IsFalse(status.Bool("userIsDriving"));
var (beginStatus, begin) = await server.SendJsonAsync(HttpMethod.Post, "/api/connection/begin", new { openLogin = true });
Assert.AreEqual(HttpStatusCode.BadRequest, beginStatus);
StringAssert.Contains(begin.Str("message"), "browser di Febe non è disponibile");
var (finishStatus, finish) = await server.SendJsonAsync(HttpMethod.Post, "/api/connection/finish");
Assert.AreEqual(HttpStatusCode.OK, finishStatus);
Assert.IsFalse(finish.Bool("connected"));
Assert.IsFalse(string.IsNullOrWhiteSpace(finish.Str("message")));
var (cancelStatus, _) = await server.SendJsonAsync(HttpMethod.Post, "/api/connection/cancel");
Assert.AreEqual(HttpStatusCode.NoContent, cancelStatus);
var (disconnectStatus, _) = await server.SendJsonAsync(HttpMethod.Post, "/api/connection/disconnect");
Assert.AreEqual(HttpStatusCode.BadRequest, disconnectStatus);
}
[TestMethod]
public async Task ARegisteredServiceIsUsedAndHoFinitoLetsRiprendiActivate()
{
var connection = new RecordingConnection();
await using var server = await Part2.StartAsync(services: s => s.AddSingleton<IConnectionService>(connection));
var status = await server.GetJsonAsync("/api/connection");
Assert.AreEqual("notConnected", status.Str("state"));
Assert.AreEqual("https://www.instagram.com/accounts/login/", status.Str("currentUrl"));
var (beginStatus, _) = await server.SendJsonAsync(HttpMethod.Post, "/api/connection/begin", new { openLogin = true });
Assert.AreEqual(HttpStatusCode.NoContent, beginStatus);
Assert.IsTrue((await server.GetJsonAsync("/api/connection")).Bool("userIsDriving"));
var (finishStatus, finish) = await server.SendJsonAsync(HttpMethod.Post, "/api/connection/finish");
Assert.AreEqual(HttpStatusCode.OK, finishStatus);
Assert.IsTrue(finish.Bool("connected"));
Assert.AreEqual("connected", (await server.GetJsonAsync("/api/connection")).Str("state"));
Assert.IsNotNull(server.App.Services.GetRequiredService<Febe.Web.Engine.BrowserUseTracker>().LastUsedAt, "«Ho finito» counts as having used the browser");
await server.SendJsonAsync(HttpMethod.Post, "/api/connection/cancel");
await server.SendJsonAsync(HttpMethod.Post, "/api/connection/disconnect");
CollectionAssert.AreEqual(new[] { "begin:True", "finish", "cancel", "disconnect" }, connection.Calls);
}
[TestMethod]
public async Task CommandsFromAnotherPageAreRefused()
{
var connection = new RecordingConnection();
await using var server = await Part2.StartAsync(services: s => s.AddSingleton<IConnectionService>(connection));
foreach (var path in new[] { "/api/connection/begin", "/api/connection/finish", "/api/connection/disconnect" })
{
using var request = server.Request(HttpMethod.Post, path, new { openLogin = true }, origin: "http://altro.example");
using var response = await server.Client.SendAsync(request);
Assert.AreEqual(HttpStatusCode.Forbidden, response.StatusCode, path);
}
using var crossSite = server.Request(HttpMethod.Post, "/api/connection/disconnect", origin: null);
crossSite.Headers.Add("Sec-Fetch-Site", "cross-site");
using var crossResponse = await server.Client.SendAsync(crossSite);
Assert.AreEqual(HttpStatusCode.Forbidden, crossResponse.StatusCode);
Assert.IsEmpty(connection.Calls, "no command reached the service");
}
[TestMethod]
public async Task CapabilitiesListTheConfigurationProblems()
{
await using (var clean = await Part2.StartAsync())
{
var caps = await clean.GetJsonAsync("/api/capabilities");
Assert.AreEqual(0, caps.GetProperty("problems").GetArrayLength(), "the default registration has no problems");
}
var problem = new ConfigurationProblem("password-mancante", "Manca la password dell'interfaccia", "Il motore non è partito.", "Imposta FEBE_PASSWORD e riavvia.");
await using var server = await Part2.StartAsync(services: s => s.AddSingleton<IConfigurationProblems>(new FixedProblems(problem)));
var listed = (await server.GetJsonAsync("/api/capabilities")).Items("problems").ToList();
Assert.HasCount(1, listed);
Assert.AreEqual("password-mancante", listed[0].Str("code"));
Assert.AreEqual(problem.Title, listed[0].Str("title"));
Assert.AreEqual(problem.Message, listed[0].Str("message"));
Assert.AreEqual(problem.Remedy, listed[0].Str("remedy"));
}
}
+148
View File
@@ -0,0 +1,148 @@
using System.Net;
using System.Text.Json;
using Febe.Tests.Support;
using Febe.Tests.Web.Support;
using Febe.Web.Demo;
namespace Febe.Tests.Web;
/// <summary>
/// The demo of the second part (spec §10.6): every page works with coherent fake data and the scenes normale,
/// sessione, fermo, scollegato and errore; /importa?passo=3 has a realistic review; there are duplicates to decide.
/// </summary>
[TestClass]
public sealed class DemoPart2Tests
{
private static TempFolder? s_temp;
private static DemoHost? s_demo;
private static HttpClient? s_client;
private static HttpClient Client => s_client ?? throw new InvalidOperationException("demo not started");
[ClassInitialize]
public static async Task StartDemoAsync(TestContext context)
{
s_temp = new TempFolder("demo2");
s_demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, s_temp.Path));
s_client = new HttpClient { BaseAddress = s_demo.Address, Timeout = TimeSpan.FromSeconds(60) };
}
[ClassCleanup]
public static async Task StopDemoAsync()
{
s_client?.Dispose();
if (s_demo is not null)
{
await s_demo.DisposeAsync();
}
s_temp?.Dispose();
}
private static async Task<JsonElement> GetAsync(string path)
{
using var response = await Client.GetAsync(path);
var text = await response.Content.ReadAsStringAsync();
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, $"{path}: {text}");
return JsonDocument.Parse(text).RootElement.Clone();
}
[TestMethod]
public async Task TheConnectionFollowsTheScene()
{
Assert.AreEqual("connected", (await GetAsync("/api/connection?scena=normale")).Str("state"));
Assert.AreEqual("tuo.profilo", (await GetAsync("/api/connection?scena=sessione")).Str("username"));
var login = await GetAsync("/api/connection?scena=scollegato");
Assert.AreEqual("notConnected", login.Str("state"));
StringAssert.Contains(login.Str("currentUrl"), "/accounts/login/");
Assert.AreEqual("verificationRequired", (await GetAsync("/api/connection?scena=fermo")).Str("state"));
using var request = new HttpRequestMessage(HttpMethod.Post, "/api/connection/finish?scena=scollegato");
request.Headers.Add("Origin", s_demo!.Address.GetLeftPart(UriPartial.Authority));
using var response = await Client.SendAsync(request);
var finish = JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement;
Assert.IsFalse(finish.Bool("connected"), "no real browser in the demo: it says so");
StringAssert.StartsWith(finish.Str("message"), "Dimostrazione");
}
[TestMethod]
public async Task TheSceneErroreShowsOnlyTheMissingPassword()
{
var problems = (await GetAsync("/api/capabilities?scena=errore")).Items("problems").ToList();
Assert.HasCount(1, problems);
Assert.AreEqual("password-mancante", problems[0].Str("code"));
StringAssert.Contains(problems[0].Str("remedy"), "FEBE_PASSWORD");
Assert.AreEqual(0, (await GetAsync("/api/capabilities?scena=normale")).GetProperty("problems").GetArrayLength());
Assert.AreEqual("Off", (await GetAsync("/api/engine?scena=errore")).GetProperty("snapshot").Str("mode"));
}
[TestMethod]
public async Task TheImportReviewIsReadyWithEveryKindOfRow()
{
var overview = await GetAsync("/api/import");
var run = overview.Items("runs").Single(r => r.Str("state") == "reviewing");
var review = await GetAsync($"/api/import/{run.Long("id")}/review");
var outcomes = review.GetProperty("outcomes");
Assert.IsGreaterThan(0, outcomes.Int("new"));
Assert.IsGreaterThan(0, outcomes.Int("alreadyInLibrary"));
Assert.IsGreaterThan(0, outcomes.Int("probableDuplicates"));
Assert.IsGreaterThan(0, outcomes.Int("unrecognized"));
Assert.IsGreaterThan(0, review.Int("recognized"), "names in Febe's own scheme give date and code");
var folders = review.Items("folders").ToList();
Assert.IsTrue(folders.Any(f => f.Bool("blocked")), "a folder without account name");
Assert.IsTrue(folders.Any(f => f.GetProperty("target").Str("kind") == "existing"));
Assert.IsTrue(folders.Any(f => f.GetProperty("target").Str("kind") == "newArchiveAccount"));
Assert.IsNotNull(review.GetProperty("plan").Str("leftOutLabel"));
var duplicates = await GetAsync($"/api/import/{run.Long("id")}/duplicates?all=true");
Assert.IsTrue(duplicates.Items("cases").All(c => c.Str("decision") == "pending"), "nothing is chosen in advance");
}
[TestMethod]
public async Task DuplicatesAfterADownloadWaitInTheReview()
{
Assert.AreEqual(3, (await GetAsync("/api/duplicates/count")).Int("download"));
var page = await GetAsync("/api/duplicates");
Assert.HasCount(3, page.Items("cases").ToList());
foreach (var c in page.Items("cases"))
{
Assert.AreEqual(c.GetProperty("existing").Str("username"), c.GetProperty("candidate").Str("username"), "a download pair is inside one account");
using var image = await Client.GetAsync(c.GetProperty("candidate").Str("image"));
Assert.AreEqual(HttpStatusCode.OK, image.StatusCode, "the thumbnail of the downloaded copy exists");
}
}
[TestMethod]
public async Task TheBrowserPreviewAndTheStopsFollowTheScene()
{
var session = await GetAsync("/api/browser/preview?scena=sessione");
Assert.IsTrue(session.Bool("hasFrame"));
using (var frame = await Client.GetAsync(session.Str("frame") + "&scena=sessione"))
{
Assert.AreEqual(HttpStatusCode.OK, frame.StatusCode);
Assert.AreEqual("image/jpeg", frame.Content.Headers.ContentType?.MediaType);
}
Assert.IsFalse((await GetAsync("/api/browser/preview?scena=normale")).Bool("hasFrame"), "between sessions the browser rests on a blank page");
var stopped = (await GetAsync("/api/engine/incidents?scena=fermo")).Items("items").ToList();
Assert.IsTrue(stopped.Any(i => i.Bool("open") && i.Str("level") == "challenge"));
var normal = (await GetAsync("/api/engine/incidents?scena=normale")).Items("items").ToList();
Assert.IsTrue(normal.All(i => !i.Bool("open")));
}
[TestMethod]
public async Task EverySettingsPageHasItsData()
{
Assert.AreEqual("prudent", (await GetAsync("/api/settings/limits")).Str("profile"));
var general = await GetAsync("/api/settings/general?veste=desktop");
Assert.IsFalse(general.Bool("foldersReadOnly"));
Assert.IsTrue(general.Bool("canChangeDataFolder"));
Assert.IsTrue(general.GetProperty("autostart").ValueKind is JsonValueKind.True or JsonValueKind.False, "«Avvio» on the desktop look");
var docker = await GetAsync("/api/settings/general?veste=docker");
Assert.IsTrue(docker.Bool("foldersReadOnly"));
Assert.AreEqual(JsonValueKind.Null, docker.GetProperty("autostart").ValueKind);
Assert.AreEqual("marta.demo", general.GetProperty("preview").Str("accountFolder"), "the preview of mockup 08");
await GetAsync("/api/settings/notifications");
await GetAsync("/api/settings/data");
Assert.AreEqual("Windows", (await GetAsync("/api/about?veste=desktop")).Str("edition"));
}
}
+174
View File
@@ -0,0 +1,174 @@
using System.Net;
using System.Text;
using System.Text.Json;
using Febe.Tests.Support;
using Febe.Tests.Web.Part2Support;
using Febe.Tests.Web.Support;
using Febe.Web;
namespace Febe.Tests.Web;
/// <summary>
/// Importa over the API (spec §9, mockup 09): the web host builds its own <c>ImportService</c> over the library when the
/// composition registers none; the four steps work end to end; a folder without account blocks only its files; the
/// duplicates wait with nothing decided; the report and its CSV; the import's own errors become Italian answers.
/// </summary>
[TestClass]
public sealed class ImportApiTests
{
private static async Task<JsonElement> WaitForStateAsync(WebTestServer server, long id, params string[] states)
{
JsonElement progress = default;
await Part2.WaitUntilAsync(async () =>
{
progress = await server.GetJsonAsync($"/api/import/{id}/progress");
return !progress.Bool("running") && states.Contains(progress.Str("state"));
}, "import state " + string.Join("/", states));
return progress;
}
[TestMethod]
public async Task TheFourStepsFromSourceToReport()
{
await using var server = await Part2.StartAsync(FebeEdition.Desktop);
var source = server.Temp.Combine("vecchio-disco");
Part2.WritePhoto(Path.Combine(source, "anna.prova", "IMG_20240612_101500.jpg"), 11);
Part2.WritePhoto(Path.Combine(source, "anna.prova", "IMG_20240613_101500.jpg"), 12);
Part2.WritePhoto(Path.Combine(source, "anna.prova", "IMG_20240614_101500.jpg"), 13, 600, 733);
Part2.WritePhoto(Path.Combine(source, "Foto sparse", "IMG_20220101_120000.jpg"), 13, 900, 1100);
await File.WriteAllTextAsync(Path.Combine(source, "Foto sparse", "note.txt"), "appunti");
var overview = await server.GetJsonAsync("/api/import");
Assert.AreEqual(0, overview.GetProperty("runs").GetArrayLength());
Assert.AreEqual(JsonValueKind.Null, overview.GetProperty("sourceRoot").ValueKind, "desktop: any folder");
var (inspectStatus, info) = await server.SendJsonAsync(HttpMethod.Post, "/api/import/inspect", new { path = source });
Assert.AreEqual(HttpStatusCode.OK, inspectStatus);
Assert.IsTrue(info.Bool("canMove"));
CollectionAssert.AreEquivalent(new[] { "anna.prova", "Foto sparse" }, info.Items("folders").Select(f => f.GetString()).ToArray());
// Step 2: the analysis, read-only.
var (startStatus, run) = await server.SendJsonAsync(HttpMethod.Post, "/api/import/start", new { path = source, stogram = false });
Assert.AreEqual(HttpStatusCode.OK, startStatus);
var id = run.Long("id");
await WaitForStateAsync(server, id, "reviewing");
Assert.HasCount(5, Directory.GetFiles(source, "*", SearchOption.AllDirectories), "the analysis touches nothing");
// Step 3: the review.
var review = await server.GetJsonAsync($"/api/import/{id}/review");
Assert.AreEqual(5, review.Int("files"));
Assert.AreEqual(1, review.GetProperty("outcomes").Int("unrecognized"));
Assert.IsTrue(review.Bool("canMove"));
var folders = review.Items("folders").ToDictionary(f => f.Str("displayName"));
Assert.AreEqual("newArchiveAccount", folders["anna.prova"].GetProperty("target").Str("kind"));
Assert.AreEqual("none", folders["Foto sparse"].GetProperty("target").Str("kind"));
Assert.IsTrue(folders["Foto sparse"].Bool("blocked"), "a folder without account blocks only its files");
StringAssert.Contains(review.GetProperty("plan").Str("leftOutLabel"), "aspettano la tua decisione", "a duplicate without decision waits");
// The two copies of scene 13 are a probable duplicate inside the source: nothing decided in advance.
var duplicates = await server.GetJsonAsync($"/api/import/{id}/duplicates?all=true");
var pair = duplicates.Items("cases").Single();
Assert.AreEqual("pending", pair.Str("decision"));
Assert.IsTrue(pair.Bool("insideSource"));
StringAssert.StartsWith(pair.GetProperty("candidate").Str("image"), "/api/import/files/");
using (var preview = await server.Client.GetAsync(pair.GetProperty("candidate").Str("image")))
{
Assert.AreEqual(HttpStatusCode.OK, preview.StatusCode);
Assert.AreEqual("image/jpeg", preview.Content.Headers.ContentType?.MediaType);
}
var (decideStatus, decided) = await server.SendJsonAsync(HttpMethod.Post, $"/api/import/{id}/duplicates/{pair.Long("pairId")}", new { decision = "keepBoth", applyToAll = false });
Assert.AreEqual(HttpStatusCode.OK, decideStatus);
Assert.AreEqual(0, decided.Int("pending"));
var afterDecision = await server.GetJsonAsync($"/api/import/{id}/review");
StringAssert.Contains(afterDecision.GetProperty("plan").Str("leftOutLabel"), "1 cartella senza account");
var (targetStatus, updated) = await server.SendJsonAsync(HttpMethod.Put, $"/api/import/{id}/folders", new { folder = folders["Foto sparse"].Str("folder"), kind = "newArchiveAccount", username = "sparse.prova" });
Assert.AreEqual(HttpStatusCode.OK, targetStatus);
var updatedPlan = updated.GetProperty("plan");
Assert.AreEqual(JsonValueKind.Null, updatedPlan.GetProperty("leftOutLabel").ValueKind);
Assert.AreEqual(4, updatedPlan.Int("toImport"));
Assert.AreEqual("Importa 4 file", updatedPlan.Str("buttonLabel"));
var (modeStatus, modePlan) = await server.SendJsonAsync(HttpMethod.Put, $"/api/import/{id}/mode", new { mode = "copy" });
Assert.AreEqual(HttpStatusCode.OK, modeStatus);
Assert.AreEqual("copy", modePlan.Str("mode"));
// Step 4: the copy, then the report and the CSV.
var (copyStatus, _) = await server.SendJsonAsync(HttpMethod.Post, $"/api/import/{id}/copy", new { mode = "copy" });
Assert.AreEqual(HttpStatusCode.OK, copyStatus);
await WaitForStateAsync(server, id, "completed");
var report = await server.GetJsonAsync($"/api/import/{id}/report");
Assert.AreEqual(4, report.Int("copied"));
Assert.AreEqual(0, report.Int("failed"));
Assert.HasCount(5, Directory.GetFiles(source, "*", SearchOption.AllDirectories), "«Copia» leaves the originals where they are");
var accounts = await server.GetJsonAsync("/api/accounts");
Assert.IsTrue(accounts.Items("accounts").Any(a => a.Str("username") == "sparse.prova" && a.Str("state") == "archiveOnly"));
using var csv = await server.Client.GetAsync($"/api/import/{id}/report.csv");
Assert.AreEqual(HttpStatusCode.OK, csv.StatusCode);
Assert.AreEqual("text/csv", csv.Content.Headers.ContentType?.MediaType);
var bytes = await csv.Content.ReadAsByteArrayAsync();
CollectionAssert.AreEqual(Encoding.UTF8.GetPreamble(), bytes.Take(3).ToArray(), "UTF-8 with BOM for Excel");
StringAssert.Contains(Encoding.UTF8.GetString(bytes), ";");
StringAssert.Contains(csv.Content.Headers.ContentDisposition?.ToString() ?? string.Empty, ".csv");
}
[TestMethod]
public async Task TheAnalysisCanBeInterruptedResumedAndDiscarded()
{
await using var server = await Part2.StartAsync(FebeEdition.Desktop);
var source = server.Temp.Combine("sorgente");
for (var i = 0; i < 6; i++)
{
Part2.WritePhoto(Path.Combine(source, "luca.prova", $"IMG_2024061{i}_101500.jpg"), 200 + i, 500, 600);
}
var (_, run) = await server.SendJsonAsync(HttpMethod.Post, "/api/import/start", new { path = source, stogram = false });
var id = run.Long("id");
var (interruptStatus, _) = await server.SendJsonAsync(HttpMethod.Post, $"/api/import/{id}/interrupt");
Assert.AreEqual(HttpStatusCode.OK, interruptStatus);
var state = (await WaitForStateAsync(server, id, "analysisInterrupted", "reviewing")).Str("state");
if (state == "analysisInterrupted")
{
var (resumeStatus, _) = await server.SendJsonAsync(HttpMethod.Post, $"/api/import/{id}/resume");
Assert.AreEqual(HttpStatusCode.OK, resumeStatus);
await WaitForStateAsync(server, id, "reviewing");
}
var (againStatus, again) = await server.SendJsonAsync(HttpMethod.Post, $"/api/import/{id}/resume");
Assert.AreEqual(HttpStatusCode.BadRequest, againStatus, "nothing to resume once reviewing");
Assert.IsFalse(string.IsNullOrWhiteSpace(again.Str("message")));
var (discardStatus, _) = await server.SendJsonAsync(HttpMethod.Post, $"/api/import/{id}/discard");
Assert.AreEqual(HttpStatusCode.OK, discardStatus);
var (gone, _, _) = await server.GetAsync($"/api/import/{id}/review");
Assert.AreEqual(HttpStatusCode.NotFound, gone, "nothing copied: the import disappears");
Assert.HasCount(6, Directory.GetFiles(source, "*", SearchOption.AllDirectories));
}
[TestMethod]
public async Task ErrorsOfTheImportAreItalianAnswers()
{
await using (var desktop = await Part2.StartAsync(FebeEdition.Desktop))
{
var (status, error) = await desktop.SendJsonAsync(HttpMethod.Post, "/api/import/inspect", new { path = desktop.Temp.Combine("non-esiste") });
Assert.AreEqual(HttpStatusCode.BadRequest, status);
Assert.IsFalse(string.IsNullOrWhiteSpace(error.Str("message")));
var (dataStatus, _) = await desktop.SendJsonAsync(HttpMethod.Post, "/api/import/inspect", new { path = desktop.Library.Data.Root });
Assert.AreEqual(HttpStatusCode.BadRequest, dataStatus, "the Data folder is never a source");
var (missing, _, _) = await desktop.GetAsync("/api/import/4242/review");
Assert.AreEqual(HttpStatusCode.NotFound, missing);
var (sources, _, _) = await desktop.GetAsync("/api/import/sources");
Assert.AreEqual(HttpStatusCode.BadRequest, sources, "desktop: the native picker, no listing");
}
// Docker: the sources live under /importa (absent on this machine: the listing says so).
await using var docker = await Part2.StartAsync();
var overview = await docker.GetJsonAsync("/api/import");
Assert.AreEqual("/importa", overview.Str("sourceRoot"));
Assert.IsFalse(overview.Bool("pickFolder"));
var (pick, _) = await docker.SendJsonAsync(HttpMethod.Post, "/api/import/pick-folder");
Assert.AreEqual(HttpStatusCode.BadRequest, pick);
}
}
@@ -0,0 +1,103 @@
using System.Net;
using System.Text.Json;
using Febe.Tests.Support;
using Febe.Tests.Web.Support;
using Febe.Web;
using Febe.Web.Connection;
using Microsoft.Extensions.DependencyInjection;
namespace Febe.Tests.Web.Part2Support;
/// <summary>Helpers of the tests of the second part of the interface (Attività, Impostazioni, Importa, Collegamento).</summary>
internal static class Part2
{
/// <summary>A web server for one test, imitating the given shell (Docker by default, like a real container).</summary>
public static Task<WebTestServer> StartAsync(FebeEdition edition = FebeEdition.Docker, Action<IServiceCollection>? services = null) =>
WebTestServer.StartAsync(new FebeWebOptions { Access = AccessMode.None, Edition = edition }, services);
/// <summary>Polls until the condition holds (background jobs: analysis, copy, rebuild).</summary>
public static async Task WaitUntilAsync(Func<Task<bool>> condition, string what, int seconds = 60)
{
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(seconds);
while (DateTime.UtcNow < deadline)
{
if (await condition())
{
return;
}
await Task.Delay(100);
}
Assert.Fail($"timeout: {what}");
}
/// <summary>GET that returns status and body without asserting.</summary>
public static async Task<(HttpStatusCode Status, string Text, JsonElement Json)> GetAsync(this WebTestServer server, string path)
{
using var response = await server.Client.GetAsync(path);
var text = await response.Content.ReadAsStringAsync();
var json = text.Length > 0 && (response.Content.Headers.ContentType?.MediaType?.Contains("json", StringComparison.Ordinal) ?? false)
? JsonDocument.Parse(text).RootElement.Clone()
: default;
return (response.StatusCode, text, json);
}
/// <summary>A command whose body is returned as text too (to check what it does not contain).</summary>
public static async Task<(HttpStatusCode Status, string Text)> SendTextAsync(this WebTestServer server, HttpMethod method, string path, object? body = null, string? origin = "")
{
using var request = server.Request(method, path, body, origin);
using var response = await server.Client.SendAsync(request);
return (response.StatusCode, await response.Content.ReadAsStringAsync());
}
/// <summary>Writes a JPEG of a generated scene.</summary>
public static void WritePhoto(string path, int scene, int width = 900, int height = 1100)
{
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
File.WriteAllBytes(path, TestFile.PhotoBytes(scene, width, height));
}
}
/// <summary>Configuration problems chosen by the test.</summary>
internal sealed class FixedProblems(params ConfigurationProblem[] problems) : IConfigurationProblems
{
public IReadOnlyList<ConfigurationProblem> Current { get; } = problems;
}
/// <summary>A connection service that records what the API asks.</summary>
internal sealed class RecordingConnection : IConnectionService
{
public List<string> Calls { get; } = [];
public ConnectionStatus Status { get; set; } = new(ConnectionState.NotConnected, null, null, false, "https://www.instagram.com/accounts/login/");
public Task<ConnectionStatus> GetStatusAsync(CancellationToken ct) => Task.FromResult(Status);
public Task BeginUserDrivingAsync(bool openLogin, CancellationToken ct)
{
Calls.Add("begin:" + openLogin);
Status = Status with { UserIsDriving = true };
return Task.CompletedTask;
}
public Task<FinishResult> FinishAsync(CancellationToken ct)
{
Calls.Add("finish");
Status = new ConnectionStatus(ConnectionState.Connected, "tuo.profilo", "Il tuo profilo", false, null);
return Task.FromResult(new FinishResult(true, "Sei collegato come @tuo.profilo."));
}
public Task CancelAsync(CancellationToken ct)
{
Calls.Add("cancel");
return Task.CompletedTask;
}
public Task DisconnectAsync(CancellationToken ct)
{
Calls.Add("disconnect");
Status = new ConnectionStatus(ConnectionState.NotConnected, null, null, false, null);
return Task.CompletedTask;
}
}
+282
View File
@@ -0,0 +1,282 @@
using System.Net;
using Febe.Core.Alerts;
using Febe.Core.Engine;
using Febe.Core.Library;
using Febe.Tests.Support;
using Febe.Tests.Web.Part2Support;
using Febe.Tests.Web.Support;
using Febe.Web;
using Febe.Web.Native;
using Microsoft.Extensions.DependencyInjection;
namespace Febe.Tests.Web;
/// <summary>
/// Impostazioni over the API (spec §4.7, §7.5, §8.5, §13.3): naming schemes with their preview and errors, the library
/// folder (desktop only, existing accounts keep their folders), the limits of §7.5 with Italian messages, the
/// notifications (the bot token is never sent back), backups and the rebuild of the database.
/// </summary>
[TestClass]
public sealed class SettingsApiTests
{
[TestMethod]
public async Task GeneralShowsTheSchemesWithPreviewAndRefusesWrongOnes()
{
await using var server = await Part2.StartAsync();
await server.Db.Accounts.AddAsync(Make.Account("marta.prova"));
var general = await server.GetJsonAsync("/api/settings/general");
Assert.AreEqual(NamingScheme.DefaultGeneral, general.Str("namingScheme"));
Assert.AreEqual(NamingScheme.DefaultHighlight, general.Str("highlightScheme"));
Assert.IsTrue(general.Bool("foldersReadOnly"), "Docker: folders change from the container");
Assert.IsTrue(general.Bool("setFileTime"));
Assert.AreEqual(JsonValueKindNull, general.GetProperty("autostart").ValueKind, "the «Avvio» block exists only on Windows");
var preview = general.GetProperty("preview");
Assert.AreEqual("marta.prova", preview.Str("accountFolder"));
Assert.IsTrue(preview.Items("folders").Any(f => f.Items("files").Any(x => x.Str("name").EndsWith("_DBx3kQ2_2.jpg", StringComparison.Ordinal))));
var bad = await server.SendJsonAsync(HttpMethod.Post, "/api/settings/naming-preview", new { namingScheme = "{account}\\{sconosciuto}", highlightScheme = NamingScheme.DefaultHighlight });
Assert.AreEqual(HttpStatusCode.OK, bad.Status);
Assert.IsTrue(bad.Body.Items("errors").Any(e => e.GetString()!.StartsWith("Schema:", StringComparison.Ordinal)));
var (status, error) = await server.SendJsonAsync(HttpMethod.Put, "/api/settings/general",
new { namingScheme = "{account}\\{sconosciuto}", highlightScheme = NamingScheme.DefaultHighlight, setFileTime = true });
Assert.AreEqual(HttpStatusCode.BadRequest, status);
StringAssert.StartsWith(error.Str("message"), "Schema:");
const string scheme = @"{account}\{tipo}\{data}_{codice}_{n}";
var (okStatus, saved) = await server.SendJsonAsync(HttpMethod.Put, "/api/settings/general", new { namingScheme = scheme, highlightScheme = NamingScheme.DefaultHighlight, setFileTime = false });
Assert.AreEqual(HttpStatusCode.OK, okStatus);
Assert.AreEqual(scheme, saved.Str("namingScheme"));
Assert.IsFalse(saved.Bool("setFileTime"));
var stored = await LibrarySettings.LoadAsync(server.Db.Settings, server.Library.Layout.Root);
Assert.AreEqual(scheme, stored.Naming.General.Text);
Assert.IsFalse(stored.SetFileTimeToPublication);
}
private const System.Text.Json.JsonValueKind JsonValueKindNull = System.Text.Json.JsonValueKind.Null;
[TestMethod]
public async Task TheLibraryFolderChangesOnlyOnTheDesktopAndAccountsKeepTheirFiles()
{
await using (var docker = await Part2.StartAsync())
{
var (status, _) = await docker.SendJsonAsync(HttpMethod.Put, "/api/settings/general",
new { libraryFolder = docker.Temp.Combine("altrove"), namingScheme = NamingScheme.DefaultGeneral, highlightScheme = NamingScheme.DefaultHighlight, setFileTime = true });
Assert.AreEqual(HttpStatusCode.BadRequest, status);
}
await using var server = await Part2.StartAsync(FebeEdition.Desktop);
var withFiles = await server.Db.Accounts.AddAsync(Make.Account("con.file"));
var empty = await server.Db.Accounts.AddAsync(Make.Account("senza.file"));
var oldFolder = server.Library.Layout.AccountFolder(withFiles);
Directory.CreateDirectory(oldFolder);
var newRoot = server.Temp.Combine("nuova-libreria");
var (inside, insideError) = await server.SendJsonAsync(HttpMethod.Put, "/api/settings/general",
new { libraryFolder = server.Temp.Combine("dati", "libreria"), namingScheme = NamingScheme.DefaultGeneral, highlightScheme = NamingScheme.DefaultHighlight, setFileTime = true });
Assert.AreEqual(HttpStatusCode.BadRequest, inside);
StringAssert.Contains(insideError.Str("message"), "cartella dei dati");
var (status2, general) = await server.SendJsonAsync(HttpMethod.Put, "/api/settings/general",
new { libraryFolder = newRoot, namingScheme = NamingScheme.DefaultGeneral, highlightScheme = NamingScheme.DefaultHighlight, setFileTime = true });
Assert.AreEqual(HttpStatusCode.OK, status2);
Assert.AreEqual(newRoot, general.GetProperty("library").Str("path"));
Assert.AreEqual(newRoot, server.Library.Layout.Root);
Assert.IsTrue(Directory.Exists(newRoot));
var kept = (await server.Db.Accounts.GetAsync(withFiles.Id))!;
Assert.AreEqual(oldFolder, server.Library.Layout.AccountFolder(kept), "an account with files keeps its folder");
var moved = (await server.Db.Accounts.GetAsync(empty.Id))!;
Assert.AreEqual(Path.Combine(newRoot, "senza.file"), server.Library.Layout.AccountFolder(moved), "an account without files goes in the new library");
}
[TestMethod]
public async Task LimitsKeepTheBoundsOfTheSpecWithItalianMessages()
{
await using var server = await Part2.StartAsync();
var limits = await server.GetJsonAsync("/api/settings/limits");
Assert.AreEqual("prudent", limits.Str("profile"));
Assert.AreEqual(3, limits.GetProperty("presets").GetArrayLength());
var rules = limits.GetProperty("rules");
Assert.AreEqual(5, rules.Int("minPauseMinutes"));
Assert.AreEqual(30, rules.Int("maxSessionMinutes"));
Assert.AreEqual(20, rules.Int("maxWindowHours"));
var current = limits.GetProperty("current");
var kinds = current.Items("budgets").Select(b => b.Str("kind")).ToList();
CollectionAssert.AreEqual(new[] { "Home", "ProfileOpen", "StoryView", "BackfillPage", "SinglePost", "FollowingListPage" }, kinds, "every row of the table of §7.5");
CollectionAssert.AreEqual(new[] { "1 ora", "6 ore", "24 ore" }, limits.Items("stops").Select(s => s.GetString()).ToArray());
object Body(Func<Dictionary<string, object?>, Dictionary<string, object?>> edit, string profile = "custom")
{
var values = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, object?>>(current.GetRawText(), WebTestServer.Json)!;
return new { profile, values = edit(values), pace = "natural", gradualStart = true, activeDays = new[] { 0, 1, 2, 3, 4, 5, 6 } };
}
async Task<string> RefusedAsync(object body)
{
var (status, error) = await server.SendJsonAsync(HttpMethod.Put, "/api/settings/limits", body);
Assert.AreEqual(HttpStatusCode.BadRequest, status);
return error.Str("message");
}
StringAssert.Contains(await RefusedAsync(Body(v => { v["sessionMaxMinutes"] = 45; return v; })), "Una sessione non può durare più di 30 minuti");
StringAssert.Contains(await RefusedAsync(Body(v => { v["pauseMinMinutes"] = 3; return v; })), "La pausa minima non può scendere sotto i 5 minuti");
StringAssert.Contains(await RefusedAsync(Body(v => { v["windowStart"] = "02:00"; v["windowEnd"] = "23:30"; return v; })), "20 ore");
StringAssert.Contains(await RefusedAsync(Body(v => { v["windowStart"] = "sette"; return v; })), "07:30");
StringAssert.Contains(await RefusedAsync(new { profile = "prudent", pace = "natural", gradualStart = true, activeDays = Array.Empty<int>() }), "almeno un giorno");
var tooMany = Body(v =>
{
var budgets = System.Text.Json.JsonSerializer.Deserialize<List<Dictionary<string, object?>>>(System.Text.Json.JsonSerializer.Serialize(v["budgets"]), WebTestServer.Json)!;
budgets[1]["perDay"] = 601;
v["budgets"] = budgets;
return v;
});
StringAssert.Contains(await RefusedAsync(tooMany), "doppio di «Rapido»");
var (okStatus, saved) = await server.SendJsonAsync(HttpMethod.Put, "/api/settings/limits", Body(v => { v["sessionMaxMinutes"] = 12; v["pauseMinMinutes"] = 25; return v; }));
Assert.AreEqual(HttpStatusCode.OK, okStatus);
Assert.AreEqual("custom", saved.Str("profile"));
var settings = await EngineSettingsStore.LoadAsync(server.Db.Settings);
Assert.AreEqual(Febe.Core.Domain.CautionProfileKind.Custom, settings.ProfileKind);
Assert.AreEqual(TimeSpan.FromMinutes(12), settings.EffectiveProfile.SessionMax);
Assert.AreEqual(TimeSpan.FromMinutes(25), settings.EffectiveProfile.PauseMin);
var (fastStatus, fast) = await server.SendJsonAsync(HttpMethod.Put, "/api/settings/limits", new { profile = "fast", pace = "brisk", gradualStart = false, activeDays = new[] { 1, 2, 3, 4, 5 } });
Assert.AreEqual(HttpStatusCode.OK, fastStatus);
Assert.AreEqual("fast", fast.Str("profile"));
Assert.AreEqual("brisk", fast.Str("pace"));
Assert.IsFalse(fast.Bool("gradualStart"));
CollectionAssert.AreEqual(new[] { 1, 2, 3, 4, 5 }, fast.Items("activeDays").Select(d => d.GetInt32()).ToArray());
Assert.IsNotNull((await EngineSettingsStore.LoadAsync(server.Db.Settings)).Custom, "the «Su misura» values stay stored for later");
}
[TestMethod]
public async Task NotificationsNeverSendTheBotTokenBack()
{
await using var server = await Part2.StartAsync();
var initial = await server.GetJsonAsync("/api/settings/notifications");
Assert.IsTrue(initial.GetProperty("events").Bool("verification"));
Assert.IsFalse(initial.Bool("telegramTokenSet"));
Assert.IsFalse(initial.Bool("windowsAvailable"), "Docker has no Windows notifications");
const string token = "123456789:AAEsegretissimoNonDaMostrare_xyz";
var events = new { verification = true, disconnection = true, throttle = false, backfillDone = true, diskLow = true, unknownFormat = false };
var (status, text) = await server.SendTextAsync(HttpMethod.Put, "/api/settings/notifications",
new { events, windows = false, telegramChatId = "987654", telegramToken = token, removeTelegramToken = false });
Assert.AreEqual(HttpStatusCode.OK, status);
Assert.DoesNotContain(token, text, "the token is not echoed back");
Assert.DoesNotContain("segretissimo", text);
var (_, getText, saved) = await server.GetAsync("/api/settings/notifications");
Assert.DoesNotContain(token, getText);
Assert.IsTrue(saved.Bool("telegramTokenSet"));
Assert.AreEqual("987654", saved.Str("telegramChatId"));
Assert.IsFalse(saved.GetProperty("events").Bool("throttle"));
Assert.AreEqual(token, (await AlertSettingsStore.LoadAsync(server.Db.Settings)).TelegramToken, "stored in the settings of the Data folder");
// An empty token keeps the stored one; «Togli il gettone» removes it.
await server.SendJsonAsync(HttpMethod.Put, "/api/settings/notifications", new { events, windows = false, telegramChatId = "987654", telegramToken = "", removeTelegramToken = false });
Assert.AreEqual(token, (await AlertSettingsStore.LoadAsync(server.Db.Settings)).TelegramToken);
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"));
var (windowsStatus, _) = await server.SendJsonAsync(HttpMethod.Post, "/api/settings/notifications/test", new { channel = "windows" });
Assert.AreEqual(HttpStatusCode.BadRequest, windowsStatus);
var (badStatus, badText) = await server.SendTextAsync(HttpMethod.Put, "/api/settings/notifications",
new { events, windows = false, telegramChatId = "987654", telegramToken = "con spazi dentro", removeTelegramToken = false });
Assert.AreEqual(HttpStatusCode.BadRequest, badStatus);
Assert.DoesNotContain("con spazi", badText, "a refused token is not echoed either");
await server.SendJsonAsync(HttpMethod.Put, "/api/settings/notifications", new { events, windows = false, telegramChatId = "987654", telegramToken = (string?)null, removeTelegramToken = true });
Assert.IsNull((await AlertSettingsStore.LoadAsync(server.Db.Settings)).TelegramToken);
Assert.IsFalse((await server.GetJsonAsync("/api/settings/notifications")).Bool("telegramTokenSet"));
}
[TestMethod]
public async Task WindowsNotificationsUseTheNativeShell()
{
var shell = new NotifyingShell();
await using var server = await Part2.StartAsync(FebeEdition.Desktop, s => s.AddSingleton<INativeShell>(shell));
Assert.IsTrue((await server.GetJsonAsync("/api/settings/notifications")).Bool("windowsAvailable"));
var (status, result) = await server.SendJsonAsync(HttpMethod.Post, "/api/settings/notifications/test", new { channel = "windows" });
Assert.AreEqual(HttpStatusCode.OK, status);
Assert.IsTrue(result.Bool("sent"));
Assert.AreEqual(1, shell.Notifications);
}
[TestMethod]
public async Task BackupsAndTheRebuildOfTheDatabase()
{
await using var server = await Part2.StartAsync();
var data = await server.GetJsonAsync("/api/settings/data");
Assert.AreEqual(0, data.GetProperty("backups").GetArrayLength());
Assert.AreEqual(7, data.Int("keepDays"));
Assert.IsFalse(data.GetProperty("rebuild").Bool("running"));
var (status, message) = await server.SendJsonAsync(HttpMethod.Post, "/api/settings/backups");
Assert.AreEqual(HttpStatusCode.OK, status);
StringAssert.Contains(message.Str("message"), "febe-2026-10-13.sqlite");
await server.SendJsonAsync(HttpMethod.Post, "/api/settings/backups");
var backups = (await server.GetJsonAsync("/api/settings/data")).Items("backups").ToList();
Assert.HasCount(1, backups, "one copy per day: a new copy replaces today's");
Assert.AreEqual("2026-10-13", backups[0].Str("day"));
var (wrong, wrongError) = await server.SendJsonAsync(HttpMethod.Post, "/api/settings/rebuild", new { confirm = "sì" });
Assert.AreEqual(HttpStatusCode.BadRequest, wrong);
StringAssert.Contains(wrongError.Str("message"), "ricostruisci");
var account = await server.Db.Accounts.AddAsync(Make.Account("giornale.prova"));
var folder = server.Library.Layout.AccountFolder(account);
Part2.WritePhoto(Path.Combine(folder, "post", "foto.jpg"), 3);
var (started, _) = await server.SendJsonAsync(HttpMethod.Post, "/api/settings/rebuild", new { confirm = "Ricostruisci" });
Assert.AreEqual(HttpStatusCode.OK, started);
await Part2.WaitUntilAsync(async () => !(await server.GetJsonAsync("/api/settings/rebuild")).Bool("running"), "rebuild");
var rebuild = await server.GetJsonAsync("/api/settings/rebuild");
Assert.AreEqual(System.Text.Json.JsonValueKind.Null, rebuild.GetProperty("error").ValueKind);
Assert.IsTrue(rebuild.Items("lines").Any(l => l.GetString()!.StartsWith("Cartelle di account lette", StringComparison.Ordinal)));
Assert.IsTrue(File.Exists(Path.Combine(folder, "post", "foto.jpg")), "the rebuild never touches files");
}
[TestMethod]
public async Task AboutSaysVersionShellAndFolders()
{
await using var server = await Part2.StartAsync();
var about = await server.GetJsonAsync("/api/about");
Assert.AreEqual("Docker", about.Str("edition"));
Assert.AreEqual(server.Library.Layout.Root, about.Str("libraryFolder"));
Assert.AreEqual(server.Library.Data.Root, about.Str("dataFolder"));
StringAssert.Contains(about.Str("guide"), "/wiki");
}
private sealed class NotifyingShell : INativeShell
{
public int Notifications { get; private set; }
public bool CanPickFolder => false;
public bool CanShowInFolder => false;
public bool CanOpenUrl => false;
public bool CanNotify => true;
public bool SupportsAutostart => true;
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)
{
Notifications++;
return Task.CompletedTask;
}
public Task<bool> GetAutostartAsync(CancellationToken ct) => Task.FromResult(false);
public Task SetAutostartAsync(bool enabled, CancellationToken ct) => Task.CompletedTask;
}
}