Files
Febe/tests/Febe.Tests/Import/ImportServiceTests.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

155 lines
7.8 KiB
C#

using System.Collections.Concurrent;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Import;
using Febe.Tests.Export.Support;
using Febe.Tests.Import.Support;
using Febe.Tests.Support;
namespace Febe.Tests.Import;
[TestClass]
public sealed class ImportServiceTests
{
[TestMethod]
public async Task TheFourStepsRunInTheBackground()
{
using var temp = new TempFolder("importa");
await using var bed = await ImportTestBed.CreateAsync(temp);
await bed.Library.Db.Accounts.AddAsync(Make.Account("marta.demo"));
for (var i = 0; i < 5; i++)
{
bed.Write($"marta.demo/foto-{i}.jpg", ImportTestFiles.Photo(300 + i, 200, 150));
}
await using var service = new ImportService(bed.Environment);
var events = new ConcurrentQueue<ImportProgress>();
service.ProgressChanged += (_, p) => events.Enqueue(p);
var source = service.InspectSource(bed.Source);
Assert.IsTrue(source.CanMove);
var run = await service.StartAsync(bed.Source);
Assert.AreEqual(ImportRunState.Analyzing, run.State);
await Assert.ThrowsAsync<InvalidOperationException>(() => service.StartAsync(bed.Source), "Un lavoro alla volta.");
var analysed = await service.WaitAsync(run.Id);
Assert.AreEqual(ImportRunState.Reviewing, analysed!.State);
Assert.IsNull(service.ActiveRunId);
Assert.IsTrue(events.Any(e => e.Phase == ImportPhase.Finished && e.RunId == run.Id && e.FilesDone == 5));
var review = await service.GetReviewAsync(run.Id);
Assert.AreEqual(5, review.ByOutcome[ImportOutcome.New]);
var plan = await service.GetPlanAsync(run.Id);
Assert.AreEqual("Importa 5 file", plan.ButtonLabel);
await service.StartCopyAsync(run.Id, ImportMode.Copy);
var copied = await service.WaitAsync(run.Id);
Assert.AreEqual(ImportRunState.Completed, copied!.State);
var progress = await service.GetProgressAsync(run.Id);
Assert.AreEqual(ImportPhase.Finished, progress.Phase);
Assert.AreEqual(5, progress.Copied);
Assert.AreEqual(5, (await service.GetReportAsync(run.Id)).Copied);
}
[TestMethod]
public async Task AJobLeftRunningByAStopIsResumed()
{
using var temp = new TempFolder("importa");
await using var bed = await ImportTestBed.CreateAsync(temp);
bed.Write("marta.demo/a.jpg", ImportTestFiles.Photo(310, 200, 150));
var run = await bed.Analyzer.CreateRunAsync(bed.Environment.CreateSources().Inspect(bed.Source));
// Febe stopped while the analysis was running: the state says «in corso» but nothing runs.
await using var service = new ImportService(bed.Environment);
Assert.AreEqual(1, await service.RecoverAsync());
Assert.AreEqual(ImportRunState.AnalysisInterrupted, (await service.GetRunAsync(run.Id))!.State);
await service.ResumeAsync(run.Id);
Assert.AreEqual(ImportRunState.Reviewing, (await service.WaitAsync(run.Id))!.State);
await Assert.ThrowsAsync<InvalidOperationException>(() => service.ResumeAsync(run.Id), "Niente da riprendere.");
}
[TestMethod]
public async Task InterruptStopsTheJobAndKeepsWhatIsDone()
{
using var temp = new TempFolder("importa");
await using var bed = await ImportTestBed.CreateAsync(temp);
for (var i = 0; i < 100; i++)
{
bed.Write($"marta.demo/f{i:000}.png", ImportTestFiles.Png(400 + i, 40, 30));
}
// Files from f080 on cannot be read until the job is stopped: the first group of 64 is done by then.
var gated = new GatedFileSystem(bed.FileSystem, path => string.CompareOrdinal(Path.GetFileName(path), "f080.png") >= 0);
await using var service = new ImportService(bed.Environment with { FileSystem = gated });
var run = await service.StartAsync(bed.Source);
await gated.Reached.Task.WaitAsync(TimeSpan.FromSeconds(60));
await service.InterruptAsync(run.Id);
var stopped = (await service.GetRunAsync(run.Id))!;
Assert.AreEqual(ImportRunState.AnalysisInterrupted, stopped.State);
Assert.IsNull(stopped.LastError);
var summary = await bed.Library.Db.Imports.GetSummaryAsync(run.Id);
Assert.AreEqual(64, summary.ByState[ImportFileState.Analyzed]);
Assert.AreEqual(36, summary.ByState[ImportFileState.Pending]);
var progress = await service.GetProgressAsync(run.Id);
Assert.AreEqual((64, 100), (progress.FilesDone, progress.FilesTotal));
await using var again = new ImportService(bed.Environment);
await again.ResumeAsync(run.Id);
Assert.AreEqual(ImportRunState.Reviewing, (await again.WaitAsync(run.Id))!.State);
Assert.AreEqual(100, (await bed.Library.Db.Imports.GetSummaryAsync(run.Id)).ByState[ImportFileState.Analyzed]);
}
[TestMethod]
public async Task DiscardingAnImportLeavesFilesAlone()
{
using var temp = new TempFolder("importa");
await using var bed = await ImportTestBed.CreateAsync(temp);
await bed.AccountWithPhotoAsync("marta.demo", "1", ImportTestFiles.Photo(320, 800, 600, 92));
bed.Write("marta.demo/simile.jpg", ImportTestFiles.Resized(320, 800, 600, 400, 300, 60));
var before = bed.Fingerprint();
await using var service = new ImportService(bed.Environment);
var run = await service.StartAsync(bed.Source, new ImportAnalysisOptions { StogramHypothesis = true });
await service.WaitAsync(run.Id);
Assert.AreEqual(1, await bed.Library.Db.Duplicates.CountPendingAsync(DuplicateOrigin.Import));
Assert.IsTrue((await service.GetReviewAsync(run.Id)).StogramHypothesis);
await service.DiscardAsync(run.Id);
Assert.IsNull(await service.GetRunAsync(run.Id), "Nulla era stato copiato: l'importazione sparisce.");
Assert.AreEqual(0, await bed.Library.Db.Duplicates.CountPendingAsync(DuplicateOrigin.Import));
Assert.IsNull(await bed.Library.Db.Settings.GetAsync($"importazione.{run.Id}.ipotesi-stogram"));
CollectionAssert.AreEqual(before.ToList(), bed.Fingerprint().ToList());
}
[TestMethod]
public async Task AnImportDoesNotStartWhileAnExportRuns()
{
// A real copy to an external folder holds the gate shared by the import, the export and the rebuild (tappa E2).
var held = new HeldExportFileSystem(path => path.EndsWith("_1.jpg", StringComparison.Ordinal));
await using var export = await ExportTestBed.CreateAsync(env => env with { FileSystem = held });
await export.PostAsync(export.Marta, "700", 1);
await export.GeneralAsync();
await export.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(export.Marta.Id)));
await held.Reached.Task.WaitAsync(TimeSpan.FromSeconds(30));
using var temp = new TempFolder("importa");
await using var bed = await ImportTestBed.CreateAsync(temp);
bed.Write("marta.demo/a.jpg", ImportTestFiles.Photo(330, 200, 150));
await using var service = new ImportService(bed.Environment with { Gate = export.Gate });
var refused = await Assert.ThrowsExactlyAsync<InvalidOperationException>(() => service.StartAsync(bed.Source));
Assert.AreEqual(LongWorkGate.BusyMessage(LongWorkKind.Import, LongWorkKind.Export), refused.Message);
Assert.StartsWith("C'è una copia nelle cartelle esterne al lavoro", refused.Message);
Assert.IsEmpty(await service.ListRunsAsync(), "a refused import records nothing");
// The copy ends: the import starts.
held.Release();
await export.Service.WaitAsync();
Assert.IsNull(export.Gate.Busy);
var run = await service.StartAsync(bed.Source);
Assert.AreEqual(ImportRunState.Reviewing, (await service.WaitAsync(run.Id))!.State);
}
}