Files
Febe/tests/Febe.Tests/Export/ExportFoundationTests.cs
T
Alby96andClaude Opus 5.5 724c5bda6f E3: conversione della libreria in sottofondo con righe sempre vere
La libreria può ora tenere accanto a ogni originale una copia nel
formato scelto, preparata in sottofondo senza mai sostituire o
cancellare l'originale.

- LongWorkGate ha un permesso di sottofondo che il lavoro in primo
  piano (importazione, copie, ricostruzione) interrompe; il
  salvataggio in corso si aspetta al più CommitWait.
- La coda e il lavoratore: nuovi file accodati all'arrivo, quelli già
  in libreria solo su richiesta, pausa, nuovo tentativo, attesa
  durante una sessione del motore o con poco spazio, nomi liberi e
  adozione di un file identico già presente.
- Le righe di media_conversion restano vere in ogni via: eliminazione
  (Ricorda e Consenti il ritorno, con RemoveWithConversionsAsync per
  il vincolo RESTRICT), perdente del ripasso dei doppioni, file
  cambiato (superate e riaccodate), ricostruzione (conta e riconosce
  i convertiti, accoda solo Pending), importazione (una copia
  convertita o un fotogramma non rientra come file nuovo).
- FebeApp avvia il lavoratore con InBackground; la demo mai.
  _febe.jsonl non cambia.

La prova RecordsCannotBeDeletedFromUnderTheirCopies usa ora una riga
Converted: RemoveAsync toglie da sé le righe senza file, e il vincolo
si verifica sia in SQL sia attraverso il magazzino.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 23:57:48 +01:00

246 lines
13 KiB
C#

