fix: resolve CI test failures after InMemory->Testcontainers migration

Three issues fixed:
- Camera.AssignAgent(Guid.Empty) violated FK constraint; changed to
  nullable Guid? and pass null on camera release
- Test fixtures now check DATABASE_URL env var first, falling back to
  Testcontainers locally (CI has no Docker socket)
- Added database truncation before each test via IAsyncLifetime to
  prevent shared state between test methods (InMemory was fresh per test,
  real PostgreSQL persists data)
This commit is contained in:
Arnaud Dartois committed 2026-07-21 17:46:32 +00:00
1 parent 58a3ce5b1b
commit 53e0d4c199
7 files changed
+127 -25

No files matched your search

+1 -1
View File
@@ -91,7 +91,7 @@ public class Camera : Entity<Guid>, IAuditableEntity, ISoftDeletable
// ── Behaviour ───────────────────────────────────────────────────
public void AssignAgent(Guid agentId) => AgentId = agentId;
public void AssignAgent(Guid? agentId) => AgentId = agentId;
public void Update(string name, string? manufacturer, string? model, string? rtspUrl)
{
@@ -253,7 +253,7 @@ public sealed class CameraAssignmentService : ICameraAssignmentService
var camera = await db.Cameras.AsTracking()
.FirstOrDefaultAsync(c => c.Id == cameraId, ct);
if (camera is not null)
camera.AssignAgent(Guid.Empty); // Clear agent
camera.AssignAgent(null); // Clear agent
await db.SaveChangesWithRetryAsync(ct: ct);
@@ -12,7 +12,7 @@ using Shouldly;
namespace Heimdall.Infrastructure.Tests;
[Collection("PostgresInfra")]
public class CameraAssignmentServiceTests
public class CameraAssignmentServiceTests : IAsyncLifetime
{
private readonly IDbContextFactory<AppDbContext> _dbFactory;
private readonly ILogger<CameraAssignmentService> _logger = Substitute.For<ILogger<CameraAssignmentService>>();
@@ -22,6 +22,20 @@ public class CameraAssignmentServiceTests
_dbFactory = CreateFactory(postgres.ConnectionString);
}
public async Task InitializeAsync()
{
await ResetDatabaseAsync();
}
public Task DisposeAsync() => Task.CompletedTask;
private async Task ResetDatabaseAsync()
{
await using var db = await _dbFactory.CreateDbContextAsync();
await db.Database.ExecuteSqlRawAsync(
"TRUNCATE TABLE camera_events, camera_assignments, cameras, agents, sites RESTART IDENTITY CASCADE");
}
private static TestDbContextFactory CreateFactory(string connectionString)
{
var opts = new DbContextOptionsBuilder<AppDbContext>()
@@ -13,7 +13,7 @@ using Shouldly;
namespace Heimdall.Infrastructure.Tests;
[Collection("PostgresInfra")]
public class CameraEventServiceTests
public class CameraEventServiceTests : IAsyncLifetime
{
private readonly IDbContextFactory<AppDbContext> _dbFactory;
private readonly ILogger<CameraEventService> _logger = Substitute.For<ILogger<CameraEventService>>();
@@ -24,6 +24,20 @@ public class CameraEventServiceTests
_dbFactory = CreateFactory(postgres.ConnectionString);
}
public async Task InitializeAsync()
{
await ResetDatabaseAsync();
}
public Task DisposeAsync() => Task.CompletedTask;
private async Task ResetDatabaseAsync()
{
await using var db = await _dbFactory.CreateDbContextAsync();
await db.Database.ExecuteSqlRawAsync(
"TRUNCATE TABLE camera_events, camera_assignments, cameras, agents, sites RESTART IDENTITY CASCADE");
}
private static TestDbContextFactory CreateFactory(string connectionString)
{
var opts = new DbContextOptionsBuilder<AppDbContext>()
@@ -5,26 +5,48 @@ 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 = new PostgreSqlBuilder("postgres:17-alpine")
.WithDatabase("heimdall_test")
.WithUsername("heimdall")
.WithPassword("heimdall_test_pwd")
.WithCleanUp(true)
.Build();
private readonly PostgreSqlContainer? _container;
private readonly string _connectionString;
public string ConnectionString => _container.GetConnectionString();
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()
{
await _container.StartAsync();
if (_container is not null)
await _container.StartAsync();
}
public async Task DisposeAsync()
{
await _container.DisposeAsync();
if (_container is not null)
await _container.DisposeAsync();
}
}
@@ -1,4 +1,7 @@
using Heimdall.Infrastructure.Data;
using Heimdall.Infrastructure.Data.Interceptors;
using Heimdall.IntegrationTests.Factories;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.IntegrationTests.Controllers;
@@ -6,26 +9,53 @@ namespace Heimdall.IntegrationTests.Controllers;
/// Base class for integration tests that need a real PostgreSQL database
/// via Testcontainers. All test classes in the "Postgres" collection share
/// the same PostgreSQL container.
/// Resets the database before each test to guarantee isolation.
/// </summary>
[Collection("Postgres")]
public abstract class PostgresTestBase : IAsyncLifetime
{
private readonly Lazy<HeimdallWebApplicationFactory> _factoryLazy;
private readonly string _connectionString;
protected PostgresTestBase(PostgreSqlContainerFixture postgres)
{
_connectionString = postgres.ConnectionString;
_factoryLazy = new Lazy<HeimdallWebApplicationFactory>(
() => new HeimdallWebApplicationFactory(postgres.ConnectionString));
}
/// <summary>HTTP client factory connected to the real PostgreSQL Testcontainer.</summary>
/// <summary>HTTP client factory connected to the real PostgreSQL Database.</summary>
protected HeimdallWebApplicationFactory Factory => _factoryLazy.Value;
public Task InitializeAsync() => Task.CompletedTask;
public async Task InitializeAsync()
{
await ResetDatabaseAsync();
}
public async Task DisposeAsync()
{
if (_factoryLazy.IsValueCreated)
await _factoryLazy.Value.DisposeAsync();
}
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
}
}
}
@@ -6,27 +6,49 @@ namespace Heimdall.IntegrationTests.Factories;
/// xUnit collection fixture that manages a PostgreSQL Testcontainer
/// for integration tests. One container per test collection (shared
/// across all test classes in the same collection).
/// 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 = new PostgreSqlBuilder("postgres:17-alpine")
.WithDatabase("heimdall_test")
.WithUsername("heimdall")
.WithPassword("heimdall_test_pwd")
.WithCleanUp(true)
.Build();
private readonly PostgreSqlContainer? _container;
private readonly string _connectionString;
/// <summary>Connection string for the running PostgreSQL container.</summary>
public string ConnectionString => _container.GetConnectionString();
/// <summary>Connection string for the running PostgreSQL instance.</summary>
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()
{
await _container.StartAsync();
if (_container is not null)
await _container.StartAsync();
}
public async Task DisposeAsync()
{
await _container.DisposeAsync();
if (_container is not null)
await _container.DisposeAsync();
}
}