Record Architecture B approval and verified pinned baseline
This commit is contained in:
1 parent
20ab461c01
commit
cee98e7035
158 files changed
+33575
No files matched your search
+102
@@ -0,0 +1,102 @@
|
||||
using System.Net;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using System.Text.Encodings.Web;
|
||||
using HealthApp.TestSupport;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Xunit;
|
||||
|
||||
namespace PatientProfile.AcceptanceTests;
|
||||
|
||||
public sealed class AuthenticationIntegrationTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Production_gateway_rejects_plain_http_even_for_login_and_public_guidance()
|
||||
{
|
||||
var authentication = new AuthenticatedTestClient();
|
||||
try
|
||||
{
|
||||
var configuration = authentication.Configuration();
|
||||
foreach (var service in new[] { "PatientProfile", "Observation", "Insights", "HealthOverview" })
|
||||
configuration[$"Services:{service}:BaseUrl"] = "https://service.example.test/";
|
||||
using var host = new WebApplicationFactory<ApiGateway.Program>().WithWebHostBuilder(builder =>
|
||||
{
|
||||
builder.UseEnvironment("Production");
|
||||
builder.ConfigureAppConfiguration((_, config) => config.AddInMemoryCollection(configuration));
|
||||
});
|
||||
using var http = host.CreateClient();
|
||||
using var guidance = await http.GetAsync("/api/measurement-guidance");
|
||||
Assert.Equal(HttpStatusCode.BadRequest, guidance.StatusCode);
|
||||
using var login = await http.PostAsync("/api/authentication/login", new StringContent("{}", Encoding.UTF8, "application/json"));
|
||||
Assert.Equal(HttpStatusCode.BadRequest, login.StatusCode);
|
||||
using var https = host.CreateClient(new WebApplicationFactoryClientOptions { BaseAddress = new Uri("https://localhost") });
|
||||
using var available = await https.GetAsync("/api/measurement-guidance");
|
||||
Assert.Equal(HttpStatusCode.OK, available.StatusCode);
|
||||
}
|
||||
finally { if (Directory.Exists(authentication.KeyDirectory)) Directory.Delete(authentication.KeyDirectory, true); }
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("Patient", "test-0")]
|
||||
[InlineData("HealthcareProfessional", "professional")]
|
||||
public async Task Standard_replacement_handler_with_same_identity_retains_ownership_policy(string role, string accountId)
|
||||
{
|
||||
var authentication = new AuthenticatedTestClient();
|
||||
var patient = Guid.NewGuid();
|
||||
try
|
||||
{
|
||||
var configuration = authentication.Configuration();
|
||||
configuration["TestIdentity:Role"] = role;
|
||||
configuration["TestIdentity:AccountId"] = accountId;
|
||||
configuration[$"Access:ProfessionalAssignments:{accountId}:0"] = patient.ToString();
|
||||
foreach (var service in new[] { "PatientProfile", "Observation", "Insights", "HealthOverview" })
|
||||
configuration[$"Services:{service}:BaseUrl"] = "http://service.example.test/";
|
||||
using var host = new WebApplicationFactory<ApiGateway.Program>().WithWebHostBuilder(builder =>
|
||||
{
|
||||
builder.UseEnvironment("Development");
|
||||
builder.ConfigureAppConfiguration((_, config) => config.AddInMemoryCollection(configuration));
|
||||
builder.ConfigureServices(services =>
|
||||
{
|
||||
services.AddAuthentication().AddScheme<AuthenticationSchemeOptions, ReplacementHandler>("Replacement", null);
|
||||
services.PostConfigure<PolicySchemeOptions>("ClientOrService", options => options.ForwardDefaultSelector = _ => "Replacement");
|
||||
services.AddHttpClient("PatientProfile").ConfigurePrimaryHttpMessageHandler(() => new PatientHandler(patient));
|
||||
});
|
||||
});
|
||||
using var client = host.CreateClient();
|
||||
using var own = await client.GetAsync($"/api/patients/{patient}");
|
||||
Assert.Equal(HttpStatusCode.OK, own.StatusCode);
|
||||
using var other = await client.GetAsync($"/api/patients/{Guid.NewGuid()}");
|
||||
Assert.Equal(HttpStatusCode.NotFound, other.StatusCode);
|
||||
Assert.Empty(await other.Content.ReadAsStringAsync());
|
||||
}
|
||||
finally { if (Directory.Exists(authentication.KeyDirectory)) Directory.Delete(authentication.KeyDirectory, true); }
|
||||
}
|
||||
|
||||
public sealed class ReplacementHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder, IConfiguration configuration)
|
||||
: AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
|
||||
{
|
||||
protected override Task<AuthenticateResult> HandleAuthenticateAsync() => Task.FromResult(
|
||||
AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(new ClaimsIdentity(new[]
|
||||
{
|
||||
new Claim(ClaimTypes.NameIdentifier, configuration["TestIdentity:AccountId"]!), new Claim(ClaimTypes.Role, configuration["TestIdentity:Role"]!)
|
||||
}, Scheme.Name)), Scheme.Name)));
|
||||
}
|
||||
|
||||
private sealed class PatientHandler(Guid patientId) : HttpMessageHandler
|
||||
{
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
Assert.True(request.Headers.Contains("X-Gateway-Key"));
|
||||
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
|
||||
{
|
||||
Content = new StringContent($"{{\"patientId\":\"{patientId}\"}}", Encoding.UTF8, "application/json")
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Xunit;
|
||||
|
||||
namespace PatientProfile.AcceptanceTests;
|
||||
|
||||
public sealed class CreatePatientTests(PatientApiFixture fixture) : IClassFixture<PatientApiFixture>
|
||||
{
|
||||
// This HTTP contract is independent of the service's implementation DTOs.
|
||||
public sealed record Profile(Guid PatientId, string Name, DateOnly DateOfBirth, string? ContactInfo);
|
||||
|
||||
[Fact]
|
||||
public async Task Valid_profile_is_assigned_an_identifier_and_can_be_retrieved_after_restart()
|
||||
{
|
||||
using var response = await fixture.Client.PostAsJsonAsync("/api/patients", new
|
||||
{
|
||||
name = "Steffen Example", dateOfBirth = "1980-01-01", contactInfo = "steffen@example.test"
|
||||
});
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
var created = await response.Content.ReadFromJsonAsync<Profile>();
|
||||
Assert.NotNull(created);
|
||||
Assert.NotEqual(Guid.Empty, created.PatientId);
|
||||
Assert.Equal("Steffen Example", created.Name);
|
||||
Assert.Equal(new DateOnly(1980, 1, 1), created.DateOfBirth);
|
||||
Assert.Equal("steffen@example.test", created.ContactInfo);
|
||||
Assert.Equal($"/api/patients/{created.PatientId}", response.Headers.Location!.ToString());
|
||||
|
||||
await fixture.RestartHostsAsync();
|
||||
using var retrieved = await fixture.Client.GetAsync(response.Headers.Location);
|
||||
Assert.Equal(HttpStatusCode.OK, retrieved.StatusCode);
|
||||
Assert.Equal(created, await retrieved.Content.ReadFromJsonAsync<Profile>());
|
||||
|
||||
await using var db = fixture.CreateDbContext();
|
||||
var stored = await db.Patients.SingleAsync(p => p.PatientId == created.PatientId);
|
||||
Assert.Equal(created.Name, stored.Name);
|
||||
Assert.Equal(created.DateOfBirth, stored.DateOfBirth);
|
||||
Assert.Equal(created.ContactInfo, stored.ContactInfo);
|
||||
Assert.NotEqual(default, stored.CreatedAt);
|
||||
Assert.Equal(stored.CreatedAt, stored.UpdatedAt);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("{\"dateOfBirth\":\"1980-01-01\"}", "Name")]
|
||||
[InlineData("{\"name\":null,\"dateOfBirth\":\"1980-01-01\"}", "Name")]
|
||||
[InlineData("{\"name\":\"\",\"dateOfBirth\":\"1980-01-01\"}", "Name")]
|
||||
[InlineData("{\"name\":\" \",\"dateOfBirth\":\"1980-01-01\"}", "Name")]
|
||||
[InlineData("{\"name\":\"Steffen Example\"}", "DateOfBirth")]
|
||||
[InlineData("{\"name\":\"Steffen Example\",\"dateOfBirth\":null}", "DateOfBirth")]
|
||||
public async Task Missing_required_information_is_rejected_without_persisting(string json, string field)
|
||||
{
|
||||
await using var db = fixture.CreateDbContext();
|
||||
var countBefore = await db.Patients.CountAsync();
|
||||
using var content = new StringContent(json, Encoding.UTF8, "application/json");
|
||||
using var response = await fixture.Client.PostAsync("/api/patients", content);
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
using var problem = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
|
||||
Assert.True(problem.RootElement.GetProperty("errors").TryGetProperty(field, out _));
|
||||
Assert.Equal(countBefore, await db.Patients.CountAsync());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("{\"name\":\"Steffen Example\",\"dateOfBirth\":\"invalid\"}")]
|
||||
[InlineData("{\"name\":\"Steffen Example\",\"dateOfBirth\":\"1980-02-30\"}")]
|
||||
[InlineData("{")]
|
||||
public async Task Malformed_information_is_rejected(string json)
|
||||
{
|
||||
await using var db = fixture.CreateDbContext();
|
||||
var countBefore = await db.Patients.CountAsync();
|
||||
using var content = new StringContent(json, Encoding.UTF8, "application/json");
|
||||
using var response = await fixture.Client.PostAsync("/api/patients", content);
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Equal(countBefore, await db.Patients.CountAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Separate_creations_have_distinct_identifiers_and_contact_information_is_optional()
|
||||
{
|
||||
var request = new { name = "Steffen Example", dateOfBirth = "1980-01-01" };
|
||||
using var first = await fixture.Client.PostAsJsonAsync("/api/patients", request);
|
||||
using var second = await fixture.Client.PostAsJsonAsync("/api/patients", request);
|
||||
Assert.Equal(HttpStatusCode.Created, first.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.Created, second.StatusCode);
|
||||
var firstProfile = await first.Content.ReadFromJsonAsync<Profile>();
|
||||
var secondProfile = await second.Content.ReadFromJsonAsync<Profile>();
|
||||
Assert.NotEqual(firstProfile!.PatientId, secondProfile!.PatientId);
|
||||
Assert.Null(firstProfile.ContactInfo);
|
||||
Assert.Equal(firstProfile, await fixture.Client.GetFromJsonAsync<Profile>(first.Headers.Location));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Unknown_identifier_returns_not_found()
|
||||
{
|
||||
using var response = await fixture.Client.GetAsync($"/api/patients/{Guid.NewGuid()}");
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
}
|
||||
}
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
using System.Net;
|
||||
using HealthApp.TestSupport;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using System.Text.Json;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Xunit;
|
||||
|
||||
namespace PatientProfile.AcceptanceTests;
|
||||
|
||||
public sealed class MeasurementGuidanceTests : IDisposable
|
||||
{
|
||||
private readonly WebApplicationFactory<ApiGateway.Program> host;
|
||||
private readonly HttpClient client;
|
||||
private int upstreamCalls;
|
||||
private readonly AuthenticatedTestClient authentication = new();
|
||||
|
||||
public MeasurementGuidanceTests()
|
||||
{
|
||||
host = new WebApplicationFactory<ApiGateway.Program>().WithWebHostBuilder(builder =>
|
||||
{
|
||||
builder.UseEnvironment("Development");
|
||||
builder.ConfigureAppConfiguration((_, config) => config.AddInMemoryCollection(authentication.Configuration()).AddInMemoryCollection(
|
||||
new Dictionary<string, string?>
|
||||
{
|
||||
["Services:PatientProfile:BaseUrl"] = "http://127.0.0.1:1/",
|
||||
["Services:Observation:BaseUrl"] = "http://127.0.0.1:1/",
|
||||
["Services:Insights:BaseUrl"] = "http://127.0.0.1:1/"
|
||||
}));
|
||||
builder.ConfigureServices(services =>
|
||||
{
|
||||
foreach (var name in new[] { "PatientProfile", "Observation", "Insights" })
|
||||
services.AddHttpClient(name).ConfigurePrimaryHttpMessageHandler(
|
||||
() => new RejectUpstreamHandler(() => Interlocked.Increment(ref upstreamCalls)));
|
||||
});
|
||||
});
|
||||
client = host.CreateClient();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")]
|
||||
[InlineData("?setting=Unknown")]
|
||||
[InlineData("?setting=Home")]
|
||||
public async Task Public_guidance_without_patient_records_is_labelled_and_has_ordered_sourced_instructions(string query)
|
||||
{
|
||||
using var response = await client.GetAsync("/api/measurement-guidance" + query);
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
|
||||
var result = json.RootElement;
|
||||
Assert.True(result.GetProperty("available").GetBoolean());
|
||||
Assert.Equal("Home", result.GetProperty("applicableSetting").GetString());
|
||||
Assert.Equal("AtRest", result.GetProperty("applicableActivityCondition").GetString());
|
||||
Assert.True(DateOnly.TryParse(result.GetProperty("reviewedOn").GetString(), out _));
|
||||
var steps = result.GetProperty("steps").EnumerateArray().ToArray();
|
||||
Assert.Equal(Enumerable.Range(1, 6), steps.Select(s => s.GetProperty("order").GetInt32()));
|
||||
var instructions = string.Join(" ", steps.Select(s => s.GetProperty("instruction").GetString()));
|
||||
foreach (var text in new[] { "validated upper-arm", "cuff", "five minutes", "back and arm supported",
|
||||
"still", "three readings", "three consecutive days", "one observation", "actual", "measurement time" })
|
||||
Assert.Contains(text, instructions);
|
||||
var sources = result.GetProperty("sources").EnumerateArray().ToArray();
|
||||
Assert.Equal(2, sources.Length);
|
||||
Assert.All(sources, source =>
|
||||
{
|
||||
Assert.StartsWith("https://www.sundhed.dk/", source.GetProperty("url").GetString());
|
||||
Assert.True(DateOnly.TryParse(source.GetProperty("updatedOn").GetString(), out _));
|
||||
});
|
||||
Assert.Contains("not a clinical measurement protocol", result.GetProperty("explanation").GetString());
|
||||
Assert.Contains("does not assess rhythm regularity", result.GetProperty("pulseExplanation").GetString());
|
||||
Assert.Contains("does not save or alter", result.GetProperty("limitations").GetString());
|
||||
Assert.Contains("prevent a valid submission", result.GetProperty("limitations").GetString());
|
||||
Assert.DoesNotContain("patientId", result.GetRawText());
|
||||
Assert.DoesNotContain("assignments", result.GetRawText());
|
||||
Assert.Equal(0, upstreamCalls);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("DuringActivity")]
|
||||
[InlineData("AfterActivity")]
|
||||
public async Task Activity_is_not_relabelled_as_rest_or_certified(string activity)
|
||||
{
|
||||
using var response = await client.GetAsync($"/api/measurement-guidance?setting=Home&activityCondition={activity}");
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
|
||||
var result = json.RootElement;
|
||||
Assert.Equal(activity, result.GetProperty("requestedActivityCondition").GetString());
|
||||
Assert.Contains("do not relabel", result.GetProperty("activityExplanation").GetString());
|
||||
Assert.Contains("remain valid to record", result.GetProperty("activityExplanation").GetString());
|
||||
Assert.Contains("does not record a setting or certify compliance", result.GetProperty("explanation").GetString());
|
||||
Assert.Equal(0, upstreamCalls);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("Clinic")]
|
||||
[InlineData("Other")]
|
||||
public async Task Unsupported_guidance_is_explicitly_unavailable_without_unverified_instructions(string setting)
|
||||
{
|
||||
using var response = await client.GetAsync($"/api/measurement-guidance?setting={setting}");
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
|
||||
var result = json.RootElement;
|
||||
Assert.False(result.GetProperty("available").GetBoolean());
|
||||
Assert.Contains("unavailable", result.GetProperty("explanation").GetString());
|
||||
Assert.Empty(result.GetProperty("steps").EnumerateArray());
|
||||
Assert.Empty(result.GetProperty("sources").EnumerateArray());
|
||||
Assert.Equal(JsonValueKind.Null, result.GetProperty("applicableSetting").ValueKind);
|
||||
Assert.Equal(0, upstreamCalls);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("setting=Unsupported")]
|
||||
[InlineData("activityCondition=Unsupported")]
|
||||
public async Task Invalid_categories_return_explained_rejections(string query)
|
||||
{
|
||||
using var response = await client.GetAsync("/api/measurement-guidance?" + query);
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Contains("Unsupported", await response.Content.ReadAsStringAsync());
|
||||
Assert.Equal(0, upstreamCalls);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
client.Dispose();
|
||||
host.Dispose();
|
||||
if (Directory.Exists(authentication.KeyDirectory)) Directory.Delete(authentication.KeyDirectory, true);
|
||||
}
|
||||
|
||||
private sealed class RejectUpstreamHandler(Action called) : HttpMessageHandler
|
||||
{
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
called();
|
||||
throw new InvalidOperationException("Guidance must not read or write patient data.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
using Microsoft.AspNetCore.Authentication.BearerToken;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using HealthApp.TestSupport;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using System.Net;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Npgsql;
|
||||
using PatientProfileService.Persistence;
|
||||
using Xunit;
|
||||
|
||||
namespace PatientProfile.AcceptanceTests;
|
||||
|
||||
public sealed class PatientApiFixture : IAsyncLifetime
|
||||
{
|
||||
private readonly string databaseName = "us01_" + Guid.NewGuid().ToString("N");
|
||||
private string adminConnectionString = "";
|
||||
private WebApplicationFactory<PatientProfileService.Program>? service;
|
||||
private WebApplicationFactory<ApiGateway.Program>? gateway;
|
||||
public string ConnectionString { get; private set; } = "";
|
||||
public HttpClient Client { get; private set; } = null!;
|
||||
public HttpClient RawClient { get; private set; } = null!;
|
||||
public AuthenticatedTestClient Authentication { get; } = new();
|
||||
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
adminConnectionString = Environment.GetEnvironmentVariable("TEST_POSTGRES_CONNECTION")
|
||||
?? throw new InvalidOperationException(
|
||||
"Set TEST_POSTGRES_CONNECTION to a PostgreSQL connection with permission to create test databases.");
|
||||
await using var connection = new NpgsqlConnection(adminConnectionString);
|
||||
await connection.OpenAsync();
|
||||
await using var command = new NpgsqlCommand($"CREATE DATABASE {databaseName}", connection);
|
||||
await command.ExecuteNonQueryAsync();
|
||||
ConnectionString = new NpgsqlConnectionStringBuilder(adminConnectionString) { Database = databaseName }.ConnectionString;
|
||||
await using var db = CreateDbContext();
|
||||
await db.Database.MigrateAsync();
|
||||
// Applying the committed migration twice must be harmless.
|
||||
await db.Database.MigrateAsync();
|
||||
StartHosts();
|
||||
}
|
||||
|
||||
public PatientDbContext CreateDbContext() => new(
|
||||
new DbContextOptionsBuilder<PatientDbContext>().UseNpgsql(ConnectionString).Options);
|
||||
|
||||
private void StartHosts()
|
||||
{
|
||||
service = new WebApplicationFactory<PatientProfileService.Program>().WithWebHostBuilder(builder =>
|
||||
{
|
||||
builder.UseEnvironment("Development");
|
||||
builder.ConfigureKestrel(options => options.Listen(IPAddress.Loopback, 0));
|
||||
builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(
|
||||
new Dictionary<string, string?> { ["ConnectionStrings:PatientDatabase"] = ConnectionString, ["InternalAccess:GatewayKey"] = Authentication.GatewayKey }));
|
||||
});
|
||||
service.UseKestrel(0);
|
||||
using var serviceClient = service.CreateClient();
|
||||
|
||||
gateway = new WebApplicationFactory<ApiGateway.Program>().WithWebHostBuilder(builder =>
|
||||
builder.UseEnvironment("Development").ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(Authentication.Configuration()).AddInMemoryCollection(
|
||||
new Dictionary<string, string?> { ["Services:PatientProfile:BaseUrl"] = serviceClient.BaseAddress!.ToString(),
|
||||
["Services:Insights:BaseUrl"] = "http://127.0.0.1:1/",
|
||||
["Services:Observation:BaseUrl"] = "http://127.0.0.1:1/" })));
|
||||
gateway = gateway.WithWebHostBuilder(builder => builder.ConfigureServices(services =>
|
||||
services.PostConfigure<BearerTokenOptions>("Bearer", options => options.TimeProvider = Authentication.Clock)));
|
||||
RawClient = gateway.CreateClient();
|
||||
Client = Authentication.Wrap(RawClient);
|
||||
}
|
||||
|
||||
public async Task RestartHostsAsync()
|
||||
{
|
||||
Client.Dispose();
|
||||
RawClient.Dispose();
|
||||
await gateway!.DisposeAsync();
|
||||
await service!.DisposeAsync();
|
||||
StartHosts();
|
||||
}
|
||||
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
Client?.Dispose();
|
||||
RawClient?.Dispose();
|
||||
if (gateway is not null) await gateway.DisposeAsync();
|
||||
if (service is not null) await service.DisposeAsync();
|
||||
if (Directory.Exists(Authentication.KeyDirectory)) Directory.Delete(Authentication.KeyDirectory, true);
|
||||
if (string.IsNullOrEmpty(adminConnectionString)) return;
|
||||
|
||||
NpgsqlConnection.ClearAllPools();
|
||||
await using var connection = new NpgsqlConnection(adminConnectionString);
|
||||
await connection.OpenAsync();
|
||||
await using var command = new NpgsqlCommand($"DROP DATABASE IF EXISTS {databaseName} WITH (FORCE)", connection);
|
||||
await command.ExecuteNonQueryAsync();
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>true</IsTestProject>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
|
||||
<PackageReference Include="xunit" Version="2.9.3" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5" PrivateAssets="all" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.12" />
|
||||
<ProjectReference Include="../../src/PatientProfileService/PatientProfileService.csproj" />
|
||||
<ProjectReference Include="../../src/ApiGateway/ApiGateway.csproj" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="../Support/AuthenticatedTestClient.cs" Link="Support/AuthenticatedTestClient.cs" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,71 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Xunit;
|
||||
|
||||
namespace PatientProfile.AcceptanceTests;
|
||||
|
||||
public sealed class UpdatePatientTests(PatientApiFixture fixture) : IClassFixture<PatientApiFixture>
|
||||
{
|
||||
private sealed record Profile(Guid PatientId, string Name, DateOnly DateOfBirth, string? ContactInfo);
|
||||
|
||||
[Fact]
|
||||
public async Task Updated_profile_preserves_identity_and_date_of_birth_and_survives_restart()
|
||||
{
|
||||
using var createdResponse = await fixture.Client.PostAsJsonAsync("/api/patients", new
|
||||
{
|
||||
name = "Steffen Example", dateOfBirth = "1980-01-01", contactInfo = "old@example.test"
|
||||
});
|
||||
Assert.Equal(HttpStatusCode.Created, createdResponse.StatusCode);
|
||||
var created = (await createdResponse.Content.ReadFromJsonAsync<Profile>())!;
|
||||
var path = $"/api/patients/{created.PatientId}";
|
||||
|
||||
using var response = await fixture.Client.PutAsJsonAsync(path, new
|
||||
{
|
||||
name = "Steffen Updated", contactInfo = "new@example.test"
|
||||
});
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
var expected = created with { Name = "Steffen Updated", ContactInfo = "new@example.test" };
|
||||
Assert.Equal(expected, await response.Content.ReadFromJsonAsync<Profile>());
|
||||
|
||||
await fixture.RestartHostsAsync();
|
||||
Assert.Equal(expected, await fixture.Client.GetFromJsonAsync<Profile>(path));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Updating_a_missing_patient_is_rejected_without_creating_a_profile()
|
||||
{
|
||||
await using var db = fixture.CreateDbContext();
|
||||
var countBefore = await db.Patients.CountAsync();
|
||||
var path = $"/api/patients/{Guid.NewGuid()}";
|
||||
using var response = await fixture.Client.PutAsJsonAsync(path, new
|
||||
{
|
||||
name = "Steffen Example", contactInfo = "new@example.test"
|
||||
});
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
Assert.Equal(countBefore, await db.Patients.CountAsync());
|
||||
using var retrieval = await fixture.Client.GetAsync(path);
|
||||
Assert.Equal(HttpStatusCode.NotFound, retrieval.StatusCode);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
public async Task Invalid_name_is_rejected_without_changing_the_profile(string? name)
|
||||
{
|
||||
using var createdResponse = await fixture.Client.PostAsJsonAsync("/api/patients", new
|
||||
{
|
||||
name = "Steffen Example", dateOfBirth = "1980-01-01", contactInfo = "old@example.test"
|
||||
});
|
||||
Assert.Equal(HttpStatusCode.Created, createdResponse.StatusCode);
|
||||
var created = (await createdResponse.Content.ReadFromJsonAsync<Profile>())!;
|
||||
var path = $"/api/patients/{created.PatientId}";
|
||||
using var response = await fixture.Client.PutAsJsonAsync(path, new
|
||||
{
|
||||
name, contactInfo = "new@example.test"
|
||||
});
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Equal(created, await fixture.Client.GetFromJsonAsync<Profile>(path));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user