Files
Anubis/tests/Anubis.Tests/RestoreServerTests.cs
Alby96andClaude Opus 5.5 76b64ef147 Replay the past of a rebuilt account in its order
What an account did while the bot was off is now written before the splits and
the dividends of those days, once and without acting on it; an attempt cut
halfway is taken up from the same point. Until then the account is not valued
at today's price, the guard keeps the last figures it knew with their time,
and a stop order only cancels what is open. Protective sales of the archive
are not continued, and the rest of a stop that fired in part is sold.

Also the decisions of the phase (ADR 0020), the manuals and the dates under
the equity chart.

refs #69 #72 #75

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 22:58:08 +01:00

426 lines
20 KiB
C#

using System.Net;
using Anubis.Access;
using Anubis.Core;
using Anubis.Db;
using Anubis.Platform;
using Anubis.Server;
namespace Anubis.Tests;
/// <summary>Restore, old copies, failed migrations and a changed secret key as the user meets them (issue #69, SPEC 9.4, 15.1).</summary>
[TestClass]
[TestCategory(Category.Integration)]
public sealed class RestoreServerTests
{
/// <summary>The database of the data folder is set aside and an empty one takes its place; the answer is how to put it back.</summary>
private static async Task<(Func<Task> PutBack, Func<Task> PutNew, TestDb? Empty)> EmptyDatabaseAsync(Dictionary<string, string?> env, string data, TestDb? postgres)
{
if (postgres is not null)
{
var empty = await TestDb.CreateAsync(DbEngine.Postgres);
ServerHarness.UsePostgres(env, empty);
return (() =>
{
ServerHarness.UsePostgres(env, postgres);
return Task.CompletedTask;
}, () =>
{
ServerHarness.UsePostgres(env, empty);
return Task.CompletedTask;
}, empty);
}
var file = new DataDirectory(data).SqliteFile;
var old = data + "-vecchio.sqlite3";
var fresh = data + "-nuovo.sqlite3";
void Take(string from, string to)
{
Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
File.Copy(from, to, overwrite: true);
foreach (var f in Directory.EnumerateFiles(Path.GetDirectoryName(file)!).Where(f => f.StartsWith(file, StringComparison.OrdinalIgnoreCase)))
{
File.Delete(f);
}
}
Take(file, old);
await File.WriteAllBytesAsync(file, []);
return (() =>
{
Take(file, fresh);
File.Copy(old, file);
return Task.CompletedTask;
}, () =>
{
Take(file, old);
File.Copy(fresh, file);
return Task.CompletedTask;
}, null);
}
[TestMethod]
public async Task AMissingSqliteFileOffersTheRestoreAndNeverCreatesADatabaseByItself()
{
var data = TempFolder.Create("missing-file");
var file = new DataDirectory(data).SqliteFile;
await using (var first = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), dataDir: data))
{
await first.SignInFirstTimeAsync();
using var saved = await first.PostFormAsync("/impostazioni", "/azioni/salvataggio");
}
Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
var away = data + "-altrove.sqlite3";
File.Copy(file, away, overwrite: true);
foreach (var f in Directory.EnumerateFiles(Path.GetDirectoryName(file)!))
{
File.Delete(f);
}
// The file comes back while the page waits: it is used, with no choice to make.
await using (var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), dataDir: data, waitReady: false))
{
await server.WaitForAsync(HostMode.IdentityProblem);
StringAssert.Contains(await server.TextAsync("/"), "Il file del database non c'è");
using var health = await server.GetAsync("/health");
Assert.AreEqual(HttpStatusCode.ServiceUnavailable, health.StatusCode);
using (var wrong = await server.PostFormAsync("/", "/azioni/servizio/da-capo", ("password", "wrong-password-123")))
{
StringAssert.Contains(ServerHarness.Location(wrong), "errore=password");
}
using (var unknown = await server.PostFormAsync("/", "/azioni/servizio/ripristina", ("password", ServerHarness.AdminPassword), ("salvataggio", "inesistente")))
{
StringAssert.Contains(ServerHarness.Location(unknown), "errore=scelta");
}
// A damaged archive: refused, and the file is still not there, however many turns the loop makes.
foreach (var damage in new[] { "index.json", "users.jsonl" })
{
var saved = new Backups(new DataDirectory(data), SystemClock.Instance).List().Single(b => b.Reason == "a-mano");
var part = Path.Combine(saved.Folder, Backups.ArchiveFolder, damage);
var good = await File.ReadAllTextAsync(part);
await File.WriteAllTextAsync(part, good[..(good.Length / 2)]);
using (var failed = await server.PostFormAsync("/", "/azioni/servizio/ripristina", ("password", ServerHarness.AdminPassword), ("salvataggio", saved.Name)))
{
StringAssert.Contains(ServerHarness.Location(failed), "errore=importazione", damage);
}
await File.WriteAllTextAsync(part, good);
await Task.Delay(6000);
Assert.IsFalse(File.Exists(file), "Trap 20, after a damaged " + damage);
StringAssert.Contains(await server.TextAsync("/"), "Il file del database non c'è");
}
Assert.IsFalse(File.Exists(file), "Trap 20: no database by itself.");
// The true file comes back while a choice is at work, and the choice fails: it is not taken away.
using (await server.Host.ExclusiveAsync(CancellationToken.None))
{
var db = server.Host.OpenForChoice();
File.Copy(away, file);
Assert.IsFalse((await Migrations.StatusAsync(db, CancellationToken.None)).IsEmpty);
await server.Host.AbandonChoiceAsync();
Assert.IsTrue(File.Exists(file), "The file that came back stays in its place.");
Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
foreach (var f in Directory.EnumerateFiles(Path.GetDirectoryName(file)!))
{
File.Delete(f);
}
// What a choice began to write is another thing: it steps aside.
await Migrations.MigrateAsync(server.Host.OpenForChoice(), SystemClock.Instance, null, CancellationToken.None);
await server.Host.AbandonChoiceAsync();
Assert.IsFalse(File.Exists(file));
Assert.HasCount(1, Directory.GetFiles(Path.GetDirectoryName(file)!, "*.incompleto-*").Where(f => !f.EndsWith("-wal", StringComparison.Ordinal) && !f.EndsWith("-shm", StringComparison.Ordinal)).ToList());
}
File.Copy(away, file);
await server.WaitForAsync(HostMode.Ready);
}
Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
foreach (var f in Directory.EnumerateFiles(Path.GetDirectoryName(file)!))
{
File.Delete(f);
}
await using (var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), dataDir: data, waitReady: false))
{
await server.WaitForAsync(HostMode.IdentityProblem);
var backup = new Backups(new DataDirectory(data), SystemClock.Instance).List().Single(b => b.Reason == "a-mano");
using (var restore = await server.PostFormAsync("/", "/azioni/servizio/ripristina", ("password", ServerHarness.AdminPassword), ("salvataggio", backup.Name)))
{
Assert.AreEqual("/", ServerHarness.Location(restore));
}
await server.WaitForAsync(HostMode.Ready);
Assert.IsTrue((await Installation.ReadRowAsync(server.Host.Services!.Db))!.ProtectedRestart);
Assert.AreEqual("stopped", (await server.Host.Services.Settings.GetAsync(SettingsStore.BotState.Key)).Value);
}
File.Delete(away);
TempFolder.Delete(data);
}
[TestMethod]
public async Task AfterARestoreTheOldDatabaseIsRefusedAndTheNewOneWaitsForTheUser()
{
var (env, postgres) = await ServerHarness.DockerOnEngineAsync();
await using var engine = postgres;
var data = TempFolder.Create("protected");
string password;
await using (var first = await ServerHarness.StartAsync("docker", env, dataDir: data))
{
password = await first.SignInFirstTimeAsync();
using var saved = await first.PostFormAsync("/impostazioni", "/azioni/salvataggio");
}
var backup = new Backups(new DataDirectory(data), SystemClock.Instance).List().Single(b => b.Reason == "a-mano");
var (putBack, putNew, empty) = await EmptyDatabaseAsync(env, data, postgres);
await using var second = empty;
await using (var server = await ServerHarness.StartAsync("docker", env, dataDir: data, waitReady: false))
{
await server.WaitForAsync(HostMode.IdentityProblem);
using (var restore = await server.PostFormAsync("/", "/azioni/servizio/ripristina", ("password", ServerHarness.AdminPassword), ("salvataggio", backup.Name)))
{
Assert.AreEqual("/", ServerHarness.Location(restore));
}
// Without the trading engine nothing can be rebuilt: the restart waits.
await server.WaitForAsync(HostMode.Ready);
using (var signIn = await server.PostFormAsync("/accesso", "/azioni/accesso", ("password", password)))
{
Assert.AreEqual("/", ServerHarness.Location(signIn));
}
StringAssert.Contains(await server.TextAsync("/"), "Ripartenza protetta");
using (var early = await server.PostFormAsync("/rischio", "/azioni/bot/riattiva"))
{
Assert.AreEqual("stopped", (await server.Host.Services!.Settings.GetAsync(SettingsStore.BotState.Key)).Value);
}
// Nor is anything sold from a ledger that has not read the accounts yet.
Assert.IsFalse((await server.TextAsync("/rischio")).Contains("Chiudi tutte le posizioni", StringComparison.Ordinal));
using (var close = await server.PostFormAsync("/rischio", "/azioni/bot/chiudi"))
{
StringAssert.Contains(ServerHarness.Location(close), "errore");
}
Assert.HasCount(1, await server.Host.Services!.Db.ReadAsync(s => s.QueryAsync("SELECT message FROM journal WHERE code = 'protected_restart'", r => r.Text("message"))));
}
// The database of before the restore comes back, by mistake: same installation, older fingerprint, engine off.
await putBack();
await using (var server = await ServerHarness.StartAsync("docker", env, dataDir: data, waitReady: false))
{
await server.WaitForAsync(HostMode.IdentityProblem);
Assert.AreEqual(IdentityVerdict.StaleDatabase, server.Host.Status.Identity!.Verdict);
StringAssert.Contains(await server.TextAsync("/"), "una copia più vecchia");
using var health = await server.GetAsync("/health");
Assert.AreEqual(HttpStatusCode.ServiceUnavailable, health.StatusCode);
Assert.IsNull(server.Host.Services);
}
// The right one: protected until the user confirms, then as before.
await putNew();
await using (var server = await ServerHarness.StartAsync("docker", env, dataDir: data, trading: true))
{
using (var signIn = await server.PostFormAsync("/accesso", "/azioni/accesso", ("password", password)))
{
Assert.AreEqual("/", ServerHarness.Location(signIn));
}
for (var i = 0; i < 300 && server.Host.Services!.Trading is not { Started: true }; i++)
{
await Task.Delay(100);
}
StringAssert.Contains(await server.TextAsync("/rischio"), "Sui conti non c'era niente che il database non conoscesse già");
using (var go = await server.PostFormAsync("/rischio", "/azioni/bot/riattiva"))
{
Assert.AreEqual(HttpStatusCode.Redirect, go.StatusCode);
}
Assert.AreEqual("active", (await server.Host.Services!.Settings.GetAsync(SettingsStore.BotState.Key)).Value);
Assert.IsFalse((await Installation.ReadRowAsync(server.Host.Services.Db))!.ProtectedRestart);
Assert.IsFalse((await server.TextAsync("/rischio")).Contains("Ripartenza protetta", StringComparison.Ordinal));
}
TempFolder.Delete(data);
foreach (var left in new[] { data + "-vecchio.sqlite3", data + "-nuovo.sqlite3" })
{
File.Delete(left);
}
}
[TestMethod]
public async Task AFailedMigrationKeepsTheEngineOffAndTakesOneBackup()
{
var (env, postgres) = await ServerHarness.DockerOnEngineAsync();
await using var engine = postgres;
var data = TempFolder.Create("migration");
var directory = new DataDirectory(data);
directory.Ensure();
var settings = postgres?.Settings ?? new DbSettings { Engine = DbEngine.Sqlite, SqlitePath = directory.SqliteFile };
await using (var db = Database.Open(settings))
{
await Migrations.MigrateAsync(db, SystemClock.Instance, null, CancellationToken.None, upTo: 12);
await Installation.CheckAsync(db, directory, SystemClock.Instance);
await db.WriteAsync(s => s.ExecuteAsync("CREATE TABLE cost_estimates (x INTEGER)"));
}
await using (var server = await ServerHarness.StartAsync("docker", env, dataDir: data, waitReady: false))
{
await server.WaitForAsync(HostMode.SchemaProblem);
await Task.Delay(1000);
Assert.HasCount(1, new Backups(directory, SystemClock.Instance).List(), "One backup, however long the page stays open.");
var html = await server.TextAsync("/");
StringAssert.Contains(html, "0013");
StringAssert.Contains(html, "prima-della-migrazione");
using (var wrong = await server.PostFormAsync("/", "/azioni/servizio/riprova", ("password", "wrong-password-123")))
{
StringAssert.Contains(ServerHarness.Location(wrong), "errore=password");
}
await using (var db = Database.Open(settings))
{
await db.WriteAsync(s => s.ExecuteAsync("DROP TABLE cost_estimates"));
}
using (var again = await server.PostFormAsync("/", "/azioni/servizio/riprova", ("password", ServerHarness.AdminPassword)))
{
Assert.AreEqual("/", ServerHarness.Location(again));
}
await server.WaitForAsync(HostMode.Ready);
}
TempFolder.Delete(data);
}
[TestMethod]
public async Task AfterAFailedMigrationTheDatabaseCanBeChosenAgain()
{
var (env, postgres) = await ServerHarness.DockerOnEngineAsync();
await using var engine = postgres;
var data = TempFolder.Create("migration-choice");
var directory = new DataDirectory(data);
directory.Ensure();
var settings = postgres?.Settings ?? new DbSettings { Engine = DbEngine.Sqlite, SqlitePath = directory.SqliteFile };
await using (var db = Database.Open(settings))
{
await Migrations.MigrateAsync(db, SystemClock.Instance, null, CancellationToken.None, upTo: 12);
await Installation.CheckAsync(db, directory, SystemClock.Instance);
await db.WriteAsync(s => s.ExecuteAsync("CREATE TABLE cost_estimates (x INTEGER)"));
}
File.Delete(directory.InstallationFile);
await using (var server = await ServerHarness.StartAsync("docker", env, dataDir: data, waitReady: false))
{
await server.WaitForAsync(HostMode.IdentityProblem);
for (var i = 0; i < 2; i++)
{
using var failed = await server.PostFormAsync("/", "/azioni/servizio/usa-questo", ("password", ServerHarness.AdminPassword));
StringAssert.Contains(ServerHarness.Location(failed), "errore=importazione");
}
await using (var db = Database.Open(settings))
{
await db.WriteAsync(s => s.ExecuteAsync("DROP TABLE cost_estimates"));
}
using (var again = await server.PostFormAsync("/", "/azioni/servizio/usa-questo", ("password", ServerHarness.AdminPassword)))
{
Assert.AreEqual("/", ServerHarness.Location(again));
}
await server.WaitForAsync(HostMode.Ready);
}
TempFolder.Delete(data);
}
[TestMethod]
public async Task WithAnotherSecretKeyNothingCrashesAndTheAccessIsResetFromTheCommandLine()
{
var (env, postgres) = await ServerHarness.DockerOnEngineAsync();
await using var engine = postgres;
var data = TempFolder.Create("key");
string password;
await using (var first = await ServerHarness.StartAsync("docker", env, dataDir: data))
{
password = await first.SignInFirstTimeAsync();
var services = first.Host.Services!;
var secret = Totp.NewSecret();
var user = (await services.Access.GetUserAsync())!;
Assert.AreEqual(AccessChange.Done, await services.Access.EnableSecondFactorAsync(user.Id, secret, password, Totp.Compute(secret, DateTimeOffset.UtcNow), Guid.Empty));
await services.Secrets.SetAsync("FINNHUB_API_KEY", "chiave-di-prova-1", "test");
}
env["ANUBIS_SECRET_KEY"] = "another-secret-key-0123456789-abcdefghij";
await using (var server = await ServerHarness.StartAsync("docker", env, dataDir: data))
{
using (var refused = await server.PostFormAsync("/accesso", "/azioni/accesso", ("password", password), ("codice", "123456")))
{
Assert.AreEqual("/accesso?errore=chiave", ServerHarness.Location(refused));
}
StringAssert.Contains(await server.TextAsync("/accesso?errore=chiave"), "ANUBIS_SECRET_KEY");
using var output = new StringWriter();
Assert.AreEqual(0, await AccessCommand.RunAsync(["reset", "--platform", "docker", "--data-dir", data], output, env, iterations: 1000), output.ToString());
var temporary = output.ToString().Split("Password provvisoria: ")[1].Split('\n')[0].Trim();
using (var signIn = await server.PostFormAsync("/accesso", "/azioni/accesso", ("password", temporary)))
{
Assert.AreEqual("/", ServerHarness.Location(signIn));
}
const string chosen = "chosen-test-pass-3";
using (var change = await server.PostFormAsync("/primo-accesso", "/azioni/primo-accesso", ("attuale", temporary), ("nuova", chosen), ("conferma", chosen)))
{
Assert.AreEqual("/?ok=password", ServerHarness.Location(change));
}
StringAssert.Contains(await server.TextAsync("/impostazioni"), "Non si legge più: la chiave dei segreti è cambiata");
}
TempFolder.Delete(data);
}
[TestMethod]
public async Task TheCommandLineImportsIntoANewSqliteFileOfTheSameFolder()
{
var data = TempFolder.Create("cli-same");
var env = ServerHarness.DockerSqlite();
await using (var server = await ServerHarness.StartAsync("docker", env, dataDir: data))
{
await server.SignInFirstTimeAsync();
}
Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
var root = TempFolder.Create("cli-same-archive");
var archive = Path.Combine(root, "archivio");
using var output = new StringWriter();
Assert.AreEqual(0, await DatabaseCommand.RunAsync(["export", archive, "--platform", "docker", "--data-dir", data], output, env), output.ToString());
var directory = new DataDirectory(data);
foreach (var f in Directory.EnumerateFiles(Path.GetDirectoryName(directory.SqliteFile)!))
{
File.Delete(f);
}
// A wrong folder creates nothing.
Assert.AreEqual(1, await DatabaseCommand.RunAsync(["import", root, "--platform", "docker", "--data-dir", data], output, env));
Assert.IsFalse(File.Exists(directory.SqliteFile));
Assert.AreEqual(0, await DatabaseCommand.RunAsync(["import", archive, "--platform", "docker", "--data-dir", data], output, env), output.ToString());
await using (var server = await ServerHarness.StartAsync("docker", env, dataDir: data))
{
Assert.IsTrue((await Installation.ReadRowAsync(server.Host.Services!.Db))!.ProtectedRestart);
}
TempFolder.Delete(data);
TempFolder.Delete(root);
}
}