Files
Febe/tests/Febe.Tests/Web/DemoExportTests.cs
T
Alby96andClaude Opus 5.5 724db13e1b E2: misure del filtro Copie, migrazione 0004 e prove di web e Docker
Il filtro «Copie» con 200.000 elementi stava al limite dei 250 ms
(«Copiati» 249 ms): la migrazione 0004 aggiunge solo l'indice
ix_media_sha256_entry e la finestra scende a 160 ms. Totali e giorni
contano «Copiati» partendo dalle copie e gli altri valori con un solo
passaggio sui file dietro gli elenchi degli SHA-256 copiati (1,5 s ->
0,7 s); hanno un limite loro di 3 s, scritto in decisioni.md con le
misure.

«Copia di nuovo» sceglie un file dell'account che è sul disco: prima
prendeva il primo con quello SHA-256 e, nella demo, a certe ore non
scriveva nulla.

Nuove prove: API delle copie, coerenza della demo, interfaccia nel
browser, opzioni del server, avvio del contenitore con /esporta,
contenuto dell'immagine e modelli, migrazione 4 e scala.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 15:29:59 +01:00

154 lines
8.0 KiB
C#

using System.Net;
using System.Security.Cryptography;
using System.Text.Json;
using Febe.Core.Domain;
using Febe.Core.Library;
using Febe.Tests.Support;
using Febe.Tests.Web.Support;
using Febe.Web.Demo;
namespace Febe.Tests.Web;
/// <summary>
/// The copies of the demo (spec §10.6, tappa E2) tell one story everywhere: the block «Copie esterne» of each account
/// counts what the «Copie» filter finds and what the tiles mark; every job has its files; a copy «Copiato» is a real
/// file with its SHA-256 in its folder, a copy «Tolto» has none, the old file of a «Superato» is still there.
/// </summary>
[TestClass]
public sealed class DemoExportTests
{
public TestContext TestContext { get; set; } = null!;
[TestMethod]
[Timeout(300_000, CooperativeCancellation = true)]
public async Task TheDemoExportDataIsCoherent()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder("demo-export-coerente");
await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path), ct);
using var client = new HttpClient { BaseAddress = demo.Address, Timeout = TimeSpan.FromSeconds(60) };
async Task<JsonElement> GetAsync(string path)
{
using var response = await client.GetAsync(path, ct);
var text = await response.Content.ReadAsStringAsync(ct);
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, $"{path}: {text}");
return JsonDocument.Parse(text).RootElement.Clone();
}
// Every tile of a query, following the cursors.
async Task<List<JsonElement>> AllTilesAsync(string query)
{
var tiles = new List<JsonElement>();
string? cursor = null;
for (var page = 0; page < 100; page++)
{
var answer = await GetAsync($"/api/library?{query}&limit=1000" + (cursor is null ? string.Empty : "&cursor=" + Uri.EscapeDataString(cursor)));
tiles.AddRange(answer.Items("tiles"));
if (answer.GetProperty("older").ValueKind == JsonValueKind.Null)
{
return tiles;
}
cursor = answer.Str("older");
}
Assert.Fail($"too many pages for {query}");
return tiles;
}
// The copies and their files.
var destinations = await demo.Storage.Exports.ListDestinationsAsync(includeRetired: true, ct);
Assert.IsGreaterThanOrEqualTo(2, destinations.Count);
var states = new HashSet<ExportCopyState>();
foreach (var destination in destinations)
{
Assert.IsTrue(Directory.Exists(destination.RootPath), destination.RootPath);
foreach (var copy in await demo.Storage.Exports.ListCopiesAsync(destination.Id, null, 0, 100_000, ct))
{
states.Add(copy.State);
var path = copy.RelativePath is { } relative ? Path.Combine(destination.RootPath, LibraryLayout.ToPlatform(relative)) : null;
switch (copy.State)
{
case ExportCopyState.Copied:
Assert.IsTrue(File.Exists(path), $"«Copiato» without its file: {path}");
Assert.AreEqual(copy.CopySha256, Convert.ToHexStringLower(SHA256.HashData(await File.ReadAllBytesAsync(path!, ct))), path);
Assert.AreEqual(copy.Bytes, new FileInfo(path!).Length, path);
break;
case ExportCopyState.Removed:
Assert.IsFalse(path is not null && File.Exists(path), $"«Tolto» with a file: {path}");
break;
case ExportCopyState.Superseded:
Assert.IsTrue(File.Exists(path), $"the old file of «Superato» stays: {path}");
Assert.AreEqual(copy.CopySha256, Convert.ToHexStringLower(SHA256.HashData(await File.ReadAllBytesAsync(path!, ct))), path);
break;
case ExportCopyState.Failed:
Assert.IsFalse(string.IsNullOrEmpty(copy.LastError), "a failure says why");
break;
}
}
}
CollectionAssert.AreEquivalent(
new[] { ExportCopyState.Copied, ExportCopyState.Removed, ExportCopyState.Superseded, ExportCopyState.Failed },
states.ToArray(),
"the demo shows every state of a copy");
Assert.IsFalse(Directory.EnumerateFiles(temp.Path, "*.part", SearchOption.AllDirectories).Any(f => f.Contains("esporta", StringComparison.Ordinal)), "no .part left");
// Every job has its files, and a finished one has none pending.
var runs = await demo.Storage.Exports.ListRecentRunsAsync(100, ct);
Assert.IsNotEmpty(runs);
foreach (var run in runs)
{
var summary = await demo.Storage.Exports.GetRunSummaryAsync(run.Id, ct);
Assert.IsGreaterThan(0, summary.Total, $"job {run.Id}");
if (run.State == ExportRunState.Completed)
{
Assert.AreEqual(0, summary.ByState.GetValueOrDefault(ExportItemState.Pending), $"job {run.Id}");
}
}
// Each account: the card, the filter and the marks count the same files.
var accounts = (await GetAsync("/api/accounts")).Items("accounts").ToList();
var checkedAccounts = 0;
foreach (var account in accounts)
{
var id = account.Long("id");
var card = (await GetAsync($"/api/accounts/{id}")).GetProperty("export");
// The card counts every due file of the account, its profile pictures too, which «Tutto» leaves out.
async Task<int> FilesAsync(string copies) =>
(await GetAsync($"/api/library/days?accounts={id}&mode=files&copies={copies}")).Int("files")
+ (await GetAsync($"/api/library/days?accounts={id}&mode=files&kind=profile&copies={copies}")).Int("files");
var copied = card.Int("due") - card.Int("notCopied") - card.Int("removedOrSuperseded");
Assert.AreEqual(card.Int("notCopied"), await FilesAsync("notCopied"), account.Str("username"));
Assert.AreEqual(card.Int("removedOrSuperseded"), await FilesAsync("removedOrSuperseded"), account.Str("username"));
Assert.AreEqual(copied, await FilesAsync("copied"), account.Str("username"));
Assert.IsLessThanOrEqualTo(card.Int("notCopied"), card.Int("failed"), "a failed file is one still to copy");
var grouped = await AllTilesAsync($"accounts={id}");
if (!card.Bool("enabled"))
{
Assert.AreEqual(0, card.Int("due"), account.Str("username"));
Assert.IsTrue(grouped.All(t => t.GetProperty("copies").ValueKind == JsonValueKind.Null), "an account that is not exported has no marks");
continue;
}
var marked = grouped.Where(t => t.Str("copies") == "copied").Select(t => t.Long("id")).ToHashSet();
var filtered = (await AllTilesAsync($"accounts={id}&copies=copied")).Select(t => t.Long("id")).ToHashSet();
Assert.IsTrue(marked.SetEquals(filtered), $"{account.Str("username")}: the mark «copiato» is the filter «Copiati»");
foreach (var partly in grouped.Where(t => t.Str("copies") == "partly"))
{
Assert.IsGreaterThan(0, partly.Int("copiesDone"));
Assert.IsLessThan(partly.Int("copiesDue"), partly.Int("copiesDone"));
}
var fileMarks = (await AllTilesAsync($"accounts={id}&mode=files")).Count(t => t.Str("copies") == "copied")
+ (await AllTilesAsync($"accounts={id}&mode=files&kind=profile")).Count(t => t.Str("copies") == "copied");
Assert.AreEqual(copied, fileMarks, $"{account.Str("username")}: one mark per copied file");
checkedAccounts += card.Int("due") > 0 ? 1 : 0;
}
Assert.IsGreaterThanOrEqualTo(2, checkedAccounts, "the demo has accounts with files to copy");
}
}