Compose coherent Overview snapshots and preserve access ordering
This commit is contained in:
1 parent
cab10c5306
commit
cc7f87105d
16 files changed
+38314
-5
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 HealthApp.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.Unauthorized, 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.ServiceUnavailable, response.StatusCode);
|
||||
}
|
||||
finally { await fixture.RestartHostsAsync(); }
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,7 @@ public class PatientApiFixture : IAsyncLifetime
|
||||
public HttpClient Client {get;private set;}=null!;
|
||||
public HttpClient RawClient {get;private set;}=null!;
|
||||
public AuthenticatedTestClient Authentication {get;}=new();
|
||||
public Action<IServiceCollection>? ConfigureServices {get;set;}
|
||||
public Dictionary<string,string?> AdditionalGatewayConfiguration {get;}=new();
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
@@ -50,7 +51,7 @@ public class PatientApiFixture : IAsyncLifetime
|
||||
host=new WebApplicationFactory<HealthApp.Program>().WithWebHostBuilder(b=>{
|
||||
b.UseEnvironment("Development");b.ConfigureKestrel(k=>k.Listen(IPAddress.Loopback,0));
|
||||
b.ConfigureAppConfiguration((_,c)=>c.AddInMemoryCollection(Authentication.Configuration()).AddInMemoryCollection(AdditionalGatewayConfiguration).AddInMemoryCollection(new Dictionary<string,string?>{["ConnectionStrings:HealthDatabase"]=RuntimeConnectionString}));
|
||||
b.ConfigureServices(s=>s.PostConfigure<BearerTokenOptions>("Bearer",o=>o.TimeProvider=Authentication.Clock));
|
||||
b.ConfigureServices(s=>{s.PostConfigure<BearerTokenOptions>("Bearer",o=>o.TimeProvider=Authentication.Clock);ConfigureServices?.Invoke(s);});
|
||||
});
|
||||
host.UseKestrel(0);RawClient=host.CreateClient();Client=Authentication.Wrap(RawClient);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using HealthApp.TestSupport;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Xunit;
|
||||
|
||||
namespace Observation.AcceptanceTests;
|
||||
|
||||
public sealed class PatientAuthenticationTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
|
||||
{
|
||||
private static int nextAccount = 150;
|
||||
private sealed record Profile(Guid PatientId);
|
||||
private sealed record Observation(Guid ObservationId, Guid PatientId, int Systolic);
|
||||
private static object ProfileRequest => new { name = "Patient", dateOfBirth = "1980-01-01" };
|
||||
private static object ObservationRequest => new { measuredAt = "2026-09-12T08:00:00", systolic = 128, diastolic = 82, pulse = 68 };
|
||||
|
||||
private async Task<HttpResponseMessage> Send(HttpMethod method, string path, string? token = null, object? body = null)
|
||||
{
|
||||
using var request = new HttpRequestMessage(method, path);
|
||||
if (token is not null) request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
||||
if (body is not null) request.Content = JsonContent.Create(body);
|
||||
return await fixture.RawClient.SendAsync(request);
|
||||
}
|
||||
|
||||
private async Task<(string Token, Guid PatientId, string Account)> Patient()
|
||||
{
|
||||
var account = "test-" + Interlocked.Increment(ref nextAccount);
|
||||
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account);
|
||||
using var response = await Send(HttpMethod.Post, "/api/patients", token, ProfileRequest);
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
return (token, (await response.Content.ReadFromJsonAsync<Profile>())!.PatientId, account);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Login_without_profile_returns_normalized_identity_and_no_patient_data()
|
||||
{
|
||||
using var response = await fixture.RawClient.PostAsJsonAsync("/api/authentication/login",
|
||||
new { accountId = "test-0", password = AuthenticatedTestClient.Password, role = "HealthcareProfessional" });
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Contains("no-store", response.Headers.CacheControl!.ToString());
|
||||
using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
|
||||
Assert.Equal("test-0", json.RootElement.GetProperty("accountId").GetString());
|
||||
Assert.Equal("Patient", json.RootElement.GetProperty("role").GetString());
|
||||
Assert.Equal(1800, json.RootElement.GetProperty("expiresIn").GetInt32());
|
||||
Assert.False(json.RootElement.TryGetProperty("patientId", out _));
|
||||
Assert.False(json.RootElement.TryGetProperty("refreshToken", out _));
|
||||
using var unavailable = await Send(HttpMethod.Get, $"/api/patients/{Guid.NewGuid()}", json.RootElement.GetProperty("accessToken").GetString());
|
||||
Assert.Equal(HttpStatusCode.NotFound, unavailable.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Invalid_account_and_invalid_password_have_same_rejection()
|
||||
{
|
||||
using var unknown = await fixture.RawClient.PostAsJsonAsync("/api/authentication/login", new { accountId = "absent", password = AuthenticatedTestClient.Password });
|
||||
using var incorrect = await fixture.RawClient.PostAsJsonAsync("/api/authentication/login", new { accountId = "test-0", password = "incorrect" });
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, unknown.StatusCode);
|
||||
Assert.Equal(unknown.StatusCode, incorrect.StatusCode);
|
||||
Assert.Equal(await unknown.Content.ReadAsStringAsync(), await incorrect.Content.ReadAsStringAsync());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("GET", "patients/00000000-0000-0000-0000-000000000001")]
|
||||
[InlineData("POST", "patients")]
|
||||
[InlineData("GET", "patients/me")]
|
||||
[InlineData("PUT", "patients/00000000-0000-0000-0000-000000000001")]
|
||||
[InlineData("GET", "observations/00000000-0000-0000-0000-000000000001")]
|
||||
[InlineData("PUT", "observations/00000000-0000-0000-0000-000000000001")]
|
||||
[InlineData("DELETE", "observations/00000000-0000-0000-0000-000000000001")]
|
||||
[InlineData("POST", "patients/00000000-0000-0000-0000-000000000001/observations")]
|
||||
[InlineData("GET", "patients/00000000-0000-0000-0000-000000000001/observations/latest")]
|
||||
[InlineData("GET", "patients/00000000-0000-0000-0000-000000000001/observations")]
|
||||
[InlineData("GET", "patients/00000000-0000-0000-0000-000000000001/insights")]
|
||||
public async Task Missing_and_invalid_tokens_reject_every_existing_patient_operation(string method, string path)
|
||||
{
|
||||
await using var patients = fixture.CreateDbContext();
|
||||
await using var observations = fixture.CreateObservationDbContext();
|
||||
var patientCount = await patients.Patients.CountAsync();
|
||||
var observationCount = await observations.Observations.CountAsync();
|
||||
foreach (var token in new string?[] { null, "unverifiable" })
|
||||
{
|
||||
using var response = await Send(new HttpMethod(method), "/api/" + path, token, method == "GET" ? null : ProfileRequest);
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.DoesNotContain("Patient", await response.Content.ReadAsStringAsync());
|
||||
}
|
||||
Assert.Equal(patientCount, await patients.Patients.CountAsync());
|
||||
Assert.Equal(observationCount, await observations.Observations.CountAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Own_observations_and_insights_are_available_but_another_patients_reads_and_writes_are_rejected()
|
||||
{
|
||||
var first = await Patient();
|
||||
var second = await Patient();
|
||||
using var record = await Send(HttpMethod.Post, $"/api/patients/{first.PatientId}/observations", first.Token, ObservationRequest);
|
||||
Assert.Equal(HttpStatusCode.Created, record.StatusCode);
|
||||
var observation = (await record.Content.ReadFromJsonAsync<Observation>())!;
|
||||
var paths = new[] { $"patients/{first.PatientId}", $"patients/{first.PatientId}/observations",
|
||||
$"patients/{first.PatientId}/observations/latest", $"patients/{first.PatientId}/insights", $"observations/{observation.ObservationId}" };
|
||||
foreach (var path in paths)
|
||||
{
|
||||
var query = path.EndsWith("/observations") || path.EndsWith("/insights") ? "?from=2026-09-01&to=2026-10-01" : "";
|
||||
using var own = await Send(HttpMethod.Get, "/api/" + path + query, first.Token);
|
||||
Assert.Equal(HttpStatusCode.OK, own.StatusCode);
|
||||
using var other = await Send(HttpMethod.Get, "/api/" + path + query, second.Token);
|
||||
Assert.Equal(HttpStatusCode.NotFound, other.StatusCode);
|
||||
Assert.Empty(await other.Content.ReadAsStringAsync());
|
||||
}
|
||||
foreach (var (method, path, body) in new[]
|
||||
{
|
||||
(HttpMethod.Put, $"patients/{first.PatientId}", ProfileRequest),
|
||||
(HttpMethod.Post, $"patients/{first.PatientId}/observations", ObservationRequest),
|
||||
(HttpMethod.Put, $"observations/{observation.ObservationId}", ObservationRequest),
|
||||
(HttpMethod.Delete, $"observations/{observation.ObservationId}", (object?)null)
|
||||
})
|
||||
{
|
||||
using var response = await Send(method, "/api/" + path, second.Token, body);
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
}
|
||||
using var retained = await Send(HttpMethod.Get, $"/api/observations/{observation.ObservationId}", first.Token);
|
||||
Assert.Equal(128, (await retained.Content.ReadFromJsonAsync<Observation>())!.Systolic);
|
||||
await using var db = fixture.CreateObservationDbContext();
|
||||
Assert.Single(await db.Observations.Where(o => o.PatientId == first.PatientId).ToListAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Caller_supplied_account_identity_cannot_replace_authenticated_identity()
|
||||
{
|
||||
var account = "test-" + Interlocked.Increment(ref nextAccount);
|
||||
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account);
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, "/api/patients") { Content = JsonContent.Create(ProfileRequest) };
|
||||
request.Headers.Authorization = new("Bearer", token);
|
||||
request.Headers.Add("X-Account-Id", "test-0");
|
||||
using var response = await fixture.RawClient.SendAsync(request);
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
await using var db = fixture.CreateDbContext();
|
||||
var id = (await response.Content.ReadFromJsonAsync<Profile>())!.PatientId;
|
||||
Assert.Equal(account, (await db.Patients.SingleAsync(p => p.PatientId == id)).AccountId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Profile_creation_retries_and_concurrency_preserve_one_persistent_association()
|
||||
{
|
||||
var account = "test-" + Interlocked.Increment(ref nextAccount);
|
||||
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account);
|
||||
var responses = await Task.WhenAll(Send(HttpMethod.Post, "/api/patients", token, ProfileRequest), Send(HttpMethod.Post, "/api/patients", token, ProfileRequest));
|
||||
try
|
||||
{
|
||||
Assert.Single(responses, r => r.StatusCode == HttpStatusCode.Created);
|
||||
Assert.Single(responses, r => r.StatusCode == HttpStatusCode.Conflict);
|
||||
var profile = (await responses.Single(r => r.StatusCode == HttpStatusCode.Created).Content.ReadFromJsonAsync<Profile>())!;
|
||||
using var retry = await Send(HttpMethod.Post, "/api/patients", token, ProfileRequest);
|
||||
Assert.Equal(HttpStatusCode.Conflict, retry.StatusCode);
|
||||
await fixture.RestartHostsAsync();
|
||||
using var read = await Send(HttpMethod.Get, "/api/patients/me", token);
|
||||
Assert.Equal(HttpStatusCode.OK, read.StatusCode);
|
||||
Assert.Equal(profile.PatientId, (await read.Content.ReadFromJsonAsync<Profile>())!.PatientId);
|
||||
await using var db = fixture.CreateDbContext();
|
||||
Assert.Single(await db.Patients.Where(p => p.AccountId == account).ToListAsync());
|
||||
}
|
||||
finally { foreach (var response in responses) response.Dispose(); }
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Failed_creation_can_be_retried_without_an_orphan_profile()
|
||||
{
|
||||
var account = "test-" + Interlocked.Increment(ref nextAccount);
|
||||
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account);
|
||||
await fixture.StopPatientServiceAsync();
|
||||
using var failed = await Send(HttpMethod.Post, "/api/patients", token, ProfileRequest);
|
||||
Assert.Equal(HttpStatusCode.ServiceUnavailable, failed.StatusCode);
|
||||
await fixture.RestartHostsAsync();
|
||||
using var retry = await Send(HttpMethod.Post, "/api/patients", token, ProfileRequest);
|
||||
Assert.Equal(HttpStatusCode.Created, retry.StatusCode);
|
||||
await using var db = fixture.CreateDbContext();
|
||||
Assert.Single(await db.Patients.Where(p => p.AccountId == account).ToListAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Expired_token_is_rejected_and_login_produces_a_fresh_token()
|
||||
{
|
||||
var patient = await Patient();
|
||||
fixture.Authentication.Clock.Advance(TimeSpan.FromMinutes(31));
|
||||
try
|
||||
{
|
||||
using var expired = await Send(HttpMethod.Get, $"/api/patients/{patient.PatientId}", patient.Token);
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, expired.StatusCode);
|
||||
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, patient.Account);
|
||||
using var renewed = await Send(HttpMethod.Get, $"/api/patients/{patient.PatientId}", token);
|
||||
Assert.Equal(HttpStatusCode.OK, renewed.StatusCode);
|
||||
}
|
||||
finally { fixture.Authentication.Clock.Advance(TimeSpan.FromMinutes(-31)); }
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Tampering_with_a_valid_token_is_rejected()
|
||||
{
|
||||
var patient = await Patient();
|
||||
var token = patient.Token.ToCharArray();
|
||||
var position = token.Length / 2;
|
||||
token[position] = token[position] == 'A' ? 'B' : 'A';
|
||||
using var response = await Send(HttpMethod.Get, $"/api/patients/{patient.PatientId}", new string(token));
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Database_failure_rolls_back_profile_and_association_together()
|
||||
{
|
||||
var account = "test-" + Interlocked.Increment(ref nextAccount);
|
||||
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account);
|
||||
await using var db = fixture.CreateDbContext();
|
||||
await db.Database.ExecuteSqlRawAsync("""
|
||||
CREATE FUNCTION fail_profile_test() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF NEW.name = 'simulate-write-failure' THEN RAISE EXCEPTION 'test write failure'; END IF;
|
||||
RETURN NEW;
|
||||
END; $$;
|
||||
CREATE TRIGGER fail_profile_test BEFORE INSERT ON patient FOR EACH ROW EXECUTE FUNCTION fail_profile_test();
|
||||
""");
|
||||
try
|
||||
{
|
||||
using var failed = await Send(HttpMethod.Post, "/api/patients", token,
|
||||
new { name = "simulate-write-failure", dateOfBirth = "1980-01-01" });
|
||||
Assert.Equal(HttpStatusCode.InternalServerError, failed.StatusCode);
|
||||
Assert.Empty(await db.Patients.Where(p => p.AccountId == account).ToListAsync());
|
||||
using var retry = await Send(HttpMethod.Post, "/api/patients", token, ProfileRequest);
|
||||
Assert.Equal(HttpStatusCode.Created, retry.StatusCode);
|
||||
Assert.Single(await db.Patients.Where(p => p.AccountId == account).ToListAsync());
|
||||
}
|
||||
finally
|
||||
{
|
||||
await db.Database.ExecuteSqlRawAsync("DROP TRIGGER fail_profile_test ON patient; DROP FUNCTION fail_profile_test();");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Sole_public_edge_accepts_client_ticket_but_service_headers_grant_no_access()
|
||||
{
|
||||
var patient = await Patient();
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, $"/api/patients/{patient.PatientId}");
|
||||
request.Headers.Authorization=new("Bearer",patient.Token);request.Headers.Add("X-Gateway-Key","forged");
|
||||
using var own=await fixture.RawClient.SendAsync(request);Assert.Equal(HttpStatusCode.OK,own.StatusCode);
|
||||
using var bypass=new HttpRequestMessage(HttpMethod.Get,"/api/patients/by-account/"+patient.Account);
|
||||
bypass.Headers.Authorization=new("Bearer",patient.Token);
|
||||
using var absent=await fixture.RawClient.SendAsync(bypass);Assert.Equal(HttpStatusCode.NotFound,absent.StatusCode);
|
||||
foreach(var path in new[]{"/api/patients","/api/patients/by-account/test-0"})
|
||||
{
|
||||
using var forged=new HttpRequestMessage(path=="/api/patients"?HttpMethod.Post:HttpMethod.Get,path){Content=path=="/api/patients"?JsonContent.Create(ProfileRequest):null};
|
||||
forged.Headers.Add("X-Service-Key",fixture.Authentication.ObservationServiceKey);
|
||||
using var denied=await fixture.RawClient.SendAsync(forged);Assert.Equal(HttpStatusCode.Unauthorized,denied.StatusCode);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Healthcare_professional_cannot_create_profiles()
|
||||
{
|
||||
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional");
|
||||
using var response = await Send(HttpMethod.Post, "/api/patients", token, ProfileRequest);
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using HealthApp.TestSupport;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Xunit;
|
||||
|
||||
namespace Observation.AcceptanceTests;
|
||||
|
||||
public sealed class ProfessionalAccessTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
|
||||
{
|
||||
private const string AssignmentPath = "/api/professionals/me/patients";
|
||||
private sealed record Profile(Guid PatientId, string Name);
|
||||
private sealed record Observation(Guid ObservationId, Guid PatientId, int Systolic, string? Context, string? Note);
|
||||
private sealed record AssignedPatient(Guid PatientId);
|
||||
|
||||
private async Task<Guid> CreatePatient()
|
||||
{
|
||||
using var response = await fixture.Client.PostAsJsonAsync("/api/patients", new { name = "Assigned Patient", dateOfBirth = "1980-01-01" });
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
return (await response.Content.ReadFromJsonAsync<Profile>())!.PatientId;
|
||||
}
|
||||
|
||||
private async Task<Observation> Record(Guid patientId)
|
||||
{
|
||||
using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{patientId}/observations", new
|
||||
{
|
||||
measuredAt = "2026-09-12T08:00:00", systolic = 128, diastolic = 82, pulse = 68,
|
||||
context = "Resting", note = "Actual conditions"
|
||||
});
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
return (await response.Content.ReadFromJsonAsync<Observation>())!;
|
||||
}
|
||||
|
||||
private async Task Assign(Guid[] first, Guid[]? second = null)
|
||||
{
|
||||
fixture.AdditionalGatewayConfiguration.Clear();
|
||||
for (var i = 0; i < first.Length; i++)
|
||||
fixture.AdditionalGatewayConfiguration[$"Access:ProfessionalAssignments:professional:{i}"] = first[i].ToString();
|
||||
for (var i = 0; i < (second?.Length ?? 0); i++)
|
||||
fixture.AdditionalGatewayConfiguration[$"Access:ProfessionalAssignments:professional-second:{i}"] = second![i].ToString();
|
||||
await fixture.RestartHostsAsync();
|
||||
}
|
||||
|
||||
private async Task<HttpResponseMessage> Send(HttpMethod method, string path, string? token, object? body = null)
|
||||
{
|
||||
using var request = new HttpRequestMessage(method, path);
|
||||
if (token is not null) request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
||||
if (body is not null) request.Content = JsonContent.Create(body);
|
||||
return await fixture.RawClient.SendAsync(request);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Login_recognizes_professional_identity_and_does_not_put_assignments_in_the_token_response()
|
||||
{
|
||||
using var response = await fixture.RawClient.PostAsJsonAsync("/api/authentication/login",
|
||||
new { accountId = "professional", password = AuthenticatedTestClient.Password, role = "Patient" });
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
|
||||
Assert.Equal("HealthcareProfessional", json.RootElement.GetProperty("role").GetString());
|
||||
Assert.Equal("professional", json.RootElement.GetProperty("accountId").GetString());
|
||||
Assert.False(json.RootElement.TryGetProperty("patientId", out _));
|
||||
Assert.False(json.RootElement.TryGetProperty("assignments", out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Professionals_list_only_their_own_assignments_and_can_share_patients()
|
||||
{
|
||||
var first = await CreatePatient();
|
||||
var shared = await CreatePatient();
|
||||
var second = await CreatePatient();
|
||||
var excluded = await CreatePatient();
|
||||
await Assign([first, shared, first], [shared, second]);
|
||||
foreach (var (account, expected) in new[]
|
||||
{
|
||||
("professional", new[] { first, shared }),
|
||||
("professional-second", new[] { shared, second }),
|
||||
("professional-empty", Array.Empty<Guid>())
|
||||
})
|
||||
{
|
||||
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account);
|
||||
using var response = await Send(HttpMethod.Get, AssignmentPath + "?accountId=professional-second", token);
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
var patients = (await response.Content.ReadFromJsonAsync<AssignedPatient[]>())!;
|
||||
Assert.Equal(expected.Order(), patients.Select(p => p.PatientId).Order());
|
||||
Assert.DoesNotContain(patients, p => p.PatientId == excluded);
|
||||
}
|
||||
var sharedToken = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional-second");
|
||||
using var read = await Send(HttpMethod.Get, $"/api/patients/{shared}", sharedToken);
|
||||
Assert.Equal(HttpStatusCode.OK, read.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Assigned_profiles_observations_context_history_latest_and_insights_are_readable()
|
||||
{
|
||||
var patient = await CreatePatient();
|
||||
var observation = await Record(patient);
|
||||
await Assign([patient]);
|
||||
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional");
|
||||
foreach (var path in new[]
|
||||
{
|
||||
$"/api/patients/{patient}", $"/api/observations/{observation.ObservationId}",
|
||||
$"/api/patients/{patient}/observations/latest", $"/api/patients/{patient}/observations?from=2026-09-01&to=2026-10-01",
|
||||
$"/api/patients/{patient}/insights?from=2026-09-01&to=2026-10-01"
|
||||
})
|
||||
{
|
||||
using var response = await Send(HttpMethod.Get, path, token);
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using var own = await fixture.Client.GetAsync(path);
|
||||
Assert.Equal(await own.Content.ReadAsStringAsync(), await response.Content.ReadAsStringAsync());
|
||||
}
|
||||
using var specific = await Send(HttpMethod.Get, $"/api/observations/{observation.ObservationId}", token);
|
||||
Assert.Equal(observation, await specific.Content.ReadFromJsonAsync<Observation>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Unassigned_patients_and_observations_are_rejected_even_with_a_supplied_assigned_patient_id()
|
||||
{
|
||||
var assigned = await CreatePatient();
|
||||
var unassigned = await CreatePatient();
|
||||
var observation = await Record(unassigned);
|
||||
await Assign([assigned]);
|
||||
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional");
|
||||
foreach (var path in new[]
|
||||
{
|
||||
$"/api/patients/{unassigned}", $"/api/observations/{observation.ObservationId}?patientId={assigned}",
|
||||
$"/api/patients/{unassigned}/observations/latest", $"/api/patients/{unassigned}/observations?from=2026-09-01&to=2026-10-01",
|
||||
$"/api/patients/{unassigned}/insights?from=2026-09-01&to=2026-10-01"
|
||||
})
|
||||
{
|
||||
using var response = await Send(HttpMethod.Get, path, token);
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
Assert.Empty(await response.Content.ReadAsStringAsync());
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Missing_information_for_assigned_patients_follows_existing_retrieval_behaviour()
|
||||
{
|
||||
var patient = await CreatePatient();
|
||||
var missingPatient = Guid.NewGuid();
|
||||
await Assign([patient, missingPatient]);
|
||||
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional");
|
||||
foreach (var path in new[]
|
||||
{
|
||||
$"/api/patients/{missingPatient}", $"/api/observations/{Guid.NewGuid()}",
|
||||
$"/api/patients/{patient}/observations/latest", $"/api/patients/{patient}/insights?from=2026-09-01&to=2026-10-01"
|
||||
})
|
||||
{
|
||||
using var response = await Send(HttpMethod.Get, path, token);
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
}
|
||||
using var history = await Send(HttpMethod.Get, $"/api/patients/{patient}/observations?from=2026-09-01&to=2026-10-01", token);
|
||||
Assert.Equal(HttpStatusCode.OK, history.StatusCode);
|
||||
Assert.Equal("[]", await history.Content.ReadAsStringAsync());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("professional")]
|
||||
[InlineData("professional-empty")]
|
||||
public async Task Professionals_cannot_create_update_or_delete_any_patient_information(string account)
|
||||
{
|
||||
var patient = await CreatePatient();
|
||||
var observation = await Record(patient);
|
||||
await Assign([patient]);
|
||||
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account);
|
||||
await using var patients = fixture.CreateDbContext();
|
||||
await using var observations = fixture.CreateObservationDbContext();
|
||||
var before = await patients.Patients.AsNoTracking().SingleAsync(p => p.PatientId == patient);
|
||||
var count = await patients.Patients.CountAsync();
|
||||
foreach (var (method, path, body) in new[]
|
||||
{
|
||||
(HttpMethod.Post, "/api/patients", (object?)new { name = "Forbidden", dateOfBirth = "1980-01-01" }),
|
||||
(HttpMethod.Put, $"/api/patients/{patient}", (object?)new { name = "Forbidden" }),
|
||||
(HttpMethod.Post, $"/api/patients/{patient}/observations", (object?)new { measuredAt = "2026-09-12T08:00:00", systolic = 190, diastolic = 90, pulse = 80 }),
|
||||
(HttpMethod.Put, $"/api/observations/{observation.ObservationId}", (object?)new { systolic = 190, diastolic = 90, pulse = 80 }),
|
||||
(HttpMethod.Delete, $"/api/observations/{observation.ObservationId}", (object?)null)
|
||||
})
|
||||
{
|
||||
using var response = await Send(method, path, token, body);
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
Assert.Empty(await response.Content.ReadAsStringAsync());
|
||||
}
|
||||
Assert.Equal(count, await patients.Patients.CountAsync());
|
||||
var after = await patients.Patients.AsNoTracking().SingleAsync(p => p.PatientId == patient);
|
||||
Assert.Equal(before.Name, after.Name);
|
||||
Assert.Equal(before.UpdatedAt, after.UpdatedAt);
|
||||
var saved = await observations.Observations.AsNoTracking().SingleAsync(o => o.ObservationId == observation.ObservationId);
|
||||
Assert.Equal(128, saved.Systolic);
|
||||
Assert.Equal("Resting", saved.Context);
|
||||
Assert.Equal("Actual conditions", saved.Note);
|
||||
Assert.Single(await observations.Observations.Where(o => o.PatientId == patient).ToListAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Missing_invalid_and_expired_tokens_do_not_disclose_assignments_or_patient_data()
|
||||
{
|
||||
var patient = await CreatePatient();
|
||||
await Assign([patient]);
|
||||
foreach (var token in new string?[] { null, "invalid" })
|
||||
{
|
||||
using var list = await Send(HttpMethod.Get, AssignmentPath, token);
|
||||
using var read = await Send(HttpMethod.Get, $"/api/patients/{patient}", token);
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, list.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, read.StatusCode);
|
||||
Assert.Empty(await list.Content.ReadAsStringAsync());
|
||||
Assert.Empty(await read.Content.ReadAsStringAsync());
|
||||
}
|
||||
var valid = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional");
|
||||
fixture.Authentication.Clock.Advance(TimeSpan.FromMinutes(31));
|
||||
try
|
||||
{
|
||||
using var expired = await Send(HttpMethod.Get, AssignmentPath, valid);
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, expired.StatusCode);
|
||||
}
|
||||
finally { fixture.Authentication.Clock.Advance(TimeSpan.FromMinutes(-31)); }
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Incorrect_professional_secret_and_unknown_account_have_identical_login_rejections()
|
||||
{
|
||||
using var incorrect = await fixture.RawClient.PostAsJsonAsync("/api/authentication/login", new { accountId = "professional", password = "wrong" });
|
||||
using var unknown = await fixture.RawClient.PostAsJsonAsync("/api/authentication/login", new { accountId = "unknown-professional", password = AuthenticatedTestClient.Password });
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, incorrect.StatusCode);
|
||||
Assert.Equal(incorrect.StatusCode, unknown.StatusCode);
|
||||
Assert.Equal(await incorrect.Content.ReadAsStringAsync(), await unknown.Content.ReadAsStringAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Patient_cannot_list_professional_assignments_and_retains_own_access()
|
||||
{
|
||||
var patient = await CreatePatient();
|
||||
await Assign([patient]);
|
||||
var account = fixture.Authentication.PatientAccounts[patient];
|
||||
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account);
|
||||
using var rejected = await Send(HttpMethod.Get, AssignmentPath, token);
|
||||
Assert.Equal(HttpStatusCode.Forbidden, rejected.StatusCode);
|
||||
using var own = await Send(HttpMethod.Get, $"/api/patients/{patient}", token);
|
||||
Assert.Equal(HttpStatusCode.OK, own.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Assignment_removal_is_used_after_restart_even_with_an_existing_token()
|
||||
{
|
||||
var patient = await CreatePatient();
|
||||
await Assign([patient]);
|
||||
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional");
|
||||
using var allowed = await Send(HttpMethod.Get, $"/api/patients/{patient}", token);
|
||||
Assert.Equal(HttpStatusCode.OK, allowed.StatusCode);
|
||||
await Assign([]);
|
||||
using var rejected = await Send(HttpMethod.Get, $"/api/patients/{patient}", token);
|
||||
Assert.Equal(HttpStatusCode.NotFound, rejected.StatusCode);
|
||||
using var list = await Send(HttpMethod.Get, AssignmentPath, token);
|
||||
Assert.Equal("[]", await list.Content.ReadAsStringAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Observation_ownership_lookup_failure_fails_closed_while_assignment_list_remains_available()
|
||||
{
|
||||
var patient = await CreatePatient();
|
||||
var observation = await Record(patient);
|
||||
await Assign([patient]);
|
||||
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional");
|
||||
await fixture.StopObservationServiceAsync();
|
||||
try
|
||||
{
|
||||
using var read = await Send(HttpMethod.Get, $"/api/observations/{observation.ObservationId}", token);
|
||||
Assert.Equal(HttpStatusCode.ServiceUnavailable, read.StatusCode);
|
||||
using var list = await Send(HttpMethod.Get, AssignmentPath, token);
|
||||
Assert.Equal(HttpStatusCode.OK, list.StatusCode);
|
||||
}
|
||||
finally { await fixture.RestartHostsAsync(); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
using System.Net.Http.Json;
|
||||
using HealthApp.Contracts;
|
||||
using HealthApp.Infrastructure;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Npgsql;
|
||||
using Observation.AcceptanceTests;
|
||||
using Xunit;
|
||||
namespace HealthApp.AcceptanceTests;
|
||||
public sealed class SnapshotTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
|
||||
{
|
||||
[Fact]
|
||||
public async Task Overview_is_coherent_and_next_snapshot_sees_commits()
|
||||
{
|
||||
using var create=await fixture.Client.PostAsJsonAsync("/api/patients",new{name="Before",dateOfBirth="1980-01-01"});var p=(await create.Content.ReadFromJsonAsync<PatientDto>())!;
|
||||
using var record=await fixture.Client.PostAsJsonAsync($"/api/patients/{p.PatientId}/observations",new{measuredAt="2026-09-12T08:00:00",systolic=120,diastolic=80,pulse=60});var o=(await record.Content.ReadFromJsonAsync<ObservationDto>())!;
|
||||
var captured=new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);var resume=new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var armed=1;var selectedCount=0;var releasedBeforeReturn=false;
|
||||
fixture.ConfigureServices=services=>{
|
||||
var pd=services.Last(d=>d.ServiceType==typeof(ProfileQueries));services.Remove(pd);
|
||||
services.AddScoped<ProfileQueries>(sp=>new PausingProfile((ProfileQueries)pd.ImplementationFactory!(sp),async()=>{if(Interlocked.Exchange(ref armed,0)==1){captured.SetResult();await resume.Task;}}));
|
||||
var od=services.Last(d=>d.ServiceType==typeof(ObservationQueries));services.Remove(od);
|
||||
services.AddScoped<ObservationQueries>(sp=>new CountingObservations((ObservationQueries)od.ImplementationFactory!(sp),()=>Interlocked.Increment(ref selectedCount)));
|
||||
var ad=services.Last(d=>d.ServiceType==typeof(AnalyticsQueries));services.Remove(ad);
|
||||
services.AddScoped<AnalyticsQueries>(sp=>new CheckingAnalytics((AnalyticsQueries)ActivatorUtilities.CreateInstance(sp,ad.ImplementationType!),()=>releasedBeforeReturn=!sp.GetRequiredService<RequestTransaction>().Active));
|
||||
};
|
||||
await fixture.RestartHostsAsync();
|
||||
try
|
||||
{
|
||||
var path=$"/api/patients/{p.PatientId}/overview?from=2026-09-01&to=2026-09-30";
|
||||
var reading=fixture.Client.GetFromJsonAsync<HealthOverviewDto>(path);
|
||||
await captured.Task.WaitAsync(TimeSpan.FromSeconds(10));
|
||||
await using(var c=new NpgsqlConnection(fixture.ConnectionString))
|
||||
{await c.OpenAsync();await using var t=await c.BeginTransactionAsync();var cmd=new NpgsqlCommand("UPDATE profile.patient SET name='After' WHERE patient_id=@p; UPDATE observations.observation SET systolic=180 WHERE observation_id=@o",c,t);cmd.Parameters.AddWithValue("p",p.PatientId);cmd.Parameters.AddWithValue("o",o.ObservationId);await cmd.ExecuteNonQueryAsync();await t.CommitAsync();}
|
||||
resume.SetResult();var first=(await reading)!;
|
||||
Assert.Equal("Before",first.Patient.Name);Assert.Equal(120,first.LatestObservation!.Systolic);Assert.Equal(120m,first.Insight!.AverageSystolic);Assert.Equal(1,selectedCount);Assert.True(releasedBeforeReturn);
|
||||
var next=(await fixture.Client.GetFromJsonAsync<HealthOverviewDto>(path))!;Assert.Equal("After",next.Patient.Name);Assert.Equal(180,next.LatestObservation!.Systolic);Assert.Equal(180m,next.Insight!.AverageSystolic);
|
||||
}
|
||||
finally{resume.TrySetResult();fixture.ConfigureServices=null;await fixture.RestartHostsAsync();}
|
||||
}
|
||||
private sealed class PausingProfile(ProfileQueries inner,Func<Task> pause) : ProfileQueries
|
||||
{
|
||||
public Task<Guid?> ResolveAccountAsync(string a,CancellationToken ct)=>inner.ResolveAccountAsync(a,ct);
|
||||
public async Task<PatientDto?> GetAsync(AuthorizedPatientContext s,CancellationToken ct){var p=await inner.GetAsync(s,ct);await pause();return p;}
|
||||
}
|
||||
private sealed class CountingObservations(ObservationQueries inner,Action count) : ObservationQueries
|
||||
{
|
||||
public Task<Guid?> ResolveOwnerAsync(Guid id,CancellationToken ct)=>inner.ResolveOwnerAsync(id,ct);
|
||||
public Task<ObservationDto?> GetAsync(AuthorizedPatientContext s,Guid id,CancellationToken ct)=>inner.GetAsync(s,id,ct);
|
||||
public Task<ObservationDto?> LatestAsync(AuthorizedPatientContext s,CancellationToken ct)=>inner.LatestAsync(s,ct);
|
||||
public Task<IReadOnlyList<ObservationDto>> SelectedAsync(AuthorizedPatientContext s,DateTime f,DateTime t,ContextSelection c,CancellationToken ct){count();return inner.SelectedAsync(s,f,t,c,ct);}
|
||||
}
|
||||
private sealed class CheckingAnalytics(AnalyticsQueries inner,Action check) : AnalyticsQueries
|
||||
{
|
||||
public async Task<HealthInsight?> InsightAsync(AuthorizedPatientContext s,DateTime f,DateTime t,ContextSelection c,CancellationToken ct){var v=await inner.InsightAsync(s,f,t,c,ct);check();return v;}
|
||||
public Task<TrendAssessment> TrendAsync(AuthorizedPatientContext s,DateTime f,DateTime t,ContextSelection c,CancellationToken ct)=>inner.TrendAsync(s,f,t,c,ct);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user