using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Import;
using Febe.Core.Library;
using Febe.Tests.Import.Support;
using Febe.Tests.Support;
namespace Febe.Tests.Export;
/// <summary>
/// The shared pieces of tappa E2 (WP1a): the gate of long work, the mount table, the export root in Docker, the folder
/// check with its probe, the destinations with «Esporta questo account» on by default. WP5 adds the full set.
/// </summary>
[TestClass]
public sealed class ExportFoundationTests
{
public TestContext TestContext { get; set; } = null!;
[TestMethod]
public void TheGateLetsOneLongJobRunAtATime()
{
var gate = new LongWorkGate();
Assert.IsTrue(gate.TryEnter(LongWorkKind.Import, out var lease, out _));
Assert.AreEqual(LongWorkKind.Import, gate.Busy);
Assert.IsFalse(gate.TryEnter(LongWorkKind.Export, out _, out var busy));
Assert.AreEqual(LongWorkKind.Import, busy);
Assert.AreEqual(
"C'è un'importazione al lavoro: aspetta che finisca o interrompila, poi copia.",
LongWorkGate.BusyMessage(LongWorkKind.Export, busy!.Value));
lease.Dispose();
Assert.IsNull(gate.Busy);
Assert.IsTrue(gate.TryEnter(LongWorkKind.Rebuild, out var rebuild, out _));
lease.Dispose(); // a second dispose of the old lease releases nothing
Assert.AreEqual(LongWorkKind.Rebuild, gate.Busy);
rebuild.Dispose();
}
[TestMethod]
public void AForegroundLeasePreemptsTheBackgroundOneAndBusyIgnoresIt()
{
var gate = new LongWorkGate();
Assert.IsTrue(gate.TryEnterBackground(out var background));
Assert.IsNull(gate.Busy, "Busy ignores the background lease");
Assert.IsTrue(gate.BackgroundRunning);
Assert.IsFalse(gate.TryEnterBackground(out _));
Assert.IsTrue(gate.TryEnter(LongWorkKind.Import, out var import, out _));
Assert.IsTrue(background.Preempted.IsCancellationRequested);
Assert.IsTrue(background.IsPreempted);
Assert.IsFalse(background.TryBeginCommit(out _), "no commit once pre-empted");
Assert.IsFalse(gate.BackgroundRunning);
Assert.AreEqual(LongWorkKind.Import, gate.Busy);
background.Dispose();
Assert.IsFalse(gate.TryEnterBackground(out _), "the background waits for the foreground");
import.Dispose();
Assert.IsTrue(gate.TryEnterBackground(out var again));
again.Dispose();
Assert.IsFalse(gate.BackgroundRunning);
Assert.IsTrue(gate.TryEnter(LongWorkKind.Export, out var export, out _));
export.Dispose();
}
[TestMethod]
public async Task AForegroundLeaseWaitsForACommit()
{
var gate = new LongWorkGate();
Assert.IsTrue(gate.TryEnterBackground(out var background));
Assert.IsTrue(background.TryBeginCommit(out var commit));
var entering = Task.Run(() => gate.TryEnter(LongWorkKind.Rebuild, out var lease, out _) ? lease : null, TestContext.CancellationToken);
while (!background.Preempted.IsCancellationRequested)
{
await Task.Yield();
}
Assert.IsFalse(entering.IsCompleted, "the rebuild waits for the commit");
commit.Dispose();
var rebuild = await entering;
Assert.IsNotNull(rebuild);
rebuild.Dispose();
background.Dispose();
// A commit that does not end in time: the foreground job is refused with its own message.
var quick = new LongWorkGate { CommitWait = TimeSpan.FromMilliseconds(20) };
Assert.IsTrue(quick.TryEnterBackground(out var slow));
Assert.IsTrue(slow.TryBeginCommit(out var held));
Assert.IsFalse(quick.TryEnter(LongWorkKind.Export, out _, out var busy));
Assert.AreEqual(LongWorkKind.LibraryConversion, busy);
Assert.IsNull(quick.Busy);
held.Dispose();
slow.Dispose();
}
[TestMethod]
public void NewKindsHaveTheirOwnMessages()
{
Assert.AreEqual(
"La conversione della libreria sta salvando un file: riprova fra un attimo.",
LongWorkGate.BusyMessage(LongWorkKind.Import, LongWorkKind.LibraryConversion));
Assert.AreEqual(
"Si sta preparando uno zip di fotogrammi: aspetta che finisca, poi importa.",
LongWorkGate.BusyMessage(LongWorkKind.Import, LongWorkKind.FrameDownload));
Assert.AreEqual(
"C'è un'importazione al lavoro: aspetta che finisca o interrompila, poi scarica i fotogrammi.",
LongWorkGate.BusyMessage(LongWorkKind.FrameDownload, LongWorkKind.Import));
Assert.AreEqual(
"La ricostruzione del database è in corso: aspetta che finisca.",
LongWorkGate.BusyMessage(LongWorkKind.FrameDownload, LongWorkKind.Rebuild));
}
[TestMethod]
public async Task AnImportDoesNotStartWhileTheGateIsHeld()
{
using var temp = new TempFolder();
await using var bed = await ImportTestBed.CreateAsync(temp);
var gate = new LongWorkGate();
await using var service = new ImportService(bed.Environment with { Gate = gate });
Assert.IsTrue(gate.TryEnter(LongWorkKind.Export, out var lease, out _));
var refused = await Assert.ThrowsExactlyAsync<InvalidOperationException>(() => service.StartAsync(bed.Source, ct: TestContext.CancellationToken));
Assert.StartsWith("C'è una copia nelle cartelle esterne al lavoro", refused.Message);
Assert.IsEmpty(await bed.Library.Db.Imports.ListRunsAsync(TestContext.CancellationToken));
lease.Dispose();
var run = await service.StartAsync(bed.Source, ct: TestContext.CancellationToken);
await service.WaitAsync(run.Id, TestContext.CancellationToken);
Assert.IsNull(gate.Busy); // the job's lease went with it
}
[TestMethod]
public void MountInfoGivesRootMountPointAndType()
{
const string content = """
22 1 8:1 / / rw,relatime shared:1 - ext4 /dev/sda1 rw
40 22 8:17 /backup/foto /esporta/usb rw,noatime master:3 - vfat /dev/sdb1 rw
41 22 0:50 / /esporta/nas\040rete ro,relatime - cifs //nas/copie rw
bad line
""";
var mounts = MountInfoTable.Parse(content);
Assert.HasCount(3, mounts);
Assert.AreEqual("/esporta/nas rete", mounts[2].MountPoint);
Assert.IsTrue(mounts[2].ReadOnly);
Assert.AreEqual("/backup/foto", MountInfoTable.FindContaining(mounts, "/esporta/usb/Febe")!.Root);
Assert.AreEqual("vfat", MountInfoTable.FindContaining(mounts, "/esporta/usb")!.FileSystemType);
Assert.AreEqual("/", MountInfoTable.FindContaining(mounts, "/esporta/usbx")!.MountPoint);
var o = ExportRootOptions.Docker("/esporta", declared: true, new ProcMountInfo(() => content));
Assert.IsFalse(ExportRoots.Evaluate(o with { Declared = false }).Active);
Assert.IsFalse(ExportRoots.Evaluate(ExportRootOptions.Docker("/esporta", declared: true, new ProcMountInfo(() => "22 1 8:1 / / rw - ext4 /dev/sda1 rw"))).Active);
if (!OperatingSystem.IsWindows())
{
// Docker paths are Linux paths: on Windows "/esporta" becomes a drive path the table cannot hold.
Assert.IsTrue(ExportRoots.Evaluate(o).Active);
Assert.IsNull(ExportRoots.MountProblem(o, "/esporta/usb/Febe"));
Assert.Contains("sola lettura", ExportRoots.MountProblem(o, "/esporta/nas rete/x")!);
Assert.IsNotNull(ExportRoots.MountProblem(o, "/esporta/altro"));
}
Assert.AreEqual(ExportFolderProblemKind.ParentSegment, Assert.ThrowsExactly<ExportFolderException>(() => ExportRoots.Resolve(o, "usb/../../etc")).Kind);
Assert.AreEqual(ExportFolderProblemKind.ExportRootItself, Assert.ThrowsExactly<ExportFolderException>(() => ExportRoots.Resolve(o, ".")).Kind);
}
[TestMethod]
public async Task TheFolderCheckRefusesOverlapsAndLeavesNoProbe()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
var library = temp.Combine("libreria");
var data = temp.Combine("dati");
var outside = temp.Combine("copie");
Directory.CreateDirectory(Path.Combine(library, "marta.demo"));
Directory.CreateDirectory(data);
Directory.CreateDirectory(outside);
var context = new ExportFolderContext(
[new(data, ProtectedFolderKind.Data, null), new(library, ProtectedFolderKind.Library, null), new(Path.Combine(library, "marta.demo"), ProtectedFolderKind.Account, "marta.demo")],
ExportRootOptions.AnyFolder);
var check = new ExportFolderCheck(new ProcMountInfo(() => null));
var accepted = await check.CheckAsync(outside, context, ct);
Assert.IsTrue(accepted.Accepted, accepted.Problem?.Message);
Assert.IsEmpty(Directory.GetFileSystemEntries(outside));
Assert.AreEqual(ExportFolderProblemKind.InsideProtected, (await check.CheckAsync(Path.Combine(library, "marta.demo"), context with { Protected = context.Protected.Take(2).ToList() }, ct)).Problem!.Kind);
Assert.AreEqual(ExportFolderProblemKind.SameAsProtected, (await check.CheckAsync(data, context, ct)).Problem!.Kind);
Assert.AreEqual(ExportFolderProblemKind.ContainsProtected, (await check.CheckAsync(temp.Path, context, ct)).Problem!.Kind);
Assert.AreEqual(ExportFolderProblemKind.Missing, (await check.CheckAsync(temp.Combine("non-esiste"), context, ct)).Problem!.Kind);
Assert.AreEqual(ExportFolderProblemKind.NotFullyQualified, (await check.CheckAsync("relativa", context, ct)).Problem!.Kind);
Assert.AreEqual(ExportFolderProblemKind.RootOfDisk, (await check.CheckAsync(Path.GetPathRoot(temp.Path)!, context, ct)).Problem!.Kind);
Assert.IsFalse(Directory.Exists(temp.Combine("non-esiste")));
}
[TestMethod]
public async Task TheSafeWriterNeverCreatesAMissingRoot()
{
using var temp = new TempFolder();
var root = temp.Combine("disco-assente");
using var source = new MemoryStream([1, 2, 3]);
await Assert.ThrowsExactlyAsync<ExportRootMissingException>(() => new SafeFileWriter().SaveAsync(
source, root, "a/b.jpg", new SafeWriteOptions { RequireExistingRoot = true, VerifyFromDisk = true }, TestContext.CancellationToken));
Assert.IsFalse(Directory.Exists(root));
Directory.CreateDirectory(root);
source.Position = 0;
var saved = await new SafeFileWriter().SaveAsync(source, root, "a/b.jpg", new SafeWriteOptions { RequireExistingRoot = true, VerifyFromDisk = true }, TestContext.CancellationToken);
Assert.AreEqual("a/b.jpg", saved.RelativePath);
}
[TestMethod]
public async Task DestinationsAreCheckedAndTheSwitchIsOnByDefault()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
await using var library = await TestLibrary.CreateAsync(temp);
var account = await library.Db.Accounts.AddAsync(Make.Account("marta.demo", "100"), ct);
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) } };
var destinations = new ExportDestinations(env);
var usb = temp.Combine("usb");
Directory.CreateDirectory(usb);
Assert.IsTrue((await destinations.ResolveAsync(account.Id, ct)) is { Enabled: true, HasDestination: false });
await Assert.ThrowsExactlyAsync<ExportFolderException>(() => destinations.CreateAsync(Spec(library.Layout.Root), ct));
await Assert.ThrowsExactlyAsync<ArgumentException>(() => destinations.CreateAsync(Spec(usb) with { ContentTypes = ContentTypes.None }, ct));
await Assert.ThrowsExactlyAsync<ArgumentException>(() => destinations.CreateAsync(Spec(usb) with { NamingScheme = "{inesistente}" }, ct));
var saved = await destinations.CreateAsync(Spec(usb) with { Label = " Disco USB " }, ct);
Assert.AreEqual("Disco USB", saved.Destination.Label);
var all = await destinations.ResolveAllAsync(ct);
Assert.AreEqual(saved.Destination.Id, all[account.Id].Destination!.Id);
Assert.IsTrue(all[account.Id].Exports);
await destinations.SetAccountEnabledAsync(account.Id, false, ct);
Assert.IsFalse((await destinations.ResolveAsync(account.Id, ct)).Exports);
var run = await library.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = saved.Destination.Id, StartedAt = library.Clock.Now }, ct);
await Assert.ThrowsExactlyAsync<InvalidOperationException>(() => destinations.RetireAsync(saved.Destination.Id, ct));
await library.Db.Exports.UpdateRunAsync(run with { State = ExportRunState.Cancelled }, ct);
await destinations.RetireAsync(saved.Destination.Id, ct);
Assert.IsTrue(Directory.Exists(usb));
Assert.IsFalse((await destinations.ResolveAsync(account.Id, ct)).HasDestination);
Assert.IsEmpty(await destinations.RecheckAsync(null, ct));
static DestinationSpec Spec(string path) => new(ExportScope.General, null, path, null, ContentTypes.All, null, null, null);
}
}