From d21005b6fe7c69fac70b0fe6d5fed4f14182ebb7 Mon Sep 17 00:00:00 2001 From: Steffen Date: Mon, 5 Oct 2026 12:55:07 +0200 Subject: [PATCH] Verify US-09 deletion of structured observation context --- src/README.md | 2 +- .../DeleteContextualisedObservationTests.cs | 129 ++++++++++++++++++ 2 files changed, 130 insertions(+), 1 deletion(-) create mode 100644 tests/Observation.AcceptanceTests/DeleteContextualisedObservationTests.cs diff --git a/src/README.md b/src/README.md index e4af491..a79f48d 100644 --- a/src/README.md +++ b/src/README.md @@ -188,7 +188,7 @@ US-08 tests cover the original full numerical corrections and rejection scenario `DELETE /api/observations/{observationId}` removes the observation and returns `204 No Content`. A missing or previously deleted observation returns `404`. The Observation Service deletes the row from its own database in a single statement; deleted observations disappear from specific retrieval, history, and latest selection. Other observations and the patient profile are preserved. -US-09 tests cover both acceptance scenarios, persistence of deletion after restart, remaining/latest observations, deletion of the only observation, repeated deletion, and preservation of other patients' observations. No new dependencies or schema changes are required. +US-09 tests cover the original deletion scenarios plus structured-context removal, filtered history after restart, current numerical summaries excluding deleted values, preservation of other observations and their context, empty filtered results, repeated deletion, and rejection of unauthenticated/other-patient/professional deletion. Context is stored in the observation row, so its existing atomic deletion needs no new production operation. US-11 trend-specific deletion checks remain to be added with that endpoint. No new dependencies or schema changes are required. `GET /api/patients/{patientId}/insights?from=2026-09-03T00:00:00&to=2026-09-08T23:59:59` returns `200` with `patientId`, `periodStart`, `periodEnd`, decimal `averageSystolic`, `averageDiastolic`, `averagePulse`, and integer `minSystolic`, `maxSystolic`, `minDiastolic`, `maxDiastolic`. Period validation, inclusive bounds, and timestamp normalization follow observation history. A single observation is sufficient; averages retain fractional values without deliberate rounding. An empty period returns `404` problem details with title `Insufficient observation data for calculation.` Missing/malformed/reversed bounds return `400`. diff --git a/tests/Observation.AcceptanceTests/DeleteContextualisedObservationTests.cs b/tests/Observation.AcceptanceTests/DeleteContextualisedObservationTests.cs new file mode 100644 index 0000000..fb1636d --- /dev/null +++ b/tests/Observation.AcceptanceTests/DeleteContextualisedObservationTests.cs @@ -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 +{ + 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 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())!.PatientId; + } + + private async Task 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())!; + } + + private Task History(Guid patient) => fixture.Client.GetFromJsonAsync( + $"/api/patients/{patient}/observations?{Period}&setting=Home&activityCondition=AtRest"); + private Task Summary(Guid patient) => fixture.Client.GetFromJsonAsync($"/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($"/api/patients/{patient}/observations/latest")); + Assert.Equal(other, Assert.Single((await History(other.PatientId))!)); + Assert.Equal(other, await fixture.Client.GetFromJsonAsync($"/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($"/api/observations/{original.ObservationId}")); + } + Assert.Equal(original, Assert.Single((await History(patient))!)); + } +}