Complete US-05 observation context retrieval acceptance coverage

This commit is contained in:
Steffen committed 2026-10-05 11:56:38 +02:00
1 parent cfacaa0c24
commit 3bfa7ea149
2 files changed
+157

No files matched your search

+8
View File
@@ -108,6 +108,14 @@ table; no new table, service or dependency is introduced. Existing rows receive
unknown categories and null details without changing their measurements, timestamps unknown categories and null details without changing their measurements, timestamps
or text. Context filtering and context-only updates remain under US-07/US-08. or text. Context filtering and context-only updates remain under US-07/US-08.
US-05 context retrieval is covered independently of creation: dedicated tests seed
saved observations directly and request them through the authenticated gateway.
They verify complete context with its measurements/timestamp after restart, partial
and unknown context, preservation of historical free text, missing-observation
behaviour, rejected unauthorised reads, and identical context for an assigned
professional and the owner. This uses the existing retrieval endpoint and DTO added
with US-04; no further production code or migration is needed for US-05.
The Observation Service checks patient existence by calling the gateway's patient retrieval API over HTTP before saving. It has no reference to Patient/Profile implementation code and no access to that service's database. Missing patients return `404`; validation failures return `400`. Patient lookup failures return `502` or `504` and do not save an observation. Measurement timestamps without an offset represent UTC clock values and are stored as supplied, independently of the host time zone; timestamps with an offset are normalized to UTC. PostgreSQL uses the diagram's `timestamp` columns without a time-zone component. The Observation Service checks patient existence by calling the gateway's patient retrieval API over HTTP before saving. It has no reference to Patient/Profile implementation code and no access to that service's database. Missing patients return `404`; validation failures return `400`. Patient lookup failures return `502` or `504` and do not save an observation. Measurement timestamps without an offset represent UTC clock values and are stored as supplied, independently of the host time zone; timestamps with an offset are normalized to UTC. PostgreSQL uses the diagram's `timestamp` columns without a time-zone component.
`GET /api/patients/{patientId}/observations/latest` returns `200` with that patient's observation having the greatest measurement timestamp, regardless of recording order. It returns `404` when no observation is available. Equal measurement timestamps are resolved consistently by observation identifier; US-06 does not prescribe which tied observation to return. Selection happens in the Observation Service's own database through the documented controller/application-service/repository layers. `GET /api/patients/{patientId}/observations/latest` returns `200` with that patient's observation having the greatest measurement timestamp, regardless of recording order. It returns `404` when no observation is available. Equal measurement timestamps are resolved consistently by observation identifier; US-06 does not prescribe which tied observation to return. Selection happens in the Observation Service's own database through the documented controller/application-service/repository layers.
@@ -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>());
}
}