Files
Heimdall/tests/Heimdall.Infrastructure.Tests/PostgreSqlContainerFixture.cs
T

56 lines
1.7 KiB
C#
Raw Normal View History

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.
/// In CI mode (DATABASE_URL env var), uses the CI-provided PostgreSQL service
/// instead of starting a Testcontainer.
/// </summary>
public class PostgreSqlContainerFixture : IAsyncLifetime
{
private readonly PostgreSqlContainer? _container;
private readonly string _connectionString;
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();
}
}
public async Task InitializeAsync()
{
if (_container is not null)
await _container.StartAsync();
}
public async Task DisposeAsync()
{
if (_container is not null)
await _container.DisposeAsync();
}
}
[CollectionDefinition("PostgresInfra")]
public class PostgresInfraFixture : ICollectionFixture<PostgreSqlContainerFixture>
{
}