2026-07-21 17:46:32 +00:00
using Heimdall.Infrastructure.Data ;
using Heimdall.Infrastructure.Data.Interceptors ;
2026-07-21 10:24:11 +00:00
using Heimdall.IntegrationTests.Factories ;
2026-07-21 18:48:39 +00:00
using Heimdall.TestCommon ;
2026-07-21 17:46:32 +00:00
using Microsoft.EntityFrameworkCore ;
2026-07-21 10:24:11 +00:00
namespace Heimdall.IntegrationTests.Controllers ;
/// <summary>
/// Base class for integration tests that need a real PostgreSQL database
/// via Testcontainers. All test classes in the "Postgres" collection share
2026-07-21 18:48:39 +00:00
/// the same PostgreSQL database.
2026-07-21 17:46:32 +00:00
/// Resets the database before each test to guarantee isolation.
2026-07-21 10:24:11 +00:00
/// </summary>
[Collection("Postgres")]
public abstract class PostgresTestBase : IAsyncLifetime
{
private readonly Lazy < HeimdallWebApplicationFactory > _factoryLazy ;
2026-07-21 17:46:32 +00:00
private readonly string _connectionString ;
2026-07-21 10:24:11 +00:00
protected PostgresTestBase ( PostgreSqlContainerFixture postgres )
{
2026-07-21 17:46:32 +00:00
_connectionString = postgres . ConnectionString ;
2026-07-21 10:24:11 +00:00
_factoryLazy = new Lazy < HeimdallWebApplicationFactory >(
() => new HeimdallWebApplicationFactory ( postgres . ConnectionString ));
}
2026-07-21 17:46:32 +00:00
/// <summary>HTTP client factory connected to the real PostgreSQL Database.</summary>
2026-07-21 10:24:11 +00:00
protected HeimdallWebApplicationFactory Factory => _factoryLazy . Value ;
2026-07-22 19:31:51 +00:00
public virtual async Task InitializeAsync ()
2026-07-21 17:46:32 +00:00
{
await ResetDatabaseAsync ();
}
2026-07-21 10:24:11 +00:00
public async Task DisposeAsync ()
{
if ( _factoryLazy . IsValueCreated )
await _factoryLazy . Value . DisposeAsync ();
}
2026-07-21 17:46:32 +00:00
private async Task ResetDatabaseAsync ()
{
var opts = new DbContextOptionsBuilder < AppDbContext >()
. UseNpgsql ( _connectionString )
. Options ;
await using var db = new AppDbContext ( opts , new AuditInterceptor ());
var tables = await db . Database . SqlQuery < string >(
$"""SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_type = 'BASE TABLE' AND table_name != '__EFMigrationsHistory'""" )
. ToListAsync ();
if ( tables . Count > 0 )
{
// Table names from information_schema (not user input) — safe to embed directly
var joined = string . Join ( ", " , tables . Select ( t => "\"" + t + "\"" ));
#pragma warning disable EF1002 , EF1003
await db . Database . ExecuteSqlRawAsync ( "TRUNCATE TABLE " + joined + " CASCADE" );
#pragma warning restore EF1002 , EF1003
}
}
2026-07-21 10:24:11 +00:00
}