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

406 lines
15 KiB
C#

using System.Security.Cryptography;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Library;
using Febe.Core.Storage;
using Febe.Data;
using Febe.Tests.Support;
namespace Febe.Tests.Export.Support;
/// <summary>
/// A real library (database, account folders, files saved as the collection pipeline saves them) in a temporary
/// folder, two accounts, a real destination folder «usb» next to it and the export service with fakes for the disk,
/// the engine session and the mount table (tappa E2, WP5). Nothing outside the temporary folder is ever touched.
/// </summary>
internal sealed class ExportTestBed : IAsyncDisposable
{
private ExportTestBed(TempFolder temp, TestLibrary library, ExportEnvironment env, Account marta, Account luca, FakeExportDisk disk, FakeSessionState session, LongWorkGate gate)
{
Temp = temp;
Library = library;
Environment = env;
Service = new ExportService(env);
Marta = marta;
Luca = luca;
Disk = disk;
Session = session;
Gate = gate;
}
public TempFolder Temp { get; }
public TestLibrary Library { get; }
public FebeDatabase Db => Library.Db;
public ManualClock Clock => Library.Clock;
public ExportEnvironment Environment { get; }
public ExportService Service { get; }
public Account Marta { get; }
public Account Luca { get; }
public FakeExportDisk Disk { get; }
public FakeSessionState Session { get; }
public LongWorkGate Gate { get; }
/// <summary>The folder of the general destination (created, empty).</summary>
public string Usb => Temp.Combine("usb");
/// <summary>
/// A new bed. <paramref name="configure"/> changes the environment (a file system seam, a Docker root…) before the
/// service is built.
/// </summary>
public static async Task<ExportTestBed> CreateAsync(Func<ExportEnvironment, ExportEnvironment>? configure = null)
{
var temp = new TempFolder("export");
var library = await TestLibrary.CreateAsync(temp);
var marta = await library.Db.Accounts.AddAsync(Make.Account("marta.demo", "100"));
var luca = await library.Db.Accounts.AddAsync(Make.Account("luca.demo", "200"));
Directory.CreateDirectory(temp.Combine("usb"));
var disk = new FakeExportDisk();
var session = new FakeSessionState();
var gate = new LongWorkGate();
var env = new ExportEnvironment
{
Storage = library.Db,
Layout = () => library.Layout,
DataFolder = library.Data.Root,
Clock = library.Clock,
Root = ExportRootOptions.AnyFolder with { Mounts = new FixedMounts() },
Disk = disk,
Session = session,
Gate = gate,
};
return new ExportTestBed(temp, library, configure is null ? env : configure(env), marta, luca, disk, session, gate);
}
/// <summary>The general folder at <see cref="Usb"/> (or another folder), every type unless told.</summary>
public async Task<ExportDestination> GeneralAsync(ContentTypes types = ContentTypes.All, string? folder = null, string? scheme = null, CancellationToken ct = default) =>
(await Service.Destinations.CreateAsync(new DestinationSpec(ExportScope.General, null, folder ?? Usb, "Disco USB", types, scheme, null, null), ct)).Destination;
/// <summary>The own folder of an account, created under the temporary folder.</summary>
public async Task<ExportDestination> OwnAsync(Account account, string name, ContentTypes types = ContentTypes.All, CancellationToken ct = default)
{
var folder = Temp.Combine(name);
Directory.CreateDirectory(folder);
return (await Service.Destinations.CreateAsync(new DestinationSpec(ExportScope.Account, account.Id, folder, null, types, null, null, null), ct)).Destination;
}
/// <summary>A post of the account with small photos (distinct scenes give distinct bytes; the same scene the same bytes).</summary>
public Task<EntryWithMedia> PostAsync(Account account, string code, params int[] scenes) =>
Library.SaveAsync(account, Make.Entry(account.Id, code, Make.T0.AddDays(-1)), [.. scenes.Select((s, i) => Photo(i + 1, s))]);
/// <summary>A small photo (fast to encode).</summary>
public static TestFile Photo(int position, int scene) => TestFile.Photo(position, scene, 96, 120);
/// <summary>«Copia in…» and waits for the job to end.</summary>
public async Task<ExportStart> CopyAsync(ExportJobRequest request, CancellationToken ct = default)
{
var start = await Service.StartAsync(request, ct);
await Service.WaitAsync(ct);
return start;
}
/// <summary>«Copia in…» of every file of an account.</summary>
public Task<ExportStart> CopyAccountAsync(Account account, bool copyAgain = false, CancellationToken ct = default) =>
CopyAsync(new ExportJobRequest(new ExportSelection.Account(account.Id), copyAgain), ct);
public async Task<IReadOnlyList<ExportItem>> ItemsAsync(long runId, CancellationToken ct = default) =>
await Db.Exports.ListItemsAsync(new ExportItemQuery { RunId = runId, Limit = 10_000 }, ct);
public async Task<ExportRun> RunAsync(long runId, CancellationToken ct = default) => (await Db.Exports.GetRunAsync(runId, ct))!;
/// <summary>Where a file of the account goes in the general folder «Come la libreria».</summary>
public string GeneralCopy(Account account, Media media) => Path.Combine(Usb, account.Username, LibraryLayout.ToPlatform(media.RelativePath!));
/// <summary>The library file.</summary>
public string LibraryFile(Account account, Media media) => Library.Layout.FullPath(account, media.RelativePath!);
public Task SetSamePostAsync(SamePostCopies value, CancellationToken ct = default) => (ExportSettings.Default with { SamePost = value }).SaveAsync(Db.Settings, ct);
public async ValueTask DisposeAsync()
{
await Service.DisposeAsync();
await Library.DisposeAsync();
Temp.Dispose();
}
}
/// <summary>A disk with settable free space and largest file (null: not measurable, no limit).</summary>
internal sealed class FakeExportDisk(long? free = null, long? max = null) : IExportDisk
{
public long? Free { get; set; } = free;
public long? Max { get; set; } = max;
public long? FreeBytes(string root) => Free;
public long? MaxFileBytes(string root) => Max;
}
/// <summary>An engine session that the test starts and ends.</summary>
internal sealed class FakeSessionState : IEngineSessionState
{
private volatile bool _inSession;
public bool InSession
{
get => _inSession;
set => _inSession = value;
}
}
/// <summary>A clock whose delays really pass a little (so a waiting loop does not spin) and move the time on.</summary>
internal sealed class WaitingClock(IClock inner) : IClock
{
private long _delays;
public DateTimeOffset Now => inner.Now;
public TimeZoneInfo LocalZone => inner.LocalZone;
/// <summary>How many delays were asked.</summary>
public long Delays => Interlocked.Read(ref _delays);
public async Task Delay(TimeSpan time, CancellationToken ct)
{
Interlocked.Increment(ref _delays);
await inner.Delay(time, ct);
await Task.Delay(5, ct);
}
}
/// <summary>A mount table given by the test, on any platform (the longest mount point that holds the path wins).</summary>
internal sealed class FixedMounts(params ExportMount[] mounts) : IExportMounts
{
public ExportMount? FindContaining(string fullPath) =>
mounts.Where(m => ExportPaths.IsSameOrInside(fullPath, m.MountPoint)).OrderByDescending(m => ExportPaths.Trim(m.MountPoint).Length).FirstOrDefault();
public IReadOnlyList<ExportMount> All() => mounts;
}
/// <summary>The real file system, but the first read of a blocked file never ends until the job is cancelled.</summary>
internal sealed class GatedExportFileSystem(Func<string, bool> blocks) : IExportFileSystem
{
private readonly IExportFileSystem _inner = ExportFileSystem.Instance;
/// <summary>Set when a blocked file is opened.</summary>
public TaskCompletionSource Reached { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public Stream OpenRead(string path)
{
var stream = _inner.OpenRead(path);
if (!blocks(path))
{
return stream;
}
Reached.TrySetResult();
return new BlockedStream(stream);
}
public Task<string> ComputeSha256Async(string path, CancellationToken ct) => _inner.ComputeSha256Async(path, ct);
public bool FileExists(string path) => _inner.FileExists(path);
public long? FileLength(string path) => _inner.FileLength(path);
private sealed class BlockedStream(Stream inner) : ReadOnlyStream(inner)
{
public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
{
await Task.Delay(Timeout.Infinite, cancellationToken);
return 0;
}
public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
}
}
/// <summary>
/// The real file system, but reading a held file waits until <see cref="Release"/> (or until the job is cancelled), so
/// a test can look at a job while it runs.
/// </summary>
internal sealed class HeldExportFileSystem(Func<string, bool> holds) : IExportFileSystem
{
private readonly IExportFileSystem _inner = ExportFileSystem.Instance;
private readonly TaskCompletionSource _release = new(TaskCreationOptions.RunContinuationsAsynchronously);
/// <summary>Set when a held file is opened.</summary>
public TaskCompletionSource Reached { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
/// <summary>Lets every held read go on.</summary>
public void Release() => _release.TrySetResult();
public Stream OpenRead(string path)
{
var stream = _inner.OpenRead(path);
if (!holds(path))
{
return stream;
}
Reached.TrySetResult();
return new HeldStream(stream, _release.Task);
}
public Task<string> ComputeSha256Async(string path, CancellationToken ct) => _inner.ComputeSha256Async(path, ct);
public bool FileExists(string path) => _inner.FileExists(path);
public long? FileLength(string path) => _inner.FileLength(path);
private sealed class HeldStream(Stream inner, Task release) : Stream
{
public override bool CanRead => true;
public override bool CanSeek => false;
public override bool CanWrite => false;
public override long Length => inner.Length;
public override long Position { get => inner.Position; set => throw new NotSupportedException(); }
public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
{
await release.WaitAsync(cancellationToken);
return await inner.ReadAsync(buffer, cancellationToken);
}
public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
public override void Flush()
{
}
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
public override void SetLength(long value) => throw new NotSupportedException();
public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
protected override void Dispose(bool disposing)
{
if (disposing)
{
inner.Dispose();
}
base.Dispose(disposing);
}
}
}
/// <summary>The real file system, but reading a chosen library file gives one byte changed (a failing disk or cable).</summary>
internal sealed class CorruptingExportFileSystem(Func<string, bool> corrupts) : IExportFileSystem
{
private readonly IExportFileSystem _inner = ExportFileSystem.Instance;
public Stream OpenRead(string path)
{
var stream = _inner.OpenRead(path);
if (!corrupts(path))
{
return stream;
}
using (stream)
{
using var copy = new MemoryStream();
stream.CopyTo(copy);
var bytes = copy.ToArray();
bytes[bytes.Length / 2] ^= 0x5A;
return new MemoryStream(bytes, writable: false);
}
}
public Task<string> ComputeSha256Async(string path, CancellationToken ct) => _inner.ComputeSha256Async(path, ct);
public bool FileExists(string path) => _inner.FileExists(path);
public long? FileLength(string path) => _inner.FileLength(path);
}
/// <summary>A read-only wrapper stream.</summary>
internal abstract class ReadOnlyStream(Stream inner) : Stream
{
public override bool CanRead => true;
public override bool CanSeek => false;
public override bool CanWrite => false;
public override long Length => inner.Length;
public override long Position { get => inner.Position; set => throw new NotSupportedException(); }
public override void Flush()
{
}
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
public override void SetLength(long value) => throw new NotSupportedException();
public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
protected override void Dispose(bool disposing)
{
if (disposing)
{
inner.Dispose();
}
base.Dispose(disposing);
}
}
/// <summary>Every file of a folder tree (relative path → length and SHA-256): equal before and after means nothing was touched.</summary>
internal static class Fingerprint
{
/// <summary>The fingerprint; files whose name starts with <paramref name="skipPrefix"/> (the open database) are left out.</summary>
public static IReadOnlyDictionary<string, string> Of(string folder, string? skipPrefix = null)
{
var files = new SortedDictionary<string, string>(StringComparer.Ordinal);
if (!Directory.Exists(folder))
{
return files;
}
foreach (var file in Directory.EnumerateFiles(folder, "*", SearchOption.AllDirectories))
{
if (skipPrefix is not null && Path.GetFileName(file).StartsWith(skipPrefix, StringComparison.Ordinal))
{
continue;
}
var bytes = File.ReadAllBytes(file);
files[Path.GetRelativePath(folder, file).Replace('\\', '/')] = $"{bytes.Length}:{Convert.ToHexStringLower(SHA256.HashData(bytes))}";
}
return files;
}
public static void AreEqual(IReadOnlyDictionary<string, string> expected, IReadOnlyDictionary<string, string> actual, string because)
{
CollectionAssert.AreEqual(expected.Keys.ToList(), actual.Keys.ToList(), $"{because}: {string.Join(", ", actual.Keys)}");
foreach (var (path, print) in expected)
{
Assert.AreEqual(print, actual[path], $"{because}: {path}");
}
}
/// <summary>Temporary files of Febe (<c>.febe-*.part</c>: the probe and the writes) anywhere below the folder.</summary>
public static IReadOnlyList<string> Temporaries(string folder) =>
Directory.Exists(folder) ? Directory.GetFiles(folder, SafeFileWriter.TempPrefix + "*", SearchOption.AllDirectories) : [];
}