chore: vire toute trace d'InMemory, remplace par Testcontainers PostgreSQL

- Supprime InMemory de tous les .csproj (Infrastructure, Domain.Tests, IntegrationTests)\n- Supprime le branchement Database:Provider=InMemory de DependencyInjection.cs\n  (plus que du PostgreSQL natif)\n- Infrastructure.Tests: CameraAssignment + CameraEvent tests -> Testcontainers\n- PostgreSqlContainerFixture ajoute aux Infrastructure.Tests\n- appsettings.Testing.json: retire Database:Provider et Hangfire:Enabled\n- 4 tests echouent encore: bugs pre-existants masques par InMemory\n  (FK non respectees, donnees de test erronees)\n\nTests: 222/226 passed (4 pre-existants lies aux FK)
This commit is contained in:
Arnaud Dartois committed 2026-07-21 12:19:43 +00:00
1 parent ee7894646f
commit 58a3ce5b1b
12 files changed
+77 -55

No files matched your search

@@ -22,32 +22,19 @@ public static class DependencyInjection
this IServiceCollection services,
IConfiguration configuration)
{
var dbProvider = configuration.GetValue<string>("Database:Provider") ?? "PostgreSQL";
// EF Core interceptor (registered as singleton — it is stateless)
services.AddSingleton<AuditInterceptor>();
if (dbProvider == "InMemory")
{
var dbName = configuration.GetValue<string>("InMemoryDbName") ?? "HeimdallTestDb";
services.AddDbContext<AppDbContext>(options =>
options.UseInMemoryDatabase(dbName));
services.AddDbContextFactory<AppDbContext>(options =>
options.UseInMemoryDatabase(dbName));
}
else
{
var connectionString = Environment.GetEnvironmentVariable("DATABASE_URL")
?? configuration.GetConnectionString("Default")
?? throw new InvalidOperationException(
"Database connection string is not configured. Set DATABASE_URL env var or ConnectionStrings:Default.");
services.AddDbContext<AppDbContext>(options =>
options.UseNpgsql(connectionString, npgsql =>
npgsql.MigrationsHistoryTable("__EFMigrationsHistory", "public")));
services.AddDbContextFactory<AppDbContext>(options =>
options.UseNpgsql(connectionString, npgsql =>
npgsql.MigrationsHistoryTable("__EFMigrationsHistory", "public")));
}
var connectionString = Environment.GetEnvironmentVariable("DATABASE_URL")
?? configuration.GetConnectionString("Default")
?? throw new InvalidOperationException(
"Database connection string is not configured. Set DATABASE_URL env var or ConnectionStrings:Default.");
services.AddDbContext<AppDbContext>(options =>
options.UseNpgsql(connectionString, npgsql =>
npgsql.MigrationsHistoryTable("__EFMigrationsHistory", "public")));
services.AddDbContextFactory<AppDbContext>(options =>
options.UseNpgsql(connectionString, npgsql =>
npgsql.MigrationsHistoryTable("__EFMigrationsHistory", "public")));
// Identity
services.AddIdentity<AppUser, AppRole>(options =>
@@ -14,7 +14,7 @@
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="10.0.8" />
<PackageReference Include="Microsoft.AspNetCore.DataProtection.Extensions" Version="10.0.8" />
<PackageReference Include="Npgsql" Version="10.0.3" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.3" />
@@ -1,12 +1,8 @@
{
"Database": {
"Provider": "InMemory",
"MigrateOnStartup": false
},
"DataProtection": {
"Mode": "Ephemeral"
},
"Hangfire": {
"Enabled": false
}
}
@@ -9,7 +9,7 @@
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="10.0.8" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
<PackageReference Include="NSubstitute" Version="6.0.0" />
<PackageReference Include="Shouldly" Version="4.3.0" />
@@ -2,6 +2,7 @@ using Heimdall.Application.Services;
using Heimdall.Domain.Entities;
using Heimdall.Domain.Enums;
using Heimdall.Infrastructure.Data;
using Heimdall.Infrastructure.Data.Interceptors;
using Heimdall.Infrastructure.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
@@ -10,22 +11,28 @@ using Shouldly;
namespace Heimdall.Infrastructure.Tests;
[Collection("PostgresInfra")]
public class CameraAssignmentServiceTests
{
private readonly IDbContextFactory<AppDbContext> _dbFactory;
private readonly ILogger<CameraAssignmentService> _logger = Substitute.For<ILogger<CameraAssignmentService>>();
public CameraAssignmentServiceTests()
public CameraAssignmentServiceTests(PostgreSqlContainerFixture postgres)
{
_dbFactory = CreateFactory();
_dbFactory = CreateFactory(postgres.ConnectionString);
}
private static TestDbContextFactory CreateFactory()
private static TestDbContextFactory CreateFactory(string connectionString)
{
var opts = new DbContextOptionsBuilder<AppDbContext>()
.UseInMemoryDatabase($"AssignTest-{Guid.NewGuid()}")
.UseNpgsql(connectionString, npgsql =>
npgsql.MigrationsHistoryTable("__EFMigrationsHistory", "public"))
.Options;
// Ensure tables exist
using var ctx = new AppDbContext(opts, new AuditInterceptor());
ctx.Database.EnsureCreated();
return new TestDbContextFactory(opts);
}
@@ -3,6 +3,7 @@ using Heimdall.Application.Services;
using Heimdall.Domain.Entities;
using Heimdall.Domain.Enums;
using Heimdall.Infrastructure.Data;
using Heimdall.Infrastructure.Data.Interceptors;
using Heimdall.Infrastructure.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
@@ -11,23 +12,29 @@ using Shouldly;
namespace Heimdall.Infrastructure.Tests;
[Collection("PostgresInfra")]
public class CameraEventServiceTests
{
private readonly IDbContextFactory<AppDbContext> _dbFactory;
private readonly ILogger<CameraEventService> _logger = Substitute.For<ILogger<CameraEventService>>();
private readonly IServiceProvider _serviceProvider = Substitute.For<IServiceProvider>();
public CameraEventServiceTests()
public CameraEventServiceTests(PostgreSqlContainerFixture postgres)
{
_dbFactory = CreateFactory();
_dbFactory = CreateFactory(postgres.ConnectionString);
}
private static TestDbContextFactory CreateFactory()
private static TestDbContextFactory CreateFactory(string connectionString)
{
var opts = new DbContextOptionsBuilder<AppDbContext>()
.UseInMemoryDatabase($"EventTest-{Guid.NewGuid()}")
.UseNpgsql(connectionString, npgsql =>
npgsql.MigrationsHistoryTable("__EFMigrationsHistory", "public"))
.Options;
// Ensure tables exist
using var ctx = new AppDbContext(opts, new AuditInterceptor());
ctx.Database.EnsureCreated();
return new TestDbContextFactory(opts);
}
@@ -12,6 +12,7 @@
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
<PackageReference Include="NSubstitute" Version="6.0.0" />
<PackageReference Include="Shouldly" Version="4.3.0" />
<PackageReference Include="Testcontainers.PostgreSql" Version="4.13.0" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.4" />
</ItemGroup>
@@ -0,0 +1,34 @@
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.
/// </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();
public string ConnectionString => _container.GetConnectionString();
public async Task InitializeAsync()
{
await _container.StartAsync();
}
public async Task DisposeAsync()
{
await _container.DisposeAsync();
}
}
[CollectionDefinition("PostgresInfra")]
public class PostgresInfraFixture : ICollectionFixture<PostgreSqlContainerFixture>
{
}
@@ -29,7 +29,7 @@ public class AuthControllerTests : PostgresTestBase
{
if (_seeded) return;
// First registration is auto-admin (no prior users in the InMemory DB)
// First registration is auto-admin (no prior users in the DB)
var adminEmail = $"admin-{Guid.NewGuid()}@heimdall.test";
var regResponse = await _client.PostAsJsonAsync("api/auth/register", new
{
@@ -96,7 +96,7 @@ public class SettingsControllerTests : PostgresTestBase
var client = Factory.CreateClient();
// First registration is auto-admin (no prior users in the InMemory DB)
// First registration is auto-admin (no prior users in the DB)
var adminEmail = $"seed-admin-{Guid.NewGuid()}@heimdall.test";
var regResponse = await client.PostAsJsonAsync("api/auth/register-admin", new
{
@@ -5,18 +5,13 @@ namespace Heimdall.IntegrationTests.Factories;
/// <summary>
/// WebApplicationFactory for integration tests.
/// By default creates a factory without a connection string.
/// Use <see cref="WithPostgreSql"/> to get a factory connected to a
/// real PostgreSQL Testcontainer (see PostgreSqlContainerFixture).
/// Requires a PostgreSQL connection string from <see cref="PostgreSqlContainerFixture"/>.
/// </summary>
public class HeimdallWebApplicationFactory : WebApplicationFactory<Program>
{
private readonly string? _connectionString;
private readonly string _connectionString;
/// <summary>Creates a factory. The SUT uses InMemory unless a connection string is provided.</summary>
public HeimdallWebApplicationFactory() { }
/// <summary>Creates a factory connected to a real PostgreSQL instance (e.g. Testcontainer).</summary>
/// <summary>Creates a factory connected to a real PostgreSQL instance via Testcontainers.</summary>
public HeimdallWebApplicationFactory(string connectionString)
{
_connectionString = connectionString;
@@ -27,13 +22,8 @@ public class HeimdallWebApplicationFactory : WebApplicationFactory<Program>
builder.UseEnvironment("Testing");
builder.UseSetting("Cors:AllowedOrigins", "*");
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");
}
builder.UseSetting("ConnectionStrings:Default", _connectionString);
builder.UseSetting("Database:MigrateOnStartup", "true");
// JWT config
builder.UseSetting("Jwt:Key", "ThisIsATestKeyThatIsAtLeast32BytesLong!");
@@ -10,7 +10,7 @@
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.4" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.10" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="10.0.10" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
<PackageReference Include="NSubstitute" Version="6.0.0" />
<PackageReference Include="Shouldly" Version="4.3.0" />