diff --git a/tests/Heimdall.IntegrationTests/Controllers/AgentsControllerTests.cs b/tests/Heimdall.IntegrationTests/Controllers/AgentsControllerTests.cs index 035d21d..90510d1 100644 --- a/tests/Heimdall.IntegrationTests/Controllers/AgentsControllerTests.cs +++ b/tests/Heimdall.IntegrationTests/Controllers/AgentsControllerTests.cs @@ -6,16 +6,14 @@ using Shouldly; namespace Heimdall.IntegrationTests.Controllers; -public class AgentsControllerTests : IClassFixture +public class AgentsControllerTests : PostgresTestBase { - private readonly HeimdallWebApplicationFactory _factory; - - public AgentsControllerTests(HeimdallWebApplicationFactory factory) => _factory = factory; + public AgentsControllerTests(PostgreSqlContainerFixture postgres) : base(postgres) { } [Fact] public async Task RegisterAgent_WithValidToken_ReturnsApiKey() { - var client = await _factory.CreateAdminClientAsync(); + var client = await Factory.CreateAdminClientAsync(); var siteResponse = await client.PostAsJsonAsync("api/sites", new { @@ -44,7 +42,7 @@ public class AgentsControllerTests : IClassFixture +public class AssignmentsControllerTests : PostgresTestBase { - private readonly HeimdallWebApplicationFactory _factory; private HttpClient? _cachedClient; - public AssignmentsControllerTests(HeimdallWebApplicationFactory factory) => _factory = factory; + public AssignmentsControllerTests(PostgreSqlContainerFixture postgres) : base(postgres) { } private async Task AdminClient() { if (_cachedClient is not null) return _cachedClient; - _cachedClient = await _factory.CreateAdminClientAsync(); + _cachedClient = await Factory.CreateAdminClientAsync(); return _cachedClient; } [Fact] public async Task AssignCamera_RequiresAuth_ReturnsUnauthorized() { - var client = _factory.CreateClient(); + var client = Factory.CreateClient(); var response = await client.PostAsJsonAsync("api/assignments", new { cameraId = Guid.NewGuid(), diff --git a/tests/Heimdall.IntegrationTests/Controllers/AuthControllerTests.cs b/tests/Heimdall.IntegrationTests/Controllers/AuthControllerTests.cs index 435ec34..9b2f047 100644 --- a/tests/Heimdall.IntegrationTests/Controllers/AuthControllerTests.cs +++ b/tests/Heimdall.IntegrationTests/Controllers/AuthControllerTests.cs @@ -5,15 +5,15 @@ using Shouldly; namespace Heimdall.IntegrationTests.Controllers; -public class AuthControllerTests : IClassFixture +public class AuthControllerTests : PostgresTestBase { private readonly HttpClient _client; private static readonly SemaphoreSlim _seedLock = new(1, 1); private static bool _seeded; - public AuthControllerTests(HeimdallWebApplicationFactory factory) + public AuthControllerTests(PostgreSqlContainerFixture postgres) : base(postgres) { - _client = factory.CreateClient(); + _client = Factory.CreateClient(); } /// diff --git a/tests/Heimdall.IntegrationTests/Controllers/CamerasControllerTests.cs b/tests/Heimdall.IntegrationTests/Controllers/CamerasControllerTests.cs index 008aada..6bdfb19 100644 --- a/tests/Heimdall.IntegrationTests/Controllers/CamerasControllerTests.cs +++ b/tests/Heimdall.IntegrationTests/Controllers/CamerasControllerTests.cs @@ -5,16 +5,14 @@ using Shouldly; namespace Heimdall.IntegrationTests.Controllers; -public class CamerasControllerTests : IClassFixture +public class CamerasControllerTests : PostgresTestBase { - private readonly HeimdallWebApplicationFactory _factory; - - public CamerasControllerTests(HeimdallWebApplicationFactory factory) => _factory = factory; + public CamerasControllerTests(PostgreSqlContainerFixture postgres) : base(postgres) { } [Fact] public async Task CreateCamera_WithAuth_ReturnsOk() { - var client = await _factory.CreateAdminClientAsync(); + var client = await Factory.CreateAdminClientAsync(); var siteResponse = await client.PostAsJsonAsync("api/sites", new { @@ -38,7 +36,7 @@ public class CamerasControllerTests : IClassFixture -public class DiscoveryControllerTests : IClassFixture +public class DiscoveryControllerTests : PostgresTestBase { - private readonly HeimdallWebApplicationFactory _factory; private HttpClient? _cachedAdminClient; - public DiscoveryControllerTests(HeimdallWebApplicationFactory factory) => _factory = factory; + public DiscoveryControllerTests(PostgreSqlContainerFixture postgres) : base(postgres) { } /// Shared admin client — reused to avoid rate-limit exhaustion. private async Task AdminClientAsync() { if (_cachedAdminClient is not null) return _cachedAdminClient; - _cachedAdminClient = await _factory.CreateAdminClientAsync(); + _cachedAdminClient = await Factory.CreateAdminClientAsync(); return _cachedAdminClient; } @@ -134,7 +133,7 @@ public class DiscoveryControllerTests : IClassFixture +public class EventsControllerTests : PostgresTestBase { - private readonly HeimdallWebApplicationFactory _factory; private HttpClient? _cachedClient; - public EventsControllerTests(HeimdallWebApplicationFactory factory) => _factory = factory; + public EventsControllerTests(PostgreSqlContainerFixture postgres) : base(postgres) { } private async Task AdminClient() { if (_cachedClient is not null) return _cachedClient; - _cachedClient = await _factory.CreateAdminClientAsync(); + _cachedClient = await Factory.CreateAdminClientAsync(); return _cachedClient; } @@ -23,7 +22,7 @@ public class EventsControllerTests : IClassFixture +/// 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. +/// +[Collection("Postgres")] +public abstract class PostgresTestBase : IAsyncLifetime +{ + private readonly Lazy _factoryLazy; + + protected PostgresTestBase(PostgreSqlContainerFixture postgres) + { + _factoryLazy = new Lazy( + () => new HeimdallWebApplicationFactory(postgres.ConnectionString)); + } + + /// HTTP client factory connected to the real PostgreSQL Testcontainer. + protected HeimdallWebApplicationFactory Factory => _factoryLazy.Value; + + public Task InitializeAsync() => Task.CompletedTask; + + public async Task DisposeAsync() + { + if (_factoryLazy.IsValueCreated) + await _factoryLazy.Value.DisposeAsync(); + } +} diff --git a/tests/Heimdall.IntegrationTests/Controllers/SettingsControllerTests.cs b/tests/Heimdall.IntegrationTests/Controllers/SettingsControllerTests.cs index 55634a8..8d2ad9c 100644 --- a/tests/Heimdall.IntegrationTests/Controllers/SettingsControllerTests.cs +++ b/tests/Heimdall.IntegrationTests/Controllers/SettingsControllerTests.cs @@ -12,16 +12,15 @@ namespace Heimdall.IntegrationTests.Controllers; /// NOTE: Rate limit is 10 auth req/min so we cache admin + viewer tokens /// statically (xUnit creates a new class instance per test). /// -public class SettingsControllerTests : IClassFixture +public class SettingsControllerTests : PostgresTestBase { - private readonly HeimdallWebApplicationFactory _factory; private static readonly JsonSerializerOptions JsonOptions = new() { PropertyNameCaseInsensitive = true }; private static string? _adminToken; private static string? _viewerToken; private static readonly object TokenLock = new(); - public SettingsControllerTests(HeimdallWebApplicationFactory factory) => _factory = factory; + public SettingsControllerTests(PostgreSqlContainerFixture postgres) : base(postgres) { } /// Get a shared admin-authenticated HttpClient (lazy, cached token). private async Task GetAdminClientAsync() @@ -34,7 +33,7 @@ public class SettingsControllerTests : IClassFixture RegisterAdminAsync() { var email = $"admin-{Guid.NewGuid()}@heimdall.test"; - var client = _factory.CreateClient(); + var client = Factory.CreateClient(); var response = await client.PostAsJsonAsync("api/auth/register-admin", new { email, @@ -75,7 +74,7 @@ public class SettingsControllerTests : IClassFixture +public class SitesControllerTests : PostgresTestBase { - private readonly HeimdallWebApplicationFactory _factory; - - public SitesControllerTests(HeimdallWebApplicationFactory factory) => _factory = factory; + public SitesControllerTests(PostgreSqlContainerFixture postgres) : base(postgres) { } [Fact] public async Task GetSites_WithoutAuth_ReturnsUnauthorized() { - var client = _factory.CreateClient(); + var client = Factory.CreateClient(); var response = await client.GetAsync("api/sites?page=1&pageSize=10"); response.StatusCode.ShouldBe(System.Net.HttpStatusCode.Unauthorized); } @@ -21,7 +19,7 @@ public class SitesControllerTests : IClassFixture [Fact] public async Task CreateSite_WithAuth_ReturnsOk() { - var client = await _factory.CreateAdminClientAsync(); + var client = await Factory.CreateAdminClientAsync(); var response = await client.PostAsJsonAsync("api/sites", new { name = "Site Test", @@ -36,7 +34,7 @@ public class SitesControllerTests : IClassFixture [Fact] public async Task ListSites_WithAuth_ReturnsOk() { - var client = await _factory.CreateAdminClientAsync(); + var client = await Factory.CreateAdminClientAsync(); var response = await client.GetAsync("api/sites?page=1&pageSize=10"); response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); } diff --git a/tests/Heimdall.IntegrationTests/Controllers/UsersControllerTests.cs b/tests/Heimdall.IntegrationTests/Controllers/UsersControllerTests.cs index 8fda27c..f12441a 100644 --- a/tests/Heimdall.IntegrationTests/Controllers/UsersControllerTests.cs +++ b/tests/Heimdall.IntegrationTests/Controllers/UsersControllerTests.cs @@ -5,16 +5,14 @@ using Shouldly; namespace Heimdall.IntegrationTests.Controllers; -public class UsersControllerTests : IClassFixture +public class UsersControllerTests : PostgresTestBase { - private readonly HeimdallWebApplicationFactory _factory; - - public UsersControllerTests(HeimdallWebApplicationFactory factory) => _factory = factory; + public UsersControllerTests(PostgreSqlContainerFixture postgres) : base(postgres) { } [Fact] public async Task ListUsers_WithAdminAuth_ReturnsOk() { - var client = await _factory.CreateAdminClientAsync(); + var client = await Factory.CreateAdminClientAsync(); var response = await client.GetAsync("api/users?page=1&pageSize=20"); response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); } @@ -22,7 +20,7 @@ public class UsersControllerTests : IClassFixture [Fact] public async Task CreateUser_WithAdminAuth_ReturnsOk() { - var client = await _factory.CreateAdminClientAsync(); + var client = await Factory.CreateAdminClientAsync(); var response = await client.PostAsJsonAsync("api/users", new { email = $"newuser-{Guid.NewGuid()}@heimdall.test", @@ -36,7 +34,7 @@ public class UsersControllerTests : IClassFixture [Fact] public async Task LockUser_WithAdminAuth_ReturnsOk() { - var client = await _factory.CreateAdminClientAsync(); + var client = await Factory.CreateAdminClientAsync(); var createResponse = await client.PostAsJsonAsync("api/users", new { email = $"lockuser-{Guid.NewGuid()}@heimdall.test", @@ -54,7 +52,7 @@ public class UsersControllerTests : IClassFixture [Fact] public async Task ResetPassword_WithAdminAuth_ReturnsTemporaryPassword() { - var client = await _factory.CreateAdminClientAsync(); + var client = await Factory.CreateAdminClientAsync(); var createResponse = await client.PostAsJsonAsync("api/users", new { email = $"resetpwd-{Guid.NewGuid()}@heimdall.test", diff --git a/tests/Heimdall.IntegrationTests/Factories/HeimdallWebApplicationFactory.cs b/tests/Heimdall.IntegrationTests/Factories/HeimdallWebApplicationFactory.cs index 6eb91d7..65187a2 100644 --- a/tests/Heimdall.IntegrationTests/Factories/HeimdallWebApplicationFactory.cs +++ b/tests/Heimdall.IntegrationTests/Factories/HeimdallWebApplicationFactory.cs @@ -5,17 +5,36 @@ namespace Heimdall.IntegrationTests.Factories; /// /// WebApplicationFactory for integration tests. -/// Uses unique InMemory database name per instance to prevent test pollution. +/// By default creates a factory without a connection string. +/// Use to get a factory connected to a +/// real PostgreSQL Testcontainer (see PostgreSqlContainerFixture). /// public class HeimdallWebApplicationFactory : WebApplicationFactory { - private readonly string _dbName = $"HeimdallTest_{Guid.NewGuid():N}"; + private readonly string? _connectionString; + + /// Creates a factory. The SUT uses InMemory unless a connection string is provided. + public HeimdallWebApplicationFactory() { } + + /// Creates a factory connected to a real PostgreSQL instance (e.g. Testcontainer). + public HeimdallWebApplicationFactory(string connectionString) + { + _connectionString = connectionString; + } protected override void ConfigureWebHost(IWebHostBuilder builder) { builder.UseEnvironment("Testing"); builder.UseSetting("Cors:AllowedOrigins", "*"); - builder.UseSetting("InMemoryDbName", _dbName); + + if (_connectionString is not null) + { + // Real PostgreSQL — override the InMemory provider from appsettings.Testing.json + builder.UseSetting("ConnectionStrings:Default", _connectionString); + builder.UseSetting("Database:Provider", "PostgreSQL"); + builder.UseSetting("Database:MigrateOnStartup", "true"); + } + // JWT config builder.UseSetting("Jwt:Key", "ThisIsATestKeyThatIsAtLeast32BytesLong!"); builder.UseSetting("Jwt:RefreshKey", "ThisIsATestRefreshKeyThatIsAlso32Bytes!"); diff --git a/tests/Heimdall.IntegrationTests/Factories/PostgreSqlContainerFixture.cs b/tests/Heimdall.IntegrationTests/Factories/PostgreSqlContainerFixture.cs new file mode 100644 index 0000000..5407df0 --- /dev/null +++ b/tests/Heimdall.IntegrationTests/Factories/PostgreSqlContainerFixture.cs @@ -0,0 +1,40 @@ +using Testcontainers.PostgreSql; + +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). +/// +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(); + + /// Connection string for the running PostgreSQL container. + public string ConnectionString => _container.GetConnectionString(); + + public async Task InitializeAsync() + { + await _container.StartAsync(); + } + + public async Task DisposeAsync() + { + await _container.DisposeAsync(); + } +} + +/// +/// Defines the "Postgres" test collection. All test classes in this +/// collection share the same PostgreSQL container via the fixture. +/// +[CollectionDefinition("Postgres")] +public class PostgresCollectionFixture : ICollectionFixture +{ +} diff --git a/tests/Heimdall.IntegrationTests/Heimdall.IntegrationTests.csproj b/tests/Heimdall.IntegrationTests/Heimdall.IntegrationTests.csproj index a27727a..c4b7d16 100644 --- a/tests/Heimdall.IntegrationTests/Heimdall.IntegrationTests.csproj +++ b/tests/Heimdall.IntegrationTests/Heimdall.IntegrationTests.csproj @@ -14,6 +14,7 @@ +