2026-07-21 12:19:43 +00:00
|
|
|
using Testcontainers.PostgreSql;
|
|
|
|
|
|
|
|
|
|
namespace Heimdall.Infrastructure.Tests;
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// xUnit collection fixture that manages a PostgreSQL Testcontainer.
|
|
|
|
|
/// One container per test collection — shared across all test classes.
|
2026-07-21 17:46:32 +00:00
|
|
|
/// In CI mode (DATABASE_URL env var), uses the CI-provided PostgreSQL service
|
|
|
|
|
/// instead of starting a Testcontainer.
|
2026-07-21 12:19:43 +00:00
|
|
|
/// </summary>
|
|
|
|
|
public class PostgreSqlContainerFixture : IAsyncLifetime
|
|
|
|
|
{
|
2026-07-21 17:46:32 +00:00
|
|
|
private readonly PostgreSqlContainer? _container;
|
|
|
|
|
private readonly string _connectionString;
|
2026-07-21 12:19:43 +00:00
|
|
|
|
2026-07-21 17:46:32 +00:00
|
|
|
public string ConnectionString => _connectionString;
|
|
|
|
|
|
|
|
|
|
public PostgreSqlContainerFixture()
|
|
|
|
|
{
|
|
|
|
|
var envUrl = Environment.GetEnvironmentVariable("DATABASE_URL");
|
|
|
|
|
if (!string.IsNullOrEmpty(envUrl))
|
|
|
|
|
{
|
|
|
|
|
// CI mode — use the CI-provided PostgreSQL service
|
|
|
|
|
_connectionString = envUrl;
|
|
|
|
|
_container = null;
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
// Local dev — start a Testcontainer
|
|
|
|
|
_container = new PostgreSqlBuilder("postgres:17-alpine")
|
|
|
|
|
.WithDatabase("heimdall_test")
|
|
|
|
|
.WithUsername("heimdall")
|
|
|
|
|
.WithPassword("heimdall_test_pwd")
|
|
|
|
|
.WithCleanUp(true)
|
|
|
|
|
.Build();
|
|
|
|
|
_connectionString = _container.GetConnectionString();
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-07-21 12:19:43 +00:00
|
|
|
|
|
|
|
|
public async Task InitializeAsync()
|
|
|
|
|
{
|
2026-07-21 17:46:32 +00:00
|
|
|
if (_container is not null)
|
|
|
|
|
await _container.StartAsync();
|
2026-07-21 12:19:43 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async Task DisposeAsync()
|
|
|
|
|
{
|
2026-07-21 17:46:32 +00:00
|
|
|
if (_container is not null)
|
|
|
|
|
await _container.DisposeAsync();
|
2026-07-21 12:19:43 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
[CollectionDefinition("PostgresInfra")]
|
|
|
|
|
public class PostgresInfraFixture : ICollectionFixture<PostgreSqlContainerFixture>
|
|
|
|
|
{
|
|
|
|
|
}
|