|
| 1 | +// File: PeaceDatabase.Tests/FileDocumentServicePersistenceTests.cs |
| 2 | +using System; |
| 3 | +using System.IO; |
| 4 | +using System.Linq; |
| 5 | +using System.Net; |
| 6 | +using System.Net.Http.Json; |
| 7 | +using System.Runtime.InteropServices; |
| 8 | +using System.Threading.Tasks; |
| 9 | +using FluentAssertions; |
| 10 | +using Microsoft.AspNetCore.Mvc.Testing; |
| 11 | +using Microsoft.Extensions.DependencyInjection; |
| 12 | +using PeaceDatabase.Core.Models; |
| 13 | +using PeaceDatabase.Core.Services; |
| 14 | +using PeaceDatabase.Storage.Disk; |
| 15 | +using PeaceDatabase.Storage.Disk.Internals; |
| 16 | +using Xunit; |
| 17 | + |
| 18 | +namespace PeaceDatabase.Tests |
| 19 | +{ |
| 20 | + public class FileDocumentServicePersistenceTests : IAsyncLifetime |
| 21 | + { |
| 22 | + private readonly string _rootDir; |
| 23 | + private readonly StorageOptions _opts; |
| 24 | + private static string? AsString(object? v) |
| 25 | + { |
| 26 | + if (v is null) return null; |
| 27 | + if (v is string s) return s; |
| 28 | + if (v is System.Text.Json.JsonElement je) |
| 29 | + { |
| 30 | + return je.ValueKind switch |
| 31 | + { |
| 32 | + System.Text.Json.JsonValueKind.String => je.GetString(), |
| 33 | + System.Text.Json.JsonValueKind.Number => je.GetRawText(), // "123" |
| 34 | + _ => je.ToString() |
| 35 | + }; |
| 36 | + } |
| 37 | + return v.ToString(); |
| 38 | + } |
| 39 | + public FileDocumentServicePersistenceTests() |
| 40 | + { |
| 41 | + _rootDir = Path.Combine(Path.GetTempPath(), "peace-db-tests", Guid.NewGuid().ToString("N")); |
| 42 | + _opts = new StorageOptions |
| 43 | + { |
| 44 | + DataRoot = _rootDir, |
| 45 | + EnableSnapshots = true, |
| 46 | + SnapshotEveryNOperations = 3, // понижен порог, чтобы точно случился снапшот |
| 47 | + SnapshotMaxWalSizeMb = 1, |
| 48 | + Durability = DurabilityLevel.Commit |
| 49 | + }; |
| 50 | + } |
| 51 | + |
| 52 | + public Task InitializeAsync() => Task.CompletedTask; |
| 53 | + |
| 54 | + public Task DisposeAsync() |
| 55 | + { |
| 56 | + try { if (Directory.Exists(_rootDir)) Directory.Delete(_rootDir, recursive: true); } catch { } |
| 57 | + return Task.CompletedTask; |
| 58 | + } |
| 59 | + |
| 60 | + [Fact] |
| 61 | + public void Persistence_WritesSnapshot_And_Manifest_And_Reloads() |
| 62 | + { |
| 63 | + var db = "t_persist"; |
| 64 | + |
| 65 | + // 1) Первый запуск: создаём сервис, пишем данные |
| 66 | + using (var svc = new FileDocumentService(_opts)) |
| 67 | + { |
| 68 | + var r1 = svc.CreateDb(db); |
| 69 | + r1.Ok.Should().BeTrue(); |
| 70 | + |
| 71 | + // 3 операции => должен сработать триггер снапшота |
| 72 | + var d1 = new Document { Id = "a1", Data = new() { ["name"] = "Alpha" } }; |
| 73 | + var p1 = svc.Post(db, d1); |
| 74 | + p1.Ok.Should().BeTrue(); |
| 75 | + |
| 76 | + var d2 = new Document { Id = "a2", Data = new() { ["name"] = "Beta" } }; |
| 77 | + var p2 = svc.Post(db, d2); |
| 78 | + p2.Ok.Should().BeTrue(); |
| 79 | + |
| 80 | + var g1 = svc.Get(db, "a1"); |
| 81 | + g1.Should().NotBeNull(); |
| 82 | + var upd = new Document { Id = g1!.Id, Rev = g1.Rev, Data = new() { ["name"] = "Alpha v2" } }; |
| 83 | + var u1 = svc.Put(db, upd); |
| 84 | + u1.Ok.Should().BeTrue(); |
| 85 | + |
| 86 | + // Проверки файлов на диске |
| 87 | + var dbDir = Path.Combine(_rootDir, db); |
| 88 | + Directory.Exists(dbDir).Should().BeTrue(); |
| 89 | + File.Exists(Path.Combine(dbDir, _opts.ManifestFileName)).Should().BeTrue(); |
| 90 | + Directory.EnumerateFiles(dbDir, $"{_opts.SnapshotPrefix}*{_opts.SnapshotExt}").Any().Should().BeTrue("snapshot must be created"); |
| 91 | + File.Exists(Path.Combine(dbDir, _opts.WalFileName)).Should().BeTrue(); |
| 92 | + } // dispose |
| 93 | + |
| 94 | + // 2) Второй запуск: сервис должен восстановить состояние из snapshot + wal |
| 95 | + using (var svc2 = new FileDocumentService(_opts)) |
| 96 | + { |
| 97 | + var all = svc2.AllDocs(db).ToList(); |
| 98 | + all.Should().ContainSingle(x => x.Id == "a1" && AsString(x.Data!["name"]) == "Alpha v2"); |
| 99 | + all.Should().ContainSingle(x => x.Id == "a2" && AsString(x.Data!["name"]) == "Beta"); |
| 100 | + |
| 101 | + // seq должен быть > 0 (загружен из manifest или доигран из WAL) |
| 102 | + svc2.Seq(db).Should().BeGreaterThan(0); |
| 103 | + } |
| 104 | + } |
| 105 | + |
| 106 | + [Fact] |
| 107 | + public async Task Api_Smoke_Uses_FileDocumentService_DI_And_Returns_Stats() |
| 108 | + { |
| 109 | + // Настраиваем тестовый хост так, чтобы WebAPI использовал FileDocumentService с нашим data-root |
| 110 | + await using var app = new TestApiFactory(_opts); |
| 111 | + var client = app.CreateClient(); |
| 112 | + |
| 113 | + // Просто дымовая проверка, что эндпоинт жив |
| 114 | + var resp = await client.GetAsync("/v1/_stats"); |
| 115 | + resp.StatusCode.Should().Be(HttpStatusCode.OK); |
| 116 | + |
| 117 | + // Создадим базу и документ через DI (напрямую) |
| 118 | + using var scope = app.Services.CreateScope(); |
| 119 | + var svc = scope.ServiceProvider.GetRequiredService<IDocumentService>(); |
| 120 | + |
| 121 | + var r = svc.CreateDb("api_db"); |
| 122 | + r.Ok.Should().BeTrue(); |
| 123 | + |
| 124 | + var p = svc.Post("api_db", new Document { Id = "x1", Data = new() { ["v"] = 1 } }); |
| 125 | + p.Ok.Should().BeTrue(); |
| 126 | + |
| 127 | + // ещё одна проверка HTTP – если есть контроллеры для чтения, можно добавить: |
| 128 | + // var docResp = await client.GetAsync("/v1/doc/api_db/x1"); |
| 129 | + // docResp.StatusCode.Should().Be(HttpStatusCode.OK); |
| 130 | + } |
| 131 | + |
| 132 | + // using System.Runtime.InteropServices; |
| 133 | + // using FluentAssertions; |
| 134 | + |
| 135 | + [Fact(DisplayName = "Open DB folder in OS file explorer (opt-in)")] |
| 136 | + public void Open_Db_Folder_In_FileExplorer() |
| 137 | + { |
| 138 | + // По умолчанию просто выходим — тест пройдёт молча |
| 139 | + var wantOpen = Environment.GetEnvironmentVariable("OPEN_DB_EXPLORER") == "1"; |
| 140 | + if (!wantOpen) return; |
| 141 | + |
| 142 | + var db = "open_me"; |
| 143 | + var root = Path.Combine(Path.GetTempPath(), "peace-db-tests", "manual-open"); |
| 144 | + var opts = new StorageOptions { DataRoot = root, EnableSnapshots = true }; |
| 145 | + |
| 146 | + using (var svc = new FileDocumentService(opts)) |
| 147 | + { |
| 148 | + svc.CreateDb(db); |
| 149 | + svc.Post(db, new Document { Id = "show", Data = new() { ["k"] = "v" } }); |
| 150 | + } |
| 151 | + |
| 152 | + var dbDir = Path.Combine(root, db); |
| 153 | + Directory.Exists(dbDir).Should().BeTrue(); |
| 154 | + |
| 155 | + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) |
| 156 | + { |
| 157 | + System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo("explorer.exe", $"\"{dbDir}\"") |
| 158 | + { UseShellExecute = true }); |
| 159 | + } |
| 160 | + else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) |
| 161 | + { |
| 162 | + System.Diagnostics.Process.Start("open", dbDir); |
| 163 | + } |
| 164 | + else |
| 165 | + { |
| 166 | + System.Diagnostics.Process.Start("xdg-open", dbDir); |
| 167 | + } |
| 168 | + } |
| 169 | + |
| 170 | + // ---- Test host that injects FileDocumentService into WebAPI ---- |
| 171 | + private sealed class TestApiFactory : WebApplicationFactory<Program>, IAsyncDisposable |
| 172 | + { |
| 173 | + private readonly StorageOptions _options; |
| 174 | + public TestApiFactory(StorageOptions options) => _options = options; |
| 175 | + |
| 176 | + protected override void ConfigureWebHost(Microsoft.AspNetCore.Hosting.IWebHostBuilder builder) |
| 177 | + { |
| 178 | + builder.ConfigureServices(services => |
| 179 | + { |
| 180 | + // Снести любую регистрацию IDocumentService (InMemory) и поставить FileDocumentService |
| 181 | + var desc = services.SingleOrDefault(d => d.ServiceType == typeof(IDocumentService)); |
| 182 | + if (desc != null) services.Remove(desc); |
| 183 | + |
| 184 | + services.AddSingleton<IDocumentService>(_ => new FileDocumentService(_options)); |
| 185 | + }); |
| 186 | + } |
| 187 | + } |
| 188 | + } |
| 189 | +} |
0 commit comments