using System.Net; using HealthApp.Infrastructure; using HealthApp.Profile.Persistence; using HealthApp.TestSupport; using Microsoft.AspNetCore.Authentication.BearerToken; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Npgsql; using Xunit; namespace PatientProfile.AcceptanceTests; public class PatientApiFixture : IAsyncLifetime { private readonly string databaseName = "architecture_b_" + Guid.NewGuid().ToString("N"); private readonly string runtimeRole = "b_runtime_" + Guid.NewGuid().ToString("N"); private string admin = ""; private WebApplicationFactory? host; public string ConnectionString { get; private set; } = ""; public string RuntimeConnectionString { get; protected set; } = ""; public HttpClient Client { get; private set; } = null!; public HttpClient RawClient { get; private set; } = null!; public AuthenticatedTestClient Authentication { get; } = new(); public Action? ConfigureServices { get; set; } public Dictionary AdditionalGatewayConfiguration { get; } = new(); public async Task InitializeAsync() { admin = Environment.GetEnvironmentVariable("TEST_POSTGRES_CONNECTION") ?? throw new InvalidOperationException("TEST_POSTGRES_CONNECTION required."); await using var c = new NpgsqlConnection(admin); await c.OpenAsync(); await new NpgsqlCommand($"CREATE DATABASE {databaseName}; CREATE ROLE {runtimeRole} LOGIN PASSWORD 'test-runtime-only';", c).ExecuteNonQueryAsync(); ConnectionString = new NpgsqlConnectionStringBuilder(admin) { Database = databaseName, SearchPath = "profile,observations" }.ConnectionString; await using var db = new NpgsqlConnection(ConnectionString); await db.OpenAsync(); var root = FindRoot(); foreach (var _ in new[] { 0, 1 }) foreach (var script in new[] { "Profile", "Observations" }.SelectMany(m => Directory.GetFiles(Path.Combine(root, "src/Modules", m, "Migrations"), "*.sql").Order())) await new NpgsqlCommand(await File.ReadAllTextAsync(script), db).ExecuteNonQueryAsync(); await new NpgsqlCommand($"REVOKE CREATE ON SCHEMA public FROM PUBLIC; GRANT CONNECT ON DATABASE {databaseName} TO {runtimeRole}; GRANT USAGE ON SCHEMA profile TO {runtimeRole}; GRANT SELECT,INSERT,UPDATE ON profile.patient TO {runtimeRole}; GRANT SELECT ON profile.schema_version TO {runtimeRole}; GRANT USAGE ON SCHEMA observations TO {runtimeRole}; GRANT SELECT,INSERT,UPDATE,DELETE ON observations.observation TO {runtimeRole}; GRANT SELECT ON observations.schema_version TO {runtimeRole};", db).ExecuteNonQueryAsync(); RuntimeConnectionString = new NpgsqlConnectionStringBuilder(ConnectionString) { Username = runtimeRole, Password = "test-runtime-only" }.ConnectionString; Start(); } public static string FindRoot() { var d = new DirectoryInfo(AppContext.BaseDirectory); while (d is not null && !File.Exists(Path.Combine(d.FullName, "HealthApp.slnx"))) d = d.Parent; return d?.FullName ?? throw new InvalidOperationException("root missing"); } internal PatientDbContext CreateDbContext() => new(new DbContextOptionsBuilder().UseNpgsql(ConnectionString).Options); private void Start() { host = new WebApplicationFactory().WithWebHostBuilder(b => { b.UseEnvironment("Development"); b.ConfigureKestrel(k => k.Listen(IPAddress.Loopback, 0)); b.ConfigureAppConfiguration((_, c) => c.AddInMemoryCollection(Authentication.Configuration()).AddInMemoryCollection(AdditionalGatewayConfiguration).AddInMemoryCollection(new Dictionary { ["ConnectionStrings:HealthDatabase"] = RuntimeConnectionString })); b.ConfigureServices(s => { s.PostConfigure("Bearer", o => o.TimeProvider = Authentication.Clock); ConfigureServices?.Invoke(s); }); }); host.UseKestrel(0); RawClient = host.CreateClient(); Client = Authentication.Wrap(RawClient); } public virtual async Task RestartHostsAsync() { Client.Dispose(); RawClient.Dispose(); if (host is not null) await host.DisposeAsync(); Start(); } public async Task DisposeAsync() { Client?.Dispose(); RawClient?.Dispose(); if (host is not null) await host.DisposeAsync(); NpgsqlConnection.ClearAllPools(); if (admin.Length > 0) { await using var c = new NpgsqlConnection(admin); await c.OpenAsync(); await new NpgsqlCommand($"DROP DATABASE IF EXISTS {databaseName} WITH(FORCE); DROP ROLE IF EXISTS {runtimeRole};", c).ExecuteNonQueryAsync(); } if (Directory.Exists(Authentication.KeyDirectory)) Directory.Delete(Authentication.KeyDirectory, true); } }