Implement US-10 on-demand health insights

This commit is contained in:
Steffen committed 2026-10-02 09:57:06 +02:00
1 parent 4cb6798ec9
commit a5b269cfc3
25 files changed
+482 -4

No files matched your search

@@ -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);
}
}
@@ -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/InsightsService/InsightsService.csproj" />
<ProjectReference Include="../../src/ObservationService/ObservationService.csproj" />
</ItemGroup>
</Project>
@@ -15,6 +15,7 @@ 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;
public string ObservationConnectionString { get; private set; } = "";
private string adminConnectionString = "";
private WebApplicationFactory<PatientProfileService.Program>? service;
@@ -68,6 +69,7 @@ public sealed class ObservationApiFixture : IAsyncLifetime
builder.ConfigureKestrel(options => options.Listen(IPAddress.Loopback, 0));
builder.ConfigureAppConfiguration((_, configuration) => 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.UseKestrel(0);
@@ -85,17 +87,33 @@ public sealed class ObservationApiFixture : IAsyncLifetime
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.ConfigureKestrel(options => options.Listen(IPAddress.Loopback, 0));
builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(
new Dictionary<string, string?> { ["Services:ApiGateway:BaseUrl"] = Client.BaseAddress!.ToString() }));
});
insights.UseKestrel(0);
using var insightsClient = insights.CreateClient();
gateway.Services.GetRequiredService<IConfiguration>()["Services:Insights:BaseUrl"] = insightsClient.BaseAddress!.ToString();
}
public async Task RestartHostsAsync()
{
Client.Dispose();
await observation!.DisposeAsync();
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 StopObservationServiceAsync()
{
if (observation is not null) await observation.DisposeAsync();
observation = null;
}
public async Task StopPatientServiceAsync()
{
await service!.DisposeAsync();
@@ -105,6 +123,7 @@ public sealed class ObservationApiFixture : IAsyncLifetime
public async Task DisposeAsync()
{
Client?.Dispose();
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();
@@ -52,6 +52,7 @@ public sealed class PatientApiFixture : IAsyncLifetime
gateway = new WebApplicationFactory<ApiGateway.Program>().WithWebHostBuilder(builder =>
builder.ConfigureAppConfiguration((_, configuration) => 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/" })));
Client = gateway.CreateClient();
}