Files
Heimdall/tests/Heimdall.TestCommon/PostgreSqlContainerFixture.cs
Arnaud Dartois 2ee12a39f8 fix(test): extension pg_trgm créée dans la fixture Testcontainers
EnsureCreated() ne joue pas les migrations → l'index GIN trigram (AddBusinessEntities)
échouait avec 'operator class gin_trgm_ops does not exist' sur 15 tests
Infrastructure (CameraEventService, CameraAssignment…). La fixture partagée
crée maintenant l'extension une fois au démarrage (idempotent, couvre CI/local).
Infrastructure.Tests : 169/169 verts.
2026-08-12 09:32:54 +02:00

133 lines
4.8 KiB
C#

using Testcontainers.PostgreSql;
using Xunit;
namespace Heimdall.TestCommon;
/// <summary>
/// xUnit collection fixture that manages ONE PostgreSQL Testcontainer
/// shared across ALL test projects via a static container with ref-counting.
/// Only the first fixture to initialize starts the container; only the last
/// to dispose stops it.
///
/// In CI mode (DATABASE_URL env var), skips Testcontainers entirely and
/// uses the CI-provided PostgreSQL service instead — avoids Docker disk
/// space issues and container startup time on CI runners.
/// </summary>
public sealed class PostgreSqlContainerFixture : IAsyncLifetime
{
/// <summary>Null in CI mode (DATABASE_URL env var); non-null in local dev.</summary>
private static readonly PostgreSqlContainer? Container;
/// <summary>Set only in CI mode. Null in local dev — use Container.GetConnectionString().</summary>
private static readonly string? CiConnectionString;
private static readonly object RefLock = new();
private static int _refCount;
static PostgreSqlContainerFixture()
{
var envUrl = Environment.GetEnvironmentVariable("DATABASE_URL");
if (!string.IsNullOrEmpty(envUrl))
{
// CI mode — use the CI-provided PostgreSQL service
CiConnectionString = envUrl;
Container = null;
}
else
{
// Local dev — build a Testcontainer (NOT started yet — StartAsync in InitializeAsync)
Container = new PostgreSqlBuilder("postgres:17-alpine")
.WithDatabase("heimdall_test")
.WithUsername("heimdall")
.WithPassword("heimdall_test_pwd")
.WithCleanUp(true)
.Build();
}
}
/// <summary>
/// Indicates whether the PostgreSQL container started successfully.
/// </summary>
public bool IsAvailable { get; private set; } = true;
/// <summary>
/// Reason the container is unavailable (for test skip messages).
/// </summary>
public string? SkipReason { get; private set; }
/// <summary>
/// Connection string for the PostgreSQL instance.
/// In CI mode returns the DATABASE_URL env var directly.
/// In local dev returns the Testcontainer connection string.
/// WARNING: In local dev, the container must be started (via InitializeAsync)
/// before accessing this property.
/// </summary>
#pragma warning disable CA1822 // Member does not access instance data
public string ConnectionString => CiConnectionString ?? Container!.GetConnectionString();
#pragma warning restore CA1822
public async Task InitializeAsync()
{
bool shouldStart;
lock (RefLock)
{
_refCount++;
shouldStart = _refCount == 1;
}
if (shouldStart && Container is not null)
{
try
{
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));
await Container.StartAsync(cts.Token);
}
catch (Exception ex) when (ex is InvalidOperationException or TimeoutException or TaskCanceledException)
{
IsAvailable = false;
SkipReason = $"PostgreSQL TestContainers unavailable (Docker not running?): {ex.Message}";
}
catch (Exception ex)
{
IsAvailable = false;
SkipReason = $"PostgreSQL TestContainers failed: {ex.Message}";
}
}
// L'extension pg_trgm est requise par l'index GIN trigram (migration
// AddBusinessEntities), mais EnsureCreated() ne joue PAS les migrations :
// sans elle, les requêtes LIKE/trigram sur license_plates échouent
// (operator class "gin_trgm_ops" does not exist). Idempotent.
if (IsAvailable)
{
try
{
await using var conn = new Npgsql.NpgsqlConnection(ConnectionString);
await conn.OpenAsync();
await using var cmd = new Npgsql.NpgsqlCommand("CREATE EXTENSION IF NOT EXISTS pg_trgm;", conn);
await cmd.ExecuteNonQueryAsync();
}
catch (Exception ex)
{
// Non fatal : l'extension peut être gérée par la migration en prod.
Console.WriteLine($"[Testcontainers] pg_trgm unavailable: {ex.Message}");
}
}
}
public async Task DisposeAsync()
{
bool shouldStop;
lock (RefLock)
{
_refCount--;
shouldStop = _refCount == 0;
}
if (shouldStop && Container is not null && IsAvailable)
await Container.DisposeAsync();
}
}
// Collection definitions are in each test project assembly
// (xUnit requires [CollectionDefinition] in the same assembly as the test).