using System.Net; using System.Runtime.Versioning; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; using Npgsql; using Xunit; namespace Deployment.AcceptanceTests; [SupportedOSPlatform("linux")] public sealed class InstallationTests(DeploymentFixture fixture) : IClassFixture { [Fact] public async Task A_selected_service_release_can_be_built_into_a_relative_output_directory() { var result = await DeploymentFixture.Run("bash", [Path.Combine(DeploymentFixture.Repository, "deploy/build-release.sh"), "--output", "single-release", "--services", "insights"], new() { ["HEALTHAPP_DOTNET"] = fixture.Dotnet }, fixture.Temporary); Assert.Equal(0, result.Code); var release = Path.Combine(fixture.Temporary, "single-release"); Assert.True(File.Exists(Path.Combine(release, "services/insights/InsightsService.dll"))); Assert.Single(Directory.GetDirectories(Path.Combine(release, "services"))); Assert.True(File.Exists(Path.Combine(release, "install.sh"))); Assert.True(File.Exists(Path.Combine(release, "INSTALLATION.md"))); } [Theory] [InlineData("insights", 1)] [InlineData("patient-profile,observation", 2)] [InlineData("all", 5)] public async Task Only_selected_payloads_configuration_and_independent_units_are_installed(string selection, int count) { var root = Path.Combine(fixture.Temporary, "selection-" + Guid.NewGuid().ToString("N")); var installed = await fixture.Install(root, selection); Assert.Equal(0, installed.Code); var payloads = Directory.GetDirectories(Path.Combine(root, "opt/healthapp")).Select(Path.GetFileName).Order().ToArray(); var expected = selection == "all" ? DeploymentFixture.Services : selection.Split(','); Assert.Equal(count, payloads.Length); Assert.Equal(expected.Order(), payloads); foreach (var service in expected) { var env = Path.Combine(root, "etc/healthapp", service + ".env"); Assert.Equal(await File.ReadAllTextAsync(Path.Combine(fixture.Configuration, service + ".env")), await File.ReadAllTextAsync(env)); Assert.Equal(UnixFileMode.UserRead | UnixFileMode.UserWrite, File.GetUnixFileMode(env)); var unit = await File.ReadAllTextAsync(Path.Combine(root, "etc/systemd/system", "healthapp-" + service + ".service")); Assert.Contains("ExecStart=/usr/bin/dotnet /opt/healthapp/" + service + "/" + DeploymentFixture.Assembly(service) + ".dll", unit); Assert.Contains("EnvironmentFile=/etc/healthapp/" + service + ".env", unit); Assert.DoesNotContain("Requires=healthapp-", unit); Assert.DoesNotContain("PartOf=", unit); Assert.DoesNotContain("BindsTo=", unit); } // A repeated install must not overwrite live configuration or application files. var repeated = await fixture.Install(root, selection); Assert.NotEqual(0, repeated.Code); Assert.Contains("Already installed", repeated.Output); } [Fact] public async Task Remote_configuration_is_preserved_as_data_without_executing_shell_text() { var config = Path.Combine(fixture.Temporary, "remote-config"); Directory.CreateDirectory(config); var marker = Path.Combine(fixture.Temporary, "must-not-exist"); var text = "ASPNETCORE_ENVIRONMENT=Production\n" + "Services__ApiGateway__BaseUrl=https://remote-gateway.example.test:5443/\n" + "Services__ApiGateway__Key=externally-provisioned-credential-with-at-least-32-characters\n" + "InternalAccess__GatewayKey=another-externally-provisioned-credential-with-at-least-32-characters\n" + $"UninterpretedValue=\"$(touch {marker})\"\n"; await File.WriteAllTextAsync(Path.Combine(config, "insights.env"), text); var root = Path.Combine(fixture.Temporary, "remote-root"); var result = await DeploymentFixture.Run("bash", [Path.Combine(fixture.Bundle, "install.sh"), "--services", "insights", "--config-dir", config, "--root", root]); Assert.Equal(0, result.Code); Assert.Equal(text, await File.ReadAllTextAsync(Path.Combine(root, "etc/healthapp/insights.env"))); Assert.False(File.Exists(marker)); Assert.Single(Directory.GetDirectories(Path.Combine(root, "opt/healthapp"))); } [Theory] [InlineData("unknown")] [InlineData("insights,insights")] [InlineData("insights,")] public async Task Invalid_service_selection_is_rejected_without_creating_an_installation(string selection) { var root = Path.Combine(fixture.Temporary, "invalid-" + Guid.NewGuid().ToString("N")); var result = await fixture.Install(root, selection); Assert.NotEqual(0, result.Code); Assert.False(Directory.Exists(root)); } [Fact] public async Task Missing_configuration_for_any_selected_service_rejects_the_whole_install_before_writes() { var config = Path.Combine(fixture.Temporary, "partial-config"); Directory.CreateDirectory(config); File.Copy(Path.Combine(fixture.Configuration, "insights.env"), Path.Combine(config, "insights.env")); var root = Path.Combine(fixture.Temporary, "partial-root"); var result = await DeploymentFixture.Run("bash", [Path.Combine(fixture.Bundle, "install.sh"), "--services", "insights,observation", "--config-dir", config, "--root", root]); Assert.NotEqual(0, result.Code); Assert.False(Directory.Exists(root)); } [Theory] [InlineData("patient-profile")] [InlineData("observation")] [InlineData("insights")] [InlineData("health-overview")] [InlineData("api-gateway")] public async Task A_single_installed_service_starts_and_stops_without_other_local_service_processes(string service) { var root = Path.Combine(fixture.Temporary, "single-" + service); Assert.Equal(0, (await fixture.Install(root, service)).Code); try { await fixture.Start(service, root); Assert.Single(fixture.Processes); Assert.False(fixture.Processes[service].HasExited); } finally { await fixture.Stop(service); } Assert.Empty(fixture.Processes); } [Theory] [InlineData("--start")] [InlineData("--migrate")] public async Task Offline_staging_rejects_live_actions_without_writing_files(string action) { var root = Path.Combine(fixture.Temporary, "offline-action-" + Guid.NewGuid().ToString("N")); var result = await DeploymentFixture.Run("bash", [Path.Combine(fixture.Bundle, "install.sh"), "--services", "insights", "--config-dir", fixture.Configuration, "--root", root, action]); Assert.NotEqual(0, result.Code); Assert.False(Directory.Exists(root)); } [Fact] public async Task Two_colocated_installed_services_run_with_independent_configuration_and_processes() { var root = Path.Combine(fixture.Temporary, "two-services"); Assert.Equal(0, (await fixture.Install(root, "patient-profile,observation")).Code); try { await fixture.Start("patient-profile", root); await fixture.Start("observation", root); Assert.Equal(2, fixture.Processes.Values.Select(p => p.Id).Distinct().Count()); using var client = new HttpClient(); using var request = new HttpRequestMessage(HttpMethod.Get, fixture.Urls["observation"] + "api/patients/00000000-0000-0000-0000-000000000001/observations?from=2026-09-01&to=2026-09-10"); request.Headers.Add("X-Gateway-Key", fixture.Settings["observation"]["InternalAccess__GatewayKey"]); using var response = await client.SendAsync(request); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("[]", await response.Content.ReadAsStringAsync()); var observationPid = fixture.Processes["observation"].Id; await fixture.Stop("patient-profile"); Assert.False(fixture.Processes["observation"].HasExited); Assert.Equal(observationPid, fixture.Processes["observation"].Id); await fixture.Start("patient-profile", root); Assert.Equal(observationPid, fixture.Processes["observation"].Id); } finally { foreach (var service in fixture.Processes.Keys.ToArray()) await fixture.Stop(service); } } [Fact] public async Task Installed_complete_system_runs_in_five_processes_and_preserves_network_and_persistence_boundaries() { try { foreach (var service in DeploymentFixture.Services) await fixture.Start(service); Assert.Equal(5, fixture.Processes.Values.Select(p => p.Id).Distinct().Count()); using var client = new HttpClient { BaseAddress = new Uri(fixture.Urls["api-gateway"]), Timeout = TimeSpan.FromSeconds(10) }; using var login = await client.PostAsJsonAsync("api/authentication/login", new { accountId = "deployment-patient", password = DeploymentFixture.Password }); Assert.Equal(HttpStatusCode.OK, login.StatusCode); using var tokenJson = JsonDocument.Parse(await login.Content.ReadAsStringAsync()); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenJson.RootElement.GetProperty("accessToken").GetString()); using var profile = await client.PostAsJsonAsync("api/patients", new { name = "Deployed patient", dateOfBirth = "1980-01-01" }); Assert.Equal(HttpStatusCode.Created, profile.StatusCode); using var profileJson = JsonDocument.Parse(await profile.Content.ReadAsStringAsync()); var patient = profileJson.RootElement.GetProperty("patientId").GetGuid(); using var recorded = await client.PostAsJsonAsync($"api/patients/{patient}/observations", new { measuredAt = "2026-09-05T08:00:00", systolic = 128, diastolic = 82, pulse = 68, measurementContext = new { setting = "Home", activityCondition = "AtRest" } }); Assert.Equal(HttpStatusCode.Created, recorded.StatusCode); var overviewPath = $"api/patients/{patient}/overview?from=2026-09-01&to=2026-09-10&setting=Home&activityCondition=AtRest"; using var overview = await client.GetAsync(overviewPath); Assert.Equal(HttpStatusCode.OK, overview.StatusCode); using var overviewJson = JsonDocument.Parse(await overview.Content.ReadAsStringAsync()); Assert.Equal(patient, overviewJson.RootElement.GetProperty("patient").GetProperty("patientId").GetGuid()); Assert.Equal(128, overviewJson.RootElement.GetProperty("latestObservation").GetProperty("systolic").GetInt32()); Assert.Equal(128m, overviewJson.RootElement.GetProperty("insight").GetProperty("averageSystolic").GetDecimal()); Assert.Equal(1, overviewJson.RootElement.GetProperty("insightContributingCount").GetInt32()); foreach (var service in DeploymentFixture.Services) { var peers = fixture.Processes.Where(p => p.Key != service).ToDictionary(p => p.Key, p => p.Value.Id); var oldId = fixture.Processes[service].Id; await fixture.Stop(service); foreach (var (peer, id) in peers) { Assert.Equal(id, fixture.Processes[peer].Id); Assert.False(fixture.Processes[peer].HasExited); } await fixture.Start(service); Assert.NotEqual(oldId, fixture.Processes[service].Id); using var fresh = await client.GetAsync(overviewPath); Assert.Equal(HttpStatusCode.OK, fresh.StatusCode); } // Each DB owns only its documented service's tables; aggregation services have no DB configuration. foreach (var (service, key, owned, absent) in new[] { ("patient-profile", "ConnectionStrings__PatientDatabase", "patient", "blood_pressure_observation"), ("observation", "ConnectionStrings__ObservationDatabase", "blood_pressure_observation", "patient") }) { await using var connection = new NpgsqlConnection(fixture.Settings[service][key]); await connection.OpenAsync(); await using var command = new NpgsqlCommand("SELECT tablename FROM pg_tables WHERE schemaname = 'public'", connection); await using var reader = await command.ExecuteReaderAsync(); List tables = []; while (await reader.ReadAsync()) tables.Add(reader.GetString(0)); Assert.Contains(owned, tables); Assert.DoesNotContain(absent, tables); } Assert.DoesNotContain(fixture.Settings["insights"].Keys, k => k.StartsWith("ConnectionStrings__")); Assert.DoesNotContain(fixture.Settings["health-overview"].Keys, k => k.StartsWith("ConnectionStrings__")); } finally { foreach (var service in fixture.Processes.Keys.ToArray()) await fixture.Stop(service); } } }