using Microsoft.AspNetCore.Authentication.BearerToken; using Microsoft.Extensions.DependencyInjection; using HealthApp.TestSupport; 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 HttpClient RawClient { get; private set; } = null!; public AuthenticatedTestClient Authentication { get; } = new(); 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.UseEnvironment("Development"); builder.ConfigureKestrel(options => options.Listen(IPAddress.Loopback, 0)); builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection( new Dictionary { ["ConnectionStrings:PatientDatabase"] = ConnectionString, ["InternalAccess:GatewayKey"] = Authentication.GatewayKey })); }); service.UseKestrel(0); using var serviceClient = service.CreateClient(); gateway = new WebApplicationFactory().WithWebHostBuilder(builder => builder.UseEnvironment("Development").ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(Authentication.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/" }))); gateway = gateway.WithWebHostBuilder(builder => builder.ConfigureServices(services => services.PostConfigure("Bearer", options => options.TimeProvider = Authentication.Clock))); RawClient = gateway.CreateClient(); Client = Authentication.Wrap(RawClient); } public async Task RestartHostsAsync() { Client.Dispose(); RawClient.Dispose(); await gateway!.DisposeAsync(); await service!.DisposeAsync(); StartHosts(); } public async Task DisposeAsync() { Client?.Dispose(); RawClient?.Dispose(); if (gateway is not null) await gateway.DisposeAsync(); if (service is not null) await service.DisposeAsync(); if (Directory.Exists(Authentication.KeyDirectory)) Directory.Delete(Authentication.KeyDirectory, true); 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(); } }