using System.Runtime.CompilerServices; using Febe.Data; using Febe.Tests.Support; namespace Febe.Tests.Data; /// /// #46: must really close the database, even when the finalizer thread is behind. /// A command left to the garbage collector keeps its SQLite statement until it is finalized; a connection closed /// meanwhile only closes then, and its WAL disappeared under the move of the Data folder. The class runs alone because /// it holds the process-wide finalizer thread for a moment. /// [TestClass] [DoNotParallelize] public sealed class DatabaseCloseTests { public TestContext TestContext { get; set; } = null!; [TestMethod] [Timeout(120_000, CooperativeCancellation = true)] public async Task DisposeClosesTheFilesEvenWhenTheFinalizerIsBehind() { using var temp = new TempFolder(); using var finalizing = new ManualResetEventSlim(); using var release = new ManualResetEventSlim(); var folder = temp.Combine("dati"); try { // Holds the finalizer thread: whatever the next collections queue for finalization waits behind it. BlockTheFinalizer(finalizing, release); GC.Collect(); Assert.IsTrue(finalizing.Wait(TimeSpan.FromSeconds(30), TestContext.CancellationToken), "Il finalizzatore non รจ partito."); var db = await FebeDatabase.OpenAsync(folder, TestContext.CancellationToken); await db.Settings.SetAsync("prova", "1", TestContext.CancellationToken); Assert.AreEqual("1", await db.Settings.GetAsync("prova", TestContext.CancellationToken)); GC.Collect(); // commands nobody disposed are collected now and wait for the finalizer await db.DisposeAsync(); Assert.IsFalse(File.Exists(Path.Combine(folder, "febe.sqlite-wal")), "Il WAL resta dopo la chiusura."); Assert.IsFalse(File.Exists(Path.Combine(folder, "febe.sqlite-shm")), "Il file -shm resta dopo la chiusura."); await using var again = await FebeDatabase.OpenAsync(folder, TestContext.CancellationToken); Assert.AreEqual("1", await again.Settings.GetAsync("prova", TestContext.CancellationToken)); } finally { release.Set(); GC.Collect(); GC.WaitForPendingFinalizers(); } } [MethodImpl(MethodImplOptions.NoInlining)] private static void BlockTheFinalizer(ManualResetEventSlim finalizing, ManualResetEventSlim release) => _ = new FinalizerBlocker(finalizing, release); private sealed class FinalizerBlocker(ManualResetEventSlim finalizing, ManualResetEventSlim release) { ~FinalizerBlocker() { finalizing.Set(); release.Wait(TimeSpan.FromSeconds(30)); // bounded: the finalizer thread never stays blocked for good } } }