Record Architecture B approval and verified pinned baseline

This commit is contained in:
Steffen committed 2026-10-14 10:58:43 +02:00
1 parent 20ab461c01
commit cee98e7035
158 files changed
+33575

No files matched your search

@@ -0,0 +1,92 @@
using System.Runtime.Versioning;
using Xunit;
namespace Deployment.AcceptanceTests;
[SupportedOSPlatform("linux")]
public sealed class BootstrapTests
{
[Theory]
[InlineData("ubuntu", "24.04", false, false, false)]
[InlineData("ubuntu", "24.04", true, true, false)]
[InlineData("ubuntu", "24.04", true, true, true)]
[InlineData("ubuntu", "26.04", false, true, false)]
[InlineData("ubuntu", "26.04", true, true, true)]
[InlineData("debian", "12", true, false, false)]
[InlineData("debian", "13", false, true, false)]
[InlineData("linuxmint", "22", false, true, false, "ubuntu debian")]
[InlineData("pop", "future", false, false, false, "ubuntu")]
[InlineData("ubuntu", "future", false, false, false)]
[InlineData("debian", "13", false, false, false, "", false)]
[InlineData("linuxmint", "22", false, false, false, "ubuntu debian", false, true, true, "aspnetcore-runtime-10.0 is unavailable")]
[InlineData("debian", "99", false, false, false, "", false, true, false, "No accessible Microsoft Debian 99 repository")]
[InlineData("ubuntu", "26.04", true, true, false, "", true, false, true, "Required package postgresql is unavailable")]
[InlineData("fedora", "44", true, false, false, "", true, true, true, "requires a Debian/Ubuntu-based distribution")]
public async Task Package_provisioning_detects_runtime_and_postgresql_and_installs_only_needed_dependencies(
string distribution, string version, bool runtimeAvailable, bool databaseRequired, bool databaseAvailable,
string ancestry = "", bool runtimePackage = true, bool postgresPackage = true,
bool repositoryAvailable = true, string expectedError = "")
{
var directory = Path.Combine(Path.GetTempPath(), "healthapp-bootstrap-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(directory);
try
{
var log = Path.Combine(directory, "commands");
await File.WriteAllTextAsync(log, "");
var installed = Path.Combine(directory, "runtime-installed");
var script = Path.Combine(directory, "test.sh");
await File.WriteAllTextAsync(script, """
set -euo pipefail
fail() { printf '%s\n' "$*" >&2; exit 1; }
runtime() { if [[ "$RUNTIME_PRESENT" == true || -f "$RUNTIME_INSTALLED" ]]; then printf '%s\n' 'Microsoft.AspNetCore.App 10.0.12 [runtime]'; else return 1; fi; }
apt-get() { printf '%s\n' "apt-get $*" >> "$COMMAND_LOG"; if [[ "$*" == *aspnetcore-runtime-10.0* ]]; then touch "$RUNTIME_INSTALLED"; fi; }
apt-cache() {
if [[ "$2" == aspnetcore-runtime-10.0 && ( "$RUNTIME_PACKAGE" == true || -f "$REPOSITORY_ADDED" ) || "$2" == postgresql && "$POSTGRES_PACKAGE" == true ]]; then
printf '%s\n' ' Candidate: 10.0.1';
else printf '%s\n' ' Candidate: (none)'; fi
}
curl() { [[ "$REPOSITORY_AVAILABLE" == true ]] || return 22; printf '%s\n' "curl $*" >> "$COMMAND_LOG"; }
update-ca-certificates() { :; }
dpkg() { printf '%s\n' "dpkg $*" >> "$COMMAND_LOG"; touch "$REPOSITORY_ADDED"; }
pg_isready() { [[ -f "$DATABASE_READY" ]]; }
systemctl() { printf '%s\n' "systemctl $*" >> "$COMMAND_LOG"; touch "$DATABASE_READY"; }
source "$BOOTSTRAP"
ensure_dependencies "$DISTRO" "$VERSION" /bin/true "$DATABASE_REQUIRED" "$ANCESTRY"
""");
// Runtime is an executable stub; installed packages switch its simulated inventory.
var runtime = Path.Combine(directory, "dotnet");
await File.WriteAllTextAsync(runtime, "#!/bin/bash\nif [[ \"$RUNTIME_PRESENT\" == true || -f \"$RUNTIME_INSTALLED\" ]]; then printf '%s\\n' 'Microsoft.AspNetCore.App 10.0.12 [runtime]'; else exit 1; fi\n");
File.SetUnixFileMode(runtime, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
var body = (await File.ReadAllTextAsync(script)).Replace("/bin/true", "\"$RUNTIME_EXECUTABLE\"");
await File.WriteAllTextAsync(script, body);
var environment = new Dictionary<string, string>
{
["COMMAND_LOG"] = log, ["RUNTIME_INSTALLED"] = installed,
["RUNTIME_PRESENT"] = runtimeAvailable ? "true" : "false", ["RUNTIME_EXECUTABLE"] = runtime,
["DATABASE_READY"] = Path.Combine(directory, "pg-ready"), ["DATABASE_REQUIRED"] = databaseRequired ? "true" : "false",
["ANCESTRY"] = ancestry, ["RUNTIME_PACKAGE"] = runtimePackage ? "true" : "false",
["POSTGRES_PACKAGE"] = postgresPackage ? "true" : "false", ["REPOSITORY_AVAILABLE"] = repositoryAvailable ? "true" : "false",
["REPOSITORY_ADDED"] = Path.Combine(directory, "repository-added"),
["BOOTSTRAP"] = Path.Combine(DeploymentFixture.Repository, "deploy/installer/bootstrap.sh"), ["DISTRO"] = distribution, ["VERSION"] = version
};
if (databaseAvailable) await File.WriteAllTextAsync(environment["DATABASE_READY"], "ready");
var result = await DeploymentFixture.Run("bash", [script], environment);
if (expectedError.Length > 0)
{
Assert.NotEqual(0, result.Code);
Assert.Contains(expectedError, result.Output);
var failedCommands = await File.ReadAllTextAsync(log);
Assert.DoesNotContain("install -y aspnetcore-runtime-10.0", failedCommands);
Assert.DoesNotContain("install -y postgresql", failedCommands);
return;
}
Assert.True(result.Code == 0, result.Output);
var commands = await File.ReadAllTextAsync(log);
Assert.Equal(!runtimeAvailable, commands.Contains("install -y aspnetcore-runtime-10.0"));
Assert.Equal(databaseRequired && !databaseAvailable, commands.Contains("install -y postgresql"));
Assert.Equal(databaseRequired && !databaseAvailable, commands.Contains("systemctl enable --now postgresql"));
Assert.Equal(!runtimeAvailable && !runtimePackage && distribution == "debian", commands.Contains("packages.microsoft.com/config/debian/" + version));
}
finally { Directory.Delete(directory, true); }
}
}
@@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5" PrivateAssets="all" />
<PackageReference Include="Npgsql" Version="10.0.3" />
</ItemGroup>
</Project>
@@ -0,0 +1,197 @@
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using System.Text.Json;
using System.Runtime.Versioning;
using Npgsql;
using Xunit;
namespace Deployment.AcceptanceTests;
[SupportedOSPlatform("linux")]
public sealed class DeploymentFixture : IAsyncLifetime
{
public static readonly string[] Services = ["api-gateway", "patient-profile", "observation", "insights", "health-overview"];
public static string Assembly(string service) => service switch
{
"api-gateway" => "ApiGateway", "patient-profile" => "PatientProfileService",
"observation" => "ObservationService", "insights" => "InsightsService", _ => "HealthOverviewService"
};
public static string Repository
{
get
{
var directory = new DirectoryInfo(AppContext.BaseDirectory);
while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "HealthApp.slnx"))) directory = directory.Parent;
return directory?.FullName ?? throw new InvalidOperationException("Repository root not found.");
}
}
public string Dotnet { get; } = Environment.GetEnvironmentVariable("HEALTHAPP_DOTNET") ??
Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? "dotnet";
public string Temporary { get; } = Path.Combine(Path.GetTempPath(), "healthapp-us16-" + Guid.NewGuid().ToString("N"));
public string Bundle => Path.Combine(Temporary, "release");
public string Deployment => Path.Combine(Temporary, "deployment");
public string AdminFile => Path.Combine(Temporary, "admin.connection");
public string Root => Path.Combine(Temporary, "installed");
public Dictionary<string, string> Urls { get; } = new();
public Dictionary<string, Dictionary<string, string>> Settings { get; } = new();
public Dictionary<string, Process> Processes { get; } = new();
private readonly List<string> databases = [];
public string Admin { get; private set; } = "";
public string Password { get; private set; } = "";
private readonly List<string> roles = [];
public async Task InitializeAsync()
{
Directory.CreateDirectory(Temporary);
Admin = Environment.GetEnvironmentVariable("TEST_POSTGRES_CONNECTION") ?? throw new InvalidOperationException("TEST_POSTGRES_CONNECTION is required.");
var release = await Run("bash", [Path.Combine(Repository, "deploy/build-release.sh"), "--output", Bundle],
new() { ["HEALTHAPP_DOTNET"] = Dotnet });
Assert.True(release.Code == 0, release.Output);
var ports = new Dictionary<string, int>();
foreach (var service in Services)
{
using var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
ports[service] = ((IPEndPoint)listener.LocalEndpoint).Port;
}
var hosts = Services.Select((name, index) => (name, index)).ToDictionary(p => p.name, p => "127.0.0." + (p.index + 1));
var topology = Path.Combine(Temporary, "topology.json");
await File.WriteAllTextAsync(topology, JsonSerializer.Serialize(new { hosts, ports }));
var prepared = await Provision("prepare", "--output", Deployment, "--topology", topology);
Assert.True(prepared.Code == 0, prepared.Output);
await File.WriteAllTextAsync(AdminFile, Admin);
File.SetUnixFileMode(AdminFile, UnixFileMode.UserRead | UnixFileMode.UserWrite);
var installation = await Run("bash", [Path.Combine(Bundle, "install.sh"), "--services", "all", "--deployment", Deployment,
"--postgres-admin-file", AdminFile, "--root", Root, "--dotnet", Dotnet]);
Assert.Equal(0, installation.Code);
using var accounts = JsonDocument.Parse(await File.ReadAllTextAsync(Path.Combine(Deployment, "accounts.json")));
Password = accounts.RootElement.EnumerateArray().Single(a => a.GetProperty("AccountId").GetString() == "prototype-patient").GetProperty("Password").GetString()!;
foreach (var service in Services)
{
Settings[service] = ReadEnvironment(Root, service);
Settings[service]["SSL_CERT_FILE"] = Path.Combine(Deployment, "healthapp-ca.crt");
Settings[service]["Logging__LogLevel__Default"] = "Warning";
Settings[service]["Logging__LogLevel__Microsoft.AspNetCore"] = "Warning";
Urls[service] = $"https://{hosts[service]}:{ports[service]}/";
}
foreach (var service in new[] { "patient-profile", "observation" })
{
var key = service == "patient-profile" ? "ConnectionStrings__PatientDatabase" : "ConnectionStrings__ObservationDatabase";
var db = new NpgsqlConnectionStringBuilder(Settings[service][key]);
databases.Add(db.Database!); roles.Add(db.Username!);
var migrated = await Run(Dotnet, [InstalledAssembly(service), "--migrate"], Settings[service]);
Assert.True(migrated.Code == 0, "Deployment database migration failed.");
}
}
public Task<(int Code, string Output)> Provision(params string[] arguments) => Run(Dotnet,
[Path.Combine(Bundle, "provisioner/HealthApp.Provisioning.dll"), .. arguments]);
public static Dictionary<string, string> ReadEnvironment(string root, string service) =>
File.ReadAllLines(Path.Combine(root, "etc/healthapp", service, "service.env")).ToDictionary(
line => line[..line.IndexOf('=')], line => JsonSerializer.Deserialize<string>(line[(line.IndexOf('=') + 1)..])!);
public HttpClient HttpClient()
{
var handler = new HttpClientHandler { ServerCertificateCustomValidationCallback = (_, certificate, _, errors) =>
{
if (certificate is null || (errors & (SslPolicyErrors.RemoteCertificateNameMismatch | SslPolicyErrors.RemoteCertificateNotAvailable)) != 0) return false;
using var root = X509CertificateLoader.LoadCertificateFromFile(Path.Combine(Deployment, "healthapp-ca.crt"));
using var chain = new X509Chain();
chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust;
chain.ChainPolicy.CustomTrustStore.Add(root);
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
return chain.Build(certificate);
}};
return new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(10) };
}
public string InstalledAssembly(string service) => Path.Combine(Root, "opt/healthapp", service, Assembly(service) + ".dll");
public Task<(int Code, string Output)> Install(string root, string services) => Run("bash",
[Path.Combine(Bundle, "install.sh"), "--services", services, "--deployment", Deployment, "--root", root, "--dotnet", Dotnet]);
public async Task Start(string service, string? root = null)
{
var start = new ProcessStartInfo(Dotnet) { WorkingDirectory = Path.Combine(root ?? Root, "opt/healthapp", service),
RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false };
start.ArgumentList.Add(Path.Combine(root ?? Root, "opt/healthapp", service, Assembly(service) + ".dll"));
foreach (var (key, value) in ReadEnvironment(root ?? Root, service)) start.Environment[key] = value;
start.Environment["SSL_CERT_FILE"] = Path.Combine(Deployment, "healthapp-ca.crt");
start.Environment["Logging__LogLevel__Default"] = "Warning";
var process = Process.Start(start)!;
// Do not emit application logs containing potentially sensitive deployment information.
process.OutputDataReceived += (_, _) => { };
process.ErrorDataReceived += (_, _) => { };
process.BeginOutputReadLine(); process.BeginErrorReadLine();
Processes[service] = process;
using var client = HttpClient();
for (var attempt = 0; attempt < 100; attempt++)
{
Assert.False(process.HasExited, $"{service} exited during startup.");
try { using var response = await client.GetAsync(Urls[service]); return; }
catch (HttpRequestException) { }
catch (TaskCanceledException) { }
await Task.Delay(100);
}
throw new TimeoutException($"{service} did not accept configured network traffic.");
}
public async Task Stop(string service)
{
if (!Processes.Remove(service, out var process)) return;
try
{
if (!process.HasExited)
{
// SIGINT is also the committed systemd unit's graceful stop signal.
var sent = await Run("kill", ["-INT", process.Id.ToString()]);
Assert.Equal(0, sent.Code);
using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(15));
try { await process.WaitForExitAsync(deadline.Token); }
catch (OperationCanceledException) { process.Kill(true); await process.WaitForExitAsync(); throw; }
Assert.Equal(0, process.ExitCode);
}
}
finally { process.Dispose(); }
}
public static async Task<(int Code, string Output)> Run(string executable, string[] arguments,
Dictionary<string, string>? environment = null, string? workingDirectory = null)
{
var start = new ProcessStartInfo(executable) { UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true };
if (workingDirectory is not null) start.WorkingDirectory = workingDirectory;
foreach (var argument in arguments) start.ArgumentList.Add(argument);
if (environment is not null) foreach (var (key, value) in environment) start.Environment[key] = value;
using var process = Process.Start(start)!;
var stdout = process.StandardOutput.ReadToEndAsync();
var stderr = process.StandardError.ReadToEndAsync();
using var deadline = new CancellationTokenSource(TimeSpan.FromMinutes(3));
try { await process.WaitForExitAsync(deadline.Token); }
catch (OperationCanceledException) { process.Kill(true); await process.WaitForExitAsync(); throw; }
return (process.ExitCode, await stdout + await stderr);
}
public async Task DisposeAsync()
{
foreach (var service in Processes.Keys.ToArray()) await Stop(service);
NpgsqlConnection.ClearAllPools();
if (!string.IsNullOrEmpty(Admin))
{
await using var connection = new NpgsqlConnection(Admin);
await connection.OpenAsync();
foreach (var database in databases)
{
await using var drop = new NpgsqlCommand("DROP DATABASE IF EXISTS " + database + " WITH (FORCE)", connection);
await drop.ExecuteNonQueryAsync();
}
foreach (var role in roles)
{
await using var dropRole = new NpgsqlCommand("DROP ROLE IF EXISTS " + role, connection);
await dropRole.ExecuteNonQueryAsync();
}
}
if (Directory.Exists(Temporary)) Directory.Delete(Temporary, true);
}
}
@@ -0,0 +1,309 @@
using System.Net;
using System.Runtime.Versioning;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using Npgsql;
using System.Security.Cryptography.X509Certificates;
using Xunit;
namespace Deployment.AcceptanceTests;
[SupportedOSPlatform("linux")]
public sealed class InstallationTests(DeploymentFixture fixture) : IClassFixture<DeploymentFixture>
{
[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, "service.env");
var generated = DeploymentFixture.ReadEnvironment(root, service);
Assert.Equal("Production", generated["ASPNETCORE_ENVIRONMENT"]);
Assert.StartsWith("https://", generated["ASPNETCORE_URLS"]);
Assert.NotEmpty(generated["InternalAccess__GatewayKey"]);
Assert.True(File.Exists(generated["Kestrel__Certificates__Default__Path"]));
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=" + fixture.Dotnet + " /opt/healthapp/" + service + "/" + DeploymentFixture.Assembly(service) + ".dll", unit);
Assert.Contains("EnvironmentFile=/etc/healthapp/" + service + "/service.env", unit);
Assert.Contains("User=healthapp-" + service, unit);
Assert.Contains("Group=healthapp-" + service, 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 Configuration_and_certificates_are_generated_with_matching_credentials_and_private_permissions()
{
Assert.Equal(5, fixture.Settings.Values.Select(s => s["InternalAccess__GatewayKey"]).Distinct().Count());
foreach (var service in DeploymentFixture.Services)
{
var settings = fixture.Settings[service];
Assert.Equal("Production", settings["ASPNETCORE_ENVIRONMENT"]);
Assert.StartsWith("https://", settings["ASPNETCORE_URLS"]);
using var certificate = X509CertificateLoader.LoadPkcs12FromFile(settings["Kestrel__Certificates__Default__Path"], settings["Kestrel__Certificates__Default__Password"]);
Assert.True(certificate.HasPrivateKey);
Assert.True(certificate.NotAfter > DateTime.UtcNow);
var env = Path.Combine(fixture.Root, "etc/healthapp", service, "service.env");
Assert.Equal(UnixFileMode.UserRead | UnixFileMode.UserWrite, File.GetUnixFileMode(env));
}
Assert.Equal(fixture.Settings["observation"]["Services__ApiGateway__Key"], fixture.Settings["api-gateway"]["InternalAccess__Observation__Key"]);
Assert.Equal(fixture.Settings["insights"]["InternalAccess__GatewayKey"], fixture.Settings["api-gateway"]["Services__Insights__Key"]);
}
[Fact]
public async Task Dedicated_database_roles_cannot_access_each_others_data_or_administer_the_server()
{
var profile = new NpgsqlConnectionStringBuilder(fixture.Settings["patient-profile"]["ConnectionStrings__PatientDatabase"]);
var observation = new NpgsqlConnectionStringBuilder(fixture.Settings["observation"]["ConnectionStrings__ObservationDatabase"]);
Assert.NotEqual(profile.Database, observation.Database);
Assert.NotEqual(profile.Username, observation.Username);
Assert.NotEqual(profile.Password, observation.Password);
await using var own = new NpgsqlConnection(profile.ConnectionString);
await own.OpenAsync();
await using var privileges = new NpgsqlCommand("SELECT rolsuper OR rolcreatedb OR rolcreaterole OR rolreplication FROM pg_roles WHERE rolname = current_user", own);
Assert.Equal(false, await privileges.ExecuteScalarAsync());
await using var other = new NpgsqlConnection(new NpgsqlConnectionStringBuilder(profile.ConnectionString) { Database = observation.Database }.ConnectionString);
var failure = await Assert.ThrowsAsync<PostgresException>(() => other.OpenAsync());
Assert.Equal("42501", failure.SqlState);
var retried = await fixture.Provision("database", "--service-dir", Path.Combine(fixture.Deployment, "patient-profile"), "--admin-file", fixture.AdminFile);
Assert.True(retried.Code == 0, retried.Output);
}
[Fact]
public async Task New_deployments_get_new_secrets_and_do_not_overwrite_existing_material()
{
var output = Path.Combine(fixture.Temporary, "another-deployment");
Assert.Equal(0, (await fixture.Provision("prepare", "--output", output, "--host", "localhost")).Code);
using var first = JsonDocument.Parse(await File.ReadAllTextAsync(Path.Combine(fixture.Deployment, "deployment.json")));
using var second = JsonDocument.Parse(await File.ReadAllTextAsync(Path.Combine(output, "deployment.json")));
Assert.NotEqual(first.RootElement.GetProperty("Services").GetProperty("insights").GetProperty("IncomingKey").GetString(),
second.RootElement.GetProperty("Services").GetProperty("insights").GetProperty("IncomingKey").GetString());
Assert.NotEqual(0, (await fixture.Provision("prepare", "--output", output)).Code);
}
[Fact]
public async Task Native_configuration_adapters_use_the_same_service_values_and_independent_paths()
{
var nativeRoot = Path.Combine(fixture.Temporary, "native-settings");
var windows = await fixture.Provision("configure", "--service-dir", Path.Combine(fixture.Deployment, "api-gateway"),
"--root", nativeRoot, "--platform", "windows");
Assert.True(windows.Code == 0, windows.Output);
using var json = JsonDocument.Parse(await File.ReadAllTextAsync(Path.Combine(nativeRoot, "config/api-gateway/appsettings.Production.json")));
Assert.StartsWith("https://", json.RootElement.GetProperty("urls").GetString());
Assert.Equal(fixture.Settings["api-gateway"]["Services__Observation__Key"], json.RootElement.GetProperty("Services").GetProperty("Observation").GetProperty("Key").GetString());
var mac = await fixture.Provision("configure", "--service-dir", Path.Combine(fixture.Deployment, "insights"),
"--root", nativeRoot, "--platform", "macos");
Assert.True(mac.Code == 0, mac.Output);
var plist = Path.Combine(nativeRoot, "insights.plist");
var launch = await fixture.Provision("launchd", "--service", "insights", "--root", nativeRoot, "--dotnet", fixture.Dotnet, "--output", plist);
Assert.True(launch.Code == 0, launch.Output);
var document = System.Xml.Linq.XDocument.Load(plist);
Assert.Contains(document.Descendants("string"), element => element.Value == "_healthapp_insights");
Assert.Contains(document.Descendants("string"), element => element.Value.EndsWith("InsightsService.dll"));
Assert.Equal(UnixFileMode.UserRead | UnixFileMode.UserWrite, File.GetUnixFileMode(plist));
}
private async Task VerifyScopedTopologyDistribution()
{
var directory = Path.Combine(fixture.Temporary, "distribution-contract");
Directory.CreateDirectory(directory);
var commands = Path.Combine(directory, "commands");
var captured = Path.Combine(directory, "captured");
Directory.CreateDirectory(captured);
var transport = Path.Combine(directory, "bin");
Directory.CreateDirectory(transport);
await File.WriteAllTextAsync(Path.Combine(transport, "ssh"), "#!/bin/bash\nprintf '%s\\n' \"$*\" >> \"$TRANSPORT_LOG\"\n");
await File.WriteAllTextAsync(Path.Combine(transport, "scp"), "#!/bin/bash\ntarget=\"${3%%:*}\"\nname=\"${target#*@}\"\nmkdir -p \"$CAPTURE/$name\"\ncp -R \"$2\" \"$CAPTURE/$name/\"\n");
foreach (var script in Directory.GetFiles(transport)) File.SetUnixFileMode(script, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
var environment = new Dictionary<string, string> { ["PATH"] = transport + ":" + Environment.GetEnvironmentVariable("PATH"), ["TRANSPORT_LOG"] = commands, ["CAPTURE"] = captured };
var result = await DeploymentFixture.Run(fixture.Dotnet, [Path.Combine(fixture.Bundle, "provisioner/HealthApp.Provisioning.dll"),
"distribute", "--bundle", fixture.Bundle, "--deployment", fixture.Deployment, "--ssh-user", "administrator", "--services", string.Join(',', DeploymentFixture.Services)], environment);
Assert.True(result.Code == 0, result.Output);
Assert.Equal(5, Directory.GetDirectories(captured).Length);
foreach (var node in Directory.GetDirectories(captured))
{
var installed = Assert.Single(Directory.GetDirectories(Path.Combine(node, "services")));
var selected = Path.GetFileName(installed);
Assert.Single(Directory.GetDirectories(Path.Combine(node, "deployment")));
using var scope = JsonDocument.Parse(await File.ReadAllTextAsync(Path.Combine(node, "deployment/deployment.json")));
foreach (var name in DeploymentFixture.Services.Where(n => n != selected))
{
Assert.Equal("", scope.RootElement.GetProperty("Services").GetProperty(name).GetProperty("IncomingKey").GetString());
Assert.Equal(JsonValueKind.Null, scope.RootElement.GetProperty("Services").GetProperty(name).GetProperty("Database").ValueKind);
}
if (selected != "api-gateway") Assert.Empty(scope.RootElement.GetProperty("Accounts").EnumerateArray());
}
Assert.Contains("--defer-topology-check", await File.ReadAllTextAsync(commands));
}
[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 Invalid_topology_fails_before_generating_configuration_or_credentials()
{
var topology = Path.Combine(fixture.Temporary, "invalid-topology.json");
await File.WriteAllTextAsync(topology, "{\"hosts\":{\"insights\":\"https://not-a-host/path\"}}");
var output = Path.Combine(fixture.Temporary, "invalid-topology-result");
var result = await fixture.Provision("prepare", "--output", output, "--topology", topology);
Assert.NotEqual(0, result.Code);
Assert.False(Directory.Exists(output));
}
[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);
}
[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 = fixture.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 = fixture.HttpClient();
client.BaseAddress = new Uri(fixture.Urls["api-gateway"]);
using var login = await client.PostAsJsonAsync("api/authentication/login", new
{ accountId = "prototype-patient", password = fixture.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);
}
var verified = await fixture.Provision("verify", "--deployment", fixture.Deployment, "--services", string.Join(',', DeploymentFixture.Services), "--complete", "true");
Assert.True(verified.Code == 0, verified.Output);
await VerifyScopedTopologyDistribution();
// 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<string> 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); }
}
}
@@ -0,0 +1,179 @@
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using HealthApp.TestSupport;
using Microsoft.EntityFrameworkCore;
using Xunit;
namespace Observation.AcceptanceTests;
public sealed class ContextFilteredHistoryTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
{
private sealed record Profile(Guid PatientId);
private sealed record ContextData(string Setting, string ActivityCondition, string? DeviceDetails);
private sealed record Observation(Guid ObservationId, Guid PatientId, DateTime MeasuredAt,
string? Context, ContextData MeasurementContext);
private const string Period = "from=2026-09-01T08%3A00%3A00&to=2026-09-10T08%3A00%3A00";
private async Task<Guid> Patient()
{
using var response = await fixture.Client.PostAsJsonAsync("/api/patients", new { name = "Filtered history", dateOfBirth = "1980-01-01" });
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
return (await response.Content.ReadFromJsonAsync<Profile>())!.PatientId;
}
private async Task<Observation> Record(Guid patient, string time, string? setting, string? activity, string? legacy = null, bool includeContext = true, bool completeContext = false)
{
using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{patient}/observations", new
{
measuredAt = time, systolic = 128, diastolic = 82, pulse = 68, context = legacy,
measurementContext = includeContext ? new
{
setting, activityCondition = activity, deviceDetails = "Saved device",
restDurationMinutes = completeContext ? (decimal?)5 : null,
bodyPosition = completeContext ? "Seated" : null,
measuredArm = completeContext ? "Left" : null,
cuffDetails = completeContext ? "Saved cuff" : null,
additionalCircumstances = completeContext ? "Usual routine" : null
} : null
});
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
return (await response.Content.ReadFromJsonAsync<Observation>())!;
}
private string PathFor(Guid patient, string selection = "", string period = Period) =>
$"/api/patients/{patient}/observations?{period}{selection}";
[Theory]
[InlineData("&setting=Home", "Home", "All", 2)]
[InlineData("&activityCondition=AtRest", "All", "AtRest", 2)]
[InlineData("&setting=Home&activityCondition=AtRest", "Home", "AtRest", 1)]
public async Task Independent_and_combined_selections_return_matching_context_and_metadata(string selection,
string settingHeader, string activityHeader, int expectedCount)
{
var patient = await Patient();
var homeRest = await Record(patient, "2026-09-05T08:00:00", "Home", "AtRest");
var homeAfter = await Record(patient, "2026-09-06T08:00:00", "Home", "AfterActivity");
var clinicRest = await Record(patient, "2026-09-07T08:00:00", "Clinic", "AtRest");
await Record(patient, "2026-09-08T08:00:00", null, null, "Home, resting? Morning reading");
using var response = await fixture.Client.GetAsync(PathFor(patient, selection));
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(settingHeader, Assert.Single(response.Headers.GetValues("X-Measurement-Setting")));
Assert.Equal(activityHeader, Assert.Single(response.Headers.GetValues("X-Activity-Condition")));
var history = (await response.Content.ReadFromJsonAsync<Observation[]>())!;
Assert.Equal(expectedCount, history.Length);
var expected = new[] { homeRest, homeAfter, clinicRest }.Where(o =>
(settingHeader == "All" || o.MeasurementContext.Setting == settingHeader) &&
(activityHeader == "All" || o.MeasurementContext.ActivityCondition == activityHeader)).ToArray();
Assert.Equal(expected, history);
Assert.All(history, o => Assert.Equal("Saved device", o.MeasurementContext.DeviceDetails));
}
[Theory]
[InlineData("&setting=Unknown", "Unknown", "All")]
[InlineData("&activityCondition=Unknown", "All", "Unknown")]
[InlineData("&setting=Unknown&activityCondition=Unknown", "Unknown", "Unknown")]
public async Task Unknown_selections_match_unknown_categories_without_interpreting_legacy_text(string selection,
string settingHeader, string activityHeader)
{
var patient = await Patient();
var unknown = await Record(patient, "2026-09-05T08:00:00", null, null, "Home resting?");
var partial = await Record(patient, "2026-09-06T08:00:00", "Clinic", null);
await Record(patient, "2026-09-07T08:00:00", "Home", "AtRest");
using var response = await fixture.Client.GetAsync(PathFor(patient, selection));
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(settingHeader, Assert.Single(response.Headers.GetValues("X-Measurement-Setting")));
Assert.Equal(activityHeader, Assert.Single(response.Headers.GetValues("X-Activity-Condition")));
var result = (await response.Content.ReadFromJsonAsync<Observation[]>())!;
Assert.Equal(activityHeader == "Unknown" && settingHeader == "All" ? new[] { unknown, partial } : new[] { unknown }, result);
Assert.Equal("Home resting?", result[0].Context);
}
[Fact]
public async Task No_selection_retains_all_contexts_in_chronological_order_after_restart()
{
var patient = await Patient();
var last = await Record(patient, "2026-09-07T08:00:00", null, null, includeContext: false);
var first = await Record(patient, "2026-09-05T08:00:00", "Home", "AtRest", completeContext: true);
var middle = await Record(patient, "2026-09-06T08:00:00", "Clinic", null);
await fixture.RestartHostsAsync();
using var response = await fixture.Client.GetAsync(PathFor(patient));
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(new[] { first, middle, last }, await response.Content.ReadFromJsonAsync<Observation[]>());
Assert.Equal("All", Assert.Single(response.Headers.GetValues("X-Measurement-Setting")));
Assert.Equal("All", Assert.Single(response.Headers.GetValues("X-Activity-Condition")));
}
[Fact]
public async Task Empty_filtered_history_is_an_empty_array_with_applied_selection_metadata()
{
var patient = await Patient();
await Record(patient, "2026-09-05T08:00:00", "Home", "AtRest");
using var response = await fixture.Client.GetAsync(PathFor(patient, "&setting=Other&activityCondition=AfterActivity"));
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("[]", await response.Content.ReadAsStringAsync());
Assert.Equal("Other", Assert.Single(response.Headers.GetValues("X-Measurement-Setting")));
Assert.Equal("AfterActivity", Assert.Single(response.Headers.GetValues("X-Activity-Condition")));
}
[Fact]
public async Task Filtered_history_preserves_patient_scope_inclusive_boundaries_and_equal_bounds()
{
var patient = await Patient();
var last = await Record(patient, "2026-09-10T08:00:00", "Home", "AtRest");
var first = await Record(patient, "2026-09-01T08:00:00", "Home", "AtRest");
await Record(patient, "2026-09-01T07:59:59", "Home", "AtRest");
await Record(patient, "2026-09-10T08:00:01", "Home", "AtRest");
await Record(patient, "2026-09-05T08:00:00", "Home", "AfterActivity");
await Record(await Patient(), "2026-09-05T08:00:00", "Home", "AtRest");
using var response = await fixture.Client.GetAsync(PathFor(patient, "&setting=Home&activityCondition=AtRest"));
Assert.Equal(new[] { first, last }, await response.Content.ReadFromJsonAsync<Observation[]>());
using var equal = await fixture.Client.GetAsync(PathFor(patient, "&setting=Home", "from=2026-09-01T10%3A00%3A00%2B02%3A00&to=2026-09-01T08%3A00%3A00Z"));
Assert.Equal(HttpStatusCode.OK, equal.StatusCode);
Assert.Equal(first, Assert.Single((await equal.Content.ReadFromJsonAsync<Observation[]>())!));
}
[Theory]
[InlineData("&setting=Unsupported")]
[InlineData("&activityCondition=Unsupported")]
[InlineData("&setting=All")]
[InlineData("&activityCondition=1")]
public async Task Unsupported_selections_are_rejected_without_changing_observations(string selection)
{
var patient = await Patient();
var observation = await Record(patient, "2026-09-05T08:00:00", "Home", "AtRest");
await using var db = fixture.CreateObservationDbContext();
var before = await db.Observations.CountAsync();
using var response = await fixture.Client.GetAsync(PathFor(patient, selection));
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
using var problem = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
Assert.True(problem.RootElement.TryGetProperty("errors", out _));
Assert.Equal(before, await db.Observations.CountAsync());
Assert.Equal(observation, await fixture.Client.GetFromJsonAsync<Observation>($"/api/observations/{observation.ObservationId}"));
}
[Fact]
public async Task Professional_reads_follow_assignments_and_other_patient_tokens_cannot_use_filters_to_gain_access()
{
var patient = await Patient();
var expected = await Record(patient, "2026-09-05T08:00:00", "Home", "AtRest");
var other = await Patient();
fixture.AdditionalGatewayConfiguration["Access:ProfessionalAssignments:professional:0"] = patient.ToString();
await fixture.RestartHostsAsync();
foreach (var (account, status) in new[]
{
("professional", HttpStatusCode.OK), ("professional-empty", HttpStatusCode.NotFound),
(fixture.Authentication.PatientAccounts[other], HttpStatusCode.NotFound)
})
{
using var request = new HttpRequestMessage(HttpMethod.Get, PathFor(patient, "&setting=Home&activityCondition=AtRest"));
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account));
using var response = await fixture.RawClient.SendAsync(request);
Assert.Equal(status, response.StatusCode);
if (status == HttpStatusCode.OK)
Assert.Equal(expected, Assert.Single((await response.Content.ReadFromJsonAsync<Observation[]>())!));
else Assert.Empty(await response.Content.ReadAsStringAsync());
}
}
}
@@ -0,0 +1,205 @@
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using HealthApp.TestSupport;
using Xunit;
namespace Observation.AcceptanceTests;
public sealed class ContextSelectedInsightTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
{
private sealed record Profile(Guid PatientId);
private sealed record Observation(Guid ObservationId);
private sealed record Selection(string? Setting, string? ActivityCondition);
private sealed record Insight(Guid PatientId, DateTime PeriodStart, DateTime PeriodEnd,
decimal AverageSystolic, decimal AverageDiastolic, decimal AveragePulse, int MinSystolic, int MaxSystolic,
int MinDiastolic, int MaxDiastolic, Selection AppliedSelection, int ContributingCount, string ContextExplanation);
private const string Period = "from=2026-09-01T08%3A00%3A00&to=2026-09-10T08%3A00%3A00";
private async Task<Guid> Patient()
{
using var response = await fixture.Client.PostAsJsonAsync("/api/patients", new { name = "Selected insight", dateOfBirth = "1980-01-01" });
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
return (await response.Content.ReadFromJsonAsync<Profile>())!.PatientId;
}
private async Task<Guid> Record(Guid patient, int systolic, int diastolic, int pulse, string? setting = "Home",
string? activity = "AtRest", string time = "2026-09-05T08:00:00", string? position = null)
{
using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{patient}/observations", new
{
measuredAt = time, systolic, diastolic, pulse, context = "Home resting?",
measurementContext = new { setting, activityCondition = activity, bodyPosition = position }
});
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
return (await response.Content.ReadFromJsonAsync<Observation>())!.ObservationId;
}
private string PathFor(Guid patient, string selection = "", string period = Period) =>
$"/api/patients/{patient}/insights?{period}{selection}";
private Task<Insight?> Summary(Guid patient, string selection = "") => fixture.Client.GetFromJsonAsync<Insight>(PathFor(patient, selection));
[Theory]
[InlineData("&setting=Home&activityCondition=AtRest", "Home", "AtRest", 2, 125)]
[InlineData("&setting=Home", "Home", null, 3, 130)]
[InlineData("&activityCondition=AtRest", null, "AtRest", 3, 136.67)]
public async Task Independent_and_combined_selections_use_only_matching_observations_and_report_their_basis(
string query, string? setting, string? activity, int count, double average)
{
var patient = await Patient();
await Record(patient, 120, 80, 60);
await Record(patient, 130, 84, 70);
await Record(patient, 140, 88, 80, activity: "AfterActivity");
await Record(patient, 160, 90, 90, setting: "Clinic");
var result = (await Summary(patient, query))!;
Assert.Equal((decimal)average, result.AverageSystolic);
Assert.Equal(count, result.ContributingCount);
Assert.Equal(new Selection(setting, activity), result.AppliedSelection);
Assert.Equal(patient, result.PatientId);
if (count == 2)
{
Assert.Equal(82m, result.AverageDiastolic);
Assert.Equal(65m, result.AveragePulse);
Assert.Equal(120, result.MinSystolic);
Assert.Equal(130, result.MaxSystolic);
Assert.Equal(80, result.MinDiastolic);
Assert.Equal(84, result.MaxDiastolic);
}
}
[Fact]
public async Task Unfiltered_insight_includes_unknown_context_and_explains_mixed_and_missing_conditions()
{
var patient = await Patient();
await Record(patient, 120, 80, 60, position: "Seated");
await Record(patient, 130, 84, 70, setting: "Clinic", activity: "AfterActivity", position: "Standing");
await Record(patient, 140, 88, 80, setting: null, activity: null);
var result = (await Summary(patient))!;
Assert.Equal(130m, result.AverageSystolic);
Assert.Equal(3, result.ContributingCount);
Assert.Equal(new Selection(null, null), result.AppliedSelection);
Assert.Contains("mixed settings or activity conditions", result.ContextExplanation);
Assert.Contains("unknown", result.ContextExplanation);
Assert.Contains("Optional details are unrecorded", result.ContextExplanation);
Assert.Contains("Recorded detail values differ: body position", result.ContextExplanation);
Assert.Contains("do not establish clinically comparable conditions", result.ContextExplanation);
}
[Theory]
[InlineData("&setting=Unknown", "Unknown", null)]
[InlineData("&activityCondition=Unknown", null, "Unknown")]
[InlineData("&setting=Unknown&activityCondition=Unknown", "Unknown", "Unknown")]
public async Task Unknown_selection_is_explicit_and_legacy_narrative_does_not_create_known_membership(string query,
string? setting, string? activity)
{
var patient = await Patient();
await Record(patient, 120, 80, 60, setting: null, activity: null);
await Record(patient, 180, 100, 90);
var result = (await Summary(patient, query))!;
Assert.Equal(1, result.ContributingCount);
Assert.Equal(120m, result.AverageSystolic);
Assert.Equal(80m, result.AverageDiastolic);
Assert.Equal(60m, result.AveragePulse);
Assert.Equal(result.MinSystolic, result.MaxSystolic);
Assert.Equal(result.MinDiastolic, result.MaxDiastolic);
Assert.Equal(new Selection(setting, activity), result.AppliedSelection);
}
[Theory]
[InlineData(8, 120.13, 80.13, 60.13)]
[InlineData(3, 120.33, 80.33, 60.33)]
public async Task Means_round_only_the_final_value_to_two_decimals_with_half_up_rounding(int count,
double systolic, double diastolic, double pulse)
{
var patient = await Patient();
for (var i = 0; i < count; i++)
await Record(patient, 120 + (i == count - 1 ? 1 : 0), 80 + (i == count - 1 ? 1 : 0), 60 + (i == count - 1 ? 1 : 0));
var result = (await Summary(patient))!;
Assert.Equal((decimal)systolic, result.AverageSystolic);
Assert.Equal((decimal)diastolic, result.AverageDiastolic);
Assert.Equal((decimal)pulse, result.AveragePulse);
Assert.Equal(count, result.ContributingCount);
Assert.Equal(120, result.MinSystolic);
Assert.Equal(121, result.MaxSystolic);
}
[Fact]
public async Task Corrections_clearing_and_deletion_change_membership_and_fresh_summary_results_after_restart()
{
var patient = await Patient();
var first = await Record(patient, 120, 80, 60);
var second = await Record(patient, 130, 84, 70);
Assert.Equal(125m, (await Summary(patient, "&setting=Home"))!.AverageSystolic);
using var corrected = await fixture.Client.PatchAsJsonAsync($"/api/observations/{second}", new { measurementContext = new { setting = "Clinic" } });
Assert.Equal(HttpStatusCode.OK, corrected.StatusCode);
Assert.Equal(120m, (await Summary(patient, "&setting=Home"))!.AverageSystolic);
using var cleared = await fixture.Client.PatchAsJsonAsync($"/api/observations/{first}", new { measurementContext = new { activityCondition = (string?)null } });
Assert.Equal(HttpStatusCode.OK, cleared.StatusCode);
var selected = (await Summary(patient, "&setting=Home&activityCondition=Unknown"))!;
Assert.Equal(1, selected.ContributingCount);
using var deleted = await fixture.Client.DeleteAsync($"/api/observations/{first}");
Assert.Equal(HttpStatusCode.NoContent, deleted.StatusCode);
await fixture.RestartHostsAsync();
using var empty = await fixture.Client.GetAsync(PathFor(patient, "&setting=Home"));
Assert.Equal(HttpStatusCode.NotFound, empty.StatusCode);
Assert.Contains("Insufficient observation data", await empty.Content.ReadAsStringAsync());
var remaining = (await Summary(patient, "&setting=Clinic"))!;
Assert.Equal(1, remaining.ContributingCount);
Assert.Equal(130m, remaining.AverageSystolic);
}
[Fact]
public async Task Filtered_insight_preserves_patient_scope_inclusive_bounds_and_equal_instants()
{
var patient = await Patient();
await Record(patient, 120, 80, 60, time: "2026-09-01T08:00:00");
await Record(patient, 130, 84, 70, time: "2026-09-10T08:00:00");
await Record(patient, 200, 100, 90, time: "2026-09-01T07:59:59");
await Record(patient, 210, 110, 95, time: "2026-09-10T08:00:01");
await Record(await Patient(), 220, 120, 100);
var summary = (await Summary(patient, "&setting=Home&activityCondition=AtRest"))!;
Assert.Equal(2, summary.ContributingCount);
Assert.Equal(125m, summary.AverageSystolic);
using var equal = await fixture.Client.GetAsync(PathFor(patient, "&setting=Home", "from=2026-09-01T10%3A00%3A00%2B02%3A00&to=2026-09-01T08%3A00%3A00Z"));
Assert.Equal(HttpStatusCode.OK, equal.StatusCode);
Assert.Equal(120m, (await equal.Content.ReadFromJsonAsync<Insight>())!.AverageSystolic);
}
[Theory]
[InlineData("&setting=Unsupported")]
[InlineData("&activityCondition=Unsupported")]
public async Task Unsupported_selection_is_rejected_with_validation_details(string query)
{
var patient = await Patient();
await Record(patient, 120, 80, 60);
using var response = await fixture.Client.GetAsync(PathFor(patient, query));
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
using var problem = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
Assert.True(problem.RootElement.TryGetProperty("errors", out _));
Assert.Equal(1, (await Summary(patient))!.ContributingCount);
}
[Fact]
public async Task Professional_selection_requires_assignment_and_other_patient_access_is_rejected()
{
var patient = await Patient();
await Record(patient, 120, 80, 60);
var other = await Patient();
fixture.AdditionalGatewayConfiguration["Access:ProfessionalAssignments:professional:0"] = patient.ToString();
await fixture.RestartHostsAsync();
foreach (var (account, status) in new[]
{
("professional", HttpStatusCode.OK), ("professional-empty", HttpStatusCode.NotFound),
(fixture.Authentication.PatientAccounts[other], HttpStatusCode.NotFound)
})
{
using var request = new HttpRequestMessage(HttpMethod.Get, PathFor(patient, "&setting=Home&activityCondition=AtRest"));
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account));
using var response = await fixture.RawClient.SendAsync(request);
Assert.Equal(status, response.StatusCode);
if (status == HttpStatusCode.OK) Assert.Equal(1, (await response.Content.ReadFromJsonAsync<Insight>())!.ContributingCount);
else Assert.Empty(await response.Content.ReadAsStringAsync());
}
}
}
@@ -0,0 +1,129 @@
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using HealthApp.TestSupport;
using Microsoft.EntityFrameworkCore;
using Xunit;
namespace Observation.AcceptanceTests;
public sealed class DeleteContextualisedObservationTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
{
private sealed record Profile(Guid PatientId);
private sealed record ContextData(string Setting, string ActivityCondition, decimal? RestDurationMinutes,
string? BodyPosition, string? MeasuredArm, string? DeviceDetails, string? CuffDetails, string? AdditionalCircumstances);
private sealed record Observation(Guid ObservationId, Guid PatientId, DateTime MeasuredAt,
int Systolic, int Diastolic, int Pulse, string? Context, string? Note, ContextData MeasurementContext);
private sealed record Insight(decimal AverageSystolic, decimal AverageDiastolic, decimal AveragePulse,
int MinSystolic, int MaxSystolic, int MinDiastolic, int MaxDiastolic);
private const string Period = "from=2026-09-01&to=2026-10-01";
private async Task<Guid> Patient()
{
using var response = await fixture.Client.PostAsJsonAsync("/api/patients", new { name = "Context deletion", dateOfBirth = "1980-01-01" });
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
return (await response.Content.ReadFromJsonAsync<Profile>())!.PatientId;
}
private async Task<Observation> Record(Guid patient, string time, int systolic, int diastolic, int pulse)
{
using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{patient}/observations", new
{
measuredAt = time, systolic, diastolic, pulse, context = "Original context", note = "Original note",
measurementContext = new { setting = "Home", activityCondition = "AtRest", restDurationMinutes = 5.5m,
bodyPosition = "Seated", measuredArm = "Left", deviceDetails = "Device", cuffDetails = "Cuff", additionalCircumstances = "Actual circumstances" }
});
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
return (await response.Content.ReadFromJsonAsync<Observation>())!;
}
private Task<Observation[]?> History(Guid patient) => fixture.Client.GetFromJsonAsync<Observation[]>(
$"/api/patients/{patient}/observations?{Period}&setting=Home&activityCondition=AtRest");
private Task<Insight?> Summary(Guid patient) => fixture.Client.GetFromJsonAsync<Insight>($"/api/patients/{patient}/insights?{Period}");
[Fact]
public async Task Deleted_context_stays_absent_from_retrieval_filtered_history_and_latest_after_restart()
{
var patient = await Patient();
var retained = await Record(patient, "2026-09-10T08:00:00", 120, 80, 60);
var deleted = await Record(patient, "2026-09-12T08:00:00", 200, 110, 100);
var other = await Record(await Patient(), "2026-09-13T08:00:00", 130, 84, 70);
using var response = await fixture.Client.DeleteAsync($"/api/observations/{deleted.ObservationId}");
Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);
Assert.Empty(await response.Content.ReadAsStringAsync());
await fixture.RestartHostsAsync();
using var missing = await fixture.Client.GetAsync($"/api/observations/{deleted.ObservationId}");
Assert.Equal(HttpStatusCode.NotFound, missing.StatusCode);
Assert.Empty(await missing.Content.ReadAsStringAsync());
Assert.Equal(retained, Assert.Single((await History(patient))!));
Assert.Equal(retained, await fixture.Client.GetFromJsonAsync<Observation>($"/api/patients/{patient}/observations/latest"));
Assert.Equal(other, Assert.Single((await History(other.PatientId))!));
Assert.Equal(other, await fixture.Client.GetFromJsonAsync<Observation>($"/api/observations/{other.ObservationId}"));
await using var db = fixture.CreateObservationDbContext();
Assert.False(await db.Observations.AnyAsync(o => o.ObservationId == deleted.ObservationId));
Assert.Equal("Device", (await db.Observations.AsNoTracking().SingleAsync(o => o.ObservationId == retained.ObservationId)).MeasurementContext.DeviceDetails);
}
[Fact]
public async Task New_numerical_summary_excludes_deleted_values_and_retains_current_remaining_observations()
{
var patient = await Patient();
var first = await Record(patient, "2026-09-10T08:00:00", 120, 80, 60);
var second = await Record(patient, "2026-09-11T08:00:00", 130, 84, 70);
var outlier = await Record(patient, "2026-09-12T08:00:00", 200, 110, 100);
Assert.Equal(150m, (await Summary(patient))!.AverageSystolic);
using var deleted = await fixture.Client.DeleteAsync($"/api/observations/{outlier.ObservationId}");
Assert.Equal(HttpStatusCode.NoContent, deleted.StatusCode);
var expected = new Insight(125m, 82m, 65m, 120, 130, 80, 84);
Assert.Equal(expected, await Summary(patient));
Assert.Equal(new[] { first, second }, await History(patient));
await fixture.RestartHostsAsync();
Assert.Equal(expected, await Summary(patient));
Assert.Equal(new[] { first, second }, await History(patient));
}
[Fact]
public async Task Deleting_only_contextualised_observation_leaves_empty_filtered_history_and_no_summary()
{
var patient = await Patient();
var observation = await Record(patient, "2026-09-12T08:00:00", 128, 82, 68);
using var deleted = await fixture.Client.DeleteAsync($"/api/observations/{observation.ObservationId}");
Assert.Equal(HttpStatusCode.NoContent, deleted.StatusCode);
using var history = await fixture.Client.GetAsync($"/api/patients/{patient}/observations?{Period}&setting=Home&activityCondition=AtRest");
Assert.Equal(HttpStatusCode.OK, history.StatusCode);
Assert.Equal("[]", await history.Content.ReadAsStringAsync());
Assert.Equal("Home", Assert.Single(history.Headers.GetValues("X-Measurement-Setting")));
Assert.Equal("AtRest", Assert.Single(history.Headers.GetValues("X-Activity-Condition")));
using var latest = await fixture.Client.GetAsync($"/api/patients/{patient}/observations/latest");
using var summary = await fixture.Client.GetAsync($"/api/patients/{patient}/insights?{Period}");
using var repeated = await fixture.Client.DeleteAsync($"/api/observations/{observation.ObservationId}");
Assert.Equal(HttpStatusCode.NotFound, latest.StatusCode);
Assert.Equal(HttpStatusCode.NotFound, summary.StatusCode);
Assert.Equal(HttpStatusCode.NotFound, repeated.StatusCode);
}
[Fact]
public async Task Unauthorised_deletions_preserve_the_observation_and_all_context()
{
var patient = await Patient();
var original = await Record(patient, "2026-09-12T08:00:00", 128, 82, 68);
var otherPatient = await Patient();
fixture.AdditionalGatewayConfiguration["Access:ProfessionalAssignments:professional:0"] = patient.ToString();
await fixture.RestartHostsAsync();
var otherToken = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, fixture.Authentication.PatientAccounts[otherPatient]);
var professional = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional");
foreach (var (token, status) in new[]
{
((string?)null, HttpStatusCode.Unauthorized), ((string?)"invalid", HttpStatusCode.Unauthorized),
((string?)otherToken, HttpStatusCode.NotFound), ((string?)professional, HttpStatusCode.Forbidden)
})
{
using var request = new HttpRequestMessage(HttpMethod.Delete, $"/api/observations/{original.ObservationId}");
if (token is not null) request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
using var rejected = await fixture.RawClient.SendAsync(request);
Assert.Equal(status, rejected.StatusCode);
Assert.Equal(original, await fixture.Client.GetFromJsonAsync<Observation>($"/api/observations/{original.ObservationId}"));
}
Assert.Equal(original, Assert.Single((await History(patient))!));
}
}
@@ -0,0 +1,91 @@
using System.Net;
using System.Net.Http.Json;
using Microsoft.EntityFrameworkCore;
using Xunit;
namespace Observation.AcceptanceTests;
public sealed class DeleteObservationTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
{
private sealed record Profile(Guid PatientId);
private sealed record Observation(Guid ObservationId, Guid PatientId, DateTime MeasuredAt,
int Systolic, int Diastolic, int Pulse, string? Context, string? Note);
private async Task<Guid> CreatePatientAsync()
{
using var response = await fixture.Client.PostAsJsonAsync("/api/patients", new
{
name = "Deletion Example", dateOfBirth = "1980-01-01"
});
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
return (await response.Content.ReadFromJsonAsync<Profile>())!.PatientId;
}
private async Task<Observation> RecordAsync(Guid patientId, string measuredAt)
{
using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{patientId}/observations", new
{
measuredAt, systolic = 128, diastolic = 82, pulse = 68, context = "Resting", note = "Before breakfast"
});
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
return (await response.Content.ReadFromJsonAsync<Observation>())!;
}
private Task<Observation[]?> HistoryAsync(Guid patientId) =>
fixture.Client.GetFromJsonAsync<Observation[]>(
$"/api/patients/{patientId}/observations?from=2026-09-01T00:00:00&to=2026-09-30T23:59:59");
[Fact]
public async Task Deleted_observation_stays_absent_after_restart_and_other_observations_are_preserved()
{
var patientId = await CreatePatientAsync();
var earlier = await RecordAsync(patientId, "2026-09-10T08:00:00");
var deleted = await RecordAsync(patientId, "2026-09-12T08:00:00");
var other = await RecordAsync(await CreatePatientAsync(), "2026-09-13T08:00:00");
using var response = await fixture.Client.DeleteAsync($"/api/observations/{deleted.ObservationId}");
Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);
Assert.Empty(await response.Content.ReadAsStringAsync());
await fixture.RestartHostsAsync();
using var retrieval = await fixture.Client.GetAsync($"/api/observations/{deleted.ObservationId}");
Assert.Equal(HttpStatusCode.NotFound, retrieval.StatusCode);
Assert.Equal(earlier, Assert.Single((await HistoryAsync(patientId))!));
Assert.Equal(earlier, await fixture.Client.GetFromJsonAsync<Observation>($"/api/observations/{earlier.ObservationId}"));
Assert.Equal(earlier, await fixture.Client.GetFromJsonAsync<Observation>(
$"/api/patients/{patientId}/observations/latest"));
Assert.Equal(other, await fixture.Client.GetFromJsonAsync<Observation>($"/api/observations/{other.ObservationId}"));
Assert.Equal(other, Assert.Single((await HistoryAsync(other.PatientId))!));
Assert.Equal(patientId, (await fixture.Client.GetFromJsonAsync<Profile>($"/api/patients/{patientId}"))!.PatientId);
await using var db = fixture.CreateObservationDbContext();
Assert.False(await db.Observations.AnyAsync(o => o.ObservationId == deleted.ObservationId));
}
[Fact]
public async Task Deleting_the_only_observation_leaves_empty_history_and_no_latest_observation()
{
var patientId = await CreatePatientAsync();
var observation = await RecordAsync(patientId, "2026-09-12T08:00:00");
using var response = await fixture.Client.DeleteAsync($"/api/observations/{observation.ObservationId}");
Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);
Assert.Empty((await HistoryAsync(patientId))!);
using var latest = await fixture.Client.GetAsync($"/api/patients/{patientId}/observations/latest");
Assert.Equal(HttpStatusCode.NotFound, latest.StatusCode);
using var repeated = await fixture.Client.DeleteAsync($"/api/observations/{observation.ObservationId}");
Assert.Equal(HttpStatusCode.NotFound, repeated.StatusCode);
}
[Fact]
public async Task Missing_observation_returns_not_found_without_changing_existing_data()
{
var observation = await RecordAsync(await CreatePatientAsync(), "2026-09-12T08:00:00");
await using var db = fixture.CreateObservationDbContext();
var count = await db.Observations.CountAsync();
using var response = await fixture.Client.DeleteAsync($"/api/observations/{Guid.NewGuid()}");
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
Assert.Equal(count, await db.Observations.CountAsync());
Assert.Equal(observation, await fixture.Client.GetFromJsonAsync<Observation>(
$"/api/observations/{observation.ObservationId}"));
Assert.Equal(observation, Assert.Single((await HistoryAsync(observation.PatientId))!));
}
}
@@ -0,0 +1,158 @@
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using Xunit;
namespace Observation.AcceptanceTests;
public sealed class HealthInsightTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
{
private sealed record Profile(Guid PatientId);
private sealed record Observation(Guid ObservationId);
private sealed record Insight(Guid PatientId, DateTime PeriodStart, DateTime PeriodEnd,
decimal AverageSystolic, decimal AverageDiastolic, decimal AveragePulse,
int MinSystolic, int MaxSystolic, int MinDiastolic, int MaxDiastolic);
private async Task<Guid> PatientAsync()
{
using var response = await fixture.Client.PostAsJsonAsync("/api/patients", new
{ name = "Insight Example", dateOfBirth = "1980-01-01" });
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
return (await response.Content.ReadFromJsonAsync<Profile>())!.PatientId;
}
private async Task<Guid> RecordAsync(Guid patientId, string time, int systolic, int diastolic, int pulse)
{
using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{patientId}/observations", new
{ measuredAt = time, systolic, diastolic, pulse });
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
return (await response.Content.ReadFromJsonAsync<Observation>())!.ObservationId;
}
private string PathFor(Guid patientId, string from = "2026-09-03T00:00:00", string to = "2026-09-08T23:59:59") =>
$"/api/patients/{patientId}/insights?from={Uri.EscapeDataString(from)}&to={Uri.EscapeDataString(to)}";
private async Task<Insight> SummaryAsync(Guid patientId)
{
using var response = await fixture.Client.GetAsync(PathFor(patientId));
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
return (await response.Content.ReadFromJsonAsync<Insight>())!;
}
[Fact]
public async Task Averages_use_only_the_requested_patient_and_period_after_restart()
{
var patientId = await PatientAsync();
await RecordAsync(patientId, "2026-09-03T00:00:00", 120, 80, 60);
await RecordAsync(patientId, "2026-09-08T23:59:59", 130, 84, 70);
await RecordAsync(patientId, "2026-09-01T08:00:00", 200, 100, 90);
await RecordAsync(patientId, "2026-09-10T08:00:00", 210, 110, 95);
await RecordAsync(await PatientAsync(), "2026-09-05T08:00:00", 220, 120, 100);
await fixture.RestartHostsAsync();
var insight = await SummaryAsync(patientId);
Assert.Equal(patientId, insight.PatientId);
Assert.Equal(new DateTime(2026, 9, 3), insight.PeriodStart);
Assert.Equal(new DateTime(2026, 9, 8, 23, 59, 59), insight.PeriodEnd);
Assert.Equal(125m, insight.AverageSystolic);
Assert.Equal(82m, insight.AverageDiastolic);
Assert.Equal(65m, insight.AveragePulse);
}
[Fact]
public async Task Minimum_and_maximum_values_are_calculated()
{
var patientId = await PatientAsync();
await RecordAsync(patientId, "2026-09-04T08:00:00", 118, 76, 61);
await RecordAsync(patientId, "2026-09-05T08:00:00", 130, 84, 70);
await RecordAsync(patientId, "2026-09-06T08:00:00", 124, 80, 66);
var insight = await SummaryAsync(patientId);
Assert.Equal(118, insight.MinSystolic);
Assert.Equal(130, insight.MaxSystolic);
Assert.Equal(76, insight.MinDiastolic);
Assert.Equal(84, insight.MaxDiastolic);
}
[Fact]
public async Task Fractional_averages_are_preserved_and_recalculated_after_correction_and_deletion()
{
var patientId = await PatientAsync();
var first = await RecordAsync(patientId, "2026-09-04T08:00:00", 120, 80, 60);
var second = await RecordAsync(patientId, "2026-09-05T08:00:00", 121, 81, 61);
var initial = await SummaryAsync(patientId);
Assert.Equal(120.5m, initial.AverageSystolic);
Assert.Equal(80.5m, initial.AverageDiastolic);
Assert.Equal(60.5m, initial.AveragePulse);
using var updated = await fixture.Client.PutAsJsonAsync($"/api/observations/{second}",
new { systolic = 130, diastolic = 84, pulse = 70 });
Assert.Equal(HttpStatusCode.OK, updated.StatusCode);
Assert.Equal(125m, (await SummaryAsync(patientId)).AverageSystolic);
using var deleted = await fixture.Client.DeleteAsync($"/api/observations/{second}");
Assert.Equal(HttpStatusCode.NoContent, deleted.StatusCode);
var single = await SummaryAsync(patientId);
Assert.Equal(120m, single.AverageSystolic);
Assert.Equal(single.MinSystolic, single.MaxSystolic);
using var last = await fixture.Client.DeleteAsync($"/api/observations/{first}");
Assert.Equal(HttpStatusCode.NoContent, last.StatusCode);
using var empty = await fixture.Client.GetAsync(PathFor(patientId));
Assert.Equal(HttpStatusCode.NotFound, empty.StatusCode);
}
[Fact]
public async Task No_matching_observations_reports_insufficient_data()
{
var patientId = await PatientAsync();
await RecordAsync(patientId, "2026-09-01T08:00:00", 120, 80, 60);
await RecordAsync(await PatientAsync(), "2026-09-05T08:00:00", 130, 84, 70);
using var response = await fixture.Client.GetAsync(PathFor(patientId));
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
using var problem = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
Assert.Equal("Insufficient observation data for calculation.", problem.RootElement.GetProperty("title").GetString());
}
[Theory]
[InlineData("from=2026-09-08T00:00:00&to=2026-09-03T00:00:00")]
[InlineData("from=invalid&to=2026-09-08T00:00:00")]
[InlineData("from=2026-09-03T00:00:00&to=invalid")]
[InlineData("from=2026-09-03T00:00:00")]
[InlineData("to=2026-09-08T00:00:00")]
[InlineData("")]
public async Task Invalid_or_missing_period_is_rejected(string query)
{
var patientId = await PatientAsync();
using var response = await fixture.Client.GetAsync($"/api/patients/{patientId}/insights?{query}");
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
using var problem = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
Assert.True(problem.RootElement.TryGetProperty("errors", out _));
}
[Fact]
public async Task Equal_bounds_and_offsets_match_recording_timestamp_semantics()
{
var patientId = await PatientAsync();
await RecordAsync(patientId, "2026-09-05T10:00:00+02:00", 120, 80, 60);
using var response = await fixture.Client.GetAsync(PathFor(patientId,
"2026-09-05T10:00:00+02:00", "2026-09-05T08:00:00Z"));
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var insight = (await response.Content.ReadFromJsonAsync<Insight>())!;
Assert.Equal(120m, insight.AverageSystolic);
Assert.Equal(insight.PeriodStart, insight.PeriodEnd);
}
[Fact]
public async Task Unavailable_observations_report_failure_instead_of_insufficient_data()
{
var patientId = await PatientAsync();
await RecordAsync(patientId, "2026-09-05T08:00:00", 120, 80, 60);
await fixture.StopObservationServiceAsync();
try
{
using var response = await fixture.Client.GetAsync(PathFor(patientId));
Assert.Equal(HttpStatusCode.BadGateway, response.StatusCode);
}
finally
{
await fixture.RestartHostsAsync();
}
Assert.Equal(120m, (await SummaryAsync(patientId)).AverageSystolic);
}
}
@@ -0,0 +1,249 @@
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using HealthApp.TestSupport;
using HealthOverviewService.Contracts;
using Xunit;
namespace Observation.AcceptanceTests;
public sealed class HealthOverviewTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
{
private sealed record Recorded(Guid ObservationId);
private const string Period = "from=2026-09-01T08%3A00%3A00&to=2026-09-10T08%3A00%3A00";
private static string PathFor(Guid patient, string query = Period) => $"/api/patients/{patient}/overview?{query}";
private async Task<Guid> Patient()
{
using var response = await fixture.Client.PostAsJsonAsync("/api/patients", new
{ name = "Overview patient", dateOfBirth = "1980-01-01", contactInfo = "Synthetic contact" });
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
return (await response.Content.ReadFromJsonAsync<PatientDto>())!.PatientId;
}
private async Task<Guid> Record(Guid patient, string time, int systolic = 120,
string? setting = "Home", string? activity = "AtRest")
{
using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{patient}/observations", new
{
measuredAt = time, systolic, diastolic = 80, pulse = 65, context = "Preserved original context", note = "Preserved note",
measurementContext = new { setting, activityCondition = activity, restDurationMinutes = 5,
bodyPosition = "Seated", measuredArm = "Left", deviceDetails = "Device", cuffDetails = "Cuff", additionalCircumstances = "Morning" }
});
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
return (await response.Content.ReadFromJsonAsync<Recorded>())!.ObservationId;
}
private async Task<HealthOverviewDto> Overview(Guid patient, string query = Period)
{
using var response = await fixture.Client.GetAsync(PathFor(patient, query));
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
return (await response.Content.ReadFromJsonAsync<HealthOverviewDto>())!;
}
[Fact]
public async Task Overview_preserves_profile_latest_context_and_selected_insight_with_different_bases()
{
var patient = await Patient();
await Record(patient, "2026-09-01T08:00:00", 120);
await Record(patient, "2026-09-10T08:00:00", 130);
await Record(patient, "2026-09-01T07:59:59", 200);
var latest = await Record(patient, "2026-09-11T08:00:00", 210, "Clinic", "AfterActivity");
await Record(await Patient(), "2026-09-05T08:00:00", 250);
var result = await Overview(patient, Period + "&setting=Home&activityCondition=AtRest");
Assert.Equal(patient, result.Patient.PatientId);
Assert.Equal("Overview patient", result.Patient.Name);
Assert.Equal(new DateOnly(1980, 1, 1), result.Patient.DateOfBirth);
Assert.Equal("Synthetic contact", result.Patient.ContactInfo);
Assert.Equal(latest, result.LatestObservation!.ObservationId);
Assert.Equal("AfterActivity", result.LatestObservation.MeasurementContext.ActivityCondition);
Assert.Equal("Clinic", result.LatestObservation.MeasurementContext.Setting);
Assert.Equal("Seated", result.LatestObservation.MeasurementContext.BodyPosition);
Assert.Equal("Left", result.LatestObservation.MeasurementContext.MeasuredArm);
Assert.Equal("Device", result.LatestObservation.MeasurementContext.DeviceDetails);
Assert.Equal("Cuff", result.LatestObservation.MeasurementContext.CuffDetails);
Assert.Equal(5m, result.LatestObservation.MeasurementContext.RestDurationMinutes);
Assert.Equal("Morning", result.LatestObservation.MeasurementContext.AdditionalCircumstances);
Assert.Equal("Preserved original context", result.LatestObservation.Context);
Assert.Equal("Preserved note", result.LatestObservation.Note);
Assert.Equal(125m, result.Insight!.AverageSystolic);
Assert.Equal(2, result.InsightContributingCount);
Assert.Equal(result.InsightSelection, result.Insight.AppliedSelection);
Assert.Equal("Home", result.InsightSelection.Setting);
Assert.Equal("AtRest", result.InsightSelection.ActivityCondition);
Assert.Equal(new DateTime(2026, 9, 1, 8, 0, 0), result.PeriodStart);
Assert.Equal(new DateTime(2026, 9, 10, 8, 0, 0), result.PeriodEnd);
Assert.Contains("independent of the insight period and context selections", result.LatestObservationBasis);
Assert.Contains("not to the insight", result.LatestObservationBasis);
using var raw = await fixture.Client.GetAsync(PathFor(patient));
using var json = JsonDocument.Parse(await raw.Content.ReadAsStringAsync());
Assert.False(json.RootElement.TryGetProperty("trend", out _));
}
[Fact]
public async Task No_observations_returns_profile_and_explicit_insight_absence()
{
var result = await Overview(await Patient());
Assert.NotNull(result.Patient);
Assert.Null(result.LatestObservation);
Assert.Null(result.Insight);
Assert.Equal(0, result.InsightContributingCount);
Assert.Contains("No calculated insight is available", result.InsightExplanation);
}
[Theory]
[InlineData("&setting=Clinic")]
[InlineData("&activityCondition=AfterActivity")]
[InlineData("&setting=Unknown&activityCondition=Unknown")]
public async Task Empty_selected_insight_preserves_profile_latest_and_applied_selection(string selection)
{
var patient = await Patient();
var latest = await Record(patient, "2026-09-05T08:00:00");
var result = await Overview(patient, Period + selection);
Assert.Equal(patient, result.Patient.PatientId);
Assert.Equal(latest, result.LatestObservation!.ObservationId);
Assert.Null(result.Insight);
Assert.Equal(0, result.InsightContributingCount);
Assert.Contains("no observations match", result.InsightExplanation);
Assert.True(result.InsightSelection.Setting is not null || result.InsightSelection.ActivityCondition is not null);
}
[Fact]
public async Task Unfiltered_pooled_insight_preserves_mixed_and_unknown_context_explanations()
{
var patient = await Patient();
await Record(patient, "2026-09-02T08:00:00", 120);
await Record(patient, "2026-09-03T08:00:00", 130, "Clinic", "AfterActivity");
var latest = await Record(patient, "2026-09-04T08:00:00", 140, null, null);
var result = await Overview(patient);
Assert.Equal(latest, result.LatestObservation!.ObservationId);
Assert.Equal("Unknown", result.LatestObservation.MeasurementContext.Setting);
Assert.Equal("Unknown", result.LatestObservation.MeasurementContext.ActivityCondition);
Assert.Null(result.InsightSelection.Setting);
Assert.Null(result.InsightSelection.ActivityCondition);
Assert.Equal(3, result.InsightContributingCount);
Assert.Equal(130m, result.Insight!.AverageSystolic);
Assert.Contains("mixed settings or activity conditions", result.Insight.ContextExplanation);
Assert.Contains("unknown", result.InsightExplanation);
}
[Fact]
public async Task Equal_offset_instants_are_valid_and_single_observation_insight_is_sufficient()
{
var patient = await Patient();
await Record(patient, "2026-09-05T10:00:00+02:00", 121);
var result = await Overview(patient,
"from=2026-09-05T10%3A00%3A00%2B02%3A00&to=2026-09-05T08%3A00%3A00Z&setting=Home");
Assert.Equal(result.PeriodStart, result.PeriodEnd);
Assert.Equal(1, result.InsightContributingCount);
Assert.Equal(121m, result.Insight!.AverageSystolic);
}
[Fact]
public async Task Latest_tie_rules_and_current_corrections_deletions_and_profile_edits_survive_restart()
{
var patient = await Patient();
var first = await Record(patient, "2026-09-05T08:00:00", 120);
var second = await Record(patient, "2026-09-05T08:00:00", 130, "Clinic", "AfterActivity");
Assert.Equal(second, (await Overview(patient)).LatestObservation!.ObservationId);
using var patched = await fixture.Client.PatchAsJsonAsync($"/api/observations/{first}",
new { systolic = 140, measurementContext = new { setting = "Clinic" } });
Assert.Equal(HttpStatusCode.OK, patched.StatusCode);
Assert.Null((await Overview(patient, Period + "&setting=Home")).Insight);
Assert.Equal(second, (await Overview(patient)).LatestObservation!.ObservationId);
using var edited = await fixture.Client.PutAsJsonAsync($"/api/patients/{patient}",
new { name = "Updated overview", dateOfBirth = "1980-01-01", contactInfo = "Updated contact" });
Assert.Equal(HttpStatusCode.OK, edited.StatusCode);
using var deleted = await fixture.Client.DeleteAsync($"/api/observations/{second}");
Assert.Equal(HttpStatusCode.NoContent, deleted.StatusCode);
await fixture.RestartHostsAsync();
var result = await Overview(patient);
Assert.Equal("Updated overview", result.Patient.Name);
Assert.Equal(first, result.LatestObservation!.ObservationId);
Assert.Equal(140m, result.Insight!.AverageSystolic);
Assert.Equal(1, result.InsightContributingCount);
}
[Theory]
[InlineData("from=2026-09-10&to=2026-09-01")]
[InlineData("from=bad&to=2026-09-10")]
[InlineData("from=2026-09-01&to=bad")]
[InlineData("from=2026-09-01")]
[InlineData("to=2026-09-10")]
[InlineData("")]
[InlineData(Period + "&setting=Invalid")]
[InlineData(Period + "&activityCondition=Invalid")]
public async Task Invalid_period_or_context_is_rejected_with_details(string query)
{
using var response = await fixture.Client.GetAsync(PathFor(await Patient(), query));
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
using var problem = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
Assert.True(problem.RootElement.TryGetProperty("errors", out _));
}
[Fact]
public async Task Assigned_missing_patient_reports_absence_without_exposing_other_patients()
{
var missing = Guid.NewGuid();
fixture.AdditionalGatewayConfiguration["Access:ProfessionalAssignments:professional:0"] = missing.ToString();
await fixture.RestartHostsAsync();
using var request = new HttpRequestMessage(HttpMethod.Get, PathFor(missing));
request.Headers.Authorization = new("Bearer", await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional"));
using var response = await fixture.RawClient.SendAsync(request);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
Assert.Contains("Patient does not exist", await response.Content.ReadAsStringAsync());
}
[Fact]
public async Task Overview_requires_owner_or_assigned_professional_and_blocks_direct_bypass()
{
var patient = await Patient();
await Record(patient, "2026-09-05T08:00:00");
var other = await Patient();
fixture.AdditionalGatewayConfiguration["Access:ProfessionalAssignments:professional:0"] = patient.ToString();
await fixture.RestartHostsAsync();
using var anonymous = await fixture.RawClient.GetAsync(PathFor(patient));
Assert.Equal(HttpStatusCode.Unauthorized, anonymous.StatusCode);
foreach (var (account, status) in new[] { ("professional", HttpStatusCode.OK),
("professional-empty", HttpStatusCode.NotFound), (fixture.Authentication.PatientAccounts[other], HttpStatusCode.NotFound) })
{
using var request = new HttpRequestMessage(HttpMethod.Get, PathFor(patient));
request.Headers.Authorization = new("Bearer", await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account));
using var response = await fixture.RawClient.SendAsync(request);
Assert.Equal(status, response.StatusCode);
if (status != HttpStatusCode.OK) Assert.Empty(await response.Content.ReadAsStringAsync());
}
using var direct = fixture.CreateDirectOverviewClient();
using var bypass = await direct.GetAsync(PathFor(patient));
Assert.Equal(HttpStatusCode.Unauthorized, bypass.StatusCode);
Assert.Empty(await bypass.Content.ReadAsStringAsync());
}
[Theory]
[InlineData("overview")]
[InlineData("trends")]
[InlineData("observations")]
public async Task Overview_service_credential_is_restricted_to_required_reads(string route)
{
using var request = new HttpRequestMessage(HttpMethod.Get, $"/api/patients/{await Patient()}/{route}?{Period}");
request.Headers.Add("X-Service-Key", fixture.Authentication.OverviewServiceKey);
using var response = await fixture.RawClient.SendAsync(request);
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
}
[Theory]
[InlineData("Observation")]
[InlineData("Insights")]
[InlineData("Overview")]
public async Task Unavailable_source_or_overview_is_a_failure_not_absent_insight(string service)
{
var patient = await Patient();
if (service == "Observation") await fixture.StopObservationServiceAsync();
if (service == "Insights") await fixture.StopInsightsServiceAsync();
if (service == "Overview") await fixture.StopOverviewServiceAsync();
try
{
using var response = await fixture.Client.GetAsync(PathFor(patient));
Assert.Equal(HttpStatusCode.BadGateway, response.StatusCode);
}
finally { await fixture.RestartHostsAsync(); }
}
}
@@ -0,0 +1,415 @@
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using HealthApp.TestSupport;
using InsightsService.Contracts;
using InsightsService.Domain;
using Xunit;
namespace Observation.AcceptanceTests;
public sealed class HealthTrendCalculationTests
{
private static readonly Guid PatientId = Guid.NewGuid();
private static readonly DateTime Start = new(2026, 9, 1);
private static readonly MeasurementContextDto Prepared = new("Home", "AtRest", 5, "Seated", "Left", "Device A", "Adult cuff", null);
private static ObservationDto Observation(int day, int systolic, int diastolic = 90, int pulse = 70,
MeasurementContextDto? context = null, string? text = null) =>
new(Guid.NewGuid(), PatientId, Start.AddDays(day), systolic, diastolic, pulse, context ?? Prepared, text);
private static TrendAssessment Calculate(params ObservationDto[] observations) =>
new InsightCalculator().CalculateTrend(PatientId, Start, Start.AddDays(10), observations, new() { Setting = "Home", ActivityCondition = "AtRest" });
[Theory]
[InlineData(140, 150, 160, "Increasing")]
[InlineData(160, 150, 140, "Decreasing")]
[InlineData(150, 150, 150, "NoClearDirection")]
public void Full_period_direction_and_separate_units_and_levels(int first, int middle, int last, string direction)
{
var result = Calculate(Observation(0, first, 95, 65), Observation(1, middle, 90, 70), Observation(2, last, 85, 75));
Assert.Equal(direction, result.Systolic.Direction);
Assert.Equal(direction, result.Systolic.OverallDirection);
Assert.Equal("Decreasing", result.Diastolic.Direction);
Assert.Equal("Increasing", result.Pulse.Direction);
Assert.Equal("mmHg", result.Systolic.Unit);
Assert.Equal("mmHg", result.Diastolic.Unit);
Assert.Equal("beats/min", result.Pulse.Unit);
Assert.Equal(150m, result.Systolic.Mean);
Assert.Equal(90m, result.Diastolic.Mean);
Assert.Equal(70m, result.Pulse.Mean);
Assert.Equal("SupportedRecordedComparability", result.Comparability.Status);
Assert.Contains("rest duration: 5", result.Comparability.KnownSimilarities);
}
[Fact]
public void Equal_endpoints_do_not_hide_intermediate_excursion_or_reversal()
{
var result = Calculate(Observation(0, 140), Observation(1, 190), Observation(2, 140));
Assert.Equal("Mixed", result.Systolic.Direction);
Assert.Equal("NoClearDirection", result.Systolic.OverallDirection);
Assert.Equal(1, result.Systolic.ReversalCount);
Assert.Equal(50, result.Systolic.Range);
Assert.Equal(100m, result.Systolic.TotalSuccessiveChange);
Assert.Equal("Mixed", result.Systolic.Interpretation);
Assert.Contains("no clinical stability classification", result.Systolic.NumericalExplanation);
}
[Fact]
public void Overall_decrease_can_coexist_with_reversals_and_large_variation()
{
var result = Calculate(Observation(0, 180), Observation(1, 160), Observation(2, 170), Observation(3, 140));
Assert.Equal("Mixed", result.Systolic.Direction);
Assert.Equal("Decreasing", result.Systolic.OverallDirection);
Assert.Equal(2, result.Systolic.ReversalCount);
Assert.Equal(60m, result.Systolic.TotalSuccessiveChange);
Assert.True(result.Systolic.SlopePerDay < 0);
}
[Fact]
public void Low_variation_outside_reference_is_not_healthy()
{
var result = Calculate(Observation(0, 155), Observation(1, 155), Observation(2, 155));
Assert.Equal(0, result.Systolic.Range);
Assert.Equal("PotentiallyConcerning", result.Systolic.Interpretation);
Assert.Contains("3 observation(s) >= 135", result.Systolic.ReferenceComparison);
Assert.Contains("Limited variation does not establish healthy", result.Systolic.Hint);
}
[Fact]
public void Favourable_pressure_decrease_can_still_be_high_while_falling_pulse_is_concerning()
{
var result = Calculate(Observation(0, 160, 85, 70), Observation(1, 150, 90, 55), Observation(2, 140, 95, 40));
Assert.Equal("PotentiallyFavourable", result.Systolic.Interpretation);
Assert.Contains("remains above or at", result.Systolic.Hint);
Assert.Equal("PotentiallyConcerning", result.Diastolic.Interpretation);
Assert.Equal("PotentiallyConcerning", result.Pulse.Interpretation);
Assert.Contains("not automatically favourable", result.Pulse.Hint);
Assert.Equal(50m, result.Pulse.Reference!.LowerBoundary);
Assert.Equal(100m, result.Pulse.Reference.UpperBoundary);
}
[Fact]
public void Moving_low_pulse_up_or_high_pulse_down_is_not_automatically_concerning()
{
Assert.Equal("PotentiallyFavourable", Calculate(Observation(0, 120, pulse: 40), Observation(1, 120, pulse: 55)).Pulse.Interpretation);
Assert.Equal("PotentiallyFavourable", Calculate(Observation(0, 120, pulse: 120), Observation(1, 120, pulse: 105)).Pulse.Interpretation);
Assert.Equal("CannotInterpret", Calculate(Observation(0, 120), Observation(1, 110)).Systolic.Interpretation);
}
[Fact]
public void Opposite_pulse_excursions_within_timestamp_ties_are_not_hidden_by_their_mean()
{
var result = Calculate(Observation(0, 120, pulse: 30), Observation(0, 120, pulse: 210),
Observation(1, 120, pulse: 105));
Assert.Equal("Decreasing", result.Pulse.Direction);
Assert.Equal(180, result.Pulse.Range);
Assert.Equal("PotentiallyConcerning", result.Pulse.Interpretation);
Assert.Contains("1 observation(s) < 50", result.Pulse.ReferenceComparison);
}
[Theory]
[InlineData("Home", 135, 85)]
[InlineData("Clinic", 140, 90)]
public void References_are_setting_specific_sourced_and_not_treatment_targets(string setting, int systolic, int diastolic)
{
var context = Prepared with { Setting = setting };
var result = Calculate(Observation(0, 138, context: context), Observation(1, 138, context: context));
Assert.Equal(systolic, result.Systolic.Reference!.UpperBoundary);
Assert.Equal(diastolic, result.Diastolic.Reference!.UpperBoundary);
Assert.Equal(">=", result.Systolic.Reference.UpperComparison);
Assert.Contains("sundhed.dk", result.Systolic.Reference.Sources.Single().Url);
Assert.Contains("not individual treatment targets", result.Systolic.Hint);
}
[Theory]
[InlineData(50, 0)]
[InlineData(100, 0)]
[InlineData(49, 2)]
[InlineData(101, 2)]
public void Pulse_reference_boundaries_are_exclusive(int pulse, int outsideCount)
{
var result = Calculate(Observation(0, 120, pulse: pulse), Observation(1, 120, pulse: pulse));
Assert.Contains($"{(pulse > 100 ? outsideCount : 0)} observation(s) > 100", result.Pulse.ReferenceComparison);
Assert.Contains($"{(pulse < 50 ? outsideCount : 0)} observation(s) < 50", result.Pulse.ReferenceComparison);
}
[Fact]
public void Missing_context_preserves_numerical_direction_but_not_resting_interpretation()
{
var unknown = new MeasurementContextDto("Unknown", "Unknown", null, null, null, null, null, null);
var result = Calculate(Observation(0, 150, context: unknown), Observation(1, 160, context: unknown));
Assert.Equal("Increasing", result.Systolic.Direction);
Assert.Equal(10, result.Systolic.Range);
Assert.Null(result.Systolic.Reference);
Assert.Null(result.Pulse.Reference);
Assert.Equal("CannotInterpret", result.Systolic.Interpretation);
Assert.Contains("setting", result.Comparability.MissingDetails);
}
[Fact]
public void Known_categories_with_missing_preparation_support_limited_reference_comparison()
{
var limited = new MeasurementContextDto("Home", "AtRest", null, null, null, null, null, null);
var result = Calculate(Observation(0, 150, context: limited), Observation(1, 160, context: limited));
Assert.Equal("InsufficientContext", result.Comparability.Status);
Assert.Contains("setting: Home", result.Comparability.KnownSimilarities);
Assert.Contains("rest duration", result.Comparability.MissingDetails);
Assert.NotNull(result.Systolic.Reference);
Assert.Contains("provisional", result.Systolic.ReferenceComparison);
Assert.Contains("limited reference comparison", result.Systolic.Hint);
Assert.Equal("CannotInterpret", result.Systolic.Interpretation);
}
[Fact]
public void Missing_optional_circumstances_do_not_block_supported_comparison()
{
var result = Calculate(Observation(0, 150), Observation(1, 160));
Assert.NotNull(result.Systolic.Reference);
Assert.Equal("PotentiallyConcerning", result.Systolic.Interpretation);
Assert.Equal("SupportedRecordedComparability", result.Comparability.Status);
}
[Theory]
[InlineData("during exercise")]
[InlineData("after activity")]
[InlineData("under træning")]
public void Conflicting_rest_narrative_withholds_resting_interpretation(string narrative)
{
var result = Calculate(Observation(0, 150, text: narrative), Observation(1, 160));
Assert.Equal("ConflictingContext", result.Comparability.Status);
Assert.Contains(result.Comparability.Conflicts, s => s.Contains("AtRest"));
Assert.Null(result.Systolic.Reference);
Assert.Null(result.Pulse.Reference);
Assert.Equal("Increasing", result.Systolic.Direction);
}
[Fact]
public void Different_conditions_and_preparation_are_visible_and_limit_combined_trajectory()
{
var result = Calculate(Observation(0, 150), Observation(1, 160, context: Prepared with
{ ActivityCondition = "AfterActivity", BodyPosition = "Standing" }));
Assert.Equal("KnownDifferences", result.Comparability.Status);
Assert.Contains(result.Comparability.KnownDifferences, s => s.Contains("activity condition"));
Assert.Contains(result.Comparability.KnownDifferences, s => s.Contains("body position"));
Assert.Null(result.Systolic.Reference);
Assert.Equal("CannotInterpret", result.Systolic.Interpretation);
}
[Fact]
public void Known_inadequate_pressure_preparation_does_not_block_resting_pulse_reference()
{
var result = Calculate(Observation(0, 150, context: Prepared with { RestDurationMinutes = 1 }), Observation(1, 160));
Assert.Null(result.Systolic.Reference);
Assert.NotNull(result.Pulse.Reference);
Assert.Contains(result.Comparability.KnownDifferences, s => s.Contains("five-minute"));
var standing = Calculate(Observation(0, 150, context: Prepared with { BodyPosition = "Standing" }),
Observation(1, 160, context: Prepared with { BodyPosition = "Standing" }));
Assert.Null(standing.Systolic.Reference);
}
[Fact]
public void Timestamp_ties_do_not_manufacture_direction_or_hide_descriptive_range()
{
var result = Calculate(Observation(1, 140), Observation(1, 180));
Assert.Equal("Unavailable", result.Systolic.Direction);
Assert.Null(result.Systolic.SlopePerDay);
Assert.Equal(160m, result.Systolic.Mean);
Assert.Equal(40, result.Systolic.Range);
Assert.NotNull(result.Systolic.Reference);
Assert.Equal("CannotInterpret", result.Systolic.Interpretation);
}
[Fact]
public void Empty_and_single_series_report_each_unavailable_part()
{
var empty = Calculate();
Assert.Equal(0, empty.ContributingCount);
Assert.Null(empty.Systolic.Mean);
Assert.Equal("Unavailable", empty.Systolic.Direction);
Assert.Contains("No matching observations", empty.Systolic.NumericalExplanation);
var single = Calculate(Observation(0, 140));
Assert.Equal(140m, single.Systolic.Mean);
Assert.Equal("Unavailable", single.Systolic.Direction);
Assert.Equal("Unavailable", single.Systolic.OverallDirection);
}
[Fact]
public void Retrieval_and_identifier_order_do_not_change_results_including_ties()
{
var series = new[] { Observation(0, 140), Observation(0, 180), Observation(1, 150), Observation(2, 140) };
Assert.Equal(JsonSerializer.Serialize(Calculate(series)), JsonSerializer.Serialize(Calculate(series.Reverse()
.Select(o => o with { ObservationId = Guid.NewGuid() }).ToArray())));
Assert.Equal("Decreasing", Calculate(series).Systolic.Direction);
}
}
public sealed class HealthTrendTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
{
private sealed record Profile(Guid PatientId);
private sealed record Recorded(Guid ObservationId);
private const string Period = "from=2026-09-01T08%3A00%3A00&to=2026-09-10T08%3A00%3A00";
private static string PathFor(Guid patient, string selection = "", string period = Period) =>
$"/api/patients/{patient}/trends?{period}{selection}";
private async Task<Guid> Patient()
{
using var response = await fixture.Client.PostAsJsonAsync("/api/patients", new { name = "Health trend", dateOfBirth = "1980-01-01" });
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
return (await response.Content.ReadFromJsonAsync<Profile>())!.PatientId;
}
private async Task<Guid> Record(Guid patient, int systolic, string time = "2026-09-05T08:00:00",
string? setting = "Home", string? activity = "AtRest")
{
using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{patient}/observations", new
{
measuredAt = time, systolic, diastolic = 85, pulse = 70,
measurementContext = new { setting, activityCondition = activity, restDurationMinutes = 5,
bodyPosition = "Seated", measuredArm = "Left", deviceDetails = "Device A", cuffDetails = "Adult cuff" }
});
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
return (await response.Content.ReadFromJsonAsync<Recorded>())!.ObservationId;
}
private async Task<TrendAssessment> Trend(Guid patient, string selection = "", string period = Period)
{
using var response = await fixture.Client.GetAsync(PathFor(patient, selection, period));
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
return (await response.Content.ReadFromJsonAsync<TrendAssessment>())!;
}
[Fact]
public async Task Inclusive_patient_period_and_equal_offset_instants_apply_before_sufficiency()
{
var patient = await Patient();
await Record(patient, 150, "2026-09-01T08:00:00");
await Record(patient, 160, "2026-09-10T08:00:00");
await Record(patient, 250, "2026-09-01T07:59:59");
await Record(patient, 250, "2026-09-10T08:00:01");
await Record(await Patient(), 250);
var result = await Trend(patient);
Assert.Equal(patient, result.PatientId);
Assert.Equal(new DateTime(2026, 9, 1, 8, 0, 0), result.PeriodStart);
Assert.Equal(new DateTime(2026, 9, 10, 8, 0, 0), result.PeriodEnd);
Assert.Equal(2, result.ContributingCount);
Assert.Equal(155m, result.Systolic.Mean);
Assert.Equal("Increasing", result.Systolic.Direction);
var equal = await Trend(patient, period: "from=2026-09-01T10%3A00%3A00%2B02%3A00&to=2026-09-01T08%3A00%3A00Z");
Assert.Equal(equal.PeriodStart, equal.PeriodEnd);
Assert.Equal(1, equal.ContributingCount);
Assert.Equal("Unavailable", equal.Systolic.Direction);
}
[Fact]
public async Task Labelled_home_and_clinic_selections_and_independent_dimensions_use_only_matches()
{
var patient = await Patient();
await Record(patient, 150, "2026-09-02T08:00:00");
await Record(patient, 145, "2026-09-03T08:00:00");
await Record(patient, 160, "2026-09-02T08:00:00", "Clinic");
await Record(patient, 155, "2026-09-03T08:00:00", "Clinic");
await Record(patient, 200, activity: "AfterActivity");
var home = await Trend(patient, "&setting=Home&activityCondition=AtRest");
var clinic = await Trend(patient, "&setting=Clinic&activityCondition=AtRest");
Assert.Equal(new ContextSelection { Setting = "Home", ActivityCondition = "AtRest" }, home.AppliedSelection);
Assert.Equal(new ContextSelection { Setting = "Clinic", ActivityCondition = "AtRest" }, clinic.AppliedSelection);
Assert.Equal(2, home.ContributingCount);
Assert.Equal(2, clinic.ContributingCount);
Assert.Equal(135m, home.Systolic.Reference!.UpperBoundary);
Assert.Equal(140m, clinic.Systolic.Reference!.UpperBoundary);
Assert.Contains("alone is not improvement or deterioration", home.Comparability.Explanation);
Assert.Equal(3, (await Trend(patient, "&setting=Home")).ContributingCount);
Assert.Equal(4, (await Trend(patient, "&activityCondition=AtRest")).ContributingCount);
Assert.Equal("KnownDifferences", (await Trend(patient)).Comparability.Status);
}
[Fact]
public async Task Unknown_empty_and_one_selected_observation_do_not_borrow_excluded_data()
{
var patient = await Patient();
await Record(patient, 150, "2026-09-02T08:00:00");
await Record(patient, 160, "2026-09-03T08:00:00");
await Record(patient, 180, setting: null, activity: null);
var unknown = await Trend(patient, "&setting=Unknown&activityCondition=Unknown");
Assert.Equal(1, unknown.ContributingCount);
Assert.Equal("Unavailable", unknown.Systolic.Direction);
Assert.Equal(180m, unknown.Systolic.Mean);
Assert.Null(unknown.Systolic.Reference);
var empty = await Trend(patient, "&setting=Clinic");
Assert.Equal(0, empty.ContributingCount);
Assert.Contains("No matching observations", empty.Pulse.NumericalExplanation);
}
[Fact]
public async Task Corrected_values_context_and_deletions_are_used_on_every_request_after_restart()
{
var patient = await Patient();
var first = await Record(patient, 150, "2026-09-02T08:00:00");
var second = await Record(patient, 160, "2026-09-03T08:00:00");
Assert.Equal("Increasing", (await Trend(patient)).Systolic.Direction);
using var corrected = await fixture.Client.PatchAsJsonAsync($"/api/observations/{second}", new { systolic = 140 });
Assert.Equal(HttpStatusCode.OK, corrected.StatusCode);
Assert.Equal("Decreasing", (await Trend(patient)).Systolic.Direction);
using var context = await fixture.Client.PatchAsJsonAsync($"/api/observations/{second}",
new { measurementContext = new { activityCondition = "AfterActivity" } });
Assert.Equal(HttpStatusCode.OK, context.StatusCode);
var selected = await Trend(patient, "&activityCondition=AtRest");
Assert.Equal(1, selected.ContributingCount);
Assert.Equal("Unavailable", selected.Systolic.Direction);
Assert.Null((await Trend(patient)).Systolic.Reference);
using var deleted = await fixture.Client.DeleteAsync($"/api/observations/{second}");
Assert.Equal(HttpStatusCode.NoContent, deleted.StatusCode);
await fixture.RestartHostsAsync();
Assert.Equal(150m, (await Trend(patient)).Systolic.Mean);
using var last = await fixture.Client.DeleteAsync($"/api/observations/{first}");
Assert.Equal(HttpStatusCode.NoContent, last.StatusCode);
Assert.Equal(0, (await Trend(patient)).ContributingCount);
}
[Theory]
[InlineData("from=2026-09-10&to=2026-09-01")]
[InlineData("from=bad&to=2026-09-10")]
[InlineData("from=2026-09-01")]
[InlineData("to=2026-09-10")]
[InlineData("")]
[InlineData(Period + "&setting=Invalid")]
[InlineData(Period + "&activityCondition=Invalid")]
public async Task Invalid_period_or_selection_is_rejected_with_explanation(string period)
{
using var response = await fixture.Client.GetAsync(PathFor(await Patient(), period: period));
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
using var problem = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
Assert.True(problem.RootElement.TryGetProperty("errors", out _));
}
[Fact]
public async Task Trend_access_requires_authentication_ownership_or_professional_assignment()
{
var patient = await Patient();
await Record(patient, 150);
var other = await Patient();
fixture.AdditionalGatewayConfiguration["Access:ProfessionalAssignments:professional:0"] = patient.ToString();
await fixture.RestartHostsAsync();
using var anonymous = await fixture.RawClient.GetAsync(PathFor(patient));
Assert.Equal(HttpStatusCode.Unauthorized, anonymous.StatusCode);
foreach (var (account, status) in new[] { ("professional", HttpStatusCode.OK),
("professional-empty", HttpStatusCode.NotFound), (fixture.Authentication.PatientAccounts[other], HttpStatusCode.NotFound) })
{
using var request = new HttpRequestMessage(HttpMethod.Get, PathFor(patient));
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account));
using var response = await fixture.RawClient.SendAsync(request);
Assert.Equal(status, response.StatusCode);
if (status != HttpStatusCode.OK) Assert.Empty(await response.Content.ReadAsStringAsync());
}
}
[Fact]
public async Task Upstream_failure_is_not_misreported_as_empty_data()
{
var patient = await Patient();
await fixture.StopObservationServiceAsync();
try
{
using var response = await fixture.Client.GetAsync(PathFor(patient));
Assert.Equal(HttpStatusCode.BadGateway, response.StatusCode);
}
finally { await fixture.RestartHostsAsync(); }
}
}
@@ -0,0 +1,157 @@
using System.Net;
using Microsoft.EntityFrameworkCore;
using ObservationService.Domain;
using System.Net.Http.Json;
using Xunit;
namespace Observation.AcceptanceTests;
public sealed class LatestObservationTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
{
private sealed record Profile(Guid PatientId);
private sealed record ContextData(string Setting, string ActivityCondition, decimal? RestDurationMinutes, string? BodyPosition);
private sealed record Observation(Guid ObservationId, Guid PatientId, DateTime MeasuredAt,
int Systolic, int Diastolic, int Pulse, string? Context, string? Note, ContextData MeasurementContext);
private async Task<Guid> CreatePatientAsync()
{
using var response = await fixture.Client.PostAsJsonAsync("/api/patients", new
{
name = "Latest Example", dateOfBirth = "1980-01-01"
});
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
return (await response.Content.ReadFromJsonAsync<Profile>())!.PatientId;
}
private async Task<Observation> RecordAsync(Guid patientId, string measuredAt, int systolic, int diastolic, int pulse)
{
using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{patientId}/observations", new
{
measuredAt, systolic, diastolic, pulse, context = "Resting", note = "Before breakfast"
});
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
return (await response.Content.ReadFromJsonAsync<Observation>())!;
}
[Fact]
public async Task Latest_is_selected_by_measurement_time_for_the_requested_patient_after_restart()
{
var patientId = await CreatePatientAsync();
await RecordAsync(patientId, "2026-09-10T08:00:00", 130, 84, 70);
var latest = await RecordAsync(patientId, "2026-09-12T08:00:00", 126, 80, 66);
await RecordAsync(patientId, "2026-09-11T08:00:00", 128, 82, 68);
var otherPatientId = await CreatePatientAsync();
var otherLatest = await RecordAsync(otherPatientId, "2026-09-13T08:00:00", 140, 90, 75);
await fixture.RestartHostsAsync();
Assert.Equal(latest, await fixture.Client.GetFromJsonAsync<Observation>(
$"/api/patients/{patientId}/observations/latest"));
Assert.Equal(otherLatest, await fixture.Client.GetFromJsonAsync<Observation>(
$"/api/patients/{otherPatientId}/observations/latest"));
}
[Fact]
public async Task Patient_without_observations_returns_not_found_even_when_another_patient_has_observations()
{
var patientId = await CreatePatientAsync();
await RecordAsync(await CreatePatientAsync(), "2026-09-12T08:00:00", 128, 82, 68);
using var response = await fixture.Client.GetAsync($"/api/patients/{patientId}/observations/latest");
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
Assert.DoesNotContain("observationId", await response.Content.ReadAsStringAsync());
}
private async Task<(Guid OlderId, Guid NewerId)> SeedPair(Guid patientId, DateTime olderMeasured,
DateTime newerMeasured, DateTime olderRecorded, DateTime newerRecorded,
MeasurementContext olderContext, MeasurementContext newerContext)
{
// Make the older observation's identifier greater, so it cannot mask the recording-time rule.
var prefix = Guid.NewGuid().ToString("N")[..24];
var olderId = Guid.ParseExact(prefix + "ffffffff", "N");
var newerId = Guid.ParseExact(prefix + "00000001", "N");
await using var db = fixture.CreateObservationDbContext();
db.Observations.AddRange(
new BloodPressureObservation
{
ObservationId = newerId, PatientId = patientId, MeasuredAt = newerMeasured,
Systolic = 126, Diastolic = 80, Pulse = 66, MeasurementContext = newerContext,
CreatedAt = newerRecorded, UpdatedAt = newerRecorded
},
new BloodPressureObservation
{
ObservationId = olderId, PatientId = patientId, MeasuredAt = olderMeasured,
Systolic = 130, Diastolic = 84, Pulse = 70, MeasurementContext = olderContext,
CreatedAt = olderRecorded, UpdatedAt = olderRecorded
});
await db.SaveChangesAsync();
return (olderId, newerId);
}
private Task<Observation?> Latest(Guid patientId) =>
fixture.Client.GetFromJsonAsync<Observation>($"/api/patients/{patientId}/observations/latest");
[Fact]
public async Task Newer_after_activity_observation_is_returned_with_its_own_context()
{
var patient = await CreatePatientAsync();
var time = new DateTime(2026, 9, 12, 8, 0, 0);
var pair = await SeedPair(patient, time.AddDays(-1), time, time.AddHours(2), time.AddHours(1),
new MeasurementContext { Setting = "Home", ActivityCondition = "AtRest", RestDurationMinutes = 5 },
new MeasurementContext { Setting = "Clinic", ActivityCondition = "AfterActivity", BodyPosition = "Standing" });
var latest = (await Latest(patient))!;
Assert.Equal(pair.NewerId, latest.ObservationId);
Assert.Equal(new ContextData("Clinic", "AfterActivity", null, "Standing"), latest.MeasurementContext);
}
[Fact]
public async Task Missing_context_does_not_replace_latest_with_an_older_complete_observation()
{
var patient = await CreatePatientAsync();
var time = new DateTime(2026, 9, 12, 8, 0, 0);
var pair = await SeedPair(patient, time.AddDays(-1), time, time, time.AddHours(1),
new MeasurementContext { Setting = "Home", ActivityCondition = "AtRest", RestDurationMinutes = 5,
BodyPosition = "Seated", MeasuredArm = "Left", DeviceDetails = "Recorded device", CuffDetails = "Recorded cuff" },
new MeasurementContext());
var latest = (await Latest(patient))!;
Assert.Equal(pair.NewerId, latest.ObservationId);
Assert.Equal(new ContextData("Unknown", "Unknown", null, null), latest.MeasurementContext);
}
[Fact]
public async Task Measurement_timestamp_ties_use_original_recording_time_and_ignore_later_edits()
{
var patient = await CreatePatientAsync();
var time = new DateTime(2026, 9, 12, 8, 0, 0);
var pair = await SeedPair(patient, time, time, time.AddHours(1), time.AddHours(2),
new MeasurementContext { Setting = "Home", ActivityCondition = "AtRest" },
new MeasurementContext { Setting = "Clinic", ActivityCondition = "AfterActivity" });
Assert.Equal(pair.NewerId, (await Latest(patient))!.ObservationId);
using var correction = await fixture.Client.PutAsJsonAsync($"/api/observations/{pair.OlderId}",
new { systolic = 125, diastolic = 80, pulse = 65 });
Assert.Equal(HttpStatusCode.OK, correction.StatusCode);
await using var db = fixture.CreateObservationDbContext();
var corrected = await db.Observations.AsNoTracking().SingleAsync(o => o.ObservationId == pair.OlderId);
Assert.Equal(time.AddHours(1), corrected.CreatedAt);
Assert.True(corrected.UpdatedAt > time.AddHours(2));
await fixture.RestartHostsAsync();
var latest = (await Latest(patient))!;
Assert.Equal(pair.NewerId, latest.ObservationId);
Assert.Equal("Clinic", latest.MeasurementContext.Setting);
Assert.Equal("AfterActivity", latest.MeasurementContext.ActivityCondition);
}
[Fact]
public async Task Complete_timestamp_ties_choose_greatest_identifier_reproducibly_across_restart()
{
var patient = await CreatePatientAsync();
var time = new DateTime(2026, 9, 12, 8, 0, 0);
var pair = await SeedPair(patient, time, time, time.AddHours(1), time.AddHours(1),
new MeasurementContext { Setting = "Home" }, new MeasurementContext { Setting = "Clinic" });
for (var i = 0; i < 3; i++)
Assert.Equal(pair.OlderId, (await Latest(patient))!.ObservationId);
await fixture.RestartHostsAsync();
Assert.Equal(pair.OlderId, (await Latest(patient))!.ObservationId);
}
}
@@ -0,0 +1,64 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql;
using ObservationService.Persistence;
using Xunit;
namespace Observation.AcceptanceTests;
public sealed class MeasurementContextMigrationTests
{
[Fact]
public async Task Upgrading_an_existing_observation_retains_values_and_text_without_inventing_context()
{
var admin = Environment.GetEnvironmentVariable("TEST_POSTGRES_CONNECTION")
?? throw new InvalidOperationException("TEST_POSTGRES_CONNECTION is required.");
var database = "us04_context_upgrade_" + Guid.NewGuid().ToString("N");
await using var connection = new NpgsqlConnection(admin);
await connection.OpenAsync();
await using (var create = new NpgsqlCommand($"CREATE DATABASE {database}", connection))
await create.ExecuteNonQueryAsync();
try
{
var options = new DbContextOptionsBuilder<ObservationDbContext>().UseNpgsql(
new NpgsqlConnectionStringBuilder(admin) { Database = database }.ConnectionString).Options;
await using var db = new ObservationDbContext(options);
await db.GetService<IMigrator>().MigrateAsync("20261001095222_InitialObservationSchema");
var observation = Guid.NewGuid();
var patient = Guid.NewGuid();
await db.Database.ExecuteSqlInterpolatedAsync($"""
INSERT INTO blood_pressure_observation
(observation_id, patient_id, measured_at, systolic, diastolic, pulse, context, note, created_at, updated_at)
VALUES ({observation}, {patient}, '2026-09-12 08:00:00', 128, 82, 68,
'Morning reading; resting?', 'Historical note', '2026-09-12 09:00:00', '2026-09-12 09:00:00')
""");
await db.Database.MigrateAsync();
await db.Database.MigrateAsync();
var saved = await db.Observations.AsNoTracking().SingleAsync();
Assert.Equal(observation, saved.ObservationId);
Assert.Equal(patient, saved.PatientId);
Assert.Equal(new DateTime(2026, 9, 12, 8, 0, 0), saved.MeasuredAt);
Assert.Equal(128, saved.Systolic);
Assert.Equal(82, saved.Diastolic);
Assert.Equal(68, saved.Pulse);
Assert.Equal("Morning reading; resting?", saved.Context);
Assert.Equal("Historical note", saved.Note);
Assert.Equal("Unknown", saved.MeasurementContext.Setting);
Assert.Equal("Unknown", saved.MeasurementContext.ActivityCondition);
Assert.Null(saved.MeasurementContext.RestDurationMinutes);
Assert.Null(saved.MeasurementContext.BodyPosition);
Assert.Null(saved.MeasurementContext.MeasuredArm);
Assert.Null(saved.MeasurementContext.DeviceDetails);
Assert.Null(saved.MeasurementContext.CuffDetails);
Assert.Null(saved.MeasurementContext.AdditionalCircumstances);
Assert.Equal(new DateTime(2026, 9, 12, 9, 0, 0), saved.CreatedAt);
Assert.Equal(saved.CreatedAt, saved.UpdatedAt);
}
finally
{
await using var drop = new NpgsqlCommand($"DROP DATABASE {database} WITH (FORCE)", connection);
await drop.ExecuteNonQueryAsync();
}
}
}
@@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5" PrivateAssets="all" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.12" />
<ProjectReference Include="../../src/PatientProfileService/PatientProfileService.csproj" />
<ProjectReference Include="../../src/ApiGateway/ApiGateway.csproj" />
<ProjectReference Include="../../src/HealthOverviewService/HealthOverviewService.csproj" />
<ProjectReference Include="../../src/InsightsService/InsightsService.csproj" />
<ProjectReference Include="../../src/ObservationService/ObservationService.csproj" />
</ItemGroup>
<ItemGroup>
<Compile Include="../Support/AuthenticatedTestClient.cs" Link="Support/AuthenticatedTestClient.cs" />
</ItemGroup>
</Project>
@@ -0,0 +1,188 @@
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<ObservationService.Program>? observation;
private WebApplicationFactory<InsightsService.Program>? insights;
private WebApplicationFactory<HealthOverviewService.Program>? overview;
public HttpClient CreateDirectOverviewClient() => overview!.CreateClient();
public string ObservationConnectionString { get; private set; } = "";
private string adminConnectionString = "";
private WebApplicationFactory<PatientProfileService.Program>? service;
private WebApplicationFactory<ApiGateway.Program>? 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<string, string?> 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<PatientDbContext>().UseNpgsql(ConnectionString).Options);
public ObservationService.Persistence.ObservationDbContext CreateObservationDbContext() => new(
new DbContextOptionsBuilder<ObservationService.Persistence.ObservationDbContext>()
.UseNpgsql(ObservationConnectionString).Options);
private void StartHosts()
{
service = new WebApplicationFactory<PatientProfileService.Program>().WithWebHostBuilder(builder =>
{
builder.UseEnvironment("Development");
builder.ConfigureKestrel(options => options.Listen(IPAddress.Loopback, 0));
builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(
new Dictionary<string, string?> { ["ConnectionStrings:PatientDatabase"] = ConnectionString, ["InternalAccess:GatewayKey"] = Authentication.GatewayKey }));
});
service.UseKestrel(0);
using var serviceClient = service.CreateClient();
gateway = new WebApplicationFactory<ApiGateway.Program>().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<string, string?> { ["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<BearerTokenOptions>("Bearer", options => options.TimeProvider = Authentication.Clock)));
gateway.UseKestrel(0);
RawClient = gateway.CreateClient();
Client = Authentication.Wrap(RawClient);
observation = new WebApplicationFactory<ObservationService.Program>().WithWebHostBuilder(builder =>
{
builder.UseEnvironment("Development");
builder.ConfigureKestrel(options => options.Listen(IPAddress.Loopback, 0));
builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(
new Dictionary<string, string?>
{
["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<IConfiguration>()["Services:Observation:BaseUrl"] = observationClient.BaseAddress!.ToString();
insights = new WebApplicationFactory<InsightsService.Program>().WithWebHostBuilder(builder =>
{
builder.UseEnvironment("Development");
builder.ConfigureKestrel(options => options.Listen(IPAddress.Loopback, 0));
builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(
new Dictionary<string, string?> { ["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<IConfiguration>()["Services:Insights:BaseUrl"] = insightsClient.BaseAddress!.ToString();
overview = new WebApplicationFactory<HealthOverviewService.Program>().WithWebHostBuilder(builder =>
{
builder.UseEnvironment("Development");
builder.ConfigureKestrel(options => options.Listen(IPAddress.Loopback, 0));
builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(
new Dictionary<string, string?> { ["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<IConfiguration>()["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();
}
}
@@ -0,0 +1,106 @@
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using Xunit;
namespace Observation.AcceptanceTests;
public sealed class ObservationHistoryTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
{
private sealed record Profile(Guid PatientId);
private sealed record Observation(Guid ObservationId, Guid PatientId, DateTime MeasuredAt,
int Systolic, int Diastolic, int Pulse, string? Context, string? Note);
private async Task<Guid> CreatePatientAsync()
{
using var response = await fixture.Client.PostAsJsonAsync("/api/patients", new
{
name = "History Example", dateOfBirth = "1980-01-01"
});
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
return (await response.Content.ReadFromJsonAsync<Profile>())!.PatientId;
}
private async Task<Observation> RecordAsync(Guid patientId, string measuredAt, int systolic, int diastolic, int pulse)
{
using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{patientId}/observations", new
{
measuredAt, systolic, diastolic, pulse, context = "Resting", note = "Before breakfast"
});
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
return (await response.Content.ReadFromJsonAsync<Observation>())!;
}
private Task<Observation[]?> HistoryAsync(Guid patientId, string from, string to) =>
fixture.Client.GetFromJsonAsync<Observation[]>(
$"/api/patients/{patientId}/observations?from={Uri.EscapeDataString(from)}&to={Uri.EscapeDataString(to)}");
[Fact]
public async Task Selected_period_returns_only_the_matching_observation_after_restart()
{
var patientId = await CreatePatientAsync();
await RecordAsync(patientId, "2026-09-01T08:00:00", 120, 80, 60);
var expected = await RecordAsync(patientId, "2026-09-05T08:00:00", 125, 82, 65);
await RecordAsync(patientId, "2026-09-10T08:00:00", 130, 84, 70);
await RecordAsync(await CreatePatientAsync(), "2026-09-05T08:00:00", 140, 90, 75);
await fixture.RestartHostsAsync();
var history = await HistoryAsync(patientId, "2026-09-03T00:00:00", "2026-09-08T23:59:59");
Assert.Equal(expected, Assert.Single(history!));
}
[Fact]
public async Task Results_are_chronological_and_include_both_period_boundaries()
{
var patientId = await CreatePatientAsync();
var last = await RecordAsync(patientId, "2026-09-10T08:00:00", 130, 84, 70);
var first = await RecordAsync(patientId, "2026-09-01T08:00:00", 120, 80, 60);
var middle = await RecordAsync(patientId, "2026-09-05T08:00:00", 125, 82, 65);
Assert.Equal(new[] { first, middle, last },
await HistoryAsync(patientId, "2026-09-01T08:00:00", "2026-09-10T08:00:00"));
Assert.Equal(first, Assert.Single((await HistoryAsync(patientId,
"2026-09-01T08:00:00", "2026-09-01T08:00:00"))!));
}
[Fact]
public async Task No_matching_observations_returns_an_empty_array()
{
var patientId = await CreatePatientAsync();
await RecordAsync(await CreatePatientAsync(), "2026-09-05T08:00:00", 125, 82, 65);
Assert.Empty((await HistoryAsync(patientId, "2026-09-03T00:00:00", "2026-09-08T23:59:59"))!);
await RecordAsync(patientId, "2026-09-01T08:00:00", 120, 80, 60);
Assert.Empty((await HistoryAsync(patientId, "2026-09-03T00:00:00", "2026-09-08T23:59:59"))!);
}
[Theory]
[InlineData("from=2026-09-08T00:00:00&to=2026-09-03T00:00:00")]
[InlineData("from=invalid&to=2026-09-08T00:00:00")]
[InlineData("from=2026-09-03T00:00:00&to=invalid")]
[InlineData("from=2026-09-03T00:00:00")]
[InlineData("to=2026-09-08T00:00:00")]
[InlineData("")]
public async Task Invalid_or_missing_period_is_rejected_without_changing_observations(string query)
{
var patientId = await CreatePatientAsync();
var saved = await RecordAsync(patientId, "2026-09-05T08:00:00", 125, 82, 65);
using var response = await fixture.Client.GetAsync($"/api/patients/{patientId}/observations?{query}");
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
using var problem = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
Assert.True(problem.RootElement.TryGetProperty("errors", out _));
Assert.Equal(saved, await fixture.Client.GetFromJsonAsync<Observation>($"/api/observations/{saved.ObservationId}"));
}
[Fact]
public async Task Offset_bounds_are_normalized_consistently_with_recorded_measurements()
{
var patientId = await CreatePatientAsync();
var saved = await RecordAsync(patientId, "2026-09-05T10:00:00+02:00", 125, 82, 65);
Assert.Equal(saved, Assert.Single((await HistoryAsync(patientId,
"2026-09-05T10:00:00+02:00", "2026-09-05T08:00:00Z"))!));
Assert.Empty((await HistoryAsync(patientId, "2026-09-05T08:00:01Z", "2026-09-05T11:00:00Z"))!);
}
}
@@ -0,0 +1,190 @@
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using HealthApp.TestSupport;
using Microsoft.EntityFrameworkCore;
using Xunit;
namespace Observation.AcceptanceTests;
public sealed class PatchObservationTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
{
private sealed record Profile(Guid PatientId);
private sealed record ContextData(string Setting, string ActivityCondition, decimal? RestDurationMinutes,
string? BodyPosition, string? MeasuredArm, string? DeviceDetails, string? CuffDetails, string? AdditionalCircumstances);
private sealed record Observation(Guid ObservationId, Guid PatientId, DateTime MeasuredAt,
int Systolic, int Diastolic, int Pulse, string? Context, string? Note, ContextData MeasurementContext);
private async Task<Observation> Record(bool withContext = true)
{
using var patient = await fixture.Client.PostAsJsonAsync("/api/patients", new { name = "Partial correction", dateOfBirth = "1980-01-01" });
Assert.Equal(HttpStatusCode.Created, patient.StatusCode);
var patientId = (await patient.Content.ReadFromJsonAsync<Profile>())!.PatientId;
using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{patientId}/observations", new
{
measuredAt = "2026-09-12T08:00:00", systolic = 182, diastolic = 82, pulse = 68,
context = "Legacy text", note = "Saved note",
measurementContext = withContext ? new { setting = "Home", activityCondition = "AtRest", restDurationMinutes = 5.5m,
bodyPosition = "Seated", measuredArm = "Left", deviceDetails = "Device", cuffDetails = "Cuff", additionalCircumstances = "Circumstances" } : null
});
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
return (await response.Content.ReadFromJsonAsync<Observation>())!;
}
private Task<HttpResponseMessage> Patch(Guid id, object body) => fixture.Client.PatchAsJsonAsync($"/api/observations/{id}", body);
private Task<Observation?> Read(Guid id) => fixture.Client.GetFromJsonAsync<Observation>($"/api/observations/{id}");
private Task<Observation[]?> History(Guid patient, string selection) => fixture.Client.GetFromJsonAsync<Observation[]>(
$"/api/patients/{patient}/observations?from=2026-09-01&to=2026-10-01&{selection}");
[Fact]
public async Task Context_can_be_added_to_a_historical_observation_without_changing_its_measurements()
{
var original = await Record(false);
using var response = await Patch(original.ObservationId, new { measurementContext = new { setting = "Home", activityCondition = "AtRest" } });
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var updated = (await response.Content.ReadFromJsonAsync<Observation>())!;
Assert.Equal(original with { MeasurementContext = original.MeasurementContext with { Setting = "Home", ActivityCondition = "AtRest" } }, updated);
}
[Fact]
public async Task Correcting_one_context_field_preserves_omitted_data_and_changes_selection_after_restart()
{
var original = await Record();
await using var db = fixture.CreateObservationDbContext();
var before = await db.Observations.AsNoTracking().SingleAsync(o => o.ObservationId == original.ObservationId);
using var response = await Patch(original.ObservationId, new { measurementContext = new { setting = "Clinic" } });
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var expected = original with { MeasurementContext = original.MeasurementContext with { Setting = "Clinic" } };
Assert.Equal(expected, await response.Content.ReadFromJsonAsync<Observation>());
await fixture.RestartHostsAsync();
Assert.Equal(expected, await Read(original.ObservationId));
Assert.Equal(expected, await fixture.Client.GetFromJsonAsync<Observation>($"/api/patients/{original.PatientId}/observations/latest"));
Assert.Empty((await History(original.PatientId, "setting=Home"))!);
Assert.Equal(expected, Assert.Single((await History(original.PatientId, "setting=Clinic&activityCondition=AtRest"))!));
var after = await db.Observations.AsNoTracking().SingleAsync(o => o.ObservationId == original.ObservationId);
Assert.Equal(before.CreatedAt, after.CreatedAt);
Assert.True(after.UpdatedAt > before.UpdatedAt);
}
[Fact]
public async Task Individual_optional_fields_can_be_corrected_or_cleared_without_erasing_other_context()
{
var original = await Record();
using var corrected = await Patch(original.ObservationId, new { measurementContext = new { restDurationMinutes = 0m,
bodyPosition = "Standing", measuredArm = "Right", deviceDetails = "Corrected device", cuffDetails = "Corrected cuff", additionalCircumstances = "After walking" } });
Assert.Equal(HttpStatusCode.OK, corrected.StatusCode);
var expected = original with { MeasurementContext = original.MeasurementContext with { RestDurationMinutes = 0,
BodyPosition = "Standing", MeasuredArm = "Right", DeviceDetails = "Corrected device", CuffDetails = "Corrected cuff", AdditionalCircumstances = "After walking" } };
Assert.Equal(expected, await corrected.Content.ReadFromJsonAsync<Observation>());
using var clear = await Patch(original.ObservationId, new { measurementContext = new { activityCondition = (string?)null,
restDurationMinutes = (decimal?)null, bodyPosition = (string?)null, measuredArm = (string?)null,
deviceDetails = (string?)null, cuffDetails = (string?)null, additionalCircumstances = (string?)null } });
Assert.Equal(HttpStatusCode.OK, clear.StatusCode);
expected = original with { MeasurementContext = new ContextData("Home", "Unknown", null, null, null, null, null, null) };
Assert.Equal(expected, await Read(original.ObservationId));
Assert.Empty((await History(original.PatientId, "activityCondition=AtRest"))!);
Assert.Equal(expected, Assert.Single((await History(original.PatientId, "activityCondition=Unknown"))!));
using var setting = await Patch(original.ObservationId, new { measurementContext = new { setting = (string?)null } });
Assert.Equal(HttpStatusCode.OK, setting.StatusCode);
Assert.Equal("Unknown", (await Read(original.ObservationId))!.MeasurementContext.Setting);
}
[Fact]
public async Task Explicit_null_context_object_clears_structured_context_but_preserves_legacy_text_and_numbers()
{
var original = await Record();
using var response = await Patch(original.ObservationId, new { measurementContext = (object?)null });
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(original with { MeasurementContext = new ContextData("Unknown", "Unknown", null, null, null, null, null, null) }, await Read(original.ObservationId));
}
[Fact]
public async Task Single_numerical_and_legacy_text_updates_preserve_other_values()
{
var original = await Record();
using var correction = await Patch(original.ObservationId, new { systolic = 128 });
Assert.Equal(HttpStatusCode.OK, correction.StatusCode);
Assert.Equal(original with { Systolic = 128 }, await Read(original.ObservationId));
using var text = await Patch(original.ObservationId, new { context = "Corrected narrative", note = (string?)null });
Assert.Equal(HttpStatusCode.OK, text.StatusCode);
Assert.Equal(original with { Systolic = 128, Context = "Corrected narrative", Note = null }, await Read(original.ObservationId));
}
[Theory]
[InlineData("{\"systolic\":128,\"measurementContext\":{\"setting\":\"Unsupported\"}}")]
[InlineData("{\"note\":\"Change\",\"measurementContext\":{\"activityCondition\":\"Unsupported\"}}")]
[InlineData("{\"measurementContext\":{\"restDurationMinutes\":-1}}")]
[InlineData("{\"systolic\":null}")]
[InlineData("{\"diastolic\":0}")]
[InlineData("{\"pulse\":-1}")]
[InlineData("{\"systolic\":\"invalid\"}")]
[InlineData("{\"systolic\":128,\"measurementContext\":{\"unsupportedField\":\"value\"}}")]
[InlineData("{}")]
[InlineData("{\"measurementContext\":{}}")]
[InlineData("{")]
public async Task Invalid_patches_reject_the_whole_update_without_changes(string json)
{
var original = await Record();
await using var db = fixture.CreateObservationDbContext();
var before = await db.Observations.AsNoTracking().SingleAsync(o => o.ObservationId == original.ObservationId);
using var content = new StringContent(json, Encoding.UTF8, "application/json");
using var response = await fixture.Client.PatchAsync($"/api/observations/{original.ObservationId}", content);
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
using var problem = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
Assert.True(problem.RootElement.TryGetProperty("errors", out _));
Assert.Equal(original, await Read(original.ObservationId));
var after = await db.Observations.AsNoTracking().SingleAsync(o => o.ObservationId == original.ObservationId);
Assert.Equal(before.UpdatedAt, after.UpdatedAt);
}
[Fact]
public async Task Unsupported_context_in_a_legacy_put_does_not_silently_apply_its_numerical_changes()
{
var original = await Record();
using var response = await fixture.Client.PutAsJsonAsync($"/api/observations/{original.ObservationId}", new
{
systolic = 128, diastolic = 80, pulse = 65,
measurementContext = new { setting = "Unsupported" }
});
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.Equal(original, await Read(original.ObservationId));
}
[Fact]
public async Task Missing_observation_is_not_created_by_a_context_patch()
{
await Record();
await using var db = fixture.CreateObservationDbContext();
var count = await db.Observations.CountAsync();
using var response = await Patch(Guid.NewGuid(), new { measurementContext = new { setting = "Clinic" } });
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
Assert.Equal(count, await db.Observations.CountAsync());
}
[Fact]
public async Task Other_patients_professionals_and_unauthenticated_clients_cannot_patch_context()
{
var original = await Record();
var other = await Record();
fixture.AdditionalGatewayConfiguration["Access:ProfessionalAssignments:professional:0"] = original.PatientId.ToString();
await fixture.RestartHostsAsync();
var otherToken = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, fixture.Authentication.PatientAccounts[other.PatientId]);
var professional = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional");
foreach (var (token, expected) in new[]
{
((string?)null, HttpStatusCode.Unauthorized), ((string?)"invalid", HttpStatusCode.Unauthorized),
((string?)otherToken, HttpStatusCode.NotFound), ((string?)professional, HttpStatusCode.Forbidden)
})
{
using var request = new HttpRequestMessage(HttpMethod.Patch, $"/api/observations/{original.ObservationId}")
{ Content = JsonContent.Create(new { measurementContext = new { setting = "Clinic" } }) };
if (token is not null) request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
using var response = await fixture.RawClient.SendAsync(request);
Assert.Equal(expected, response.StatusCode);
}
Assert.Equal(original, await Read(original.ObservationId));
Assert.Equal(other, await Read(other.ObservationId));
}
}
@@ -0,0 +1,277 @@
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using HealthApp.TestSupport;
using Microsoft.EntityFrameworkCore;
using Xunit;
namespace Observation.AcceptanceTests;
public sealed class PatientAuthenticationTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
{
private static int nextAccount = 150;
private sealed record Profile(Guid PatientId);
private sealed record Observation(Guid ObservationId, Guid PatientId, int Systolic);
private static object ProfileRequest => new { name = "Patient", dateOfBirth = "1980-01-01" };
private static object ObservationRequest => new { measuredAt = "2026-09-12T08:00:00", systolic = 128, diastolic = 82, pulse = 68 };
private async Task<HttpResponseMessage> Send(HttpMethod method, string path, string? token = null, object? body = null)
{
using var request = new HttpRequestMessage(method, path);
if (token is not null) request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
if (body is not null) request.Content = JsonContent.Create(body);
return await fixture.RawClient.SendAsync(request);
}
private async Task<(string Token, Guid PatientId, string Account)> Patient()
{
var account = "test-" + Interlocked.Increment(ref nextAccount);
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account);
using var response = await Send(HttpMethod.Post, "/api/patients", token, ProfileRequest);
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
return (token, (await response.Content.ReadFromJsonAsync<Profile>())!.PatientId, account);
}
[Fact]
public async Task Login_without_profile_returns_normalized_identity_and_no_patient_data()
{
using var response = await fixture.RawClient.PostAsJsonAsync("/api/authentication/login",
new { accountId = "test-0", password = AuthenticatedTestClient.Password, role = "HealthcareProfessional" });
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Contains("no-store", response.Headers.CacheControl!.ToString());
using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
Assert.Equal("test-0", json.RootElement.GetProperty("accountId").GetString());
Assert.Equal("Patient", json.RootElement.GetProperty("role").GetString());
Assert.Equal(1800, json.RootElement.GetProperty("expiresIn").GetInt32());
Assert.False(json.RootElement.TryGetProperty("patientId", out _));
Assert.False(json.RootElement.TryGetProperty("refreshToken", out _));
using var unavailable = await Send(HttpMethod.Get, $"/api/patients/{Guid.NewGuid()}", json.RootElement.GetProperty("accessToken").GetString());
Assert.Equal(HttpStatusCode.NotFound, unavailable.StatusCode);
}
[Fact]
public async Task Invalid_account_and_invalid_password_have_same_rejection()
{
using var unknown = await fixture.RawClient.PostAsJsonAsync("/api/authentication/login", new { accountId = "absent", password = AuthenticatedTestClient.Password });
using var incorrect = await fixture.RawClient.PostAsJsonAsync("/api/authentication/login", new { accountId = "test-0", password = "incorrect" });
Assert.Equal(HttpStatusCode.Unauthorized, unknown.StatusCode);
Assert.Equal(unknown.StatusCode, incorrect.StatusCode);
Assert.Equal(await unknown.Content.ReadAsStringAsync(), await incorrect.Content.ReadAsStringAsync());
}
[Theory]
[InlineData("GET", "patients/00000000-0000-0000-0000-000000000001")]
[InlineData("POST", "patients")]
[InlineData("GET", "patients/me")]
[InlineData("PUT", "patients/00000000-0000-0000-0000-000000000001")]
[InlineData("GET", "observations/00000000-0000-0000-0000-000000000001")]
[InlineData("PUT", "observations/00000000-0000-0000-0000-000000000001")]
[InlineData("DELETE", "observations/00000000-0000-0000-0000-000000000001")]
[InlineData("POST", "patients/00000000-0000-0000-0000-000000000001/observations")]
[InlineData("GET", "patients/00000000-0000-0000-0000-000000000001/observations/latest")]
[InlineData("GET", "patients/00000000-0000-0000-0000-000000000001/observations")]
[InlineData("GET", "patients/00000000-0000-0000-0000-000000000001/insights")]
public async Task Missing_and_invalid_tokens_reject_every_existing_patient_operation(string method, string path)
{
await using var patients = fixture.CreateDbContext();
await using var observations = fixture.CreateObservationDbContext();
var patientCount = await patients.Patients.CountAsync();
var observationCount = await observations.Observations.CountAsync();
foreach (var token in new string?[] { null, "unverifiable" })
{
using var response = await Send(new HttpMethod(method), "/api/" + path, token, method == "GET" ? null : ProfileRequest);
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
Assert.DoesNotContain("Patient", await response.Content.ReadAsStringAsync());
}
Assert.Equal(patientCount, await patients.Patients.CountAsync());
Assert.Equal(observationCount, await observations.Observations.CountAsync());
}
[Fact]
public async Task Own_observations_and_insights_are_available_but_another_patients_reads_and_writes_are_rejected()
{
var first = await Patient();
var second = await Patient();
using var record = await Send(HttpMethod.Post, $"/api/patients/{first.PatientId}/observations", first.Token, ObservationRequest);
Assert.Equal(HttpStatusCode.Created, record.StatusCode);
var observation = (await record.Content.ReadFromJsonAsync<Observation>())!;
var paths = new[] { $"patients/{first.PatientId}", $"patients/{first.PatientId}/observations",
$"patients/{first.PatientId}/observations/latest", $"patients/{first.PatientId}/insights", $"observations/{observation.ObservationId}" };
foreach (var path in paths)
{
var query = path.EndsWith("/observations") || path.EndsWith("/insights") ? "?from=2026-09-01&to=2026-10-01" : "";
using var own = await Send(HttpMethod.Get, "/api/" + path + query, first.Token);
Assert.Equal(HttpStatusCode.OK, own.StatusCode);
using var other = await Send(HttpMethod.Get, "/api/" + path + query, second.Token);
Assert.Equal(HttpStatusCode.NotFound, other.StatusCode);
Assert.Empty(await other.Content.ReadAsStringAsync());
}
foreach (var (method, path, body) in new[]
{
(HttpMethod.Put, $"patients/{first.PatientId}", ProfileRequest),
(HttpMethod.Post, $"patients/{first.PatientId}/observations", ObservationRequest),
(HttpMethod.Put, $"observations/{observation.ObservationId}", ObservationRequest),
(HttpMethod.Delete, $"observations/{observation.ObservationId}", (object?)null)
})
{
using var response = await Send(method, "/api/" + path, second.Token, body);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
using var retained = await Send(HttpMethod.Get, $"/api/observations/{observation.ObservationId}", first.Token);
Assert.Equal(128, (await retained.Content.ReadFromJsonAsync<Observation>())!.Systolic);
await using var db = fixture.CreateObservationDbContext();
Assert.Single(await db.Observations.Where(o => o.PatientId == first.PatientId).ToListAsync());
}
[Fact]
public async Task Caller_supplied_account_identity_cannot_replace_authenticated_identity()
{
var account = "test-" + Interlocked.Increment(ref nextAccount);
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account);
using var request = new HttpRequestMessage(HttpMethod.Post, "/api/patients") { Content = JsonContent.Create(ProfileRequest) };
request.Headers.Authorization = new("Bearer", token);
request.Headers.Add("X-Account-Id", "test-0");
using var response = await fixture.RawClient.SendAsync(request);
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
await using var db = fixture.CreateDbContext();
var id = (await response.Content.ReadFromJsonAsync<Profile>())!.PatientId;
Assert.Equal(account, (await db.Patients.SingleAsync(p => p.PatientId == id)).AccountId);
}
[Fact]
public async Task Profile_creation_retries_and_concurrency_preserve_one_persistent_association()
{
var account = "test-" + Interlocked.Increment(ref nextAccount);
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account);
var responses = await Task.WhenAll(Send(HttpMethod.Post, "/api/patients", token, ProfileRequest), Send(HttpMethod.Post, "/api/patients", token, ProfileRequest));
try
{
Assert.Single(responses, r => r.StatusCode == HttpStatusCode.Created);
Assert.Single(responses, r => r.StatusCode == HttpStatusCode.Conflict);
var profile = (await responses.Single(r => r.StatusCode == HttpStatusCode.Created).Content.ReadFromJsonAsync<Profile>())!;
using var retry = await Send(HttpMethod.Post, "/api/patients", token, ProfileRequest);
Assert.Equal(HttpStatusCode.Conflict, retry.StatusCode);
await fixture.RestartHostsAsync();
using var read = await Send(HttpMethod.Get, "/api/patients/me", token);
Assert.Equal(HttpStatusCode.OK, read.StatusCode);
Assert.Equal(profile.PatientId, (await read.Content.ReadFromJsonAsync<Profile>())!.PatientId);
await using var db = fixture.CreateDbContext();
Assert.Single(await db.Patients.Where(p => p.AccountId == account).ToListAsync());
}
finally { foreach (var response in responses) response.Dispose(); }
}
[Fact]
public async Task Failed_creation_can_be_retried_without_an_orphan_profile()
{
var account = "test-" + Interlocked.Increment(ref nextAccount);
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account);
await fixture.StopPatientServiceAsync();
using var failed = await Send(HttpMethod.Post, "/api/patients", token, ProfileRequest);
Assert.Equal(HttpStatusCode.BadGateway, failed.StatusCode);
await fixture.RestartHostsAsync();
using var retry = await Send(HttpMethod.Post, "/api/patients", token, ProfileRequest);
Assert.Equal(HttpStatusCode.Created, retry.StatusCode);
await using var db = fixture.CreateDbContext();
Assert.Single(await db.Patients.Where(p => p.AccountId == account).ToListAsync());
}
[Fact]
public async Task Expired_token_is_rejected_and_login_produces_a_fresh_token()
{
var patient = await Patient();
fixture.Authentication.Clock.Advance(TimeSpan.FromMinutes(31));
try
{
using var expired = await Send(HttpMethod.Get, $"/api/patients/{patient.PatientId}", patient.Token);
Assert.Equal(HttpStatusCode.Unauthorized, expired.StatusCode);
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, patient.Account);
using var renewed = await Send(HttpMethod.Get, $"/api/patients/{patient.PatientId}", token);
Assert.Equal(HttpStatusCode.OK, renewed.StatusCode);
}
finally { fixture.Authentication.Clock.Advance(TimeSpan.FromMinutes(-31)); }
}
[Fact]
public async Task Tampering_with_a_valid_token_is_rejected()
{
var patient = await Patient();
var token = patient.Token.ToCharArray();
var position = token.Length / 2;
token[position] = token[position] == 'A' ? 'B' : 'A';
using var response = await Send(HttpMethod.Get, $"/api/patients/{patient.PatientId}", new string(token));
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
[Fact]
public async Task Database_failure_rolls_back_profile_and_association_together()
{
var account = "test-" + Interlocked.Increment(ref nextAccount);
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account);
await using var db = fixture.CreateDbContext();
await db.Database.ExecuteSqlRawAsync("""
CREATE FUNCTION fail_profile_test() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF NEW.name = 'simulate-write-failure' THEN RAISE EXCEPTION 'test write failure'; END IF;
RETURN NEW;
END; $$;
CREATE TRIGGER fail_profile_test BEFORE INSERT ON patient FOR EACH ROW EXECUTE FUNCTION fail_profile_test();
""");
try
{
using var failed = await Send(HttpMethod.Post, "/api/patients", token,
new { name = "simulate-write-failure", dateOfBirth = "1980-01-01" });
Assert.Equal(HttpStatusCode.InternalServerError, failed.StatusCode);
Assert.Empty(await db.Patients.Where(p => p.AccountId == account).ToListAsync());
using var retry = await Send(HttpMethod.Post, "/api/patients", token, ProfileRequest);
Assert.Equal(HttpStatusCode.Created, retry.StatusCode);
Assert.Single(await db.Patients.Where(p => p.AccountId == account).ToListAsync());
}
finally
{
await db.Database.ExecuteSqlRawAsync("DROP TRIGGER fail_profile_test ON patient; DROP FUNCTION fail_profile_test();");
}
}
[Fact]
public async Task Direct_services_reject_client_tokens_missing_keys_and_forged_keys()
{
var patient = await Patient();
foreach (var client in new[] { fixture.CreateDirectPatientClient(), fixture.CreateDirectObservationClient(), fixture.CreateDirectInsightsClient() })
{
using (client)
{
client.DefaultRequestHeaders.Authorization = new("Bearer", patient.Token);
foreach (var key in new string?[] { null, "forged" })
{
client.DefaultRequestHeaders.Remove("X-Gateway-Key");
if (key is not null) client.DefaultRequestHeaders.Add("X-Gateway-Key", key);
using var response = await client.GetAsync($"/api/patients/{patient.PatientId}");
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
}
}
}
[Fact]
public async Task Service_credentials_are_limited_to_their_documented_read_calls()
{
using var request = new HttpRequestMessage(HttpMethod.Post, "/api/patients") { Content = JsonContent.Create(ProfileRequest) };
request.Headers.Add("X-Service-Key", fixture.Authentication.ObservationServiceKey);
using var response = await fixture.RawClient.SendAsync(request);
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
using var forbidden = new HttpRequestMessage(HttpMethod.Get, "/api/patients/by-account/test-0");
forbidden.Headers.Add("X-Service-Key", fixture.Authentication.InsightsServiceKey);
using var rejected = await fixture.RawClient.SendAsync(forbidden);
Assert.Equal(HttpStatusCode.Forbidden, rejected.StatusCode);
}
[Fact]
public async Task Healthcare_professional_cannot_create_profiles()
{
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional");
using var response = await Send(HttpMethod.Post, "/api/patients", token, ProfileRequest);
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
}
}
@@ -0,0 +1,275 @@
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using HealthApp.TestSupport;
using Microsoft.EntityFrameworkCore;
using Xunit;
namespace Observation.AcceptanceTests;
public sealed class ProfessionalAccessTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
{
private const string AssignmentPath = "/api/professionals/me/patients";
private sealed record Profile(Guid PatientId, string Name);
private sealed record Observation(Guid ObservationId, Guid PatientId, int Systolic, string? Context, string? Note);
private sealed record AssignedPatient(Guid PatientId);
private async Task<Guid> CreatePatient()
{
using var response = await fixture.Client.PostAsJsonAsync("/api/patients", new { name = "Assigned Patient", dateOfBirth = "1980-01-01" });
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
return (await response.Content.ReadFromJsonAsync<Profile>())!.PatientId;
}
private async Task<Observation> Record(Guid patientId)
{
using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{patientId}/observations", new
{
measuredAt = "2026-09-12T08:00:00", systolic = 128, diastolic = 82, pulse = 68,
context = "Resting", note = "Actual conditions"
});
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
return (await response.Content.ReadFromJsonAsync<Observation>())!;
}
private async Task Assign(Guid[] first, Guid[]? second = null)
{
fixture.AdditionalGatewayConfiguration.Clear();
for (var i = 0; i < first.Length; i++)
fixture.AdditionalGatewayConfiguration[$"Access:ProfessionalAssignments:professional:{i}"] = first[i].ToString();
for (var i = 0; i < (second?.Length ?? 0); i++)
fixture.AdditionalGatewayConfiguration[$"Access:ProfessionalAssignments:professional-second:{i}"] = second![i].ToString();
await fixture.RestartHostsAsync();
}
private async Task<HttpResponseMessage> Send(HttpMethod method, string path, string? token, object? body = null)
{
using var request = new HttpRequestMessage(method, path);
if (token is not null) request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
if (body is not null) request.Content = JsonContent.Create(body);
return await fixture.RawClient.SendAsync(request);
}
[Fact]
public async Task Login_recognizes_professional_identity_and_does_not_put_assignments_in_the_token_response()
{
using var response = await fixture.RawClient.PostAsJsonAsync("/api/authentication/login",
new { accountId = "professional", password = AuthenticatedTestClient.Password, role = "Patient" });
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
Assert.Equal("HealthcareProfessional", json.RootElement.GetProperty("role").GetString());
Assert.Equal("professional", json.RootElement.GetProperty("accountId").GetString());
Assert.False(json.RootElement.TryGetProperty("patientId", out _));
Assert.False(json.RootElement.TryGetProperty("assignments", out _));
}
[Fact]
public async Task Professionals_list_only_their_own_assignments_and_can_share_patients()
{
var first = await CreatePatient();
var shared = await CreatePatient();
var second = await CreatePatient();
var excluded = await CreatePatient();
await Assign([first, shared, first], [shared, second]);
foreach (var (account, expected) in new[]
{
("professional", new[] { first, shared }),
("professional-second", new[] { shared, second }),
("professional-empty", Array.Empty<Guid>())
})
{
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account);
using var response = await Send(HttpMethod.Get, AssignmentPath + "?accountId=professional-second", token);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var patients = (await response.Content.ReadFromJsonAsync<AssignedPatient[]>())!;
Assert.Equal(expected.Order(), patients.Select(p => p.PatientId).Order());
Assert.DoesNotContain(patients, p => p.PatientId == excluded);
}
var sharedToken = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional-second");
using var read = await Send(HttpMethod.Get, $"/api/patients/{shared}", sharedToken);
Assert.Equal(HttpStatusCode.OK, read.StatusCode);
}
[Fact]
public async Task Assigned_profiles_observations_context_history_latest_and_insights_are_readable()
{
var patient = await CreatePatient();
var observation = await Record(patient);
await Assign([patient]);
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional");
foreach (var path in new[]
{
$"/api/patients/{patient}", $"/api/observations/{observation.ObservationId}",
$"/api/patients/{patient}/observations/latest", $"/api/patients/{patient}/observations?from=2026-09-01&to=2026-10-01",
$"/api/patients/{patient}/insights?from=2026-09-01&to=2026-10-01"
})
{
using var response = await Send(HttpMethod.Get, path, token);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using var own = await fixture.Client.GetAsync(path);
Assert.Equal(await own.Content.ReadAsStringAsync(), await response.Content.ReadAsStringAsync());
}
using var specific = await Send(HttpMethod.Get, $"/api/observations/{observation.ObservationId}", token);
Assert.Equal(observation, await specific.Content.ReadFromJsonAsync<Observation>());
}
[Fact]
public async Task Unassigned_patients_and_observations_are_rejected_even_with_a_supplied_assigned_patient_id()
{
var assigned = await CreatePatient();
var unassigned = await CreatePatient();
var observation = await Record(unassigned);
await Assign([assigned]);
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional");
foreach (var path in new[]
{
$"/api/patients/{unassigned}", $"/api/observations/{observation.ObservationId}?patientId={assigned}",
$"/api/patients/{unassigned}/observations/latest", $"/api/patients/{unassigned}/observations?from=2026-09-01&to=2026-10-01",
$"/api/patients/{unassigned}/insights?from=2026-09-01&to=2026-10-01"
})
{
using var response = await Send(HttpMethod.Get, path, token);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
Assert.Empty(await response.Content.ReadAsStringAsync());
}
}
[Fact]
public async Task Missing_information_for_assigned_patients_follows_existing_retrieval_behaviour()
{
var patient = await CreatePatient();
var missingPatient = Guid.NewGuid();
await Assign([patient, missingPatient]);
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional");
foreach (var path in new[]
{
$"/api/patients/{missingPatient}", $"/api/observations/{Guid.NewGuid()}",
$"/api/patients/{patient}/observations/latest", $"/api/patients/{patient}/insights?from=2026-09-01&to=2026-10-01"
})
{
using var response = await Send(HttpMethod.Get, path, token);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
using var history = await Send(HttpMethod.Get, $"/api/patients/{patient}/observations?from=2026-09-01&to=2026-10-01", token);
Assert.Equal(HttpStatusCode.OK, history.StatusCode);
Assert.Equal("[]", await history.Content.ReadAsStringAsync());
}
[Theory]
[InlineData("professional")]
[InlineData("professional-empty")]
public async Task Professionals_cannot_create_update_or_delete_any_patient_information(string account)
{
var patient = await CreatePatient();
var observation = await Record(patient);
await Assign([patient]);
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account);
await using var patients = fixture.CreateDbContext();
await using var observations = fixture.CreateObservationDbContext();
var before = await patients.Patients.AsNoTracking().SingleAsync(p => p.PatientId == patient);
var count = await patients.Patients.CountAsync();
foreach (var (method, path, body) in new[]
{
(HttpMethod.Post, "/api/patients", (object?)new { name = "Forbidden", dateOfBirth = "1980-01-01" }),
(HttpMethod.Put, $"/api/patients/{patient}", (object?)new { name = "Forbidden" }),
(HttpMethod.Post, $"/api/patients/{patient}/observations", (object?)new { measuredAt = "2026-09-12T08:00:00", systolic = 190, diastolic = 90, pulse = 80 }),
(HttpMethod.Put, $"/api/observations/{observation.ObservationId}", (object?)new { systolic = 190, diastolic = 90, pulse = 80 }),
(HttpMethod.Delete, $"/api/observations/{observation.ObservationId}", (object?)null)
})
{
using var response = await Send(method, path, token, body);
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Assert.Empty(await response.Content.ReadAsStringAsync());
}
Assert.Equal(count, await patients.Patients.CountAsync());
var after = await patients.Patients.AsNoTracking().SingleAsync(p => p.PatientId == patient);
Assert.Equal(before.Name, after.Name);
Assert.Equal(before.UpdatedAt, after.UpdatedAt);
var saved = await observations.Observations.AsNoTracking().SingleAsync(o => o.ObservationId == observation.ObservationId);
Assert.Equal(128, saved.Systolic);
Assert.Equal("Resting", saved.Context);
Assert.Equal("Actual conditions", saved.Note);
Assert.Single(await observations.Observations.Where(o => o.PatientId == patient).ToListAsync());
}
[Fact]
public async Task Missing_invalid_and_expired_tokens_do_not_disclose_assignments_or_patient_data()
{
var patient = await CreatePatient();
await Assign([patient]);
foreach (var token in new string?[] { null, "invalid" })
{
using var list = await Send(HttpMethod.Get, AssignmentPath, token);
using var read = await Send(HttpMethod.Get, $"/api/patients/{patient}", token);
Assert.Equal(HttpStatusCode.Unauthorized, list.StatusCode);
Assert.Equal(HttpStatusCode.Unauthorized, read.StatusCode);
Assert.Empty(await list.Content.ReadAsStringAsync());
Assert.Empty(await read.Content.ReadAsStringAsync());
}
var valid = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional");
fixture.Authentication.Clock.Advance(TimeSpan.FromMinutes(31));
try
{
using var expired = await Send(HttpMethod.Get, AssignmentPath, valid);
Assert.Equal(HttpStatusCode.Unauthorized, expired.StatusCode);
}
finally { fixture.Authentication.Clock.Advance(TimeSpan.FromMinutes(-31)); }
}
[Fact]
public async Task Incorrect_professional_secret_and_unknown_account_have_identical_login_rejections()
{
using var incorrect = await fixture.RawClient.PostAsJsonAsync("/api/authentication/login", new { accountId = "professional", password = "wrong" });
using var unknown = await fixture.RawClient.PostAsJsonAsync("/api/authentication/login", new { accountId = "unknown-professional", password = AuthenticatedTestClient.Password });
Assert.Equal(HttpStatusCode.Unauthorized, incorrect.StatusCode);
Assert.Equal(incorrect.StatusCode, unknown.StatusCode);
Assert.Equal(await incorrect.Content.ReadAsStringAsync(), await unknown.Content.ReadAsStringAsync());
}
[Fact]
public async Task Patient_cannot_list_professional_assignments_and_retains_own_access()
{
var patient = await CreatePatient();
await Assign([patient]);
var account = fixture.Authentication.PatientAccounts[patient];
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account);
using var rejected = await Send(HttpMethod.Get, AssignmentPath, token);
Assert.Equal(HttpStatusCode.Forbidden, rejected.StatusCode);
using var own = await Send(HttpMethod.Get, $"/api/patients/{patient}", token);
Assert.Equal(HttpStatusCode.OK, own.StatusCode);
}
[Fact]
public async Task Assignment_removal_is_used_after_restart_even_with_an_existing_token()
{
var patient = await CreatePatient();
await Assign([patient]);
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional");
using var allowed = await Send(HttpMethod.Get, $"/api/patients/{patient}", token);
Assert.Equal(HttpStatusCode.OK, allowed.StatusCode);
await Assign([]);
using var rejected = await Send(HttpMethod.Get, $"/api/patients/{patient}", token);
Assert.Equal(HttpStatusCode.NotFound, rejected.StatusCode);
using var list = await Send(HttpMethod.Get, AssignmentPath, token);
Assert.Equal("[]", await list.Content.ReadAsStringAsync());
}
[Fact]
public async Task Observation_ownership_lookup_failure_fails_closed_while_assignment_list_remains_available()
{
var patient = await CreatePatient();
var observation = await Record(patient);
await Assign([patient]);
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional");
await fixture.StopObservationServiceAsync();
try
{
using var read = await Send(HttpMethod.Get, $"/api/observations/{observation.ObservationId}", token);
Assert.Equal(HttpStatusCode.BadGateway, read.StatusCode);
using var list = await Send(HttpMethod.Get, AssignmentPath, token);
Assert.Equal(HttpStatusCode.OK, list.StatusCode);
}
finally { await fixture.RestartHostsAsync(); }
}
}
@@ -0,0 +1,195 @@
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using HealthApp.TestSupport;
using Microsoft.EntityFrameworkCore;
using Xunit;
namespace Observation.AcceptanceTests;
public sealed class RecordMeasurementContextTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
{
private sealed record Profile(Guid PatientId);
private sealed record Context(string Setting, string ActivityCondition, decimal? RestDurationMinutes,
string? BodyPosition, string? MeasuredArm, string? DeviceDetails, string? CuffDetails, string? AdditionalCircumstances);
private sealed record Observation(Guid ObservationId, Guid PatientId, DateTime MeasuredAt,
int Systolic, int Diastolic, int Pulse, string? Context, string? Note, Context MeasurementContext);
private async Task<Guid> Patient()
{
using var response = await fixture.Client.PostAsJsonAsync("/api/patients", new { name = "Context patient", dateOfBirth = "1980-01-01" });
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
return (await response.Content.ReadFromJsonAsync<Profile>())!.PatientId;
}
private Task<HttpResponseMessage> Record(Guid patientId, object? measurementContext, string? context = null, string? note = null) =>
fixture.Client.PostAsJsonAsync($"/api/patients/{patientId}/observations", new
{
measuredAt = "2026-09-12T08:00:00", systolic = 128, diastolic = 82, pulse = 68,
measurementContext, context, note
});
[Fact]
public async Task Complete_context_is_saved_with_the_correct_values_and_retrievable_after_restart()
{
var patient = await Patient();
var expected = new Context("Home", "AtRest", 5.5m, "Seated", "Left", "Example upper-arm device",
"Example cuff", "Recent stress");
using var response = await Record(patient, expected, "Before breakfast", "Actual reading");
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
var saved = (await response.Content.ReadFromJsonAsync<Observation>())!;
Assert.Equal(expected, saved.MeasurementContext);
Assert.Equal(patient, saved.PatientId);
Assert.Equal(new DateTime(2026, 9, 12, 8, 0, 0), saved.MeasuredAt);
Assert.Equal(128, saved.Systolic);
Assert.Equal(82, saved.Diastolic);
Assert.Equal(68, saved.Pulse);
Assert.Equal("Before breakfast", saved.Context);
Assert.Equal("Actual reading", saved.Note);
await fixture.RestartHostsAsync();
Assert.Equal(saved, await fixture.Client.GetFromJsonAsync<Observation>(response.Headers.Location));
var latest = await fixture.Client.GetFromJsonAsync<Observation>($"/api/patients/{patient}/observations/latest");
Assert.Equal(saved, latest);
var history = await fixture.Client.GetFromJsonAsync<Observation[]>($"/api/patients/{patient}/observations?from=2026-09-11&to=2026-09-13");
Assert.Equal(saved, Assert.Single(history!));
using var corrected = await fixture.Client.PutAsJsonAsync($"/api/observations/{saved.ObservationId}",
new { systolic = 130, diastolic = 84, pulse = 70 });
Assert.Equal(HttpStatusCode.OK, corrected.StatusCode);
Assert.Equal(expected, (await corrected.Content.ReadFromJsonAsync<Observation>())!.MeasurementContext);
await using var db = fixture.CreateObservationDbContext();
var persisted = await db.Observations.SingleAsync(o => o.ObservationId == saved.ObservationId);
Assert.Equal(5.5m, persisted.MeasurementContext.RestDurationMinutes);
Assert.Equal("Home", persisted.MeasurementContext.Setting);
Assert.Equal("Example cuff", persisted.MeasurementContext.CuffDetails);
}
[Theory]
[InlineData("Home", "AtRest")]
[InlineData("Home", "DuringActivity")]
[InlineData("Clinic", "AfterActivity")]
[InlineData("Other", "Unknown")]
[InlineData("Unknown", "AtRest")]
[InlineData("Unknown", "Unknown")]
public async Task Setting_and_activity_are_independent_and_departures_from_guidance_are_valid(string setting, string activity)
{
var patient = await Patient();
using var response = await Record(patient, new { setting, activityCondition = activity,
restDurationMinutes = 0m, bodyPosition = "Standing", additionalCircumstances = "Walking immediately beforehand" });
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
var saved = (await response.Content.ReadFromJsonAsync<Observation>())!;
Assert.Equal(setting, saved.MeasurementContext.Setting);
Assert.Equal(activity, saved.MeasurementContext.ActivityCondition);
Assert.Equal(0m, saved.MeasurementContext.RestDurationMinutes);
Assert.Equal("Standing", saved.MeasurementContext.BodyPosition);
Assert.Equal("Walking immediately beforehand", saved.MeasurementContext.AdditionalCircumstances);
}
[Fact]
public async Task Partial_and_absent_context_remain_unknown_without_reinterpreting_legacy_text()
{
var patient = await Patient();
using var partial = await Record(patient, new { setting = "Clinic" });
var first = (await partial.Content.ReadFromJsonAsync<Observation>())!;
Assert.Equal(HttpStatusCode.Created, partial.StatusCode);
Assert.Equal("Clinic", first.MeasurementContext.Setting);
Assert.Equal("Unknown", first.MeasurementContext.ActivityCondition);
Assert.Null(first.MeasurementContext.RestDurationMinutes);
Assert.Null(first.MeasurementContext.BodyPosition);
using var absent = await Record(patient, null, "Morning reading; resting?", "Keep original text");
var second = (await absent.Content.ReadFromJsonAsync<Observation>())!;
Assert.Equal(HttpStatusCode.Created, absent.StatusCode);
Assert.Equal("Unknown", second.MeasurementContext.Setting);
Assert.Equal("Unknown", second.MeasurementContext.ActivityCondition);
Assert.Equal("Morning reading; resting?", second.Context);
Assert.Equal("Keep original text", second.Note);
Assert.Equal(second, await fixture.Client.GetFromJsonAsync<Observation>(absent.Headers.Location));
using var explicitNulls = await Record(patient, new { setting = (string?)null, activityCondition = (string?)null });
Assert.Equal(HttpStatusCode.Created, explicitNulls.StatusCode);
var third = (await explicitNulls.Content.ReadFromJsonAsync<Observation>())!;
Assert.Equal("Unknown", third.MeasurementContext.Setting);
Assert.Equal("Unknown", third.MeasurementContext.ActivityCondition);
}
[Fact]
public async Task Conflicting_categories_and_narrative_are_preserved_without_relabelling()
{
var patient = await Patient();
using var response = await Record(patient, new { setting = "Home", activityCondition = "AtRest",
additionalCircumstances = "During exercise" }, "During exercise", "Recorded as supplied");
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
var saved = (await response.Content.ReadFromJsonAsync<Observation>())!;
Assert.Equal("AtRest", saved.MeasurementContext.ActivityCondition);
Assert.Equal("During exercise", saved.MeasurementContext.AdditionalCircumstances);
Assert.Equal("During exercise", saved.Context);
Assert.Equal(saved, await fixture.Client.GetFromJsonAsync<Observation>(response.Headers.Location));
}
[Theory]
[InlineData("{\"setting\":\"Unsupported\"}")]
[InlineData("{\"activityCondition\":\"Unsupported\"}")]
[InlineData("{\"setting\":42}")]
[InlineData("{\"activityCondition\":true}")]
[InlineData("{\"restDurationMinutes\":-1}")]
public async Task Invalid_context_is_rejected_with_validation_details_without_saving(string contextJson)
{
var patient = await Patient();
await using var db = fixture.CreateObservationDbContext();
var before = await db.Observations.CountAsync();
var json = "{\"measuredAt\":\"2026-09-12T08:00:00\",\"systolic\":128,\"diastolic\":82,\"pulse\":68,\"measurementContext\":" + contextJson + "}";
using var content = new StringContent(json, Encoding.UTF8, "application/json");
using var response = await fixture.Client.PostAsync($"/api/patients/{patient}/observations", content);
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
using var problem = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
Assert.True(problem.RootElement.TryGetProperty("errors", out _));
Assert.Equal(before, await db.Observations.CountAsync());
}
[Fact]
public async Task Context_is_protected_against_other_patient_reads_and_submissions_and_professional_writes()
{
var patient = await Patient();
var otherPatient = await Patient();
using var recorded = await Record(patient, new { setting = "Home", activityCondition = "AtRest" });
Assert.Equal(HttpStatusCode.Created, recorded.StatusCode);
var observation = (await recorded.Content.ReadFromJsonAsync<Observation>())!;
var otherToken = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, fixture.Authentication.PatientAccounts[otherPatient]);
await using var db = fixture.CreateObservationDbContext();
var count = await db.Observations.CountAsync();
using var read = new HttpRequestMessage(HttpMethod.Get, $"/api/observations/{observation.ObservationId}");
read.Headers.Authorization = new("Bearer", otherToken);
using var rejectedRead = await fixture.RawClient.SendAsync(read);
Assert.Equal(HttpStatusCode.NotFound, rejectedRead.StatusCode);
Assert.Empty(await rejectedRead.Content.ReadAsStringAsync());
foreach (var token in new[] { otherToken, await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional") })
{
using var request = new HttpRequestMessage(HttpMethod.Post, $"/api/patients/{patient}/observations")
{
Content = JsonContent.Create(new { measuredAt = "2026-09-12T08:00:00", systolic = 128, diastolic = 82,
pulse = 68, measurementContext = new { setting = "Clinic" } })
};
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
using var response = await fixture.RawClient.SendAsync(request);
Assert.Equal(token == otherToken ? HttpStatusCode.NotFound : HttpStatusCode.Forbidden, response.StatusCode);
}
Assert.Equal(count, await db.Observations.CountAsync());
}
[Fact]
public async Task Assigned_professional_can_retrieve_saved_context()
{
var patient = await Patient();
using var recorded = await Record(patient, new { setting = "Clinic", activityCondition = "AtRest", deviceDetails = "Clinic device" });
Assert.Equal(HttpStatusCode.Created, recorded.StatusCode);
var saved = (await recorded.Content.ReadFromJsonAsync<Observation>())!;
fixture.AdditionalGatewayConfiguration["Access:ProfessionalAssignments:professional:0"] = patient.ToString();
await fixture.RestartHostsAsync();
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional");
using var request = new HttpRequestMessage(HttpMethod.Get, $"/api/observations/{saved.ObservationId}");
request.Headers.Authorization = new("Bearer", token);
using var response = await fixture.RawClient.SendAsync(request);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(saved, await response.Content.ReadFromJsonAsync<Observation>());
}
}
@@ -0,0 +1,150 @@
using System.Net;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using Xunit;
namespace Observation.AcceptanceTests;
public sealed class RecordObservationTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
{
private sealed record Profile(Guid PatientId);
private sealed record Observation(Guid ObservationId, Guid PatientId, DateTime MeasuredAt,
int Systolic, int Diastolic, int Pulse, string? Context, string? Note);
private async Task<Guid> CreatePatientAsync()
{
using var response = await fixture.Client.PostAsJsonAsync("/api/patients", new
{
name = "Steffen Example", dateOfBirth = "1980-01-01"
});
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
return (await response.Content.ReadFromJsonAsync<Profile>())!.PatientId;
}
[Fact]
public async Task Valid_observation_is_assigned_an_identifier_associated_with_the_patient_and_retrievable_after_restart()
{
var patientId = await CreatePatientAsync();
using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{patientId}/observations", new
{
measuredAt = "2026-09-12T08:00:00", systolic = 128, diastolic = 82, pulse = 68,
context = "Resting", note = "Before breakfast"
});
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
var saved = await response.Content.ReadFromJsonAsync<Observation>();
Assert.NotNull(saved);
Assert.NotEqual(Guid.Empty, saved.ObservationId);
Assert.Equal(patientId, saved.PatientId);
Assert.Equal(new DateTime(2026, 9, 12, 8, 0, 0), saved.MeasuredAt);
Assert.Equal(128, saved.Systolic);
Assert.Equal(82, saved.Diastolic);
Assert.Equal(68, saved.Pulse);
Assert.Equal("Resting", saved.Context);
Assert.Equal("Before breakfast", saved.Note);
Assert.Equal($"/api/observations/{saved.ObservationId}", response.Headers.Location!.ToString());
await fixture.RestartHostsAsync();
Assert.Equal(saved, await fixture.Client.GetFromJsonAsync<Observation>(response.Headers.Location));
}
[Fact]
public async Task Optional_fields_can_be_omitted_and_identifiers_are_distinct()
{
var patientId = await CreatePatientAsync();
var request = new { measuredAt = "2026-09-12T08:00:00", systolic = 128, diastolic = 82, pulse = 68 };
using var first = await fixture.Client.PostAsJsonAsync($"/api/patients/{patientId}/observations", request);
using var second = await fixture.Client.PostAsJsonAsync($"/api/patients/{patientId}/observations", request);
Assert.Equal(HttpStatusCode.Created, first.StatusCode);
Assert.Equal(HttpStatusCode.Created, second.StatusCode);
var saved = (await first.Content.ReadFromJsonAsync<Observation>())!;
Assert.Null(saved.Context);
Assert.Null(saved.Note);
Assert.NotEqual(saved.ObservationId, (await second.Content.ReadFromJsonAsync<Observation>())!.ObservationId);
Assert.Equal(saved, await fixture.Client.GetFromJsonAsync<Observation>(first.Headers.Location));
}
[Theory]
[InlineData(0, 82, 68)]
[InlineData(-1, 82, 68)]
[InlineData(128, 0, 68)]
[InlineData(128, -1, 68)]
[InlineData(128, 82, 0)]
[InlineData(128, 82, -1)]
public async Task Non_positive_values_are_rejected_without_saving(int systolic, int diastolic, int pulse)
{
var patientId = await CreatePatientAsync();
await using var db = fixture.CreateObservationDbContext();
var before = await db.Observations.CountAsync();
using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{patientId}/observations", new
{
measuredAt = "2026-09-12T08:00:00", systolic, diastolic, pulse
});
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.Equal(before, await db.Observations.CountAsync());
}
[Theory]
[InlineData("{\"systolic\":128,\"diastolic\":82,\"pulse\":68}")]
[InlineData("{\"measuredAt\":null,\"systolic\":128,\"diastolic\":82,\"pulse\":68}")]
[InlineData("{\"measuredAt\":\"invalid\",\"systolic\":128,\"diastolic\":82,\"pulse\":68}")]
[InlineData("{\"measuredAt\":\"2026-09-12T08:00:00\",\"diastolic\":82,\"pulse\":68}")]
[InlineData("{\"measuredAt\":\"2026-09-12T08:00:00\",\"systolic\":128,\"pulse\":68}")]
[InlineData("{\"measuredAt\":\"2026-09-12T08:00:00\",\"systolic\":128,\"diastolic\":82}")]
[InlineData("{")]
public async Task Missing_or_malformed_information_is_rejected_without_saving(string json)
{
var patientId = await CreatePatientAsync();
await using var db = fixture.CreateObservationDbContext();
var before = await db.Observations.CountAsync();
using var content = new StringContent(json, Encoding.UTF8, "application/json");
using var response = await fixture.Client.PostAsync($"/api/patients/{patientId}/observations", content);
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
using var problem = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
Assert.True(problem.RootElement.TryGetProperty("errors", out _));
Assert.Equal(before, await db.Observations.CountAsync());
}
[Fact]
public async Task Missing_patient_is_rejected_without_saving()
{
await using var db = fixture.CreateObservationDbContext();
var before = await db.Observations.CountAsync();
using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{Guid.NewGuid()}/observations", new
{
measuredAt = "2026-09-12T08:00:00", systolic = 128, diastolic = 82, pulse = 68
});
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
Assert.Equal(before, await db.Observations.CountAsync());
}
[Fact]
public async Task Missing_observation_returns_not_found()
{
using var response = await fixture.Client.GetAsync($"/api/observations/{Guid.NewGuid()}");
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
[Fact]
public async Task Failed_patient_lookup_is_rejected_without_saving()
{
var patientId = await CreatePatientAsync();
await using var db = fixture.CreateObservationDbContext();
var before = await db.Observations.CountAsync();
await fixture.StopPatientServiceAsync();
try
{
using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{patientId}/observations", new
{
measuredAt = "2026-09-12T08:00:00", systolic = 128, diastolic = 82, pulse = 68
});
Assert.Equal(HttpStatusCode.BadGateway, response.StatusCode);
Assert.Equal(before, await db.Observations.CountAsync());
}
finally
{
await fixture.RestartHostsAsync();
}
}
}
@@ -0,0 +1,121 @@
using System.Net;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using Xunit;
namespace Observation.AcceptanceTests;
public sealed class UpdateObservationTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
{
private sealed record Profile(Guid PatientId);
private sealed record Observation(Guid ObservationId, Guid PatientId, DateTime MeasuredAt,
int Systolic, int Diastolic, int Pulse, string? Context, string? Note);
private async Task<Observation> RecordAsync()
{
using var patient = await fixture.Client.PostAsJsonAsync("/api/patients", new
{
name = "Correction Example", dateOfBirth = "1980-01-01"
});
Assert.Equal(HttpStatusCode.Created, patient.StatusCode);
var patientId = (await patient.Content.ReadFromJsonAsync<Profile>())!.PatientId;
using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{patientId}/observations", new
{
measuredAt = "2026-09-12T08:00:00", systolic = 182, diastolic = 82, pulse = 68,
context = "Resting", note = "Before breakfast"
});
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
return (await response.Content.ReadFromJsonAsync<Observation>())!;
}
[Fact]
public async Task Correction_preserves_other_information_and_is_visible_in_all_retrievals_after_restart()
{
var original = await RecordAsync();
var other = await RecordAsync();
await using var db = fixture.CreateObservationDbContext();
var before = await db.Observations.AsNoTracking().SingleAsync(o => o.ObservationId == original.ObservationId);
using var response = await fixture.Client.PutAsJsonAsync($"/api/observations/{original.ObservationId}",
new { systolic = 128, diastolic = 82, pulse = 68 });
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var expected = original with { Systolic = 128 };
Assert.Equal(expected, await response.Content.ReadFromJsonAsync<Observation>());
await fixture.RestartHostsAsync();
Assert.Equal(expected, await fixture.Client.GetFromJsonAsync<Observation>($"/api/observations/{original.ObservationId}"));
Assert.Equal(expected, await fixture.Client.GetFromJsonAsync<Observation>(
$"/api/patients/{original.PatientId}/observations/latest"));
var history = await fixture.Client.GetFromJsonAsync<Observation[]>(
$"/api/patients/{original.PatientId}/observations?from=2026-09-12T00:00:00&to=2026-09-12T23:59:59");
Assert.Equal(expected, Assert.Single(history!));
Assert.Equal(other, await fixture.Client.GetFromJsonAsync<Observation>($"/api/observations/{other.ObservationId}"));
var after = await db.Observations.AsNoTracking().SingleAsync(o => o.ObservationId == original.ObservationId);
Assert.Equal(before.CreatedAt, after.CreatedAt);
Assert.True(after.UpdatedAt > before.UpdatedAt);
}
[Fact]
public async Task All_three_measured_values_can_be_corrected()
{
var original = await RecordAsync();
using var response = await fixture.Client.PutAsJsonAsync($"/api/observations/{original.ObservationId}",
new { systolic = 120, diastolic = 80, pulse = 60 });
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(original with { Systolic = 120, Diastolic = 80, Pulse = 60 },
await fixture.Client.GetFromJsonAsync<Observation>($"/api/observations/{original.ObservationId}"));
}
[Theory]
[InlineData(0, 82, 68)]
[InlineData(128, 0, 68)]
[InlineData(128, 82, 0)]
[InlineData(-1, 82, 68)]
[InlineData(128, -1, 68)]
[InlineData(128, 82, -1)]
public async Task Non_positive_values_are_rejected_without_changing_observation(int systolic, int diastolic, int pulse)
{
var original = await RecordAsync();
await using var db = fixture.CreateObservationDbContext();
var before = await db.Observations.AsNoTracking().SingleAsync(o => o.ObservationId == original.ObservationId);
using var response = await fixture.Client.PutAsJsonAsync($"/api/observations/{original.ObservationId}",
new { systolic, diastolic, pulse });
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.Equal(original, await fixture.Client.GetFromJsonAsync<Observation>($"/api/observations/{original.ObservationId}"));
var after = await db.Observations.AsNoTracking().SingleAsync(o => o.ObservationId == original.ObservationId);
Assert.Equal(before.UpdatedAt, after.UpdatedAt);
}
[Theory]
[InlineData("{\"diastolic\":82,\"pulse\":68}")]
[InlineData("{\"systolic\":128,\"pulse\":68}")]
[InlineData("{\"systolic\":128,\"diastolic\":82}")]
[InlineData("{\"systolic\":null,\"diastolic\":82,\"pulse\":68}")]
[InlineData("{\"systolic\":\"invalid\",\"diastolic\":82,\"pulse\":68}")]
[InlineData("{")]
public async Task Missing_or_malformed_values_are_rejected_without_changes(string json)
{
var original = await RecordAsync();
using var content = new StringContent(json, Encoding.UTF8, "application/json");
using var response = await fixture.Client.PutAsync($"/api/observations/{original.ObservationId}", content);
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
using var problem = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
Assert.True(problem.RootElement.TryGetProperty("errors", out _));
Assert.Equal(original, await fixture.Client.GetFromJsonAsync<Observation>($"/api/observations/{original.ObservationId}"));
}
[Fact]
public async Task Missing_observation_is_rejected_without_inserting_a_new_observation()
{
await using var db = fixture.CreateObservationDbContext();
var count = await db.Observations.CountAsync();
var observationId = Guid.NewGuid();
using var response = await fixture.Client.PutAsJsonAsync($"/api/observations/{observationId}",
new { systolic = 128, diastolic = 82, pulse = 68 });
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
Assert.Equal(count, await db.Observations.CountAsync());
using var retrieval = await fixture.Client.GetAsync($"/api/observations/{observationId}");
Assert.Equal(HttpStatusCode.NotFound, retrieval.StatusCode);
}
}
@@ -0,0 +1,149 @@
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using HealthApp.TestSupport;
using ObservationService.Domain;
using PatientProfileService.Domain;
using Xunit;
namespace Observation.AcceptanceTests;
public sealed class ViewObservationContextTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
{
private static int nextAccount = 180;
private sealed record Saved(string AccountId, Guid PatientId, Guid ObservationId);
private sealed record ContextData(string Setting, string ActivityCondition, decimal? RestDurationMinutes,
string? BodyPosition, string? MeasuredArm, string? DeviceDetails, string? CuffDetails, string? AdditionalCircumstances);
private sealed record ObservationData(Guid ObservationId, Guid PatientId, DateTime MeasuredAt,
int Systolic, int Diastolic, int Pulse, string? Context, string? Note, ContextData MeasurementContext);
// Establish Given directly, independently of observation creation and its response.
private async Task<Saved> Seed(MeasurementContext? context = null, string? legacyText = null)
{
var account = "test-" + Interlocked.Increment(ref nextAccount);
var patientId = Guid.NewGuid();
var observationId = Guid.NewGuid();
var timestamp = new DateTime(2026, 9, 12, 8, 0, 0);
await using var patients = fixture.CreateDbContext();
patients.Patients.Add(new Patient
{
PatientId = patientId, AccountId = account, Name = "Retrieval patient",
DateOfBirth = new DateOnly(1980, 1, 1), CreatedAt = timestamp, UpdatedAt = timestamp
});
await patients.SaveChangesAsync();
await using var observations = fixture.CreateObservationDbContext();
observations.Observations.Add(new BloodPressureObservation
{
ObservationId = observationId, PatientId = patientId, MeasuredAt = timestamp,
Systolic = 128, Diastolic = 82, Pulse = 68, Context = legacyText, Note = "Saved note",
MeasurementContext = context ?? new(), CreatedAt = timestamp, UpdatedAt = timestamp
});
await observations.SaveChangesAsync();
return new Saved(account, patientId, observationId);
}
private async Task<HttpResponseMessage> Read(Guid observationId, string? token)
{
using var request = new HttpRequestMessage(HttpMethod.Get, $"/api/observations/{observationId}");
if (token is not null) request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
return await fixture.RawClient.SendAsync(request);
}
[Fact]
public async Task Complete_saved_context_is_returned_with_its_measurements_and_timestamp_after_restart()
{
var saved = await Seed(new MeasurementContext
{
Setting = "Home", ActivityCondition = "AtRest", RestDurationMinutes = 5.5m,
BodyPosition = "Seated", MeasuredArm = "Right", DeviceDetails = "Recorded device",
CuffDetails = "Recorded cuff", AdditionalCircumstances = "Recorded circumstances"
}, "Original context text");
await fixture.RestartHostsAsync();
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, saved.AccountId);
using var response = await Read(saved.ObservationId, token);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var observation = (await response.Content.ReadFromJsonAsync<ObservationData>())!;
Assert.Equal(saved.ObservationId, observation.ObservationId);
Assert.Equal(saved.PatientId, observation.PatientId);
Assert.Equal(new DateTime(2026, 9, 12, 8, 0, 0), observation.MeasuredAt);
Assert.Equal(128, observation.Systolic);
Assert.Equal(82, observation.Diastolic);
Assert.Equal(68, observation.Pulse);
Assert.Equal("Original context text", observation.Context);
Assert.Equal("Saved note", observation.Note);
Assert.Equal(new ContextData("Home", "AtRest", 5.5m, "Seated", "Right", "Recorded device",
"Recorded cuff", "Recorded circumstances"), observation.MeasurementContext);
}
[Fact]
public async Task Partial_saved_context_distinguishes_known_setting_from_unknown_condition_and_details()
{
var saved = await Seed(new MeasurementContext { Setting = "Clinic" });
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, saved.AccountId);
using var response = await Read(saved.ObservationId, token);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var observation = (await response.Content.ReadFromJsonAsync<ObservationData>())!;
Assert.Equal(new ContextData("Clinic", "Unknown", null, null, null, null, null, null), observation.MeasurementContext);
Assert.Equal(saved.ObservationId, observation.ObservationId);
}
[Fact]
public async Task Historical_free_text_is_returned_without_inventing_setting_or_activity()
{
var saved = await Seed(legacyText: "Morning reading");
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, saved.AccountId);
using var response = await Read(saved.ObservationId, token);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var observation = (await response.Content.ReadFromJsonAsync<ObservationData>())!;
Assert.Equal("Morning reading", observation.Context);
Assert.Equal("Saved note", observation.Note);
Assert.Equal(new ContextData("Unknown", "Unknown", null, null, null, null, null, null), observation.MeasurementContext);
}
[Fact]
public async Task Missing_observation_reports_not_found_without_disclosing_saved_context()
{
var saved = await Seed(new MeasurementContext { Setting = "Home" });
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, saved.AccountId);
using var response = await Read(Guid.NewGuid(), token);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
Assert.Empty(await response.Content.ReadAsStringAsync());
}
[Fact]
public async Task Unauthorised_callers_cannot_read_observation_context()
{
var saved = await Seed(new MeasurementContext { Setting = "Home", DeviceDetails = "Private device details" });
var other = await Seed();
var otherToken = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, other.AccountId);
var professional = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional-empty");
foreach (var (token, expected) in new[]
{
((string?)null, HttpStatusCode.Unauthorized),
((string?)"invalid", HttpStatusCode.Unauthorized),
((string?)otherToken, HttpStatusCode.NotFound),
((string?)professional, HttpStatusCode.NotFound)
})
{
using var response = await Read(saved.ObservationId, token);
Assert.Equal(expected, response.StatusCode);
Assert.Empty(await response.Content.ReadAsStringAsync());
}
}
[Fact]
public async Task Assigned_professional_reads_the_same_context_as_the_owner()
{
var saved = await Seed(new MeasurementContext { Setting = "Clinic", ActivityCondition = "AfterActivity",
AdditionalCircumstances = "Actual circumstances" }, "Original narrative");
fixture.AdditionalGatewayConfiguration["Access:ProfessionalAssignments:professional:0"] = saved.PatientId.ToString();
await fixture.RestartHostsAsync();
var patientToken = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, saved.AccountId);
var professionalToken = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional");
using var patient = await Read(saved.ObservationId, patientToken);
using var professional = await Read(saved.ObservationId, professionalToken);
Assert.Equal(HttpStatusCode.OK, patient.StatusCode);
Assert.Equal(HttpStatusCode.OK, professional.StatusCode);
Assert.Equal(await patient.Content.ReadFromJsonAsync<ObservationData>(), await professional.Content.ReadFromJsonAsync<ObservationData>());
}
}
@@ -0,0 +1,102 @@
using System.Net;
using System.Security.Claims;
using System.Text;
using System.Text.Encodings.Web;
using HealthApp.TestSupport;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Xunit;
namespace PatientProfile.AcceptanceTests;
public sealed class AuthenticationIntegrationTests
{
[Fact]
public async Task Production_gateway_rejects_plain_http_even_for_login_and_public_guidance()
{
var authentication = new AuthenticatedTestClient();
try
{
var configuration = authentication.Configuration();
foreach (var service in new[] { "PatientProfile", "Observation", "Insights", "HealthOverview" })
configuration[$"Services:{service}:BaseUrl"] = "https://service.example.test/";
using var host = new WebApplicationFactory<ApiGateway.Program>().WithWebHostBuilder(builder =>
{
builder.UseEnvironment("Production");
builder.ConfigureAppConfiguration((_, config) => config.AddInMemoryCollection(configuration));
});
using var http = host.CreateClient();
using var guidance = await http.GetAsync("/api/measurement-guidance");
Assert.Equal(HttpStatusCode.BadRequest, guidance.StatusCode);
using var login = await http.PostAsync("/api/authentication/login", new StringContent("{}", Encoding.UTF8, "application/json"));
Assert.Equal(HttpStatusCode.BadRequest, login.StatusCode);
using var https = host.CreateClient(new WebApplicationFactoryClientOptions { BaseAddress = new Uri("https://localhost") });
using var available = await https.GetAsync("/api/measurement-guidance");
Assert.Equal(HttpStatusCode.OK, available.StatusCode);
}
finally { if (Directory.Exists(authentication.KeyDirectory)) Directory.Delete(authentication.KeyDirectory, true); }
}
[Theory]
[InlineData("Patient", "test-0")]
[InlineData("HealthcareProfessional", "professional")]
public async Task Standard_replacement_handler_with_same_identity_retains_ownership_policy(string role, string accountId)
{
var authentication = new AuthenticatedTestClient();
var patient = Guid.NewGuid();
try
{
var configuration = authentication.Configuration();
configuration["TestIdentity:Role"] = role;
configuration["TestIdentity:AccountId"] = accountId;
configuration[$"Access:ProfessionalAssignments:{accountId}:0"] = patient.ToString();
foreach (var service in new[] { "PatientProfile", "Observation", "Insights", "HealthOverview" })
configuration[$"Services:{service}:BaseUrl"] = "http://service.example.test/";
using var host = new WebApplicationFactory<ApiGateway.Program>().WithWebHostBuilder(builder =>
{
builder.UseEnvironment("Development");
builder.ConfigureAppConfiguration((_, config) => config.AddInMemoryCollection(configuration));
builder.ConfigureServices(services =>
{
services.AddAuthentication().AddScheme<AuthenticationSchemeOptions, ReplacementHandler>("Replacement", null);
services.PostConfigure<PolicySchemeOptions>("ClientOrService", options => options.ForwardDefaultSelector = _ => "Replacement");
services.AddHttpClient("PatientProfile").ConfigurePrimaryHttpMessageHandler(() => new PatientHandler(patient));
});
});
using var client = host.CreateClient();
using var own = await client.GetAsync($"/api/patients/{patient}");
Assert.Equal(HttpStatusCode.OK, own.StatusCode);
using var other = await client.GetAsync($"/api/patients/{Guid.NewGuid()}");
Assert.Equal(HttpStatusCode.NotFound, other.StatusCode);
Assert.Empty(await other.Content.ReadAsStringAsync());
}
finally { if (Directory.Exists(authentication.KeyDirectory)) Directory.Delete(authentication.KeyDirectory, true); }
}
public sealed class ReplacementHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder, IConfiguration configuration)
: AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
{
protected override Task<AuthenticateResult> HandleAuthenticateAsync() => Task.FromResult(
AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.NameIdentifier, configuration["TestIdentity:AccountId"]!), new Claim(ClaimTypes.Role, configuration["TestIdentity:Role"]!)
}, Scheme.Name)), Scheme.Name)));
}
private sealed class PatientHandler(Guid patientId) : HttpMessageHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
Assert.True(request.Headers.Contains("X-Gateway-Key"));
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent($"{{\"patientId\":\"{patientId}\"}}", Encoding.UTF8, "application/json")
});
}
}
}
@@ -0,0 +1,99 @@
using System.Net;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using Xunit;
namespace PatientProfile.AcceptanceTests;
public sealed class CreatePatientTests(PatientApiFixture fixture) : IClassFixture<PatientApiFixture>
{
// This HTTP contract is independent of the service's implementation DTOs.
public sealed record Profile(Guid PatientId, string Name, DateOnly DateOfBirth, string? ContactInfo);
[Fact]
public async Task Valid_profile_is_assigned_an_identifier_and_can_be_retrieved_after_restart()
{
using var response = await fixture.Client.PostAsJsonAsync("/api/patients", new
{
name = "Steffen Example", dateOfBirth = "1980-01-01", contactInfo = "steffen@example.test"
});
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
var created = await response.Content.ReadFromJsonAsync<Profile>();
Assert.NotNull(created);
Assert.NotEqual(Guid.Empty, created.PatientId);
Assert.Equal("Steffen Example", created.Name);
Assert.Equal(new DateOnly(1980, 1, 1), created.DateOfBirth);
Assert.Equal("steffen@example.test", created.ContactInfo);
Assert.Equal($"/api/patients/{created.PatientId}", response.Headers.Location!.ToString());
await fixture.RestartHostsAsync();
using var retrieved = await fixture.Client.GetAsync(response.Headers.Location);
Assert.Equal(HttpStatusCode.OK, retrieved.StatusCode);
Assert.Equal(created, await retrieved.Content.ReadFromJsonAsync<Profile>());
await using var db = fixture.CreateDbContext();
var stored = await db.Patients.SingleAsync(p => p.PatientId == created.PatientId);
Assert.Equal(created.Name, stored.Name);
Assert.Equal(created.DateOfBirth, stored.DateOfBirth);
Assert.Equal(created.ContactInfo, stored.ContactInfo);
Assert.NotEqual(default, stored.CreatedAt);
Assert.Equal(stored.CreatedAt, stored.UpdatedAt);
}
[Theory]
[InlineData("{\"dateOfBirth\":\"1980-01-01\"}", "Name")]
[InlineData("{\"name\":null,\"dateOfBirth\":\"1980-01-01\"}", "Name")]
[InlineData("{\"name\":\"\",\"dateOfBirth\":\"1980-01-01\"}", "Name")]
[InlineData("{\"name\":\" \",\"dateOfBirth\":\"1980-01-01\"}", "Name")]
[InlineData("{\"name\":\"Steffen Example\"}", "DateOfBirth")]
[InlineData("{\"name\":\"Steffen Example\",\"dateOfBirth\":null}", "DateOfBirth")]
public async Task Missing_required_information_is_rejected_without_persisting(string json, string field)
{
await using var db = fixture.CreateDbContext();
var countBefore = await db.Patients.CountAsync();
using var content = new StringContent(json, Encoding.UTF8, "application/json");
using var response = await fixture.Client.PostAsync("/api/patients", content);
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
using var problem = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
Assert.True(problem.RootElement.GetProperty("errors").TryGetProperty(field, out _));
Assert.Equal(countBefore, await db.Patients.CountAsync());
}
[Theory]
[InlineData("{\"name\":\"Steffen Example\",\"dateOfBirth\":\"invalid\"}")]
[InlineData("{\"name\":\"Steffen Example\",\"dateOfBirth\":\"1980-02-30\"}")]
[InlineData("{")]
public async Task Malformed_information_is_rejected(string json)
{
await using var db = fixture.CreateDbContext();
var countBefore = await db.Patients.CountAsync();
using var content = new StringContent(json, Encoding.UTF8, "application/json");
using var response = await fixture.Client.PostAsync("/api/patients", content);
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.Equal(countBefore, await db.Patients.CountAsync());
}
[Fact]
public async Task Separate_creations_have_distinct_identifiers_and_contact_information_is_optional()
{
var request = new { name = "Steffen Example", dateOfBirth = "1980-01-01" };
using var first = await fixture.Client.PostAsJsonAsync("/api/patients", request);
using var second = await fixture.Client.PostAsJsonAsync("/api/patients", request);
Assert.Equal(HttpStatusCode.Created, first.StatusCode);
Assert.Equal(HttpStatusCode.Created, second.StatusCode);
var firstProfile = await first.Content.ReadFromJsonAsync<Profile>();
var secondProfile = await second.Content.ReadFromJsonAsync<Profile>();
Assert.NotEqual(firstProfile!.PatientId, secondProfile!.PatientId);
Assert.Null(firstProfile.ContactInfo);
Assert.Equal(firstProfile, await fixture.Client.GetFromJsonAsync<Profile>(first.Headers.Location));
}
[Fact]
public async Task Unknown_identifier_returns_not_found()
{
using var response = await fixture.Client.GetAsync($"/api/patients/{Guid.NewGuid()}");
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
}
@@ -0,0 +1,136 @@
using System.Net;
using HealthApp.TestSupport;
using Microsoft.AspNetCore.Hosting;
using System.Text.Json;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
namespace PatientProfile.AcceptanceTests;
public sealed class MeasurementGuidanceTests : IDisposable
{
private readonly WebApplicationFactory<ApiGateway.Program> host;
private readonly HttpClient client;
private int upstreamCalls;
private readonly AuthenticatedTestClient authentication = new();
public MeasurementGuidanceTests()
{
host = new WebApplicationFactory<ApiGateway.Program>().WithWebHostBuilder(builder =>
{
builder.UseEnvironment("Development");
builder.ConfigureAppConfiguration((_, config) => config.AddInMemoryCollection(authentication.Configuration()).AddInMemoryCollection(
new Dictionary<string, string?>
{
["Services:PatientProfile:BaseUrl"] = "http://127.0.0.1:1/",
["Services:Observation:BaseUrl"] = "http://127.0.0.1:1/",
["Services:Insights:BaseUrl"] = "http://127.0.0.1:1/"
}));
builder.ConfigureServices(services =>
{
foreach (var name in new[] { "PatientProfile", "Observation", "Insights" })
services.AddHttpClient(name).ConfigurePrimaryHttpMessageHandler(
() => new RejectUpstreamHandler(() => Interlocked.Increment(ref upstreamCalls)));
});
});
client = host.CreateClient();
}
[Theory]
[InlineData("")]
[InlineData("?setting=Unknown")]
[InlineData("?setting=Home")]
public async Task Public_guidance_without_patient_records_is_labelled_and_has_ordered_sourced_instructions(string query)
{
using var response = await client.GetAsync("/api/measurement-guidance" + query);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
var result = json.RootElement;
Assert.True(result.GetProperty("available").GetBoolean());
Assert.Equal("Home", result.GetProperty("applicableSetting").GetString());
Assert.Equal("AtRest", result.GetProperty("applicableActivityCondition").GetString());
Assert.True(DateOnly.TryParse(result.GetProperty("reviewedOn").GetString(), out _));
var steps = result.GetProperty("steps").EnumerateArray().ToArray();
Assert.Equal(Enumerable.Range(1, 6), steps.Select(s => s.GetProperty("order").GetInt32()));
var instructions = string.Join(" ", steps.Select(s => s.GetProperty("instruction").GetString()));
foreach (var text in new[] { "validated upper-arm", "cuff", "five minutes", "back and arm supported",
"still", "three readings", "three consecutive days", "one observation", "actual", "measurement time" })
Assert.Contains(text, instructions);
var sources = result.GetProperty("sources").EnumerateArray().ToArray();
Assert.Equal(2, sources.Length);
Assert.All(sources, source =>
{
Assert.StartsWith("https://www.sundhed.dk/", source.GetProperty("url").GetString());
Assert.True(DateOnly.TryParse(source.GetProperty("updatedOn").GetString(), out _));
});
Assert.Contains("not a clinical measurement protocol", result.GetProperty("explanation").GetString());
Assert.Contains("does not assess rhythm regularity", result.GetProperty("pulseExplanation").GetString());
Assert.Contains("does not save or alter", result.GetProperty("limitations").GetString());
Assert.Contains("prevent a valid submission", result.GetProperty("limitations").GetString());
Assert.DoesNotContain("patientId", result.GetRawText());
Assert.DoesNotContain("assignments", result.GetRawText());
Assert.Equal(0, upstreamCalls);
}
[Theory]
[InlineData("DuringActivity")]
[InlineData("AfterActivity")]
public async Task Activity_is_not_relabelled_as_rest_or_certified(string activity)
{
using var response = await client.GetAsync($"/api/measurement-guidance?setting=Home&activityCondition={activity}");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
var result = json.RootElement;
Assert.Equal(activity, result.GetProperty("requestedActivityCondition").GetString());
Assert.Contains("do not relabel", result.GetProperty("activityExplanation").GetString());
Assert.Contains("remain valid to record", result.GetProperty("activityExplanation").GetString());
Assert.Contains("does not record a setting or certify compliance", result.GetProperty("explanation").GetString());
Assert.Equal(0, upstreamCalls);
}
[Theory]
[InlineData("Clinic")]
[InlineData("Other")]
public async Task Unsupported_guidance_is_explicitly_unavailable_without_unverified_instructions(string setting)
{
using var response = await client.GetAsync($"/api/measurement-guidance?setting={setting}");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
var result = json.RootElement;
Assert.False(result.GetProperty("available").GetBoolean());
Assert.Contains("unavailable", result.GetProperty("explanation").GetString());
Assert.Empty(result.GetProperty("steps").EnumerateArray());
Assert.Empty(result.GetProperty("sources").EnumerateArray());
Assert.Equal(JsonValueKind.Null, result.GetProperty("applicableSetting").ValueKind);
Assert.Equal(0, upstreamCalls);
}
[Theory]
[InlineData("setting=Unsupported")]
[InlineData("activityCondition=Unsupported")]
public async Task Invalid_categories_return_explained_rejections(string query)
{
using var response = await client.GetAsync("/api/measurement-guidance?" + query);
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.Contains("Unsupported", await response.Content.ReadAsStringAsync());
Assert.Equal(0, upstreamCalls);
}
public void Dispose()
{
client.Dispose();
host.Dispose();
if (Directory.Exists(authentication.KeyDirectory)) Directory.Delete(authentication.KeyDirectory, true);
}
private sealed class RejectUpstreamHandler(Action called) : HttpMessageHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
called();
throw new InvalidOperationException("Guidance must not read or write patient data.");
}
}
}
@@ -0,0 +1,93 @@
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<PatientProfileService.Program>? service;
private WebApplicationFactory<ApiGateway.Program>? 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<PatientDbContext>().UseNpgsql(ConnectionString).Options);
private void StartHosts()
{
service = new WebApplicationFactory<PatientProfileService.Program>().WithWebHostBuilder(builder =>
{
builder.UseEnvironment("Development");
builder.ConfigureKestrel(options => options.Listen(IPAddress.Loopback, 0));
builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(
new Dictionary<string, string?> { ["ConnectionStrings:PatientDatabase"] = ConnectionString, ["InternalAccess:GatewayKey"] = Authentication.GatewayKey }));
});
service.UseKestrel(0);
using var serviceClient = service.CreateClient();
gateway = new WebApplicationFactory<ApiGateway.Program>().WithWebHostBuilder(builder =>
builder.UseEnvironment("Development").ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(Authentication.Configuration()).AddInMemoryCollection(
new Dictionary<string, string?> { ["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<BearerTokenOptions>("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();
}
}
@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5" PrivateAssets="all" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.12" />
<ProjectReference Include="../../src/PatientProfileService/PatientProfileService.csproj" />
<ProjectReference Include="../../src/ApiGateway/ApiGateway.csproj" />
</ItemGroup>
<ItemGroup>
<Compile Include="../Support/AuthenticatedTestClient.cs" Link="Support/AuthenticatedTestClient.cs" />
</ItemGroup>
</Project>
@@ -0,0 +1,71 @@
using System.Net;
using System.Net.Http.Json;
using Microsoft.EntityFrameworkCore;
using Xunit;
namespace PatientProfile.AcceptanceTests;
public sealed class UpdatePatientTests(PatientApiFixture fixture) : IClassFixture<PatientApiFixture>
{
private sealed record Profile(Guid PatientId, string Name, DateOnly DateOfBirth, string? ContactInfo);
[Fact]
public async Task Updated_profile_preserves_identity_and_date_of_birth_and_survives_restart()
{
using var createdResponse = await fixture.Client.PostAsJsonAsync("/api/patients", new
{
name = "Steffen Example", dateOfBirth = "1980-01-01", contactInfo = "old@example.test"
});
Assert.Equal(HttpStatusCode.Created, createdResponse.StatusCode);
var created = (await createdResponse.Content.ReadFromJsonAsync<Profile>())!;
var path = $"/api/patients/{created.PatientId}";
using var response = await fixture.Client.PutAsJsonAsync(path, new
{
name = "Steffen Updated", contactInfo = "new@example.test"
});
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var expected = created with { Name = "Steffen Updated", ContactInfo = "new@example.test" };
Assert.Equal(expected, await response.Content.ReadFromJsonAsync<Profile>());
await fixture.RestartHostsAsync();
Assert.Equal(expected, await fixture.Client.GetFromJsonAsync<Profile>(path));
}
[Fact]
public async Task Updating_a_missing_patient_is_rejected_without_creating_a_profile()
{
await using var db = fixture.CreateDbContext();
var countBefore = await db.Patients.CountAsync();
var path = $"/api/patients/{Guid.NewGuid()}";
using var response = await fixture.Client.PutAsJsonAsync(path, new
{
name = "Steffen Example", contactInfo = "new@example.test"
});
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
Assert.Equal(countBefore, await db.Patients.CountAsync());
using var retrieval = await fixture.Client.GetAsync(path);
Assert.Equal(HttpStatusCode.NotFound, retrieval.StatusCode);
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
public async Task Invalid_name_is_rejected_without_changing_the_profile(string? name)
{
using var createdResponse = await fixture.Client.PostAsJsonAsync("/api/patients", new
{
name = "Steffen Example", dateOfBirth = "1980-01-01", contactInfo = "old@example.test"
});
Assert.Equal(HttpStatusCode.Created, createdResponse.StatusCode);
var created = (await createdResponse.Content.ReadFromJsonAsync<Profile>())!;
var path = $"/api/patients/{created.PatientId}";
using var response = await fixture.Client.PutAsJsonAsync(path, new
{
name, contactInfo = "new@example.test"
});
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.Equal(created, await fixture.Client.GetFromJsonAsync<Profile>(path));
}
}
@@ -0,0 +1,112 @@
using System.Collections.Concurrent;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using ApiGateway.Security;
using Microsoft.AspNetCore.Identity;
namespace HealthApp.TestSupport;
// Existing functional tests use real login and an authorised account for each resource.
// Security tests use RawClient instead to exercise rejected requests explicitly.
public sealed class AuthenticatedTestClient
{
public const string Password = "synthetic-test-password";
public readonly string GatewayKey = new('g', 48);
public readonly string ObservationServiceKey = new('o', 48);
public readonly string InsightsServiceKey = new('i', 48);
public readonly string OverviewServiceKey = new('v', 48);
public TestClock Clock { get; } = new();
public string KeyDirectory { get; } = Path.Combine(Path.GetTempPath(), "healthapp-keys-" + Guid.NewGuid());
public ConcurrentDictionary<Guid, string> PatientAccounts { get; } = new();
private readonly ConcurrentDictionary<Guid, string> observationAccounts = new();
private readonly ConcurrentDictionary<string, string> tokens = new();
private int accountNumber;
private string lastAccount = "test-0";
private readonly string hash = new PasswordHasher<PrototypeAccount>().HashPassword(new(), Password);
public Dictionary<string, string?> Configuration()
{
var values = new Dictionary<string, string?>
{
["Authentication:KeyDirectory"] = KeyDirectory,
["Services:PatientProfile:Key"] = GatewayKey,
["Services:Observation:Key"] = GatewayKey,
["Services:Insights:Key"] = GatewayKey,
["InternalAccess:Observation:Key"] = ObservationServiceKey,
["InternalAccess:Insights:Key"] = InsightsServiceKey,
["InternalAccess:HealthOverview:Key"] = OverviewServiceKey,
["Services:HealthOverview:Key"] = GatewayKey,
["Services:HealthOverview:BaseUrl"] = "http://127.0.0.1:1/"
};
for (var i = 0; i < 256; i++)
{
values[$"Authentication:Accounts:{i}:AccountId"] = "test-" + i;
values[$"Authentication:Accounts:{i}:PasswordHash"] = hash;
values[$"Authentication:Accounts:{i}:Role"] = "Patient";
}
values["Authentication:Accounts:256:AccountId"] = "professional";
values["Authentication:Accounts:256:PasswordHash"] = hash;
values["Authentication:Accounts:256:Role"] = "HealthcareProfessional";
for (var i = 257; i <= 258; i++)
{
values[$"Authentication:Accounts:{i}:AccountId"] = i == 257 ? "professional-second" : "professional-empty";
values[$"Authentication:Accounts:{i}:PasswordHash"] = hash;
values[$"Authentication:Accounts:{i}:Role"] = "HealthcareProfessional";
}
return values;
}
public HttpClient Wrap(HttpClient raw) => new(new Handler(this, raw)) { BaseAddress = raw.BaseAddress };
public static async Task<string> LoginAsync(HttpClient raw, string account = "test-0", string password = Password)
{
using var response = await raw.PostAsJsonAsync("/api/authentication/login", new { accountId = account, password });
response.EnsureSuccessStatusCode();
using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
return json.RootElement.GetProperty("accessToken").GetString()!;
}
private sealed class Handler(AuthenticatedTestClient owner, HttpClient raw) : HttpMessageHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var path = request.RequestUri!.AbsolutePath;
var parts = path.Trim('/').Split('/');
var account = owner.lastAccount;
if (path == "/api/patients" && request.Method == HttpMethod.Post)
account = "test-" + Interlocked.Increment(ref owner.accountNumber);
else if (parts.Length >= 3 && Guid.TryParse(parts[2], out var id))
{
var map = parts[1] == "patients" ? owner.PatientAccounts : owner.observationAccounts;
if (map.TryGetValue(id, out var found)) account = found;
}
if (!owner.tokens.TryGetValue(account, out var token))
{
token = await LoginAsync(raw, account);
owner.tokens[account] = token;
}
using var forwarded = new HttpRequestMessage(request.Method, request.RequestUri) { Content = request.Content };
foreach (var header in request.Headers) forwarded.Headers.TryAddWithoutValidation(header.Key, header.Value);
forwarded.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
var response = await raw.SendAsync(forwarded, cancellationToken);
if (response.IsSuccessStatusCode && request.Method == HttpMethod.Post)
{
using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync(cancellationToken));
if (json.RootElement.TryGetProperty("patientId", out var patient))
owner.PatientAccounts[patient.GetGuid()] = account;
if (json.RootElement.TryGetProperty("observationId", out var observation))
owner.observationAccounts[observation.GetGuid()] = account;
owner.lastAccount = account;
}
return response;
}
}
}
public sealed class TestClock : TimeProvider
{
private DateTimeOffset now = DateTimeOffset.UtcNow;
public override DateTimeOffset GetUtcNow() => now;
public void Advance(TimeSpan span) => now += span;
}