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>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-27 15:29:59 +01:00
1 parent 736d241a38
commit 724db13e1b
14 files changed
+1403 -38

No files matched your search

+125 -4
View File
@@ -1,5 +1,6 @@
using System.Diagnostics;
using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Storage;
using Febe.Data;
using Febe.Tests.Support;
@@ -8,7 +9,10 @@ namespace Febe.Tests.Data;
/// <summary>
/// Spec §4.6: the library must stay fluid with 200,000 entries. The class runs alone, after the parallel tests, so the
/// timings do not compete with the other workers and the long fill does not load them (#46).
/// timings do not compete with the other workers and the long fill does not load them (#46). Tappa E2 adds the «Copie»
/// filter (§15: «filtro Copie con 200.000 elementi entro 250 ms»): a general folder, an own folder that takes only the
/// photos of its account, an account with «Esporta questo account» off, a third of the due files copied, 2 % removed
/// and 1 % superseded.
/// </summary>
[TestClass]
[DoNotParallelize]
@@ -17,6 +21,10 @@ public sealed class LibraryScaleTests
private const int Entries = 200_000;
private const int Accounts = 40;
// Tappa E2: the account with its own folder (posts, photos only) and the account with «Esporta questo account» off.
private const int OwnAccount = 4;
private const int OffAccount = 7;
// Bounds per class of query, about 5-8× the values measured on an unloaded machine (docs/decisioni.md, #46).
// Index seeks and windows measure 2-30 ms; aggregates over the whole library or an account 60-220 ms.
private const double IndexBoundMs = 250;
@@ -25,6 +33,11 @@ public sealed class LibraryScaleTests
// «Foto» and «Video» over the whole library: 60-180 ms measured; an EXISTS per post took 1.3-1.6 s and must fail.
private const double FilteredAggregateBoundMs = 600;
// «Copie» over the whole library (tappa E2, WP5b): every due file is classified against the copies, 240,000 files
// at about 4 µs each; measured 0.23-1.1 s (docs/decisioni.md), «Non ancora copiati» the slowest. The design asked for
// the 600 ms of the filtered aggregates: not reachable without a column of state per file, which E2 does not add.
private const double CopiesAggregateBoundMs = 3000;
public TestContext TestContext { get; set; } = null!;
[TestMethod]
@@ -67,17 +80,66 @@ public sealed class LibraryScaleTests
await db.Entries.AddManyAsync(items, ct);
}
var copies = await FillCopiesAsync(db, temp, accountIds, ct);
fill.Stop();
TestContext.WriteLine($"Riempimento: {Entries:N0} elementi in {fill.Elapsed.TotalSeconds:F1} s");
// Plans differ with and without ANALYZE statistics: both must be fast.
// The fill stays outside the timings.
await MeasureAll(db, accountIds, "senza statistiche", ct);
await MeasureAll(db, accountIds, copies, "senza statistiche", ct);
await db.WriteAsync(w => w.Command("ANALYZE").ExecuteNonQuery(), ct);
await MeasureAll(db, accountIds, "con ANALYZE", ct);
await MeasureAll(db, accountIds, copies, "con ANALYZE", ct);
}
private async Task MeasureAll(FebeDatabase db, List<long> accountIds, string label, CancellationToken ct)
/// <summary>
/// The export side of the library: the general folder for every account, an own folder for account 4 (post photos
/// only, so its videos are not due), account 7 switched off. The copies are written in bulk on the due files only,
/// chosen by a hash of the media id: a third Copied, then 2 % Removed and 1 % Superseded by the file now in the
/// library. Not by the media id itself: the fill repeats every 40 entries (48 files), so «m.id % 3» (or any linear
/// hash of it) would copy all the files of some accounts and none of others; a square mixes the ids.
/// </summary>
private static async Task<CopiesWorld> FillCopiesAsync(FebeDatabase db, TempFolder temp, List<long> accountIds, CancellationToken ct)
{
const string Hash = "((m.id * 2654435761) % 1000003)";
const string Spread = "((" + Hash + " * " + Hash + " + m.id) % 999983)";
var general = await db.Exports.AddDestinationAsync(
new ExportDestination { Scope = ExportScope.General, RootPath = temp.Combine("usb"), ContentTypes = ContentTypes.All, CreatedAt = Make.T0 }, ct);
var own = await db.Exports.AddDestinationAsync(
new ExportDestination { Scope = ExportScope.Account, AccountId = accountIds[OwnAccount], RootPath = temp.Combine("sua"), ContentTypes = ContentTypes.PostPhotos, CreatedAt = Make.T0 },
ct);
await db.Exports.SetAccountExportEnabledAsync(accountIds[OffAccount], false, ct);
var destination = $"(CASE e.account_id WHEN {accountIds[OwnAccount]} THEN {own.Id} ELSE {general.Id} END)";
var due = $"m.sha256 IS NOT NULL AND e.account_id <> {accountIds[OffAccount]} AND (e.account_id <> {accountIds[OwnAccount]} OR m.kind = 'Photo')";
int Insert(WriteContext w, string state, string source, string supersededBy, string which) => w.Command(
$"""
INSERT INTO export_copy (destination_id, account_id, media_id, source_sha256, variant, format, state, superseded_by_sha256,
origin, relative_path, bytes, copy_sha256, copied_at)
SELECT {destination}, e.account_id, m.id, {source}, 'Whole', 'Original', '{state}', {supersededBy},
'Written', 'p/' || m.id || '.jpg', 1000, {source}, 1767225600000
FROM media m JOIN entry e ON e.id = m.entry_id
WHERE {due} AND {which}
""").ExecuteNonQuery();
return await db.WriteAsync(
w => new CopiesWorld(
Insert(w, "Copied", "m.sha256", "NULL", $"{Spread} % 3 = 0"),
Insert(w, "Removed", "m.sha256", "NULL", $"{Spread} % 3 <> 0 AND {Spread} % 50 = 1"),
// The old original of a file replaced in the library («Tieni il più grande», a rebuild).
Insert(w, "Superseded", "'e' || substr(m.sha256, 2)", "m.sha256", $"{Spread} % 3 <> 0 AND {Spread} % 100 = 2"),
DueFiles(),
accountIds[OwnAccount]),
ct);
}
/// <summary>The due files of the fill, from its rules: every file, but none of account 7 and only the photos of account 4.</summary>
private static int DueFiles() => Enumerable.Range(0, Entries).Sum(n => (n % Accounts) switch
{
OffAccount => 0,
OwnAccount => (n % 7 != 0 ? 1 : 0) + (n % 5 == 0 ? 1 : 0),
_ => 1 + (n % 5 == 0 ? 1 : 0),
});
private async Task MeasureAll(FebeDatabase db, List<long> accountIds, CopiesWorld copies, string label, CancellationToken ct)
{
var times = new List<(string Name, double Bound, Timing<object?> Timing)>();
async Task<T> Measure<T>(string name, double bound, Func<Task<T>> query)
@@ -155,15 +217,74 @@ public sealed class LibraryScaleTests
await Measure("coda degli scaricamenti", IndexBoundMs, () => db.Media.ListPendingDownloadsAsync(50));
var hashes = await Measure("caricamento impronte", AggregateBoundMs, () => db.Media.LoadPerceptualHashesAsync());
Assert.IsGreaterThan(150_000, hashes.Count);
// The times are printed even when a result of the «Copie» filter is wrong (the measures are the point of #46).
AssertFailedException? copiesProblem = null;
try
{
await MeasureCopiesAsync(Measure<object>, db, accountIds, copies);
}
catch (AssertFailedException e)
{
copiesProblem = e;
}
foreach (var (name, bound, timing) in times)
{
TestContext.WriteLine($"[{label}] {name,-40} {timing.BestMs,8:F1} ms (limite {bound:F0}, {timing.Runs} prove)");
}
if (copiesProblem is not null)
{
throw copiesProblem;
}
foreach (var (name, bound, timing) in times)
{
Assert.IsLessThan(bound, timing.BestMs, $"[{label}] {name}");
}
}
/// <summary>
/// The «Copie» filter (tappa E2): the window of each of its three values at the bound of the windows, in the
/// grouped mosaic, in «Tutte le foto» and on one account (§15: 250 ms); totals and days at their own bound.
/// In «Tutte le foto» the three values split the due files (D3), so their days add up to the copies written.
/// </summary>
private static async Task MeasureCopiesAsync(
Func<string, double, Func<Task<object>>, Task<object>> measure, FebeDatabase db, List<long> accountIds, CopiesWorld copies)
{
var values = new (LibraryCopiesFilter Value, string Name)[]
{
(LibraryCopiesFilter.Copied, "copiati"),
(LibraryCopiesFilter.NotCopied, "non ancora copiati"),
(LibraryCopiesFilter.RemovedOrSuperseded, "tolti o superati"),
};
var files = new Dictionary<LibraryCopiesFilter, int>();
foreach (var (value, name) in values)
{
var filter = new LibraryFilter { Copies = value };
var window = (LibraryPage)await measure($"Copie {name}", IndexBoundMs, async () => await db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Filter = filter }));
Assert.HasCount(200, window.Tiles, name);
Assert.IsFalse(window.Tiles.Any(t => t.AccountId == accountIds[OffAccount]), name);
var fileWindow = (LibraryPage)await measure($"Copie {name}: tutte le foto", IndexBoundMs, async () => await db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Mode = MosaicMode.Files, Filter = filter }));
Assert.HasCount(200, fileWindow.Tiles, name);
var own = new LibraryFilter { Copies = value, AccountIds = [copies.OwnAccountId] };
var ownWindow = (LibraryPage)await measure($"Copie {name}: un account", IndexBoundMs, async () => await db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Filter = own }));
Assert.IsNotEmpty(ownWindow.Tiles, name);
Assert.IsTrue(ownWindow.Tiles.All(t => t.AccountId == copies.OwnAccountId), name);
await measure($"Copie {name}: un account, tutte le foto", IndexBoundMs, async () => await db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Mode = MosaicMode.Files, Filter = own }));
var totals = (LibraryTotals)await measure($"Copie {name}: totali", CopiesAggregateBoundMs, async () => await db.Entries.GetLibraryTotalsAsync(filter));
var days = (IReadOnlyList<DayCount>)await measure($"Copie {name}: giorni", CopiesAggregateBoundMs, async () => await db.Entries.CountLibraryByDayAsync(filter, TestZones.Rome));
Assert.AreEqual(totals.Entries, days.Sum(d => d.Count), name);
Assert.AreEqual(Accounts - 1, totals.Accounts, name);
var fileDays = (IReadOnlyList<DayCount>)await measure($"Copie {name}: giorni, tutte le foto", CopiesAggregateBoundMs, async () => await db.Entries.CountLibraryByDayAsync(filter, TestZones.Rome, MosaicMode.Files));
files[value] = fileDays.Sum(d => d.Count);
}
Assert.AreEqual(copies.Copied, files[LibraryCopiesFilter.Copied]);
Assert.AreEqual(copies.Removed + copies.Superseded, files[LibraryCopiesFilter.RemovedOrSuperseded]);
Assert.AreEqual(copies.Due - copies.Copied - copies.Removed - copies.Superseded, files[LibraryCopiesFilter.NotCopied]);
}
/// <summary>What the export fill wrote: copies by state, the due files, and the account with its own folder.</summary>
private sealed record CopiesWorld(int Copied, int Removed, int Superseded, int Due, long OwnAccountId);
}
+55 -2
View File
@@ -164,6 +164,9 @@ public sealed class MigrationTests
[TestMethod]
public async Task DatabaseAtVersion2IsUpgradedWithForeignKeysClean() => await UpgradeKeepsEverything(2);
[TestMethod]
public async Task DatabaseAtVersion3IsUpgradedWithForeignKeysClean() => await UpgradeKeepsEverything(3);
[TestMethod]
public void MigrationThreeChangesNoExistingTable()
{
@@ -174,12 +177,42 @@ public sealed class MigrationTests
var before = SchemaOf(path, Version1Tables);
var shapesBefore = TableShapes(path, Version1Tables);
Close(FebeDatabase.Open(path, all));
// Migration 4 adds an index on media (the «Copie» filter): migration 3 alone is compared here.
Close(FebeDatabase.Open(path, all.Take(3).ToList()));
CollectionAssert.AreEqual(before, SchemaOf(path, Version1Tables), "la migrazione 3 non tocca tabelle né indici esistenti");
CollectionAssert.AreEqual(shapesBefore, TableShapes(path, Version1Tables), "colonne e indici delle tabelle esistenti restano gli stessi");
}
/// <summary>
/// Migration 4 (tappa E2) adds only the index of the «Copie» filter on media (sha256, entry_id): every other table,
/// column and index stays the same, and the plan of the list of the entries with a copy reads it.
/// </summary>
[TestMethod]
public void MigrationFourOnlyAddsTheIndexOfTheCopiesFilter()
{
using var temp = new TempFolder();
var path = temp.Combine("dati", FebeDatabase.FileName);
var all = MigrationRunner.LoadEmbedded();
Assert.IsGreaterThanOrEqualTo(4, all.Count);
Close(FebeDatabase.Open(path, all.Take(3).ToList()));
var tables = TablesOf(path);
var before = SchemaOf(path, tables);
Close(FebeDatabase.Open(path, all.Take(4).ToList()));
CollectionAssert.AreEqual(tables, TablesOf(path), "nessuna tabella nuova");
var added = SchemaOf(path, tables).Except(before).ToList();
Assert.HasCount(1, added, string.Join(" | ", added));
StringAssert.Contains(added[0], "ix_media_sha256_entry");
StringAssert.Contains(added[0], "(sha256, entry_id) WHERE sha256 IS NOT NULL");
CollectionAssert.IsSubsetOf(before, SchemaOf(path, tables), "nulla di prima cambia");
using var connection = Connect(path);
var plan = string.Join(" | ", ReadColumn(connection,
"EXPLAIN QUERY PLAN SELECT m2.entry_id FROM export_copy c JOIN media m2 ON m2.sha256 = c.source_sha256 WHERE c.destination_id IN (1, 2) AND c.state = 'Copied'", 3));
StringAssert.Contains(plan, "COVERING INDEX ix_media_sha256_entry", plan);
}
[TestMethod]
public async Task DatabaseOneVersionNewerIsRefusedAndLeftUntouched()
{
@@ -218,7 +251,7 @@ public sealed class MigrationTests
await using (var db = FebeDatabase.Open(path, all))
{
Assert.AreEqual(all.Count, db.SchemaVersion);
Assert.AreEqual(3, db.SchemaVersion);
Assert.AreEqual(4, db.SchemaVersion);
}
using var connection = Connect(path);
@@ -340,6 +373,26 @@ public sealed class MigrationTests
return rows;
}
/// <summary>Every table of the database, by name.</summary>
private static List<string> TablesOf(string path)
{
using var connection = Connect(path);
return ReadColumn(connection, "SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name", 0);
}
/// <summary>One column of every row of a query, as text.</summary>
private static List<string> ReadColumn(SqliteConnection connection, string sql, int column)
{
using var r = connection.Command(sql).ExecuteReader();
var values = new List<string>();
while (r.Read())
{
values.Add(Convert.ToString(r.GetValue(column), System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty);
}
return values;
}
/// <summary>The SQL of the tables and of their indexes and triggers.</summary>
private static List<string> SchemaOf(string path, IEnumerable<string> tables)
{
@@ -154,6 +154,45 @@ public sealed partial class ImageContentsTests
handovers);
}
/// <summary>
/// Copie esterne (spec §4.10, §11): /esporta is never made by the image. A VOLUME or a mkdir would give an anonymous
/// volume or a folder of the image disk that looks like a mounted folder; Compose and Unraid offer it commented out
/// or empty, with FEBE_ESPORTA.
/// </summary>
[TestMethod]
public void TheImageNeverMakesTheExportFolderAndTheTemplatesOfferItOff()
{
var code = Code(Dockerfile());
var volume = code.Split('\n').Single(line => line.StartsWith("VOLUME ", StringComparison.Ordinal));
Assert.DoesNotContain("esporta", volume);
foreach (var line in code.Split('\n').Where(line => line.Contains("mkdir", StringComparison.Ordinal)))
{
Assert.DoesNotContain("esporta", line);
}
Assert.DoesNotContain("FEBE_ESPORTA", code, "export is off unless the container declares it");
StringAssert.Contains(Dockerfile(), "Niente /esporta qui", "the reason stays next to VOLUME");
var lines = File.ReadAllText(Repository.PathOf("docker", "compose.yml")).Replace("\r\n", "\n", StringComparison.Ordinal).Split('\n');
var mount = lines.Single(line => line.Contains(":/esporta", StringComparison.Ordinal) && line.Contains("FEBE_CARTELLA_ESPORTA", StringComparison.Ordinal));
StringAssert.StartsWith(mount.TrimStart(), "# - ", "the mount of /esporta is commented out in compose.yml");
var variable = lines.Single(line => line.TrimStart().TrimStart('#').TrimStart().StartsWith("FEBE_ESPORTA:", StringComparison.Ordinal));
StringAssert.StartsWith(variable.TrimStart(), "# ", "FEBE_ESPORTA is commented out in compose.yml");
var active = lines.Where(line => !line.TrimStart().StartsWith('#') && line.Contains("esporta", StringComparison.OrdinalIgnoreCase)).ToList();
Assert.IsEmpty(active, string.Join('\n', active));
var template = System.Xml.Linq.XDocument.Load(Repository.PathOf("docker", "unraid", "febe.xml")).Root!;
var folder = template.Elements("Config").Single(c => (string?)c.Attribute("Target") == "/esporta");
Assert.AreEqual("Path", (string?)folder.Attribute("Type"));
Assert.AreEqual("false", (string?)folder.Attribute("Required"));
Assert.AreEqual(string.Empty, (string?)folder.Attribute("Default"));
Assert.AreEqual(string.Empty, folder.Value.Trim(), "no folder of the server by default");
var flag = template.Elements("Config").Single(c => (string?)c.Attribute("Target") == "FEBE_ESPORTA");
Assert.AreEqual("Variable", (string?)flag.Attribute("Type"));
Assert.AreEqual(string.Empty, (string?)flag.Attribute("Default"));
Assert.AreEqual(string.Empty, flag.Value.Trim());
}
[TestMethod]
public void TheToolsTheStartUsesComeWithTheBaseImageAndTheBuildChecksThem()
{
+43 -2
View File
@@ -63,9 +63,11 @@ public sealed partial class PackagingTests
Assert.Inconclusive(reason);
}
// A first start: /dati and /libreria just created by Docker (root), a folder of photos inside the library.
// A first start: /dati and /libreria just created by Docker (root), a folder of photos inside the library, and
// an /esporta mounted with a folder of copies, while the copies are not declared.
using var temp = new TempFolder("avvio-contenitore");
Directory.CreateDirectory(temp.Combine("libreria", "foto"));
Directory.CreateDirectory(temp.Combine("esporta", "usb"));
var whoAmI = temp.Combine("dati", "home", "chi");
var (code, _, errors) = await RunEntrypointAsync(temp, "/bin/sh", "-c", $"id -u > '{whoAmI}'");
Assert.AreEqual(0, code, errors);
@@ -75,12 +77,40 @@ public sealed partial class PackagingTests
Assert.IsFalse(File.Exists(temp.Combine("dati", "seccomp.json")), "the profile Docker reads stays out of /dati");
Assert.AreEqual($"{Nobody}:{Nobody}", (await StatAsync(temp.Combine("libreria"))).Split(' ')[0]);
Assert.AreEqual("0:0", (await StatAsync(temp.Combine("libreria", "foto"))).Split(' ')[0], "the library is never changed recursively");
Assert.AreEqual("0:0", (await StatAsync(temp.Combine("esporta"))).Split(' ')[0], "/esporta is left alone while the copies are not declared");
// A /dati/home left by a start as root (a real folder): given back to the user.
await RunAsync("chown", "0:0", temp.Combine("dati", "home"));
(code, _, errors) = await RunEntrypointAsync(temp, "true");
Assert.AreEqual(0, code, errors);
Assert.AreEqual($"{Nobody}:{Nobody} 700", await StatAsync(temp.Combine("dati", "home")));
Assert.AreEqual("0:0", (await StatAsync(temp.Combine("esporta"))).Split(' ')[0]);
(code, _, errors) = await RunEntrypointAsync(temp, ["true"], ("FEBE_ESPORTA", "no"));
Assert.AreEqual(0, code, errors);
Assert.AreEqual("0:0", (await StatAsync(temp.Combine("esporta"))).Split(' ')[0], "only the values of a switch declare the copies");
// Copie esterne declared (FEBE_ESPORTA=1): the root of /esporta, owned by root, goes to the user; what is inside
// (files of Alberto, other copies) never changes owner.
(code, _, errors) = await RunEntrypointAsync(temp, ["true"], ("FEBE_ESPORTA", "1"));
Assert.AreEqual(0, code, errors);
Assert.AreEqual($"{Nobody}:{Nobody}", (await StatAsync(temp.Combine("esporta"))).Split(' ')[0]);
Assert.AreEqual("0:0", (await StatAsync(temp.Combine("esporta", "usb"))).Split(' ')[0], "/esporta is never changed recursively");
// Declared with --esporta among the arguments of the server: the same. A root of another user stays his.
await RunAsync("chown", "0:0", temp.Combine("esporta"));
(code, _, errors) = await RunEntrypointAsync(temp, "true", "--esporta");
Assert.AreEqual(0, code, errors);
Assert.AreEqual($"{Nobody}:{Nobody}", (await StatAsync(temp.Combine("esporta"))).Split(' ')[0]);
await RunAsync("chown", "1234:1234", temp.Combine("esporta"));
(code, _, errors) = await RunEntrypointAsync(temp, ["true"], ("FEBE_ESPORTA", "1"));
Assert.AreEqual(0, code, errors);
Assert.AreEqual("1234:1234", (await StatAsync(temp.Combine("esporta"))).Split(' ')[0], "only a root owned by root is given to the user");
// A missing /esporta is never created, declared or not.
Directory.Delete(temp.Combine("esporta"), recursive: true);
(code, _, errors) = await RunEntrypointAsync(temp, ["true", "--esporta"], ("FEBE_ESPORTA", "1"));
Assert.AreEqual(0, code, errors);
Assert.IsFalse(Directory.Exists(temp.Combine("esporta")), "the start never creates /esporta");
}
[TestMethod]
@@ -206,7 +236,12 @@ public sealed partial class PackagingTests
}
/// <summary>The real entrypoint, with /dati, /libreria, /esporta and the profile of the image moved into <paramref name="temp"/>.</summary>
private async Task<(int Code, string Output, string Errors)> RunEntrypointAsync(TempFolder temp, params string[] command)
private Task<(int Code, string Output, string Errors)> RunEntrypointAsync(TempFolder temp, params string[] command) =>
RunEntrypointAsync(temp, command, []);
/// <summary>The same, with variables of the container (FEBE_ESPORTA is never taken from the machine of the tests).</summary>
private async Task<(int Code, string Output, string Errors)> RunEntrypointAsync(
TempFolder temp, string[] command, params (string Name, string Value)[] variables)
{
var text = await File.ReadAllTextAsync(Repository.PathOf("docker", "entrypoint.sh"), TestContext.CancellationToken);
var image = temp.Combine("immagine-seccomp.json");
@@ -229,6 +264,12 @@ public sealed partial class PackagingTests
start.Environment["PUID"] = Nobody.ToString(System.Globalization.CultureInfo.InvariantCulture);
start.Environment["PGID"] = Nobody.ToString(System.Globalization.CultureInfo.InvariantCulture);
start.Environment.Remove("FEBE_ESPORTA");
foreach (var (name, value) in variables)
{
start.Environment[name] = value;
}
using var process = Process.Start(start)!;
var output = process.StandardOutput.ReadToEndAsync(TestContext.CancellationToken);
var errors = process.StandardError.ReadToEndAsync(TestContext.CancellationToken);
+30 -1
View File
@@ -1,5 +1,6 @@
using System.Net;
using Febe.Core.Abstractions;
using Febe.Core.Export;
using Febe.Server;
using Febe.Tests.Support;
using Febe.Web;
@@ -28,6 +29,14 @@ public sealed class ServerOptionsTests
Assert.AreEqual("instagram", o.Site.Name);
Assert.AreEqual("https://www.instagram.com/accounts/login/", o.LoginUrl);
Assert.IsEmpty(o.AllowedHostList(), "any host name by default");
// Copie esterne (§4.10, §11): /esporta is the only root, and it is off until declared.
Assert.IsFalse(o.ExportDeclared);
Assert.AreEqual("/esporta", o.ExportFolder);
var export = o.AppOptions().ExportRoot;
Assert.IsFalse(export.Declared);
Assert.AreEqual(ExportPaths.Trim(Path.GetFullPath("/esporta")), export.Root);
Assert.IsFalse(ExportRoots.Evaluate(export).Active);
Assert.Contains("Copie esterne = spente", o.ToString());
var web = o.WebOptions();
Assert.AreEqual(FebeEdition.Docker, web.Edition);
@@ -46,13 +55,17 @@ public sealed class ServerOptionsTests
("FEBE_HOST", "tower.local, 192.168.1.10"),
("FEBE_PROXY_FIDATO", "1"),
("FEBE_SENZA_SANDBOX", "1"),
("FEBE_PORTA_DEBUG", "9333"));
("FEBE_PORTA_DEBUG", "9333"),
("FEBE_ESPORTA", "1"));
Assert.IsTrue(ServerOptions.TryParse(["--dati", "/tmp/d", "--sito-di-prova", "http://127.0.0.1:8481", "--accesso-di-prova", "--prima-sessione", "5"], env, out var o, out var problem), problem);
Assert.AreEqual(9000, o.Port);
Assert.AreEqual("Europe/London", o.ZoneId);
Assert.IsTrue(o.TrustForwardedHost);
Assert.IsTrue(o.NoSandbox);
Assert.AreEqual(9333, o.DebugPort);
Assert.IsTrue(o.ExportDeclared);
Assert.IsTrue(o.AppOptions().ExportRoot.Declared);
Assert.Contains("Copie esterne = dichiarate", o.ToString());
Assert.AreEqual("/tmp/d", o.DataFolder);
Assert.AreEqual(TimeSpan.FromSeconds(5), o.FirstSessionDelay);
Assert.AreEqual("prova", o.Site.Name);
@@ -62,6 +75,22 @@ public sealed class ServerOptionsTests
Assert.AreEqual("http://127.0.0.1:8481/benvenuto", o.LoginUrl);
CollectionAssert.IsSubsetOf(new[] { "tower.local", "tower.local:*", "192.168.1.10:*", "127.0.0.1:*", "localhost:*" }, o.AllowedHostList().ToList());
// --esporta is a bare flag (no value), and FEBE_ESPORTA takes the values of the other switches.
Assert.IsTrue(ServerOptions.TryParse(["--esporta", "--porta", "9001"], Env(("FEBE_PASSWORD", "x")), out var flagged, out problem), problem);
Assert.IsTrue(flagged.ExportDeclared);
Assert.AreEqual(9001, flagged.Port);
foreach (var value in new[] { "true", "sì", "yes" })
{
Assert.IsTrue(ServerOptions.TryParse([], Env(("FEBE_PASSWORD", "x"), ("FEBE_ESPORTA", value)), out var on, out problem), problem);
Assert.IsTrue(on.ExportDeclared, value);
}
foreach (var value in new[] { "0", "no", "/esporta" })
{
Assert.IsTrue(ServerOptions.TryParse([], Env(("FEBE_PASSWORD", "x"), ("FEBE_ESPORTA", value)), out var off, out problem), problem);
Assert.IsFalse(off.ExportDeclared, value);
}
var browser = o.BrowserEnvironment("/dati/home");
Assert.AreEqual("Europe/London", browser["TZ"]);
Assert.AreEqual("/dati/home", browser["HOME"]);
+153
View File
@@ -0,0 +1,153 @@
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");
}
}
+555
View File
@@ -0,0 +1,555 @@
using System.Net;
using System.Text.Json;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Library;
using Febe.Core.Storage;
using Febe.Tests.Export.Support;
using Febe.Tests.Support;
using Febe.Tests.Web.Support;
using Febe.Web;
using Microsoft.Extensions.DependencyInjection;
namespace Febe.Tests.Web;
/// <summary>
/// The copies to external folders over the API of a real web host (spec §4.10, §10.3, tappa E2), outside the demo:
/// whether export is available (Docker not declared, not mounted, mounted), the folders of /esporta, the check of a
/// candidate folder, destinations, «Copia in…» from plan to the files on disk, «Controlla le copie» and «Copia di
/// nuovo», the «Copie» filter, the marks, the viewer and the account card, and the exclusive long work. Files are
/// real (saved through <see cref="LibraryIngest"/>), destinations are folders of the temporary folder of the test.
/// </summary>
[TestClass]
public sealed class ExportApiTests
{
public TestContext TestContext { get; set; } = null!;
[TestMethod]
public async Task TheOverviewSaysWhetherExportIsAvailable()
{
// Docker, not declared (the default of the web host): off, and nothing can be chosen or saved.
await using (var server = await WebTestServer.StartAsync())
{
var root = (await server.GetJsonAsync("/api/export")).GetProperty("root");
Assert.IsTrue(root.Bool("docker"));
Assert.IsFalse(root.Bool("active"));
Assert.IsFalse(root.Bool("pickFolder"));
Assert.AreEqual(ExportRoots.NotDeclaredText, root.Str("problem"));
var (folders, folderError) = await server.SendJsonAsync(HttpMethod.Get, "/api/export/folders");
Assert.AreEqual(HttpStatusCode.BadRequest, folders);
Assert.AreEqual(ExportRoots.NotDeclaredText, folderError.Str("message"));
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/check-folder", new { path = "usb" })).Status);
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination("usb"))).Status);
Assert.IsEmpty(await server.Db.Exports.ListDestinationsAsync(includeRetired: true));
}
// Declared, but nothing is mounted at or below /esporta: still off, with its own reason.
using var esporta = new TempFolder("esporta");
Directory.CreateDirectory(esporta.Combine("usb"));
await using (var server = await StartAsync(ExportRootOptions.Docker(esporta.Path, declared: true, new FixedMounts()), desktop: false))
{
var root = (await server.GetJsonAsync("/api/export")).GetProperty("root");
Assert.IsTrue(root.Bool("docker"));
Assert.IsFalse(root.Bool("active"));
Assert.AreNotEqual(ExportRoots.NotDeclaredText, root.Str("problem"));
Assert.IsNotEmpty(root.Str("problem"));
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination("usb"))).Status);
}
// Declared and mounted: on.
await using (var server = await StartAsync(Mounted(esporta), desktop: false))
{
var root = (await server.GetJsonAsync("/api/export")).GetProperty("root");
Assert.IsTrue(root.Bool("active"), root.ToString());
Assert.AreEqual(JsonValueKind.Null, root.GetProperty("problem").ValueKind);
}
// Windows: any folder, through the picker of the system.
await using (var server = await StartAsync())
{
var root = (await server.GetJsonAsync("/api/export")).GetProperty("root");
Assert.IsFalse(root.Bool("docker"));
Assert.IsTrue(root.Bool("active"));
Assert.AreEqual(JsonValueKind.Null, root.GetProperty("root").ValueKind);
}
}
[TestMethod]
public async Task FoldersAreListedUnderTheExportRootAndDotDotIsRefused()
{
using var esporta = new TempFolder("esporta");
Directory.CreateDirectory(esporta.Combine("usb", "foto"));
Directory.CreateDirectory(esporta.Combine("nas"));
// Hidden as the import picker hides it: a dot folder on Linux, the attribute on Windows.
var hidden = Directory.CreateDirectory(esporta.Combine(".nascosta"));
hidden.Attributes |= FileAttributes.Hidden;
await using var server = await StartAsync(Mounted(esporta), desktop: false);
var list = await server.GetJsonAsync("/api/export/folders");
CollectionAssert.AreEquivalent(new[] { "nas", "usb" }, list.Items("folders").Select(f => f.Str("name")).ToArray(), "no hidden folders");
Assert.AreEqual(string.Empty, list.Str("relative"));
Assert.AreEqual(JsonValueKind.Null, list.GetProperty("parent").ValueKind);
var usb = await server.GetJsonAsync("/api/export/folders?path=usb");
Assert.AreEqual("foto", usb.Items("folders").Single().Str("name"));
Assert.AreEqual(string.Empty, usb.Str("parent"));
foreach (var path in new[] { "..", "usb/../..", "../fuori" })
{
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Get, $"/api/export/folders?path={Uri.EscapeDataString(path)}")).Status, path);
}
var check = (await server.SendJsonAsync(HttpMethod.Post, "/api/export/check-folder", new { path = "usb" })).Body;
Assert.IsTrue(check.Bool("accepted"), check.ToString());
Assert.AreEqual(Free, check.Long("freeBytes"));
Assert.IsFalse(check.Bool("fat32"));
foreach (var path in new[] { string.Empty, "..", "../fuori", "usb/../.." })
{
var (status, answer) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/check-folder", new { path });
Assert.IsTrue(status == HttpStatusCode.BadRequest || !answer.Bool("accepted"), $"«{path}»: {answer}");
}
// In Docker there is no picker of the system: the page lists the folders of /esporta.
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/pick-folder", new { })).Status);
Assert.IsFalse(Directory.Exists(esporta.Combine("fuori")), "nothing is ever created");
}
[TestMethod]
public async Task CheckFolderRefusesTheLibraryAndTheDataFolder()
{
await using var server = await StartAsync();
var account = await AddPhotosAsync(server, "marta.demo", 1);
var usb = server.Temp.Combine("usb");
Directory.CreateDirectory(usb);
Directory.CreateDirectory(server.Library.Layout.AccountFolder(account.Account));
var accepted = await CheckAsync(server, usb);
Assert.IsTrue(accepted.Bool("accepted"), accepted.ToString());
Assert.AreEqual(Free, accepted.Long("freeBytes"));
foreach (var refused in new[]
{
server.Library.Layout.Root,
Path.Combine(server.Library.Layout.Root, "dentro"),
server.Library.Data.Root,
server.Library.Layout.AccountFolder(account.Account),
server.Temp.Path,
server.Temp.Combine("non-esiste"),
})
{
if (refused.EndsWith("dentro", StringComparison.Ordinal))
{
Directory.CreateDirectory(refused);
}
var answer = await CheckAsync(server, refused);
Assert.IsFalse(answer.Bool("accepted"), refused);
Assert.IsNotEmpty(answer.Str("problem"), refused);
}
Assert.IsFalse(Directory.Exists(server.Temp.Combine("non-esiste")), "a missing folder is never created");
Assert.IsEmpty(Directory.GetFiles(usb, "*", SearchOption.AllDirectories), "the probe leaves nothing behind");
}
[TestMethod]
public async Task DestinationsAreCreatedUpdatedAndRetired()
{
await using var server = await StartAsync();
var marta = await AddPhotosAsync(server, "marta.demo", 1);
var usb = server.Temp.Combine("usb");
var nas = server.Temp.Combine("nas");
Directory.CreateDirectory(usb);
Directory.CreateDirectory(nas);
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination(usb, types: []))).Status, "at least one type");
var (status, created) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination(usb, label: "Disco USB"));
Assert.AreEqual(HttpStatusCode.OK, status, created.ToString());
var general = created.GetProperty("destination");
Assert.AreEqual("general", general.Str("scope"));
Assert.AreEqual("Disco USB", general.Str("label"));
Assert.HasCount(6, general.Items("types").ToList());
Assert.IsFalse(general.Bool("automatic"));
Assert.AreEqual(general.Long("id"), (await server.GetJsonAsync("/api/export")).GetProperty("general").Long("id"));
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination(nas))).Status, "one general folder");
// The same folder: the same destination, changed in place.
var (sameStatus, same) = await server.SendJsonAsync(HttpMethod.Put, $"/api/export/destinations/{general.Long("id")}", Destination(usb, label: "Chiavetta", types: ["postFoto"]));
Assert.AreEqual(HttpStatusCode.OK, sameStatus, same.ToString());
Assert.AreEqual(general.Long("id"), same.GetProperty("destination").Long("id"));
Assert.AreEqual("Chiavetta", same.GetProperty("destination").Str("label"));
CollectionAssert.AreEqual(new[] { "postFoto" }, same.GetProperty("destination").Items("types").Select(t => t.GetString()).ToArray());
// Another folder: the old destination is retired (it keeps its copies), a new one takes its place.
var (movedStatus, moved) = await server.SendJsonAsync(HttpMethod.Put, $"/api/export/destinations/{general.Long("id")}", Destination(nas));
Assert.AreEqual(HttpStatusCode.OK, movedStatus, moved.ToString());
var next = moved.GetProperty("destination").Long("id");
Assert.AreNotEqual(general.Long("id"), next);
Assert.IsNotNull((await server.Db.Exports.GetDestinationAsync(general.Long("id")))!.RemovedAt);
// An own folder of the account, then retired: the account goes back to the general folder.
var sua = server.Temp.Combine("sua");
Directory.CreateDirectory(sua);
var (ownStatus, own) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination(sua, scope: "account", accountId: marta.Account.Id, types: ["postFoto", "postVideo"]));
Assert.AreEqual(HttpStatusCode.OK, ownStatus, own.ToString());
Assert.AreEqual("marta.demo", own.GetProperty("destination").Str("username"));
var card = (await server.GetJsonAsync($"/api/accounts/{marta.Account.Id}")).GetProperty("export");
Assert.IsTrue(card.Bool("hasOwnFolder"));
Assert.AreEqual(own.GetProperty("destination").Long("id"), card.GetProperty("destination").Long("id"));
var overview = await server.GetJsonAsync("/api/export");
Assert.AreEqual("marta.demo", overview.Items("own").Single().Str("username"));
var (retiredStatus, retired) = await server.SendJsonAsync(HttpMethod.Delete, $"/api/export/destinations/{own.GetProperty("destination").Long("id")}");
Assert.AreEqual(HttpStatusCode.OK, retiredStatus);
Assert.AreEqual(ExportDestinations.RetiredText, retired.Str("message"));
card = (await server.GetJsonAsync($"/api/accounts/{marta.Account.Id}")).GetProperty("export");
Assert.IsFalse(card.Bool("hasOwnFolder"));
Assert.AreEqual(next, card.GetProperty("destination").Long("id"));
Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Delete, $"/api/export/destinations/{next}")).Status);
Assert.AreEqual(JsonValueKind.Null, (await server.GetJsonAsync("/api/export")).GetProperty("general").ValueKind);
Assert.IsTrue(Directory.Exists(usb) && Directory.Exists(nas) && Directory.Exists(sua), "retiring a destination never touches its folder");
}
[TestMethod]
public async Task PlanAndStartCopyTheFilesAndTheProgressFinishes()
{
await using var server = await StartAsync();
var marta = await AddPhotosAsync(server, "marta.demo", 3);
var usb = await GeneralAsync(server);
var plan = (await server.SendJsonAsync(HttpMethod.Post, "/api/export/plan", new { accountId = marta.Account.Id })).Body;
Assert.AreEqual(3, plan.Int("files"), plan.ToString());
Assert.IsGreaterThan(0L, plan.Long("bytes"));
Assert.AreEqual(0, plan.Int("alreadyCopied"));
Assert.AreEqual(usb.Id, plan.Items("destinations").Single().Long("id"));
Assert.IsEmpty(Directory.GetFiles(usb.Root, "*", SearchOption.AllDirectories), "a plan writes nothing");
var (status, job) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/start", new { accountId = marta.Account.Id });
Assert.AreEqual(HttpStatusCode.OK, status, job.ToString());
var run = job.Items("runIds").Single().GetInt64();
await WaitIdleAsync(server);
var progress = await server.GetJsonAsync("/api/export/progress");
Assert.IsFalse(progress.Bool("running"));
Assert.AreEqual(JsonValueKind.Null, progress.GetProperty("error").ValueKind, progress.ToString());
var written = Directory.GetFiles(usb.Root, "*", SearchOption.AllDirectories);
Assert.HasCount(3, written);
Assert.IsTrue(written.All(f => Path.GetRelativePath(usb.Root, f).StartsWith("marta.demo", StringComparison.Ordinal)), "the account segment comes first in the general folder");
CollectionAssert.AreEquivalent(
marta.Files.Select(f => Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(File.ReadAllBytes(f)))).ToArray(),
written.Select(f => Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(File.ReadAllBytes(f)))).ToArray(),
"copies byte for byte");
Assert.IsFalse(written.Any(f => f.EndsWith(".part", StringComparison.Ordinal)));
var runs = (await server.GetJsonAsync("/api/export/runs")).EnumerateArray().ToList();
var done = runs.Single(r => r.Long("id") == run);
Assert.AreEqual("completed", done.Str("state"));
Assert.AreEqual(3, done.Int("done"));
var report = await server.GetJsonAsync($"/api/export/runs/{run}/report");
Assert.AreEqual(3, report.GetProperty("byState").Int("copied"));
Assert.AreEqual("marta.demo", report.Items("accounts").Single().Str("username"));
Assert.IsEmpty(report.Items("problems").ToList());
var again = (await server.SendJsonAsync(HttpMethod.Post, "/api/export/plan", new { accountId = marta.Account.Id })).Body;
Assert.AreEqual(0, again.Int("files"));
Assert.AreEqual(3, again.Int("alreadyCopied"));
var overview = await server.GetJsonAsync("/api/export");
Assert.AreEqual(3, overview.GetProperty("general").GetProperty("counts").Int("copied"));
Assert.AreEqual(0, overview.Int("unfinishedRuns"));
}
[TestMethod]
public async Task CheckCopiesThenCopyAgainWritesTheRemovedFileOnce()
{
await using var server = await StartAsync();
var marta = await AddPhotosAsync(server, "marta.demo", 2);
var usb = await GeneralAsync(server);
await StartAndWaitAsync(server, new { accountId = marta.Account.Id });
// Alberto deletes one copy by hand; «Controlla le copie» finds it «Tolto» and touches no file.
var gone = Directory.GetFiles(usb.Root, "*", SearchOption.AllDirectories).Order(StringComparer.Ordinal).First();
File.Delete(gone);
var kept = Fingerprint.Of(usb.Root);
Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Post, $"/api/export/destinations/{usb.Id}/check")).Status);
var removed = await WaitForAsync(async () =>
{
var copies = await server.Db.Exports.ListCopiesAsync(usb.Id, ExportCopyState.Removed, 0, 10);
return copies.Count == 1 ? copies[0] : null;
});
await WaitIdleAsync(server);
Fingerprint.AreEqual(kept, Fingerprint.Of(usb.Root), "«Controlla le copie» touches no file");
// The plan skips it by itself; the viewer offers «Copia di nuovo».
var plan = (await server.SendJsonAsync(HttpMethod.Post, "/api/export/plan", new { accountId = marta.Account.Id })).Body;
Assert.AreEqual(0, plan.Int("files"));
Assert.AreEqual(1, plan.Int("removedOrSuperseded"));
var entry = marta.Entries.Single(e => e.Media.Any(m => m.Id == removed.MediaId));
var file = (await server.GetJsonAsync($"/api/entries/{entry.Entry.Id}")).Items("media").Single(m => m.Long("id") == removed.MediaId);
var copy = file.Items("copies").Single();
Assert.AreEqual("removed", copy.Str("state"));
Assert.IsTrue(copy.Bool("canCopyAgain"));
Assert.AreEqual(removed.Id, copy.Long("copyId"));
var (status, job) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/copy-again", new { copyId = removed.Id });
Assert.AreEqual(HttpStatusCode.OK, status, job.ToString());
Assert.HasCount(1, job.Items("runIds").ToList());
await WaitIdleAsync(server);
Assert.HasCount(2, Directory.GetFiles(usb.Root, "*", SearchOption.AllDirectories));
Assert.IsTrue(File.Exists(gone), "written again at its place");
Assert.AreEqual(ExportCopyState.Removed, (await server.Db.Exports.GetCopyAsync(removed.Id))!.State, "the old row stays as history");
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/copy-again", new { copyId = removed.Id })).Status, "already copied again");
var notRemoved = (await server.Db.Exports.ListCopiesAsync(usb.Id, ExportCopyState.Copied, 0, 10)).First();
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/copy-again", new { copyId = notRemoved.Id })).Status, "only a removed or superseded copy");
}
[TestMethod]
public async Task TheLibraryFilterTheMarksTheViewerAndTheCardAgree()
{
await using var server = await StartAsync();
var marta = await AddPhotosAsync(server, "marta.demo", 3);
var pair = await AddPostAsync(server, marta.Account, "coppia", 40, 41);
// No destination: no mark, no «Copie» filter offered, and every count is zero.
var days = await server.GetJsonAsync("/api/library/days");
Assert.IsFalse(days.Bool("hasDestinations"));
Assert.IsTrue((await server.GetJsonAsync("/api/library?limit=50")).Items("tiles").All(t => t.GetProperty("copies").ValueKind == JsonValueKind.Null));
var card = (await server.GetJsonAsync($"/api/accounts/{marta.Account.Id}")).GetProperty("export");
Assert.IsTrue(card.Bool("enabled"), "«Esporta questo account» is on when nothing is recorded");
Assert.AreEqual(0, card.Int("due"));
Assert.AreEqual(JsonValueKind.Null, card.GetProperty("destination").ValueKind);
Assert.IsFalse((await server.GetJsonAsync($"/api/entries/{pair.Entry.Id}")).Bool("canCopy"));
// A destination and the copy of the first photos: one post copied, one in part.
var usb = await GeneralAsync(server);
await StartAndWaitAsync(server, new { mediaIds = new[] { marta.Entries[0].Media[0].Id, pair.Media[0].Id } });
Assert.IsTrue((await server.GetJsonAsync("/api/library/days")).Bool("hasDestinations"));
var tiles = (await server.GetJsonAsync("/api/library?limit=50")).Items("tiles").ToDictionary(t => t.Long("id"));
Assert.AreEqual("copied", tiles[marta.Entries[0].Entry.Id].Str("copies"));
Assert.AreEqual("partly", tiles[pair.Entry.Id].Str("copies"));
Assert.AreEqual(1, tiles[pair.Entry.Id].Int("copiesDone"));
Assert.AreEqual(2, tiles[pair.Entry.Id].Int("copiesDue"));
Assert.AreEqual(JsonValueKind.Null, tiles[marta.Entries[1].Entry.Id].GetProperty("copies").ValueKind);
// The filter: grouped («Copiati» only when every due file is copied) and per file.
long[] Ids(JsonElement page) => [.. page.Items("tiles").Select(t => t.Long("id"))];
CollectionAssert.AreEquivalent(new[] { marta.Entries[0].Entry.Id }, Ids(await server.GetJsonAsync("/api/library?copies=copied")));
CollectionAssert.AreEquivalent(
new[] { marta.Entries[1].Entry.Id, marta.Entries[2].Entry.Id, pair.Entry.Id },
Ids(await server.GetJsonAsync("/api/library?copies=notCopied")));
Assert.IsEmpty(Ids(await server.GetJsonAsync("/api/library?copies=removedOrSuperseded")));
Assert.HasCount(2, (await server.GetJsonAsync("/api/library?copies=copied&mode=files")).Items("tiles").ToList());
Assert.AreEqual(3, (await server.GetJsonAsync("/api/library/days?copies=notCopied&mode=files")).Int("files"));
Assert.AreEqual(1, (await server.GetJsonAsync("/api/library/days?copies=copied")).Int("entries"));
foreach (var bad in new[] { "tutti", "copied,notCopied", "1" })
{
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Get, $"/api/library?copies={bad}")).Status, bad);
}
// The viewer: the copy of the file, and «Copia in…».
var entry = await server.GetJsonAsync($"/api/entries/{pair.Entry.Id}");
Assert.IsTrue(entry.Bool("canCopy"));
var media = entry.Items("media").ToDictionary(m => m.Long("id"));
var copy = media[pair.Media[0].Id].Items("copies").Single();
Assert.AreEqual("copied", copy.Str("state"));
Assert.AreEqual("usb", copy.Str("destination"));
Assert.AreEqual("whole", copy.Str("variant"));
Assert.IsFalse(copy.Bool("canCopyAgain"));
Assert.IsFalse(copy.Bool("destinationRetired"));
Assert.IsEmpty(media[pair.Media[1].Id].Items("copies").ToList());
// The card counts what the filter finds; the switch off counts nothing and acts at once.
card = (await server.GetJsonAsync($"/api/accounts/{marta.Account.Id}")).GetProperty("export");
Assert.AreEqual(5, card.Int("due"));
Assert.AreEqual(3, card.Int("notCopied"));
Assert.AreEqual(0, card.Int("removedOrSuperseded"));
Assert.AreEqual(usb.Id, card.GetProperty("destination").Long("id"));
var (offStatus, _) = await server.SendJsonAsync(HttpMethod.Post, $"/api/accounts/{marta.Account.Id}/export-enabled", new { value = false });
Assert.AreEqual(HttpStatusCode.OK, offStatus);
card = (await server.GetJsonAsync($"/api/accounts/{marta.Account.Id}")).GetProperty("export");
Assert.IsFalse(card.Bool("enabled"));
Assert.AreEqual(0, card.Int("due"));
Assert.AreEqual(0, card.Int("notCopied"));
Assert.IsEmpty(Ids(await server.GetJsonAsync("/api/library?copies=notCopied")));
var off = (await server.SendJsonAsync(HttpMethod.Post, "/api/export/plan", new { accountId = marta.Account.Id })).Body;
Assert.AreEqual(0, off.Int("files"));
Assert.IsGreaterThan(0, off.Int("notExported"), "Q1: the switch off skips manual copies too");
Assert.IsTrue((await server.GetJsonAsync($"/api/entries/{pair.Entry.Id}")).Items("media").Any(m => m.Items("copies").Any()), "the copies made stay visible");
Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Post, $"/api/accounts/{marta.Account.Id}/export-enabled", new { value = true })).Status);
Assert.AreEqual(3, (await server.GetJsonAsync($"/api/accounts/{marta.Account.Id}")).GetProperty("export").Int("notCopied"));
}
[TestMethod]
public async Task RebuildIsRefusedDuringAnExportAndTheCopyWaitsForTheEngineSession()
{
var session = new FakeSessionState { InSession = true };
await using var server = await StartAsync(session: session, clock: new WaitingClock(new ManualClock(Make.T0)));
var marta = await AddPhotosAsync(server, "marta.demo", 2);
var usb = await GeneralAsync(server);
var (status, job) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/start", new { accountId = marta.Account.Id });
Assert.AreEqual(HttpStatusCode.OK, status, job.ToString());
var waiting = await WaitForAsync(async () =>
{
var progress = await server.GetJsonAsync("/api/export/progress");
return progress.Str("phase") == "waitingForSession" ? (JsonElement?)progress : null;
});
Assert.IsTrue(waiting.GetValueOrDefault().Bool("running"));
Assert.IsEmpty(Directory.GetFiles(usb.Root, "*", SearchOption.AllDirectories), "no copy during an engine session");
var (rebuild, refusal) = await server.SendJsonAsync(HttpMethod.Post, "/api/settings/rebuild", new { confirm = "ricostruisci" });
Assert.AreEqual(HttpStatusCode.BadRequest, rebuild);
Assert.AreEqual(LongWorkGate.BusyMessage(LongWorkKind.Rebuild, LongWorkKind.Export), refusal.Str("message"));
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/start", new { accountId = marta.Account.Id })).Status, "one copy at a time");
session.InSession = false;
await WaitIdleAsync(server);
Assert.HasCount(2, Directory.GetFiles(usb.Root, "*", SearchOption.AllDirectories));
Assert.IsNull(server.App.Services.GetRequiredService<LongWorkGate>().Busy, "the long work is free again once the copy ended");
}
[TestMethod]
public async Task AnAccountFolderInsideADestinationIsRefused()
{
await using var server = await StartAsync();
var marta = await AddPhotosAsync(server, "marta.demo", 1);
var usb = await GeneralAsync(server);
var detail = await server.GetJsonAsync($"/api/accounts/{marta.Account.Id}");
var form = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(detail.GetProperty("settings").GetRawText())!
.ToDictionary(k => k.Key, k => (object?)k.Value);
form["folder"] = Path.Combine(usb.Root, "marta");
var (status, error) = await server.SendJsonAsync(HttpMethod.Put, $"/api/accounts/{marta.Account.Id}/settings", form);
Assert.AreEqual(HttpStatusCode.BadRequest, status);
StringAssert.Contains(error.Str("message"), "cartella di esportazione");
Assert.IsNull((await server.Db.Accounts.GetAsync(marta.Account.Id))!.Folder, "nothing saved");
form["folder"] = server.Temp.Combine("altrove", "marta");
Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Put, $"/api/accounts/{marta.Account.Id}/settings", form)).Status);
Assert.IsNull((await server.Db.Exports.GetDestinationAsync(usb.Id))!.PausedAt);
}
// ------------------------------------------------------------------------------------------------- support
private const long Free = 500_000_000_000;
private static ExportRootOptions Mounted(TempFolder esporta) =>
ExportRootOptions.Docker(esporta.Path, declared: true, new FixedMounts(new ExportMount(esporta.Path, "/", "ext4", ReadOnly: false)));
/// <summary>A web host of the Windows edition (any folder) or, with a root, the Docker one, with a disk of 500 GB.</summary>
private static Task<WebTestServer> StartAsync(ExportRootOptions? root = null, bool desktop = true, IEngineSessionState? session = null, IClock? clock = null) =>
WebTestServer.StartAsync(
desktop ? new FebeWebOptions { Edition = FebeEdition.Desktop, Access = AccessMode.None } : null,
s =>
{
if (root is not null)
{
s.AddSingleton(root);
}
s.AddSingleton<IExportDisk>(new FakeExportDisk(Free));
if (session is not null)
{
s.AddSingleton(session);
}
if (clock is not null)
{
s.AddSingleton(clock);
}
});
private static object Destination(string path, string scope = "general", long? accountId = null, string? label = null, string[]? types = null) => new
{
scope,
accountId,
path,
label,
types = types ?? ["postFoto", "postVideo", "storie", "evidenza", "taggati", "profilo"],
namingScheme = (string?)null,
highlightNamingScheme = (string?)null,
profileNamingScheme = (string?)null,
};
/// <summary>The general folder «usb» in the temporary folder of the host.</summary>
private static async Task<(long Id, string Root)> GeneralAsync(WebTestServer server)
{
var root = server.Temp.Combine("usb");
Directory.CreateDirectory(root);
var (status, saved) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination(root));
Assert.AreEqual(HttpStatusCode.OK, status, saved.ToString());
return (saved.GetProperty("destination").Long("id"), root);
}
private static async Task<JsonElement> CheckAsync(WebTestServer server, string path)
{
var (status, answer) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/check-folder", new { path });
Assert.AreEqual(HttpStatusCode.OK, status, $"{path}: {answer}");
return answer;
}
/// <summary>An account with <paramref name="count"/> posts of one real photo each, saved as the collection does.</summary>
private static async Task<(Account Account, List<EntryWithMedia> Entries, List<string> Files)> AddPhotosAsync(WebTestServer server, string username, int count)
{
var account = await server.Db.Accounts.AddAsync(Make.Account(username));
var entries = new List<EntryWithMedia>();
for (var i = 0; i < count; i++)
{
entries.Add(await AddPostAsync(server, account, $"{username}-{i}", 10 + i));
}
var files = entries.SelectMany(e => e.Media).Select(m => Path.Combine(server.Library.Layout.AccountFolder(account), LibraryLayout.ToPlatform(m.RelativePath!))).ToList();
Assert.IsTrue(files.All(File.Exists));
return (account, entries, files);
}
private static async Task<EntryWithMedia> AddPostAsync(WebTestServer server, Account account, string code, params int[] scenes)
{
var ingest = new LibraryIngest(server.Db, server.Library.Layout, LibraryNaming.Default, server.Library.Journal, server.Clock, server.Library.Thumbnails, new PerceptualHashIndex());
var added = await server.Db.Entries.AddAsync(
Make.Entry(account.Id, code, Make.T0.AddDays(-scenes[0])),
[.. scenes.Select((_, i) => Make.Photo(i + 1))]);
foreach (var (media, scene) in added.Stored.Media.Zip(scenes))
{
await ingest.SaveMediaAsync(account, added.Stored.Entry, media, new MediaContent { Content = new MemoryStream(TestFile.PhotoBytes(scene, 96, 120)), Extension = ".jpg" });
}
await ingest.AppendJournalAsync(added.Stored.Entry.Id);
return (await server.Db.Entries.GetWithMediaAsync(added.Stored.Entry.Id))!;
}
private static async Task StartAndWaitAsync(WebTestServer server, object request)
{
var (status, job) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/start", request);
Assert.AreEqual(HttpStatusCode.OK, status, job.ToString());
Assert.IsNotEmpty(job.Items("runIds").ToList(), job.ToString());
await WaitIdleAsync(server);
}
private static async Task WaitIdleAsync(WebTestServer server)
{
for (var i = 0; i < 600; i++)
{
if (!(await server.GetJsonAsync("/api/export/progress")).Bool("running"))
{
return;
}
await Task.Delay(50);
}
Assert.Fail("the copy did not end");
}
private static async Task<T> WaitForAsync<T>(Func<Task<T?>> probe)
{
for (var i = 0; i < 600; i++)
{
if (await probe() is { } found)
{
return found;
}
await Task.Delay(50);
}
Assert.Fail("the expected state did not come");
return default!;
}
}
@@ -0,0 +1,279 @@
using Febe.Tests.Support;
using Febe.Tests.Web.Support;
using Febe.Web.Demo;
namespace Febe.Tests.Web;
/// <summary>
/// The copies to external folders in a real browser, on the demo (spec §4.10, §10.3, tappa E2): Impostazioni →
/// Esportazione with the note of Docker, the dialog of a destination (folders of /esporta, the check of the folder, the
/// types, the preview of the names), the block «Copie esterne» of an account whose switch acts at once, «Copia in…» from
/// the selection with its summary and the toast that leads to the Dashboard, the «Copie» filter in the address with the
/// marks of the tiles and the menu of the CSV icon, the rows «Copia» of the viewer with «Copia di nuovo», and the
/// Dashboard tab «Esportazione». Chromium only (CI); the selectors follow the pages of WP3, checked on the demo.
/// </summary>
[TestClass]
public sealed class ExportInterfaceTests
{
/// <summary>The demo copies its general folder to «Disco USB», under /esporta in the Docker look.</summary>
private const string General = "document.querySelector('.cartella-impostazioni .val')?.textContent || ''";
/// <summary>The «Copie» button of the tools row (the one whose label is a value of the filter).</summary>
private const string CopiesButton = "[...document.querySelectorAll('.strumenti .campo.scelta')].find((b) => /^(Copie|Copiati|Non ancora copiati|Tolti o superati)$/.test(b.textContent.trim()))";
/// <summary>Clicks the button (or menu item) of a scope whose text contains a given text.</summary>
private static string ClickText(string scope, string selector, string text) =>
$"(() => {{ const b = [...document.querySelectorAll({Js(scope + " " + selector)})].find((x) => x.textContent.includes({Js(text)})); if (!b) return false; b.click(); return true; }})()";
/// <summary>The last open menu.</summary>
private const string LastMenu = "[...document.querySelectorAll('.menu[role=menu]')].pop()";
private static string Js(string text) => System.Text.Json.JsonSerializer.Serialize(text);
[TestMethod]
public async Task TheExportSettingsPageShowsTheGeneralFolderAndTheDockerNote()
{
await using var ui = await UiBrowser.StartAsync(1440, 900);
using var temp = new TempFolder("esporta-impostazioni-ui");
await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path));
// Docker: the folders are under /esporta, and the page says so.
await ui.OpenAsync(new Uri(demo.Address, "/impostazioni/esportazione?veste=docker"));
await ui.WaitAsync($"({General}) !== ''", "la cartella generale " + ui.Report());
Assert.AreEqual("/esporta/Disco USB", (await ui.EvalAsync(General)).GetString());
var notes = (await ui.EvalAsync("[...document.querySelectorAll('.avviso')].map((a) => a.textContent).join(' | ')")).GetString()!;
StringAssert.Contains(notes, "sottocartelle di /esporta", "la nota di Docker");
StringAssert.Contains(notes, "da riprendere", "il lavoro interrotto della demo");
CollectionAssert.AreEqual(
new[] { "Esportazione", "Cartella generale", "Lo stesso post in due account", "Cartelle degli account" },
(await ui.EvalAsync<string[]>("[...document.querySelectorAll('.sezione h2')].map((x) => x.textContent)")));
StringAssert.Contains((await ui.EvalAsync("document.querySelector('.stato-copie')?.textContent || ''")).GetString(), "copiati", "i conteggi della cartella");
Assert.IsTrue((await ui.EvalAsync("[...document.querySelectorAll('.stato-copie button')].some((b) => b.textContent.includes('Controlla le copie'))")).GetBoolean(), "«Controlla le copie»");
StringAssert.Contains((await ui.EvalAsync("[...document.querySelectorAll('table tbody tr')].map((r) => r.textContent).join(' | ')")).GetString(), "@studio.lumen.demo", "la cartella sua di un account");
// Windows: the path of the folder, no note of Docker.
await ui.OpenAsync(new Uri(demo.Address, "/impostazioni/esportazione?veste=desktop"));
await ui.WaitAsync($"({General}).endsWith('Disco USB') && !({General}).startsWith('/esporta')", "la cartella generale in Windows");
Assert.IsFalse((await ui.EvalAsync("[...document.querySelectorAll('.avviso')].some((a) => a.textContent.includes('sottocartelle di'))")).GetBoolean(), "nessuna nota di Docker");
}
[TestMethod]
public async Task TheDestinationDialogChecksTheFolderAndPreviewsNames()
{
await using var ui = await UiBrowser.StartAsync(1440, 900);
using var temp = new TempFolder("esporta-dialogo-ui");
await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path));
await ui.OpenAsync(new Uri(demo.Address, "/impostazioni/esportazione?veste=docker"));
await ui.WaitAsync($"({General}) !== ''", "la cartella generale");
Assert.IsTrue((await ui.EvalAsync(ClickText(".cartella-impostazioni", "button", "Modifica"))).GetBoolean());
const string Dialog = "document.querySelector('.dialogo.destinazione')";
await ui.WaitAsync($"{Dialog}?.querySelector('.sfoglia-voce') && /liberi/.test({Dialog}.querySelector('.controllo-cartella').textContent)", "il dialogo con le cartelle di /esporta e il controllo");
CollectionAssert.IsSubsetOf(
new[] { "Chiavetta", "Disco USB", "Studio Lumen" },
await ui.EvalAsync<string[]>($"[...{Dialog}.querySelectorAll('.sfoglia-voce')].map((b) => b.textContent.trim())"));
Assert.AreEqual("Disco USB", (await ui.EvalAsync($"{Dialog}.querySelector('.sfoglia-voce[aria-pressed=true]').textContent.trim()")).GetString(), "la cartella di adesso è scelta");
// Another folder: the check follows it.
await ui.EvalAsync($"[...{Dialog}.querySelectorAll('.sfoglia-voce')].find((b) => b.textContent.trim() === 'Chiavetta').click()");
await ui.WaitAsync($"{Dialog}.querySelector('.controllo-cartella').textContent.includes('/esporta/Chiavetta')", "il controllo della cartella scelta");
// «Uno schema suo»: the three schemes of the library to start from, and the tree follows what is typed.
await ui.EvalAsync($"{Dialog}.querySelector('input[value=suo]').click()");
await ui.WaitAsync($"!{Dialog}.querySelector('.schemi-copie').hidden", "gli schemi");
Assert.IsTrue((await ui.EvalAsync($"[...{Dialog}.querySelectorAll('.schemi-copie input')].every((i) => i.value.includes('{{account}}'))")).GetBoolean(), "gli schemi partono da quelli della libreria");
var before = (await ui.EvalAsync($"{Dialog}.querySelector('.albero').textContent")).GetString();
await ui.EvalAsync($"(() => {{ const i = {Dialog}.querySelector('#schema-copie'); i.value = '{{account}}/{{anno}}/{{codice}}_{{n}}'; i.dispatchEvent(new Event('input', {{ bubbles: true }})); }})()");
await ui.WaitAsync($"{Dialog}.querySelector('.albero').textContent !== {Js(before!)} && {Dialog}.querySelector('.albero').textContent.startsWith('Chiavetta')", "l'anteprima dei nomi nella cartella scelta");
StringAssert.Contains((await ui.EvalAsync($"{Dialog}.querySelector('.albero').textContent")).GetString(), "marta.demo / 2026");
// No type: nothing to save.
await ui.EvalAsync($"{Dialog}.querySelectorAll('.tipi input:checked').forEach((i) => i.click())");
await ui.WaitAsync($"!{Dialog}.querySelector('.errore-testo').hidden", "«Scegli almeno un tipo.»");
Assert.IsTrue((await ui.EvalAsync($"[...{Dialog}.querySelectorAll('footer button')].find((b) => b.textContent.includes('Salva')).disabled")).GetBoolean());
// «Annulla» keeps the folder of before.
await ui.EvalAsync($"[...{Dialog}.querySelectorAll('footer button')].find((b) => b.textContent === 'Annulla').click()");
await ui.WaitAsync($"{Dialog} === null", "il dialogo si chiude");
Assert.AreEqual("/esporta/Disco USB", (await ui.EvalAsync(General)).GetString());
}
[TestMethod]
public async Task TheAccountBlockSwitchActsAtOnce()
{
await using var ui = await UiBrowser.StartAsync(1440, 900);
using var temp = new TempFolder("esporta-account-ui");
await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path));
await ui.OpenAsync(new Uri(demo.Address, "/account"));
await ui.WaitAsync("document.querySelector('a[href^=\"/account/\"]') !== null", "elenco degli account");
var id = (await ui.EvalAsync("fetch('/api/accounts').then((r) => r.json()).then((j) => j.accounts.find((a) => a.username === 'marta.demo').id)")).GetInt64();
await ui.OpenAsync(new Uri(demo.Address, $"/account/{id}/impostazioni"));
const string Block = "document.querySelector('.copie-esterne')";
await ui.WaitAsync($"{Block}?.querySelector('.conteggio-copie') != null", "il blocco «Copie esterne»");
Assert.IsTrue((await ui.EvalAsync($"{Block}.querySelector('input[role=switch]').checked")).GetBoolean(), "«Esporta questo account» acceso");
StringAssert.Contains((await ui.EvalAsync($"{Block}.textContent")).GetString(), "Nella cartella generale");
StringAssert.Contains((await ui.EvalAsync($"{Block}.querySelector('.conteggio-copie').textContent")).GetString(), "non ancora copiati");
// Off: at once, without «Salva», the server knows it and the block says what it means.
await ui.EvalAsync($"{Block}.querySelector('input[role=switch]').click()");
await ui.WaitAsync($"{Block}.textContent.includes('Questo account non si esporta')", "il blocco spento");
await ui.WaitAsync($"fetch('/api/accounts/{id}').then((r) => r.json()).then((j) => j.export.enabled === false)", "spento sul server");
await ui.WaitAsync("[...document.querySelectorAll('.brevi .breve')].some((b) => b.textContent.includes('non si copia più'))", "l'avviso breve");
Assert.IsFalse((await ui.EvalAsync($"[...{Block}.querySelectorAll('button')].some((b) => b.textContent.includes('Copia in'))")).GetBoolean(), "niente «Copia in…» da spento");
// On again.
await ui.EvalAsync($"{Block}.querySelector('input[role=switch]').click()");
await ui.WaitAsync($"{Block}.querySelector('.conteggio-copie')?.textContent.includes('non ancora copiati') && {Block}.querySelector('input[role=switch]').checked", "di nuovo acceso");
await ui.WaitAsync($"fetch('/api/accounts/{id}').then((r) => r.json()).then((j) => j.export.enabled === true)", "acceso sul server");
}
[TestMethod]
public async Task CopyInFromTheSelectionShowsTheSummaryAndStarts()
{
await using var ui = await UiBrowser.StartAsync(1440, 900);
using var temp = new TempFolder("esporta-selezione-ui");
await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path));
// The three newest entries of the demo have four files still to copy.
await ui.OpenAsync(new Uri(demo.Address, "/libreria"));
await ui.WaitAsync("document.querySelectorAll('.mosaico .tess').length >= 3", "il mosaico");
Assert.IsTrue((await ui.EvalAsync(ClickText(".strumenti", ".btn", "Seleziona"))).GetBoolean());
await ui.EvalAsync("[...document.querySelectorAll('.mosaico .tess')].slice(0, 3).forEach((t) => t.click())");
const string CopyIn = "[...document.querySelectorAll('.salva button')].find((b) => b.textContent.includes('Copia in'))";
await ui.WaitAsync($"({CopyIn}) && !({CopyIn}).disabled", "«Copia in…» nella barra della scelta");
await ui.EvalAsync($"({CopyIn}).click()");
const string Dialog = "document.querySelector('.dialogo.copia-in')";
await ui.WaitAsync($"{Dialog}?.querySelector('.riepilogo-copia') != null", "il riepilogo");
var summary = (await ui.EvalAsync($"{Dialog}.querySelector('.riepilogo-copia').textContent")).GetString()!;
StringAssert.StartsWith(summary, "4 file", summary);
StringAssert.Contains(summary, "circa", "lo spazio");
StringAssert.Contains((await ui.EvalAsync($"{Dialog}.querySelector('.destinazioni-copia').textContent")).GetString(), "In Disco USB");
Assert.AreEqual("Copia 4 file", (await ui.EvalAsync($"{Dialog}.querySelector('footer .btn.primo').textContent.trim()")).GetString());
await ui.EvalAsync($"{Dialog}.querySelector('footer .btn.primo').click()");
await ui.WaitAsync($"{Dialog} === null", "il dialogo si chiude");
await ui.WaitAsync("document.querySelector('.brevi .breve a.breve-link') !== null", "l'avviso breve con il collegamento");
Assert.AreEqual("/dashboard/esportazione", (await ui.EvalAsync("new URL(document.querySelector('.brevi .breve a.breve-link').href).pathname")).GetString());
// The job is in the Dashboard tab, finished: the demo copies at once.
await ui.EvalAsync("document.querySelector('.brevi .breve a.breve-link').click()");
await ui.WaitAsync("location.pathname === '/dashboard/esportazione' && document.querySelector('.esportazione-dashboard .elenco-attivita li') !== null", "la linguetta «Esportazione»");
await ui.WaitAsync("document.querySelector('.esportazione-dashboard .elenco-attivita li').textContent.includes('4 di 4 file')", "il lavoro di 4 file " + ui.Report());
}
[TestMethod]
public async Task TheCopiesFilterIsRememberedInTheAddressAndTheTilesShowTheCopiedMark()
{
await using var ui = await UiBrowser.StartAsync(1440, 900);
using var temp = new TempFolder("esporta-filtro-ui");
await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path));
// «Copiati» from the address: the button says it, every tile has the mark.
await ui.OpenAsync(new Uri(demo.Address, "/libreria?copie=copiati"));
await ui.WaitAsync($"({CopiesButton}) && document.querySelectorAll('.mosaico .tess').length > 0", "la Libreria con «Copiati»");
Assert.AreEqual("Copiati", (await ui.EvalAsync($"({CopiesButton}).textContent.trim()")).GetString());
Assert.IsTrue((await ui.EvalAsync($"({CopiesButton}).classList.contains('attivo')")).GetBoolean());
Assert.IsTrue((await ui.EvalAsync("[...document.querySelectorAll('.mosaico .tess')].every((t) => t.querySelector('.segno span.copia:not(.parte)') !== null)")).GetBoolean(), "il segno «copiato» su ogni tessera " + ui.Report());
Assert.AreEqual("copia", (await ui.EvalAsync("document.querySelector('.mosaico .tess .segno').lastElementChild.className")).GetString(), "il segno sta per ultimo");
// The menu of the filter: «Tolti o superati» goes to the address and stays after a reload.
await ui.EvalAsync($"({CopiesButton}).click()");
await ui.WaitAsync($"({LastMenu})?.querySelectorAll('[role=menuitemradio]').length === 4", "il menu delle copie");
CollectionAssert.AreEqual(
new[] { "Tutti", "Non ancora copiati", "Copiati", "Tolti o superati" },
await ui.EvalAsync<string[]>($"[...({LastMenu}).querySelectorAll('[role=menuitemradio]')].map((b) => b.textContent.trim())"));
await ui.EvalAsync($"[...({LastMenu}).querySelectorAll('[role=menuitemradio]')].find((b) => b.textContent.trim() === 'Tolti o superati').click()");
await ui.WaitAsync("new URLSearchParams(location.search).get('copie') === 'tolti'", "«copie=tolti» nell'indirizzo");
await ui.OpenAsync(new Uri(demo.Address, "/libreria?copie=tolti"));
await ui.WaitAsync($"({CopiesButton})?.textContent.trim() === 'Tolti o superati'", "il filtro dopo il ricaricamento");
await ui.WaitAsync("document.querySelectorAll('.mosaico .tess').length > 0", "le tessere dei tolti o superati");
// The CSV icon is a menu: the list, and «Copia i file in…» of what the filter shows.
await ui.EvalAsync("document.querySelector('.strumenti button[aria-label=Esporta]').click()");
await ui.WaitAsync($"({LastMenu})?.querySelectorAll('[role=menuitem]').length === 2", "il menu dell'icona CSV");
CollectionAssert.AreEqual(
new[] { "Esporta l'elenco (CSV)", "Copia i file in…" },
await ui.EvalAsync<string[]>($"[...({LastMenu}).querySelectorAll('[role=menuitem]')].map((b) => b.textContent.trim())"));
await ui.EvalAsync($"[...({LastMenu}).querySelectorAll('[role=menuitem]')].find((b) => b.textContent.includes('Copia i file')).click()");
await ui.WaitAsync("document.querySelector('.dialogo.copia-in .di-nuovo input') != null", "«Copia in…» del filtro, con «Copia di nuovo anche…»");
Assert.IsFalse((await ui.EvalAsync("document.querySelector('.dialogo.copia-in .di-nuovo input').checked")).GetBoolean(), "«Copia di nuovo» spento");
StringAssert.Contains((await ui.EvalAsync("document.querySelector('.dialogo.copia-in .di-nuovo').textContent")).GetString(), "Copia di nuovo anche i");
await ui.EvalAsync("[...document.querySelectorAll('.dialogo.copia-in footer button')].find((b) => b.textContent === 'Annulla').click()");
await ui.WaitAsync("document.querySelector('.dialogo.copia-in') === null", "il dialogo si chiude");
// «Tutti» takes the filter out of the address.
await ui.EvalAsync($"({CopiesButton}).click()");
await ui.WaitAsync($"({LastMenu})?.querySelectorAll('[role=menuitemradio]').length === 4", "il menu delle copie");
await ui.EvalAsync($"[...({LastMenu}).querySelectorAll('[role=menuitemradio]')].find((b) => b.textContent.trim() === 'Tutti').click()");
await ui.WaitAsync("!new URLSearchParams(location.search).has('copie')", "nessun filtro nell'indirizzo");
Assert.AreEqual("Copie", (await ui.EvalAsync($"({CopiesButton}).textContent.trim()")).GetString());
}
[TestMethod]
public async Task TheViewerShowsCopyRowsWithCopyAgain()
{
await using var ui = await UiBrowser.StartAsync(1440, 900);
using var temp = new TempFolder("esporta-visualizzatore-ui");
await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path));
// «Tutte le foto» with «Tolti o superati»: every tile is a file whose copy was removed or superseded.
await ui.OpenAsync(new Uri(demo.Address, "/libreria?copie=tolti"));
await ui.WaitAsync("document.querySelector('.strumenti .modo-mosaico [data-value=files]') !== null && document.querySelector('.mosaico .tess') !== null", "la Libreria con «Tolti o superati»");
await ui.EvalAsync("document.querySelector('.strumenti .modo-mosaico [data-value=files]').click()");
await ui.WaitAsync("document.querySelector('.strumenti .modo-mosaico [aria-checked=true]').dataset.value === 'files' && document.querySelector('.mosaico .tess') !== null", "«Tutte le foto»");
await ui.EvalAsync("document.querySelector('.mosaico .tess').click()");
await ui.WaitAsync("document.querySelector('.vis .riga-copia') !== null", "le righe «Copia» del visualizzatore " + ui.Report());
var row = (await ui.EvalAsync("document.querySelector('.vis .riga-copia').textContent")).GetString()!;
Assert.IsTrue(row.StartsWith("Tolto da Disco USB", StringComparison.Ordinal) || row.StartsWith("Superato in Disco USB", StringComparison.Ordinal), row);
Assert.AreEqual("Copia", (await ui.EvalAsync("document.querySelector('.vis .riga-copia').previousElementSibling.textContent")).GetString());
Assert.IsTrue((await ui.EvalAsync("[...document.querySelectorAll('.vis button')].some((b) => b.textContent.trim() === 'Copia in…')")).GetBoolean(), "«Copia in…» in fondo al pannello");
// «Copia di nuovo»: the job starts, with its toast, and the file is copied again (no longer «tolto o superato»).
const string Replaced = "fetch('/api/library?mode=files&copies=removedOrSuperseded&limit=1000').then((r) => r.json()).then((j) => j.tiles.length)";
var before = (await ui.EvalAsync(Replaced)).GetInt32();
Assert.IsGreaterThan(0, before);
await ui.EvalAsync("document.querySelector('.vis .riga-copia .copia-di-nuovo').click()");
await ui.WaitAsync("document.querySelector('.brevi .breve a.breve-link') !== null", "l'avviso breve del lavoro");
StringAssert.Contains((await ui.EvalAsync("document.querySelector('.brevi .breve').textContent")).GetString(), "Copia avviata");
await ui.WaitAsync($"({Replaced}).then((n) => n < {before})", "il file copiato di nuovo");
await ui.EvalAsync("document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }))");
await ui.WaitAsync("document.querySelector('.vis') === null", "Esc chiude");
}
[TestMethod]
public async Task TheDashboardExportTabShowsProgressAndResume()
{
await using var ui = await UiBrowser.StartAsync(1440, 900);
using var temp = new TempFolder("esporta-dashboard-ui");
await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path));
// The engine tab says there is a copy to resume and leads to the export tab.
await ui.OpenAsync(new Uri(demo.Address, "/dashboard"));
const string Notice = "[...document.querySelectorAll('.avviso')].find((a) => a.textContent.includes('da riprendere'))";
await ui.WaitAsync($"({Notice}) !== undefined", "l'avviso della copia da riprendere");
CollectionAssert.AreEqual(new[] { "Motore", "Esportazione" }, await ui.EvalAsync<string[]>("[...document.querySelectorAll('.linguette-dashboard a')].map((a) => a.textContent)"));
await ui.EvalAsync($"({Notice}).querySelector('a').click()");
await ui.WaitAsync("location.pathname === '/dashboard/esportazione' && document.querySelector('.esportazione-dashboard .riga-riprendi') !== null", "la linguetta «Esportazione»");
Assert.AreEqual("Esportazione", (await ui.EvalAsync("document.querySelector('.linguette-dashboard a.qui').textContent")).GetString());
CollectionAssert.AreEqual(new[] { "In corso", "Da riprendere", "Ultimi lavori" }, await ui.EvalAsync<string[]>("[...document.querySelectorAll('.esportazione-dashboard h2')].map((x) => x.textContent)"));
StringAssert.Contains((await ui.EvalAsync("document.querySelector('.copia-in-corso').textContent")).GetString(), "Nessuna copia al lavoro");
StringAssert.Contains((await ui.EvalAsync("document.querySelector('.riga-riprendi').textContent")).GetString(), "interrotta");
// «Resoconto» of the last job.
await ui.EvalAsync("[...document.querySelectorAll('.esportazione-dashboard .elenco-attivita li')][0].querySelector('button').click()");
await ui.WaitAsync("document.querySelector('.dialogo.resoconto-copia') !== null", "il resoconto");
StringAssert.StartsWith((await ui.EvalAsync("document.querySelector('.dialogo.resoconto-copia h2').textContent")).GetString(), "Resoconto");
StringAssert.Contains((await ui.EvalAsync("document.querySelector('.dialogo.resoconto-copia').textContent")).GetString(), "Per account");
await ui.EvalAsync("document.querySelector('.dialogo.resoconto-copia header button').click()");
await ui.WaitAsync("document.querySelector('.dialogo.resoconto-copia') === null", "il resoconto si chiude");
// «Riprendi»: the job goes on (the demo copies at once) and leaves «Da riprendere».
Assert.IsTrue((await ui.EvalAsync(ClickText(".riga-riprendi", "button", "Riprendi"))).GetBoolean());
await ui.WaitAsync("[...document.querySelectorAll('.brevi .breve')].some((b) => b.textContent.includes('ripresa'))", "«Copia ripresa»");
await ui.WaitAsync("document.querySelector('.esportazione-dashboard .riga-riprendi') === null", "niente più da riprendere " + ui.Report());
}
}