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; /// /// 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. /// [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(() => 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(() => ExportRoots.Resolve(o, "usb/../../etc")).Kind); Assert.AreEqual(ExportFolderProblemKind.ExportRootItself, Assert.ThrowsExactly(() => 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(() => 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(() => destinations.CreateAsync(Spec(library.Layout.Root), ct)); await Assert.ThrowsExactlyAsync(() => destinations.CreateAsync(Spec(usb) with { ContentTypes = ContentTypes.None }, ct)); await Assert.ThrowsExactlyAsync(() => 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(() => 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); } }