The tournament of Phase 13 needs many trials to run on more than one thread and to survive a restart without redoing finished work. The judge was one monolithic call on one thread, so a restart redid the whole trial. TrialRunner.Run is now Judge(Variants()): Variants does every engine execution as a keyed unit in two stages (grid and outside-grid run, then, after the plateau choice, costed runs, benchmark and look-ahead), and Judge is the old pure judging code working on runs assembled by key. Both Run overloads keep their signatures; on one thread the engine is called in the order of today, and the three golden reports do not move. The single low-priority worker becomes a pool of N threads (setting laboratory.workers, default 1, at most one less than the processors, shown in Impostazioni > Sistema). The Laboratory records each unit in the new tournament_units table (migration 0016, which also creates tournaments for the next part of the phase): claimed as running, then done with the gzip of its run. A resumed trial drops its running units, reloads the done ones and runs only the rest; a run reloaded from storage gives the same report byte for byte. Plain trials drop their unit outcomes when they finish or fail. The pool no longer disposes its queue while a thread may still read it. refs #122 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
371 lines
21 KiB
C#
371 lines
21 KiB
C#
using Anubis.Core;
|
|
using Anubis.Db;
|
|
using Anubis.Platform;
|
|
|
|
namespace Anubis.Tests;
|
|
|
|
/// <summary>Export, import and backups (issue #9, SPEC 5.4).</summary>
|
|
[TestClass]
|
|
public sealed class ArchiveTests
|
|
{
|
|
private static readonly ManualClock _clock = new(new DateTimeOffset(2026, 10, 9, 6, 21, 0, TimeSpan.Zero));
|
|
|
|
/// <summary>Fills a database with rows of every column kind, including accounting rows and a reversal.</summary>
|
|
internal static async Task SeedAsync(Database db)
|
|
{
|
|
var (account, instrument) = await DatabaseTests.SeedAccountAsync(db).ConfigureAwait(false);
|
|
await db.WriteAsync(async s =>
|
|
{
|
|
var fill = Guid.CreateVersion7(_clock.UtcNow.AddSeconds(1));
|
|
var reversal = Guid.CreateVersion7(_clock.UtcNow.AddSeconds(2));
|
|
await s.ExecuteAsync(
|
|
"INSERT INTO fills (id, account_id, instrument_id, execution_id, side, quantity, price, fee, fee_currency, executed_at, created_at) VALUES (@id, @a, @i, 'EX-1', 'buy', @q, @p, @f, 'EUR', @t, @t)",
|
|
("id", fill), ("a", account), ("i", instrument), ("q", 0.0182m), ("p", 68950m), ("f", 1.254890000000000001m), ("t", _clock.UtcNow)).ConfigureAwait(false);
|
|
await s.ExecuteAsync(
|
|
"INSERT INTO fills (id, account_id, instrument_id, execution_id, side, quantity, price, fee, fee_currency, reverses_id, executed_at, created_at) VALUES (@id, @a, @i, 'EX-1-R', 'buy', @q, @p, @f, 'EUR', @r, @t, @t)",
|
|
("id", reversal), ("a", account), ("i", instrument), ("q", -0.0182m), ("p", 68950m), ("f", -1.254890000000000001m), ("r", fill), ("t", _clock.UtcNow)).ConfigureAwait(false);
|
|
for (var i = 0; i < 25; i++)
|
|
{
|
|
await s.ExecuteAsync("INSERT INTO cash_ledger (id, account_id, currency, amount, kind, note, occurred_at, created_at) VALUES (@id, @a, 'EUR', @v, 'deposit', @n, @t, @t)",
|
|
("id", Guid.CreateVersion7(_clock.UtcNow.AddSeconds(10 + i))), ("a", account), ("v", 100.01m * i - 333.333333333333333333m), ("n", i % 3 == 0 ? null : "nota \"" + i + "\" ;\n"),
|
|
("t", _clock.UtcNow.AddDays(-i))).ConfigureAwait(false);
|
|
}
|
|
|
|
await s.ExecuteAsync("INSERT INTO journal (id, occurred_at, kind, code, message, data, created_at) VALUES (@id, @t, 'Ordini', 'stop_raised', @m, @d, @t)",
|
|
("id", Guid.CreateVersion7(_clock.UtcNow)), ("t", _clock.UtcNow), ("m", "Alzato lo stop di BTC/EUR da 65.400 € a 66.180 €."), ("d", new DbJson("{\"from\": \"65400\", \"to\": \"66180\"}"))).ConfigureAwait(false);
|
|
await s.ExecuteAsync("INSERT INTO users (id, username, password_hash, must_change_password, totp_secret, created_at, updated_at) VALUES (@id, 'admin', 'h', @m, @s, @t, @t)",
|
|
("id", Guid.CreateVersion7(_clock.UtcNow)), ("m", true), ("s", new byte[] { 0, 1, 2, 255 }), ("t", _clock.UtcNow)).ConfigureAwait(false);
|
|
|
|
// A tournament, one of its trials and a unit with its outcome: JSON, bytes and a measure across engines (Phase 13).
|
|
var tournament = Guid.CreateVersion7(_clock.UtcNow.AddSeconds(40));
|
|
var trial = Guid.CreateVersion7(_clock.UtcNow.AddSeconds(41));
|
|
await s.ExecuteAsync(
|
|
"INSERT INTO tournaments (id, name, plan, plan_hash, status, finalists, created_at, started_at) VALUES (@id, 'Campionato', @p, 'abc', 'running', @f, @t, @t)",
|
|
("id", tournament), ("p", new DbJson("{\"name\": \"Campionato\", \"cost_multipliers\": [1, 2, 3]}")), ("f", new DbJson("[\"a\", \"b\"]")),
|
|
("t", _clock.UtcNow)).ConfigureAwait(false);
|
|
await s.ExecuteAsync(
|
|
"INSERT INTO backtest_trials (id, strategy, strategy_version, plan, plan_hash, variants, status, created_at, tournament_id) VALUES (@id, 'sma_cross', '1', @p, 'def', 4, 'running', @t, @tour)",
|
|
("id", trial), ("p", new DbJson("{\"strategy\": \"sma_cross\"}")), ("t", _clock.UtcNow), ("tour", tournament)).ConfigureAwait(false);
|
|
await s.ExecuteAsync(
|
|
"INSERT INTO tournament_units (id, trial_id, tournament_id, unit_key, kind, status, outcome, seconds, created_at, finished_at) VALUES (@id, @tr, @tour, 'variant:0:fast=5;slow=20:x1', 'variant', 'done', @o, @sec, @t, @t)",
|
|
("id", Guid.CreateVersion7(_clock.UtcNow.AddSeconds(42))), ("tr", trial), ("tour", tournament), ("o", new byte[] { 31, 139, 8, 0, 255, 0 }), ("sec", 0.1234567890123),
|
|
("t", _clock.UtcNow)).ConfigureAwait(false);
|
|
}).ConfigureAwait(false);
|
|
}
|
|
|
|
[TestMethod]
|
|
[TestCategory(Category.Integration)]
|
|
public async Task ExportThenImportOnTheSameEngineKeepsEverything()
|
|
{
|
|
await using var source = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
|
|
await using var target = await TestDb.CreateAsync().ConfigureAwait(false);
|
|
await RoundTripAsync(source, target).ConfigureAwait(false);
|
|
}
|
|
|
|
[TestMethod]
|
|
[TestCategory(Category.Integration)]
|
|
public async Task ExportFromOneEngineImportsIntoTheOtherWithSameCountsAndTotals()
|
|
{
|
|
if (!await TestDb.PostgresAvailableAsync().ConfigureAwait(false))
|
|
{
|
|
Assert.Inconclusive("PostgreSQL per i test non raggiungibile: la prova tra motori gira in CI e con `tasks ci`.");
|
|
}
|
|
|
|
foreach (var (from, to) in new[] { (DbEngine.Sqlite, DbEngine.Postgres), (DbEngine.Postgres, DbEngine.Sqlite) })
|
|
{
|
|
await using var source = await TestDb.CreateAsync(from).ConfigureAwait(false);
|
|
await Migrations.MigrateAsync(source.Db, _clock, null, CancellationToken.None).ConfigureAwait(false);
|
|
await using var target = await TestDb.CreateAsync(to).ConfigureAwait(false);
|
|
await RoundTripAsync(source, target).ConfigureAwait(false);
|
|
}
|
|
}
|
|
|
|
private static async Task RoundTripAsync(TestDb source, TestDb target)
|
|
{
|
|
await SeedAsync(source.Db).ConfigureAwait(false);
|
|
var folder = TempFolder.Create("archive");
|
|
try
|
|
{
|
|
var index = await Archive.ExportAsync(source.Db, Path.Combine(folder, "a"), _clock).ConfigureAwait(false);
|
|
Assert.AreEqual(Migrations.Latest, index.SchemaVersion);
|
|
Assert.AreEqual(2L, index.Tables.Single(t => t.Name == "fills").Count);
|
|
Assert.AreEqual("0", index.AccountingTotals["fills.quantity"], "il fill e il suo storno si annullano");
|
|
|
|
await Archive.ImportAsync(target.Db, Path.Combine(folder, "a"), _clock).ConfigureAwait(false);
|
|
|
|
CollectionAssert.AreEquivalent(
|
|
(await Archive.CountsAsync(source.Db).ConfigureAwait(false)).ToList(),
|
|
(await Archive.CountsAsync(target.Db).ConfigureAwait(false)).ToList(), $"{source.Db.Engine} → {target.Db.Engine}");
|
|
CollectionAssert.AreEquivalent(
|
|
(await Archive.AccountingTotalsAsync(source.Db).ConfigureAwait(false)).ToList(),
|
|
(await Archive.AccountingTotalsAsync(target.Db).ConfigureAwait(false)).ToList());
|
|
|
|
// A second export of the target is identical row by row.
|
|
await Archive.ExportAsync(target.Db, Path.Combine(folder, "b"), _clock).ConfigureAwait(false);
|
|
foreach (var table in Schema.Tables)
|
|
{
|
|
CollectionAssert.AreEqual(
|
|
File.ReadAllLines(Path.Combine(folder, "a", table.Name + ".jsonl")),
|
|
File.ReadAllLines(Path.Combine(folder, "b", table.Name + ".jsonl")), table.Name);
|
|
}
|
|
}
|
|
finally
|
|
{
|
|
TempFolder.Delete(folder);
|
|
}
|
|
}
|
|
|
|
[TestMethod]
|
|
[TestCategory(Category.Integration)]
|
|
public async Task ImportRefusesANonEmptyDatabaseAndATamperedArchive()
|
|
{
|
|
await using var source = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
|
|
await SeedAsync(source.Db).ConfigureAwait(false);
|
|
var folder = TempFolder.Create("archive-bad");
|
|
try
|
|
{
|
|
await Archive.ExportAsync(source.Db, Path.Combine(folder, "a"), _clock).ConfigureAwait(false);
|
|
await Assert.ThrowsAsync<InvalidOperationException>(() => Archive.ImportAsync(source.Db, Path.Combine(folder, "a"), _clock)).ConfigureAwait(false);
|
|
|
|
var cash = Path.Combine(folder, "a", "cash_ledger.jsonl");
|
|
var lines = File.ReadAllLines(cash);
|
|
File.WriteAllLines(cash, lines.Skip(1));
|
|
await using var target = await TestDb.CreateAsync().ConfigureAwait(false);
|
|
await Assert.ThrowsAsync<InvalidDataException>(() => Archive.ImportAsync(target.Db, Path.Combine(folder, "a"), _clock)).ConfigureAwait(false);
|
|
Assert.IsEmpty(await Archive.CountsAsync(target.Db).ConfigureAwait(false), "un archivio guasto non lascia nemmeno lo schema");
|
|
|
|
await Assert.ThrowsAsync<IOException>(() => Archive.ExportAsync(source.Db, Path.Combine(folder, "a"), _clock)).ConfigureAwait(false);
|
|
}
|
|
finally
|
|
{
|
|
TempFolder.Delete(folder);
|
|
}
|
|
}
|
|
|
|
[TestMethod]
|
|
[TestCategory(Category.Integration)]
|
|
public async Task BackupsKeepTheLastFourteenAndCopyTheSqliteFile()
|
|
{
|
|
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
|
|
await SeedAsync(test.Db).ConfigureAwait(false);
|
|
var folder = TempFolder.Create("backups");
|
|
try
|
|
{
|
|
var clock = new ManualClock(_clock.UtcNow);
|
|
var backups = new Backups(new DataDirectory(folder), clock);
|
|
for (var i = 0; i < 16; i++)
|
|
{
|
|
await backups.TakeAsync(test.Db, "notturno").ConfigureAwait(false);
|
|
clock.Advance(TimeSpan.FromDays(1));
|
|
}
|
|
|
|
var list = backups.List();
|
|
Assert.HasCount(Backups.Keep, list);
|
|
Assert.AreEqual(clock.UtcNow.AddDays(-1).Date, list[0].TakenAt.UtcDateTime.Date, "la più recente è la prima");
|
|
Assert.AreEqual(test.Db.Engine == DbEngine.Sqlite, list[0].HasSqliteCopy);
|
|
Assert.IsFalse(Directory.EnumerateDirectories(folder, "*", SearchOption.AllDirectories).Any(d => d.EndsWith(".partial", StringComparison.Ordinal)));
|
|
|
|
if (test.Db.Engine == DbEngine.Sqlite)
|
|
{
|
|
// The copy made with the backup API opens and has the same rows.
|
|
await using var copy = Database.Open(new DbSettings { Engine = DbEngine.Sqlite, SqlitePath = Path.Combine(list[0].Folder, Backups.SqliteCopy) }, allowCreate: false);
|
|
CollectionAssert.AreEquivalent((await Archive.CountsAsync(test.Db).ConfigureAwait(false)).ToList(), (await Archive.CountsAsync(copy).ConfigureAwait(false)).ToList());
|
|
}
|
|
}
|
|
finally
|
|
{
|
|
TempFolder.Delete(folder);
|
|
}
|
|
}
|
|
|
|
[TestMethod]
|
|
[TestCategory(Category.Integration)]
|
|
public async Task MigratingADatabaseWithDataTakesABackupFirst()
|
|
{
|
|
await using var test = await TestDb.CreateAsync().ConfigureAwait(false);
|
|
var calls = 0;
|
|
await Migrations.MigrateAsync(test.Db, _clock, _ =>
|
|
{
|
|
calls++;
|
|
return Task.CompletedTask;
|
|
}, CancellationToken.None).ConfigureAwait(false);
|
|
Assert.AreEqual(0, calls, "un database vuoto non ha nulla da salvare");
|
|
|
|
// A failing backup stops the migration (simulated on an older schema by removing the version row).
|
|
await test.Db.WriteAsync(s => s.ExecuteAsync($"DELETE FROM {Migrations.VersionTable} WHERE version = @v", ("v", Migrations.Latest))).ConfigureAwait(false);
|
|
if (Migrations.Latest > 1)
|
|
{
|
|
await Assert.ThrowsAsync<SchemaException>(() => Migrations.MigrateAsync(test.Db, _clock, _ => throw new IOException("disco pieno"), CancellationToken.None)).ConfigureAwait(false);
|
|
}
|
|
}
|
|
|
|
[TestMethod]
|
|
[TestCategory(Category.Integration)]
|
|
public async Task ADamagedArchiveLeavesTheDatabaseUntouchedAndTheGoodOneGoesInAfterwards()
|
|
{
|
|
await using var source = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
|
|
await SeedAsync(source.Db).ConfigureAwait(false);
|
|
var folder = TempFolder.Create("archive-retry");
|
|
try
|
|
{
|
|
var good = Path.Combine(folder, "a");
|
|
await Archive.ExportAsync(source.Db, good, _clock).ConfigureAwait(false);
|
|
await using var target = await TestDb.CreateAsync().ConfigureAwait(false);
|
|
|
|
async Task RefusedAsync(string file, Func<string, string> damage)
|
|
{
|
|
var path = Path.Combine(good, file);
|
|
var before = await File.ReadAllTextAsync(path).ConfigureAwait(false);
|
|
await File.WriteAllTextAsync(path, damage(before)).ConfigureAwait(false);
|
|
try
|
|
{
|
|
await Archive.ImportAsync(target.Db, good, _clock).ConfigureAwait(false);
|
|
Assert.Fail("Accepted: " + file);
|
|
}
|
|
catch (Exception ex) when (Anubis.Server.Forms.IsArchiveProblem(ex))
|
|
{
|
|
}
|
|
|
|
await File.WriteAllTextAsync(path, before).ConfigureAwait(false);
|
|
Assert.IsTrue((await Migrations.StatusAsync(target.Db, CancellationToken.None).ConfigureAwait(false)).IsEmpty, "Not even the schema: " + file);
|
|
}
|
|
|
|
// A row less, a number that is not one, a total that changed, a row that is not an object.
|
|
await RefusedAsync("cash_ledger.jsonl", t => t[(t.IndexOf('\n', StringComparison.Ordinal) + 1)..]).ConfigureAwait(false);
|
|
await RefusedAsync("fills.jsonl", t => t.Replace("68950", "novanta", StringComparison.Ordinal)).ConfigureAwait(false);
|
|
await RefusedAsync("fills.jsonl", t => t.Replace("0.0182", "0.0183", StringComparison.Ordinal).Replace("-0.0183", "-0.0182", StringComparison.Ordinal)).ConfigureAwait(false);
|
|
await RefusedAsync("accounts.jsonl", _ => "[]\n").ConfigureAwait(false);
|
|
|
|
// An index that points outside its folder, or names a table twice.
|
|
await RefusedAsync(Archive.IndexFile, t => t.Replace("\"fills.jsonl\"", "\"../fills.jsonl\"", StringComparison.Ordinal)).ConfigureAwait(false);
|
|
await RefusedAsync(Archive.IndexFile, t => t.Replace("\"fills\"", "\"accounts\"", StringComparison.Ordinal)).ConfigureAwait(false);
|
|
|
|
await Archive.ImportAsync(target.Db, good, _clock).ConfigureAwait(false);
|
|
Assert.AreEqual(2L, (await Archive.CountsAsync(target.Db).ConfigureAwait(false))["fills"]);
|
|
}
|
|
finally
|
|
{
|
|
TempFolder.Delete(folder);
|
|
}
|
|
}
|
|
|
|
[TestMethod]
|
|
[TestCategory(Category.Integration)]
|
|
public async Task AnOlderArchiveGoesInAfterAnImportThatStoppedHalfWay()
|
|
{
|
|
await using var old = await TestDb.CreateAsync().ConfigureAwait(false);
|
|
await Migrations.MigrateAsync(old.Db, _clock, null, CancellationToken.None, upTo: 8).ConfigureAwait(false);
|
|
var folder = TempFolder.Create("archive-old");
|
|
try
|
|
{
|
|
await Archive.ExportAsync(old.Db, Path.Combine(folder, "a"), _clock).ConfigureAwait(false);
|
|
|
|
// The first attempt created the schema of the archive and stopped there (power lost).
|
|
await using var target = await TestDb.CreateAsync().ConfigureAwait(false);
|
|
await Migrations.MigrateAsync(target.Db, _clock, null, CancellationToken.None, upTo: 5).ConfigureAwait(false);
|
|
await Archive.ImportAsync(target.Db, Path.Combine(folder, "a"), _clock).ConfigureAwait(false);
|
|
Assert.AreEqual(Migrations.Latest, (await Migrations.StatusAsync(target.Db, CancellationToken.None).ConfigureAwait(false)).Current);
|
|
}
|
|
finally
|
|
{
|
|
TempFolder.Delete(folder);
|
|
}
|
|
}
|
|
|
|
[TestMethod]
|
|
[TestCategory(Category.Integration)]
|
|
public async Task AnImportIsSealedUntilTheInstallationIsRenewedAndSoIsTheSqliteCopy()
|
|
{
|
|
await using var source = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
|
|
var folder = TempFolder.Create("seal");
|
|
try
|
|
{
|
|
var data = new DataDirectory(Path.Combine(folder, "data"));
|
|
await Installation.CheckAsync(source.Db, data, _clock).ConfigureAwait(false);
|
|
var backup = await new Backups(data, _clock).TakeAsync(source.Db, "a-mano").ConfigureAwait(false);
|
|
|
|
// The same fingerprint as installation.json is in the archive: without the seal the import would be accepted as it is.
|
|
await using var target = await TestDb.CreateAsync().ConfigureAwait(false);
|
|
await Archive.ImportAsync(target.Db, Path.Combine(backup.Folder, Backups.ArchiveFolder), _clock).ConfigureAwait(false);
|
|
Assert.AreEqual(IdentityVerdict.StaleDatabase, (await Installation.CheckAsync(target.Db, data, _clock).ConfigureAwait(false)).Verdict);
|
|
|
|
if (backup.HasSqliteCopy)
|
|
{
|
|
var copy = new DbSettings { Engine = DbEngine.Sqlite, SqlitePath = Path.Combine(backup.Folder, Backups.SqliteCopy) };
|
|
await using var byHand = Database.Open(copy, allowCreate: false);
|
|
Assert.AreEqual(IdentityVerdict.StaleDatabase, (await Installation.CheckAsync(byHand, data, _clock).ConfigureAwait(false)).Verdict);
|
|
Assert.IsTrue((await Installation.ReadRowAsync(byHand).ConfigureAwait(false))!.ProtectedRestart);
|
|
}
|
|
|
|
// Renewed, the new one is accepted and the source becomes the old copy.
|
|
await Installation.RenewAsync(target.Db, data, _clock, "prova").ConfigureAwait(false);
|
|
Assert.AreEqual(IdentityVerdict.Match, (await Installation.CheckAsync(target.Db, data, _clock).ConfigureAwait(false)).Verdict);
|
|
Assert.AreEqual(IdentityVerdict.StaleDatabase, (await Installation.CheckAsync(source.Db, data, _clock).ConfigureAwait(false)).Verdict);
|
|
Assert.AreEqual(Installation.ReadFile(data)!.InstallationId, (await Installation.ReadRowAsync(source.Db).ConfigureAwait(false))!.Id, "The orders of the ledger keep their installation.");
|
|
|
|
// Rows without an installation are never taken for an empty database.
|
|
await SeedAsync(target.Db).ConfigureAwait(false);
|
|
await target.Db.WriteAsync(s => s.ExecuteAsync("DELETE FROM installation")).ConfigureAwait(false);
|
|
Assert.AreEqual(IdentityVerdict.DifferentInstallation, (await Installation.CheckAsync(target.Db, data, _clock).ConfigureAwait(false)).Verdict);
|
|
}
|
|
finally
|
|
{
|
|
TempFolder.Delete(folder);
|
|
}
|
|
}
|
|
|
|
[TestMethod]
|
|
[TestCategory(Category.Integration)]
|
|
public async Task ASeriesOfBackupsOfOneKindNeverPushesOutTheNightlyOnes()
|
|
{
|
|
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
|
|
var folder = TempFolder.Create("kinds");
|
|
try
|
|
{
|
|
var clock = new ManualClock(_clock.UtcNow);
|
|
var data = new DataDirectory(folder);
|
|
var backups = new Backups(data, clock);
|
|
await backups.TakeAsync(test.Db, "notturno").ConfigureAwait(false);
|
|
var left = Directory.CreateDirectory(Path.Combine(data.Backups, "20260901-010101-notturno.partial"));
|
|
left.LastWriteTimeUtc = clock.UtcNow.UtcDateTime.AddDays(-3);
|
|
for (var i = 0; i < Backups.Keep + 3; i++)
|
|
{
|
|
// The same second twice: the second one takes a number.
|
|
await backups.TakeAsync(test.Db, Backups.BeforeMigration).ConfigureAwait(false);
|
|
clock.Advance(TimeSpan.FromSeconds(i % 2));
|
|
}
|
|
|
|
Assert.HasCount(1, backups.List().Where(b => b.Reason == "notturno").ToList());
|
|
Assert.HasCount(Backups.Keep, backups.List().Where(b => b.Reason.StartsWith(Backups.BeforeMigration, StringComparison.Ordinal)).ToList());
|
|
Assert.IsFalse(Directory.Exists(left.FullName), "What a power failure left is cleaned.");
|
|
}
|
|
finally
|
|
{
|
|
TempFolder.Delete(folder);
|
|
}
|
|
}
|
|
|
|
[TestMethod]
|
|
[TestCategory(Category.Integration)]
|
|
public async Task AMigrationThatFailsIsASchemaProblemAndLeavesTheVersionBefore()
|
|
{
|
|
await using var test = await TestDb.CreateAsync().ConfigureAwait(false);
|
|
await Migrations.MigrateAsync(test.Db, _clock, null, CancellationToken.None, upTo: 12).ConfigureAwait(false);
|
|
await test.Db.WriteAsync(s => s.ExecuteAsync("CREATE TABLE cost_estimates (x INTEGER)")).ConfigureAwait(false);
|
|
var backups = 0;
|
|
var error = await Assert.ThrowsExactlyAsync<SchemaException>(() => Migrations.MigrateAsync(test.Db, _clock, _ =>
|
|
{
|
|
backups++;
|
|
return Task.CompletedTask;
|
|
}, CancellationToken.None)).ConfigureAwait(false);
|
|
Assert.Contains("0013", error.Message);
|
|
Assert.AreEqual(1, backups);
|
|
Assert.AreEqual(12, (await Migrations.StatusAsync(test.Db, CancellationToken.None).ConfigureAwait(false)).Current);
|
|
|
|
// Without room for the backup nothing is migrated.
|
|
var full = await Assert.ThrowsExactlyAsync<SchemaException>(() => Migrations.MigrateAsync(test.Db, _clock, _ => throw new IOException("disco pieno"), CancellationToken.None))
|
|
.ConfigureAwait(false);
|
|
Assert.Contains("disco pieno", full.Message);
|
|
}
|
|
}
|