using Microsoft.AspNetCore.Authentication.BearerToken; using HealthApp.TestSupport; using Microsoft.AspNetCore.Hosting; using System.Net; using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Npgsql; using PatientProfileService.Persistence; using Xunit; namespace Observation.AcceptanceTests; public sealed class ObservationApiFixture : IAsyncLifetime { private readonly string databaseName = "us04_patient_" + Guid.NewGuid().ToString("N"); private readonly string observationDatabaseName = "us04_observation_" + Guid.NewGuid().ToString("N"); private WebApplicationFactory? observation; private WebApplicationFactory? insights; private WebApplicationFactory? overview; public HttpClient CreateDirectOverviewClient() => overview!.CreateClient(); public string ObservationConnectionString { get; private set; } = ""; 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 HttpClient CreateDirectPatientClient() => service!.CreateClient(); public HttpClient CreateDirectObservationClient() => observation!.CreateClient(); public HttpClient CreateDirectInsightsClient() => insights!.CreateClient(); public AuthenticatedTestClient Authentication { get; } = new(); public Dictionary AdditionalGatewayConfiguration { 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(); await using var observationCommand = new NpgsqlCommand($"CREATE DATABASE {observationDatabaseName}", connection); await observationCommand.ExecuteNonQueryAsync(); ObservationConnectionString = new NpgsqlConnectionStringBuilder(adminConnectionString) { Database = observationDatabaseName }.ConnectionString; await using var observationDb = CreateObservationDbContext(); await observationDb.Database.MigrateAsync(); await observationDb.Database.MigrateAsync(); 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); public ObservationService.Persistence.ObservationDbContext CreateObservationDbContext() => new( new DbContextOptionsBuilder() .UseNpgsql(ObservationConnectionString).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"); builder.ConfigureKestrel(options => options.Listen(IPAddress.Loopback, 0)); builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(Authentication.Configuration()).AddInMemoryCollection(AdditionalGatewayConfiguration).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))); gateway.UseKestrel(0); RawClient = gateway.CreateClient(); Client = Authentication.Wrap(RawClient); observation = new WebApplicationFactory().WithWebHostBuilder(builder => { builder.UseEnvironment("Development"); builder.ConfigureKestrel(options => options.Listen(IPAddress.Loopback, 0)); builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection( new Dictionary { ["ConnectionStrings:ObservationDatabase"] = ObservationConnectionString, ["Services:ApiGateway:BaseUrl"] = Client.BaseAddress!.ToString(), ["InternalAccess:GatewayKey"] = Authentication.GatewayKey, ["Services:ApiGateway:Key"] = Authentication.ObservationServiceKey })); }); observation.UseKestrel(0); using var observationClient = observation.CreateClient(); gateway.Services.GetRequiredService()["Services:Observation:BaseUrl"] = observationClient.BaseAddress!.ToString(); insights = new WebApplicationFactory().WithWebHostBuilder(builder => { builder.UseEnvironment("Development"); builder.ConfigureKestrel(options => options.Listen(IPAddress.Loopback, 0)); builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection( new Dictionary { ["Services:ApiGateway:BaseUrl"] = Client.BaseAddress!.ToString(), ["InternalAccess:GatewayKey"] = Authentication.GatewayKey, ["Services:ApiGateway:Key"] = Authentication.InsightsServiceKey })); }); insights.UseKestrel(0); using var insightsClient = insights.CreateClient(); gateway.Services.GetRequiredService()["Services:Insights:BaseUrl"] = insightsClient.BaseAddress!.ToString(); overview = new WebApplicationFactory().WithWebHostBuilder(builder => { builder.UseEnvironment("Development"); builder.ConfigureKestrel(options => options.Listen(IPAddress.Loopback, 0)); builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection( new Dictionary { ["Services:ApiGateway:BaseUrl"] = Client.BaseAddress!.ToString(), ["InternalAccess:GatewayKey"] = Authentication.GatewayKey, ["Services:ApiGateway:Key"] = Authentication.OverviewServiceKey })); }); overview.UseKestrel(0); using var overviewClient = overview.CreateClient(); gateway.Services.GetRequiredService()["Services:HealthOverview:BaseUrl"] = overviewClient.BaseAddress!.ToString(); } public async Task RestartHostsAsync() { Client.Dispose(); RawClient.Dispose(); if (overview is not null) await overview.DisposeAsync(); if (insights is not null) await insights.DisposeAsync(); if (observation is not null) await observation.DisposeAsync(); await gateway!.DisposeAsync(); if (service is not null) await service.DisposeAsync(); StartHosts(); } public async Task StopOverviewServiceAsync() { if (overview is not null) await overview.DisposeAsync(); overview = null; } public async Task StopInsightsServiceAsync() { if (insights is not null) await insights.DisposeAsync(); insights = null; } public async Task StopObservationServiceAsync() { if (observation is not null) await observation.DisposeAsync(); observation = null; } public async Task StopPatientServiceAsync() { await service!.DisposeAsync(); service = null; } public async Task DisposeAsync() { Client?.Dispose(); RawClient?.Dispose(); if (overview is not null) await overview.DisposeAsync(); if (insights is not null) await insights.DisposeAsync(); if (observation is not null) await observation.DisposeAsync(); 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(); await using var observationCommand = new NpgsqlCommand($"DROP DATABASE IF EXISTS {observationDatabaseName} WITH (FORCE)", connection); await observationCommand.ExecuteNonQueryAsync(); } }