Files
Heimdall/tests/Heimdall.TestCommon/PostgreSqlContainerFixture.cs
T
Arnaud Dartois 6825880b52 fix: share single PostgreSQL container across test projects via static ref-count
Use a static PostgreSqlContainer with reference counting so both
Infrastructure and Integration test projects share one PostgreSQL
container instead of each starting their own. Fixes resource
conflict in CI where only the first test project could connect.
2026-07-21 19:05:54 +00:00

57 lines
1.6 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.
/// </summary>
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).