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 { 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 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())!.PatientId; } private async Task 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())!; } [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( $"/api/patients/{patientId}/observations/latest")); Assert.Equal(otherLatest, await fixture.Client.GetFromJsonAsync( $"/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 Latest(Guid patientId) => fixture.Client.GetFromJsonAsync($"/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); } }