w4c-workflows-api/w4c-workflows-api.Tests/WorkflowsPostgresFixture.cs

54 lines
1.6 KiB
C#
Raw Permalink Normal View History

using Microsoft.EntityFrameworkCore;
using Testcontainers.PostgreSql;
using w4c_workflows.Data;
using Xunit;
namespace w4c_workflows.Tests;
[CollectionDefinition("WorkflowsPostgres")]
public class WorkflowsPostgresCollection : ICollectionFixture<WorkflowsPostgresFixture>
{
}
/// <summary>
/// One Postgres 17 container per collection; applies the EF Core migration once
/// and hands out fresh (scoped-like) DbContext instances per test.
/// </summary>
public sealed class WorkflowsPostgresFixture : IAsyncLifetime
{
private PostgreSqlContainer? _container;
private string _connectionString = "";
public async Task InitializeAsync()
{
_container = new PostgreSqlBuilder()
.WithImage("postgres:17-alpine")
.WithDatabase("w4c_workflows_test")
.WithUsername("w4c")
.WithPassword("w4c_test_pw")
.Build();
await _container.StartAsync();
_connectionString = _container.GetConnectionString() + ";Timezone=UTC";
await using var context = CreateContext();
2026-09-11 22:02:46 +00:00
// Apply the exact production schema (EF migrations + additive raw SQL) via
// the shared applier so the fixture can never drift from Program.cs.
await WorkflowsSchema.ApplyAsync(context, liteMode: false);
}
public async Task DisposeAsync()
{
if (_container is not null)
await _container.DisposeAsync();
}
public WorkflowsDbContext CreateContext()
{
var options = new DbContextOptionsBuilder<WorkflowsDbContext>()
.UseNpgsql(_connectionString)
.Options;
return new WorkflowsDbContext(options);
}
}