Files
Febe/tests/Febe.Tests/Export/ExportStatesTests.cs
T
Alby96andClaude Opus 5.5 736d241a38 E2: prove del motore, dell'archivio e del servizio delle copie
Le prove della tappa E2 (WP5a) coprono il montaggio di /esporta, la
radice, il controllo delle cartelle, le destinazioni, i percorsi, la
copia, gli stati «Tolto» e «Superato», lo stesso post in due account,
il lavoro in sottofondo (interrompi, riprendi, annulla, riavvio, porta
condivisa con importazione e ricostruzione, sessione del motore,
interruttore dell'account, Docker senza montaggio) e il filtro «Copie».
Si appoggiano a un banco comune con falsi per disco, sessione, montaggi
e file system, senza permessi dei file, così girano anche da root.

Le prove hanno trovato due difetti, corretti:
- MarkCopiesRemovedAsync riusava il comando in cache del primo blocco
  di 900 id: «Controlla le copie» falliva con più di 900 file mancanti
  in una pagina.
- ReplacedStatesSql senza statistiche leggeva tutte le copie tolte o
  superate della destinazione: «+state» la tiene sul suo indice.

Il controllo delle cartelle accetta una scrittura di prova sostituibile,
per provare il guasto della sonda senza permessi.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 13:28:20 +01:00

289 lines
18 KiB
C#

using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Import;
using Febe.Core.Library;
using Febe.Tests.Export.Support;
using Febe.Tests.Import.Support;
using Febe.Tests.Support;
namespace Febe.Tests.Export;
/// <summary>
/// «Tolto» and «Superato» (spec §4.10 l.304, §14.1; decision D9 of tappa E2): a copy whose file went from the
/// destination, or whose library file changed, is never copied again by itself, only with «Copia di nuovo», and the old
/// files always stay where they are.
/// </summary>
[TestClass]
public sealed class ExportStatesTests
{
public TestContext TestContext { get; set; } = null!;
[TestMethod]
public async Task RemovedIsRecopiedOnlyWithCopyAgain()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var post = await bed.PostAsync(bed.Marta, "970", 41);
var usb = await bed.GeneralAsync(ct: ct);
var first = await bed.CopyAccountAsync(bed.Marta, ct: ct);
var oldCopy = (await bed.ItemsAsync(first.Runs.Single().Id, ct)).Single().CopyId!.Value;
File.Delete(bed.GeneralCopy(bed.Marta, post.Media[0]));
// The next «Copia in…» finds it gone: «Tolto», skipped, not written.
var skipped = await bed.CopyAccountAsync(bed.Marta, ct: ct);
Assert.AreEqual(ExportItemState.Skipped, (await bed.ItemsAsync(skipped.Runs.Single().Id, ct)).Single().State);
Assert.AreEqual(ExportCopyState.Removed, (await bed.Db.Exports.GetCopyAsync(oldCopy, ct))!.State);
Assert.IsEmpty(Fingerprint.Of(bed.Usb));
Assert.AreEqual(new Core.Storage.ExportAccountCounts(1, 0, 1, 0), await bed.Db.Exports.CountAccountFilesAsync(bed.Marta.Id, ct));
var plan = await bed.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct);
Assert.AreEqual((0, 1), (plan.Files, plan.RemovedOrSuperseded));
await bed.CopyAccountAsync(bed.Marta, ct: ct);
Assert.IsEmpty(Fingerprint.Of(bed.Usb), "a second «Copia in…» still writes nothing");
// «Copia di nuovo»: a new row, the old one stays «Tolto» in the history.
var again = await bed.CopyAccountAsync(bed.Marta, copyAgain: true, ct: ct);
Assert.AreEqual((1, 1), (again.Plan.Files, again.Plan.RemovedOrSuperseded));
var newCopy = (await bed.ItemsAsync(again.Runs.Single().Id, ct)).Single().CopyId!.Value;
Assert.AreNotEqual(oldCopy, newCopy);
Assert.AreEqual(ExportCopyState.Removed, (await bed.Db.Exports.GetCopyAsync(oldCopy, ct))!.State);
Assert.AreEqual(ExportCopyState.Copied, (await bed.Db.Exports.GetCopyAsync(newCopy, ct))!.State);
Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Marta, post.Media[0])));
Assert.HasCount(2, await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct));
Assert.AreEqual(new Core.Storage.ExportAccountCounts(1, 0, 0, 0), await bed.Db.Exports.CountAccountFilesAsync(bed.Marta.Id, ct));
}
[TestMethod]
public async Task ReplacingTheLibraryFileSupersedesTheCopy()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder("importa");
await using var bed = await ImportTestBed.CreateAsync(temp);
var (marta, library) = await bed.AccountWithPhotoAsync("marta.demo", "60", ImportTestFiles.Resized(60, 800, 600, 400, 300, 70));
var usb = temp.Combine("usb");
Directory.CreateDirectory(usb);
await using var export = new ExportService(Environment(bed.Library));
await export.Destinations.CreateAsync(new DestinationSpec(ExportScope.General, null, usb, null, ContentTypes.All, null, null, null), ct);
await export.StartAsync(new ExportJobRequest(new ExportSelection.Account(marta.Id)), ct);
await export.WaitAsync(ct);
var copy = (await bed.Library.Db.Exports.ListCopiesBySha256Async(library.Media[0].Sha256!, ct)).Single();
var files = Fingerprint.Of(usb);
// An import brings the original, larger: «Tieni il più grande» replaces the library file.
var largest = ImportTestFiles.Photo(60, 800, 600, 92);
bed.Write("marta.demo/originale.jpg", largest);
var run = await bed.AnalyzeAsync();
var pair = (await bed.Review.ListDuplicatesAsync(run.Id, ct: ct)).Single();
await bed.Review.DecideAsync(run.Id, pair.Pair.Id, DuplicateDecision.KeepLarger, ct: ct);
await bed.Copier.CopyAsync(run.Id, ct: ct);
var media = (await bed.Library.Db.Media.GetAsync(library.Media[0].Id, ct))!;
Assert.AreNotEqual(copy.SourceSha256, media.Sha256);
var superseded = (await bed.Library.Db.Exports.GetCopyAsync(copy.Id, ct))!;
Assert.AreEqual((ExportCopyState.Superseded, media.Sha256), (superseded.State, superseded.SupersededBySha256));
Fingerprint.AreEqual(files, Fingerprint.Of(usb), "the old copy stays, untouched");
// Never copied again by itself; «Copia di nuovo» writes the new file beside the old one.
var plan = await export.PlanAsync(new ExportJobRequest(new ExportSelection.Account(marta.Id)), ct);
Assert.AreEqual((0, 1), (plan.Files, plan.RemovedOrSuperseded));
await export.StartAsync(new ExportJobRequest(new ExportSelection.Account(marta.Id), CopyAgain: true), ct);
await export.WaitAsync(ct);
var after = Fingerprint.Of(usb);
Assert.HasCount(2, after);
foreach (var (path, print) in files)
{
Assert.AreEqual(print, after[path], path);
}
Assert.AreEqual(ExportCopyState.Superseded, (await bed.Library.Db.Exports.GetCopyAsync(copy.Id, ct))!.State);
}
[TestMethod]
public async Task KeepLargerAfterADownloadSupersedes()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var small = await bed.Library.SaveAsync(bed.Marta, Make.Entry(bed.Marta.Id, "971", Make.T0.AddDays(-3)), [TestFile.Photo(1, 42, 360, 450)]);
var usb = await bed.GeneralAsync(ct: ct);
await bed.CopyAccountAsync(bed.Marta, ct: ct);
var copy = (await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)).Single();
var files = Fingerprint.Of(bed.Usb);
// The same picture comes again, larger, in another post: «Tieni il più grande».
var large = await bed.Library.SaveAsync(bed.Marta, Make.Entry(bed.Marta.Id, "972", Make.T0), [TestFile.Photo(1, 42, 720, 900)]);
var lib = bed.Library;
var review = new DownloadDuplicateReview(lib.Db, lib.Layout, lib.Journal, lib.Clock, lib.Thumbnails, lib.Index);
var pair = (await review.ListAsync(ct: ct)).Single(c => c.Candidate.MediaId == large.Media[0].Id);
Assert.AreEqual(small.Media[0].Id, pair.Existing.MediaId);
Assert.AreEqual(1, (await review.DecideAsync(pair.Pair.Id, DuplicateDecision.KeepLarger, ct: ct)).FilesRemoved);
var superseded = (await bed.Db.Exports.GetCopyAsync(copy.Id, ct))!;
Assert.AreEqual((ExportCopyState.Superseded, large.Media[0].Sha256), (superseded.State, superseded.SupersededBySha256));
Fingerprint.AreEqual(files, Fingerprint.Of(bed.Usb), "the copy of the smaller file stays");
var plan = await bed.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct);
Assert.AreEqual((0, 1), (plan.Files, plan.RemovedOrSuperseded)); // the larger file is «tolto o superato», never copied by itself
}
[TestMethod]
public async Task ARefilledSlotAfterRebuildSupersedes()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var post = await bed.PostAsync(bed.Marta, "973", 43);
await bed.GeneralAsync(ct: ct);
await bed.CopyAccountAsync(bed.Marta, ct: ct);
var oldSha = post.Media[0].Sha256!;
// After a rebuild the file is to download again, the journal's SHA-256 kept; the download brings other bytes.
File.Delete(bed.LibraryFile(bed.Marta, post.Media[0]));
await bed.Db.Media.UpdateAsync(post.Media[0] with { State = MediaState.ToDownload, RelativePath = null }, ct);
var media = (await bed.Db.Media.GetAsync(post.Media[0].Id, ct))!;
Assert.AreEqual(oldSha, media.Sha256);
var other = ExportTestBed.Photo(1, 44);
var saved = await bed.Library.Ingest.SaveMediaAsync(bed.Marta, post.Entry, media, new MediaContent { Content = new MemoryStream(other.Bytes), Extension = ".jpg" }, ct: ct);
Assert.AreEqual(MediaSaveOutcome.Stored, saved.Outcome);
var copy = (await bed.Db.Exports.ListCopiesBySha256Async(oldSha, ct)).Single();
Assert.AreEqual((ExportCopyState.Superseded, saved.File!.Sha256), (copy.State, copy.SupersededBySha256));
Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Marta, post.Media[0])), "the old copy stays");
}
[TestMethod]
public async Task SupersededIsNotRecopiedByItselfButCopyAgainWritesANewFile()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var post = await bed.PostAsync(bed.Marta, "974", 45);
var usb = await bed.GeneralAsync(ct: ct);
await bed.CopyAccountAsync(bed.Marta, ct: ct);
var copy = (await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)).Single();
var oldFile = bed.GeneralCopy(bed.Marta, post.Media[0]);
var oldBytes = await File.ReadAllBytesAsync(oldFile, ct);
// The library file changes in place (same path, other bytes), as a replacement does.
var newBytes = ExportTestBed.Photo(1, 46).Bytes;
var library = bed.LibraryFile(bed.Marta, post.Media[0]);
await File.WriteAllBytesAsync(library, newBytes, ct);
var newSha = Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(newBytes));
await bed.Db.Media.MarkStoredAsync(post.Media[0].Id, new StoredFile(post.Media[0].RelativePath!, newBytes.Length, newSha, null, 96, 120, null, false), MediaState.Downloaded, bed.Clock.Now, ct);
Assert.AreEqual(1, await ExportSupersession.FileChangedAsync(bed.Db, bed.Marta.Id, post.Media[0].Sha256, newSha, bed.Clock.Now, ct));
// By itself: skipped as «Superato», nothing written.
var skipped = await bed.CopyAccountAsync(bed.Marta, ct: ct);
var item = (await bed.ItemsAsync(skipped.Runs.Single().Id, ct)).Single();
Assert.AreEqual((ExportItemState.Skipped, ExportText.Notes.Superseded, copy.Id), (item.State, item.Note, item.CopyId));
Assert.HasCount(1, Fingerprint.Of(bed.Usb));
// «Copia di nuovo»: the new file goes beside the old one, which is never overwritten.
var again = await bed.CopyAccountAsync(bed.Marta, copyAgain: true, ct: ct);
var written = (await bed.ItemsAsync(again.Runs.Single().Id, ct)).Single();
Assert.AreEqual((ExportItemState.Copied, ExportText.Notes.NameTaken), (written.State, written.Note));
CollectionAssert.AreEqual(oldBytes, await File.ReadAllBytesAsync(oldFile, ct));
CollectionAssert.AreEqual(newBytes, await File.ReadAllBytesAsync(Path.Combine(bed.Usb, LibraryLayout.ToPlatform(written.RelativePath!)), ct));
Assert.AreEqual(ExportCopyState.Superseded, (await bed.Db.Exports.GetCopyAsync(copy.Id, ct))!.State);
Assert.AreEqual(0, (await bed.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct)).RemovedOrSuperseded);
}
[TestMethod]
public async Task SupersessionWaitsWhileAnotherPresentFileHasTheOldSha()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await Data.ExportWorld.CreateAsync(db);
// A second post of marta.demo with the same bytes as her first (for instance a story and its highlight).
var twin = await db.Entries.AddAsync(Make.Entry(w.Marta, "556", Make.T0), [Make.Stored(Make.Photo(), Make.Sha(1), "post/twin.jpg")], ct);
var copy = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a.jpg"), ct);
var luca = await db.Exports.AddCopyAsync(w.WholeCopy("luca.demo/a.jpg", account: w.Luca, media: w.LucaMedia), ct);
// The first file changes: the twin still has the old bytes, so the copy is still of a file of the library.
await db.Media.MarkStoredAsync(w.MartaMedia, new StoredFile("post/a.jpg", 2000, Make.Sha(7), null, 1, 1, null, false), MediaState.Downloaded, Make.T0, ct);
Assert.AreEqual(0, await ExportSupersession.FileChangedAsync(db, w.Marta, Make.Sha(1), Make.Sha(7), Make.T0, ct));
Assert.AreEqual(ExportCopyState.Copied, (await db.Exports.GetCopyAsync(copy.Id, ct))!.State);
// The twin changes too: now the copy is superseded, and only marta's (luca.demo still has the old file).
await db.Media.MarkStoredAsync(twin.Stored.Media[0].Id, new StoredFile("post/twin.jpg", 2000, Make.Sha(8), null, 1, 1, null, false), MediaState.Downloaded, Make.T0, ct);
Assert.AreEqual(1, await ExportSupersession.FileChangedAsync(db, w.Marta, Make.Sha(1), Make.Sha(8), Make.T0, ct));
Assert.AreEqual((ExportCopyState.Superseded, Make.Sha(8)), ((await db.Exports.GetCopyAsync(copy.Id, ct))!.State, (await db.Exports.GetCopyAsync(copy.Id, ct))!.SupersededBySha256));
Assert.AreEqual(ExportCopyState.Copied, (await db.Exports.GetCopyAsync(luca.Id, ct))!.State);
// Nothing to do without an old file, or when nothing changed.
Assert.AreEqual(0, await ExportSupersession.FileChangedAsync(db, w.Marta, null, Make.Sha(8), Make.T0, ct));
Assert.AreEqual(0, await ExportSupersession.FileChangedAsync(db, w.Marta, Make.Sha(8), Make.Sha(8).ToUpperInvariant(), Make.T0, ct));
}
[TestMethod]
public async Task CheckCopiesMarksMissingFilesRemoved()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var post = await bed.PostAsync(bed.Marta, "975", 47, 48, 49);
var usb = await bed.GeneralAsync(ct: ct);
await bed.CopyAccountAsync(bed.Marta, ct: ct);
var copies = (await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)).ToDictionary(c => c.MediaId!.Value);
await bed.Db.Exports.UpdateCopyAsync(copies[post.Media[2].Id] with { State = ExportCopyState.Superseded, SupersededBySha256 = Make.Sha(99) }, ct);
File.Delete(bed.GeneralCopy(bed.Marta, post.Media[0]));
File.Delete(bed.GeneralCopy(bed.Marta, post.Media[2]));
var files = Fingerprint.Of(bed.Usb);
// The disk is unplugged first: nothing becomes «Tolto», the folder pauses.
Directory.Move(bed.Usb, bed.Temp.Combine("staccato"));
await bed.Service.CheckCopiesAsync(usb.Id, ct);
await bed.Service.WaitAsync(ct);
Assert.IsTrue((await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)).All(c => c.State != ExportCopyState.Removed));
Assert.IsNotNull((await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.PausedAt);
Assert.IsFalse(Directory.Exists(bed.Usb));
Directory.Move(bed.Temp.Combine("staccato"), bed.Usb);
await bed.Service.CheckCopiesAsync(usb.Id, ct);
await bed.Service.WaitAsync(ct);
var after = (await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)).ToDictionary(c => c.MediaId!.Value);
Assert.AreEqual(ExportCopyState.Removed, after[post.Media[0].Id].State);
Assert.AreEqual(ExportCopyState.Copied, after[post.Media[1].Id].State);
Assert.AreEqual(ExportCopyState.Removed, after[post.Media[2].Id].State);
Assert.AreEqual(Make.Sha(99), after[post.Media[2].Id].SupersededBySha256);
Assert.IsNull((await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.PausedAt);
Fingerprint.AreEqual(files, Fingerprint.Of(bed.Usb), "the check never touches a file");
var check = (await bed.Db.Events.ListAsync(new() { Limit = 50 }, ct)).First(e => e.Code == "esportazione-controllo");
Assert.AreEqual(EventSeverity.Warning, check.Severity);
Assert.IsEmpty(await bed.Db.Exports.ListUnfinishedRunsAsync(ct));
// Idempotent.
await bed.Service.CheckCopiesAsync(usb.Id, ct);
await bed.Service.WaitAsync(ct);
Assert.AreEqual(2, (await bed.Db.Exports.ListCopiesAsync(usb.Id, ExportCopyState.Removed, ct: ct)).Count);
}
[TestMethod]
public async Task DeletingAnEntryLeavesItsCopies()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var post = await bed.PostAsync(bed.Marta, "976", 50);
var usb = await bed.GeneralAsync(ct: ct);
await bed.CopyAccountAsync(bed.Marta, ct: ct);
var files = Fingerprint.Of(bed.Usb);
var lib = bed.Library;
var deleted = await new LibraryDeletion(lib.Db, lib.Layout, lib.Journal, lib.Clock, lib.Thumbnails, lib.Index).DeleteAsync(post.Entry.Id, ct: ct);
Assert.IsTrue(deleted.Complete);
Assert.IsFalse(File.Exists(bed.LibraryFile(bed.Marta, post.Media[0])));
Fingerprint.AreEqual(files, Fingerprint.Of(bed.Usb), "the copy outside is Alberto's");
var copy = (await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)).Single();
Assert.AreEqual(ExportCopyState.Copied, copy.State);
Assert.AreEqual(post.Media[0].Sha256, copy.SourceSha256);
var plan = await bed.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct);
Assert.AreEqual((0, 0, 0), (plan.Files, plan.AlreadyCopied, plan.Missing)); // a deleted entry is not a candidate
}
private static ExportEnvironment Environment(TestLibrary library) => new()
{
Storage = library.Db,
Layout = () => library.Layout,
DataFolder = library.Data.Root,
Clock = library.Clock,
Root = ExportRootOptions.AnyFolder with { Mounts = new FixedMounts() },
Disk = new FakeExportDisk(),
};
}