Implement US-12 consolidated health overview service
This commit is contained in:
1 parent
cc76c9bde4
commit
076e675c81
26 files changed
+804
-16
No files matched your search
@@ -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(); }
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@
|
||||
<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>
|
||||
|
||||
@@ -18,6 +18,8 @@ public sealed class ObservationApiFixture : IAsyncLifetime
|
||||
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;
|
||||
@@ -113,19 +115,44 @@ public sealed class ObservationApiFixture : IAsyncLifetime
|
||||
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();
|
||||
await insights!.DisposeAsync();
|
||||
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();
|
||||
@@ -142,6 +169,7 @@ public sealed class ObservationApiFixture : IAsyncLifetime
|
||||
{
|
||||
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();
|
||||
|
||||
@@ -23,7 +23,7 @@ public sealed class AuthenticationIntegrationTests
|
||||
try
|
||||
{
|
||||
var configuration = authentication.Configuration();
|
||||
foreach (var service in new[] { "PatientProfile", "Observation", "Insights" })
|
||||
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 =>
|
||||
{
|
||||
@@ -55,7 +55,7 @@ public sealed class AuthenticationIntegrationTests
|
||||
configuration["TestIdentity:Role"] = role;
|
||||
configuration["TestIdentity:AccountId"] = accountId;
|
||||
configuration[$"Access:ProfessionalAssignments:{accountId}:0"] = patient.ToString();
|
||||
foreach (var service in new[] { "PatientProfile", "Observation", "Insights" })
|
||||
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 =>
|
||||
{
|
||||
|
||||
@@ -15,6 +15,7 @@ public sealed class AuthenticatedTestClient
|
||||
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();
|
||||
@@ -33,7 +34,10 @@ public sealed class AuthenticatedTestClient
|
||||
["Services:Observation:Key"] = GatewayKey,
|
||||
["Services:Insights:Key"] = GatewayKey,
|
||||
["InternalAccess:Observation:Key"] = ObservationServiceKey,
|
||||
["InternalAccess:Insights:Key"] = InsightsServiceKey
|
||||
["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++)
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user