Interfaccia web, parte 1: ospite, sicurezza, API, modalità dimostrativa, libreria, visualizzatore e account
Febe.Web: AddFebeWeb/UseFebe/FebeWebHost per le due vesti, interfaccia incorporata con IFileProvider proprio, indirizzi italiani, API JSON con contesto generato, eventi SSE, controlli di Host/Origin, gettone del desktop e password con blocco (§13.1), INativeShell e capacità per veste. Modalità --demo con 38 account e circa 18.000 elementi finti e scene del motore. Pagine Libreria, Visualizzatore, Account, Aggiungi account e Scheda account (contenuti, impostazioni con piano, cronologia); schermate in docs/schermate con le differenze dai mockup; prove delle API, della sicurezza, dell'esportazione CSV e dei dati dimostrativi. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
76 files changed
+12503
-17
No files matched your search
@@ -0,0 +1,219 @@
|
||||
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 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,287 @@
|
||||
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>
|
||||
/// Demo mode (spec §10.6): the seeded library is coherent (the counts add up, times are plausible), every path lives
|
||||
/// in the temporary folder, and the scenes chosen by address change what the engine reports.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class DemoTests
|
||||
{
|
||||
private static TempFolder? s_temp;
|
||||
private static DemoHost? s_demo;
|
||||
private static HttpClient? s_client;
|
||||
|
||||
private static DemoHost Demo => s_demo ?? throw new InvalidOperationException("demo not started");
|
||||
|
||||
private static HttpClient Client => s_client ?? throw new InvalidOperationException("demo not started");
|
||||
|
||||
[ClassInitialize]
|
||||
public static async Task StartDemoAsync(TestContext context)
|
||||
{
|
||||
s_temp = new TempFolder("demo");
|
||||
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();
|
||||
var root = s_demo?.Root;
|
||||
if (s_demo is not null)
|
||||
{
|
||||
await s_demo.DisposeAsync();
|
||||
}
|
||||
|
||||
if (root is not null)
|
||||
{
|
||||
Assert.IsFalse(Directory.Exists(root), "the temporary folder of the demo is removed at the end");
|
||||
}
|
||||
|
||||
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 TheAccountsAreTheDemoOnesInEveryStateAndTheirCountsAddUp()
|
||||
{
|
||||
var list = await GetAsync("/api/accounts");
|
||||
var rows = list.Items("accounts").ToList();
|
||||
var counts = list.GetProperty("counts");
|
||||
Assert.HasCount(38, rows);
|
||||
Assert.AreEqual(Demo.World.Accounts, rows.Count);
|
||||
Assert.AreEqual(rows.Count, counts.Int("all"));
|
||||
|
||||
var mine = rows.Where(r => r.Bool("isMine")).ToList();
|
||||
Assert.HasCount(1, mine);
|
||||
Assert.AreEqual("tuo.profilo", mine[0].Str("username"));
|
||||
Assert.AreEqual(Demo.World.MineId, mine[0].Long("id"));
|
||||
foreach (var row in rows.Where(r => !r.Bool("isMine")))
|
||||
{
|
||||
Assert.EndsWith(".demo", row.Str("username"), "demo accounts are recognizable as such");
|
||||
}
|
||||
|
||||
var states = rows.GroupBy(r => r.Str("state")).ToDictionary(g => g.Key, g => g.Count());
|
||||
foreach (var state in new[] { "upToDate", "backfilling", "paused", "archiveOnly", "unreachable" })
|
||||
{
|
||||
Assert.IsTrue(states.ContainsKey(state), $"no account in state {state}");
|
||||
}
|
||||
|
||||
Assert.AreEqual(states["upToDate"], counts.Int("upToDate"));
|
||||
Assert.AreEqual(states["backfilling"], counts.Int("backfilling"));
|
||||
Assert.AreEqual(states["paused"], counts.Int("paused"));
|
||||
Assert.AreEqual(states["archiveOnly"], counts.Int("archiveOnly"));
|
||||
Assert.AreEqual(rows.Count(r => r.Bool("needsAttention")), counts.Int("needsAttention"));
|
||||
Assert.AreEqual(rows.Count(r => r.Bool("keptUpdated")), counts.Int("keptUpdated"));
|
||||
Assert.AreEqual(rows.Count, states.Values.Sum());
|
||||
|
||||
// Backfill as in mockup 03: «340 di 1.280 post».
|
||||
var lumen = rows.Single(r => r.Str("username") == "studio.lumen.demo");
|
||||
Assert.AreEqual("backfilling", lumen.Str("state"));
|
||||
Assert.AreEqual(340, lumen.Int("posts"));
|
||||
Assert.AreEqual(1280, lumen.GetProperty("postCount").GetInt32());
|
||||
|
||||
// The library holds exactly what the accounts hold, and the days add up to the same total.
|
||||
var days = await GetAsync("/api/library/days");
|
||||
var inLibrary = rows.Sum(r => r.Int("inLibrary"));
|
||||
Assert.AreEqual(Demo.World.Entries, days.Int("entries"));
|
||||
Assert.AreEqual(inLibrary, days.Int("entries"));
|
||||
Assert.AreEqual(days.Int("entries"), days.Items("days").Sum(d => d.Int("count")));
|
||||
Assert.IsGreaterThan(10_000, inLibrary, "thousands of entries, so the mosaic is exercised for real");
|
||||
|
||||
// Each account card agrees with its row.
|
||||
foreach (var row in rows.Where(r => r.Int("inLibrary") > 0).Take(12))
|
||||
{
|
||||
var detail = await GetAsync($"/api/accounts/{row.Long("id")}");
|
||||
var stats = detail.GetProperty("stats");
|
||||
Assert.AreEqual(row.Int("inLibrary"), stats.Int("entries"), row.Str("username"));
|
||||
Assert.AreEqual(stats.Int("entries"), stats.Int("posts") + stats.Int("stories") + stats.Int("highlightItems") + stats.Int("tagged"), row.Str("username"));
|
||||
Assert.AreEqual(row.Int("posts"), stats.Int("posts"), row.Str("username"));
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheLibraryPagesThroughEveryEntryWithPlausibleTimesAndEveryKind()
|
||||
{
|
||||
var days = await GetAsync("/api/library/days");
|
||||
var now = days.Long("now");
|
||||
var total = days.Int("entries");
|
||||
var seen = new HashSet<long>();
|
||||
var kinds = new HashSet<string>();
|
||||
var provenances = new HashSet<string>();
|
||||
var multiFile = 0;
|
||||
var videos = 0;
|
||||
long previous = long.MaxValue;
|
||||
string? cursor = null;
|
||||
var pages = 0;
|
||||
do
|
||||
{
|
||||
var page = await GetAsync("/api/library?limit=600" + (cursor is null ? string.Empty : "&cursor=" + Uri.EscapeDataString(cursor)));
|
||||
foreach (var tile in page.Items("tiles"))
|
||||
{
|
||||
Assert.IsTrue(seen.Add(tile.Long("id")), "every entry appears once");
|
||||
var published = tile.Long("publishedAt");
|
||||
Assert.IsLessThanOrEqualTo(now, published, "nothing is published in the future");
|
||||
Assert.IsLessThanOrEqualTo(previous, published, "newest first");
|
||||
previous = published;
|
||||
kinds.Add(tile.Str("kind"));
|
||||
provenances.Add(tile.Str("provenance"));
|
||||
multiFile += tile.Int("files") > 1 ? 1 : 0;
|
||||
if (tile.GetProperty("cover").ValueKind == JsonValueKind.Object && tile.GetProperty("cover").Str("kind") == "video")
|
||||
{
|
||||
videos++;
|
||||
}
|
||||
}
|
||||
|
||||
cursor = page.GetProperty("older").ValueKind == JsonValueKind.String ? page.Str("older") : null;
|
||||
pages++;
|
||||
}
|
||||
while (cursor is not null && pages < 100);
|
||||
|
||||
Assert.AreEqual(total, seen.Count, "paging reaches every entry of the day counts");
|
||||
foreach (var kind in new[] { "post", "story", "highlight", "tagged" })
|
||||
{
|
||||
Assert.Contains(kind, kinds);
|
||||
}
|
||||
|
||||
Assert.Contains("imported", provenances);
|
||||
Assert.Contains("downloaded", provenances);
|
||||
Assert.IsGreaterThan(0, multiFile, "some posts have more files");
|
||||
Assert.IsGreaterThan(0, videos, "some entries are videos");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task EntriesAreDiscoveredAfterPublicationAndTheirFilesLiveInTheTemporaryFolder()
|
||||
{
|
||||
var page = await GetAsync("/api/library?limit=400");
|
||||
var checkedPhotos = 0;
|
||||
var checkedVideos = 0;
|
||||
foreach (var tile in page.Items("tiles").Where((_, i) => i % 8 == 0))
|
||||
{
|
||||
var entry = await GetAsync($"/api/entries/{tile.Long("id")}");
|
||||
Assert.IsGreaterThanOrEqualTo(entry.Long("publishedAt"), entry.GetProperty("discovered").Long("ms"), "found after publication");
|
||||
if (entry.GetProperty("downloaded").ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
Assert.IsGreaterThanOrEqualTo(entry.GetProperty("discovered").Long("ms"), entry.GetProperty("downloaded").Long("ms"));
|
||||
}
|
||||
|
||||
foreach (var media in entry.Items("media"))
|
||||
{
|
||||
using var file = await Client.GetAsync($"/api/media/{media.Long("id")}/file");
|
||||
if (media.Str("kind") == "photo")
|
||||
{
|
||||
Assert.AreEqual(HttpStatusCode.OK, file.StatusCode);
|
||||
Assert.AreEqual("image/jpeg", file.Content.Headers.ContentType?.MediaType);
|
||||
var bytes = await file.Content.ReadAsByteArrayAsync();
|
||||
Assert.IsTrue(bytes.Length > 3 && bytes[0] == 0xFF && bytes[1] == 0xD8, "a real JPEG");
|
||||
checkedPhotos++;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Videos have only their cover in the demo.
|
||||
Assert.AreEqual(HttpStatusCode.NotFound, file.StatusCode);
|
||||
checkedVideos++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Assert.IsGreaterThan(0, checkedPhotos);
|
||||
Assert.IsGreaterThan(0, checkedVideos + checkedPhotos);
|
||||
|
||||
var root = Path.GetFullPath(Demo.Root) + Path.DirectorySeparatorChar;
|
||||
Assert.IsNotEmpty(Demo.World.Pictures);
|
||||
foreach (var path in Demo.World.Pictures.Values)
|
||||
{
|
||||
Assert.StartsWith(root, Path.GetFullPath(path), "demo files never leave the temporary folder");
|
||||
Assert.IsTrue(File.Exists(path), path);
|
||||
}
|
||||
|
||||
var thumb = page.Items("tiles").Select(t => t.GetProperty("cover")).First(c => c.ValueKind == JsonValueKind.Object && c.GetProperty("thumb").ValueKind == JsonValueKind.String).Str("thumb");
|
||||
using var thumbnail = await Client.GetAsync($"/api/thumbnails/{thumb}");
|
||||
Assert.AreEqual(HttpStatusCode.OK, thumbnail.StatusCode);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ScenesChangeWhatTheEngineReports()
|
||||
{
|
||||
var normal = await GetAsync("/api/engine?scena=normale");
|
||||
Assert.AreEqual(JsonValueKind.Null, normal.GetProperty("snapshot").GetProperty("banner").ValueKind);
|
||||
Assert.AreEqual("connected", normal.GetProperty("connection").Str("state"));
|
||||
CollectionAssert.Contains(new[] { "Resting", "OutsideWindow" }, normal.GetProperty("snapshot").Str("mode"));
|
||||
|
||||
var session = await GetAsync("/api/engine?scena=sessione");
|
||||
Assert.AreEqual("InSession", session.GetProperty("snapshot").Str("mode"));
|
||||
|
||||
var stopped = await GetAsync("/api/engine?scena=fermo");
|
||||
Assert.AreEqual("StoppedForVerification", stopped.GetProperty("snapshot").Str("mode"));
|
||||
Assert.AreEqual(JsonValueKind.Object, stopped.GetProperty("snapshot").GetProperty("banner").ValueKind);
|
||||
Assert.AreEqual("verification", stopped.GetProperty("connection").Str("state"));
|
||||
|
||||
// The scene also travels in a header (the interface sends it on every call).
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, "/api/engine");
|
||||
request.Headers.Add(DemoRequest.SceneHeader, "scollegato");
|
||||
using var response = await Client.SendAsync(request);
|
||||
using var disconnected = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
|
||||
Assert.AreEqual("NotConnected", disconnected.RootElement.GetProperty("snapshot").Str("mode"));
|
||||
Assert.AreEqual("notConnected", disconnected.RootElement.GetProperty("connection").Str("state"));
|
||||
|
||||
foreach (var scene in new[] { normal, session, stopped, disconnected.RootElement })
|
||||
{
|
||||
foreach (var budget in scene.GetProperty("snapshot").Items("allBudgets"))
|
||||
{
|
||||
Assert.IsLessThanOrEqualTo(budget.Long("limitToday"), budget.Long("usedToday"), budget.Str("label"));
|
||||
}
|
||||
}
|
||||
|
||||
// Asking for a check while stopped is refused with a message.
|
||||
var marta = (await GetAsync("/api/accounts")).Items("accounts").First(r => r.Str("username") == "marta.demo").Long("id");
|
||||
using var check = new HttpRequestMessage(HttpMethod.Post, $"/api/accounts/{marta}/check-now?scena=fermo")
|
||||
{
|
||||
Content = new StringContent("{}", System.Text.Encoding.UTF8, "application/json"),
|
||||
};
|
||||
check.Headers.Add("Origin", $"{Demo.Address.Scheme}://{Demo.Address.Authority}");
|
||||
using var answer = await Client.SendAsync(check);
|
||||
using var body = JsonDocument.Parse(await answer.Content.ReadAsStringAsync());
|
||||
Assert.AreEqual(HttpStatusCode.OK, answer.StatusCode);
|
||||
Assert.AreEqual("refused", body.RootElement.Str("status"));
|
||||
Assert.IsFalse(string.IsNullOrWhiteSpace(body.RootElement.Str("message")));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheEditionCanBeChosenByAddress()
|
||||
{
|
||||
var desktop = await GetAsync("/api/capabilities");
|
||||
Assert.IsTrue(desktop.Bool("demo"));
|
||||
Assert.AreEqual("desktop", desktop.Str("edition"));
|
||||
Assert.IsTrue(desktop.Bool("showInFolder"));
|
||||
Assert.IsFalse(desktop.Bool("foldersReadOnly"));
|
||||
Assert.AreEqual("none", desktop.Str("access"));
|
||||
|
||||
var docker = await GetAsync("/api/capabilities?veste=docker");
|
||||
Assert.AreEqual("docker", docker.Str("edition"));
|
||||
Assert.IsFalse(docker.Bool("showInFolder"));
|
||||
Assert.IsTrue(docker.Bool("foldersReadOnly"));
|
||||
Assert.IsFalse(docker.Bool("autostart"));
|
||||
|
||||
// The addresses that open a dialog or a step directly are pages of the interface.
|
||||
foreach (var page in new[] { "/account?dialogo=aggiungi", "/importa?passo=3", "/libreria?scena=fermo&tema=scuro" })
|
||||
{
|
||||
using var response = await Client.GetAsync(page);
|
||||
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, page);
|
||||
StringAssert.Contains(await response.Content.ReadAsStringAsync(), "<div id=\"app\"", page);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,349 @@
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
using Febe.Tests.Support;
|
||||
using Febe.Tests.Web.Support;
|
||||
using Febe.Web;
|
||||
using Febe.Web.Api;
|
||||
using Febe.Web.Hosting;
|
||||
using Febe.Web.Security;
|
||||
|
||||
namespace Febe.Tests.Web;
|
||||
|
||||
/// <summary>The embedded interface, the page addresses and the access checks of spec §13.1.</summary>
|
||||
[TestClass]
|
||||
public sealed class HostingAndSecurityTests
|
||||
{
|
||||
private static readonly string[] Pages =
|
||||
[
|
||||
"/", "/libreria", "/account", "/account/12", "/account/12/impostazioni", "/attivita", "/importa",
|
||||
"/impostazioni/generali", "/impostazioni/limiti", "/impostazioni/collegamento", "/impostazioni/notifiche",
|
||||
"/impostazioni/dati", "/impostazioni/informazioni", "/browser",
|
||||
];
|
||||
|
||||
[TestMethod]
|
||||
public void TheEmbeddedInterfaceHasEveryFileAndRefusesPathsOutsideIt()
|
||||
{
|
||||
var files = new EmbeddedWwwroot();
|
||||
foreach (var path in new[] { "index.html", "accesso.html", "css/febe.css", "js/app.js", "testi/it.json", "img/marchio.svg", "icone/image.svg", "caratteri/archivo-latin-standard-normal.woff2" })
|
||||
{
|
||||
var info = files.GetFileInfo(path);
|
||||
Assert.IsTrue(info.Exists, path);
|
||||
Assert.IsGreaterThan(0L, info.Length, path);
|
||||
using var stream = info.CreateReadStream();
|
||||
Assert.AreEqual(info.Length, stream.Length, path);
|
||||
}
|
||||
|
||||
Assert.IsTrue(files.GetFileInfo("/css/febe.css").Exists, "a leading slash is accepted");
|
||||
foreach (var bad in new[] { "../Febe.Web.dll", "css/../index.html", "./index.html", "css\\febe.css", "C:/index.html", "css//febe.css", "nonexistent.js", "" })
|
||||
{
|
||||
Assert.IsFalse(files.GetFileInfo(bad).Exists, bad);
|
||||
}
|
||||
|
||||
var icons = files.GetDirectoryContents("icone").Select(f => f.Name).ToList();
|
||||
Assert.Contains("image.svg", icons);
|
||||
Assert.IsFalse(files.GetDirectoryContents("../").Exists);
|
||||
Assert.IsTrue(files.GetDirectoryContents(string.Empty).Any(f => f.IsDirectory && f.Name == "css"));
|
||||
|
||||
// The text resource is valid JSON with the Italian texts.
|
||||
using var texts = JsonDocument.Parse(files.ReadText("testi/it.json")!);
|
||||
Assert.AreEqual("Libreria", texts.RootElement.GetProperty("nav").GetProperty("libreria").GetString());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheIconSpriteHasOneSymbolPerLucideFileWithoutItsOwnStroke()
|
||||
{
|
||||
var files = new EmbeddedWwwroot();
|
||||
var sprite = SystemApi.BuildSprite(files);
|
||||
var count = files.Files.Count(f => f.StartsWith("icone/", StringComparison.Ordinal) && f.EndsWith(".svg", StringComparison.Ordinal));
|
||||
Assert.AreEqual(count, sprite.Split("<symbol ").Length - 1);
|
||||
StringAssert.Contains(sprite, "id=\"i-layout-grid\"");
|
||||
Assert.DoesNotContain("stroke-width=\"2\"", sprite, "stroke 1,75 comes from the style sheet");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ItalianPageAddressesAnswerWithTheApplicationAndTheApiStaysJson()
|
||||
{
|
||||
await using var server = await WebTestServer.StartAsync();
|
||||
foreach (var page in Pages)
|
||||
{
|
||||
using var response = await server.Client.GetAsync(page);
|
||||
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, page);
|
||||
Assert.AreEqual("text/html", response.Content.Headers.ContentType?.MediaType, page);
|
||||
StringAssert.Contains(await response.Content.ReadAsStringAsync(), "<div id=\"app\"></div>", page);
|
||||
Assert.IsTrue(response.Headers.Contains("Content-Security-Policy"), page);
|
||||
}
|
||||
|
||||
using (var css = await server.Client.GetAsync("/css/febe.css"))
|
||||
{
|
||||
Assert.AreEqual("text/css", css.Content.Headers.ContentType?.MediaType);
|
||||
Assert.AreEqual("nosniff", css.Headers.GetValues("X-Content-Type-Options").Single());
|
||||
}
|
||||
|
||||
using (var js = await server.Client.GetAsync("/js/app.js"))
|
||||
{
|
||||
Assert.AreEqual("text/javascript", js.Content.Headers.ContentType?.MediaType);
|
||||
}
|
||||
|
||||
using (var missing = await server.Client.GetAsync("/js/non-esiste.js"))
|
||||
{
|
||||
Assert.AreEqual(HttpStatusCode.NotFound, missing.StatusCode);
|
||||
}
|
||||
|
||||
using var api = await server.Client.GetAsync("/api/non-esiste");
|
||||
Assert.AreEqual(HttpStatusCode.NotFound, api.StatusCode);
|
||||
Assert.AreEqual("application/json", api.Content.Headers.ContentType?.MediaType);
|
||||
StringAssert.Contains(await api.Content.ReadAsStringAsync(), "sconosciuto");
|
||||
|
||||
var capabilities = await server.GetJsonAsync("/api/capabilities");
|
||||
Assert.AreEqual("docker", capabilities.Str("edition"));
|
||||
Assert.IsTrue(capabilities.Bool("foldersReadOnly"));
|
||||
Assert.IsFalse(capabilities.Bool("showInFolder"));
|
||||
Assert.AreEqual("2026-10-13", capabilities.Str("today"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task HostAndOriginChecksStopOtherPagesAndOtherNames()
|
||||
{
|
||||
await using var server = await WebTestServer.StartAsync();
|
||||
|
||||
using (var foreignHost = new HttpRequestMessage(HttpMethod.Get, "/api/capabilities"))
|
||||
{
|
||||
foreignHost.Headers.Host = "attacco.example:80";
|
||||
using var response = await server.Client.SendAsync(foreignHost);
|
||||
Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode, "DNS rebinding: a foreign host name is refused");
|
||||
}
|
||||
|
||||
using (var crossOrigin = server.Request(HttpMethod.Post, "/api/engine/pause", origin: "http://attacco.example"))
|
||||
using (var response = await server.Client.SendAsync(crossOrigin))
|
||||
{
|
||||
Assert.AreEqual(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
}
|
||||
|
||||
using (var nullOrigin = server.Request(HttpMethod.Post, "/api/engine/pause", origin: "null"))
|
||||
using (var response = await server.Client.SendAsync(nullOrigin))
|
||||
{
|
||||
Assert.AreEqual(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
}
|
||||
|
||||
using (var crossSite = server.Request(HttpMethod.Post, "/api/engine/pause", origin: null))
|
||||
{
|
||||
crossSite.Headers.TryAddWithoutValidation("Sec-Fetch-Site", "cross-site");
|
||||
using var response = await server.Client.SendAsync(crossSite);
|
||||
Assert.AreEqual(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
}
|
||||
|
||||
using (var events = server.Request(HttpMethod.Get, "/api/eventi", origin: "http://attacco.example"))
|
||||
using (var response = await server.Client.SendAsync(events))
|
||||
{
|
||||
Assert.AreEqual(HttpStatusCode.Forbidden, response.StatusCode, "the event stream counts as a command channel");
|
||||
}
|
||||
|
||||
using (var sameOrigin = server.Request(HttpMethod.Post, "/api/engine/pause"))
|
||||
using (var response = await server.Client.SendAsync(sameOrigin))
|
||||
{
|
||||
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, await response.Content.ReadAsStringAsync());
|
||||
}
|
||||
|
||||
using (var sameSite = server.Request(HttpMethod.Post, "/api/engine/pause", origin: null))
|
||||
{
|
||||
sameSite.Headers.TryAddWithoutValidation("Sec-Fetch-Site", "same-origin");
|
||||
using var response = await server.Client.SendAsync(sameSite);
|
||||
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheDesktopTokenOpensTheInterfaceOnceAndThenLivesInAStrictCookie()
|
||||
{
|
||||
var token = AccessToken.Create();
|
||||
await using var server = await WebTestServer.StartAsync(new FebeWebOptions { Edition = FebeEdition.Desktop, Access = AccessMode.Token, AccessToken = token });
|
||||
|
||||
using (var bare = await server.Client.GetAsync("/api/capabilities"))
|
||||
{
|
||||
Assert.AreEqual(HttpStatusCode.Unauthorized, bare.StatusCode);
|
||||
}
|
||||
|
||||
using (var page = await server.Client.GetAsync("/libreria"))
|
||||
{
|
||||
Assert.AreEqual(HttpStatusCode.Unauthorized, page.StatusCode);
|
||||
}
|
||||
|
||||
using (var wrong = await server.Client.GetAsync("/libreria?gettone=sbagliato"))
|
||||
{
|
||||
Assert.AreEqual(HttpStatusCode.Unauthorized, wrong.StatusCode);
|
||||
}
|
||||
|
||||
string cookie;
|
||||
using (var first = await server.Client.GetAsync($"/libreria?tema=scuro&gettone={token}"))
|
||||
{
|
||||
Assert.AreEqual(HttpStatusCode.Redirect, first.StatusCode);
|
||||
Assert.AreEqual("/libreria?tema=scuro", first.Headers.Location?.OriginalString, "the token leaves the address at once");
|
||||
cookie = first.Headers.GetValues("Set-Cookie").Single();
|
||||
StringAssert.Contains(cookie, AccessToken.CookieName + "=");
|
||||
StringAssert.Contains(cookie.ToLowerInvariant(), "httponly");
|
||||
StringAssert.Contains(cookie.ToLowerInvariant(), "samesite=strict");
|
||||
}
|
||||
|
||||
using (var withCookie = new HttpRequestMessage(HttpMethod.Get, "/api/capabilities"))
|
||||
{
|
||||
withCookie.Headers.TryAddWithoutValidation("Cookie", cookie.Split(';')[0]);
|
||||
using var response = await server.Client.SendAsync(withCookie);
|
||||
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
|
||||
}
|
||||
|
||||
using (var withHeader = new HttpRequestMessage(HttpMethod.Get, "/api/capabilities"))
|
||||
{
|
||||
withHeader.Headers.TryAddWithoutValidation(AccessToken.HeaderName, token);
|
||||
using var response = await server.Client.SendAsync(withHeader);
|
||||
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
|
||||
}
|
||||
|
||||
// The token is necessary but not sufficient: commands from another origin are refused even with it.
|
||||
using (var forged = server.Request(HttpMethod.Post, "/api/engine/pause", origin: "http://127.0.0.1:1"))
|
||||
{
|
||||
forged.Headers.TryAddWithoutValidation(AccessToken.HeaderName, token);
|
||||
using var response = await server.Client.SendAsync(forged);
|
||||
Assert.AreEqual(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ThePasswordOpensASessionAndRepeatedFailuresLockTheLogin()
|
||||
{
|
||||
await using var server = await WebTestServer.StartAsync(new FebeWebOptions
|
||||
{
|
||||
Access = AccessMode.Password,
|
||||
Password = "una password lunga",
|
||||
Lockout = new LockoutOptions { AttemptsPerClient = 3, AttemptsOverall = 50 },
|
||||
});
|
||||
|
||||
using (var page = await server.Client.GetAsync("/libreria"))
|
||||
{
|
||||
Assert.AreEqual(HttpStatusCode.Redirect, page.StatusCode);
|
||||
StringAssert.StartsWith(page.Headers.Location?.OriginalString, "/accesso?torna=");
|
||||
}
|
||||
|
||||
using (var api = await server.Client.GetAsync("/api/accounts"))
|
||||
{
|
||||
Assert.AreEqual(HttpStatusCode.Unauthorized, api.StatusCode);
|
||||
}
|
||||
|
||||
using (var login = await server.Client.GetAsync("/accesso"))
|
||||
{
|
||||
Assert.AreEqual(HttpStatusCode.OK, login.StatusCode, "the login page is public");
|
||||
}
|
||||
|
||||
using (var css = await server.Client.GetAsync("/css/febe.css"))
|
||||
{
|
||||
Assert.AreEqual(HttpStatusCode.OK, css.StatusCode, "and so is what it needs");
|
||||
}
|
||||
|
||||
var (wrong, _) = await server.SendJsonAsync(HttpMethod.Post, "/api/accesso", new { password = "no" });
|
||||
Assert.AreEqual(HttpStatusCode.Unauthorized, wrong);
|
||||
|
||||
string cookie;
|
||||
using (var ok = server.Request(HttpMethod.Post, "/api/accesso", new { password = "una password lunga" }))
|
||||
using (var response = await server.Client.SendAsync(ok))
|
||||
{
|
||||
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
|
||||
cookie = response.Headers.GetValues("Set-Cookie").Single();
|
||||
StringAssert.Contains(cookie.ToLowerInvariant(), "httponly");
|
||||
StringAssert.Contains(cookie.ToLowerInvariant(), "samesite=strict");
|
||||
}
|
||||
|
||||
using (var authed = new HttpRequestMessage(HttpMethod.Get, "/api/accounts"))
|
||||
{
|
||||
authed.Headers.TryAddWithoutValidation("Cookie", cookie.Split(';')[0]);
|
||||
using var response = await server.Client.SendAsync(authed);
|
||||
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
|
||||
}
|
||||
|
||||
// A login from another page is refused before the password is even checked.
|
||||
var (foreign, _) = await SendWithOrigin(server, "/api/accesso", new { password = "una password lunga" }, "http://attacco.example");
|
||||
Assert.AreEqual(HttpStatusCode.Forbidden, foreign);
|
||||
|
||||
// The right password cleared the earlier failure: the third failure from now on locks the login.
|
||||
Assert.AreEqual(HttpStatusCode.Unauthorized, (await server.SendJsonAsync(HttpMethod.Post, "/api/accesso", new { password = "no" })).Status);
|
||||
Assert.AreEqual(HttpStatusCode.Unauthorized, (await server.SendJsonAsync(HttpMethod.Post, "/api/accesso", new { password = "no" })).Status);
|
||||
Assert.AreEqual(HttpStatusCode.TooManyRequests, (await server.SendJsonAsync(HttpMethod.Post, "/api/accesso", new { password = "no" })).Status);
|
||||
Assert.AreEqual(HttpStatusCode.TooManyRequests, (await server.SendJsonAsync(HttpMethod.Post, "/api/accesso", new { password = "una password lunga" })).Status,
|
||||
"while locked even the right password waits");
|
||||
|
||||
using (var logout = server.Request(HttpMethod.Post, "/api/uscita"))
|
||||
{
|
||||
logout.Headers.TryAddWithoutValidation("Cookie", cookie.Split(';')[0]);
|
||||
using var response = await server.Client.SendAsync(logout);
|
||||
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
|
||||
}
|
||||
|
||||
using (var after = new HttpRequestMessage(HttpMethod.Get, "/api/accounts"))
|
||||
{
|
||||
after.Headers.TryAddWithoutValidation("Cookie", cookie.Split(';')[0]);
|
||||
using var response = await server.Client.SendAsync(after);
|
||||
Assert.AreEqual(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheLockoutCoversOneClientAndAllClientsAndEndsByItself()
|
||||
{
|
||||
var now = Make.T0;
|
||||
var access = new PasswordAccess("segreta", new LockoutOptions { AttemptsPerClient = 2, AttemptsOverall = 3, LockFor = TimeSpan.FromMinutes(15) }, () => now);
|
||||
Assert.AreEqual(LoginStatus.WrongPassword, access.TryLogin("x", "a").Status);
|
||||
Assert.AreEqual(LoginStatus.Locked, access.TryLogin("x", "a").Status);
|
||||
Assert.AreEqual(LoginStatus.Locked, access.TryLogin("segreta", "a").Status);
|
||||
Assert.AreEqual(LoginStatus.Locked, access.TryLogin("x", "b").Status, "the third failure overall locks every client");
|
||||
Assert.AreEqual(LoginStatus.Locked, access.TryLogin("segreta", "c").Status, "even one that never failed");
|
||||
now += TimeSpan.FromMinutes(16);
|
||||
var ok = access.TryLogin("segreta", "a");
|
||||
Assert.AreEqual(LoginStatus.Accepted, ok.Status);
|
||||
Assert.IsTrue(access.IsValid(ok.SessionId));
|
||||
now += TimeSpan.FromDays(31);
|
||||
Assert.IsFalse(access.IsValid(ok.SessionId), "sessions expire");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheEventStreamStartsWithTheEngine()
|
||||
{
|
||||
await using var server = await WebTestServer.StartAsync();
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, "/api/eventi");
|
||||
request.Headers.TryAddWithoutValidation("Sec-Fetch-Site", "same-origin");
|
||||
using var response = await server.Client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
|
||||
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.AreEqual("text/event-stream", response.Content.Headers.ContentType?.MediaType);
|
||||
using var stream = await response.Content.ReadAsStreamAsync();
|
||||
using var reader = new StreamReader(stream);
|
||||
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(10));
|
||||
string? eventName = null;
|
||||
string? data = null;
|
||||
while (data is null)
|
||||
{
|
||||
var line = await reader.ReadLineAsync(timeout.Token);
|
||||
if (line is null)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
if (line.StartsWith("event: ", StringComparison.Ordinal))
|
||||
{
|
||||
eventName = line[7..];
|
||||
}
|
||||
else if (line.StartsWith("data: ", StringComparison.Ordinal))
|
||||
{
|
||||
data = line[6..];
|
||||
}
|
||||
}
|
||||
|
||||
Assert.AreEqual("motore", eventName);
|
||||
using var json = JsonDocument.Parse(data!);
|
||||
Assert.AreEqual("Off", json.RootElement.GetProperty("snapshot").GetProperty("mode").GetString(), "without an engine Febe says «Motore spento»");
|
||||
Assert.AreEqual("Motore spento", json.RootElement.GetProperty("snapshot").GetProperty("headline").GetString());
|
||||
}
|
||||
|
||||
private static async Task<(HttpStatusCode Status, string Body)> SendWithOrigin(WebTestServer server, string path, object body, string origin)
|
||||
{
|
||||
using var request = server.Request(HttpMethod.Post, path, body, origin);
|
||||
using var response = await server.Client.SendAsync(request);
|
||||
return (response.StatusCode, await response.Content.ReadAsStringAsync());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Library;
|
||||
using Febe.Tests.Support;
|
||||
using Febe.Tests.Web.Support;
|
||||
using Febe.Web.Library;
|
||||
|
||||
namespace Febe.Tests.Web;
|
||||
|
||||
/// <summary>The library API (spec §4.6): day groups, keyset windows, filters, viewer data, deletion, CSV export.</summary>
|
||||
[TestClass]
|
||||
public sealed class LibraryApiTests
|
||||
{
|
||||
[TestMethod]
|
||||
public async Task WindowsFollowTheCursorsWithoutGapsOrRepeatsAndDaysAddUp()
|
||||
{
|
||||
await using var server = await WebTestServer.StartAsync();
|
||||
await server.AddAccountWithEntriesAsync("marta.demo", 40, Make.T0, TimeSpan.FromHours(5));
|
||||
await server.AddAccountWithEntriesAsync("luca.viaggi.demo", 23, Make.T0 - TimeSpan.FromMinutes(30), TimeSpan.FromHours(7), EntryKind.Story);
|
||||
|
||||
var days = await server.GetJsonAsync("/api/library/days");
|
||||
Assert.AreEqual(63, days.Int("entries"));
|
||||
Assert.AreEqual(2, days.Int("accounts"));
|
||||
Assert.AreEqual(63, days.Items("days").Sum(d => d.Int("count")), "the counts of the days add up to the total");
|
||||
var dayNames = days.Items("days").Select(d => d.Str("day")).ToList();
|
||||
CollectionAssert.AreEqual(dayNames.OrderByDescending(d => d, StringComparer.Ordinal).ToList(), dayNames, "newest day first");
|
||||
|
||||
var seen = new List<(long Ms, long Id)>();
|
||||
string? cursor = null;
|
||||
var pages = 0;
|
||||
do
|
||||
{
|
||||
var page = await server.GetJsonAsync("/api/library?limit=7" + (cursor is null ? string.Empty : "&cursor=" + cursor));
|
||||
seen.AddRange(page.Items("tiles").Select(t => (t.Long("publishedAt"), t.Long("id"))));
|
||||
cursor = page.GetProperty("older").ValueKind == JsonValueKind.Null ? null : page.Str("older");
|
||||
pages++;
|
||||
}
|
||||
while (cursor is not null && pages < 50);
|
||||
|
||||
Assert.HasCount(63, seen);
|
||||
Assert.HasCount(63, seen.Select(s => s.Id).Distinct());
|
||||
for (var i = 1; i < seen.Count; i++)
|
||||
{
|
||||
Assert.IsTrue(seen[i].Ms < seen[i - 1].Ms || (seen[i].Ms == seen[i - 1].Ms && seen[i].Id < seen[i - 1].Id), "display order: newest first");
|
||||
}
|
||||
|
||||
// The cursor of a day starts exactly at that day.
|
||||
foreach (var day in days.Items("days").Take(4))
|
||||
{
|
||||
var page = await server.GetJsonAsync($"/api/library?limit={day.Int("count")}&cursor={day.Str("cursor")}");
|
||||
Assert.IsTrue(page.Items("tiles").All(t => t.Str("day") == day.Str("day")), day.Str("day"));
|
||||
Assert.AreEqual(day.Int("count"), page.Items("tiles").Count());
|
||||
}
|
||||
|
||||
// Going back up from a cursor gives the newer entries.
|
||||
var middle = await server.GetJsonAsync("/api/library?limit=10&cursor=" + Uri.EscapeDataString($"{seen[30].Ms}.{seen[30].Id}"));
|
||||
Assert.AreEqual(seen[31].Id, middle.Items("tiles").First().Long("id"));
|
||||
var newer = await server.GetJsonAsync("/api/library?limit=5&direction=newer&cursor=" + Uri.EscapeDataString($"{seen[30].Ms}.{seen[30].Id}"));
|
||||
CollectionAssert.AreEqual(seen.Skip(25).Take(5).Select(s => s.Id).ToList(), newer.Items("tiles").Select(t => t.Long("id")).ToList());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task FiltersByKindAccountSearchAndPeriod()
|
||||
{
|
||||
await using var server = await WebTestServer.StartAsync();
|
||||
var marta = await server.AddAccountWithEntriesAsync("marta.demo", 10, Make.T0, TimeSpan.FromDays(1), caption: "Tramonto sul molo");
|
||||
await server.AddAccountWithEntriesAsync("luca.viaggi.demo", 6, Make.T0, TimeSpan.FromDays(1), EntryKind.Story);
|
||||
|
||||
Assert.AreEqual(6, (await server.GetJsonAsync("/api/library/days?kind=stories")).Int("entries"));
|
||||
Assert.AreEqual(10, (await server.GetJsonAsync("/api/library/days?kind=photos")).Int("entries"));
|
||||
Assert.AreEqual(0, (await server.GetJsonAsync("/api/library/days?kind=videos")).Int("entries"), "«Video» concerns posts; story videos are under «Storie»");
|
||||
Assert.AreEqual(10, (await server.GetJsonAsync($"/api/library/days?accounts={marta.Id}")).Int("entries"));
|
||||
Assert.AreEqual(10, (await server.GetJsonAsync("/api/library/days?q=tramonto")).Int("entries"), "caption search ignores case");
|
||||
Assert.AreEqual(6, (await server.GetJsonAsync("/api/library/days?q=luca")).Int("entries"), "account name search");
|
||||
Assert.AreEqual(0, (await server.GetJsonAsync("/api/library/days?provenance=imported")).Int("entries"));
|
||||
Assert.AreEqual(6, (await server.GetJsonAsync("/api/library/days?from=2026-10-08&to=2026-10-10")).Int("entries"), "three local days, both accounts");
|
||||
|
||||
var (status, body) = await server.SendJsonAsync(HttpMethod.Get, "/api/library?cursor=nonvalido");
|
||||
Assert.AreEqual(HttpStatusCode.BadRequest, status);
|
||||
StringAssert.Contains(body.Str("message"), "non valida");
|
||||
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Get, "/api/library/days?kind=gatti")).Status);
|
||||
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Get, "/api/library/days?from=13/10/2026")).Status);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheViewerGetsDataFilesAndProvenanceAndDeletionIsRemembered()
|
||||
{
|
||||
await using var server = await WebTestServer.StartAsync();
|
||||
var account = await server.Db.Accounts.AddAsync(Make.Account("marta.demo"));
|
||||
var folder = server.Library.Layout.AccountFolder(account);
|
||||
Directory.CreateDirectory(Path.Combine(folder, "post"));
|
||||
var bytes = TestImages.Jpeg(TestImages.Scene(3, 120, 150));
|
||||
await File.WriteAllBytesAsync(Path.Combine(folder, "post", "foto_1.jpg"), bytes);
|
||||
var added = await server.Db.Entries.AddAsync(
|
||||
Make.Entry(account.Id, "1", Make.T0, caption: "Luce della sera") with { State = EntryState.Downloaded },
|
||||
[Make.Stored(Make.Photo(1), Make.Sha(1), "post/foto_1.jpg") with { Bytes = bytes.Length }, Make.Stored(Make.Video(2), Make.Sha(2), "post/video_2.mp4")]);
|
||||
var id = added.Stored.Entry.Id;
|
||||
|
||||
var entry = await server.GetJsonAsync($"/api/entries/{id}");
|
||||
Assert.AreEqual("post", entry.Str("kind"));
|
||||
Assert.AreEqual("Luce della sera", entry.Str("caption"));
|
||||
Assert.AreEqual("C1", entry.Str("code"));
|
||||
Assert.AreEqual("https://www.instagram.com/p/C1/", entry.Str("instagramUrl"));
|
||||
Assert.AreEqual("2026-10-13", entry.Str("publishedDay"));
|
||||
Assert.AreEqual("10:00", entry.Str("publishedTime"), "local time of Alberto's zone (Rome, UTC+2 in October)");
|
||||
var media = entry.Items("media").ToList();
|
||||
Assert.HasCount(2, media);
|
||||
Assert.IsTrue(media[0].Bool("available"));
|
||||
Assert.AreEqual("foto_1.jpg", media[0].Str("fileName"));
|
||||
Assert.AreEqual(Path.Combine("marta.demo", "post"), media[0].Str("folder"));
|
||||
Assert.IsFalse(media[1].Bool("available"), "a file missing from disk is said, not hidden");
|
||||
|
||||
using (var file = await server.Client.GetAsync($"/api/media/{media[0].Long("id")}/file?download=1"))
|
||||
{
|
||||
Assert.AreEqual(HttpStatusCode.OK, file.StatusCode);
|
||||
Assert.AreEqual("image/jpeg", file.Content.Headers.ContentType?.MediaType);
|
||||
Assert.AreEqual("foto_1.jpg", file.Content.Headers.ContentDisposition?.FileName?.Trim('"'));
|
||||
CollectionAssert.AreEqual(bytes, await file.Content.ReadAsByteArrayAsync());
|
||||
}
|
||||
|
||||
Assert.AreEqual(HttpStatusCode.NotFound, (await server.SendJsonAsync(HttpMethod.Get, $"/api/media/{media[1].Long("id")}/file")).Status);
|
||||
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Get, "/api/thumbnails/nonvalida")).Status);
|
||||
Assert.AreEqual(HttpStatusCode.NotFound, (await server.SendJsonAsync(HttpMethod.Get, "/api/thumbnails/" + Make.Sha(99))).Status);
|
||||
using (var neutral = await server.Client.GetAsync("/api/thumbnails/video"))
|
||||
{
|
||||
Assert.AreEqual("image/jpeg", neutral.Content.Headers.ContentType?.MediaType);
|
||||
}
|
||||
|
||||
// Without the desktop, «Mostra nella cartella» does not exist: the page offers «Scarica».
|
||||
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/media/show-in-folder", new { mediaId = media[0].Long("id") })).Status);
|
||||
|
||||
var changes = server.Changes.SubscribeAsync().GetAsyncEnumerator();
|
||||
var next = changes.MoveNextAsync().AsTask();
|
||||
var (status, result) = await server.SendJsonAsync(HttpMethod.Post, "/api/entries/delete", new { ids = new[] { id }, mode = "remember" });
|
||||
Assert.AreEqual(HttpStatusCode.OK, status);
|
||||
Assert.AreEqual(1, result.Int("deleted"));
|
||||
Assert.AreEqual(1, result.Int("filesRemoved"));
|
||||
Assert.IsFalse(File.Exists(Path.Combine(folder, "post", "foto_1.jpg")));
|
||||
Assert.AreEqual(EntryState.Deleted, (await server.Db.Entries.GetAsync(id))!.State, "remembered: never downloaded again");
|
||||
Assert.AreEqual(0, (await server.GetJsonAsync("/api/library/days")).Int("entries"));
|
||||
Assert.IsTrue(await next.WaitAsync(TimeSpan.FromSeconds(5)), "the open pages hear about it");
|
||||
Assert.AreEqual("deleted", changes.Current.Reason);
|
||||
await changes.DisposeAsync();
|
||||
|
||||
var after = await server.GetJsonAsync($"/api/entries/{id}");
|
||||
Assert.AreEqual("deleted", after.Str("state"));
|
||||
Assert.AreEqual(JsonValueKind.Null, after.GetProperty("instagramUrl").ValueKind);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task DeletionCanLetTheEntryComeBack()
|
||||
{
|
||||
await using var server = await WebTestServer.StartAsync();
|
||||
var account = await server.AddAccountWithEntriesAsync("marta.demo", 2, Make.T0, TimeSpan.FromHours(1));
|
||||
var ids = (await server.Db.Entries.ListByAccountAsync(account.Id)).Select(e => e.Id).ToList();
|
||||
var (status, _) = await server.SendJsonAsync(HttpMethod.Post, "/api/entries/delete", new { ids, mode = "allowReturn" });
|
||||
Assert.AreEqual(HttpStatusCode.OK, status);
|
||||
Assert.IsEmpty(await server.Db.Entries.ListByAccountAsync(account.Id), "forgotten: a later check may download them again");
|
||||
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/entries/delete", new { ids = Array.Empty<long>() })).Status);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CsvFieldsAreQuotedForExcelAndFormulasAreDefused()
|
||||
{
|
||||
Assert.AreEqual(string.Empty, CsvExport.Field(null));
|
||||
Assert.AreEqual("semplice", CsvExport.Field("semplice"));
|
||||
Assert.AreEqual("\"a;b\"", CsvExport.Field("a;b"));
|
||||
Assert.AreEqual("\"dice \"\"ciao\"\"\"", CsvExport.Field("dice \"ciao\""));
|
||||
Assert.AreEqual("\"riga\nnuova\"", CsvExport.Field("riga\nnuova"));
|
||||
Assert.AreEqual("\" spazio\"", CsvExport.Field(" spazio"));
|
||||
Assert.AreEqual("\"'=1+1\"", CsvExport.Field("=1+1"));
|
||||
Assert.AreEqual("\"'@marta ciao\"", CsvExport.Field("@marta ciao"));
|
||||
Assert.AreEqual("\"'-3\"", CsvExport.Field("-3"));
|
||||
Assert.AreEqual("a;\"b;c\";", CsvExport.Line(["a", "b;c", null]));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheExportIsUtf8WithBomSemicolonsAndOneLinePerEntry()
|
||||
{
|
||||
await using var server = await WebTestServer.StartAsync();
|
||||
var account = await server.AddAccountWithEntriesAsync("marta.demo", 3, Make.T0, TimeSpan.FromDays(1), caption: "Città; mare e \"sole\"\nseconda riga");
|
||||
var ids = (await server.Db.Entries.ListByAccountAsync(account.Id)).Select(e => e.Id).ToList();
|
||||
|
||||
using var request = server.Request(HttpMethod.Post, "/api/entries/export", new { ids });
|
||||
using var response = await server.Client.SendAsync(request);
|
||||
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.AreEqual("text/csv", response.Content.Headers.ContentType?.MediaType);
|
||||
Assert.AreEqual("attachment", response.Content.Headers.ContentDisposition?.DispositionType);
|
||||
StringAssert.EndsWith(response.Content.Headers.ContentDisposition?.FileName?.Trim('"'), ".csv");
|
||||
var bytes = await response.Content.ReadAsByteArrayAsync();
|
||||
CollectionAssert.AreEqual(new byte[] { 0xEF, 0xBB, 0xBF }, bytes.Take(3).ToArray(), "UTF-8 with BOM for Excel");
|
||||
var text = Encoding.UTF8.GetString(bytes, 3, bytes.Length - 3);
|
||||
StringAssert.StartsWith(text, string.Join(';', CsvExport.Header) + "\r\n");
|
||||
StringAssert.Contains(text, "\"Città; mare e \"\"sole\"\"\nseconda riga\"");
|
||||
StringAssert.Contains(text, "marta.demo;Post;13/10/2026;10:00:00;");
|
||||
Assert.AreEqual(4, text.Split("\r\n", StringSplitOptions.RemoveEmptyEntries).Length, "header and three entries");
|
||||
|
||||
// By filter: the same query the page uses.
|
||||
using var byFilter = server.Request(HttpMethod.Post, "/api/entries/export", new { query = "kind=photos&from=2026-10-12" });
|
||||
using var filtered = await server.Client.SendAsync(byFilter);
|
||||
var filteredText = Encoding.UTF8.GetString(await filtered.Content.ReadAsByteArrayAsync());
|
||||
Assert.AreEqual(3, filteredText.Split("\r\n", StringSplitOptions.RemoveEmptyEntries).Length, "header and the two entries of 12 and 13 October");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Library;
|
||||
using Febe.Core.Storage;
|
||||
using Febe.Data;
|
||||
using Febe.Tests.Support;
|
||||
using Febe.Web;
|
||||
using Febe.Web.Library;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Febe.Tests.Web.Support;
|
||||
|
||||
/// <summary>
|
||||
/// Febe.Web on a real Kestrel listening on 127.0.0.1 with a free port (no test server package needed), with a
|
||||
/// temporary database and library, and an HttpClient pointed at it.
|
||||
/// </summary>
|
||||
internal sealed class WebTestServer : IAsyncDisposable
|
||||
{
|
||||
private WebTestServer(TempFolder temp, FebeDatabase db, FebeLibrary library, ManualClock clock, WebApplication app, Uri address)
|
||||
{
|
||||
Temp = temp;
|
||||
Db = db;
|
||||
Library = library;
|
||||
Clock = clock;
|
||||
App = app;
|
||||
Address = address;
|
||||
Client = NewClient();
|
||||
}
|
||||
|
||||
public TempFolder Temp { get; }
|
||||
|
||||
public FebeDatabase Db { get; }
|
||||
|
||||
public FebeLibrary Library { get; }
|
||||
|
||||
public ManualClock Clock { get; }
|
||||
|
||||
public WebApplication App { get; }
|
||||
|
||||
public Uri Address { get; }
|
||||
|
||||
/// <summary>A client without cookies of its own (each test decides what to send).</summary>
|
||||
public HttpClient Client { get; }
|
||||
|
||||
/// <summary>«http://127.0.0.1:port», the value of Origin for requests coming from the interface.</summary>
|
||||
public string Origin => $"{Address.Scheme}://{Address.Authority}";
|
||||
|
||||
public LibraryChanges Changes => App.Services.GetRequiredService<LibraryChanges>();
|
||||
|
||||
public static async Task<WebTestServer> StartAsync(FebeWebOptions? options = null, Action<IServiceCollection>? services = null)
|
||||
{
|
||||
var temp = new TempFolder("web");
|
||||
var db = await FebeDatabase.OpenAsync(temp.Combine("dati"));
|
||||
var clock = new ManualClock(Make.T0);
|
||||
var library = new FebeLibrary(db, new DataFolderLayout(temp.Combine("dati")), new LibraryLayout(temp.Combine("libreria")), clock);
|
||||
options ??= new FebeWebOptions { Access = AccessMode.None };
|
||||
options = options with { AllowedHosts = options.AllowedHosts.Count == 0 ? FebeWebOptions.LoopbackHosts(0) : options.AllowedHosts };
|
||||
var app = FebeWebHost.Build(options, FebeListen.Loopback(0), s =>
|
||||
{
|
||||
s.AddSingleton<IFebeStorage>(db);
|
||||
s.AddSingleton(library);
|
||||
s.AddSingleton<IClock>(clock);
|
||||
services?.Invoke(s);
|
||||
});
|
||||
await app.StartAsync();
|
||||
return new WebTestServer(temp, db, library, clock, app, FebeWebHost.BoundAddress(app));
|
||||
}
|
||||
|
||||
public HttpClient NewClient(bool cookies = false, bool redirects = false)
|
||||
{
|
||||
var handler = new HttpClientHandler { AllowAutoRedirect = redirects, UseCookies = cookies, CookieContainer = new CookieContainer() };
|
||||
return new HttpClient(handler) { BaseAddress = Address, Timeout = TimeSpan.FromSeconds(30) };
|
||||
}
|
||||
|
||||
/// <summary>A request as the interface sends it (Origin of the interface on commands).</summary>
|
||||
public HttpRequestMessage Request(HttpMethod method, string path, object? body = null, string? origin = "")
|
||||
{
|
||||
var request = new HttpRequestMessage(method, path);
|
||||
if (body is not null)
|
||||
{
|
||||
request.Content = new StringContent(body as string ?? JsonSerializer.Serialize(body, Json), Encoding.UTF8, "application/json");
|
||||
}
|
||||
|
||||
if (origin is not null)
|
||||
{
|
||||
request.Headers.TryAddWithoutValidation("Origin", origin.Length == 0 ? Origin : origin);
|
||||
}
|
||||
|
||||
return request;
|
||||
}
|
||||
|
||||
public static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
|
||||
|
||||
public async Task<JsonElement> GetJsonAsync(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();
|
||||
}
|
||||
|
||||
public async Task<(HttpStatusCode Status, JsonElement Body)> SendJsonAsync(HttpMethod method, string path, object? body = null)
|
||||
{
|
||||
using var request = Request(method, path, body);
|
||||
using var response = await Client.SendAsync(request);
|
||||
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, json);
|
||||
}
|
||||
|
||||
/// <summary>Adds an account with a few stored entries spread over days (no files on disk).</summary>
|
||||
public async Task<Account> AddAccountWithEntriesAsync(string username, int entries, DateTimeOffset newest, TimeSpan step, EntryKind kind = EntryKind.Post, string? caption = null)
|
||||
{
|
||||
var account = await Db.Accounts.AddAsync(Make.Account(username));
|
||||
var items = new List<NewEntry>();
|
||||
for (var i = 0; i < entries; i++)
|
||||
{
|
||||
var media = Make.Stored(kind == EntryKind.Story ? Make.Video() : Make.Photo(), Make.Sha((1000 * username.Length) + i + 1), $"post/{username}-{i}.jpg");
|
||||
items.Add(new NewEntry(Make.Entry(account.Id, $"{username}-{i}", newest - (step * i), kind, caption) with { State = EntryState.Downloaded }, [media]));
|
||||
}
|
||||
|
||||
await Db.Entries.AddManyAsync(items);
|
||||
return account;
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
Client.Dispose();
|
||||
await App.StopAsync();
|
||||
await App.DisposeAsync();
|
||||
await Db.DisposeAsync();
|
||||
Temp.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Small JSON helpers for the API answers.</summary>
|
||||
internal static class JsonAnswers
|
||||
{
|
||||
public static string Str(this JsonElement e, string name) => e.GetProperty(name).GetString() ?? string.Empty;
|
||||
|
||||
public static int Int(this JsonElement e, string name) => e.GetProperty(name).GetInt32();
|
||||
|
||||
public static long Long(this JsonElement e, string name) => e.GetProperty(name).GetInt64();
|
||||
|
||||
public static bool Bool(this JsonElement e, string name) => e.GetProperty(name).GetBoolean();
|
||||
|
||||
public static JsonElement.ArrayEnumerator Items(this JsonElement e, string name) => e.GetProperty(name).EnumerateArray();
|
||||
|
||||
public static Task<T?> ReadAsync<T>(this HttpContent content) => content.ReadFromJsonAsync<T>(WebTestServer.Json);
|
||||
}
|
||||
Reference in new issue
Block a user