Il browser preso dalle pagine Browser e Collegamento si restituisce uscendo senza «Ho finito» (anche chiudendo o ricaricando la scheda); dopo «Ho finito» la vista remota si chiude e non si riprende il browser. Vista remota: AltGr/Option come testo, pulsante rilasciato anche fuori dalla vista. Mosaico e scheda account senza risposte vecchie né viste sovrascritte; nuovi elementi dopo la libreria vuota; intestazione sempre aggiornata. Indietro del browser con la richiesta delle modifiche non salvate; nulla resta registrato da una pagina lasciata mentre caricava; maniglie della fascia trascinabili. «Da una data» come giorno locale; niente «@null» nel riquadro di stato; orari futuri dei fermi «verso le». Prove nel browser vero (InterfaceTests). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
259 lines
16 KiB
C#
259 lines
16 KiB
C#
using System.Net;
|
|
using System.Text.Json;
|
|
using Febe.Core.Domain;
|
|
using Febe.Core.Engine;
|
|
using Febe.Tests.Support;
|
|
using Febe.Tests.Web.Support;
|
|
using Febe.Web.Engine;
|
|
using Febe.Web.Library;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
|
|
namespace Febe.Tests.Web;
|
|
|
|
/// <summary>The accounts API (spec §4.2, §4.4, §7.8).</summary>
|
|
[TestClass]
|
|
public sealed class AccountsApiTests
|
|
{
|
|
[TestMethod]
|
|
public async Task TheListCountsEveryGroupAndTheSwitchActsAtOnce()
|
|
{
|
|
var engine = new RecordingEngine();
|
|
await using var server = await WebTestServer.StartAsync(services: s => s.AddSingleton<IEngineControl>(engine));
|
|
var marta = await server.AddAccountWithEntriesAsync("marta.demo", 5, Make.T0, TimeSpan.FromHours(3));
|
|
var paused = await server.Db.Accounts.AddAsync(Make.Account("trattoria.demo") with { State = AccountState.Paused, KeepUpdated = false });
|
|
await server.Db.Accounts.AddAsync(Make.Account("chiuso.demo") with { State = AccountState.Unreachable, UnreachableReason = UnreachableReason.PrivateNotFollowed, KeepUpdated = false });
|
|
await server.Db.Accounts.AddAsync(Make.Account("estate.2019.demo") with { InstagramId = null, State = AccountState.ArchiveOnly, KeepUpdated = false });
|
|
await server.Db.Accounts.AddAsync(Make.Account("studio.lumen.demo") with { State = AccountState.Backfilling, PostCount = 1280 });
|
|
|
|
var list = await server.GetJsonAsync("/api/accounts");
|
|
var counts = list.GetProperty("counts");
|
|
Assert.AreEqual(5, counts.Int("all"));
|
|
Assert.AreEqual(counts.Int("all"), counts.Int("upToDate") + counts.Int("backfilling") + counts.Int("paused") + counts.Int("archiveOnly") + 1, "plus one unreachable");
|
|
Assert.AreEqual(1, counts.Int("needsAttention"));
|
|
Assert.AreEqual(2, counts.Int("keptUpdated"));
|
|
var row = list.Items("accounts").Single(a => a.Str("username") == "marta.demo");
|
|
Assert.AreEqual(5, row.Int("inLibrary"));
|
|
Assert.IsTrue(row.GetProperty("types").Bool("photos"));
|
|
Assert.IsFalse(row.GetProperty("types").Bool("tagged"));
|
|
|
|
var (status, _) = await server.SendJsonAsync(HttpMethod.Post, $"/api/accounts/{marta.Id}/keep-updated", new { value = false });
|
|
Assert.AreEqual(HttpStatusCode.OK, status);
|
|
var stored = await server.Db.Accounts.GetAsync(marta.Id);
|
|
Assert.IsFalse(stored!.KeepUpdated);
|
|
Assert.AreEqual(AccountState.Paused, stored.State, "«no»: the single download is done, the account rests");
|
|
Assert.AreEqual(1, engine.AccountsChanged);
|
|
|
|
(status, _) = await server.SendJsonAsync(HttpMethod.Post, $"/api/accounts/{paused.Id}/keep-updated", new { value = true });
|
|
Assert.AreEqual(HttpStatusCode.OK, status);
|
|
Assert.AreEqual(AccountState.Backfilling, (await server.Db.Accounts.GetAsync(paused.Id))!.State, "its history was never completed");
|
|
|
|
var archive = list.Items("accounts").Single(a => a.Str("username") == "estate.2019.demo");
|
|
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, $"/api/accounts/{archive.Long("id")}/keep-updated", new { value = true })).Status);
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task CheckNowGoesThroughTheEngineWithItsConfirmation()
|
|
{
|
|
var engine = new RecordingEngine();
|
|
await using var server = await WebTestServer.StartAsync(services: s => s.AddSingleton<IEngineControl>(engine));
|
|
var account = await server.Db.Accounts.AddAsync(Make.Account("marta.demo"));
|
|
|
|
var (_, first) = await server.SendJsonAsync(HttpMethod.Post, $"/api/accounts/{account.Id}/check-now", new { });
|
|
Assert.AreEqual("needsConfirmation", first.Str("status"));
|
|
Assert.AreEqual("gettone-1", first.Str("token"));
|
|
var (_, second) = await server.SendJsonAsync(HttpMethod.Post, $"/api/accounts/{account.Id}/check-now", new { token = "gettone-1" });
|
|
Assert.AreEqual("queued", second.Str("status"));
|
|
CollectionAssert.AreEqual(new[] { (account.Id, (string?)null), (account.Id, (string?)"gettone-1") }, engine.Checks);
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task RemovingKeepsTheFilesByDefaultAndDeletesThemOnlyWhenAsked()
|
|
{
|
|
await using var server = await WebTestServer.StartAsync();
|
|
var keep = await server.AddAccountWithEntriesAsync("marta.demo", 3, Make.T0, TimeSpan.FromHours(3));
|
|
var (status, result) = await server.SendJsonAsync(HttpMethod.Post, $"/api/accounts/{keep.Id}/remove", new { deleteFiles = false });
|
|
Assert.AreEqual(HttpStatusCode.OK, status);
|
|
Assert.AreEqual("archived", result.Str("outcome"));
|
|
Assert.AreEqual(AccountState.ArchiveOnly, (await server.Db.Accounts.GetAsync(keep.Id))!.State);
|
|
Assert.HasCount(3, await server.Db.Entries.ListByAccountAsync(keep.Id));
|
|
|
|
var gone = await server.Db.Accounts.AddAsync(Make.Account("luca.viaggi.demo"));
|
|
var folder = server.Library.Layout.AccountFolder(gone);
|
|
Directory.CreateDirectory(Path.Combine(folder, "post"));
|
|
await File.WriteAllBytesAsync(Path.Combine(folder, "post", "a.jpg"), [1, 2, 3]);
|
|
await server.Db.Entries.AddAsync(Make.Entry(gone.Id, "x1", Make.T0), [Make.Stored(Make.Photo(), Make.Sha(5), "post/a.jpg")]);
|
|
(status, result) = await server.SendJsonAsync(HttpMethod.Post, $"/api/accounts/{gone.Id}/remove", new { deleteFiles = true });
|
|
Assert.AreEqual(HttpStatusCode.OK, status);
|
|
Assert.AreEqual("removed", result.Str("outcome"));
|
|
Assert.AreEqual(1, result.Int("deletedEntries"));
|
|
Assert.IsNull(await server.Db.Accounts.GetAsync(gone.Id));
|
|
Assert.IsFalse(File.Exists(Path.Combine(folder, "post", "a.jpg")));
|
|
|
|
var mine = await server.Db.Accounts.AddAsync(Make.Account("tuo.profilo", mine: true));
|
|
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, $"/api/accounts/{mine.Id}/remove", new { deleteFiles = false })).Status);
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task SettingsAreValidatedSavedAndExplainedByThePlan()
|
|
{
|
|
await using var server = await WebTestServer.StartAsync();
|
|
var account = await server.Db.Accounts.AddAsync(Make.Account("studio.lumen.demo") with { PostCount = 1280, State = AccountState.Backfilling });
|
|
var detail = await server.GetJsonAsync($"/api/accounts/{account.Id}");
|
|
var settings = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(detail.GetProperty("settings").GetRawText())!;
|
|
Assert.AreEqual("normal", settings["frequency"].GetString());
|
|
Assert.IsTrue(detail.GetProperty("plan").Items("lines").Any(l => l.Str("key") == "backfill" && l.Str("text").Contains("mancano 1.280 post", StringComparison.Ordinal)));
|
|
StringAssert.Contains(detail.GetProperty("plan").Str("frequencyHint"), "ogni 3 ore");
|
|
|
|
var custom = new Dictionary<string, object?>(settings.ToDictionary(k => k.Key, k => (object?)k.Value))
|
|
{
|
|
["frequency"] = "custom",
|
|
["customPostHours"] = 0.2,
|
|
};
|
|
var (status, error) = await server.SendJsonAsync(HttpMethod.Post, $"/api/accounts/{account.Id}/plan", custom);
|
|
Assert.AreEqual(HttpStatusCode.BadRequest, status);
|
|
StringAssert.Contains(error.Str("message"), "Su misura");
|
|
|
|
custom["customPostHours"] = 2;
|
|
custom["customStoryHours"] = 4;
|
|
var (planStatus, plan) = await server.SendJsonAsync(HttpMethod.Post, $"/api/accounts/{account.Id}/plan", custom);
|
|
Assert.AreEqual(HttpStatusCode.OK, planStatus);
|
|
StringAssert.Contains(plan.Str("frequencyHint"), "ogni 2 ore");
|
|
Assert.AreEqual(Frequency.Normal, (await server.Db.Accounts.GetAsync(account.Id))!.Frequency, "the plan never saves");
|
|
|
|
custom["maxVideoMb"] = 200;
|
|
custom["depth"] = "lastPosts";
|
|
custom["lastPosts"] = 500;
|
|
var (saveStatus, saved) = await server.SendJsonAsync(HttpMethod.Put, $"/api/accounts/{account.Id}/settings", custom);
|
|
Assert.AreEqual(HttpStatusCode.OK, saveStatus);
|
|
Assert.AreEqual("custom", saved.GetProperty("settings").Str("frequency"));
|
|
var stored = (await server.Db.Accounts.GetAsync(account.Id))!;
|
|
Assert.AreEqual(TimeSpan.FromHours(2), stored.CustomPostInterval);
|
|
Assert.AreEqual(200L * 1024 * 1024, stored.Limits.MaxVideoBytes);
|
|
Assert.AreEqual(500, stored.Limits.LastPosts);
|
|
|
|
custom["folder"] = "/altrove/foto";
|
|
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Put, $"/api/accounts/{account.Id}/settings", custom)).Status,
|
|
"in Docker (the default shell of the tests) folders are read-only");
|
|
}
|
|
|
|
[TestMethod]
|
|
public void FromDateIsTheLocalDayAndSurvivesARoundTrip()
|
|
{
|
|
// «Solo i nuovi da oggi» in Rome: local midnight of 13 October is 12 October 22:00 UTC.
|
|
var rome = TestZones.Rome;
|
|
var account = Account.Create("marta.demo", StartingPoint.OnlyNewFromToday, Make.T0, rome);
|
|
Assert.AreEqual(new DateTimeOffset(2026, 10, 12, 22, 0, 0, TimeSpan.Zero), account.Limits.FromDate);
|
|
|
|
var form = Febe.Web.Api.AccountSettingsMapper.ToDto(account, rome);
|
|
Assert.AreEqual("2026-10-13", form.FromDate, "the form shows the day Alberto chose");
|
|
var again = Febe.Web.Api.AccountSettingsMapper.Apply(account, form, rome, Make.T0, account.Folder);
|
|
Assert.AreEqual(account.Limits.FromDate, again.Limits.FromDate, "saving the form as it is changes nothing");
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task TheKeepUpdatedSwitchAndSavingDoNotMoveTheStartingDay()
|
|
{
|
|
await using var server = await WebTestServer.StartAsync();
|
|
var account = await server.Db.Accounts.AddAsync(Account.Create("anna.demo", StartingPoint.OnlyNewFromToday, Make.T0, server.Clock.LocalZone));
|
|
var from = account.Limits.FromDate;
|
|
Assert.IsNotNull(from);
|
|
|
|
var detail = await server.GetJsonAsync($"/api/accounts/{account.Id}");
|
|
Assert.AreEqual("2026-10-13", detail.GetProperty("settings").Str("fromDate"));
|
|
foreach (var value in new[] { false, true, false, true })
|
|
{
|
|
var (status, _) = await server.SendJsonAsync(HttpMethod.Post, $"/api/accounts/{account.Id}/keep-updated", new { value });
|
|
Assert.AreEqual(HttpStatusCode.OK, status);
|
|
}
|
|
|
|
Assert.AreEqual(from, (await server.Db.Accounts.GetAsync(account.Id))!.Limits.FromDate, "«Tieni aggiornato» does not move «Da una data»");
|
|
|
|
var settings = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>((await server.GetJsonAsync($"/api/accounts/{account.Id}")).GetProperty("settings").GetRawText())!;
|
|
var (saveStatus, saved) = await server.SendJsonAsync(HttpMethod.Put, $"/api/accounts/{account.Id}/settings", settings);
|
|
Assert.AreEqual(HttpStatusCode.OK, saveStatus);
|
|
Assert.AreEqual("2026-10-13", saved.GetProperty("settings").Str("fromDate"));
|
|
Assert.AreEqual(from, (await server.Db.Accounts.GetAsync(account.Id))!.Limits.FromDate, "saving the settings as they are does not move it either");
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task AccountsAreAddedFromTheFollowedListOrByNameWithAStartingPoint()
|
|
{
|
|
await using var server = await WebTestServer.StartAsync();
|
|
await server.Db.Accounts.AddAsync(Make.Account("marta.demo"));
|
|
await server.Db.Following.UpsertAsync(
|
|
[
|
|
new FollowingRecord { InstagramId = "77", Username = "anna.orto.demo", DisplayName = "Anna", IsPrivate = true, ReadAt = Make.T0 },
|
|
new FollowingRecord { InstagramId = "78", Username = "marta.demo", DisplayName = "Marta", ReadAt = Make.T0 },
|
|
]);
|
|
|
|
var following = await server.GetJsonAsync("/api/following");
|
|
Assert.AreEqual(2, following.Int("total"));
|
|
Assert.AreEqual("2026-10-13", following.Str("readDay"));
|
|
Assert.IsFalse(following.Bool("inProgress"));
|
|
Assert.AreEqual(300, following.Int("backfillPerDay"));
|
|
Assert.AreEqual(JsonValueKind.Number, following.Items("profiles").Single(p => p.Str("username") == "marta.demo").GetProperty("accountId").ValueKind, "already present");
|
|
|
|
var (_, parsed) = await server.SendJsonAsync(HttpMethod.Post, "/api/accounts/parse", new { text = "@anna.orto.demo\nhttps://www.instagram.com/Nuovo.Profilo/?hl=it\nmarta.demo\ninstagram.com/p/DBx3kQ2/\nnome con spazi\n\nanna.orto.demo" });
|
|
var names = parsed.Items("names").ToList();
|
|
CollectionAssert.AreEqual(new[] { "anna.orto.demo", "nuovo.profilo", "marta.demo" }, names.Select(n => n.Str("username")).ToList());
|
|
Assert.IsTrue(names[0].Bool("followed"));
|
|
Assert.IsTrue(names[2].Bool("present"));
|
|
Assert.HasCount(3, parsed.Items("problems").ToList(), "a post address, a name with spaces, a repeated line");
|
|
|
|
var (status, added) = await server.SendJsonAsync(HttpMethod.Post, "/api/accounts", new { usernames = new[] { "anna.orto.demo", "nuovo.profilo", "marta.demo" }, start = "everything", depth = "lastPosts", lastPosts = 200 });
|
|
Assert.AreEqual(HttpStatusCode.OK, status);
|
|
Assert.AreEqual(2, added.Int("added"));
|
|
var anna = (await server.Db.Accounts.FindByUsernameAsync("anna.orto.demo"))!;
|
|
Assert.IsTrue(anna.IsFollowed);
|
|
Assert.IsTrue(anna.IsPrivate);
|
|
Assert.AreEqual("77", anna.InstagramId);
|
|
Assert.AreEqual(AccountState.Backfilling, anna.State);
|
|
Assert.AreEqual(200, anna.Limits.LastPosts);
|
|
|
|
(status, added) = await server.SendJsonAsync(HttpMethod.Post, "/api/accounts", new { usernames = new[] { "solo.storie.demo" }, start = "storiesOnly" });
|
|
Assert.AreEqual(1, added.Int("added"));
|
|
var stories = (await server.Db.Accounts.FindByUsernameAsync("solo.storie.demo"))!;
|
|
Assert.AreEqual(ContentTypes.Stories | ContentTypes.Highlights, stories.ContentTypes);
|
|
Assert.AreEqual(AccountState.UpToDate, stories.State);
|
|
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/accounts", new { usernames = new[] { "x.demo" }, start = "tutto" })).Status);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void UserNamesAndProfileAddressesAreRecognizedOnePerLine()
|
|
{
|
|
var (names, problems) = UsernameParser.Parse("marta.demo\r\n@Luca.Viaggi\n instagram.com/studio.lumen.demo \nhttps://www.instagram.com/reel/abc/\nhttps://esempio.it/marta\n.punto\ndue..punti\n" + new string('a', 31));
|
|
CollectionAssert.AreEqual(new[] { "marta.demo", "luca.viaggi", "studio.lumen.demo" }, names.Select(n => n.Username).ToList());
|
|
Assert.HasCount(5, problems);
|
|
Assert.IsTrue(problems.All(p => p.Reason.Length > 10), "every refusal says why");
|
|
Assert.IsEmpty(UsernameParser.Parse(" \n\n").Names);
|
|
}
|
|
|
|
/// <summary>An engine that records the commands of the interface.</summary>
|
|
private sealed class RecordingEngine : IEngineControl
|
|
{
|
|
public List<(long, string?)> Checks { get; } = [];
|
|
|
|
public int AccountsChanged { get; private set; }
|
|
|
|
public Task PauseAsync(CancellationToken ct) => Task.CompletedTask;
|
|
|
|
public Task<ResumeResult> ResumeAsync(CancellationToken ct) => Task.FromResult(new ResumeResult(true, "Ripreso."));
|
|
|
|
public Task<CheckNowResult> CheckNowAsync(long accountId, string? confirmationToken, CancellationToken ct)
|
|
{
|
|
Checks.Add((accountId, confirmationToken));
|
|
return Task.FromResult(confirmationToken is null
|
|
? new CheckNowResult(CheckNowStatus.NeedsConfirmation, "Fuori fascia: confermi?", "gettone-1")
|
|
: new CheckNowResult(CheckNowStatus.Queued, "Confermato."));
|
|
}
|
|
|
|
public Task RequestFollowingListAsync(CancellationToken ct) => Task.CompletedTask;
|
|
|
|
public Task NotifyAccountsChangedAsync(CancellationToken ct)
|
|
{
|
|
AccountsChanged++;
|
|
return Task.CompletedTask;
|
|
}
|
|
}
|
|
}
|