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>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-27 13:28:20 +01:00
1 parent 31cfdac051
commit 736d241a38
18 files changed
+3124 -12

No files matched your search

@@ -0,0 +1,412 @@
using System.Collections.Concurrent;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Tests.Export.Support;
using Febe.Tests.Support;
namespace Febe.Tests.Export;
/// <summary>
/// The export job as the page drives it (spec §4.10, decisions D6, D10, D11 of tappa E2): one run per destination in
/// the background, «Interrompi», «Riprendi», «Annulla», the restart, the gate shared with the import and the rebuild,
/// the engine session, «Esporta questo account» and Docker without its mount.
/// </summary>
[TestClass]
public sealed class ExportServiceTests
{
private static readonly TimeSpan Patience = TimeSpan.FromSeconds(30);
public TestContext TestContext { get; set; } = null!;
[TestMethod]
public async Task TheJobRunsInTheBackgroundOneRunPerDestination()
{
var ct = TestContext.CancellationToken;
var held = new HeldExportFileSystem(SecondFile);
await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = held });
var marta = await bed.PostAsync(bed.Marta, "990", 70, 71);
var luca = await bed.PostAsync(bed.Luca, "991", 72);
var usb = await bed.GeneralAsync(ct: ct);
var own = await bed.OwnAsync(bed.Luca, "luca-nas", ct: ct);
var finished = new ConcurrentQueue<ExportJobFinished>();
var progress = new ConcurrentQueue<ExportProgress>();
bed.Service.JobFinished += (_, f) => finished.Enqueue(f);
bed.Service.ProgressChanged += (_, p) => progress.Enqueue(p);
var start = await bed.Service.StartAsync(new ExportJobRequest(new ExportSelection.Entries([marta.Entry.Id, luca.Entry.Id])), ct);
CollectionAssert.AreEqual(new[] { usb.Id, own.Id }, start.Runs.Select(r => r.DestinationId).ToArray());
Assert.AreEqual(3, start.Plan.Files);
Assert.HasCount(2, start.Plan.Destinations);
// While it runs: busy, its runs, and a second «Copia in…» or «Controlla le copie» is refused.
await held.Reached.Task.WaitAsync(Patience, ct);
Assert.IsTrue(bed.Service.IsBusy);
CollectionAssert.AreEqual(start.Runs.Select(r => r.Id).ToArray(), bed.Service.ActiveRunIds.ToArray());
var busy = await Assert.ThrowsExactlyAsync<InvalidOperationException>(() => bed.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(bed.Luca.Id)), ct));
Assert.StartsWith("C'è già una copia al lavoro", busy.Message);
await Assert.ThrowsExactlyAsync<InvalidOperationException>(() => bed.Service.CheckCopiesAsync(usb.Id, ct));
var now = await bed.Service.GetProgressAsync(ct);
Assert.AreEqual((start.Runs[0].Id, ExportPhase.Copying, "Disco USB"), (now.RunId, now.Phase, now.DestinationLabel));
Assert.HasCount(2, await bed.Db.Exports.ListRunsAsync(ct));
held.Release();
await bed.Service.WaitAsync(ct);
Assert.IsFalse(bed.Service.IsBusy);
Assert.IsEmpty(bed.Service.ActiveRunIds);
foreach (var run in start.Runs)
{
Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(run.Id, ct)).State);
}
Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Marta, marta.Media[1])));
Assert.IsTrue(File.Exists(Path.Combine(own.RootPath, Core.Library.LibraryLayout.ToPlatform(luca.Media[0].RelativePath!))));
Assert.IsFalse(Directory.Exists(Path.Combine(bed.Usb, "luca.demo")), "Luca's own folder replaces the general one");
var job = finished.Single();
CollectionAssert.AreEqual(start.Runs.Select(r => r.Id).ToArray(), job.RunIds.ToArray());
Assert.IsTrue(progress.Any(p => p.Phase == ExportPhase.Finished));
Assert.AreEqual(2, (await bed.Db.Events.ListAsync(new() { Limit = 50 }, ct)).Count(e => e.Code == "esportazione-completata"));
var last = await bed.Service.GetProgressAsync(ct);
Assert.AreEqual((start.Runs[1].Id, ExportPhase.Finished), (last.RunId, last.Phase));
}
[TestMethod]
public async Task InterruptStopsAndKeepsWhatIsDoneAndResumeSkipsFinishedItems()
{
var ct = TestContext.CancellationToken;
var block = true;
var gated = new GatedExportFileSystem(p => Volatile.Read(ref block) && SecondFile(p));
await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = gated });
var post = await bed.PostAsync(bed.Marta, "992", 73, 74, 75);
await bed.GeneralAsync(ct: ct);
var start = await bed.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct);
var runId = start.Runs.Single().Id;
await gated.Reached.Task.WaitAsync(Patience, ct);
await bed.Service.InterruptAsync(ct);
Assert.IsFalse(bed.Service.IsBusy);
var run = await bed.RunAsync(runId, ct);
Assert.AreEqual((ExportRunState.Interrupted, null), (run.State, run.LastError));
var items = (await bed.ItemsAsync(runId, ct)).ToDictionary(i => i.MediaId!.Value);
Assert.AreEqual(ExportItemState.Copied, items[post.Media[0].Id].State);
Assert.AreEqual(ExportItemState.Pending, items[post.Media[1].Id].State);
Assert.AreEqual(ExportItemState.Pending, items[post.Media[2].Id].State);
Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Marta, post.Media[0])));
Assert.IsFalse(File.Exists(bed.GeneralCopy(bed.Marta, post.Media[1])));
Assert.HasCount(1, await bed.Db.Exports.ListCopiesAsync(start.Runs[0].DestinationId, ct: ct));
var first = File.GetLastWriteTimeUtc(bed.GeneralCopy(bed.Marta, post.Media[0]));
Assert.HasCount(1, await bed.Db.Exports.ListUnfinishedRunsAsync(ct));
// «Riprendi»: only the pending items are worked on; the copied one is neither written again nor recorded twice.
Volatile.Write(ref block, false);
var resumed = await bed.Service.ResumeAsync(ct: ct);
Assert.AreEqual(runId, resumed.Single().Id);
await bed.Service.WaitAsync(ct);
Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(runId, ct)).State);
var after = (await bed.ItemsAsync(runId, ct)).ToDictionary(i => i.MediaId!.Value);
Assert.IsTrue(after.Values.All(i => i.State == ExportItemState.Copied));
Assert.AreEqual(items[post.Media[0].Id].CopyId, after[post.Media[0].Id].CopyId);
Assert.HasCount(3, await bed.Db.Exports.ListCopiesAsync(start.Runs[0].DestinationId, ct: ct));
Assert.AreEqual(first, File.GetLastWriteTimeUtc(bed.GeneralCopy(bed.Marta, post.Media[0])));
Assert.HasCount(3, Fingerprint.Of(bed.Usb));
Assert.IsEmpty(Fingerprint.Temporaries(bed.Usb));
Assert.IsEmpty(await bed.Db.Exports.ListUnfinishedRunsAsync(ct));
var done = await Assert.ThrowsExactlyAsync<InvalidOperationException>(() => bed.Service.ResumeAsync([runId], ct));
Assert.Contains("già finito", done.Message);
}
[TestMethod]
public async Task AJobLeftRunningByAStopIsRecoveredAsInterrupted()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var post = await bed.PostAsync(bed.Marta, "993", 76);
var usb = await bed.GeneralAsync(ct: ct);
// Febe stopped while a job was running: the record still says «in corso».
var running = await bed.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = usb.Id, State = ExportRunState.Running, StartedAt = Make.T0 }, ct);
await bed.Db.Exports.AddItemsAsync([Pending(running.Id, post.Media[0], bed.Marta.Id)], ct);
var paused = await bed.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = usb.Id, State = ExportRunState.Paused, StartedAt = Make.T0, LastError = "Disco USB non è raggiungibile." }, ct);
Assert.AreEqual(1, await bed.Service.RecoverAsync(ct));
await bed.Service.WaitAsync(ct);
Assert.AreEqual(ExportRunState.Interrupted, (await bed.RunAsync(running.Id, ct)).State);
Assert.AreEqual(ExportRunState.Paused, (await bed.RunAsync(paused.Id, ct)).State);
Assert.IsFalse(bed.Service.IsBusy, "never resumes by itself");
Assert.AreEqual(ExportItemState.Pending, (await bed.ItemsAsync(running.Id, ct)).Single().State);
Assert.IsEmpty(Fingerprint.Of(bed.Usb));
Assert.AreEqual(0, await bed.Service.RecoverAsync(ct));
await bed.Service.WaitAsync(ct);
await bed.Service.ResumeAsync([running.Id], ct);
await bed.Service.WaitAsync(ct);
Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(running.Id, ct)).State);
Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Marta, post.Media[0])));
Assert.AreEqual(ExportRunState.Paused, (await bed.RunAsync(paused.Id, ct)).State);
}
[TestMethod]
public async Task DiscardLeavesFilesAlone()
{
var ct = TestContext.CancellationToken;
var gated = new GatedExportFileSystem(SecondFile);
await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = gated });
var post = await bed.PostAsync(bed.Marta, "994", 77, 78);
var usb = await bed.GeneralAsync(ct: ct);
await File.WriteAllTextAsync(Path.Combine(bed.Usb, "di Alberto.txt"), "non toccare", ct);
var start = await bed.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct);
var runId = start.Runs.Single().Id;
await gated.Reached.Task.WaitAsync(Patience, ct);
// «Annulla» of the running job interrupts it first.
await bed.Service.DiscardAsync(runId, ct);
await bed.Service.WaitAsync(ct);
Assert.IsFalse(bed.Service.IsBusy);
var run = await bed.RunAsync(runId, ct);
Assert.AreEqual(ExportRunState.Cancelled, run.State);
Assert.IsNotNull(run.CompletedAt);
var files = Fingerprint.Of(bed.Usb);
Assert.HasCount(2, files);
Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Marta, post.Media[0])), "the copies made stay");
Assert.AreEqual("non toccare", await File.ReadAllTextAsync(Path.Combine(bed.Usb, "di Alberto.txt"), ct));
Assert.IsEmpty(Fingerprint.Temporaries(bed.Usb));
Assert.AreEqual(ExportCopyState.Copied, (await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)).Single().State);
Assert.IsEmpty(await bed.Db.Exports.ListUnfinishedRunsAsync(ct));
// Nothing to resume, and a second «Annulla» changes nothing.
await Assert.ThrowsExactlyAsync<InvalidOperationException>(() => bed.Service.ResumeAsync([runId], ct));
await bed.Service.DiscardAsync(runId, ct);
Assert.AreEqual(run, await bed.RunAsync(runId, ct));
Fingerprint.AreEqual(files, Fingerprint.Of(bed.Usb), "«Annulla» never removes a copy");
await Assert.ThrowsExactlyAsync<KeyNotFoundException>(() => bed.Service.DiscardAsync(runId + 100, ct));
}
[TestMethod]
public async Task ExportImportAndRebuildNeverRunTogether()
{
var ct = TestContext.CancellationToken;
var gated = new GatedExportFileSystem(SecondFile);
await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = gated });
await bed.PostAsync(bed.Marta, "995", 79, 80);
var usb = await bed.GeneralAsync(ct: ct);
// A copy holds the gate: the import and the rebuild wait.
await bed.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct);
await gated.Reached.Task.WaitAsync(Patience, ct);
Assert.AreEqual(LongWorkKind.Export, bed.Gate.Busy);
Assert.IsFalse(bed.Gate.TryEnter(LongWorkKind.Import, out _, out var holder));
Assert.AreEqual(LongWorkKind.Export, holder);
Assert.IsFalse(bed.Gate.TryEnter(LongWorkKind.Rebuild, out _, out _));
Assert.StartsWith("C'è una copia nelle cartelle esterne al lavoro", LongWorkGate.BusyMessage(LongWorkKind.Import, LongWorkKind.Export));
await bed.Service.InterruptAsync(ct);
Assert.IsNull(bed.Gate.Busy, "the gate is given back however the job ends");
// A rebuild holds it: no copy starts, resumes or checks, and nothing is recorded.
var runs = await bed.Db.Exports.ListRunsAsync(ct);
Assert.IsTrue(bed.Gate.TryEnter(LongWorkKind.Rebuild, out var lease, out _));
using (lease)
{
var expected = LongWorkGate.BusyMessage(LongWorkKind.Export, LongWorkKind.Rebuild);
Assert.AreEqual(expected, (await Assert.ThrowsExactlyAsync<InvalidOperationException>(() => bed.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct))).Message);
Assert.AreEqual(expected, (await Assert.ThrowsExactlyAsync<InvalidOperationException>(() => bed.Service.ResumeAsync(ct: ct))).Message);
Assert.AreEqual(expected, (await Assert.ThrowsExactlyAsync<InvalidOperationException>(() => bed.Service.CheckCopiesAsync(usb.Id, ct))).Message);
Assert.IsFalse(bed.Service.IsBusy);
CollectionAssert.AreEqual(runs.ToArray(), (await bed.Db.Exports.ListRunsAsync(ct)).ToArray());
var retry = await bed.Service.RetryDestinationAsync(usb.Id, ct);
Assert.IsNull(retry.Problem);
Assert.IsEmpty(retry.Resumed, "with other long work running the paused jobs wait for «Riprendi»");
}
Assert.IsNull(bed.Gate.Busy);
}
[TestMethod]
public async Task NoCopyDuringAnEngineSession()
{
var ct = TestContext.CancellationToken;
WaitingClock? clock = null;
await using var bed = await ExportTestBed.CreateAsync(env => env with { Clock = clock = new WaitingClock(env.Clock) });
var post = await bed.PostAsync(bed.Marta, "996", 81);
await bed.GeneralAsync(ct: ct);
bed.Session.InSession = true;
var before = bed.Clock.Now;
var start = await bed.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct);
var waiting = await PollAsync(bed, p => p.Phase == ExportPhase.WaitingForSession, ct);
Assert.AreEqual(start.Runs.Single().Id, waiting.RunId);
await PollUntilAsync(() => clock!.Delays >= 3, ct);
Assert.IsTrue(bed.Service.IsBusy);
Assert.IsEmpty(Fingerprint.Of(bed.Usb), "nothing is written while the engine works");
Assert.AreEqual(ExportItemState.Pending, (await bed.ItemsAsync(start.Runs[0].Id, ct)).Single().State);
bed.Session.InSession = false;
await bed.Service.WaitAsync(ct);
Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(start.Runs[0].Id, ct)).State);
Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Marta, post.Media[0])));
var waited = bed.Clock.Now - before;
Assert.AreEqual(0, waited.Ticks % TimeSpan.FromSeconds(5).Ticks, "the wait goes by polls of 5 s on the clock");
Assert.IsGreaterThanOrEqualTo(TimeSpan.FromSeconds(15), waited);
}
[TestMethod]
public async Task TheSwitchOffSkipsTheAccount()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var marta = await bed.PostAsync(bed.Marta, "997", 82, 83);
var luca = await bed.PostAsync(bed.Luca, "998", 84);
await bed.GeneralAsync(ct: ct);
var own = await bed.OwnAsync(bed.Marta, "marta-nas", ct: ct);
await bed.Service.Destinations.SetAccountEnabledAsync(bed.Marta.Id, false, ct);
// Even a manual «Copia in…» of her entry skips her files (decision Q1), in her own folder too.
var plan = await bed.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Entries([marta.Entry.Id])), ct);
Assert.AreEqual((0, 2), (plan.Files, plan.NotExported));
var start = await bed.CopyAsync(new ExportJobRequest(new ExportSelection.Entries([marta.Entry.Id, luca.Entry.Id])), ct);
Assert.AreEqual((1, 2), (start.Plan.Files, start.Plan.NotExported));
Assert.IsTrue(start.Runs.All(r => r.DestinationId != own.Id));
Assert.IsEmpty(Fingerprint.Of(own.RootPath));
Assert.IsFalse(Directory.Exists(Path.Combine(bed.Usb, "marta.demo")));
Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, luca.Media[0])));
Assert.IsEmpty((await bed.CopyAccountAsync(bed.Marta, ct: ct)).Runs);
// Switched on again, her files are due.
await bed.Service.Destinations.SetAccountEnabledAsync(bed.Marta.Id, true, ct);
Assert.AreEqual(2, (await bed.CopyAccountAsync(bed.Marta, ct: ct)).Plan.Files);
Assert.HasCount(2, Fingerprint.Of(own.RootPath));
await Assert.ThrowsExactlyAsync<KeyNotFoundException>(() => bed.Service.Destinations.SetAccountEnabledAsync(9999, false, ct));
}
[TestMethod]
public async Task PlanCountsFilesAlreadyCopiedRemovedAndBytes()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var post = await bed.PostAsync(bed.Marta, "999", 85, 86, 87);
await bed.Library.SaveAsync(bed.Marta, Make.Entry(bed.Marta.Id, "1000", Make.T0.AddDays(-2), EntryKind.Tagged), [ExportTestBed.Photo(1, 88)]);
var waiting = await bed.Db.Entries.AddAsync(Make.Entry(bed.Marta.Id, "1001", Make.T0.AddDays(-3)), [Make.Photo(1)], ct); // never downloaded
var usb = await bed.GeneralAsync(ContentTypes.All & ~ContentTypes.Tagged, ct: ct);
await bed.CopyAsync(new ExportJobRequest(new ExportSelection.Media([post.Media[0].Id, post.Media[1].Id])), ct);
File.Delete(bed.GeneralCopy(bed.Marta, post.Media[1]));
await bed.Service.CheckCopiesAsync(usb.Id, ct);
await bed.Service.WaitAsync(ct);
bed.Disk.Free = 123_456_789;
var request = new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id));
var plan = await bed.Service.PlanAsync(request, ct);
var third = new FileInfo(bed.LibraryFile(bed.Marta, post.Media[2])).Length;
// The account card counts the files of the library: an entry still to download is not one of them.
Assert.AreEqual((1, third, 1, 1, 1, 0), (plan.Files, plan.Bytes, plan.AlreadyCopied, plan.RemovedOrSuperseded, plan.NotExported, plan.Missing));
var asked = await bed.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Entries([waiting.Stored.Entry.Id])), ct);
Assert.AreEqual((0, 1), (asked.Files, asked.Missing)); // asked for by itself, it is «non presente in libreria»
var destination = plan.Destinations.Single();
Assert.AreEqual((usb.Id, "Disco USB", ExportScope.General, (string?)null, 1, third, false, (string?)null, (long?)123_456_789),
(destination.DestinationId, destination.Label, destination.Scope, destination.Username, destination.Files, destination.Bytes, destination.Paused, destination.Problem, destination.FreeBytes));
// With «Copia di nuovo» the removed one is counted among the files to write too.
var again = await bed.Service.PlanAsync(request with { CopyAgain = true }, ct);
var second = new FileInfo(bed.LibraryFile(bed.Marta, post.Media[1])).Length;
Assert.AreEqual((2, third + second, 1, 1), (again.Files, again.Bytes, again.AlreadyCopied, again.RemovedOrSuperseded));
// The plan is database only: it records and writes nothing.
Assert.HasCount(1, await bed.Db.Exports.ListRunsAsync(ct));
Assert.HasCount(1, Fingerprint.Of(bed.Usb));
// Only files not exported or not in the library: no job is recorded and nothing starts.
var tagged = (await bed.Db.Exports.ListCandidatesAsync(request.Selection, 0, 100, ct)).Single(c => c.EntryKind == EntryKind.Tagged);
var nothing = await bed.Service.StartAsync(new ExportJobRequest(new ExportSelection.Media([tagged.MediaId, waiting.Stored.Media[0].Id])), ct);
Assert.IsEmpty(nothing.Runs);
Assert.AreEqual((1, 1), (nothing.Plan.NotExported, nothing.Plan.Missing));
Assert.IsFalse(bed.Service.IsBusy);
Assert.HasCount(1, await bed.Db.Exports.ListRunsAsync(ct));
// An already copied file still makes a job, for its report: «Già copiato», and nothing written.
var copied = await bed.CopyAsync(new ExportJobRequest(new ExportSelection.Media([post.Media[0].Id])), ct);
Assert.AreEqual(ExportItemState.AlreadyCopied, (await bed.ItemsAsync(copied.Runs.Single().Id, ct)).Single().State);
Assert.HasCount(1, Fingerprint.Of(bed.Usb));
}
[TestMethod]
[DataRow(true, DisplayName = "dichiarato, senza montaggio")]
[DataRow(false, DisplayName = "non dichiarato")]
public async Task DockerNotMountedWritesNothing(bool declared)
{
var ct = TestContext.CancellationToken;
string? root = null;
await using var bed = await ExportTestBed.CreateAsync(env =>
{
root = Path.Combine(Path.GetDirectoryName(env.DataFolder)!, "esporta");
return env with { Root = ExportRootOptions.Docker(root, declared, new FixedMounts()) with { ShownAs = "/esporta" } };
});
var usb = Path.Combine(root!, "usb");
Directory.CreateDirectory(usb);
await File.WriteAllTextAsync(Path.Combine(usb, "già qui.txt"), "di Alberto", ct);
var files = Fingerprint.Of(root!);
await bed.PostAsync(bed.Marta, "1002", 89);
// A destination recorded when the folder was mounted; now the container runs without it.
var destination = await bed.Db.Exports.AddDestinationAsync(Data.ExportWorld.Destination(ExportScope.General, null, usb), ct);
var state = ExportRoots.Evaluate(bed.Environment.Root);
Assert.IsFalse(state.Active);
var plan = await bed.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct);
Assert.IsNotNull(plan.Destinations.Single().Problem);
var start = await bed.CopyAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct);
var run = await bed.RunAsync(start.Runs.Single().Id, ct);
Assert.AreEqual(ExportRunState.Paused, run.State);
Assert.AreEqual(state.Problem, run.LastError);
Assert.AreEqual(declared, run.LastError != ExportRoots.NotDeclaredText);
Assert.AreEqual(ExportItemState.Pending, (await bed.ItemsAsync(run.Id, ct)).Single().State);
Assert.IsNotNull((await bed.Db.Exports.GetDestinationAsync(destination.Id, ct))!.PausedAt);
Assert.IsEmpty(await bed.Db.Exports.ListCopiesAsync(destination.Id, ct: ct));
Fingerprint.AreEqual(files, Fingerprint.Of(root!), "not a byte in /esporta, not even the probe file");
// «Controlla le copie» and «Riprova» write nothing either.
Assert.IsNotNull((await bed.Service.RetryDestinationAsync(destination.Id, ct)).Problem);
await bed.Service.CheckCopiesAsync(destination.Id, ct);
await bed.Service.WaitAsync(ct);
Fingerprint.AreEqual(files, Fingerprint.Of(root!), "the checks write nothing");
Assert.AreEqual(ExportRunState.Paused, (await bed.RunAsync(run.Id, ct)).State);
}
private static bool SecondFile(string path) => path.EndsWith("_2.jpg", StringComparison.Ordinal);
private static ExportItem Pending(long runId, Media media, long accountId) => new()
{
RunId = runId,
MediaId = media.Id,
AccountId = accountId,
SourceSha256 = media.Sha256,
Variant = ExportVariant.Whole,
Format = ExportFormat.Original,
State = ExportItemState.Pending,
};
private async Task<ExportProgress> PollAsync(ExportTestBed bed, Func<ExportProgress, bool> until, CancellationToken ct)
{
var deadline = DateTime.UtcNow + Patience;
while (true)
{
var progress = await bed.Service.GetProgressAsync(ct);
if (until(progress))
{
return progress;
}
Assert.IsLessThan(deadline, DateTime.UtcNow, $"never reached; last phase {progress.Phase}");
await Task.Delay(10, ct);
}
}
private static async Task PollUntilAsync(Func<bool> until, CancellationToken ct)
{
var deadline = DateTime.UtcNow + Patience;
while (!until())
{
Assert.IsLessThan(deadline, DateTime.UtcNow, "never reached");
await Task.Delay(10, ct);
}
}
}