feat(core): platform layer, portable database, archives and access (refs #7 #8 #9 #10 #11)

Phase 1 foundations in the Anubis library:
- Platform: startup configuration from environment variables (Docker) or
  config.toml (desktop, in-house TOML subset), data folder layout, secret key
  custody (ANUBIS_SECRET_KEY, DPAPI on Windows, restricted file elsewhere),
  installation identity and database fingerprint.
- Db: ADO.NET with Npgsql and Microsoft.Data.Sqlite, money as NUMERIC(38,18)
  or canonical text rounded to 18 decimals, UTC moments, UUIDv7 ids; numbered
  SQL migrations with type tokens and a version table; engine-independent
  export/import with count and accounting-total checks; backups keeping 14.
- Core: injectable clock, channel event bus, scheduler with fixed, interval
  and market-relative times, settings with change log, AES-GCM secrets, log
  redaction, Italian formats.
- Access: PBKDF2-SHA512 hashes, RFC 6238 TOTP, hashed session tokens,
  sign-in attempt limit.

SQLitePCLRaw (Apache-2.0) arrives with Microsoft.Data.Sqlite and is declared
in DependencyPolicyTests and API-NOTES.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-10 11:09:42 +01:00
1 parent ffb67c9135
commit 53ca01b7c3
44 files changed
+5644 -12

No files matched your search

+186
View File
@@ -0,0 +1,186 @@
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);
}).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.AreEqual(0L, (await Archive.CountsAsync(target.Db).ConfigureAwait(false))["accounts"], "un'importazione fallita non lascia righe");
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, i == 0 ? "prima-della-migrazione" : "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<IOException>(() => Migrations.MigrateAsync(test.Db, _clock, _ => throw new IOException("disco pieno"), CancellationToken.None)).ConfigureAwait(false);
}
}
}
+246
View File
@@ -0,0 +1,246 @@
using Anubis.Core;
namespace Anubis.Tests;
[TestClass]
public sealed class CoreTests
{
[TestMethod]
[TestCategory(Category.Unit)]
public void IdsAreVersion7AndFollowTheInjectedClock()
{
var clock = new ManualClock(new DateTimeOffset(2026, 10, 9, 6, 21, 0, TimeSpan.Zero));
var first = Ids.NewId(clock);
clock.Advance(TimeSpan.FromMilliseconds(5));
var second = Ids.NewId(clock);
Assert.AreEqual(7, first.Version);
Assert.IsLessThan(0, string.CompareOrdinal(first.ToString(), second.ToString()), "gli identificativi seguono il tempo");
Assert.AreNotEqual(Ids.NewToken(), Ids.NewToken());
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task ManualClockReleasesWaitersOnlyWhenMoved()
{
var clock = new ManualClock(DateTimeOffset.UnixEpoch);
var waiting = clock.WaitUntilAsync(DateTimeOffset.UnixEpoch.AddMinutes(5), CancellationToken.None);
clock.Advance(TimeSpan.FromMinutes(4));
Assert.IsFalse(waiting.IsCompleted);
clock.Advance(TimeSpan.FromMinutes(1));
await waiting.WaitAsync(TimeSpan.FromSeconds(5)).ConfigureAwait(false);
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task BusDeliversToEachSubscriberAndDropsOldestWhenFull()
{
var bus = new EventBus();
using var all = bus.Subscribe<object>();
using var small = bus.Subscribe<string>(capacity: 2);
bus.Publish("a");
bus.Publish("b");
bus.Publish("c");
bus.Publish(42);
var received = new List<string>();
while (small.TryRead(out var message))
{
received.Add(message!);
}
CollectionAssert.AreEqual(new[] { "b", "c" }, received, "un lettore lento perde i più vecchi, non blocca chi pubblica");
var count = 0;
while (all.TryRead(out _))
{
count++;
}
Assert.AreEqual(4, count);
all.Dispose();
Assert.AreEqual(1, bus.SubscriberCount);
await Task.CompletedTask.ConfigureAwait(false);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void RedactorRemovesKeysSignaturesAndHeaders()
{
Redactor.Register("registered-secret-value-123");
var samples = new Dictionary<string, string>
{
["OK-ACCESS-SIGN: " + "abc123signature=="] = "abc123signature",
["APCA-API-SECRET-KEY: " + "Sk1234567890abcdef"] = "Sk1234567890abcdef",
["Authorization: Bearer " + "eyJhbGciOiJIUzI1NiJ9.payload"] = "eyJhbGciOiJIUzI1NiJ9",
["{\"api_key\": \"" + "AK12345678\"}"] = "AK12345678",
["password=" + "hunter2hunter2&x=1"] = "hunter2hunter2",
["postgres://anubis:" + "S3cretPw@db:5432/anubis"] = "S3cretPw",
["bot" + "123456789:" + "AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsawq"] = "AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsawq",
["value registered-secret-value-123 in text"] = "registered-secret-value-123",
};
foreach (var (input, secret) in samples)
{
var output = Redactor.Redact(input);
Assert.IsFalse(output.Contains(secret, StringComparison.Ordinal), $"Segreto rimasto in: {output}");
Assert.Contains(Redactor.Mask, output);
}
Assert.AreEqual("Ordine eseguito: 2 AAPL a 259,80 $", Redactor.Redact("Ordine eseguito: 2 AAPL a 259,80 $"));
}
}
/// <summary>The scheduler with a fake calendar (issue #10): fixed times, intervals, open and close, sleeps.</summary>
[TestClass]
public sealed class SchedulerTests
{
private static readonly TimeZoneInfo _rome = TimeZoneInfo.FindSystemTimeZoneById("Europe/Rome");
private static readonly TimeZoneInfo _newYork = TimeZoneInfo.FindSystemTimeZoneById("America/New_York");
/// <summary>New York, 09:30–16:00 on weekdays, 13:00 close on the day after Thanksgiving 2026, closed on 3 July.</summary>
private sealed class FakeCalendar : IMarketCalendar
{
public MarketSession? SessionOn(DateOnly day)
{
if (day.DayOfWeek is DayOfWeek.Saturday or DayOfWeek.Sunday || day == new DateOnly(2026, 7, 3))
{
return null;
}
var close = day == new DateOnly(2026, 11, 27) ? new TimeOnly(13, 0) : new TimeOnly(16, 0);
return new MarketSession(day, At(day, new TimeOnly(9, 30)), At(day, close));
}
private static DateTimeOffset At(DateOnly day, TimeOnly time)
{
var local = day.ToDateTime(time);
return new DateTimeOffset(local, _newYork.GetUtcOffset(local)).ToUniversalTime();
}
}
private static DateTimeOffset Rome(int y, int mo, int d, int h, int mi)
{
var local = new DateTime(y, mo, d, h, mi, 0);
return new DateTimeOffset(local, _rome.GetUtcOffset(local));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void MarketTimesFollowTheExchangeNotItalianTime()
{
var calendar = new FakeCalendar();
var afterOpen = Schedule.Market(MarketAnchor.Open, TimeSpan.FromMinutes(5), calendar);
// Normal week: 09:35 in New York is 15:35 in Rome.
Assert.AreEqual(Rome(2026, 10, 9, 15, 35), afterOpen.NextAfter(Rome(2026, 10, 9, 8, 21)));
// 16 March 2026: the USA already moved to summer time, Europe not yet: 09:35 NY is 14:35 in Rome.
Assert.AreEqual(Rome(2026, 3, 16, 14, 35), afterOpen.NextAfter(Rome(2026, 3, 16, 8, 0)));
// Friday after the open: the next run is Monday.
Assert.AreEqual(Rome(2026, 10, 12, 15, 35), afterOpen.NextAfter(Rome(2026, 10, 9, 16, 0)));
// Holiday skipped (Friday 3 July): Monday 6 July.
Assert.AreEqual(Rome(2026, 7, 6, 15, 35), afterOpen.NextAfter(Rome(2026, 7, 2, 16, 0)));
// Early close: 5 minutes before a 13:00 close is 12:55 in New York, 18:55 in Rome.
var beforeClose = Schedule.Market(MarketAnchor.Close, TimeSpan.FromMinutes(-5), calendar);
Assert.AreEqual(Rome(2026, 11, 27, 18, 55), beforeClose.NextAfter(Rome(2026, 11, 27, 9, 0)));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void DailyAndIntervalSchedules()
{
var backup = Schedule.Daily(new TimeOnly(3, 30), _rome);
Assert.AreEqual(Rome(2026, 10, 10, 3, 30), backup.NextAfter(Rome(2026, 10, 9, 8, 21)));
// The night summer time ends (25 October 2026) 03:30 exists once, in winter time.
Assert.AreEqual(Rome(2026, 10, 25, 3, 30), backup.NextAfter(Rome(2026, 10, 24, 12, 0)));
// 02:30 does not exist on 29 March 2026 in Rome: it moves to 03:00.
var skipped = Schedule.Daily(new TimeOnly(2, 30), _rome);
Assert.AreEqual(new DateTimeOffset(2026, 3, 29, 1, 0, 0, TimeSpan.Zero), skipped.NextAfter(Rome(2026, 3, 28, 12, 0)));
var crypto = Schedule.Daily(new TimeOnly(0, 5), TimeZoneInfo.Utc);
Assert.AreEqual(new DateTimeOffset(2026, 10, 10, 0, 5, 0, TimeSpan.Zero), crypto.NextAfter(Rome(2026, 10, 9, 8, 21)));
var every5 = Schedule.Every(TimeSpan.FromMinutes(5));
Assert.AreEqual(new DateTimeOffset(2026, 10, 9, 6, 25, 0, TimeSpan.Zero), every5.NextAfter(new DateTimeOffset(2026, 10, 9, 6, 21, 0, TimeSpan.Zero)));
Assert.AreEqual(new DateTimeOffset(2026, 10, 9, 6, 30, 0, TimeSpan.Zero), every5.NextAfter(new DateTimeOffset(2026, 10, 9, 6, 25, 0, TimeSpan.Zero)));
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task RunsDueJobsOnceAndSkipsRunsMissedDuringASleep()
{
var clock = new ManualClock(Rome(2026, 10, 9, 8, 21));
var bus = new EventBus();
using var runs = bus.Subscribe<JobRun>();
var scheduler = new Scheduler(clock, bus);
var count = 0;
scheduler.Add(new ScheduledJob("backup", "Salvataggio", Schedule.Daily(new TimeOnly(3, 30), _rome), _ =>
{
count++;
return Task.CompletedTask;
}));
scheduler.Add(new ScheduledJob("broken", "Rotto", Schedule.Daily(new TimeOnly(3, 30), _rome), _ => throw new InvalidOperationException("guasto")));
Assert.HasCount(2, scheduler.Upcoming());
clock.Set(Rome(2026, 10, 10, 3, 30));
await scheduler.RunDueAsync(CancellationToken.None).ConfigureAwait(false);
Assert.AreEqual(1, count);
await scheduler.RunDueAsync(CancellationToken.None).ConfigureAwait(false);
Assert.AreEqual(1, count, "un lavoro già eseguito non riparte");
// The computer slept two days: the 03:30 run is found late by hours and is skipped, not run blindly.
clock.Set(Rome(2026, 10, 11, 9, 0));
await scheduler.RunDueAsync(CancellationToken.None).ConfigureAwait(false);
Assert.AreEqual(1, count);
var outcomes = new List<JobRun>();
while (runs.TryRead(out var run))
{
outcomes.Add(run!);
}
Assert.IsTrue(outcomes.Any(r => r.Name == "backup" && r.Outcome == JobOutcome.Completed));
Assert.IsTrue(outcomes.Any(r => r.Name == "backup" && r.Outcome == JobOutcome.Skipped));
Assert.IsTrue(outcomes.Any(r => r.Name == "broken" && r.Outcome == JobOutcome.Failed && r.Error == "guasto"));
Assert.AreEqual(Rome(2026, 10, 12, 3, 30), scheduler.Upcoming().Single(u => u.Name == "backup").DueUtc);
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task LoopWaitsOnTheInjectedClock()
{
var clock = new ManualClock(new DateTimeOffset(2026, 10, 9, 6, 21, 0, TimeSpan.Zero));
var scheduler = new Scheduler(clock, new EventBus());
var ran = new TaskCompletionSource();
scheduler.Add(new ScheduledJob("tick", "Prova", Schedule.Every(TimeSpan.FromMinutes(5)), _ =>
{
ran.TrySetResult();
return Task.CompletedTask;
}));
using var cts = new CancellationTokenSource();
var loop = scheduler.RunAsync(cts.Token);
await WaitUntil(() => clock.Waiting > 0).ConfigureAwait(false);
Assert.IsFalse(ran.Task.IsCompleted, "nessun lavoro prima dell'orario");
clock.Set(new DateTimeOffset(2026, 10, 9, 6, 25, 0, TimeSpan.Zero));
await ran.Task.WaitAsync(TimeSpan.FromSeconds(10)).ConfigureAwait(false);
Assert.IsNotNull(scheduler.LastBeatUtc);
await cts.CancelAsync().ConfigureAwait(false);
await Assert.ThrowsAsync<OperationCanceledException>(() => loop).ConfigureAwait(false);
}
internal static async Task WaitUntil(Func<bool> condition)
{
for (var i = 0; i < 500 && !condition(); i++)
{
await Task.Delay(10).ConfigureAwait(false);
}
Assert.IsTrue(condition(), "condizione non raggiunta in tempo");
}
}
+249
View File
@@ -0,0 +1,249 @@
using Anubis.Core;
using Anubis.Db;
using Anubis.Platform;
namespace Anubis.Tests;
/// <summary>
/// The portable database (issue #8): every test runs on the engine of this run (ANUBIS_TEST_DB), so the same
/// battery passes on SQLite and on PostgreSQL.
/// </summary>
[TestClass]
public sealed class DatabaseTests
{
private static readonly ManualClock _clock = new(new DateTimeOffset(2026, 10, 9, 6, 21, 0, TimeSpan.Zero));
internal static async Task<TestDb> MigratedAsync()
{
var test = await TestDb.CreateAsync().ConfigureAwait(false);
await Migrations.MigrateAsync(test.Db, _clock, null, CancellationToken.None).ConfigureAwait(false);
return test;
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task MigrationsCreateTheSchemaAndRunOnce()
{
await using var test = await TestDb.CreateAsync().ConfigureAwait(false);
Assert.IsTrue((await Migrations.StatusAsync(test.Db, CancellationToken.None).ConfigureAwait(false)).IsEmpty);
Assert.AreEqual(Migrations.Latest, await Migrations.MigrateAsync(test.Db, _clock, null, CancellationToken.None).ConfigureAwait(false));
Assert.AreEqual(0, await Migrations.MigrateAsync(test.Db, _clock, null, CancellationToken.None).ConfigureAwait(false));
var status = await Migrations.StatusAsync(test.Db, CancellationToken.None).ConfigureAwait(false);
Assert.AreEqual(Migrations.Latest, status.Current);
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task ColumnsInTheDatabaseMatchTheSchemaReadFromMigrations()
{
await using var test = await MigratedAsync().ConfigureAwait(false);
foreach (var table in Schema.Tables)
{
var actual = await test.Db.ReadAsync(s => s.QueryAsync(
s.Engine == DbEngine.Sqlite
? $"SELECT name, type, \"notnull\" AS required FROM pragma_table_info('{table.Name}')"
: $"SELECT column_name AS name, data_type AS type, CASE WHEN is_nullable = 'NO' THEN 1 ELSE 0 END AS required FROM information_schema.columns WHERE table_schema = current_schema() AND table_name = '{table.Name}'",
r => (Name: r.Text("name"), Type: r.Text("type").ToUpperInvariant(), Required: r.Number("required") != 0))).ConfigureAwait(false);
CollectionAssert.AreEquivalent(table.Columns.Select(c => c.Name).ToList(), actual.Select(a => a.Name).ToList(), table.Name);
foreach (var column in table.Columns)
{
var found = actual.Single(a => a.Name == column.Name);
if (column.Kind == ColumnKind.Money)
{
Assert.IsTrue(found.Type is "TEXT" or "NUMERIC", $"{table.Name}.{column.Name} è {found.Type}: il denaro non è mai in virgola mobile");
}
if (!column.Nullable)
{
Assert.IsTrue(found.Required || column.Name == "id", $"{table.Name}.{column.Name} dovrebbe essere obbligatoria");
}
}
}
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task DecimalsDatesAndIdsRoundTripExactly()
{
await using var test = await MigratedAsync().ConfigureAwait(false);
await test.Db.WriteAsync(s => s.ExecuteAsync("INSERT INTO accounts (id, name, broker, environment, base_currency, created_at) VALUES (@id, 'Prova', 'paper', 'simulation', 'EUR', @t)",
("id", Guid.CreateVersion7(_clock.UtcNow)), ("t", _clock.UtcNow))).ConfigureAwait(false);
var account = await test.Db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT id FROM accounts", r => r.Id("id"))).ConfigureAwait(false);
decimal[] values =
[
0m, 1m, -1m, 0.000000000000000001m, -0.000000000000000001m, 1299.84m, 0.1m + 0.2m,
99_999_999_999_999_999_999m, -99_999_999_999_999_999_999m, 1234567890.123456789012345678m,
12345678901.12345678901234567m, 7.000000000000000000m, 79228162514.264337593543950335m,
];
var moments = new[]
{
new DateTimeOffset(2026, 10, 9, 8, 21, 0, TimeSpan.FromHours(2)),
new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero),
new DateTimeOffset(2099, 12, 31, 23, 59, 59, TimeSpan.Zero).AddTicks(1234567),
};
var rows = new List<(Guid Id, decimal Value, DateTimeOffset At)>();
for (var i = 0; i < values.Length; i++)
{
rows.Add((Guid.CreateVersion7(_clock.UtcNow.AddMilliseconds(i)), values[i], moments[i % moments.Length]));
}
await test.Db.WriteAsync(async s =>
{
foreach (var (id, value, at) in rows)
{
await s.ExecuteAsync("INSERT INTO cash_ledger (id, account_id, currency, amount, kind, occurred_at, created_at) VALUES (@id, @a, 'EUR', @v, 'test', @at, @t)",
("id", id), ("a", account), ("v", value), ("at", at), ("t", _clock.UtcNow)).ConfigureAwait(false);
}
}).ConfigureAwait(false);
var read = await test.Db.ReadAsync(s => s.QueryAsync("SELECT id, amount, occurred_at FROM cash_ledger ORDER BY id",
r => (Id: r.Id("id"), Value: r.Money("amount"), At: r.Moment("occurred_at")))).ConfigureAwait(false);
Assert.HasCount(rows.Count, read);
for (var i = 0; i < rows.Count; i++)
{
Assert.AreEqual(rows[i].Id, read[i].Id);
Assert.AreEqual(DbValues.Money(rows[i].Value), read[i].Value, $"valore {rows[i].Value}");
Assert.AreEqual(DbValues.Moment(rows[i].At), read[i].At);
Assert.AreEqual(TimeSpan.Zero, read[i].At.Offset, "si rilegge sempre in UTC");
}
// More than 18 decimals: rounded half away from zero, the same on both engines.
Assert.AreEqual(0.000000000000000002m, DbValues.Money(0.0000000000000000015m));
Assert.AreEqual(1.123456789012345679m, DbValues.Money(1.1234567890123456789m));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void ValuesOutsideNumeric38And18AndMomentsWithoutZoneAreRefused()
{
Assert.Throws<OverflowException>(() => DbValues.Money(100_000_000_000_000_000_000m));
Assert.Throws<OverflowException>(() => DbValues.Money(decimal.MaxValue));
Assert.Throws<ArgumentException>(() => DbValues.ToProvider(new DateTime(2026, 10, 9), DbEngine.Sqlite));
Assert.Throws<FormatException>(() => DbValues.ParseMoment("2026-10-09T08:21:00"));
Assert.AreEqual("1.5", DbValues.MoneyText(1.500m));
Assert.AreEqual("0", DbValues.MoneyText(0.000m));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void MoneyRoundTripsForAnyValue() =>
Property.ForAll(g => g.Decimal(-1_000_000m, 1_000_000m, 12), value =>
{
var text = DbValues.MoneyText(value);
Assert.AreEqual(DbValues.Money(value), DbValues.ParseMoney(text));
});
[TestMethod]
[TestCategory(Category.Integration)]
public async Task SameExecutionIsRecordedOnce()
{
await using var test = await MigratedAsync().ConfigureAwait(false);
var (account, instrument) = await SeedAccountAsync(test.Db).ConfigureAwait(false);
async Task InsertFill() => await test.Db.WriteAsync(s => 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', 1, 100, 0, 'EUR', @t, @t)",
("id", Guid.NewGuid()), ("a", account), ("i", instrument), ("t", _clock.UtcNow))).ConfigureAwait(false);
await InsertFill().ConfigureAwait(false);
await Assert.ThrowsAsync<System.Data.Common.DbException>(InsertFill).ConfigureAwait(false);
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task FailedWritesLeaveNothingBehind()
{
await using var test = await MigratedAsync().ConfigureAwait(false);
await Assert.ThrowsAsync<InvalidOperationException>(() => test.Db.WriteAsync(async s =>
{
await s.ExecuteAsync("INSERT INTO accounts (id, name, broker, environment, base_currency, created_at) VALUES (@id, 'X', 'paper', 'simulation', 'EUR', @t)",
("id", Guid.NewGuid()), ("t", _clock.UtcNow)).ConfigureAwait(false);
throw new InvalidOperationException("stop");
})).ConfigureAwait(false);
Assert.AreEqual(0L, await test.Db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM accounts")).ConfigureAwait(false));
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task SqliteUsesWalFullSyncAndForeignKeys()
{
if (TestDatabase.Engine != "sqlite")
{
Assert.Inconclusive("Solo su SQLite.");
}
await using var test = await MigratedAsync().ConfigureAwait(false);
var pragmas = await test.Db.ReadAsync(async s => (
Journal: await s.FirstOrDefaultAsync("PRAGMA journal_mode", r => r.Text("journal_mode")).ConfigureAwait(false),
Sync: await s.CountAsync("PRAGMA synchronous").ConfigureAwait(false),
Keys: await s.CountAsync("PRAGMA foreign_keys").ConfigureAwait(false),
Busy: await s.CountAsync("PRAGMA busy_timeout").ConfigureAwait(false))).ConfigureAwait(false);
Assert.AreEqual("wal", pragmas.Journal);
Assert.AreEqual(2L, pragmas.Sync, "synchronous=FULL");
Assert.AreEqual(1L, pragmas.Keys);
Assert.AreEqual(5000L, pragmas.Busy);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void SqliteDoesNotCreateAMissingFileWhenAskedNotTo()
{
var folder = TempFolder.Create("nocreate");
try
{
var path = Path.Combine(folder, "db", "anubis.sqlite3");
var db = Database.Open(new DbSettings { Engine = DbEngine.Sqlite, SqlitePath = path }, allowCreate: false);
Assert.ThrowsAsync<Microsoft.Data.Sqlite.SqliteException>(() => db.PingAsync(CancellationToken.None)).GetAwaiter().GetResult();
Assert.IsFalse(File.Exists(path));
}
finally
{
TempFolder.Delete(folder);
}
}
[TestMethod]
[TestCategory(Category.Unit)]
public void MigrationsUseOnlyPortableSql()
{
string[] forbidden = ["SERIAL", "AUTOINCREMENT", "JSONB", "MATERIALIZED", "PARTITION", "LISTEN", "NOTIFY", "REAL", "FLOAT", "DOUBLE", "pg_advisory", "RETURNING"];
foreach (var migration in Migrations.All)
{
var sql = System.Text.RegularExpressions.Regex.Replace(migration.Sql, @"--[^\n]*|\{[a-z]+\}", "");
foreach (var word in forbidden)
{
Assert.IsFalse(System.Text.RegularExpressions.Regex.IsMatch(sql, $@"\b{word}\b", System.Text.RegularExpressions.RegexOptions.IgnoreCase),
$"{migration.Version:D4}: '{word}' non è portabile");
}
}
Assert.IsTrue(Schema.Tables.All(t => t.Columns.Any(c => c.Name == "id" && c.Kind == ColumnKind.Uuid)), "ogni tabella ha una chiave UUID");
Assert.IsTrue(Schema.Tables.All(t => t.Columns.Any(c => c.Name == "created_at" && c.Kind == ColumnKind.Moment)), "ogni tabella ha created_at");
}
[TestMethod]
[TestCategory(Category.Unit)]
public void AccountingTablesAreNeverUpdatedOrDeletedInCode()
{
var pattern = new System.Text.RegularExpressions.Regex(@"\b(UPDATE\s+(fills|lots|cash_ledger)\b|DELETE\s+FROM\s+(fills|lots|cash_ledger)\b)", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
var offenders = Repo.Files()
.Where(f => f.Extension is ".cs" or ".sql" && Repo.Relative(f).StartsWith("src/", StringComparison.Ordinal))
.Where(f => pattern.IsMatch(File.ReadAllText(f.FullName)))
.Select(Repo.Relative)
.ToList();
Assert.IsEmpty(offenders, "Le tabelle contabili si correggono con righe di storno: " + string.Join(", ", offenders));
}
internal static async Task<(Guid Account, Guid Instrument)> SeedAccountAsync(Database db)
{
var account = Guid.CreateVersion7(_clock.UtcNow);
var instrument = Guid.CreateVersion7(_clock.UtcNow.AddMilliseconds(1));
await db.WriteAsync(async s =>
{
await s.ExecuteAsync("INSERT INTO accounts (id, name, broker, environment, base_currency, created_at) VALUES (@id, 'OKX Europe', 'okx', 'simulation', 'EUR', @t)",
("id", account), ("t", _clock.UtcNow)).ConfigureAwait(false);
await s.ExecuteAsync("INSERT INTO instruments (id, venue, symbol, name, asset_class, quote_currency, created_at) VALUES (@id, 'okx', 'BTC/EUR', 'Bitcoin', 'crypto', 'EUR', @t)",
("id", instrument), ("t", _clock.UtcNow)).ConfigureAwait(false);
}).ConfigureAwait(false);
return (account, instrument);
}
}
+8 -1
View File
@@ -28,7 +28,14 @@ public sealed class DependencyPolicyTests
/// Third-party packages pulled in by an authorised one. Each must also be listed in docs/API-NOTES.md
/// and reported to the user (checked below). Microsoft.* and System.* ids are reserved to Microsoft on nuget.org.
/// </summary>
private static readonly HashSet<string> _knownThirdPartyTransitive = new(StringComparer.OrdinalIgnoreCase);
private static readonly HashSet<string> _knownThirdPartyTransitive = new(StringComparer.OrdinalIgnoreCase)
{
// Native SQLite library and its loader, brought by Microsoft.Data.Sqlite (phase 1).
"SQLitePCLRaw.bundle_e_sqlite3",
"SQLitePCLRaw.core",
"SQLitePCLRaw.lib.e_sqlite3",
"SQLitePCLRaw.provider.e_sqlite3",
};
private static readonly string[] _packageElements = ["PackageReference", "GlobalPackageReference", "PackageDownload"];
+108
View File
@@ -0,0 +1,108 @@
using System.Text;
using Anubis.Core;
namespace Anubis.Tests;
/// <summary>Italian formats of SPEC 13.3, with the values of the mockups (appendix F).</summary>
[TestClass]
public sealed class FormatTests
{
private const string Nbsp = " ";
private static readonly TimeZoneInfo _rome = TimeZoneInfo.FindSystemTimeZoneById("Europe/Rome");
[TestMethod]
[TestCategory(Category.Unit)]
[DataRow(1299.84, "1.299,84" + Nbsp + "€")]
[DataRow(10412.46, "10.412,46" + Nbsp + "€")]
[DataRow(0.0, "0,00" + Nbsp + "€")]
[DataRow(-26.0, "−26,00" + Nbsp + "€")]
[DataRow(1234567.891, "1.234.567,89" + Nbsp + "€")]
public void MoneyUsesCommaDotsAndSymbolAfterNonBreakingSpace(double value, string expected) =>
Assert.AreEqual(expected, Format.Money((decimal)value));
[TestMethod]
[TestCategory(Category.Unit)]
public void ResultsCarryPlusAndTypographicMinus()
{
Assert.AreEqual("+412,46" + Nbsp + "€", Format.Money(412.46m, withSign: true));
Assert.AreEqual("−9,53" + Nbsp + "€", Format.Money(-9.53m, withSign: true));
Assert.AreEqual("0,00" + Nbsp + "€", Format.Money(0m, withSign: true));
Assert.AreEqual("259,80" + Nbsp + "$", Format.Money(259.8m, "USD"));
Assert.IsFalse(Format.Money(-1m).Contains('-', StringComparison.Ordinal), "il meno deve essere tipografico");
}
[TestMethod]
[TestCategory(Category.Unit)]
public void RoundingIsHalfAwayFromZero()
{
Assert.AreEqual("0,13" + Nbsp + "€", Format.Money(0.125m));
Assert.AreEqual("−0,13" + Nbsp + "€", Format.Money(-0.125m));
Assert.AreEqual("0,00" + Nbsp + "€", Format.Money(-0.004m), "un valore che arrotondato è zero non ha segno");
}
[TestMethod]
[TestCategory(Category.Unit)]
public void PercentagesAndNumbers()
{
Assert.AreEqual("+4,12%", Format.Percent(4.12m, 2, withSign: true));
Assert.AreEqual("−0,26%", Format.Percent(-0.26m, 2, withSign: true));
Assert.AreEqual("64,1%", Format.Percent(64.1m));
Assert.AreEqual("10.412", Format.Number(10412.46m));
Assert.AreEqual("0,0182", Format.Number(0.0182m, 4));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void SharesAlwaysAddUpToOneHundred()
{
// Appendix F.1: open positions by strategy (F.4) and cash, out of 10.412,46 €.
var shares = Format.Shares([2326.50m, 3899.31m, 445.32m, 3741.33m]);
Assert.AreEqual(100m, shares.Sum());
CollectionAssert.AreEqual(new[] { 22.3m, 37.5m, 4.3m, 35.9m }, shares.ToArray());
Assert.AreEqual(100m, Format.Shares([1m, 1m, 1m]).Sum(), "tre terzi fanno 100");
CollectionAssert.AreEqual(new[] { 33.4m, 33.3m, 33.3m }, Format.Shares([1m, 1m, 1m]).ToArray());
CollectionAssert.AreEqual(new[] { 0m, 0m }, Format.Shares([0m, -5m]).ToArray());
}
[TestMethod]
[TestCategory(Category.Unit)]
public void SharesHoldForAnyWeights() =>
Property.ForAll(
g => Enumerable.Range(0, g.Int(1, 12)).Select(_ => g.Decimal(0m, 10_000m, 2)).ToArray(),
weights =>
{
var shares = Format.Shares(weights, 1);
if (weights.Any(w => w > 0))
{
Assert.AreEqual(100m, shares.Sum());
}
Assert.IsTrue(shares.All(s => s >= 0));
});
[TestMethod]
[TestCategory(Category.Unit)]
public void SpokenDatesInItalianTime()
{
var now = new DateTimeOffset(2026, 10, 9, 6, 21, 0, TimeSpan.Zero); // 08:21 in Rome
Assert.AreEqual("Oggi 06:10", Format.ShortDate(new DateTimeOffset(2026, 10, 9, 4, 10, 0, TimeSpan.Zero), now, _rome));
Assert.AreEqual("Ieri 21:58", Format.ShortDate(new DateTimeOffset(2026, 10, 8, 19, 58, 0, TimeSpan.Zero), now, _rome));
Assert.AreEqual("mar 6 ott", Format.ShortDate(new DateTimeOffset(2026, 10, 6, 13, 41, 0, TimeSpan.Zero), now, _rome));
Assert.AreEqual("mer 31 dic 2025", Format.ShortDate(new DateTimeOffset(2025, 12, 31, 10, 0, 0, TimeSpan.Zero), now, _rome));
Assert.AreEqual("Venerdì 9 ottobre 2026, ore 08:21", Format.LongDateTime(now, _rome));
Assert.AreEqual("12 agosto 2026", Format.LongDate(new DateOnly(2026, 8, 12)));
Assert.AreEqual("4 secondi fa", Format.Ago(TimeSpan.FromSeconds(4)));
Assert.AreEqual("1 minuto fa", Format.Ago(TimeSpan.FromSeconds(65)));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void CsvHasBomSemicolonsAndDecimalComma()
{
var bytes = Format.Csv(["Strumento", "Valore €", "Nota"], [["BTC/EUR", 1299.84m, "stop; mobile"], ["AAPL", -2.57m, null]]);
CollectionAssert.AreEqual(Encoding.UTF8.GetPreamble(), bytes.Take(3).ToArray());
var text = Encoding.UTF8.GetString(bytes, 3, bytes.Length - 3);
Assert.AreEqual("Strumento;Valore €;Nota\r\nBTC/EUR;1299,84;\"stop; mobile\"\r\nAAPL;-2,57;\r\n", text);
}
}
+199
View File
@@ -0,0 +1,199 @@
using Anubis.Platform;
namespace Anubis.Tests;
/// <summary>Startup configuration in Docker and on desktop (issue #7, SPEC 15.1, 15.6).</summary>
[TestClass]
public sealed class PlatformTests
{
private static readonly string _key = new('k', 40);
private static Dictionary<string, string?> Env(params (string Key, string? Value)[] values)
{
var env = new Dictionary<string, string?>
{
["ANUBIS_DB_ENGINE"] = "sqlite",
["ANUBIS_SECRET_KEY"] = _key,
["ANUBIS_ADMIN_PASSWORD"] = "initial-pass-1",
};
foreach (var (key, value) in values)
{
env[key] = value;
}
return env;
}
[TestMethod]
[TestCategory(Category.Unit)]
public void DockerWithSqliteNeedsNothingElse()
{
var config = DockerPlatform.Load(Env(), "/data");
Assert.IsTrue(config.IsComplete, string.Join("; ", config.Problems.Select(p => p.What)));
Assert.AreEqual(DbEngine.Sqlite, config.Db!.Engine);
Assert.AreEqual(Path.Combine("/data", "db", "anubis.sqlite3"), config.Db.SqlitePath);
Assert.AreEqual(8787, config.Port);
Assert.AreEqual(99, config.Puid);
Assert.AreEqual(100, config.Pgid);
Assert.IsFalse(config.AllowLive);
Assert.AreEqual("Europe/Rome", config.TimeZone.Id);
Assert.IsTrue(config.SecretKey.HasKey);
Assert.HasCount(32, config.SecretKey.GetOrCreateKey());
}
[TestMethod]
[TestCategory(Category.Unit)]
public void DockerPostgresUsesDefaultsAndNeverShowsThePassword()
{
var config = DockerPlatform.Load(Env(("ANUBIS_DB_ENGINE", "postgres"), ("ANUBIS_DB_HOST", "192.168.30.23"), ("ANUBIS_DB_PASSWORD", "pg-password-xyz")));
Assert.IsTrue(config.IsComplete);
Assert.AreEqual(5432, config.Db!.Port);
Assert.AreEqual("anubis", config.Db.Database);
Assert.AreEqual("anubis", config.Db.User);
Assert.IsFalse(config.Db.Describe().Contains("pg-password-xyz", StringComparison.Ordinal));
Assert.IsFalse(config.Db.ToString().Contains("pg-password-xyz", StringComparison.Ordinal));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void MissingOrWrongValuesBecomeProblemsAndNoDatabaseIsChosen()
{
var empty = DockerPlatform.Load(new Dictionary<string, string?>());
Assert.IsNull(empty.Db, "senza ANUBIS_DB_ENGINE nessun database viene scelto al posto dell'utente");
CollectionAssert.IsSubsetOf(new[] { "ANUBIS_DB_ENGINE", "ANUBIS_SECRET_KEY", "ANUBIS_ADMIN_PASSWORD" }, empty.Problems.Select(p => p.Setting).ToList());
Assert.IsTrue(empty.Problems.All(p => p.Remedy.Length > 0));
var wrong = DockerPlatform.Load(Env(("ANUBIS_DB_ENGINE", "mysql")));
Assert.IsNull(wrong.Db);
Assert.IsFalse(wrong.IsComplete);
var postgresWithoutHost = DockerPlatform.Load(Env(("ANUBIS_DB_ENGINE", "postgres")));
Assert.IsNull(postgresWithoutHost.Db, "PostgreSQL incompleto non ripiega su SQLite");
CollectionAssert.IsSubsetOf(new[] { "ANUBIS_DB_HOST", "ANUBIS_DB_PASSWORD" }, postgresWithoutHost.Problems.Select(p => p.Setting).ToList());
var shortKey = DockerPlatform.Load(Env(("ANUBIS_SECRET_KEY", "short")));
Assert.IsTrue(shortKey.Problems.Any(p => p.Setting == "ANUBIS_SECRET_KEY"));
var badLive = DockerPlatform.Load(Env(("ANUBIS_ALLOW_LIVE", "yes")));
Assert.IsFalse(badLive.AllowLive);
Assert.IsTrue(badLive.Problems.Any(p => p.Setting == "ANUBIS_ALLOW_LIVE"));
var badZone = DockerPlatform.Load(Env(("TZ", "Mars/Olympus")));
Assert.IsTrue(badZone.Problems.Any(p => p.Setting == "TZ"));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void OptionalKeysAreReadWithTheDemoSuffix()
{
var config = DockerPlatform.Load(Env(("OKX_API_KEY_DEMO", "demo-key-123456"), ("TELEGRAM_CHAT_ID", "12345")));
Assert.AreEqual("demo-key-123456", config.EnvironmentKeys["OKX_API_KEY_DEMO"]);
Assert.AreEqual("12345", config.EnvironmentKeys["TELEGRAM_CHAT_ID"]);
Assert.IsFalse(config.EnvironmentKeys.ContainsKey("OKX_API_KEY"));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TomlSubsetParsesAndRejectsWithLineNumbers()
{
var values = Toml.Parse("""
# comment
allow_live = false
port = 8_787 # trailing comment
name = "a \"quoted\" # not a comment"
[database]
engine = "postgres"
""");
Assert.IsFalse((bool)values["allow_live"]);
Assert.AreEqual(8787L, values["port"]);
Assert.AreEqual("a \"quoted\" # not a comment", values["name"]);
Assert.AreEqual("postgres", values["database.engine"]);
var error = Assert.Throws<FormatException>(() => Toml.Parse("a = 1\nb = [1, 2]\n"));
Assert.Contains("Riga 2", error.Message);
Assert.Throws<FormatException>(() => Toml.Parse("a = 1\na = 2"));
Assert.Throws<FormatException>(() => Toml.Parse("a = \"open"));
}
[TestMethod]
[TestCategory(Category.Integration)]
public void DesktopStartsFromAnEmptyFolderAndKeepsSecretsOutOfConfigToml()
{
var folder = TempFolder.Create("desktop");
try
{
var data = new DataDirectory(folder);
var store = ProtectedSecretKey.DefaultStore(data);
var first = DesktopPlatform.Load(data, store);
Assert.IsTrue(first.NeedsFirstRun);
Assert.IsFalse(first.IsComplete);
var key = first.SecretKey.GetOrCreateKey();
DesktopPlatform.WriteConfig(data, store, new DbSettings { Engine = DbEngine.Postgres, Host = "localhost", Password = "fake-pg-pass-1" });
var text = File.ReadAllText(data.ConfigFile);
Assert.Contains("allow_live = false", text);
Assert.IsFalse(text.Contains("fake-pg-pass-1", StringComparison.Ordinal), "la password del database non va in config.toml");
Assert.IsFalse(text.Contains(Convert.ToBase64String(key), StringComparison.Ordinal), "la chiave dei segreti non va in config.toml");
Assert.IsFalse(text.Contains("secret", StringComparison.OrdinalIgnoreCase) && text.Contains("key =", StringComparison.Ordinal));
var second = DesktopPlatform.Load(data, store);
Assert.IsTrue(second.IsComplete, string.Join("; ", second.Problems.Select(p => p.What)));
Assert.AreEqual("fake-pg-pass-1", second.Db!.Password);
CollectionAssert.AreEqual(key, second.SecretKey.GetOrCreateKey(), "la chiave resta la stessa tra un avvio e l'altro");
Assert.IsFalse(second.AllowLive);
Assert.IsFalse(second.AllowNetwork);
DesktopPlatform.WriteConfig(data, store, new DbSettings { Engine = DbEngine.Sqlite });
var sqlite = DesktopPlatform.Load(data, store);
Assert.AreEqual(data.SqliteFile, sqlite.Db!.SqlitePath);
}
finally
{
TempFolder.Delete(folder);
}
}
[TestMethod]
[TestCategory(Category.Unit)]
public void BrokenConfigTomlIsAProblemNotAGuess()
{
var folder = TempFolder.Create("desktop-bad");
try
{
var data = new DataDirectory(folder);
File.WriteAllText(data.ConfigFile, "[database]\nengine = sqlite\n");
var config = DesktopPlatform.Load(data, ProtectedSecretKey.DefaultStore(data));
Assert.IsNull(config.Db);
Assert.IsFalse(config.IsComplete);
Assert.Contains("Riga 2", config.Problems[0].What);
}
finally
{
TempFolder.Delete(folder);
}
}
[TestMethod]
[TestCategory(Category.Unit)]
public void DataFolderHasTheLayoutOfSpec152()
{
var folder = TempFolder.Create("layout");
try
{
var data = new DataDirectory(Path.Combine(folder, "data"));
data.Ensure();
foreach (var name in new[] { "db", "models", "research", "import", "backups", "logs" })
{
Assert.IsTrue(Directory.Exists(Path.Combine(data.Root, name)), name);
}
Assert.AreEqual(Path.Combine(data.Root, "installation.json"), data.InstallationFile);
}
finally
{
TempFolder.Delete(folder);
}
}
}
+6 -1
View File
@@ -53,6 +53,11 @@ public sealed partial class SecretScanTests
Assert.IsFalse(LooksLikeSecret("REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}"));
Assert.IsFalse(LooksLikeSecret("private const string SecretKeyVariable = \"ANUBIS_SECRET_KEY\";"));
Assert.IsFalse(LooksLikeSecret("OKX_API_PASSPHRASE=<passphrase-123>"));
// Code that assigns a computed value is not a secret.
Assert.IsFalse(LooksLikeSecret("var key = RandomNumberGenerator.GetBytes(32);"));
Assert.IsFalse(LooksLikeSecret("builder.Password = Uri.UnescapeDataString(userInfo[1]);"));
Assert.IsFalse(LooksLikeSecret("?secret={Base32.Encode(secret)}&issuer=x"));
}
private static bool LooksLikeSecret(string line) =>
@@ -80,6 +85,6 @@ public sealed partial class SecretScanTests
// Variables named like the project's secrets (…KEY, …SECRET, …TOKEN, …PASSPHRASE, …PASSWORD) with a value
// of at least 8 characters that mixes letters and digits, as real keys and passwords do.
[GeneratedRegex("""(?i)[A-Za-z0-9_\-]*(key|secret|token|passphrase|password)["']?\s*[:=]\s*["']?(?<value>(?=[^\s"',;#]*\d)(?=[^\s"',;#]*[A-Za-z])[^\s"',;#]{8,})""")]
[GeneratedRegex("""(?i)[A-Za-z0-9_\-]*(key|secret|token|passphrase|password)["']?\s*[:=]\s*["']?(?<value>(?=[^\s"',;#]*\d)(?=[^\s"',;#]*[A-Za-z])[^\s"',;#(){}\[\]<>]{8,})(?=$|[\s"',;#])""")]
private static partial Regex NamedSecret();
}
+264
View File
@@ -0,0 +1,264 @@
using System.Text;
using Anubis.Access;
using Anubis.Core;
using Anubis.Db;
using Anubis.Platform;
namespace Anubis.Tests;
/// <summary>Installation identity, settings, secrets (issues #7, #10).</summary>
[TestClass]
public sealed class StoresTests
{
private static readonly byte[] _key = Enumerable.Range(1, 32).Select(i => (byte)i).ToArray();
[TestMethod]
[TestCategory(Category.Integration)]
public async Task InstallationIdentityAndFingerprint()
{
var clock = new ManualClock(new DateTimeOffset(2026, 10, 9, 6, 21, 0, TimeSpan.Zero));
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
var folder = TempFolder.Create("installation");
try
{
var data = new DataDirectory(folder);
var first = await Installation.CheckAsync(test.Db, data, clock).ConfigureAwait(false);
Assert.AreEqual(IdentityVerdict.Created, first.Verdict);
Assert.IsTrue(File.Exists(data.InstallationFile));
Assert.AreEqual(IdentityVerdict.Match, (await Installation.CheckAsync(test.Db, data, clock).ConfigureAwait(false)).Verdict);
// Data folder lost: rewritten from the database.
File.Delete(data.InstallationFile);
Assert.AreEqual(IdentityVerdict.FileRestored, (await Installation.CheckAsync(test.Db, data, clock).ConfigureAwait(false)).Verdict);
// A stale copy of the database: same installation, older fingerprint.
var before = Installation.ReadFile(data)!;
Installation.WriteFile(data, before with { Fingerprint = "newer" });
var stale = await Installation.CheckAsync(test.Db, data, clock).ConfigureAwait(false);
Assert.AreEqual(IdentityVerdict.StaleDatabase, stale.Verdict);
Assert.IsFalse(stale.CanStart);
// Another installation's folder.
Installation.WriteFile(data, before with { InstallationId = Guid.NewGuid() });
Assert.AreEqual(IdentityVerdict.DifferentInstallation, (await Installation.CheckAsync(test.Db, data, clock).ConfigureAwait(false)).Verdict);
// The user adopts this database: new fingerprint on both sides, protected restart on.
var renewed = await Installation.RenewAsync(test.Db, data, clock, adoptDatabaseIdentity: true).ConfigureAwait(false);
Assert.AreEqual(before.InstallationId, renewed.InstallationId);
Assert.AreNotEqual(before.Fingerprint, renewed.Fingerprint);
var row = await Installation.ReadRowAsync(test.Db).ConfigureAwait(false);
Assert.IsTrue(row!.ProtectedRestart);
Assert.AreEqual(IdentityVerdict.Match, (await Installation.CheckAsync(test.Db, data, clock).ConfigureAwait(false)).Verdict);
// An empty database while the folder belongs to an installation: nothing is created.
await using var empty = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
var check = await Installation.CheckAsync(empty.Db, data, clock).ConfigureAwait(false);
Assert.AreEqual(IdentityVerdict.EmptyDatabase, check.Verdict);
Assert.IsNull(await Installation.ReadRowAsync(empty.Db).ConfigureAwait(false));
Installation.StartOver(data, clock);
Assert.AreEqual(IdentityVerdict.Created, (await Installation.CheckAsync(empty.Db, data, clock).ConfigureAwait(false)).Verdict);
}
finally
{
TempFolder.Delete(folder);
}
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task SettingsKeepAChangeLogAndStartupValuesAreReadOnly()
{
var clock = new ManualClock(new DateTimeOffset(2026, 10, 9, 6, 21, 0, TimeSpan.Zero));
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
var bus = new EventBus();
using var changes = bus.Subscribe<SettingChanged>();
var settings = new SettingsStore(test.Db, clock, bus, new Dictionary<string, StartupOverride>
{
["appearance.currency"] = new("USD", "variabile d'ambiente di prova"),
});
Assert.AreEqual("auto", (await settings.GetAsync("appearance.theme").ConfigureAwait(false)).Value);
await settings.SetAsync("appearance.theme", "dark", "admin").ConfigureAwait(false);
clock.Advance(TimeSpan.FromMinutes(1));
await settings.SetAsync("appearance.theme", "light", "admin").ConfigureAwait(false);
await settings.SetAsync("appearance.theme", "light", "admin").ConfigureAwait(false);
Assert.AreEqual("light", (await settings.GetAsync("appearance.theme").ConfigureAwait(false)).Value);
var history = await settings.HistoryAsync("appearance.theme").ConfigureAwait(false);
Assert.HasCount(2, history, "un valore uguale non crea una voce");
Assert.AreEqual(("dark", "light"), (history[0].OldValue, history[0].NewValue));
Assert.AreEqual(("auto", "dark"), (history[1].OldValue, history[1].NewValue));
var currency = await settings.GetAsync("appearance.currency").ConfigureAwait(false);
Assert.IsTrue(currency.ReadOnly);
Assert.AreEqual("USD", currency.Value);
await Assert.ThrowsAsync<ReadOnlySettingException>(() => settings.SetAsync("appearance.currency", "EUR", "admin")).ConfigureAwait(false);
await Assert.ThrowsAsync<ArgumentException>(() => settings.SetAsync("appearance.theme", "pink", "admin")).ConfigureAwait(false);
Assert.IsTrue(changes.TryRead(out var changed));
Assert.AreEqual("dark", changed!.Value);
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task SecretsAreEncryptedNeverLoggedAndEnvironmentWins()
{
var clock = new ManualClock(new DateTimeOffset(2026, 10, 9, 6, 21, 0, TimeSpan.Zero));
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
var secrets = new SecretStore(test.Db, clock, _key, new Dictionary<string, string> { ["OKX_API_KEY_DEMO"] = "from-environment-1" });
const string value = "alpaca-paper-secret-0123456789";
await secrets.SetAsync("ALPACA_API_SECRET_DEMO", value, "admin").ConfigureAwait(false);
var stored = await test.Db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT ciphertext FROM secrets", r => r.Bytes("ciphertext"))).ConfigureAwait(false);
Assert.IsFalse(Encoding.UTF8.GetString(stored!).Contains(value, StringComparison.Ordinal), "nel database il segreto è cifrato");
Assert.AreEqual(value, await secrets.RevealAsync("ALPACA_API_SECRET_DEMO").ConfigureAwait(false));
Assert.IsTrue((await secrets.StatusAsync("ALPACA_API_SECRET_DEMO").ConfigureAwait(false)).IsSet);
Assert.IsFalse(Redactor.Redact("got " + value).Contains(value, StringComparison.Ordinal), "un segreto letto viene filtrato dai registri");
var history = await new SettingsStore(test.Db, clock, new EventBus()).HistoryAsync("secret:ALPACA_API_SECRET_DEMO").ConfigureAwait(false);
Assert.AreEqual("impostato", history.Single().NewValue);
Assert.IsFalse(history.Any(h => (h.NewValue ?? "").Contains(value, StringComparison.Ordinal) || (h.OldValue ?? "").Contains(value, StringComparison.Ordinal)));
// Environment keys win and cannot be overwritten from the interface.
Assert.AreEqual("from-environment-1", await secrets.RevealAsync("OKX_API_KEY_DEMO").ConfigureAwait(false));
Assert.IsTrue((await secrets.StatusAsync("OKX_API_KEY_DEMO").ConfigureAwait(false)).FromEnvironment);
await Assert.ThrowsAsync<ReadOnlySettingException>(() => secrets.SetAsync("OKX_API_KEY_DEMO", "x-123456789", "admin")).ConfigureAwait(false);
// With another key the value cannot be read: the error says to enter it again.
var otherKey = new SecretStore(test.Db, clock, Enumerable.Repeat((byte)7, 32).ToArray());
var error = await Assert.ThrowsAsync<System.Security.Cryptography.CryptographicException>(() => otherKey.RevealAsync("ALPACA_API_SECRET_DEMO")).ConfigureAwait(false);
Assert.Contains("Reinserisci", error.Message);
// A value sealed under one name does not open under another.
var sealedValue = secrets.Seal("A", "x");
Assert.Throws<System.Security.Cryptography.CryptographicException>(() => secrets.Open("B", sealedValue));
Assert.IsTrue(await secrets.RemoveAsync("ALPACA_API_SECRET_DEMO", "admin").ConfigureAwait(false));
Assert.IsNull(await secrets.RevealAsync("ALPACA_API_SECRET_DEMO").ConfigureAwait(false));
}
}
/// <summary>Passwords, TOTP, sessions and the attempt limit (issue #11).</summary>
[TestClass]
public sealed class AccessTests
{
[TestMethod]
[TestCategory(Category.Unit)]
public void PasswordHashesVerifyAndCarryTheirCost()
{
var hash = Passwords.Hash("correct horse battery", 1000);
Assert.StartsWith("pbkdf2-sha512$1000$", hash);
Assert.IsTrue(Passwords.Verify("correct horse battery", hash));
Assert.IsFalse(Passwords.Verify("correct horse batterY", hash));
Assert.IsFalse(Passwords.Verify("x", "garbage"));
Assert.IsFalse(Passwords.Verify("x", "pbkdf2-sha512$abc$$"));
Assert.AreNotEqual(Passwords.Hash("same", 1000), Passwords.Hash("same", 1000), "sale diverso a ogni hash");
Assert.IsNotNull(Passwords.Problem("short"));
Assert.IsNotNull(Passwords.Problem("initial-pass-1", "initial-pass-1"));
Assert.IsNull(Passwords.Problem("una password lunga"));
}
// RFC 6238, appendix B: the official test vectors.
[TestMethod]
[TestCategory(Category.Unit)]
[DataRow(59L, "94287082", "46119246", "90693936")]
[DataRow(1111111109L, "07081804", "68084774", "25091201")]
[DataRow(1111111111L, "14050471", "67062674", "99943326")]
[DataRow(1234567890L, "89005924", "91819424", "93441116")]
[DataRow(2000000000L, "69279037", "90698825", "38618901")]
[DataRow(20000000000L, "65353130", "77737706", "47863826")]
public void TotpMatchesTheRfcVectors(long unixSeconds, string sha1, string sha256, string sha512)
{
var at = DateTimeOffset.FromUnixTimeSeconds(unixSeconds);
Assert.AreEqual(sha1, Totp.Compute("12345678901234567890"u8, at, 8, 30, "SHA1"));
Assert.AreEqual(sha256, Totp.Compute("12345678901234567890123456789012"u8, at, 8, 30, "SHA256"));
Assert.AreEqual(sha512, Totp.Compute("1234567890123456789012345678901234567890123456789012345678901234"u8, at, 8, 30, "SHA512"));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TotpAcceptsOneStepOfDriftAndBase32RoundTrips()
{
var secret = Totp.NewSecret();
var now = new DateTimeOffset(2026, 10, 9, 6, 21, 0, TimeSpan.Zero);
Assert.IsTrue(Totp.Verify(secret, Totp.Compute(secret, now), now));
Assert.IsTrue(Totp.Verify(secret, Totp.Compute(secret, now.AddSeconds(-30)), now));
Assert.IsFalse(Totp.Verify(secret, Totp.Compute(secret, now.AddSeconds(-90)), now));
Assert.IsFalse(Totp.Verify(secret, "12a456", now));
CollectionAssert.AreEqual(secret, Base32.Decode(Base32.Encode(secret)));
Assert.AreEqual("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ", Base32.Encode("12345678901234567890"u8));
Assert.StartsWith("otpauth://totp/Anubis:admin?secret=", Totp.Uri("Anubis", "admin", secret));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void LoginLimiterBlocksAnAddressAfterFiveFailures()
{
var clock = new ManualClock(DateTimeOffset.UnixEpoch);
var limiter = new LoginLimiter(clock);
for (var i = 0; i < LoginLimiter.PerAddress; i++)
{
Assert.AreEqual(TimeSpan.Zero, limiter.Wait("10.0.0.2"));
limiter.Failed("10.0.0.2");
}
Assert.AreEqual(LoginLimiter.Window, limiter.Wait("10.0.0.2"));
Assert.AreEqual(TimeSpan.Zero, limiter.Wait("10.0.0.3"), "un altro indirizzo non è bloccato");
clock.Advance(LoginLimiter.Window);
Assert.AreEqual(TimeSpan.Zero, limiter.Wait("10.0.0.2"));
for (var i = 0; i < LoginLimiter.Overall; i++)
{
limiter.Failed("host-" + i);
}
Assert.IsGreaterThan(TimeSpan.Zero, limiter.Wait("10.0.0.9"), "troppi errori in tutto: aspettano tutti");
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task SignInSessionsSecondFactorAndPasswordChange()
{
var clock = new ManualClock(new DateTimeOffset(2026, 10, 9, 6, 21, 0, TimeSpan.Zero));
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
var secrets = new SecretStore(test.Db, clock, new byte[32]);
var access = new AccessStore(test.Db, clock, secrets, iterations: 1000);
Assert.IsTrue(await access.EnsureUserAsync("initial-pass-1", mustChange: true).ConfigureAwait(false));
Assert.IsFalse(await access.EnsureUserAsync("other-password", mustChange: false).ConfigureAwait(false), "un solo utente");
Assert.AreEqual(LoginResult.WrongPassword, (await access.SignInAsync("wrong", null, null, null).ConfigureAwait(false)).Result);
var (result, token) = await access.SignInAsync("initial-pass-1", null, "test", "127.0.0.1").ConfigureAwait(false);
Assert.AreEqual(LoginResult.Ok, result);
var session = await access.ValidateAsync(token).ConfigureAwait(false);
Assert.IsNotNull(session);
Assert.IsTrue(session.User.MustChangePassword);
var stored = await test.Db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT token_hash FROM sessions", r => r.Text("token_hash"))).ConfigureAwait(false);
Assert.AreNotEqual(token, stored, "nel database c'è solo l'impronta del token");
// Second session, then a password change ends every other session.
var (_, other) = await access.SignInAsync("initial-pass-1", null, null, null).ConfigureAwait(false);
Assert.IsTrue(await access.ChangePasswordAsync(session.User.Id, "initial-pass-1", "una password nuova", session.Id).ConfigureAwait(false));
Assert.IsNotNull(await access.ValidateAsync(token).ConfigureAwait(false));
Assert.IsNull(await access.ValidateAsync(other).ConfigureAwait(false));
Assert.IsFalse((await access.ValidateAsync(token).ConfigureAwait(false))!.User.MustChangePassword);
// Second factor.
var secret = Totp.NewSecret();
Assert.IsFalse(await access.EnableSecondFactorAsync(session.User.Id, secret, Totp.Compute(secret, clock.UtcNow.AddMinutes(10))).ConfigureAwait(false));
Assert.IsTrue(await access.EnableSecondFactorAsync(session.User.Id, secret, Totp.Compute(secret, clock.UtcNow)).ConfigureAwait(false));
Assert.AreEqual(LoginResult.SecondFactorNeeded, (await access.SignInAsync("una password nuova", null, null, null).ConfigureAwait(false)).Result);
var badCode = Totp.Compute(secret, clock.UtcNow.AddMinutes(10));
Assert.AreEqual(LoginResult.WrongSecondFactor, (await access.SignInAsync("una password nuova", badCode, null, null).ConfigureAwait(false)).Result);
Assert.AreEqual(LoginResult.Ok, (await access.SignInAsync("una password nuova", Totp.Compute(secret, clock.UtcNow), null, null).ConfigureAwait(false)).Result);
Assert.IsTrue(await access.DisableSecondFactorAsync(session.User.Id, "una password nuova").ConfigureAwait(false));
// Idle and absolute timeouts.
clock.Advance(AccessStore.IdleTimeout);
Assert.IsNull(await access.ValidateAsync(token).ConfigureAwait(false));
var history = await new SettingsStore(test.Db, clock, new EventBus()).HistoryAsync().ConfigureAwait(false);
CollectionAssert.IsSubsetOf(new[] { "security.password", "security.second_factor" }, history.Select(h => h.Key).Distinct().ToList());
}
}
+116 -1
View File
@@ -82,7 +82,7 @@ internal static class TestDatabase
/// <summary>Host and port of the PostgreSQL used by the tests, from <c>ANUBIS_TEST_PG_HOST</c> and <c>ANUBIS_TEST_PG_PORT</c>.</summary>
public static (string Host, int Port) Postgres { get; } = (
Environment.GetEnvironmentVariable("ANUBIS_TEST_PG_HOST") ?? "localhost",
Environment.GetEnvironmentVariable("ANUBIS_TEST_PG_HOST") ?? "127.0.0.1",
int.TryParse(Environment.GetEnvironmentVariable("ANUBIS_TEST_PG_PORT"), out var port) ? port : 55432);
public static async Task<bool> PostgresReachableAsync(TimeSpan timeout)
@@ -100,3 +100,118 @@ internal static class TestDatabase
}
}
}
/// <summary>
/// A fresh, empty database for one test: a SQLite file in a temporary folder, or a new PostgreSQL database
/// created on the test server and dropped afterwards. Never the developer's or the user's database.
/// </summary>
internal sealed class TestDb : IAsyncDisposable
{
private readonly string? _folder;
private readonly string? _postgresName;
private TestDb(Anubis.Platform.DbSettings settings, string? folder, string? postgresName)
{
Settings = settings;
_folder = folder;
_postgresName = postgresName;
Db = Anubis.Db.Database.Open(settings);
}
public Anubis.Platform.DbSettings Settings { get; }
public Anubis.Db.Database Db { get; }
public static string PostgresPassword { get; } = Environment.GetEnvironmentVariable("ANUBIS_TEST_PG_PASSWORD") ?? "anubis-dev";
/// <summary>A database on the engine of this run (ANUBIS_TEST_DB).</summary>
public static Task<TestDb> CreateAsync() =>
CreateAsync(TestDatabase.Engine == "postgres" ? Anubis.Platform.DbEngine.Postgres : Anubis.Platform.DbEngine.Sqlite);
public static async Task<TestDb> CreateAsync(Anubis.Platform.DbEngine engine)
{
if (engine == Anubis.Platform.DbEngine.Sqlite)
{
var folder = TempFolder.Create("db");
return new TestDb(new() { Engine = engine, SqlitePath = Path.Combine(folder, "test.sqlite3") }, folder, null);
}
var name = "anubis_t_" + Guid.NewGuid().ToString("N");
await using (var admin = Anubis.Db.Database.Open(AdminSettings()))
{
await using var connection = await admin.OpenConnectionAsync(CancellationToken.None).ConfigureAwait(false);
await using var command = connection.CreateCommand();
command.CommandText = $"CREATE DATABASE {name}";
await command.ExecuteNonQueryAsync().ConfigureAwait(false);
}
return new TestDb(AdminSettings() with { Database = name }, null, name);
}
/// <summary>True when a PostgreSQL server for tests answers: cross-engine tests run only then.</summary>
public static Task<bool> PostgresAvailableAsync() => TestDatabase.PostgresReachableAsync(TimeSpan.FromSeconds(5));
private static Anubis.Platform.DbSettings AdminSettings() => new()
{
Engine = Anubis.Platform.DbEngine.Postgres,
Host = TestDatabase.Postgres.Host,
Port = TestDatabase.Postgres.Port,
Database = "anubis",
User = "anubis",
Password = PostgresPassword,
};
public async ValueTask DisposeAsync()
{
await Db.DisposeAsync().ConfigureAwait(false);
if (_postgresName is not null)
{
await using var admin = Anubis.Db.Database.Open(AdminSettings());
await using var connection = await admin.OpenConnectionAsync(CancellationToken.None).ConfigureAwait(false);
await using var command = connection.CreateCommand();
command.CommandText = $"DROP DATABASE IF EXISTS {_postgresName} WITH (FORCE)";
await command.ExecuteNonQueryAsync().ConfigureAwait(false);
}
if (_folder is not null)
{
TempFolder.Delete(_folder);
}
}
}
/// <summary>Temporary folders for tests, under the system temp directory.</summary>
internal static class TempFolder
{
public static string Create(string purpose)
{
var path = Path.Combine(Path.GetTempPath(), "anubis-tests", purpose + "-" + Guid.NewGuid().ToString("N")[..12]);
Directory.CreateDirectory(path);
return path;
}
public static void Delete(string path)
{
Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
for (var attempt = 0; attempt < 5; attempt++)
{
try
{
if (Directory.Exists(path))
{
Directory.Delete(path, recursive: true);
}
return;
}
catch (IOException) when (attempt < 4)
{
Thread.Sleep(100);
}
catch (UnauthorizedAccessException) when (attempt < 4)
{
Thread.Sleep(100);
}
}
}
}
+80 -1
View File
@@ -44,6 +44,27 @@
"resolved": "18.11.0",
"contentHash": "MhN9wpvL1Es4hfIYslrsVgIsUdDFxuOBTbAl9mGIMvFo8PP5CLf4DrGdNrfwWSyn0lqi6sssm+I/qkkLL3MU+g=="
},
"Microsoft.Data.Sqlite.Core": {
"type": "Transitive",
"resolved": "10.0.14",
"contentHash": "1p9rO3Q2X/L/9YrYog3vaDzi8u+WZfJCOkDYoHqmofqYP0DLPLPyZcS2Rnh/79JXAodgbs1AgsaNwLpIvC3Xew==",
"dependencies": {
"SQLitePCLRaw.core": "2.1.13"
}
},
"Microsoft.Extensions.DependencyInjection.Abstractions": {
"type": "Transitive",
"resolved": "10.0.0",
"contentHash": "L3AdmZ1WOK4XXT5YFPEwyt0ep6l8lGIPs7F5OOBZc77Zqeo01Of7XXICy47628sdVl0v/owxYJTe86DTgFwKCA=="
},
"Microsoft.Extensions.Logging.Abstractions": {
"type": "Transitive",
"resolved": "10.0.0",
"contentHash": "FU/IfjDfwaMuKr414SSQNTIti/69bHEMb+QKrskRb26oVqpx3lNFXMjs/RC9ZUuhBhcwDM2BwOgoMw+PZ+beqQ==",
"dependencies": {
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.0"
}
},
"Microsoft.Testing.Extensions.Telemetry": {
"type": "Transitive",
"resolved": "2.5.2",
@@ -92,14 +113,72 @@
"resolved": "4.5.2",
"contentHash": "t6Dj9AmWO9IfkMBi3yYTf7bfgSTAetsi4LFA3xGdKbJ+gBbSDqbo41U5vYiW9puD8UGl2elsizNeJVYtwNim0Q=="
},
"SQLitePCLRaw.bundle_e_sqlite3": {
"type": "Transitive",
"resolved": "2.1.13",
"contentHash": "NlDixlC7uHmo+ojXRgkNvN0tQtVGpLDZ3x2OpgNj+G07VHh5cXSszFDrAiC4BpUiPwkcaeuQkMV9WQ123xVtmQ==",
"dependencies": {
"SQLitePCLRaw.lib.e_sqlite3": "2.1.13",
"SQLitePCLRaw.provider.e_sqlite3": "2.1.13"
}
},
"SQLitePCLRaw.core": {
"type": "Transitive",
"resolved": "2.1.13",
"contentHash": "2joofoinuHBFs0nMX3nKuXgxpXryRkCOdM2Ua6HBqQLLy6IW+5f28ZI+HAvMyF8vG7XfNz/lwfBfE6V4juru8Q=="
},
"SQLitePCLRaw.lib.e_sqlite3": {
"type": "Transitive",
"resolved": "2.1.13",
"contentHash": "D2UAuiGxFYBqeRXjjjGgvJ5UQifzn6wefmSqeKU7XcNGKLbJRP6X7kcPZ6opOBJGdCIlgbSxTvDpBbLvsN594A=="
},
"SQLitePCLRaw.provider.e_sqlite3": {
"type": "Transitive",
"resolved": "2.1.13",
"contentHash": "ZU60dSqoSNRe49KcQDUmOVgdRtjITOssVXFtiISs+zJXDI4D2Sndwpn2NOtzDQNPu0ZAvpoLPQ+GLKv6iEZn8Q==",
"dependencies": {
"SQLitePCLRaw.core": "2.1.13"
}
},
"anubis": {
"type": "Project"
"type": "Project",
"dependencies": {
"Microsoft.Data.Sqlite": "[10.0.14, )",
"Npgsql": "[10.0.3, )",
"System.Security.Cryptography.ProtectedData": "[10.0.14, )"
}
},
"anubis.server": {
"type": "Project",
"dependencies": {
"Anubis": "[0.0.1, )"
}
},
"Microsoft.Data.Sqlite": {
"type": "CentralTransitive",
"requested": "[10.0.14, )",
"resolved": "10.0.14",
"contentHash": "muyroan6rKrf0omZL8UF7Kw5uOGp/yBg1L/XWvkFN3WhKaNtK2IWqRZw93nIwVqjhTVDO0l4CEGhHIh+mb+sKg==",
"dependencies": {
"Microsoft.Data.Sqlite.Core": "10.0.14",
"SQLitePCLRaw.bundle_e_sqlite3": "2.1.13",
"SQLitePCLRaw.core": "2.1.13"
}
},
"Npgsql": {
"type": "CentralTransitive",
"requested": "[10.0.3, )",
"resolved": "10.0.3",
"contentHash": "7nb5YzXuvWWJxB0J8DiyL3we+X4FOctZrt0fIBnucOIaIevFEEwGQVZKtiu9olXdlNAK1eNgqSral6r/jlhI4w==",
"dependencies": {
"Microsoft.Extensions.Logging.Abstractions": "10.0.0"
}
},
"System.Security.Cryptography.ProtectedData": {
"type": "CentralTransitive",
"requested": "[10.0.14, )",
"resolved": "10.0.14",
"contentHash": "UuaBUHgmtc9h6CMxaQqFDDJxkS5JVy7XEB+DbtCvD68GFcVM9/AccuNwFpARx8nwCnvjaxzoOBjG3gPz32P1Eg=="
}
}
}