Files
Febe/tests/Febe.Tests/Web/DemoTests.cs
T
Claude e33540246e 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
2026-10-13 19:14:35 +00:00

288 lines
13 KiB
C#

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);
}
}
}