using Microsoft.AspNetCore.Hosting; using System.Net; using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Npgsql; using PatientProfileService.Persistence; using Xunit; namespace PatientProfile.AcceptanceTests; public sealed class PatientApiFixture : IAsyncLifetime { private readonly string databaseName = "us01_" + Guid.NewGuid().ToString("N"); private string adminConnectionString = ""; private WebApplicationFactory? service; private WebApplicationFactory? gateway; public string ConnectionString { get; private set; } = ""; public HttpClient Client { get; private set; } = null!; public async Task InitializeAsync() { adminConnectionString = Environment.GetEnvironmentVariable("TEST_POSTGRES_CONNECTION") ?? throw new InvalidOperationException( "Set TEST_POSTGRES_CONNECTION to a PostgreSQL connection with permission to create test databases."); await using var connection = new NpgsqlConnection(adminConnectionString); await connection.OpenAsync(); await using var command = new NpgsqlCommand($"CREATE DATABASE {databaseName}", connection); await command.ExecuteNonQueryAsync(); ConnectionString = new NpgsqlConnectionStringBuilder(adminConnectionString) { Database = databaseName }.ConnectionString; await using var db = CreateDbContext(); await db.Database.MigrateAsync(); // Applying the committed migration twice must be harmless. await db.Database.MigrateAsync(); StartHosts(); } public PatientDbContext CreateDbContext() => new( new DbContextOptionsBuilder().UseNpgsql(ConnectionString).Options); private void StartHosts() { service = new WebApplicationFactory().WithWebHostBuilder(builder => { builder.ConfigureKestrel(options => options.Listen(IPAddress.Loopback, 0)); builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection( new Dictionary { ["ConnectionStrings:PatientDatabase"] = ConnectionString })); }); service.UseKestrel(0); using var serviceClient = service.CreateClient(); gateway = new WebApplicationFactory().WithWebHostBuilder(builder => builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection( new Dictionary { ["Services:PatientProfile:BaseUrl"] = serviceClient.BaseAddress!.ToString(), ["Services:Insights:BaseUrl"] = "http://127.0.0.1:1/", ["Services:Observation:BaseUrl"] = "http://127.0.0.1:1/" }))); Client = gateway.CreateClient(); } public async Task RestartHostsAsync() { Client.Dispose(); await gateway!.DisposeAsync(); await service!.DisposeAsync(); StartHosts(); } public async Task DisposeAsync() { Client?.Dispose(); if (gateway is not null) await gateway.DisposeAsync(); if (service is not null) await service.DisposeAsync(); if (string.IsNullOrEmpty(adminConnectionString)) return; NpgsqlConnection.ClearAllPools(); await using var connection = new NpgsqlConnection(adminConnectionString); await connection.OpenAsync(); await using var command = new NpgsqlCommand($"DROP DATABASE IF EXISTS {databaseName} WITH (FORCE)", connection); await command.ExecuteNonQueryAsync(); } }