using Testcontainers.PostgreSql; using Xunit; namespace Heimdall.TestCommon; /// /// 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. /// public sealed class PostgreSqlContainerFixture : IAsyncLifetime { private static readonly PostgreSqlContainer Container = new PostgreSqlBuilder("postgres:17-alpine") .WithDatabase("heimdall_test") .WithUsername("heimdall") .WithPassword("heimdall_test_pwd") .WithCleanUp(true) .Build(); private static readonly object RefLock = new(); private static int _refCount; #pragma warning disable CA1822 // Member does not access instance data public string ConnectionString => Container.GetConnectionString(); #pragma warning restore CA1822 public async Task InitializeAsync() { bool shouldStart; lock (RefLock) { _refCount++; shouldStart = _refCount == 1; } if (shouldStart) await Container.StartAsync(); } public async Task DisposeAsync() { bool shouldStop; lock (RefLock) { _refCount--; shouldStop = _refCount == 0; } if (shouldStop) await Container.DisposeAsync(); } } // Collection definitions are in each test project assembly // (xUnit requires [CollectionDefinition] in the same assembly as the test).