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.
57 lines
1.6 KiB
C#
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).
|