Files
Febe/tests/Febe.Tests/Export/ExportCopyJobTests.cs
T
Alby96andClaude Opus 5.5 a112c92893 E2: motore delle copie esterne (porta, destinazioni, piano, copia)
Prima metà della tappa E2 «Copie esterne» (#58), parte Core e Data:

- porta del lavoro lungo: importazione, copia e ricostruzione mai insieme;
- radice /esporta in Docker con mountinfo, controllo delle cartelle con
  il file di prova, destinazioni con «Esporta questo account» acceso se
  Alberto non ha mai scelto (decisione del 27/11/2026);
- filtro «Copie», segni delle tessere e conteggi dell'account sui soli
  file dovuti (D3);
- percorsi «Come la libreria», segmento dell'account nella cartella
  generale, 240 caratteri, storia in evidenza;
- piano di «Copia in…», un lavoro per destinazione, copia in .part con
  SHA-256 riletto dal disco, nome libero, mai sovrascrivere, adozione
  per percorso, pausa della destinazione su prova, spazio e FAT32,
  attesa fuori dalle sessioni del motore, ripresa e recupero;
- .part rimossi solo nelle cartelle degli elementi di lavori non finiti;
- «Tolto» e «Superato» (agganci in importazione, scaricamenti,
  doppioni e ricostruzione), mai ricopiati da soli;
- rapporti e testi in italiano, prove del lavoro di copia.

Interfaccia, API e composizione restano alla parte successiva.

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

359 lines
19 KiB
C#

using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Library;
using Febe.Tests.Support;
namespace Febe.Tests.Export;
/// <summary>
/// The copy job of tappa E2 (WP1b) on a real library and real folders: paths, never overwriting, adoption by path,
/// «Tolto» and «Copia di nuovo», pause of a missing destination, engine sessions, leftovers and «Superato». WP5 adds
/// the full set.
/// </summary>
[TestClass]
public sealed class ExportCopyJobTests
{
public TestContext TestContext { get; set; } = null!;
[TestMethod]
public async Task ACopyGoesUnderTheAccountSegmentAndIsNotWrittenTwice()
{
var ct = TestContext.CancellationToken;
await using var w = await World.CreateAsync();
var post = await w.Library.SaveAsync(w.Marta, Make.Entry(w.Marta.Id, "777", Make.T0.AddDays(-1)), [TestFile.Photo(1, 1), TestFile.Photo(2, 2)]);
var usb = await w.GeneralAsync(ct);
var plan = await w.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(w.Marta.Id)), ct);
Assert.AreEqual(2, plan.Files);
Assert.AreEqual(usb.Id, plan.Destinations.Single().DestinationId);
Assert.IsNull(plan.Destinations.Single().Problem);
var start = await w.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(w.Marta.Id)), ct);
await w.Service.WaitAsync(ct);
var run = (await w.Library.Db.Exports.GetRunAsync(start.Runs.Single().Id, ct))!;
Assert.AreEqual(ExportRunState.Completed, run.State, run.LastError);
foreach (var media in post.Media)
{
var copied = Path.Combine(w.Usb, "marta.demo", LibraryLayout.ToPlatform(media.RelativePath!));
Assert.IsTrue(File.Exists(copied), copied);
CollectionAssert.AreEqual(await File.ReadAllBytesAsync(w.Library.Layout.FullPath(w.Marta, media.RelativePath!), ct), await File.ReadAllBytesAsync(copied, ct));
}
Assert.IsEmpty(Directory.GetFiles(w.Usb, "*.part", SearchOption.AllDirectories));
var report = await w.Service.Reports.BuildAsync(run.Id, ct);
Assert.AreEqual(2, report.ByState[ExportItemState.Copied]);
Assert.AreEqual(2, report.Accounts.Single().Copied);
// Nothing is written twice: the plan says «già copiati», a second job finds them.
var again = await w.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(w.Marta.Id)), ct);
Assert.AreEqual(0, again.Files);
Assert.AreEqual(2, again.AlreadyCopied);
var second = await w.Service.StartAsync(new ExportJobRequest(new ExportSelection.Entries([post.Entry.Id])), ct);
await w.Service.WaitAsync(ct);
Assert.AreEqual(2, (await w.Library.Db.Exports.GetRunSummaryAsync(second.Runs.Single().Id, ct)).ByState[ExportItemState.AlreadyCopied]);
Assert.HasCount(2, Directory.GetFiles(w.Usb, "*", SearchOption.AllDirectories));
}
[TestMethod]
public async Task ARemovedCopyIsNotCopiedAgainUnlessAsked()
{
var ct = TestContext.CancellationToken;
await using var w = await World.CreateAsync();
var post = await w.Library.SaveAsync(w.Marta, Make.Entry(w.Marta.Id, "778", Make.T0.AddDays(-1)), [TestFile.Photo(1, 3)]);
await w.GeneralAsync(ct);
var request = new ExportJobRequest(new ExportSelection.Account(w.Marta.Id));
await w.Service.StartAsync(request, ct);
await w.Service.WaitAsync(ct);
var copy = Path.Combine(w.Usb, "marta.demo", LibraryLayout.ToPlatform(post.Media[0].RelativePath!));
File.Delete(copy); // Alberto removed it from the disk
var skipped = await w.Service.StartAsync(request, ct);
await w.Service.WaitAsync(ct);
var item = (await w.Library.Db.Exports.ListItemsAsync(new() { RunId = skipped.Runs.Single().Id }, ct)).Single();
Assert.AreEqual(ExportItemState.Skipped, item.State);
Assert.AreEqual(ExportText.Notes.Removed, item.Note);
Assert.IsFalse(File.Exists(copy));
var plan = await w.Service.PlanAsync(request, ct);
Assert.AreEqual((0, 1), (plan.Files, plan.RemovedOrSuperseded));
var again = await w.Service.StartAsync(request with { CopyAgain = true }, ct);
await w.Service.WaitAsync(ct);
Assert.AreEqual(1, again.Plan.Files);
Assert.AreEqual(ExportItemState.Copied, (await w.Library.Db.Exports.ListItemsAsync(new() { RunId = again.Runs.Single().Id }, ct)).Single().State);
Assert.IsTrue(File.Exists(copy));
}
[TestMethod]
public async Task AFileAlreadyThereIsAdoptedAndAnotherFileIsNeverOverwritten()
{
var ct = TestContext.CancellationToken;
await using var w = await World.CreateAsync();
var first = await w.Library.SaveAsync(w.Marta, Make.Entry(w.Marta.Id, "779", Make.T0.AddDays(-1)), [TestFile.Photo(1, 4)]);
var second = await w.Library.SaveAsync(w.Marta, Make.Entry(w.Marta.Id, "780", Make.T0.AddDays(-2)), [TestFile.Photo(1, 5)]);
await w.GeneralAsync(ct);
var same = Path.Combine(w.Usb, "marta.demo", LibraryLayout.ToPlatform(first.Media[0].RelativePath!));
var other = Path.Combine(w.Usb, "marta.demo", LibraryLayout.ToPlatform(second.Media[0].RelativePath!));
Directory.CreateDirectory(Path.GetDirectoryName(same)!);
Directory.CreateDirectory(Path.GetDirectoryName(other)!);
File.Copy(w.Library.Layout.FullPath(w.Marta, first.Media[0].RelativePath!), same);
await File.WriteAllBytesAsync(other, [1, 2, 3], ct); // something else with that name
var start = await w.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(w.Marta.Id)), ct);
await w.Service.WaitAsync(ct);
var items = (await w.Library.Db.Exports.ListItemsAsync(new() { RunId = start.Runs.Single().Id }, ct)).ToDictionary(i => i.MediaId!.Value);
Assert.AreEqual(ExportItemState.Adopted, items[first.Media[0].Id].State);
Assert.AreEqual(ExportItemState.Copied, items[second.Media[0].Id].State);
Assert.AreEqual(ExportText.Notes.NameTaken, items[second.Media[0].Id].Note);
CollectionAssert.AreEqual(new byte[] { 1, 2, 3 }, await File.ReadAllBytesAsync(other, ct));
var renamed = Path.Combine(w.Usb, LibraryLayout.ToPlatform(items[second.Media[0].Id].RelativePath!));
StringAssert.EndsWith(renamed, " (2).jpg");
Assert.IsTrue(File.Exists(renamed));
Assert.AreEqual(ExportCopyOrigin.Adopted, (await w.Library.Db.Exports.GetCopyAsync(items[first.Media[0].Id].CopyId!.Value, ct))!.Origin);
}
[TestMethod]
public async Task AMissingDestinationPausesAndIsNeverCreated()
{
var ct = TestContext.CancellationToken;
await using var w = await World.CreateAsync();
await w.Library.SaveAsync(w.Marta, Make.Entry(w.Marta.Id, "781", Make.T0.AddDays(-1)), [TestFile.Photo(1, 6)]);
var usb = await w.GeneralAsync(ct);
Directory.Delete(w.Usb); // the disk was unplugged
var plan = await w.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(w.Marta.Id)), ct);
Assert.IsNotNull(plan.Destinations.Single().Problem);
var start = await w.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(w.Marta.Id)), ct);
await w.Service.WaitAsync(ct);
var run = (await w.Library.Db.Exports.GetRunAsync(start.Runs.Single().Id, ct))!;
Assert.AreEqual(ExportRunState.Paused, run.State);
Assert.IsFalse(Directory.Exists(w.Usb));
var paused = (await w.Library.Db.Exports.GetDestinationAsync(usb.Id, ct))!;
Assert.IsNotNull(paused.PausedAt);
Assert.Contains("non è raggiungibile", paused.LastError!);
Assert.AreEqual(ExportItemState.Pending, (await w.Library.Db.Exports.ListItemsAsync(new() { RunId = run.Id }, ct)).Single().State);
// The disk is back: «Riprendi» clears the pause and copies.
Directory.CreateDirectory(w.Usb);
await w.Service.ResumeAsync(null, ct);
await w.Service.WaitAsync(ct);
Assert.AreEqual(ExportRunState.Completed, (await w.Library.Db.Exports.GetRunAsync(run.Id, ct))!.State);
Assert.IsNull((await w.Library.Db.Exports.GetDestinationAsync(usb.Id, ct))!.PausedAt);
}
[TestMethod]
public async Task CopiesWaitForTheEngineSessionAndForSpace()
{
var ct = TestContext.CancellationToken;
var session = new CountedSession(3);
var disk = new FakeDisk();
await using var w = await World.CreateAsync(session, disk);
await w.Library.SaveAsync(w.Marta, Make.Entry(w.Marta.Id, "782", Make.T0.AddDays(-1)), [TestFile.Photo(1, 7)]);
await w.GeneralAsync(ct);
var before = w.Library.Clock.Now;
disk.Free = 1000; // less than the file plus 64 MB
var start = await w.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(w.Marta.Id)), ct);
await w.Service.WaitAsync(ct);
var run = (await w.Library.Db.Exports.GetRunAsync(start.Runs.Single().Id, ct))!;
Assert.AreEqual(ExportRunState.Paused, run.State);
Assert.Contains("margine di 64 MB", run.LastError!);
Assert.AreEqual(w.Library.Clock.Now, before + TimeSpan.FromSeconds(15)); // three polls of 5 s while the session ran
disk.Free = null;
disk.Max = 10; // a FAT32 disk, with a tiny limit for the test
await w.Service.ResumeAsync([run.Id], ct);
await w.Service.WaitAsync(ct);
var item = (await w.Library.Db.Exports.ListItemsAsync(new() { RunId = run.Id }, ct)).Single();
Assert.AreEqual(ExportItemState.Failed, item.State);
Assert.AreEqual(ExportText.Notes.TooLargeForFileSystem, item.Note);
Assert.AreEqual(ExportRunState.Completed, (await w.Library.Db.Exports.GetRunAsync(run.Id, ct))!.State);
Assert.AreEqual(ExportCopyState.Failed, (await w.Library.Db.Exports.GetCopyAsync(item.CopyId!.Value, ct))!.State);
}
[TestMethod]
public async Task LeftoversGoOnlyInTheFoldersOfAnUnfinishedJob()
{
var ct = TestContext.CancellationToken;
await using var w = await World.CreateAsync();
var post = await w.Library.SaveAsync(w.Marta, Make.Entry(w.Marta.Id, "783", Make.T0.AddDays(-1)), [TestFile.Photo(1, 8)]);
var usb = await w.GeneralAsync(ct);
var relative = "marta.demo/" + post.Media[0].RelativePath;
var folder = Path.GetDirectoryName(Path.Combine(w.Usb, LibraryLayout.ToPlatform(relative)))!;
Directory.CreateDirectory(folder);
var leftover = Path.Combine(folder, ".febe-0123456789ab.part");
var elsewhere = Path.Combine(w.Usb, ".febe-ba9876543210.part");
await File.WriteAllBytesAsync(leftover, [9], ct);
await File.WriteAllBytesAsync(elsewhere, [9], ct);
// A job interrupted after it recorded the target path.
var run = await w.Library.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = usb.Id, State = ExportRunState.Running, StartedAt = w.Library.Clock.Now }, ct);
await w.Library.Db.Exports.AddItemsAsync([new ExportItem { RunId = run.Id, MediaId = post.Media[0].Id, AccountId = w.Marta.Id, SourceSha256 = post.Media[0].Sha256 }], ct);
var item = (await w.Library.Db.Exports.ListItemsAsync(new() { RunId = run.Id }, ct)).Single();
await w.Library.Db.Exports.UpdateItemsAsync([item with { RelativePath = relative }], ct);
Assert.AreEqual(1, await w.Service.RecoverAsync(ct));
await w.Service.WaitAsync(ct);
Assert.AreEqual(ExportRunState.Interrupted, (await w.Library.Db.Exports.GetRunAsync(run.Id, ct))!.State);
Assert.IsFalse(File.Exists(leftover));
Assert.IsTrue(File.Exists(elsewhere)); // the root holds no item: never cleaned
await w.Service.ResumeAsync(null, ct);
await w.Service.WaitAsync(ct);
Assert.AreEqual(ExportItemState.Copied, (await w.Library.Db.Exports.GetItemAsync(item.Id, ct))!.State);
}
[TestMethod]
public async Task ASwitchedOffAccountIsSkippedWhenAJobResumes()
{
var ct = TestContext.CancellationToken;
await using var w = await World.CreateAsync();
var post = await w.Library.SaveAsync(w.Marta, Make.Entry(w.Marta.Id, "786", Make.T0.AddDays(-1)), [TestFile.Photo(1, 11)]);
var usb = await w.GeneralAsync(ct);
var run = await w.Library.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = usb.Id, State = ExportRunState.Interrupted, StartedAt = w.Library.Clock.Now }, ct);
await w.Library.Db.Exports.AddItemsAsync([new ExportItem { RunId = run.Id, MediaId = post.Media[0].Id, AccountId = w.Marta.Id, SourceSha256 = post.Media[0].Sha256 }], ct);
await w.Service.Destinations.SetAccountEnabledAsync(w.Marta.Id, false, ct);
await w.Service.ResumeAsync([run.Id], ct);
await w.Service.WaitAsync(ct);
var item = (await w.Library.Db.Exports.ListItemsAsync(new() { RunId = run.Id }, ct)).Single();
Assert.AreEqual((ExportItemState.Skipped, ExportText.Notes.NotExported), (item.State, item.Note));
Assert.IsEmpty(Directory.GetFiles(w.Usb, "*", SearchOption.AllDirectories));
}
[TestMethod]
public async Task AChangedLibraryFileSupersedesItsCopies()
{
var ct = TestContext.CancellationToken;
await using var w = await World.CreateAsync();
var post = await w.Library.SaveAsync(w.Marta, Make.Entry(w.Marta.Id, "784", Make.T0.AddDays(-1)), [TestFile.Photo(1, 9)]);
await w.GeneralAsync(ct);
var request = new ExportJobRequest(new ExportSelection.Account(w.Marta.Id));
await w.Service.StartAsync(request, ct);
await w.Service.WaitAsync(ct);
// «Tieni il più grande» put another file in the slot.
var oldSha = post.Media[0].Sha256!;
var newSha = Make.Sha(4242);
await w.Library.Db.Media.MarkStoredAsync(post.Media[0].Id, new StoredFile(post.Media[0].RelativePath!, 10, newSha, null, 1, 1, null, false), MediaState.Downloaded, w.Library.Clock.Now, ct);
Assert.AreEqual(0, await ExportSupersession.FileChangedAsync(w.Library.Db, w.Marta.Id, newSha, newSha, w.Library.Clock.Now, ct));
Assert.AreEqual(1, await ExportSupersession.FileChangedAsync(w.Library.Db, w.Marta.Id, oldSha, newSha, w.Library.Clock.Now, ct));
var copies = await w.Library.Db.Exports.ListCopiesBySha256Async(newSha, ct);
Assert.AreEqual(ExportCopyState.Superseded, copies.Single().State);
Assert.AreEqual(1, (await w.Service.PlanAsync(request, ct)).RemovedOrSuperseded);
}
[TestMethod]
public async Task AnExportDoesNotStartWhileAnImportHoldsTheGate()
{
var ct = TestContext.CancellationToken;
var gate = new LongWorkGate();
await using var w = await World.CreateAsync(gate: gate);
await w.Library.SaveAsync(w.Marta, Make.Entry(w.Marta.Id, "785", Make.T0.AddDays(-1)), [TestFile.Photo(1, 10)]);
await w.GeneralAsync(ct);
Assert.IsTrue(gate.TryEnter(LongWorkKind.Import, out var lease, out _));
var refused = await Assert.ThrowsExactlyAsync<InvalidOperationException>(() => w.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(w.Marta.Id)), ct));
Assert.StartsWith("C'è un'importazione al lavoro", refused.Message);
Assert.IsEmpty(await w.Library.Db.Exports.ListRunsAsync(ct));
lease.Dispose();
}
[TestMethod]
public void PathsFollowTheLibraryTheAccountSegmentAndTheHighlightRule()
{
var naming = LibraryNaming.Default;
var account = Make.Account("marta.demo") with { Id = 1 };
var general = new ExportDestination { Id = 1, Scope = ExportScope.General, RootPath = Path.GetTempPath(), ContentTypes = ContentTypes.All, CreatedAt = Make.T0 };
var story = Make.Entry(1, "9001", Make.T0, EntryKind.Story);
var media = Make.Stored(Make.Photo(), Make.Sha(1), "storie/2026/x.jpg");
var asStory = ExportPaths.Segments(general, naming, account, story, media, "Estate", inHighlight: true, TestZones.Rome);
Assert.AreEqual("marta.demo", asStory[0]);
Assert.AreEqual("storie", asStory[1]);
var onlyHighlights = general with { Scope = ExportScope.Account, AccountId = 1, ContentTypes = ContentTypes.Highlights };
var asHighlight = ExportPaths.Segments(onlyHighlights, naming, account, story, media, "Estate", inHighlight: true, TestZones.Rome);
CollectionAssert.AreEqual(new[] { "evidenza", "Estate" }, asHighlight.Take(2).ToArray());
var imported = media with { RelativePath = "importati/IMG_0001.JPG" };
CollectionAssert.AreEqual(new[] { "marta.demo", "importati", "IMG_0001.JPG" }, ExportPaths.Segments(general, naming, account, story, imported, null, false, TestZones.Rome).ToArray());
var renamed = ExportPaths.Segments(general with { NamingScheme = @"{anno}\{codice}_{n}" }, naming, account, story, imported, null, false, TestZones.Rome);
CollectionAssert.AreEqual(new[] { "marta.demo", "2026", "9001_1.jpg" }, renamed.ToArray());
var deep = general with { RootPath = Path.Combine(Path.GetTempPath(), new string('d', 150)) };
var fitted = ExportPaths.RelativePathFor(deep, ["marta.demo", new string('x', 120) + ".jpg"]);
Assert.IsLessThanOrEqualTo(240, Path.TrimEndingDirectorySeparator(deep.RootPath).Length + 1 + fitted.Length);
StringAssert.EndsWith(fitted, ".jpg");
}
private sealed class CountedSession(int polls) : IEngineSessionState
{
private int _left = polls;
public bool InSession => Interlocked.Decrement(ref _left) >= 0;
}
private sealed class FakeDisk : IExportDisk
{
public long? Free { get; set; }
public long? Max { get; set; }
public long? FreeBytes(string root) => Free;
public long? MaxFileBytes(string root) => Max;
}
private sealed class World : IAsyncDisposable
{
private readonly TempFolder _temp;
private World(TempFolder temp, TestLibrary library, ExportService service, Account marta)
{
_temp = temp;
Library = library;
Service = service;
Marta = marta;
Usb = temp.Combine("usb");
Directory.CreateDirectory(Usb);
}
public TestLibrary Library { get; }
public ExportService Service { get; }
public Account Marta { get; }
public string Usb { get; }
public static async Task<World> CreateAsync(IEngineSessionState? session = null, IExportDisk? disk = null, LongWorkGate? gate = null)
{
var temp = new TempFolder();
var library = await TestLibrary.CreateAsync(temp);
var marta = await library.Db.Accounts.AddAsync(Make.Account("marta.demo", "100"));
var env = new ExportEnvironment
{
Storage = library.Db,
Layout = () => library.Layout,
DataFolder = library.Data.Root,
Clock = library.Clock,
Root = ExportRootOptions.AnyFolder with { Mounts = new ProcMountInfo(() => null) },
Disk = disk ?? new FakeDisk(),
Session = session ?? NoEngineSession.Instance,
Gate = gate,
};
return new World(temp, library, new ExportService(env), marta);
}
public async Task<ExportDestination> GeneralAsync(CancellationToken ct) =>
(await Service.Destinations.CreateAsync(new DestinationSpec(ExportScope.General, null, Usb, "Disco USB", ContentTypes.All, null, null, null), ct)).Destination;
public async ValueTask DisposeAsync()
{
await Service.DisposeAsync();
await Library.DisposeAsync();
_temp.Dispose();
}
}
}