Files
Chronos/tests/Titano.Data.Tests/Infrastructure/DatabaseTest.cs
T
Claude 14567ecac3 test(data): cover sessions, SQLite binding and PostgreSQL wire client
Shared session tests run on SQLite and PostgreSQL (types, nulls,
placeholders, transactions, constraint errors, COPY/bulk escaping,
cancellation). PostgreSQL tests cover SCRAM/MD5/cleartext/trust auth,
TLS, result decoding, bytea, LISTEN/NOTIFY, error mapping, pooling and
broken-connection recovery, and the statement cache. In-memory SQLite
now pools shared-cache connections and retries SQLITE_LOCKED.

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

105 lines
4.4 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");
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);
}
}