CI / Build and test (pull_request) Failing after 2m3s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / Docker image (pull_request) Skipped
CI / Windows tests and installer (pull_request) Skipped
CI / YAML check (pull_request) Successful in 4s
The owner renamed the product and moved the repository to the self-hosted Gitea (https://gitea.encke-hake.ts.net/BalboSoft/Chronos) for more control, and asked for Actions and a first automatic release with the server package and the Windows exe (docs/requests/2026-10-23-chronos-gitea.md). - Chronos everywhere: a byte-exact rename of contents and paths, then a per-language review of the forms the old name's ending had dictated. - Gitea instead of GitHub: the update check, licence, issue and support links read ChronosReleasesUrl; the update check takes the highest stable version, offers a pre-release build its final release and reports a repository it cannot see as a failed check. EULA, security policy and Gitea issue forms live at the repository root. - Gitea Actions for the Linux act_runner (.gitea/workflows): CI, release, nightly image and performance gates in the .NET SDK container with git checkout. The release cross-compiles the Windows programs, checks their icon, version and DPI manifest, packs installers and zips, publishes the Gitea release and pushes the server image (REGISTRY_TOKEN). Windows-only tests run in an opt-in job on a Windows runner (WINDOWS_RUNNER). - New Chronos.Tools commands: zip, gitea-release, postgres-ci (replaces the docker-exec script, which Gitea's service containers do not allow) and pe-check. BREAKING CHANGE: programs, settings, data folders, file types, environment variables and the Docker image use the new name; nothing is migrated from Titano, which never had a release. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
324 lines
16 KiB
C#
324 lines
16 KiB
C#
using System.Diagnostics;
|
|
using System.Diagnostics.CodeAnalysis;
|
|
using System.Security.Authentication;
|
|
using Chronos.Data.Postgres;
|
|
using Chronos.Data.Tests.Infrastructure;
|
|
using Chronos.Testing;
|
|
|
|
namespace Chronos.Data.Tests.Postgres;
|
|
|
|
/// <summary>
|
|
/// Protocol-level tests against a live server (CHRONOS_TEST_PG). Optional: CHRONOS_TEST_PG_MD5/_CLEARTEXT/_TRUST (roles
|
|
/// of the other authentication methods), CHRONOS_TEST_PG_TLS=1 (the server offers TLS) and CHRONOS_TEST_PG_ROOT_CERT (the
|
|
/// PEM its certificate chains to). CI sets them all up (<c>Chronos.Tools postgres-ci</c>).
|
|
/// </summary>
|
|
[RequiresEnvironment(PgTestServer.Variable)]
|
|
public sealed class PgWireTests(TestContext context) : DatabaseTest(context)
|
|
{
|
|
protected override Backend Backend => Backend.Postgres;
|
|
|
|
private async Task<PostgresDatabase> OpenAsync(string? extra = null) =>
|
|
(PostgresDatabase)Own(DatabaseFactory.Open(await NewOptionsAsync(extraPostgres: extra)));
|
|
|
|
/// <summary>A server without TLS skips the TLS tests, unless it was set up with TLS (<see cref="PgTestServer.TlsVariable"/>).</summary>
|
|
[DoesNotReturn]
|
|
private static void WithoutTls(DatabaseConnectionException refusal)
|
|
{
|
|
if (PgTestServer.TlsExpected) Assert.Fail($"{PgTestServer.TlsVariable} says the server offers TLS, but it refused: {refusal.Message}");
|
|
TestContext.Skip("server has no TLS");
|
|
}
|
|
|
|
private async Task<string> AuthenticateAsync(string connectionString)
|
|
{
|
|
var database = Own(new PostgresDatabase(PostgresSettings.Parse(connectionString)));
|
|
await using var session = await database.OpenAsync(Ct);
|
|
return (await session.ScalarAsync<string>("SELECT current_user", [], Ct))!;
|
|
}
|
|
|
|
[Test]
|
|
public async Task ScramSha256Login()
|
|
{
|
|
var settings = PostgresSettings.Parse(PgTestServer.ConnectionString);
|
|
Assert.Equal(settings.Username, await AuthenticateAsync(PgTestServer.ConnectionString));
|
|
}
|
|
|
|
[Test]
|
|
public async Task Md5Login() =>
|
|
Assert.NotNull(await AuthenticateAsync(PgTestServer.Optional("CHRONOS_TEST_PG_MD5")));
|
|
|
|
[Test]
|
|
public async Task CleartextLogin() =>
|
|
Assert.NotNull(await AuthenticateAsync(PgTestServer.Optional("CHRONOS_TEST_PG_CLEARTEXT")));
|
|
|
|
[Test]
|
|
public async Task TrustLogin() =>
|
|
Assert.NotNull(await AuthenticateAsync(PgTestServer.Optional("CHRONOS_TEST_PG_TRUST")));
|
|
|
|
[Test]
|
|
public async Task WrongPasswordIsRejected()
|
|
{
|
|
var wrong = PgTestServer.With(PgTestServer.ConnectionString, "Password=definitely-wrong");
|
|
var error = await Assert.ThrowsAsync<PostgresException>(() => AuthenticateAsync(wrong));
|
|
Assert.Equal("28P01", error.SqlState);
|
|
Assert.Equal("FATAL", error.Severity);
|
|
}
|
|
|
|
[Test]
|
|
public async Task TlsIsNegotiatedWhenRequired()
|
|
{
|
|
PostgresDatabase database;
|
|
try
|
|
{
|
|
database = await OpenAsync("SslMode=Require");
|
|
await using var probe = await database.OpenAsync(Ct);
|
|
}
|
|
catch (DatabaseConnectionException ex) when (ex.Message.Contains("does not support TLS", StringComparison.Ordinal))
|
|
{
|
|
WithoutTls(ex);
|
|
return;
|
|
}
|
|
await using var session = await database.OpenAsync(Ct);
|
|
Assert.True(await session.ScalarAsync<bool>("SELECT ssl FROM pg_stat_ssl WHERE pid = pg_backend_pid()", [], Ct));
|
|
|
|
var plain = await OpenAsync("SslMode=Disable");
|
|
await using var plainSession = await plain.OpenAsync(Ct);
|
|
Assert.False(await plainSession.ScalarAsync<bool>("SELECT ssl FROM pg_stat_ssl WHERE pid = pg_backend_pid()", [], Ct));
|
|
}
|
|
|
|
[Test]
|
|
public async Task VerifyFullRejectsAnUntrustedCertificate()
|
|
{
|
|
var database = await OpenAsync("SslMode=VerifyFull");
|
|
try
|
|
{
|
|
await using var session = await database.OpenAsync(Ct);
|
|
Assert.Fail("A self-signed server certificate must not pass verify-full.");
|
|
}
|
|
catch (DatabaseConnectionException ex) when (ex.Message.Contains("does not support TLS", StringComparison.Ordinal))
|
|
{
|
|
WithoutTls(ex);
|
|
}
|
|
catch (AuthenticationException)
|
|
{
|
|
}
|
|
}
|
|
|
|
[Test]
|
|
public async Task VerifyFullAcceptsACertificateThatChainsToTheConfiguredRoot()
|
|
{
|
|
var root = PgTestServer.Optional("CHRONOS_TEST_PG_ROOT_CERT");
|
|
var database = await OpenAsync($"SslMode=VerifyFull;Root Certificate={root}");
|
|
await using var session = await database.OpenAsync(Ct);
|
|
Assert.True(await session.ScalarAsync<bool>("SELECT ssl FROM pg_stat_ssl WHERE pid = pg_backend_pid()", [], Ct));
|
|
}
|
|
|
|
[Test]
|
|
public async Task DecodesEveryMappedResultType()
|
|
{
|
|
await using var session = await (await OpenAsync()).OpenAsync(Ct);
|
|
var row = await session.QuerySingleAsync(
|
|
"SELECT 'txt'::text, 'vc'::varchar(5), 'bp'::bpchar(4), 7::int2, -8::int4, 9000000000::int8, 1.5::float4, " +
|
|
"-2.25::float8, 'Infinity'::float8, true, '\\x00ff10'::bytea, '2026-09-28 18:30:15.123456+02'::timestamptz, " +
|
|
"'2024-02-29 23:59:58.5'::timestamp, '2026-01-31'::date, '0190a8b4-5c4e-7a1b-9c3d-0123456789ab'::uuid, " +
|
|
"'{\"k\": 1}'::json, '{\"k\": [true]}'::jsonb, 12345678901234567890.123::numeric, NULL::int4", [], Ct);
|
|
Assert.Equal("txt", row.GetString(0));
|
|
Assert.Equal("vc", row.GetString(1));
|
|
Assert.Equal("bp ", row.GetString(2));
|
|
Assert.Equal(7, row.GetInt32(3));
|
|
Assert.Equal(-8, row.GetInt32(4));
|
|
Assert.Equal(9000000000L, row.GetInt64(5));
|
|
Assert.Equal(1.5, row.GetDouble(6));
|
|
Assert.Equal(-2.25, row.GetDouble(7));
|
|
Assert.Equal(double.PositiveInfinity, row.GetDouble(8));
|
|
Assert.True(row.GetBool(9));
|
|
Assert.BytesEqual(new byte[] { 0, 0xFF, 0x10 }, row.GetBytes(10));
|
|
Assert.Equal(new DateTimeOffset(2026, 9, 28, 16, 30, 15, 123, TimeSpan.Zero).AddTicks(4560), row.GetDateTimeOffset(11));
|
|
Assert.Equal(new DateTime(2024, 2, 29, 23, 59, 58, 500), row.GetDateTime(12));
|
|
Assert.Equal(new DateTime(2026, 1, 31), row.GetDateTime(13));
|
|
Assert.Equal(Guid.Parse("0190a8b4-5c4e-7a1b-9c3d-0123456789ab"), row.GetGuid(14));
|
|
Assert.Equal("{\"k\": 1}", row.GetString(15));
|
|
Assert.Equal("{\"k\": [true]}", row.GetString(16));
|
|
Assert.Equal("12345678901234567890.123", row.GetString(17));
|
|
Assert.True(row.IsNull(18));
|
|
}
|
|
|
|
[Test]
|
|
public async Task ByteaTravelsInBinary()
|
|
{
|
|
await using var session = await (await OpenAsync()).OpenAsync(Ct);
|
|
await session.ExecuteScriptAsync("CREATE TABLE blobs (id integer PRIMARY KEY, data bytea)", Ct);
|
|
var all = Enumerable.Range(0, 256).Select(i => (byte)i).ToArray();
|
|
var large = new byte[1 << 20];
|
|
new Random(7).NextBytes(large);
|
|
await session.ExecuteAsync("INSERT INTO blobs VALUES ($1, $2), ($3, $4), ($5, $6)", [1, all, 2, large, 3, Array.Empty<byte>()], Ct);
|
|
var readAll = await session.ScalarAsync<byte[]>("SELECT data FROM blobs WHERE id = 1", [], Ct);
|
|
var readLarge = await session.ScalarAsync<byte[]>("SELECT data FROM blobs WHERE id = 2", [], Ct);
|
|
Assert.BytesEqual(all, readAll);
|
|
Assert.BytesEqual(large, readLarge);
|
|
Assert.Equal(0, (await session.ScalarAsync<byte[]>("SELECT data FROM blobs WHERE id = 3", [], Ct))!.Length);
|
|
Assert.Equal(1L << 20, await session.ScalarAsync<long>("SELECT length(data) FROM blobs WHERE id = $1", [2], Ct));
|
|
}
|
|
|
|
[Test]
|
|
public async Task ListenReceivesNotifications()
|
|
{
|
|
var database = await OpenAsync();
|
|
var listener = Own(await database.CreateListenerAsync(Ct));
|
|
var received = new TaskCompletionSource<PgNotification>(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
listener.Notification += (_, n) => received.TrySetResult(n);
|
|
await listener.ListenAsync("chronos_jobs", Ct);
|
|
|
|
await using (var session = await database.OpenAsync(Ct))
|
|
await session.ExecuteAsync("SELECT pg_notify($1, $2)", ["chronos_jobs", "wake ✓"], Ct);
|
|
|
|
var notification = await received.Task.WaitAsync(TimeSpan.FromSeconds(5), Ct);
|
|
Assert.Equal("chronos_jobs", notification.Channel);
|
|
Assert.Equal("wake ✓", notification.Payload);
|
|
await listener.UnlistenAsync("chronos_jobs", Ct);
|
|
await Assert.ThrowsAsync<PostgresException>(() => listener.ListenAsync("", Ct));
|
|
await listener.ListenAsync("still_usable", Ct);
|
|
}
|
|
|
|
[Test]
|
|
public async Task ServerErrorsMapToTypedExceptions()
|
|
{
|
|
await using var session = await (await OpenAsync()).OpenAsync(Ct);
|
|
await session.ExecuteScriptAsync("CREATE TABLE u (id integer PRIMARY KEY, code text CONSTRAINT u_code_key UNIQUE)", Ct);
|
|
await session.ExecuteAsync("INSERT INTO u VALUES ($1, $2)", [1, "a"], Ct);
|
|
var unique = await Assert.ThrowsAsync<PostgresException>(() => session.ExecuteAsync("INSERT INTO u VALUES ($1, $2)", [2, "a"], Ct));
|
|
Assert.Equal("23505", unique.SqlState);
|
|
Assert.Equal("ERROR", unique.Severity);
|
|
Assert.Equal("u_code_key", unique.ConstraintName);
|
|
Assert.Equal("u", unique.TableName);
|
|
Assert.NotNull(unique.Detail);
|
|
Assert.True(unique.IsUniqueViolation);
|
|
|
|
var syntax = await Assert.ThrowsAsync<PostgresException>(() => session.ExecuteAsync("SELECT * FROM u WHER id = 1", [], Ct));
|
|
Assert.Equal("42601", syntax.SqlState);
|
|
Assert.Equal(22, syntax.Position);
|
|
Assert.Equal(1, await session.ScalarAsync<int>("SELECT 1", [], Ct));
|
|
}
|
|
|
|
[Test]
|
|
public async Task CommitOfAnAbortedTransactionThrows()
|
|
{
|
|
await using var session = await (await OpenAsync()).OpenAsync(Ct);
|
|
await session.ExecuteScriptAsync("CREATE TABLE a (id integer PRIMARY KEY)", Ct);
|
|
var tx = await session.BeginAsync(Ct);
|
|
await session.ExecuteAsync("INSERT INTO a VALUES ($1)", [1], Ct);
|
|
await Assert.ThrowsAsync<PostgresException>(() => session.ExecuteAsync("INSERT INTO a VALUES ($1)", [1], Ct));
|
|
await Assert.ThrowsAsync<InvalidOperationException>(() => tx.CommitAsync(Ct));
|
|
Assert.False(session.InTransaction);
|
|
Assert.Equal(0L, await session.ScalarAsync<long>("SELECT count(*) FROM a", [], Ct));
|
|
}
|
|
|
|
[Test]
|
|
public async Task PoolReusesConnectionsAndHandsOutDistinctOnesConcurrently()
|
|
{
|
|
var database = await OpenAsync("Maximum Pool Size=3;Timeout=2");
|
|
int first;
|
|
await using (var s = await database.OpenAsync(Ct)) first = await s.ScalarAsync<int>("SELECT pg_backend_pid()", [], Ct);
|
|
await using (var s = await database.OpenAsync(Ct)) Assert.Equal(first, await s.ScalarAsync<int>("SELECT pg_backend_pid()", [], Ct));
|
|
|
|
var sessions = new List<IDbSession>();
|
|
for (var i = 0; i < 3; i++) sessions.Add(await database.OpenAsync(Ct));
|
|
var pids = new HashSet<int>();
|
|
foreach (var s in sessions) pids.Add(await s.ScalarAsync<int>("SELECT pg_backend_pid()", [], Ct));
|
|
Assert.Equal(3, pids.Count);
|
|
var watch = Stopwatch.StartNew();
|
|
await Assert.ThrowsAsync<DatabaseConnectionException>(() => database.OpenAsync(Ct));
|
|
Assert.InRange(watch.Elapsed.TotalSeconds, 1.5, 5);
|
|
foreach (var s in sessions) await s.DisposeAsync();
|
|
}
|
|
|
|
[Test]
|
|
public async Task ReadsRecoverFromATerminatedBackend()
|
|
{
|
|
var database = await OpenAsync("Maximum Pool Size=2");
|
|
int victim;
|
|
await using (var s = await database.OpenAsync(Ct)) victim = await s.ScalarAsync<int>("SELECT pg_backend_pid()", [], Ct);
|
|
|
|
var killer = Own(new PostgresDatabase(PostgresSettings.Parse(PgTestServer.ConnectionString)));
|
|
await using (var k = await killer.OpenAsync(Ct))
|
|
Assert.True(await k.ScalarAsync<bool>("SELECT pg_terminate_backend($1)", [victim], Ct));
|
|
await Task.Delay(200, Ct);
|
|
|
|
await using (var s = await database.OpenAsync(Ct))
|
|
{
|
|
var pid = await s.ScalarAsync<int>("SELECT pg_backend_pid()", [], Ct);
|
|
Assert.NotEqual(victim, pid);
|
|
Assert.Equal(2, await s.ScalarAsync<int>("SELECT 1 + 1", [], Ct));
|
|
}
|
|
}
|
|
|
|
[Test]
|
|
public async Task WritesOnABrokenConnectionFailWithoutRetry()
|
|
{
|
|
var database = await OpenAsync("Maximum Pool Size=1");
|
|
await using var session = await database.OpenAsync(Ct);
|
|
await session.ExecuteScriptAsync("CREATE TABLE w (id integer)", Ct);
|
|
var pid = await session.ScalarAsync<int>("SELECT pg_backend_pid()", [], Ct);
|
|
var killer = Own(new PostgresDatabase(PostgresSettings.Parse(PgTestServer.ConnectionString)));
|
|
await using (var k = await killer.OpenAsync(Ct)) await k.ExecuteAsync("SELECT pg_terminate_backend($1)", [pid], Ct);
|
|
await Task.Delay(200, Ct);
|
|
var error = await Assert.ThrowsAsync<DatabaseException>(() => session.ExecuteAsync("INSERT INTO w VALUES ($1)", [1], Ct));
|
|
Assert.True(error.IsTransient);
|
|
}
|
|
|
|
[Test]
|
|
public async Task StatementCacheEvictsAndSurvivesSchemaChanges()
|
|
{
|
|
await using var session = await (await OpenAsync("Statement Cache Size=2")).OpenAsync(Ct);
|
|
await session.ExecuteScriptAsync("CREATE TABLE c (a integer); INSERT INTO c VALUES (1)", Ct);
|
|
for (var i = 0; i < 5; i++) Assert.Equal(i, await session.ScalarAsync<int>($"SELECT {i} + 0 * $1", [i], Ct));
|
|
// Evicted statements are closed with the next command: the cache size plus the counting statement remain.
|
|
Assert.LessOrEqual(await session.ScalarAsync<long>("SELECT count(*) FROM pg_prepared_statements", [], Ct), 3);
|
|
|
|
var first = await session.QuerySingleAsync("SELECT * FROM c", [], Ct);
|
|
Assert.Equal(1, first.FieldCount);
|
|
await session.ExecuteScriptAsync("ALTER TABLE c ADD COLUMN b text DEFAULT 'x'", Ct);
|
|
var second = await session.QuerySingleAsync("SELECT * FROM c", [], Ct);
|
|
Assert.Equal(2, second.FieldCount);
|
|
Assert.Equal("x", second.GetString("b"));
|
|
}
|
|
|
|
[Test]
|
|
public async Task ACommandCannotStartWhileARowStreamIsOpen()
|
|
{
|
|
await using var session = await (await OpenAsync()).OpenAsync(Ct);
|
|
var rows = session.QueryAsync("SELECT generate_series(1, 1000)", [], Ct).GetAsyncEnumerator(Ct);
|
|
Assert.True(await rows.MoveNextAsync());
|
|
await Assert.ThrowsAsync<InvalidOperationException>(() => session.ExecuteAsync("SELECT 1", [], Ct));
|
|
await rows.DisposeAsync();
|
|
Assert.Equal(1, await session.ScalarAsync<int>("SELECT 1", [], Ct));
|
|
}
|
|
|
|
[Test]
|
|
public async Task DisposingABusySessionInATransactionFreesItsPoolSlot()
|
|
{
|
|
var database = await OpenAsync("Maximum Pool Size=1;Timeout=3");
|
|
var session = await database.OpenAsync(Ct);
|
|
await session.ExecuteScriptAsync("CREATE TABLE t (id integer)", Ct);
|
|
var tx = await session.BeginAsync(Ct);
|
|
await session.ExecuteAsync("INSERT INTO t VALUES ($1)", [1], Ct);
|
|
var rows = session.QueryAsync("SELECT generate_series(1, 1000)", [], Ct).GetAsyncEnumerator(Ct);
|
|
Assert.True(await rows.MoveNextAsync());
|
|
await tx.DisposeAsync();
|
|
Assert.True(session.InTransaction, "a busy session cannot roll back yet");
|
|
await session.DisposeAsync();
|
|
|
|
await using var next = await database.OpenAsync(Ct);
|
|
Assert.Equal(0L, await next.ScalarAsync<long>("SELECT count(*) FROM t", [], Ct));
|
|
}
|
|
|
|
[Test]
|
|
public async Task NoticesAndScriptsDoNotDisturbTheSession()
|
|
{
|
|
await using var session = await (await OpenAsync()).OpenAsync(Ct);
|
|
await session.ExecuteScriptAsync("DO $$ BEGIN RAISE NOTICE 'hello from the server'; END $$; CREATE TABLE n (id integer)", Ct);
|
|
Assert.Equal(1, await session.ExecuteAsync("INSERT INTO n VALUES ($1)", [1], Ct));
|
|
await Assert.ThrowsAsync<PostgresException>(() => session.ExecuteScriptAsync("SELECT 1; SELECT * FROM missing_table; SELECT 2", Ct));
|
|
Assert.Equal(1L, await session.ScalarAsync<long>("SELECT count(*) FROM n", [], Ct));
|
|
}
|
|
}
|