Files
Chronos/tests/Titano.Data.Tests/Infrastructure/DatabaseTest.cs
T
Claude ec247a96e1 test(data): PostgreSQL MD5, cleartext, trust and TLS tests can run, and must where TLS is set up
BRIEF §6.3 requires every authentication method and TLS mode against the
PostgreSQL service containers, but the MD5, cleartext and trust tests always
skipped in CI (no roles) and the TLS tests skipped at run time because the
official images start with TLS off. .github/scripts/postgres-ci-setup.sh prepares
a server container: a role per method with its pg_hba line ahead of the image's
SCRAM line (the MD5 password stored as MD5), and TLS with a self-signed
certificate for localhost and 127.0.0.1, enabled with ALTER SYSTEM and a reload
whose rejected lines fail the script. With TITANO_TEST_PG_TLS=1 a server that
refuses TLS fails the TLS tests instead of skipping them, and a new test checks
that verify-full accepts the server whose certificate chains to
TITANO_TEST_PG_ROOT_CERT.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
2026-10-12 10:06:10 +00:00

110 lines
4.6 KiB
C#

using Titano.Data.Postgres;
using Titano.Testing;
namespace Titano.Data.Tests.Infrastructure;
/// <summary>Engine a dialect-parameterised test class runs against.</summary>
public enum Backend
{
SqliteMemory,
SqliteFile,
Postgres,
}
/// <summary>
/// The PostgreSQL server named by <c>TITANO_TEST_PG</c>. Every test gets its own schema (selected through
/// <c>Search Path</c>), so classes run in parallel without seeing each other's tables.
/// </summary>
internal static class PgTestServer
{
public const string Variable = "TITANO_TEST_PG";
private static readonly Lazy<PostgresDatabase> Admin = new(() =>
new PostgresDatabase(PostgresSettings.Parse(ConnectionString) with { MaxPoolSize = 4 }));
public static string ConnectionString =>
Environment.GetEnvironmentVariable(Variable) is { Length: > 0 } cs ? cs : throw new SkipException($"{Variable} not set");
/// <summary>A connection string for another role (MD5, cleartext, trust tests), or a skip when not configured.</summary>
public static string Optional(string variable) =>
Environment.GetEnvironmentVariable(variable) is { Length: > 0 } cs ? cs : throw new SkipException($"{variable} not set");
/// <summary>Set to 1 where the server was set up with TLS (CI): a server that refuses TLS then fails the TLS tests.</summary>
public const string TlsVariable = "TITANO_TEST_PG_TLS";
public static bool TlsExpected => Environment.GetEnvironmentVariable(TlsVariable) is "1" or "true";
public static async Task<string> CreateSchemaAsync(CancellationToken cancellationToken)
{
var name = "titano_t_" + Guid.NewGuid().ToString("N")[..16];
await using var session = await Admin.Value.OpenAsync(cancellationToken);
await session.ExecuteScriptAsync($"CREATE SCHEMA {name}", cancellationToken);
return name;
}
public static async Task DropSchemaAsync(string name)
{
await using var session = await Admin.Value.OpenAsync(CancellationToken.None);
await session.ExecuteScriptAsync($"DROP SCHEMA IF EXISTS {name} CASCADE", CancellationToken.None);
}
public static string With(string connectionString, string extra) => connectionString.TrimEnd(';', ' ') + ";" + extra;
}
/// <summary>
/// Base of tests that run against a fresh database per test: an in-memory or temporary-file SQLite database, or
/// a private schema on the PostgreSQL test server. Everything opened through it is disposed after the test.
/// </summary>
public abstract class DatabaseTest(TestContext context) : IAsyncDisposable
{
private readonly List<IAsyncDisposable> _owned = [];
private readonly List<string> _schemas = [];
protected TestContext Context => context;
protected CancellationToken Ct => context.Cancellation;
protected abstract Backend Backend { get; }
protected Dialect Dialect => Backend == Backend.Postgres ? Dialect.Postgres : Dialect.Sqlite;
/// <summary>Picks the DDL/SQL variant of the current dialect.</summary>
protected string ForDialect(string sqlite, string postgres) => Dialect == Dialect.Postgres ? postgres : sqlite;
/// <summary>Options for a new empty database; <paramref name="multiConnection"/> forces a SQLite file (pooled readers).</summary>
protected async Task<DatabaseOptions> NewOptionsAsync(bool multiConnection = false, string? extraPostgres = null)
{
switch (Backend)
{
case Backend.SqliteMemory when !multiConnection:
return DatabaseOptions.SqliteInMemory();
case Backend.SqliteMemory or Backend.SqliteFile:
return DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory(), "titano.db"));
default:
var schema = await PgTestServer.CreateSchemaAsync(Ct);
_schemas.Add(schema);
var cs = PgTestServer.With(PgTestServer.ConnectionString, $"Search Path={schema};Maximum Pool Size=12");
return DatabaseOptions.Postgres(extraPostgres is null ? cs : PgTestServer.With(cs, extraPostgres));
}
}
/// <summary>Opens a bare database (no migrations).</summary>
protected async Task<IDatabase> OpenDatabaseAsync(bool multiConnection = false)
{
var database = DatabaseFactory.Open(await NewOptionsAsync(multiConnection));
return Own(database);
}
protected T Own<T>(T disposable) where T : IAsyncDisposable
{
_owned.Add(disposable);
return disposable;
}
public async ValueTask DisposeAsync()
{
for (var i = _owned.Count - 1; i >= 0; i--) await _owned[i].DisposeAsync();
foreach (var schema in _schemas) await PgTestServer.DropSchemaAsync(schema);
}
}