Files
Febe/tests/Febe.Tests/Export/ExportFoundationTests.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

173 lines
9.7 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 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);
}
}