Implement owner-scoped Observation lifecycle with serialized patches
This commit is contained in:
1 parent
bfe6ebf5af
commit
3a70e3e296
37 files changed
+31249
-9
No files matched your search
+1
-1
@@ -1 +1 @@
|
||||
<Solution><Folder Name="/src/"><Project Path="src/HealthApp.Infrastructure/HealthApp.Infrastructure.csproj"/><Project Path="src/Modules/Profile/Profile.csproj"/><Project Path="src/HealthApp/HealthApp.csproj" /><Project Path="src/HealthApp.Contracts/HealthApp.Contracts.csproj" /><Project Path="src/Modules/Guidance/Guidance.csproj" /></Folder><Folder Name="/tests/"><Project Path="tests/HealthApp.AcceptanceTests/HealthApp.AcceptanceTests.csproj" /></Folder></Solution>
|
||||
<Solution><Folder Name="/src/"><Project Path="src/Modules/Observations/Observations.csproj"/><Project Path="src/HealthApp.Infrastructure/HealthApp.Infrastructure.csproj"/><Project Path="src/Modules/Profile/Profile.csproj"/><Project Path="src/HealthApp/HealthApp.csproj" /><Project Path="src/HealthApp.Contracts/HealthApp.Contracts.csproj" /><Project Path="src/Modules/Guidance/Guidance.csproj" /></Folder><Folder Name="/tests/"><Project Path="tests/HealthApp.AcceptanceTests/HealthApp.AcceptanceTests.csproj" /></Folder></Solution>
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -31,3 +31,7 @@ Single ASP.NET host, Contracts and Guidance projects; framework login/accounts/a
|
||||
### Stage 2 — Profile checkpoint
|
||||
|
||||
Profile facade/owned schema/immutable DTOs; account unique/non-null, durable atomic insert and locked updates. Shared request transaction uses repeatable-read for reads and read-committed for locked writes. Runtime DB role restricted to DML, no runtime migration. Module-owned versioned SQL migration (applied twice) implements schema lifecycle; EF Core retains data access. Original create/update tests copied with namespace adaptation only; relative Location regression fixed in production controller, not assertions. Added concurrent create/retry/restart/persistent-ticket and runtime DDL-denial tests. 29/29 cases passed. Remaining all-endpoint authorization and Observation schema checks proceed with Stage 3. Stage 1 commit `523cfbf`.
|
||||
|
||||
### Stage 3 checkpoint — passed
|
||||
|
||||
Observation module owns its private EF context/entities and versioned schema SQL; patient FK restricted, positive/category/rest checks, patient/time/original/UUID index. Typed Profile existence query inside write transaction. API resolves actual observation owner, authorizes, and uses owner-scoped read/locked patch/delete. Original patch application retained; omitted/clear semantics unchanged. Original US-04–09 suites run with one HTTP host/one DB and namespaces updated. Q1 lookup failure test uses DB outage and 503 instead of service stop/502; no-write assertion unchanged. Empty-404 regression fixed in production adapters. 138/138 tests passed including controlled two-patch row-lock barrier and orphan FK rejection; zero build warnings/errors. Private types exposed only to test assembly via InternalsVisibleTo. Stage 2 commit `bfe6ebf`.
|
||||
@@ -0,0 +1,12 @@
|
||||
# Architecture-dependent test adaptations
|
||||
|
||||
Authority: approval Q1. Unmodified originals remain under Reference/ArchitectureA. Functional assertions stay intact except explicitly approved architecture-dependent conditions below.
|
||||
|
||||
| Original scenario / infrastructure | B replacement / reason |
|
||||
| --- | --- |
|
||||
| PatientApiFixture / ObservationApiFixture: multiple hosts/two databases | One real Kestrel host and one isolated database, module-owned schemas. Test-admin contexts remain available solely to establish Given and inspect persistence. Runtime uses restricted DML role |
|
||||
| All adopted suites: service namespaces | Module/shared immutable value namespaces; JSON expectation vocabulary preserved |
|
||||
| RecordObservationTests.Failed_patient_lookup_is_rejected_without_saving | StopPatientService helper now configures unusable shared DB endpoint; 502 assertion becomes approved 503; persisted count assertion unchanged |
|
||||
| Guidance tests: ApiGateway host | HealthApp host; all original instructions/source/applicability/side-effect assertions and upstream traps unchanged |
|
||||
| ViewObservationContextTests / filtered access | Empty denied 404 preserved, corrected implementation after tests caught accidental Problem Details |
|
||||
| New concurrency checks | Hold row lock, prove both patches wait, release, verify both disjoint changes and unchanged owner/time/note; new architecture obligation |
|
||||
@@ -0,0 +1,12 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace HealthApp.Contracts;
|
||||
|
||||
public sealed record ContextSelection
|
||||
{
|
||||
[AllowedValues("Home", "Clinic", "Other", "Unknown", null)]
|
||||
public string? Setting { get; init; }
|
||||
|
||||
[AllowedValues("AtRest", "DuringActivity", "AfterActivity", "Unknown", null)]
|
||||
public string? ActivityCondition { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace HealthApp.Contracts;
|
||||
|
||||
public sealed record MeasurementContext
|
||||
{
|
||||
[AllowedValues("Home", "Clinic", "Other", "Unknown", null)]
|
||||
public string? Setting { get; init; } = "Unknown";
|
||||
|
||||
[AllowedValues("AtRest", "DuringActivity", "AfterActivity", "Unknown", null)]
|
||||
public string? ActivityCondition { get; init; } = "Unknown";
|
||||
|
||||
[Range(0, double.MaxValue)]
|
||||
public decimal? RestDurationMinutes { get; init; }
|
||||
|
||||
public string? BodyPosition { get; init; }
|
||||
public string? MeasuredArm { get; init; }
|
||||
public string? DeviceDetails { get; init; }
|
||||
public string? CuffDetails { get; init; }
|
||||
public string? AdditionalCircumstances { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace HealthApp.Contracts;
|
||||
|
||||
[JsonUnmappedMemberHandling(JsonUnmappedMemberHandling.Disallow)]
|
||||
public sealed record MeasurementContextPatch
|
||||
{
|
||||
private string? setting;
|
||||
[AllowedValues("Home", "Clinic", "Other", "Unknown", null)]
|
||||
public string? Setting
|
||||
{
|
||||
get => setting;
|
||||
init { setting = value; SettingSpecified = true; }
|
||||
}
|
||||
[JsonIgnore]
|
||||
public bool SettingSpecified { get; private set; }
|
||||
|
||||
private string? activityCondition;
|
||||
[AllowedValues("AtRest", "DuringActivity", "AfterActivity", "Unknown", null)]
|
||||
public string? ActivityCondition
|
||||
{
|
||||
get => activityCondition;
|
||||
init { activityCondition = value; ActivityConditionSpecified = true; }
|
||||
}
|
||||
[JsonIgnore]
|
||||
public bool ActivityConditionSpecified { get; private set; }
|
||||
|
||||
private decimal? restDurationMinutes;
|
||||
[Range(0, double.MaxValue)]
|
||||
public decimal? RestDurationMinutes
|
||||
{
|
||||
get => restDurationMinutes;
|
||||
init { restDurationMinutes = value; RestDurationMinutesSpecified = true; }
|
||||
}
|
||||
[JsonIgnore]
|
||||
public bool RestDurationMinutesSpecified { get; private set; }
|
||||
|
||||
private string? bodyPosition;
|
||||
public string? BodyPosition
|
||||
{
|
||||
get => bodyPosition;
|
||||
init { bodyPosition = value; BodyPositionSpecified = true; }
|
||||
}
|
||||
[JsonIgnore]
|
||||
public bool BodyPositionSpecified { get; private set; }
|
||||
|
||||
private string? measuredArm;
|
||||
public string? MeasuredArm
|
||||
{
|
||||
get => measuredArm;
|
||||
init { measuredArm = value; MeasuredArmSpecified = true; }
|
||||
}
|
||||
[JsonIgnore]
|
||||
public bool MeasuredArmSpecified { get; private set; }
|
||||
|
||||
private string? deviceDetails;
|
||||
public string? DeviceDetails
|
||||
{
|
||||
get => deviceDetails;
|
||||
init { deviceDetails = value; DeviceDetailsSpecified = true; }
|
||||
}
|
||||
[JsonIgnore]
|
||||
public bool DeviceDetailsSpecified { get; private set; }
|
||||
|
||||
private string? cuffDetails;
|
||||
public string? CuffDetails
|
||||
{
|
||||
get => cuffDetails;
|
||||
init { cuffDetails = value; CuffDetailsSpecified = true; }
|
||||
}
|
||||
[JsonIgnore]
|
||||
public bool CuffDetailsSpecified { get; private set; }
|
||||
|
||||
private string? additionalCircumstances;
|
||||
public string? AdditionalCircumstances
|
||||
{
|
||||
get => additionalCircumstances;
|
||||
init { additionalCircumstances = value; AdditionalCircumstancesSpecified = true; }
|
||||
}
|
||||
[JsonIgnore]
|
||||
public bool AdditionalCircumstancesSpecified { get; private set; }
|
||||
|
||||
[JsonIgnore]
|
||||
public bool HasChanges => SettingSpecified || ActivityConditionSpecified || RestDurationMinutesSpecified ||
|
||||
BodyPositionSpecified || MeasuredArmSpecified || DeviceDetailsSpecified || CuffDetailsSpecified || AdditionalCircumstancesSpecified;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace HealthApp.Contracts;
|
||||
|
||||
public sealed record ObservationDto(Guid ObservationId, Guid PatientId, DateTime MeasuredAt,
|
||||
int Systolic, int Diastolic, int Pulse, MeasurementContextDto? MeasurementContext = null,
|
||||
string? Context = null, string? Note = null);
|
||||
|
||||
public sealed record MeasurementContextDto(string? Setting, string? ActivityCondition, decimal? RestDurationMinutes,
|
||||
string? BodyPosition, string? MeasuredArm, string? DeviceDetails, string? CuffDetails, string? AdditionalCircumstances);
|
||||
@@ -0,0 +1,19 @@
|
||||
namespace HealthApp.Contracts;
|
||||
public interface ObservationQueries
|
||||
{
|
||||
Task<Guid?> ResolveOwnerAsync(Guid observationId,CancellationToken ct);
|
||||
Task<ObservationDto?> GetAsync(AuthorizedPatientContext scope,Guid id,CancellationToken ct);
|
||||
Task<ObservationDto?> LatestAsync(AuthorizedPatientContext scope,CancellationToken ct);
|
||||
Task<IReadOnlyList<ObservationDto>> SelectedAsync(AuthorizedPatientContext scope,DateTime from,DateTime to,ContextSelection selection,CancellationToken ct);
|
||||
}
|
||||
public interface ObservationCommands
|
||||
{
|
||||
Task<ObservationDto?> RecordAsync(AuthorizedPatientContext scope,RecordObservationRequest request,CancellationToken ct);
|
||||
Task<ObservationDto?> PatchAsync(AuthorizedPatientContext scope,Guid id,PatchObservationRequest request,CancellationToken ct);
|
||||
Task<bool> DeleteAsync(AuthorizedPatientContext scope,Guid id,CancellationToken ct);
|
||||
}
|
||||
public static class MeasurementPeriod
|
||||
{
|
||||
public static DateTime Normalize(DateTime t)=>DateTime.SpecifyKind(t.Kind==DateTimeKind.Unspecified?t:t.ToUniversalTime(),DateTimeKind.Unspecified);
|
||||
public static void Validate(DateTime from,DateTime to){if(Normalize(to)<Normalize(from))throw new ArgumentException("The end time must not be earlier than the start time.");}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace HealthApp.Contracts;
|
||||
|
||||
[JsonUnmappedMemberHandling(JsonUnmappedMemberHandling.Disallow)]
|
||||
public sealed record PatchObservationRequest : IValidatableObject
|
||||
{
|
||||
private int? systolic;
|
||||
[Range(1, int.MaxValue)]
|
||||
public int? Systolic
|
||||
{
|
||||
get => systolic;
|
||||
init { systolic = value; SystolicSpecified = true; }
|
||||
}
|
||||
[JsonIgnore]
|
||||
public bool SystolicSpecified { get; private set; }
|
||||
|
||||
private int? diastolic;
|
||||
[Range(1, int.MaxValue)]
|
||||
public int? Diastolic
|
||||
{
|
||||
get => diastolic;
|
||||
init { diastolic = value; DiastolicSpecified = true; }
|
||||
}
|
||||
[JsonIgnore]
|
||||
public bool DiastolicSpecified { get; private set; }
|
||||
|
||||
private int? pulse;
|
||||
[Range(1, int.MaxValue)]
|
||||
public int? Pulse
|
||||
{
|
||||
get => pulse;
|
||||
init { pulse = value; PulseSpecified = true; }
|
||||
}
|
||||
[JsonIgnore]
|
||||
public bool PulseSpecified { get; private set; }
|
||||
|
||||
private MeasurementContextPatch? measurementContext;
|
||||
public MeasurementContextPatch? MeasurementContext
|
||||
{
|
||||
get => measurementContext;
|
||||
init { measurementContext = value; MeasurementContextSpecified = true; }
|
||||
}
|
||||
[JsonIgnore]
|
||||
public bool MeasurementContextSpecified { get; private set; }
|
||||
|
||||
private string? context;
|
||||
public string? Context
|
||||
{
|
||||
get => context;
|
||||
init { context = value; ContextSpecified = true; }
|
||||
}
|
||||
[JsonIgnore]
|
||||
public bool ContextSpecified { get; private set; }
|
||||
|
||||
private string? note;
|
||||
public string? Note
|
||||
{
|
||||
get => note;
|
||||
init { note = value; NoteSpecified = true; }
|
||||
}
|
||||
[JsonIgnore]
|
||||
public bool NoteSpecified { get; private set; }
|
||||
|
||||
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
|
||||
{
|
||||
if (SystolicSpecified && Systolic is null)
|
||||
yield return new ValidationResult("Systolic cannot be cleared.", [nameof(Systolic)]);
|
||||
if (DiastolicSpecified && Diastolic is null)
|
||||
yield return new ValidationResult("Diastolic cannot be cleared.", [nameof(Diastolic)]);
|
||||
if (PulseSpecified && Pulse is null)
|
||||
yield return new ValidationResult("Pulse cannot be cleared.", [nameof(Pulse)]);
|
||||
if (!SystolicSpecified && !DiastolicSpecified && !PulseSpecified && !ContextSpecified && !NoteSpecified &&
|
||||
!(MeasurementContextSpecified && (MeasurementContext is null || MeasurementContext.HasChanges)))
|
||||
yield return new ValidationResult("Supply at least one supported field to update.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace HealthApp.Contracts;
|
||||
|
||||
public sealed record RecordObservationRequest
|
||||
{
|
||||
[Required]
|
||||
public DateTime? MeasuredAt { get; init; }
|
||||
|
||||
[Required, Range(1, int.MaxValue)]
|
||||
public int? Systolic { get; init; }
|
||||
|
||||
[Required, Range(1, int.MaxValue)]
|
||||
public int? Diastolic { get; init; }
|
||||
|
||||
[Required, Range(1, int.MaxValue)]
|
||||
public int? Pulse { get; init; }
|
||||
|
||||
public MeasurementContext? MeasurementContext { get; init; }
|
||||
|
||||
public string? Context { get; init; }
|
||||
public string? Note { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
using System.Text.Json.Serialization;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace HealthApp.Contracts;
|
||||
|
||||
[JsonUnmappedMemberHandling(JsonUnmappedMemberHandling.Disallow)]
|
||||
public sealed record UpdateObservationRequest
|
||||
{
|
||||
[Required, Range(1, int.MaxValue)]
|
||||
public int? Systolic { get; init; }
|
||||
|
||||
[Required, Range(1, int.MaxValue)]
|
||||
public int? Diastolic { get; init; }
|
||||
|
||||
[Required, Range(1, int.MaxValue)]
|
||||
public int? Pulse { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
using HealthApp.Contracts;
|
||||
using HealthApp.Infrastructure;
|
||||
using HealthApp.Security;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.ModelBinding;
|
||||
namespace HealthApp.Controllers;
|
||||
[ApiController,Route("api")]
|
||||
public sealed class ObservationController(ObservationQueries queries,ObservationCommands commands,AccessPolicy access,RequestTransaction tx) : ControllerBase
|
||||
{
|
||||
private IActionResult Unavailable(){Response.StatusCode=404;return new EmptyResult();}
|
||||
|
||||
private async Task<AuthorizedPatientContext?> Owner(Guid id,bool write,CancellationToken ct){var owner=await queries.ResolveOwnerAsync(id,ct);return owner is null?null:await access.AuthorizeAsync(User,owner.Value,write,ct);}
|
||||
[HttpPost("patients/{patientId:guid}/observations"),Authorize(Policy="Patient")]
|
||||
public async Task<IActionResult> Record(Guid patientId,RecordObservationRequest r,CancellationToken ct){var scope=await access.AuthorizeAsync(User,patientId,true,ct);if(scope is null)return Unavailable();var o=await commands.RecordAsync(scope,r,ct);await tx.FinishAsync(ct);return o is null?NotFound():Created($"/api/observations/{o.ObservationId}",o);}
|
||||
[HttpGet("observations/{observationId:guid}")]
|
||||
public async Task<IActionResult> Get(Guid observationId,CancellationToken ct){var scope=await Owner(observationId,false,ct);if(scope is null)return Unavailable();var o=await queries.GetAsync(scope,observationId,ct);await tx.FinishAsync(ct);return o is null?NotFound():Ok(o);}
|
||||
[HttpPut("observations/{observationId:guid}"),Authorize(Policy="Patient")]
|
||||
public Task<IActionResult> Put(Guid observationId,UpdateObservationRequest r,CancellationToken ct)=>Patch(observationId,new PatchObservationRequest{Systolic=r.Systolic,Diastolic=r.Diastolic,Pulse=r.Pulse},ct);
|
||||
[HttpPatch("observations/{observationId:guid}"),Authorize(Policy="Patient")]
|
||||
public async Task<IActionResult> Patch(Guid observationId,PatchObservationRequest r,CancellationToken ct){var scope=await Owner(observationId,true,ct);if(scope is null)return Unavailable();var o=await commands.PatchAsync(scope,observationId,r,ct);await tx.FinishAsync(ct);return o is null?NotFound():Ok(o);}
|
||||
[HttpDelete("observations/{observationId:guid}"),Authorize(Policy="Patient")]
|
||||
public async Task<IActionResult> Delete(Guid observationId,CancellationToken ct){var scope=await Owner(observationId,true,ct);if(scope is null)return Unavailable();var found=await commands.DeleteAsync(scope,observationId,ct);await tx.FinishAsync(ct);return found?NoContent():NotFound();}
|
||||
[HttpGet("patients/{patientId:guid}/observations/latest")]
|
||||
public async Task<IActionResult> Latest(Guid patientId,CancellationToken ct){var scope=await access.AuthorizeAsync(User,patientId,false,ct);if(scope is null)return Unavailable();var o=await queries.LatestAsync(scope,ct);await tx.FinishAsync(ct);return o is null?NotFound():Ok(o);}
|
||||
[HttpGet("patients/{patientId:guid}/observations")]
|
||||
public async Task<IActionResult> History(Guid patientId,[FromQuery,BindRequired]DateTime from,[FromQuery,BindRequired]DateTime to,[FromQuery]ContextSelection selection,CancellationToken ct)
|
||||
{
|
||||
var scope=await access.AuthorizeAsync(User,patientId,false,ct);if(scope is null)return Unavailable();
|
||||
try{var series=await queries.SelectedAsync(scope,from,to,selection,ct);await tx.FinishAsync(ct);Response.Headers["X-Measurement-Setting"]=selection.Setting??"All";Response.Headers["X-Activity-Condition"]=selection.ActivityCondition??"All";return Ok(series);}
|
||||
catch(ArgumentException){ModelState.AddModelError(nameof(to),"The end time must not be earlier than the start time.");return ValidationProblem(ModelState);}
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,8 @@ namespace HealthApp.Controllers;
|
||||
[ApiController,Route("api/patients")]
|
||||
public sealed class PatientController(ProfileQueries queries,ProfileCommands commands,AccessPolicy access,RequestTransaction tx) : ControllerBase
|
||||
{
|
||||
private IActionResult Unavailable(){Response.StatusCode=404;return new EmptyResult();}
|
||||
|
||||
[HttpPost,Authorize(Policy="Patient")]
|
||||
public async Task<IActionResult> Create(CreatePatientRequest r,CancellationToken ct)
|
||||
{
|
||||
@@ -22,8 +24,8 @@ public sealed class PatientController(ProfileQueries queries,ProfileCommands com
|
||||
}
|
||||
[HttpGet("{patientId:guid}")]
|
||||
public async Task<IActionResult> Get(Guid patientId,CancellationToken ct)
|
||||
{var scope=await access.AuthorizeAsync(User,patientId,false,ct);if(scope is null)return NotFound();var p=await queries.GetAsync(scope,ct);await tx.FinishAsync(ct);return p is null?NotFound():Ok(p);}
|
||||
{var scope=await access.AuthorizeAsync(User,patientId,false,ct);if(scope is null)return Unavailable();var p=await queries.GetAsync(scope,ct);await tx.FinishAsync(ct);return p is null?NotFound():Ok(p);}
|
||||
[HttpPut("{patientId:guid}"),Authorize(Policy="Patient")]
|
||||
public async Task<IActionResult> Update(Guid patientId,UpdatePatientRequest r,CancellationToken ct)
|
||||
{var scope=await access.AuthorizeAsync(User,patientId,true,ct);if(scope is null)return NotFound();var p=await commands.UpdateAsync(scope,r,ct);await tx.FinishAsync(ct);return p is null?NotFound():Ok(p);}
|
||||
{var scope=await access.AuthorizeAsync(User,patientId,true,ct);if(scope is null)return Unavailable();var p=await commands.UpdateAsync(scope,r,ct);await tx.FinishAsync(ct);return p is null?NotFound():Ok(p);}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
<PropertyGroup><TargetFramework>net10.0</TargetFramework><Nullable>enable</Nullable><ImplicitUsings>enable</ImplicitUsings></PropertyGroup>
|
||||
<ItemGroup><ProjectReference Include="../HealthApp.Contracts/HealthApp.Contracts.csproj" /><ProjectReference Include="../Modules/Guidance/Guidance.csproj" /><ProjectReference Include="../HealthApp.Infrastructure/HealthApp.Infrastructure.csproj"/><ProjectReference Include="../Modules/Profile/Profile.csproj"/></ItemGroup>
|
||||
<ItemGroup><ProjectReference Include="../HealthApp.Contracts/HealthApp.Contracts.csproj" /><ProjectReference Include="../Modules/Guidance/Guidance.csproj" /><ProjectReference Include="../HealthApp.Infrastructure/HealthApp.Infrastructure.csproj"/><ProjectReference Include="../Modules/Profile/Profile.csproj"/><ProjectReference Include="../Modules/Observations/Observations.csproj"/></ItemGroup>
|
||||
</Project>
|
||||
@@ -1,6 +1,7 @@
|
||||
using HealthApp.Guidance;
|
||||
using HealthApp.Infrastructure;
|
||||
using HealthApp.Profile;
|
||||
using HealthApp.Observations;
|
||||
using Npgsql;
|
||||
using HealthApp.Security;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
@@ -24,7 +25,7 @@ public class Program
|
||||
var options=new NpgsqlConnectionStringBuilder(text){Pooling=true,MaxPoolSize=c.GetValue("Resources:MaxPoolSize",32)};
|
||||
return NpgsqlDataSource.Create(options.ConnectionString);
|
||||
});
|
||||
builder.Services.AddScoped<RequestTransaction>();builder.Services.AddProfile();builder.Services.AddScoped<AccessPolicy>();
|
||||
builder.Services.AddScoped<RequestTransaction>();builder.Services.AddProfile();builder.Services.AddObservations();builder.Services.AddScoped<AccessPolicy>();
|
||||
builder.Services.AddDataProtection().SetApplicationName("HealthApp.ApiGateway");
|
||||
builder.Services.AddOptions<Microsoft.AspNetCore.DataProtection.KeyManagement.KeyManagementOptions>().Configure<IConfiguration, ILoggerFactory>((o,c,l)=> {
|
||||
var keys=c["Authentication:KeyDirectory"];
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
[assembly:InternalsVisibleTo("HealthApp.AcceptanceTests")]
|
||||
@@ -0,0 +1,17 @@
|
||||
using HealthApp.Contracts;
|
||||
namespace HealthApp.Observations.Domain;
|
||||
|
||||
internal sealed class BloodPressureObservation
|
||||
{
|
||||
public Guid ObservationId { get; set; }
|
||||
public Guid PatientId { get; set; }
|
||||
public DateTime MeasuredAt { get; set; }
|
||||
public int Systolic { get; set; }
|
||||
public int Diastolic { get; set; }
|
||||
public int Pulse { get; set; }
|
||||
public MeasurementContext MeasurementContext { get; set; } = new();
|
||||
public string? Context { get; set; }
|
||||
public string? Note { get; set; }
|
||||
public DateTime CreatedAt { get; set; }
|
||||
public DateTime UpdatedAt { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
CREATE SCHEMA IF NOT EXISTS observations;
|
||||
CREATE TABLE IF NOT EXISTS observations.schema_version(version integer PRIMARY KEY);
|
||||
CREATE TABLE IF NOT EXISTS observations.observation(
|
||||
observation_id uuid PRIMARY KEY, patient_id uuid NOT NULL REFERENCES profile.patient(patient_id) ON DELETE RESTRICT,
|
||||
measured_at timestamp without time zone NOT NULL,systolic integer NOT NULL CHECK(systolic>0),diastolic integer NOT NULL CHECK(diastolic>0),pulse integer NOT NULL CHECK(pulse>0),
|
||||
context varchar,note varchar,setting text NOT NULL DEFAULT 'Unknown' CHECK(setting IN('Home','Clinic','Other','Unknown')),
|
||||
activity_condition text NOT NULL DEFAULT 'Unknown' CHECK(activity_condition IN('AtRest','DuringActivity','AfterActivity','Unknown')),
|
||||
rest_duration_minutes numeric CHECK(rest_duration_minutes>=0),body_position text,measured_arm text,device_details text,cuff_details text,additional_circumstances text,
|
||||
created_at timestamp without time zone NOT NULL,updated_at timestamp without time zone NOT NULL);
|
||||
CREATE INDEX IF NOT EXISTS ix_observation_patient_time ON observations.observation(patient_id,measured_at,created_at,observation_id);
|
||||
INSERT INTO observations.schema_version VALUES(1) ON CONFLICT DO NOTHING;
|
||||
@@ -0,0 +1,77 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using HealthApp.Contracts;
|
||||
using HealthApp.Infrastructure;
|
||||
using HealthApp.Observations.Domain;
|
||||
using HealthApp.Observations.Persistence;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
namespace HealthApp.Observations;
|
||||
internal sealed class ObservationFacade(ObservationDbContext db,RequestTransaction tx,ProfileQueries profiles) : ObservationQueries,ObservationCommands
|
||||
{
|
||||
public async Task<Guid?> ResolveOwnerAsync(Guid id,CancellationToken ct){await tx.EnlistAsync(db,ct);return await db.Observations.AsNoTracking().Where(o=>o.ObservationId==id).Select(o=>(Guid?)o.PatientId).SingleOrDefaultAsync(ct);}
|
||||
public async Task<ObservationDto?> GetAsync(AuthorizedPatientContext scope,Guid id,CancellationToken ct){await tx.EnlistAsync(db,ct);var o=await db.Observations.AsNoTracking().SingleOrDefaultAsync(o=>o.ObservationId==id&&o.PatientId==scope.PatientId,ct);return o is null?null:Dto(o);}
|
||||
public async Task<ObservationDto?> LatestAsync(AuthorizedPatientContext scope,CancellationToken ct){await tx.EnlistAsync(db,ct);var o=await db.Observations.AsNoTracking().Where(o=>o.PatientId==scope.PatientId).OrderByDescending(o=>o.MeasuredAt).ThenByDescending(o=>o.CreatedAt).ThenByDescending(o=>o.ObservationId).FirstOrDefaultAsync(ct);return o is null?null:Dto(o);}
|
||||
public async Task<IReadOnlyList<ObservationDto>> SelectedAsync(AuthorizedPatientContext scope,DateTime from,DateTime to,ContextSelection selection,CancellationToken ct)
|
||||
{
|
||||
from=MeasurementPeriod.Normalize(from);to=MeasurementPeriod.Normalize(to);MeasurementPeriod.Validate(from,to);Validator.ValidateObject(selection,new ValidationContext(selection),true);await tx.EnlistAsync(db,ct);
|
||||
var q=db.Observations.AsNoTracking().Where(o=>o.PatientId==scope.PatientId&&o.MeasuredAt>=from&&o.MeasuredAt<=to);
|
||||
if(selection.Setting is not null)q=q.Where(o=>o.MeasurementContext.Setting==selection.Setting);
|
||||
if(selection.ActivityCondition is not null)q=q.Where(o=>o.MeasurementContext.ActivityCondition==selection.ActivityCondition);
|
||||
return Array.AsReadOnly((await q.OrderBy(o=>o.MeasuredAt).ThenBy(o=>o.ObservationId).ToListAsync(ct)).Select(Dto).ToArray());
|
||||
}
|
||||
public async Task<ObservationDto?> RecordAsync(AuthorizedPatientContext scope,RecordObservationRequest request,CancellationToken ct)
|
||||
{
|
||||
scope.RequireWrite();Validator.ValidateObject(request,new ValidationContext(request),true);
|
||||
var context=request.MeasurementContext??new();context=context with{Setting=context.Setting??"Unknown",ActivityCondition=context.ActivityCondition??"Unknown"};Validator.ValidateObject(context,new ValidationContext(context),true);
|
||||
if(await profiles.GetAsync(scope,ct) is null)return null;await tx.EnlistAsync(db,ct);
|
||||
var now=DateTime.SpecifyKind(DateTime.UtcNow,DateTimeKind.Unspecified);
|
||||
var o=new BloodPressureObservation{ObservationId=Guid.NewGuid(),PatientId=scope.PatientId,MeasuredAt=MeasurementPeriod.Normalize(request.MeasuredAt!.Value),Systolic=request.Systolic!.Value,Diastolic=request.Diastolic!.Value,Pulse=request.Pulse!.Value,MeasurementContext=context,Context=request.Context,Note=request.Note,CreatedAt=now,UpdatedAt=now};db.Observations.Add(o);await db.SaveChangesAsync(ct);return Dto(o);
|
||||
}
|
||||
private async Task<BloodPressureObservation?> LockedAsync(AuthorizedPatientContext scope,Guid id,CancellationToken cancellationToken)
|
||||
{scope.RequireWrite();await tx.EnlistAsync(db,cancellationToken);return await db.Observations.FromSqlInterpolated($"SELECT * FROM observations.observation WHERE observation_id={id} AND patient_id={scope.PatientId} FOR UPDATE").SingleOrDefaultAsync(cancellationToken);}
|
||||
public async Task<ObservationDto?> PatchAsync(AuthorizedPatientContext scope,Guid id,PatchObservationRequest request,CancellationToken cancellationToken)
|
||||
{
|
||||
Validator.ValidateObject(request,new ValidationContext(request),true);if(request.MeasurementContext is not null)Validator.ValidateObject(request.MeasurementContext,new ValidationContext(request.MeasurementContext),true);
|
||||
var observation=await LockedAsync(scope,id,cancellationToken);if(observation is null)return null;
|
||||
var updatedAt=DateTime.SpecifyKind(DateTime.UtcNow,DateTimeKind.Unspecified);
|
||||
if (request.SystolicSpecified) observation.Systolic = request.Systolic!.Value;
|
||||
if (request.DiastolicSpecified) observation.Diastolic = request.Diastolic!.Value;
|
||||
if (request.PulseSpecified) observation.Pulse = request.Pulse!.Value;
|
||||
if (request.ContextSpecified) observation.Context = request.Context;
|
||||
if (request.NoteSpecified) observation.Note = request.Note;
|
||||
if (request.MeasurementContextSpecified)
|
||||
{
|
||||
if (request.MeasurementContext is null) observation.MeasurementContext = new();
|
||||
else
|
||||
{
|
||||
var patch = request.MeasurementContext;
|
||||
var current = observation.MeasurementContext;
|
||||
observation.MeasurementContext = current with
|
||||
{
|
||||
Setting = patch.SettingSpecified ? patch.Setting ?? "Unknown" : current.Setting,
|
||||
ActivityCondition = patch.ActivityConditionSpecified ? patch.ActivityCondition ?? "Unknown" : current.ActivityCondition,
|
||||
RestDurationMinutes = patch.RestDurationMinutesSpecified ? patch.RestDurationMinutes : current.RestDurationMinutes,
|
||||
BodyPosition = patch.BodyPositionSpecified ? patch.BodyPosition : current.BodyPosition,
|
||||
MeasuredArm = patch.MeasuredArmSpecified ? patch.MeasuredArm : current.MeasuredArm,
|
||||
DeviceDetails = patch.DeviceDetailsSpecified ? patch.DeviceDetails : current.DeviceDetails,
|
||||
CuffDetails = patch.CuffDetailsSpecified ? patch.CuffDetails : current.CuffDetails,
|
||||
AdditionalCircumstances = patch.AdditionalCircumstancesSpecified ? patch.AdditionalCircumstances : current.AdditionalCircumstances
|
||||
};
|
||||
}
|
||||
}
|
||||
observation.UpdatedAt = updatedAt;
|
||||
await db.SaveChangesAsync(cancellationToken);
|
||||
return Dto(observation);
|
||||
}
|
||||
public async Task<bool> DeleteAsync(AuthorizedPatientContext scope,Guid id,CancellationToken ct)
|
||||
{var o=await LockedAsync(scope,id,ct);if(o is null)return false;db.Observations.Remove(o);await db.SaveChangesAsync(ct);return true;}
|
||||
private static ObservationDto Dto(BloodPressureObservation o)=>new(o.ObservationId,o.PatientId,o.MeasuredAt,o.Systolic,o.Diastolic,o.Pulse,new MeasurementContextDto(o.MeasurementContext.Setting,o.MeasurementContext.ActivityCondition,o.MeasurementContext.RestDurationMinutes,o.MeasurementContext.BodyPosition,o.MeasurementContext.MeasuredArm,o.MeasurementContext.DeviceDetails,o.MeasurementContext.CuffDetails,o.MeasurementContext.AdditionalCircumstances),o.Context,o.Note);
|
||||
}
|
||||
public static class ObservationsModule
|
||||
{
|
||||
public static IServiceCollection AddObservations(this IServiceCollection s)
|
||||
{
|
||||
s.AddScoped(sp=>new ObservationDbContext(new DbContextOptionsBuilder<ObservationDbContext>().UseNpgsql(sp.GetRequiredService<RequestTransaction>().Connection??throw new InvalidOperationException("No request transaction.")).Options));
|
||||
s.AddScoped<ObservationFacade>();s.AddScoped<ObservationQueries>(sp=>sp.GetRequiredService<ObservationFacade>());s.AddScoped<ObservationCommands>(sp=>sp.GetRequiredService<ObservationFacade>());return s;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup><TargetFramework>net10.0</TargetFramework><Nullable>enable</Nullable><ImplicitUsings>enable</ImplicitUsings></PropertyGroup>
|
||||
<ItemGroup><FrameworkReference Include="Microsoft.AspNetCore.App" /><ProjectReference Include="../../HealthApp.Contracts/HealthApp.Contracts.csproj" /><ProjectReference Include="../../HealthApp.Infrastructure/HealthApp.Infrastructure.csproj" /></ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,39 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using HealthApp.Observations.Domain;
|
||||
|
||||
namespace HealthApp.Observations.Persistence;
|
||||
|
||||
internal sealed class ObservationDbContext(DbContextOptions<ObservationDbContext> options) : DbContext(options)
|
||||
{
|
||||
public DbSet<BloodPressureObservation> Observations => Set<BloodPressureObservation>();
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
var observation = modelBuilder.Entity<BloodPressureObservation>();
|
||||
observation.ToTable("observation", "observations");
|
||||
observation.HasKey(o => o.ObservationId);
|
||||
observation.Property(o => o.ObservationId).HasColumnName("observation_id").ValueGeneratedNever();
|
||||
// Controlled restricted FK is installed by the module-owned schema migration.
|
||||
observation.Property(o => o.PatientId).HasColumnName("patient_id");
|
||||
observation.Property(o => o.MeasuredAt).HasColumnName("measured_at").HasColumnType("timestamp without time zone");
|
||||
observation.Property(o => o.Systolic).HasColumnName("systolic");
|
||||
observation.Property(o => o.Diastolic).HasColumnName("diastolic");
|
||||
observation.Property(o => o.Pulse).HasColumnName("pulse");
|
||||
observation.Property(o => o.Context).HasColumnName("context").HasColumnType("character varying");
|
||||
observation.Property(o => o.Note).HasColumnName("note").HasColumnType("character varying");
|
||||
observation.OwnsOne(o => o.MeasurementContext, context =>
|
||||
{
|
||||
context.Property(c => c.Setting).HasColumnName("setting").HasDefaultValue("Unknown").IsRequired();
|
||||
context.Property(c => c.ActivityCondition).HasColumnName("activity_condition").HasDefaultValue("Unknown").IsRequired();
|
||||
context.Property(c => c.RestDurationMinutes).HasColumnName("rest_duration_minutes");
|
||||
context.Property(c => c.BodyPosition).HasColumnName("body_position");
|
||||
context.Property(c => c.MeasuredArm).HasColumnName("measured_arm");
|
||||
context.Property(c => c.DeviceDetails).HasColumnName("device_details");
|
||||
context.Property(c => c.CuffDetails).HasColumnName("cuff_details");
|
||||
context.Property(c => c.AdditionalCircumstances).HasColumnName("additional_circumstances");
|
||||
});
|
||||
observation.Navigation(o => o.MeasurementContext).IsRequired();
|
||||
observation.Property(o => o.CreatedAt).HasColumnName("created_at").HasColumnType("timestamp without time zone");
|
||||
observation.Property(o => o.UpdatedAt).HasColumnName("updated_at").HasColumnType("timestamp without time zone");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
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 ContextFilteredHistoryTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
|
||||
{
|
||||
private sealed record Profile(Guid PatientId);
|
||||
private sealed record ContextData(string Setting, string ActivityCondition, string? DeviceDetails);
|
||||
private sealed record Observation(Guid ObservationId, Guid PatientId, DateTime MeasuredAt,
|
||||
string? Context, ContextData MeasurementContext);
|
||||
private const string Period = "from=2026-09-01T08%3A00%3A00&to=2026-09-10T08%3A00%3A00";
|
||||
|
||||
private async Task<Guid> Patient()
|
||||
{
|
||||
using var response = await fixture.Client.PostAsJsonAsync("/api/patients", new { name = "Filtered history", dateOfBirth = "1980-01-01" });
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
return (await response.Content.ReadFromJsonAsync<Profile>())!.PatientId;
|
||||
}
|
||||
|
||||
private async Task<Observation> Record(Guid patient, string time, string? setting, string? activity, string? legacy = null, bool includeContext = true, bool completeContext = false)
|
||||
{
|
||||
using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{patient}/observations", new
|
||||
{
|
||||
measuredAt = time, systolic = 128, diastolic = 82, pulse = 68, context = legacy,
|
||||
measurementContext = includeContext ? new
|
||||
{
|
||||
setting, activityCondition = activity, deviceDetails = "Saved device",
|
||||
restDurationMinutes = completeContext ? (decimal?)5 : null,
|
||||
bodyPosition = completeContext ? "Seated" : null,
|
||||
measuredArm = completeContext ? "Left" : null,
|
||||
cuffDetails = completeContext ? "Saved cuff" : null,
|
||||
additionalCircumstances = completeContext ? "Usual routine" : null
|
||||
} : null
|
||||
});
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
return (await response.Content.ReadFromJsonAsync<Observation>())!;
|
||||
}
|
||||
|
||||
private string PathFor(Guid patient, string selection = "", string period = Period) =>
|
||||
$"/api/patients/{patient}/observations?{period}{selection}";
|
||||
|
||||
[Theory]
|
||||
[InlineData("&setting=Home", "Home", "All", 2)]
|
||||
[InlineData("&activityCondition=AtRest", "All", "AtRest", 2)]
|
||||
[InlineData("&setting=Home&activityCondition=AtRest", "Home", "AtRest", 1)]
|
||||
public async Task Independent_and_combined_selections_return_matching_context_and_metadata(string selection,
|
||||
string settingHeader, string activityHeader, int expectedCount)
|
||||
{
|
||||
var patient = await Patient();
|
||||
var homeRest = await Record(patient, "2026-09-05T08:00:00", "Home", "AtRest");
|
||||
var homeAfter = await Record(patient, "2026-09-06T08:00:00", "Home", "AfterActivity");
|
||||
var clinicRest = await Record(patient, "2026-09-07T08:00:00", "Clinic", "AtRest");
|
||||
await Record(patient, "2026-09-08T08:00:00", null, null, "Home, resting? Morning reading");
|
||||
using var response = await fixture.Client.GetAsync(PathFor(patient, selection));
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal(settingHeader, Assert.Single(response.Headers.GetValues("X-Measurement-Setting")));
|
||||
Assert.Equal(activityHeader, Assert.Single(response.Headers.GetValues("X-Activity-Condition")));
|
||||
var history = (await response.Content.ReadFromJsonAsync<Observation[]>())!;
|
||||
Assert.Equal(expectedCount, history.Length);
|
||||
var expected = new[] { homeRest, homeAfter, clinicRest }.Where(o =>
|
||||
(settingHeader == "All" || o.MeasurementContext.Setting == settingHeader) &&
|
||||
(activityHeader == "All" || o.MeasurementContext.ActivityCondition == activityHeader)).ToArray();
|
||||
Assert.Equal(expected, history);
|
||||
Assert.All(history, o => Assert.Equal("Saved device", o.MeasurementContext.DeviceDetails));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("&setting=Unknown", "Unknown", "All")]
|
||||
[InlineData("&activityCondition=Unknown", "All", "Unknown")]
|
||||
[InlineData("&setting=Unknown&activityCondition=Unknown", "Unknown", "Unknown")]
|
||||
public async Task Unknown_selections_match_unknown_categories_without_interpreting_legacy_text(string selection,
|
||||
string settingHeader, string activityHeader)
|
||||
{
|
||||
var patient = await Patient();
|
||||
var unknown = await Record(patient, "2026-09-05T08:00:00", null, null, "Home resting?");
|
||||
var partial = await Record(patient, "2026-09-06T08:00:00", "Clinic", null);
|
||||
await Record(patient, "2026-09-07T08:00:00", "Home", "AtRest");
|
||||
using var response = await fixture.Client.GetAsync(PathFor(patient, selection));
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal(settingHeader, Assert.Single(response.Headers.GetValues("X-Measurement-Setting")));
|
||||
Assert.Equal(activityHeader, Assert.Single(response.Headers.GetValues("X-Activity-Condition")));
|
||||
var result = (await response.Content.ReadFromJsonAsync<Observation[]>())!;
|
||||
Assert.Equal(activityHeader == "Unknown" && settingHeader == "All" ? new[] { unknown, partial } : new[] { unknown }, result);
|
||||
Assert.Equal("Home resting?", result[0].Context);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task No_selection_retains_all_contexts_in_chronological_order_after_restart()
|
||||
{
|
||||
var patient = await Patient();
|
||||
var last = await Record(patient, "2026-09-07T08:00:00", null, null, includeContext: false);
|
||||
var first = await Record(patient, "2026-09-05T08:00:00", "Home", "AtRest", completeContext: true);
|
||||
var middle = await Record(patient, "2026-09-06T08:00:00", "Clinic", null);
|
||||
await fixture.RestartHostsAsync();
|
||||
using var response = await fixture.Client.GetAsync(PathFor(patient));
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal(new[] { first, middle, last }, await response.Content.ReadFromJsonAsync<Observation[]>());
|
||||
Assert.Equal("All", Assert.Single(response.Headers.GetValues("X-Measurement-Setting")));
|
||||
Assert.Equal("All", Assert.Single(response.Headers.GetValues("X-Activity-Condition")));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Empty_filtered_history_is_an_empty_array_with_applied_selection_metadata()
|
||||
{
|
||||
var patient = await Patient();
|
||||
await Record(patient, "2026-09-05T08:00:00", "Home", "AtRest");
|
||||
using var response = await fixture.Client.GetAsync(PathFor(patient, "&setting=Other&activityCondition=AfterActivity"));
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("[]", await response.Content.ReadAsStringAsync());
|
||||
Assert.Equal("Other", Assert.Single(response.Headers.GetValues("X-Measurement-Setting")));
|
||||
Assert.Equal("AfterActivity", Assert.Single(response.Headers.GetValues("X-Activity-Condition")));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Filtered_history_preserves_patient_scope_inclusive_boundaries_and_equal_bounds()
|
||||
{
|
||||
var patient = await Patient();
|
||||
var last = await Record(patient, "2026-09-10T08:00:00", "Home", "AtRest");
|
||||
var first = await Record(patient, "2026-09-01T08:00:00", "Home", "AtRest");
|
||||
await Record(patient, "2026-09-01T07:59:59", "Home", "AtRest");
|
||||
await Record(patient, "2026-09-10T08:00:01", "Home", "AtRest");
|
||||
await Record(patient, "2026-09-05T08:00:00", "Home", "AfterActivity");
|
||||
await Record(await Patient(), "2026-09-05T08:00:00", "Home", "AtRest");
|
||||
using var response = await fixture.Client.GetAsync(PathFor(patient, "&setting=Home&activityCondition=AtRest"));
|
||||
Assert.Equal(new[] { first, last }, await response.Content.ReadFromJsonAsync<Observation[]>());
|
||||
using var equal = await fixture.Client.GetAsync(PathFor(patient, "&setting=Home", "from=2026-09-01T10%3A00%3A00%2B02%3A00&to=2026-09-01T08%3A00%3A00Z"));
|
||||
Assert.Equal(HttpStatusCode.OK, equal.StatusCode);
|
||||
Assert.Equal(first, Assert.Single((await equal.Content.ReadFromJsonAsync<Observation[]>())!));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("&setting=Unsupported")]
|
||||
[InlineData("&activityCondition=Unsupported")]
|
||||
[InlineData("&setting=All")]
|
||||
[InlineData("&activityCondition=1")]
|
||||
public async Task Unsupported_selections_are_rejected_without_changing_observations(string selection)
|
||||
{
|
||||
var patient = await Patient();
|
||||
var observation = await Record(patient, "2026-09-05T08:00:00", "Home", "AtRest");
|
||||
await using var db = fixture.CreateObservationDbContext();
|
||||
var before = await db.Observations.CountAsync();
|
||||
using var response = await fixture.Client.GetAsync(PathFor(patient, selection));
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
using var problem = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
|
||||
Assert.True(problem.RootElement.TryGetProperty("errors", out _));
|
||||
Assert.Equal(before, await db.Observations.CountAsync());
|
||||
Assert.Equal(observation, await fixture.Client.GetFromJsonAsync<Observation>($"/api/observations/{observation.ObservationId}"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Professional_reads_follow_assignments_and_other_patient_tokens_cannot_use_filters_to_gain_access()
|
||||
{
|
||||
var patient = await Patient();
|
||||
var expected = await Record(patient, "2026-09-05T08:00:00", "Home", "AtRest");
|
||||
var other = await Patient();
|
||||
fixture.AdditionalGatewayConfiguration["Access:ProfessionalAssignments:professional:0"] = patient.ToString();
|
||||
await fixture.RestartHostsAsync();
|
||||
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, "&setting=Home&activityCondition=AtRest"));
|
||||
request.Headers.Authorization = new AuthenticationHeaderValue("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.Equal(expected, Assert.Single((await response.Content.ReadFromJsonAsync<Observation[]>())!));
|
||||
else Assert.Empty(await response.Content.ReadAsStringAsync());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Xunit;
|
||||
|
||||
namespace Observation.AcceptanceTests;
|
||||
|
||||
public sealed class DeleteObservationTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
|
||||
{
|
||||
private sealed record Profile(Guid PatientId);
|
||||
private sealed record Observation(Guid ObservationId, Guid PatientId, DateTime MeasuredAt,
|
||||
int Systolic, int Diastolic, int Pulse, string? Context, string? Note);
|
||||
|
||||
private async Task<Guid> CreatePatientAsync()
|
||||
{
|
||||
using var response = await fixture.Client.PostAsJsonAsync("/api/patients", new
|
||||
{
|
||||
name = "Deletion Example", dateOfBirth = "1980-01-01"
|
||||
});
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
return (await response.Content.ReadFromJsonAsync<Profile>())!.PatientId;
|
||||
}
|
||||
|
||||
private async Task<Observation> RecordAsync(Guid patientId, string measuredAt)
|
||||
{
|
||||
using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{patientId}/observations", new
|
||||
{
|
||||
measuredAt, systolic = 128, diastolic = 82, pulse = 68, context = "Resting", note = "Before breakfast"
|
||||
});
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
return (await response.Content.ReadFromJsonAsync<Observation>())!;
|
||||
}
|
||||
|
||||
private Task<Observation[]?> HistoryAsync(Guid patientId) =>
|
||||
fixture.Client.GetFromJsonAsync<Observation[]>(
|
||||
$"/api/patients/{patientId}/observations?from=2026-09-01T00:00:00&to=2026-09-30T23:59:59");
|
||||
|
||||
[Fact]
|
||||
public async Task Deleted_observation_stays_absent_after_restart_and_other_observations_are_preserved()
|
||||
{
|
||||
var patientId = await CreatePatientAsync();
|
||||
var earlier = await RecordAsync(patientId, "2026-09-10T08:00:00");
|
||||
var deleted = await RecordAsync(patientId, "2026-09-12T08:00:00");
|
||||
var other = await RecordAsync(await CreatePatientAsync(), "2026-09-13T08:00:00");
|
||||
|
||||
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 retrieval = await fixture.Client.GetAsync($"/api/observations/{deleted.ObservationId}");
|
||||
Assert.Equal(HttpStatusCode.NotFound, retrieval.StatusCode);
|
||||
Assert.Equal(earlier, Assert.Single((await HistoryAsync(patientId))!));
|
||||
Assert.Equal(earlier, await fixture.Client.GetFromJsonAsync<Observation>($"/api/observations/{earlier.ObservationId}"));
|
||||
Assert.Equal(earlier, await fixture.Client.GetFromJsonAsync<Observation>(
|
||||
$"/api/patients/{patientId}/observations/latest"));
|
||||
Assert.Equal(other, await fixture.Client.GetFromJsonAsync<Observation>($"/api/observations/{other.ObservationId}"));
|
||||
Assert.Equal(other, Assert.Single((await HistoryAsync(other.PatientId))!));
|
||||
Assert.Equal(patientId, (await fixture.Client.GetFromJsonAsync<Profile>($"/api/patients/{patientId}"))!.PatientId);
|
||||
await using var db = fixture.CreateObservationDbContext();
|
||||
Assert.False(await db.Observations.AnyAsync(o => o.ObservationId == deleted.ObservationId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Deleting_the_only_observation_leaves_empty_history_and_no_latest_observation()
|
||||
{
|
||||
var patientId = await CreatePatientAsync();
|
||||
var observation = await RecordAsync(patientId, "2026-09-12T08:00:00");
|
||||
using var response = await fixture.Client.DeleteAsync($"/api/observations/{observation.ObservationId}");
|
||||
Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);
|
||||
Assert.Empty((await HistoryAsync(patientId))!);
|
||||
using var latest = await fixture.Client.GetAsync($"/api/patients/{patientId}/observations/latest");
|
||||
Assert.Equal(HttpStatusCode.NotFound, latest.StatusCode);
|
||||
using var repeated = await fixture.Client.DeleteAsync($"/api/observations/{observation.ObservationId}");
|
||||
Assert.Equal(HttpStatusCode.NotFound, repeated.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Missing_observation_returns_not_found_without_changing_existing_data()
|
||||
{
|
||||
var observation = await RecordAsync(await CreatePatientAsync(), "2026-09-12T08:00:00");
|
||||
await using var db = fixture.CreateObservationDbContext();
|
||||
var count = await db.Observations.CountAsync();
|
||||
using var response = await fixture.Client.DeleteAsync($"/api/observations/{Guid.NewGuid()}");
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
Assert.Equal(count, await db.Observations.CountAsync());
|
||||
Assert.Equal(observation, await fixture.Client.GetFromJsonAsync<Observation>(
|
||||
$"/api/observations/{observation.ObservationId}"));
|
||||
Assert.Equal(observation, Assert.Single((await HistoryAsync(observation.PatientId))!));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
global using HealthApp.Contracts;
|
||||
@@ -0,0 +1,157 @@
|
||||
using System.Net;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using HealthApp.Observations.Domain;
|
||||
using System.Net.Http.Json;
|
||||
using Xunit;
|
||||
|
||||
namespace Observation.AcceptanceTests;
|
||||
|
||||
public sealed class LatestObservationTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
|
||||
{
|
||||
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<Guid> 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<Profile>())!.PatientId;
|
||||
}
|
||||
|
||||
private async Task<Observation> 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<Observation>())!;
|
||||
}
|
||||
|
||||
[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<Observation>(
|
||||
$"/api/patients/{patientId}/observations/latest"));
|
||||
Assert.Equal(otherLatest, await fixture.Client.GetFromJsonAsync<Observation>(
|
||||
$"/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<Observation?> Latest(Guid patientId) =>
|
||||
fixture.Client.GetFromJsonAsync<Observation>($"/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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using HealthApp.Observations.Persistence;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Npgsql;
|
||||
namespace Observation.AcceptanceTests;
|
||||
public sealed class ObservationApiFixture : PatientProfile.AcceptanceTests.PatientApiFixture
|
||||
{
|
||||
private string? healthyConnection;
|
||||
public string ObservationConnectionString=>ConnectionString;
|
||||
internal ObservationDbContext CreateObservationDbContext()=>new(new DbContextOptionsBuilder<ObservationDbContext>().UseNpgsql(ConnectionString).Options);
|
||||
public async Task StopPatientServiceAsync(){healthyConnection=RuntimeConnectionString;RuntimeConnectionString=new NpgsqlConnectionStringBuilder(RuntimeConnectionString){Host="127.0.0.1",Port=1,Timeout=1}.ConnectionString;await base.RestartHostsAsync();}
|
||||
public Task StopObservationServiceAsync()=>StopPatientServiceAsync();
|
||||
public Task StopInsightsServiceAsync()=>StopPatientServiceAsync();
|
||||
public Task StopOverviewServiceAsync()=>StopPatientServiceAsync();
|
||||
public override async Task RestartHostsAsync(){if(healthyConnection is not null){RuntimeConnectionString=healthyConnection;healthyConnection=null;}await base.RestartHostsAsync();}
|
||||
public HttpClient CreateDirectPatientClient()=>new(){BaseAddress=RawClient.BaseAddress};
|
||||
public HttpClient CreateDirectObservationClient()=>CreateDirectPatientClient();
|
||||
public HttpClient CreateDirectInsightsClient()=>CreateDirectPatientClient();
|
||||
public HttpClient CreateDirectOverviewClient()=>CreateDirectPatientClient();
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Npgsql;
|
||||
using Observation.AcceptanceTests;
|
||||
using Xunit;
|
||||
namespace HealthApp.AcceptanceTests;
|
||||
public sealed class ObservationConcurrencyTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
|
||||
{
|
||||
[Fact]
|
||||
public async Task Locked_disjoint_patches_preserve_both_committed_changes()
|
||||
{
|
||||
using var created=await fixture.Client.PostAsJsonAsync("/api/patients",new{name="Concurrency",dateOfBirth="1980-01-01"});var p=(await created.Content.ReadFromJsonAsync<PatientDto>())!;
|
||||
using var recorded=await fixture.Client.PostAsJsonAsync($"/api/patients/{p.PatientId}/observations",new{measuredAt="2026-09-12T08:00:00",systolic=128,diastolic=82,pulse=68,note="Keep"});var o=(await recorded.Content.ReadFromJsonAsync<ObservationDto>())!;
|
||||
await using var c=new NpgsqlConnection(fixture.ConnectionString);await c.OpenAsync();await using var held=await c.BeginTransactionAsync();
|
||||
await new NpgsqlCommand("SELECT observation_id FROM observations.observation WHERE observation_id=@id FOR UPDATE",c,held){Parameters={new NpgsqlParameter("id",o.ObservationId)}}.ExecuteScalarAsync();
|
||||
var first=fixture.Client.PatchAsJsonAsync($"/api/observations/{o.ObservationId}",new{systolic=130});
|
||||
var second=fixture.Client.PatchAsJsonAsync($"/api/observations/{o.ObservationId}",new{measurementContext=new{setting="Clinic"}});
|
||||
await using var probe=new NpgsqlConnection(fixture.ConnectionString);await probe.OpenAsync();
|
||||
var role=new NpgsqlConnectionStringBuilder(fixture.RuntimeConnectionString).Username;
|
||||
var waited=false;
|
||||
for(var i=0;i<100;i++)
|
||||
{
|
||||
var count=(long)(await new NpgsqlCommand("SELECT count(*) FROM pg_stat_activity WHERE usename=@role AND wait_event_type='Lock'",probe){Parameters={new NpgsqlParameter("role",role)}}.ExecuteScalarAsync())!;
|
||||
if(count>=2){waited=true;break;}await Task.Delay(20);
|
||||
}
|
||||
Assert.True(waited,"Both mutations must wait on the held observation lock.");
|
||||
Assert.False(first.IsCompleted);Assert.False(second.IsCompleted);
|
||||
await held.CommitAsync();using var a=await first;using var b=await second;Assert.Equal(HttpStatusCode.OK,a.StatusCode);Assert.Equal(HttpStatusCode.OK,b.StatusCode);
|
||||
var saved=(await fixture.Client.GetFromJsonAsync<ObservationDto>($"/api/observations/{o.ObservationId}"))!;
|
||||
Assert.Equal(130,saved.Systolic);Assert.Equal("Clinic",saved.MeasurementContext!.Setting);Assert.Equal("Keep",saved.Note);Assert.Equal(o.MeasuredAt,saved.MeasuredAt);Assert.Equal(o.PatientId,saved.PatientId);
|
||||
}
|
||||
[Fact]
|
||||
public async Task Database_rejects_orphan_and_invalid_measurement_values()
|
||||
{
|
||||
await using var c=new NpgsqlConnection(fixture.ConnectionString);await c.OpenAsync();
|
||||
var e=await Assert.ThrowsAsync<PostgresException>(()=>new NpgsqlCommand("INSERT INTO observations.observation(observation_id,patient_id,measured_at,systolic,diastolic,pulse,created_at,updated_at) VALUES(gen_random_uuid(),gen_random_uuid(),now(),128,82,68,now(),now())",c).ExecuteNonQueryAsync());Assert.Equal("23503",e.SqlState);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using Xunit;
|
||||
|
||||
namespace Observation.AcceptanceTests;
|
||||
|
||||
public sealed class ObservationHistoryTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
|
||||
{
|
||||
private sealed record Profile(Guid PatientId);
|
||||
private sealed record Observation(Guid ObservationId, Guid PatientId, DateTime MeasuredAt,
|
||||
int Systolic, int Diastolic, int Pulse, string? Context, string? Note);
|
||||
|
||||
private async Task<Guid> CreatePatientAsync()
|
||||
{
|
||||
using var response = await fixture.Client.PostAsJsonAsync("/api/patients", new
|
||||
{
|
||||
name = "History Example", dateOfBirth = "1980-01-01"
|
||||
});
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
return (await response.Content.ReadFromJsonAsync<Profile>())!.PatientId;
|
||||
}
|
||||
|
||||
private async Task<Observation> 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<Observation>())!;
|
||||
}
|
||||
|
||||
private Task<Observation[]?> HistoryAsync(Guid patientId, string from, string to) =>
|
||||
fixture.Client.GetFromJsonAsync<Observation[]>(
|
||||
$"/api/patients/{patientId}/observations?from={Uri.EscapeDataString(from)}&to={Uri.EscapeDataString(to)}");
|
||||
|
||||
[Fact]
|
||||
public async Task Selected_period_returns_only_the_matching_observation_after_restart()
|
||||
{
|
||||
var patientId = await CreatePatientAsync();
|
||||
await RecordAsync(patientId, "2026-09-01T08:00:00", 120, 80, 60);
|
||||
var expected = await RecordAsync(patientId, "2026-09-05T08:00:00", 125, 82, 65);
|
||||
await RecordAsync(patientId, "2026-09-10T08:00:00", 130, 84, 70);
|
||||
await RecordAsync(await CreatePatientAsync(), "2026-09-05T08:00:00", 140, 90, 75);
|
||||
await fixture.RestartHostsAsync();
|
||||
|
||||
var history = await HistoryAsync(patientId, "2026-09-03T00:00:00", "2026-09-08T23:59:59");
|
||||
|
||||
Assert.Equal(expected, Assert.Single(history!));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Results_are_chronological_and_include_both_period_boundaries()
|
||||
{
|
||||
var patientId = await CreatePatientAsync();
|
||||
var last = await RecordAsync(patientId, "2026-09-10T08:00:00", 130, 84, 70);
|
||||
var first = await RecordAsync(patientId, "2026-09-01T08:00:00", 120, 80, 60);
|
||||
var middle = await RecordAsync(patientId, "2026-09-05T08:00:00", 125, 82, 65);
|
||||
|
||||
Assert.Equal(new[] { first, middle, last },
|
||||
await HistoryAsync(patientId, "2026-09-01T08:00:00", "2026-09-10T08:00:00"));
|
||||
Assert.Equal(first, Assert.Single((await HistoryAsync(patientId,
|
||||
"2026-09-01T08:00:00", "2026-09-01T08:00:00"))!));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task No_matching_observations_returns_an_empty_array()
|
||||
{
|
||||
var patientId = await CreatePatientAsync();
|
||||
await RecordAsync(await CreatePatientAsync(), "2026-09-05T08:00:00", 125, 82, 65);
|
||||
Assert.Empty((await HistoryAsync(patientId, "2026-09-03T00:00:00", "2026-09-08T23:59:59"))!);
|
||||
await RecordAsync(patientId, "2026-09-01T08:00:00", 120, 80, 60);
|
||||
Assert.Empty((await HistoryAsync(patientId, "2026-09-03T00:00:00", "2026-09-08T23:59:59"))!);
|
||||
}
|
||||
|
||||
[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_without_changing_observations(string query)
|
||||
{
|
||||
var patientId = await CreatePatientAsync();
|
||||
var saved = await RecordAsync(patientId, "2026-09-05T08:00:00", 125, 82, 65);
|
||||
using var response = await fixture.Client.GetAsync($"/api/patients/{patientId}/observations?{query}");
|
||||
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
using var problem = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
|
||||
Assert.True(problem.RootElement.TryGetProperty("errors", out _));
|
||||
Assert.Equal(saved, await fixture.Client.GetFromJsonAsync<Observation>($"/api/observations/{saved.ObservationId}"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Offset_bounds_are_normalized_consistently_with_recorded_measurements()
|
||||
{
|
||||
var patientId = await CreatePatientAsync();
|
||||
var saved = await RecordAsync(patientId, "2026-09-05T10:00:00+02:00", 125, 82, 65);
|
||||
|
||||
Assert.Equal(saved, Assert.Single((await HistoryAsync(patientId,
|
||||
"2026-09-05T10:00:00+02:00", "2026-09-05T08:00:00Z"))!));
|
||||
Assert.Empty((await HistoryAsync(patientId, "2026-09-05T08:00:01Z", "2026-09-05T11:00:00Z"))!);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using HealthApp.TestSupport;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Xunit;
|
||||
|
||||
namespace Observation.AcceptanceTests;
|
||||
|
||||
public sealed class PatchObservationTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
|
||||
{
|
||||
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 async Task<Observation> Record(bool withContext = true)
|
||||
{
|
||||
using var patient = await fixture.Client.PostAsJsonAsync("/api/patients", new { name = "Partial correction", dateOfBirth = "1980-01-01" });
|
||||
Assert.Equal(HttpStatusCode.Created, patient.StatusCode);
|
||||
var patientId = (await patient.Content.ReadFromJsonAsync<Profile>())!.PatientId;
|
||||
using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{patientId}/observations", new
|
||||
{
|
||||
measuredAt = "2026-09-12T08:00:00", systolic = 182, diastolic = 82, pulse = 68,
|
||||
context = "Legacy text", note = "Saved note",
|
||||
measurementContext = withContext ? new { setting = "Home", activityCondition = "AtRest", restDurationMinutes = 5.5m,
|
||||
bodyPosition = "Seated", measuredArm = "Left", deviceDetails = "Device", cuffDetails = "Cuff", additionalCircumstances = "Circumstances" } : null
|
||||
});
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
return (await response.Content.ReadFromJsonAsync<Observation>())!;
|
||||
}
|
||||
|
||||
private Task<HttpResponseMessage> Patch(Guid id, object body) => fixture.Client.PatchAsJsonAsync($"/api/observations/{id}", body);
|
||||
private Task<Observation?> Read(Guid id) => fixture.Client.GetFromJsonAsync<Observation>($"/api/observations/{id}");
|
||||
private Task<Observation[]?> History(Guid patient, string selection) => fixture.Client.GetFromJsonAsync<Observation[]>(
|
||||
$"/api/patients/{patient}/observations?from=2026-09-01&to=2026-10-01&{selection}");
|
||||
|
||||
[Fact]
|
||||
public async Task Context_can_be_added_to_a_historical_observation_without_changing_its_measurements()
|
||||
{
|
||||
var original = await Record(false);
|
||||
using var response = await Patch(original.ObservationId, new { measurementContext = new { setting = "Home", activityCondition = "AtRest" } });
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
var updated = (await response.Content.ReadFromJsonAsync<Observation>())!;
|
||||
Assert.Equal(original with { MeasurementContext = original.MeasurementContext with { Setting = "Home", ActivityCondition = "AtRest" } }, updated);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Correcting_one_context_field_preserves_omitted_data_and_changes_selection_after_restart()
|
||||
{
|
||||
var original = await Record();
|
||||
await using var db = fixture.CreateObservationDbContext();
|
||||
var before = await db.Observations.AsNoTracking().SingleAsync(o => o.ObservationId == original.ObservationId);
|
||||
using var response = await Patch(original.ObservationId, new { measurementContext = new { setting = "Clinic" } });
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
var expected = original with { MeasurementContext = original.MeasurementContext with { Setting = "Clinic" } };
|
||||
Assert.Equal(expected, await response.Content.ReadFromJsonAsync<Observation>());
|
||||
await fixture.RestartHostsAsync();
|
||||
Assert.Equal(expected, await Read(original.ObservationId));
|
||||
Assert.Equal(expected, await fixture.Client.GetFromJsonAsync<Observation>($"/api/patients/{original.PatientId}/observations/latest"));
|
||||
Assert.Empty((await History(original.PatientId, "setting=Home"))!);
|
||||
Assert.Equal(expected, Assert.Single((await History(original.PatientId, "setting=Clinic&activityCondition=AtRest"))!));
|
||||
var after = await db.Observations.AsNoTracking().SingleAsync(o => o.ObservationId == original.ObservationId);
|
||||
Assert.Equal(before.CreatedAt, after.CreatedAt);
|
||||
Assert.True(after.UpdatedAt > before.UpdatedAt);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Individual_optional_fields_can_be_corrected_or_cleared_without_erasing_other_context()
|
||||
{
|
||||
var original = await Record();
|
||||
using var corrected = await Patch(original.ObservationId, new { measurementContext = new { restDurationMinutes = 0m,
|
||||
bodyPosition = "Standing", measuredArm = "Right", deviceDetails = "Corrected device", cuffDetails = "Corrected cuff", additionalCircumstances = "After walking" } });
|
||||
Assert.Equal(HttpStatusCode.OK, corrected.StatusCode);
|
||||
var expected = original with { MeasurementContext = original.MeasurementContext with { RestDurationMinutes = 0,
|
||||
BodyPosition = "Standing", MeasuredArm = "Right", DeviceDetails = "Corrected device", CuffDetails = "Corrected cuff", AdditionalCircumstances = "After walking" } };
|
||||
Assert.Equal(expected, await corrected.Content.ReadFromJsonAsync<Observation>());
|
||||
using var clear = await Patch(original.ObservationId, new { measurementContext = new { activityCondition = (string?)null,
|
||||
restDurationMinutes = (decimal?)null, bodyPosition = (string?)null, measuredArm = (string?)null,
|
||||
deviceDetails = (string?)null, cuffDetails = (string?)null, additionalCircumstances = (string?)null } });
|
||||
Assert.Equal(HttpStatusCode.OK, clear.StatusCode);
|
||||
expected = original with { MeasurementContext = new ContextData("Home", "Unknown", null, null, null, null, null, null) };
|
||||
Assert.Equal(expected, await Read(original.ObservationId));
|
||||
Assert.Empty((await History(original.PatientId, "activityCondition=AtRest"))!);
|
||||
Assert.Equal(expected, Assert.Single((await History(original.PatientId, "activityCondition=Unknown"))!));
|
||||
using var setting = await Patch(original.ObservationId, new { measurementContext = new { setting = (string?)null } });
|
||||
Assert.Equal(HttpStatusCode.OK, setting.StatusCode);
|
||||
Assert.Equal("Unknown", (await Read(original.ObservationId))!.MeasurementContext.Setting);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Explicit_null_context_object_clears_structured_context_but_preserves_legacy_text_and_numbers()
|
||||
{
|
||||
var original = await Record();
|
||||
using var response = await Patch(original.ObservationId, new { measurementContext = (object?)null });
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal(original with { MeasurementContext = new ContextData("Unknown", "Unknown", null, null, null, null, null, null) }, await Read(original.ObservationId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Single_numerical_and_legacy_text_updates_preserve_other_values()
|
||||
{
|
||||
var original = await Record();
|
||||
using var correction = await Patch(original.ObservationId, new { systolic = 128 });
|
||||
Assert.Equal(HttpStatusCode.OK, correction.StatusCode);
|
||||
Assert.Equal(original with { Systolic = 128 }, await Read(original.ObservationId));
|
||||
using var text = await Patch(original.ObservationId, new { context = "Corrected narrative", note = (string?)null });
|
||||
Assert.Equal(HttpStatusCode.OK, text.StatusCode);
|
||||
Assert.Equal(original with { Systolic = 128, Context = "Corrected narrative", Note = null }, await Read(original.ObservationId));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("{\"systolic\":128,\"measurementContext\":{\"setting\":\"Unsupported\"}}")]
|
||||
[InlineData("{\"note\":\"Change\",\"measurementContext\":{\"activityCondition\":\"Unsupported\"}}")]
|
||||
[InlineData("{\"measurementContext\":{\"restDurationMinutes\":-1}}")]
|
||||
[InlineData("{\"systolic\":null}")]
|
||||
[InlineData("{\"diastolic\":0}")]
|
||||
[InlineData("{\"pulse\":-1}")]
|
||||
[InlineData("{\"systolic\":\"invalid\"}")]
|
||||
[InlineData("{\"systolic\":128,\"measurementContext\":{\"unsupportedField\":\"value\"}}")]
|
||||
[InlineData("{}")]
|
||||
[InlineData("{\"measurementContext\":{}}")]
|
||||
[InlineData("{")]
|
||||
public async Task Invalid_patches_reject_the_whole_update_without_changes(string json)
|
||||
{
|
||||
var original = await Record();
|
||||
await using var db = fixture.CreateObservationDbContext();
|
||||
var before = await db.Observations.AsNoTracking().SingleAsync(o => o.ObservationId == original.ObservationId);
|
||||
using var content = new StringContent(json, Encoding.UTF8, "application/json");
|
||||
using var response = await fixture.Client.PatchAsync($"/api/observations/{original.ObservationId}", content);
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
using var problem = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
|
||||
Assert.True(problem.RootElement.TryGetProperty("errors", out _));
|
||||
Assert.Equal(original, await Read(original.ObservationId));
|
||||
var after = await db.Observations.AsNoTracking().SingleAsync(o => o.ObservationId == original.ObservationId);
|
||||
Assert.Equal(before.UpdatedAt, after.UpdatedAt);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Unsupported_context_in_a_legacy_put_does_not_silently_apply_its_numerical_changes()
|
||||
{
|
||||
var original = await Record();
|
||||
using var response = await fixture.Client.PutAsJsonAsync($"/api/observations/{original.ObservationId}", new
|
||||
{
|
||||
systolic = 128, diastolic = 80, pulse = 65,
|
||||
measurementContext = new { setting = "Unsupported" }
|
||||
});
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Equal(original, await Read(original.ObservationId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Missing_observation_is_not_created_by_a_context_patch()
|
||||
{
|
||||
await Record();
|
||||
await using var db = fixture.CreateObservationDbContext();
|
||||
var count = await db.Observations.CountAsync();
|
||||
using var response = await Patch(Guid.NewGuid(), new { measurementContext = new { setting = "Clinic" } });
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
Assert.Equal(count, await db.Observations.CountAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Other_patients_professionals_and_unauthenticated_clients_cannot_patch_context()
|
||||
{
|
||||
var original = await Record();
|
||||
var other = await Record();
|
||||
fixture.AdditionalGatewayConfiguration["Access:ProfessionalAssignments:professional:0"] = original.PatientId.ToString();
|
||||
await fixture.RestartHostsAsync();
|
||||
var otherToken = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, fixture.Authentication.PatientAccounts[other.PatientId]);
|
||||
var professional = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional");
|
||||
foreach (var (token, expected) in new[]
|
||||
{
|
||||
((string?)null, HttpStatusCode.Unauthorized), ((string?)"invalid", HttpStatusCode.Unauthorized),
|
||||
((string?)otherToken, HttpStatusCode.NotFound), ((string?)professional, HttpStatusCode.Forbidden)
|
||||
})
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Patch, $"/api/observations/{original.ObservationId}")
|
||||
{ Content = JsonContent.Create(new { measurementContext = new { setting = "Clinic" } }) };
|
||||
if (token is not null) request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
||||
using var response = await fixture.RawClient.SendAsync(request);
|
||||
Assert.Equal(expected, response.StatusCode);
|
||||
}
|
||||
Assert.Equal(original, await Read(original.ObservationId));
|
||||
Assert.Equal(other, await Read(other.ObservationId));
|
||||
}
|
||||
}
|
||||
@@ -18,7 +18,7 @@ public class PatientApiFixture : IAsyncLifetime
|
||||
private string admin="";
|
||||
private WebApplicationFactory<HealthApp.Program>? host;
|
||||
public string ConnectionString {get;private set;}="";
|
||||
public string RuntimeConnectionString {get;private set;}="";
|
||||
public string RuntimeConnectionString {get;protected set;}="";
|
||||
public HttpClient Client {get;private set;}=null!;
|
||||
public HttpClient RawClient {get;private set;}=null!;
|
||||
public AuthenticatedTestClient Authentication {get;}=new();
|
||||
@@ -32,9 +32,9 @@ public class PatientApiFixture : IAsyncLifetime
|
||||
await using var db=new NpgsqlConnection(ConnectionString);await db.OpenAsync();
|
||||
var root=FindRoot();
|
||||
foreach(var _ in new[]{0,1})
|
||||
foreach(var script in Directory.GetFiles(Path.Combine(root,"src/Modules/Profile/Migrations"),"*.sql").Order())
|
||||
foreach(var script in new[]{"Profile","Observations"}.SelectMany(m=>Directory.GetFiles(Path.Combine(root,"src/Modules",m,"Migrations"),"*.sql").Order()))
|
||||
await new NpgsqlCommand(await File.ReadAllTextAsync(script),db).ExecuteNonQueryAsync();
|
||||
await new NpgsqlCommand($"REVOKE CREATE ON SCHEMA public FROM PUBLIC; GRANT CONNECT ON DATABASE {databaseName} TO {runtimeRole}; GRANT USAGE ON SCHEMA profile TO {runtimeRole}; GRANT SELECT,INSERT,UPDATE ON profile.patient TO {runtimeRole}; GRANT SELECT ON profile.schema_version TO {runtimeRole};",db).ExecuteNonQueryAsync();
|
||||
await new NpgsqlCommand($"REVOKE CREATE ON SCHEMA public FROM PUBLIC; GRANT CONNECT ON DATABASE {databaseName} TO {runtimeRole}; GRANT USAGE ON SCHEMA profile TO {runtimeRole}; GRANT SELECT,INSERT,UPDATE ON profile.patient TO {runtimeRole}; GRANT SELECT ON profile.schema_version TO {runtimeRole}; GRANT USAGE ON SCHEMA observations TO {runtimeRole}; GRANT SELECT,INSERT,UPDATE,DELETE ON observations.observation TO {runtimeRole}; GRANT SELECT ON observations.schema_version TO {runtimeRole};",db).ExecuteNonQueryAsync();
|
||||
RuntimeConnectionString=new NpgsqlConnectionStringBuilder(ConnectionString){Username=runtimeRole,Password="test-runtime-only"}.ConnectionString;
|
||||
Start();
|
||||
}
|
||||
@@ -54,7 +54,7 @@ public class PatientApiFixture : IAsyncLifetime
|
||||
});
|
||||
host.UseKestrel(0);RawClient=host.CreateClient();Client=Authentication.Wrap(RawClient);
|
||||
}
|
||||
public async Task RestartHostsAsync(){Client.Dispose();RawClient.Dispose();if(host is not null)await host.DisposeAsync();Start();}
|
||||
public virtual async Task RestartHostsAsync(){Client.Dispose();RawClient.Dispose();if(host is not null)await host.DisposeAsync();Start();}
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
Client?.Dispose();RawClient?.Dispose();if(host is not null)await host.DisposeAsync();
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using HealthApp.TestSupport;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Xunit;
|
||||
|
||||
namespace Observation.AcceptanceTests;
|
||||
|
||||
public sealed class RecordMeasurementContextTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
|
||||
{
|
||||
private sealed record Profile(Guid PatientId);
|
||||
private sealed record Context(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, Context MeasurementContext);
|
||||
|
||||
private async Task<Guid> Patient()
|
||||
{
|
||||
using var response = await fixture.Client.PostAsJsonAsync("/api/patients", new { name = "Context patient", dateOfBirth = "1980-01-01" });
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
return (await response.Content.ReadFromJsonAsync<Profile>())!.PatientId;
|
||||
}
|
||||
|
||||
private Task<HttpResponseMessage> Record(Guid patientId, object? measurementContext, string? context = null, string? note = null) =>
|
||||
fixture.Client.PostAsJsonAsync($"/api/patients/{patientId}/observations", new
|
||||
{
|
||||
measuredAt = "2026-09-12T08:00:00", systolic = 128, diastolic = 82, pulse = 68,
|
||||
measurementContext, context, note
|
||||
});
|
||||
|
||||
[Fact]
|
||||
public async Task Complete_context_is_saved_with_the_correct_values_and_retrievable_after_restart()
|
||||
{
|
||||
var patient = await Patient();
|
||||
var expected = new Context("Home", "AtRest", 5.5m, "Seated", "Left", "Example upper-arm device",
|
||||
"Example cuff", "Recent stress");
|
||||
using var response = await Record(patient, expected, "Before breakfast", "Actual reading");
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
var saved = (await response.Content.ReadFromJsonAsync<Observation>())!;
|
||||
Assert.Equal(expected, saved.MeasurementContext);
|
||||
Assert.Equal(patient, saved.PatientId);
|
||||
Assert.Equal(new DateTime(2026, 9, 12, 8, 0, 0), saved.MeasuredAt);
|
||||
Assert.Equal(128, saved.Systolic);
|
||||
Assert.Equal(82, saved.Diastolic);
|
||||
Assert.Equal(68, saved.Pulse);
|
||||
Assert.Equal("Before breakfast", saved.Context);
|
||||
Assert.Equal("Actual reading", saved.Note);
|
||||
await fixture.RestartHostsAsync();
|
||||
Assert.Equal(saved, await fixture.Client.GetFromJsonAsync<Observation>(response.Headers.Location));
|
||||
var latest = await fixture.Client.GetFromJsonAsync<Observation>($"/api/patients/{patient}/observations/latest");
|
||||
Assert.Equal(saved, latest);
|
||||
var history = await fixture.Client.GetFromJsonAsync<Observation[]>($"/api/patients/{patient}/observations?from=2026-09-11&to=2026-09-13");
|
||||
Assert.Equal(saved, Assert.Single(history!));
|
||||
using var corrected = await fixture.Client.PutAsJsonAsync($"/api/observations/{saved.ObservationId}",
|
||||
new { systolic = 130, diastolic = 84, pulse = 70 });
|
||||
Assert.Equal(HttpStatusCode.OK, corrected.StatusCode);
|
||||
Assert.Equal(expected, (await corrected.Content.ReadFromJsonAsync<Observation>())!.MeasurementContext);
|
||||
await using var db = fixture.CreateObservationDbContext();
|
||||
var persisted = await db.Observations.SingleAsync(o => o.ObservationId == saved.ObservationId);
|
||||
Assert.Equal(5.5m, persisted.MeasurementContext.RestDurationMinutes);
|
||||
Assert.Equal("Home", persisted.MeasurementContext.Setting);
|
||||
Assert.Equal("Example cuff", persisted.MeasurementContext.CuffDetails);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("Home", "AtRest")]
|
||||
[InlineData("Home", "DuringActivity")]
|
||||
[InlineData("Clinic", "AfterActivity")]
|
||||
[InlineData("Other", "Unknown")]
|
||||
[InlineData("Unknown", "AtRest")]
|
||||
[InlineData("Unknown", "Unknown")]
|
||||
public async Task Setting_and_activity_are_independent_and_departures_from_guidance_are_valid(string setting, string activity)
|
||||
{
|
||||
var patient = await Patient();
|
||||
using var response = await Record(patient, new { setting, activityCondition = activity,
|
||||
restDurationMinutes = 0m, bodyPosition = "Standing", additionalCircumstances = "Walking immediately beforehand" });
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
var saved = (await response.Content.ReadFromJsonAsync<Observation>())!;
|
||||
Assert.Equal(setting, saved.MeasurementContext.Setting);
|
||||
Assert.Equal(activity, saved.MeasurementContext.ActivityCondition);
|
||||
Assert.Equal(0m, saved.MeasurementContext.RestDurationMinutes);
|
||||
Assert.Equal("Standing", saved.MeasurementContext.BodyPosition);
|
||||
Assert.Equal("Walking immediately beforehand", saved.MeasurementContext.AdditionalCircumstances);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Partial_and_absent_context_remain_unknown_without_reinterpreting_legacy_text()
|
||||
{
|
||||
var patient = await Patient();
|
||||
using var partial = await Record(patient, new { setting = "Clinic" });
|
||||
var first = (await partial.Content.ReadFromJsonAsync<Observation>())!;
|
||||
Assert.Equal(HttpStatusCode.Created, partial.StatusCode);
|
||||
Assert.Equal("Clinic", first.MeasurementContext.Setting);
|
||||
Assert.Equal("Unknown", first.MeasurementContext.ActivityCondition);
|
||||
Assert.Null(first.MeasurementContext.RestDurationMinutes);
|
||||
Assert.Null(first.MeasurementContext.BodyPosition);
|
||||
using var absent = await Record(patient, null, "Morning reading; resting?", "Keep original text");
|
||||
var second = (await absent.Content.ReadFromJsonAsync<Observation>())!;
|
||||
Assert.Equal(HttpStatusCode.Created, absent.StatusCode);
|
||||
Assert.Equal("Unknown", second.MeasurementContext.Setting);
|
||||
Assert.Equal("Unknown", second.MeasurementContext.ActivityCondition);
|
||||
Assert.Equal("Morning reading; resting?", second.Context);
|
||||
Assert.Equal("Keep original text", second.Note);
|
||||
Assert.Equal(second, await fixture.Client.GetFromJsonAsync<Observation>(absent.Headers.Location));
|
||||
using var explicitNulls = await Record(patient, new { setting = (string?)null, activityCondition = (string?)null });
|
||||
Assert.Equal(HttpStatusCode.Created, explicitNulls.StatusCode);
|
||||
var third = (await explicitNulls.Content.ReadFromJsonAsync<Observation>())!;
|
||||
Assert.Equal("Unknown", third.MeasurementContext.Setting);
|
||||
Assert.Equal("Unknown", third.MeasurementContext.ActivityCondition);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Conflicting_categories_and_narrative_are_preserved_without_relabelling()
|
||||
{
|
||||
var patient = await Patient();
|
||||
using var response = await Record(patient, new { setting = "Home", activityCondition = "AtRest",
|
||||
additionalCircumstances = "During exercise" }, "During exercise", "Recorded as supplied");
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
var saved = (await response.Content.ReadFromJsonAsync<Observation>())!;
|
||||
Assert.Equal("AtRest", saved.MeasurementContext.ActivityCondition);
|
||||
Assert.Equal("During exercise", saved.MeasurementContext.AdditionalCircumstances);
|
||||
Assert.Equal("During exercise", saved.Context);
|
||||
Assert.Equal(saved, await fixture.Client.GetFromJsonAsync<Observation>(response.Headers.Location));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("{\"setting\":\"Unsupported\"}")]
|
||||
[InlineData("{\"activityCondition\":\"Unsupported\"}")]
|
||||
[InlineData("{\"setting\":42}")]
|
||||
[InlineData("{\"activityCondition\":true}")]
|
||||
[InlineData("{\"restDurationMinutes\":-1}")]
|
||||
public async Task Invalid_context_is_rejected_with_validation_details_without_saving(string contextJson)
|
||||
{
|
||||
var patient = await Patient();
|
||||
await using var db = fixture.CreateObservationDbContext();
|
||||
var before = await db.Observations.CountAsync();
|
||||
var json = "{\"measuredAt\":\"2026-09-12T08:00:00\",\"systolic\":128,\"diastolic\":82,\"pulse\":68,\"measurementContext\":" + contextJson + "}";
|
||||
using var content = new StringContent(json, Encoding.UTF8, "application/json");
|
||||
using var response = await fixture.Client.PostAsync($"/api/patients/{patient}/observations", content);
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
using var problem = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
|
||||
Assert.True(problem.RootElement.TryGetProperty("errors", out _));
|
||||
Assert.Equal(before, await db.Observations.CountAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Context_is_protected_against_other_patient_reads_and_submissions_and_professional_writes()
|
||||
{
|
||||
var patient = await Patient();
|
||||
var otherPatient = await Patient();
|
||||
using var recorded = await Record(patient, new { setting = "Home", activityCondition = "AtRest" });
|
||||
Assert.Equal(HttpStatusCode.Created, recorded.StatusCode);
|
||||
var observation = (await recorded.Content.ReadFromJsonAsync<Observation>())!;
|
||||
var otherToken = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, fixture.Authentication.PatientAccounts[otherPatient]);
|
||||
await using var db = fixture.CreateObservationDbContext();
|
||||
var count = await db.Observations.CountAsync();
|
||||
using var read = new HttpRequestMessage(HttpMethod.Get, $"/api/observations/{observation.ObservationId}");
|
||||
read.Headers.Authorization = new("Bearer", otherToken);
|
||||
using var rejectedRead = await fixture.RawClient.SendAsync(read);
|
||||
Assert.Equal(HttpStatusCode.NotFound, rejectedRead.StatusCode);
|
||||
Assert.Empty(await rejectedRead.Content.ReadAsStringAsync());
|
||||
foreach (var token in new[] { otherToken, await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional") })
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, $"/api/patients/{patient}/observations")
|
||||
{
|
||||
Content = JsonContent.Create(new { measuredAt = "2026-09-12T08:00:00", systolic = 128, diastolic = 82,
|
||||
pulse = 68, measurementContext = new { setting = "Clinic" } })
|
||||
};
|
||||
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
||||
using var response = await fixture.RawClient.SendAsync(request);
|
||||
Assert.Equal(token == otherToken ? HttpStatusCode.NotFound : HttpStatusCode.Forbidden, response.StatusCode);
|
||||
}
|
||||
Assert.Equal(count, await db.Observations.CountAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Assigned_professional_can_retrieve_saved_context()
|
||||
{
|
||||
var patient = await Patient();
|
||||
using var recorded = await Record(patient, new { setting = "Clinic", activityCondition = "AtRest", deviceDetails = "Clinic device" });
|
||||
Assert.Equal(HttpStatusCode.Created, recorded.StatusCode);
|
||||
var saved = (await recorded.Content.ReadFromJsonAsync<Observation>())!;
|
||||
fixture.AdditionalGatewayConfiguration["Access:ProfessionalAssignments:professional:0"] = patient.ToString();
|
||||
await fixture.RestartHostsAsync();
|
||||
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional");
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, $"/api/observations/{saved.ObservationId}");
|
||||
request.Headers.Authorization = new("Bearer", token);
|
||||
using var response = await fixture.RawClient.SendAsync(request);
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal(saved, await response.Content.ReadFromJsonAsync<Observation>());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Xunit;
|
||||
|
||||
namespace Observation.AcceptanceTests;
|
||||
|
||||
public sealed class RecordObservationTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
|
||||
{
|
||||
private sealed record Profile(Guid PatientId);
|
||||
private sealed record Observation(Guid ObservationId, Guid PatientId, DateTime MeasuredAt,
|
||||
int Systolic, int Diastolic, int Pulse, string? Context, string? Note);
|
||||
|
||||
private async Task<Guid> CreatePatientAsync()
|
||||
{
|
||||
using var response = await fixture.Client.PostAsJsonAsync("/api/patients", new
|
||||
{
|
||||
name = "Steffen Example", dateOfBirth = "1980-01-01"
|
||||
});
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
return (await response.Content.ReadFromJsonAsync<Profile>())!.PatientId;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Valid_observation_is_assigned_an_identifier_associated_with_the_patient_and_retrievable_after_restart()
|
||||
{
|
||||
var patientId = await CreatePatientAsync();
|
||||
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 = "Before breakfast"
|
||||
});
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
var saved = await response.Content.ReadFromJsonAsync<Observation>();
|
||||
Assert.NotNull(saved);
|
||||
Assert.NotEqual(Guid.Empty, saved.ObservationId);
|
||||
Assert.Equal(patientId, saved.PatientId);
|
||||
Assert.Equal(new DateTime(2026, 9, 12, 8, 0, 0), saved.MeasuredAt);
|
||||
Assert.Equal(128, saved.Systolic);
|
||||
Assert.Equal(82, saved.Diastolic);
|
||||
Assert.Equal(68, saved.Pulse);
|
||||
Assert.Equal("Resting", saved.Context);
|
||||
Assert.Equal("Before breakfast", saved.Note);
|
||||
Assert.Equal($"/api/observations/{saved.ObservationId}", response.Headers.Location!.ToString());
|
||||
|
||||
await fixture.RestartHostsAsync();
|
||||
Assert.Equal(saved, await fixture.Client.GetFromJsonAsync<Observation>(response.Headers.Location));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Optional_fields_can_be_omitted_and_identifiers_are_distinct()
|
||||
{
|
||||
var patientId = await CreatePatientAsync();
|
||||
var request = new { measuredAt = "2026-09-12T08:00:00", systolic = 128, diastolic = 82, pulse = 68 };
|
||||
using var first = await fixture.Client.PostAsJsonAsync($"/api/patients/{patientId}/observations", request);
|
||||
using var second = await fixture.Client.PostAsJsonAsync($"/api/patients/{patientId}/observations", request);
|
||||
Assert.Equal(HttpStatusCode.Created, first.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.Created, second.StatusCode);
|
||||
var saved = (await first.Content.ReadFromJsonAsync<Observation>())!;
|
||||
Assert.Null(saved.Context);
|
||||
Assert.Null(saved.Note);
|
||||
Assert.NotEqual(saved.ObservationId, (await second.Content.ReadFromJsonAsync<Observation>())!.ObservationId);
|
||||
Assert.Equal(saved, await fixture.Client.GetFromJsonAsync<Observation>(first.Headers.Location));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0, 82, 68)]
|
||||
[InlineData(-1, 82, 68)]
|
||||
[InlineData(128, 0, 68)]
|
||||
[InlineData(128, -1, 68)]
|
||||
[InlineData(128, 82, 0)]
|
||||
[InlineData(128, 82, -1)]
|
||||
public async Task Non_positive_values_are_rejected_without_saving(int systolic, int diastolic, int pulse)
|
||||
{
|
||||
var patientId = await CreatePatientAsync();
|
||||
await using var db = fixture.CreateObservationDbContext();
|
||||
var before = await db.Observations.CountAsync();
|
||||
using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{patientId}/observations", new
|
||||
{
|
||||
measuredAt = "2026-09-12T08:00:00", systolic, diastolic, pulse
|
||||
});
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Equal(before, await db.Observations.CountAsync());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("{\"systolic\":128,\"diastolic\":82,\"pulse\":68}")]
|
||||
[InlineData("{\"measuredAt\":null,\"systolic\":128,\"diastolic\":82,\"pulse\":68}")]
|
||||
[InlineData("{\"measuredAt\":\"invalid\",\"systolic\":128,\"diastolic\":82,\"pulse\":68}")]
|
||||
[InlineData("{\"measuredAt\":\"2026-09-12T08:00:00\",\"diastolic\":82,\"pulse\":68}")]
|
||||
[InlineData("{\"measuredAt\":\"2026-09-12T08:00:00\",\"systolic\":128,\"pulse\":68}")]
|
||||
[InlineData("{\"measuredAt\":\"2026-09-12T08:00:00\",\"systolic\":128,\"diastolic\":82}")]
|
||||
[InlineData("{")]
|
||||
public async Task Missing_or_malformed_information_is_rejected_without_saving(string json)
|
||||
{
|
||||
var patientId = await CreatePatientAsync();
|
||||
await using var db = fixture.CreateObservationDbContext();
|
||||
var before = await db.Observations.CountAsync();
|
||||
using var content = new StringContent(json, Encoding.UTF8, "application/json");
|
||||
using var response = await fixture.Client.PostAsync($"/api/patients/{patientId}/observations", content);
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
using var problem = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
|
||||
Assert.True(problem.RootElement.TryGetProperty("errors", out _));
|
||||
Assert.Equal(before, await db.Observations.CountAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Missing_patient_is_rejected_without_saving()
|
||||
{
|
||||
await using var db = fixture.CreateObservationDbContext();
|
||||
var before = await db.Observations.CountAsync();
|
||||
using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{Guid.NewGuid()}/observations", new
|
||||
{
|
||||
measuredAt = "2026-09-12T08:00:00", systolic = 128, diastolic = 82, pulse = 68
|
||||
});
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
Assert.Equal(before, await db.Observations.CountAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Missing_observation_returns_not_found()
|
||||
{
|
||||
using var response = await fixture.Client.GetAsync($"/api/observations/{Guid.NewGuid()}");
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Failed_patient_lookup_is_rejected_without_saving()
|
||||
{
|
||||
var patientId = await CreatePatientAsync();
|
||||
await using var db = fixture.CreateObservationDbContext();
|
||||
var before = await db.Observations.CountAsync();
|
||||
await fixture.StopPatientServiceAsync();
|
||||
try
|
||||
{
|
||||
using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{patientId}/observations", new
|
||||
{
|
||||
measuredAt = "2026-09-12T08:00:00", systolic = 128, diastolic = 82, pulse = 68
|
||||
});
|
||||
Assert.Equal(HttpStatusCode.ServiceUnavailable, response.StatusCode);
|
||||
Assert.Equal(before, await db.Observations.CountAsync());
|
||||
}
|
||||
finally
|
||||
{
|
||||
await fixture.RestartHostsAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Xunit;
|
||||
|
||||
namespace Observation.AcceptanceTests;
|
||||
|
||||
public sealed class UpdateObservationTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
|
||||
{
|
||||
private sealed record Profile(Guid PatientId);
|
||||
private sealed record Observation(Guid ObservationId, Guid PatientId, DateTime MeasuredAt,
|
||||
int Systolic, int Diastolic, int Pulse, string? Context, string? Note);
|
||||
|
||||
private async Task<Observation> RecordAsync()
|
||||
{
|
||||
using var patient = await fixture.Client.PostAsJsonAsync("/api/patients", new
|
||||
{
|
||||
name = "Correction Example", dateOfBirth = "1980-01-01"
|
||||
});
|
||||
Assert.Equal(HttpStatusCode.Created, patient.StatusCode);
|
||||
var patientId = (await patient.Content.ReadFromJsonAsync<Profile>())!.PatientId;
|
||||
using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{patientId}/observations", new
|
||||
{
|
||||
measuredAt = "2026-09-12T08:00:00", systolic = 182, diastolic = 82, pulse = 68,
|
||||
context = "Resting", note = "Before breakfast"
|
||||
});
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
return (await response.Content.ReadFromJsonAsync<Observation>())!;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Correction_preserves_other_information_and_is_visible_in_all_retrievals_after_restart()
|
||||
{
|
||||
var original = await RecordAsync();
|
||||
var other = await RecordAsync();
|
||||
await using var db = fixture.CreateObservationDbContext();
|
||||
var before = await db.Observations.AsNoTracking().SingleAsync(o => o.ObservationId == original.ObservationId);
|
||||
using var response = await fixture.Client.PutAsJsonAsync($"/api/observations/{original.ObservationId}",
|
||||
new { systolic = 128, diastolic = 82, pulse = 68 });
|
||||
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
var expected = original with { Systolic = 128 };
|
||||
Assert.Equal(expected, await response.Content.ReadFromJsonAsync<Observation>());
|
||||
await fixture.RestartHostsAsync();
|
||||
Assert.Equal(expected, await fixture.Client.GetFromJsonAsync<Observation>($"/api/observations/{original.ObservationId}"));
|
||||
Assert.Equal(expected, await fixture.Client.GetFromJsonAsync<Observation>(
|
||||
$"/api/patients/{original.PatientId}/observations/latest"));
|
||||
var history = await fixture.Client.GetFromJsonAsync<Observation[]>(
|
||||
$"/api/patients/{original.PatientId}/observations?from=2026-09-12T00:00:00&to=2026-09-12T23:59:59");
|
||||
Assert.Equal(expected, Assert.Single(history!));
|
||||
Assert.Equal(other, await fixture.Client.GetFromJsonAsync<Observation>($"/api/observations/{other.ObservationId}"));
|
||||
var after = await db.Observations.AsNoTracking().SingleAsync(o => o.ObservationId == original.ObservationId);
|
||||
Assert.Equal(before.CreatedAt, after.CreatedAt);
|
||||
Assert.True(after.UpdatedAt > before.UpdatedAt);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task All_three_measured_values_can_be_corrected()
|
||||
{
|
||||
var original = await RecordAsync();
|
||||
using var response = await fixture.Client.PutAsJsonAsync($"/api/observations/{original.ObservationId}",
|
||||
new { systolic = 120, diastolic = 80, pulse = 60 });
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal(original with { Systolic = 120, Diastolic = 80, Pulse = 60 },
|
||||
await fixture.Client.GetFromJsonAsync<Observation>($"/api/observations/{original.ObservationId}"));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0, 82, 68)]
|
||||
[InlineData(128, 0, 68)]
|
||||
[InlineData(128, 82, 0)]
|
||||
[InlineData(-1, 82, 68)]
|
||||
[InlineData(128, -1, 68)]
|
||||
[InlineData(128, 82, -1)]
|
||||
public async Task Non_positive_values_are_rejected_without_changing_observation(int systolic, int diastolic, int pulse)
|
||||
{
|
||||
var original = await RecordAsync();
|
||||
await using var db = fixture.CreateObservationDbContext();
|
||||
var before = await db.Observations.AsNoTracking().SingleAsync(o => o.ObservationId == original.ObservationId);
|
||||
using var response = await fixture.Client.PutAsJsonAsync($"/api/observations/{original.ObservationId}",
|
||||
new { systolic, diastolic, pulse });
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Equal(original, await fixture.Client.GetFromJsonAsync<Observation>($"/api/observations/{original.ObservationId}"));
|
||||
var after = await db.Observations.AsNoTracking().SingleAsync(o => o.ObservationId == original.ObservationId);
|
||||
Assert.Equal(before.UpdatedAt, after.UpdatedAt);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("{\"diastolic\":82,\"pulse\":68}")]
|
||||
[InlineData("{\"systolic\":128,\"pulse\":68}")]
|
||||
[InlineData("{\"systolic\":128,\"diastolic\":82}")]
|
||||
[InlineData("{\"systolic\":null,\"diastolic\":82,\"pulse\":68}")]
|
||||
[InlineData("{\"systolic\":\"invalid\",\"diastolic\":82,\"pulse\":68}")]
|
||||
[InlineData("{")]
|
||||
public async Task Missing_or_malformed_values_are_rejected_without_changes(string json)
|
||||
{
|
||||
var original = await RecordAsync();
|
||||
using var content = new StringContent(json, Encoding.UTF8, "application/json");
|
||||
using var response = await fixture.Client.PutAsync($"/api/observations/{original.ObservationId}", content);
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
using var problem = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
|
||||
Assert.True(problem.RootElement.TryGetProperty("errors", out _));
|
||||
Assert.Equal(original, await fixture.Client.GetFromJsonAsync<Observation>($"/api/observations/{original.ObservationId}"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Missing_observation_is_rejected_without_inserting_a_new_observation()
|
||||
{
|
||||
await using var db = fixture.CreateObservationDbContext();
|
||||
var count = await db.Observations.CountAsync();
|
||||
var observationId = Guid.NewGuid();
|
||||
using var response = await fixture.Client.PutAsJsonAsync($"/api/observations/{observationId}",
|
||||
new { systolic = 128, diastolic = 82, pulse = 68 });
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
Assert.Equal(count, await db.Observations.CountAsync());
|
||||
using var retrieval = await fixture.Client.GetAsync($"/api/observations/{observationId}");
|
||||
Assert.Equal(HttpStatusCode.NotFound, retrieval.StatusCode);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using HealthApp.TestSupport;
|
||||
using HealthApp.Observations.Domain;
|
||||
using HealthApp.Contracts;
|
||||
using HealthApp.Profile.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>());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user