diff --git a/src/Heimdall.Domain/Entities/Camera.cs b/src/Heimdall.Domain/Entities/Camera.cs index 303b892..8258e24 100644 --- a/src/Heimdall.Domain/Entities/Camera.cs +++ b/src/Heimdall.Domain/Entities/Camera.cs @@ -91,7 +91,7 @@ public class Camera : Entity, 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) { diff --git a/src/Heimdall.Infrastructure/Services/CameraAssignmentService.cs b/src/Heimdall.Infrastructure/Services/CameraAssignmentService.cs index da95473..cdaeba8 100644 --- a/src/Heimdall.Infrastructure/Services/CameraAssignmentService.cs +++ b/src/Heimdall.Infrastructure/Services/CameraAssignmentService.cs @@ -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); diff --git a/tests/Heimdall.Infrastructure.Tests/CameraAssignmentServiceTests.cs b/tests/Heimdall.Infrastructure.Tests/CameraAssignmentServiceTests.cs index 87c5e8b..fb2dc77 100644 --- a/tests/Heimdall.Infrastructure.Tests/CameraAssignmentServiceTests.cs +++ b/tests/Heimdall.Infrastructure.Tests/CameraAssignmentServiceTests.cs @@ -12,7 +12,7 @@ using Shouldly; namespace Heimdall.Infrastructure.Tests; [Collection("PostgresInfra")] -public class CameraAssignmentServiceTests +public class CameraAssignmentServiceTests : IAsyncLifetime { private readonly IDbContextFactory _dbFactory; private readonly ILogger _logger = Substitute.For>(); @@ -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() diff --git a/tests/Heimdall.Infrastructure.Tests/CameraEventServiceTests.cs b/tests/Heimdall.Infrastructure.Tests/CameraEventServiceTests.cs index 082e091..2831244 100644 --- a/tests/Heimdall.Infrastructure.Tests/CameraEventServiceTests.cs +++ b/tests/Heimdall.Infrastructure.Tests/CameraEventServiceTests.cs @@ -13,7 +13,7 @@ using Shouldly; namespace Heimdall.Infrastructure.Tests; [Collection("PostgresInfra")] -public class CameraEventServiceTests +public class CameraEventServiceTests : IAsyncLifetime { private readonly IDbContextFactory _dbFactory; private readonly ILogger _logger = Substitute.For>(); @@ -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() diff --git a/tests/Heimdall.Infrastructure.Tests/PostgreSqlContainerFixture.cs b/tests/Heimdall.Infrastructure.Tests/PostgreSqlContainerFixture.cs index 39d5bc7..d1569ca 100644 --- a/tests/Heimdall.Infrastructure.Tests/PostgreSqlContainerFixture.cs +++ b/tests/Heimdall.Infrastructure.Tests/PostgreSqlContainerFixture.cs @@ -5,26 +5,48 @@ namespace Heimdall.Infrastructure.Tests; /// /// 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. /// 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(); } } diff --git a/tests/Heimdall.IntegrationTests/Controllers/PostgresTestBase.cs b/tests/Heimdall.IntegrationTests/Controllers/PostgresTestBase.cs index f099a41..c83d5e5 100644 --- a/tests/Heimdall.IntegrationTests/Controllers/PostgresTestBase.cs +++ b/tests/Heimdall.IntegrationTests/Controllers/PostgresTestBase.cs @@ -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. /// [Collection("Postgres")] public abstract class PostgresTestBase : IAsyncLifetime { private readonly Lazy _factoryLazy; + private readonly string _connectionString; protected PostgresTestBase(PostgreSqlContainerFixture postgres) { + _connectionString = postgres.ConnectionString; _factoryLazy = new Lazy( () => new HeimdallWebApplicationFactory(postgres.ConnectionString)); } - /// HTTP client factory connected to the real PostgreSQL Testcontainer. + /// HTTP client factory connected to the real PostgreSQL Database. 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() + .UseNpgsql(_connectionString) + .Options; + + await using var db = new AppDbContext(opts, new AuditInterceptor()); + var tables = await db.Database.SqlQuery( + $"""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 + } + } } diff --git a/tests/Heimdall.IntegrationTests/Factories/PostgreSqlContainerFixture.cs b/tests/Heimdall.IntegrationTests/Factories/PostgreSqlContainerFixture.cs index 5407df0..7754bf0 100644 --- a/tests/Heimdall.IntegrationTests/Factories/PostgreSqlContainerFixture.cs +++ b/tests/Heimdall.IntegrationTests/Factories/PostgreSqlContainerFixture.cs @@ -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. /// 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; - /// Connection string for the running PostgreSQL container. - public string ConnectionString => _container.GetConnectionString(); + /// Connection string for the running PostgreSQL instance. + 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(); } }