Implement US-01 patient profile creation and retrieval

This commit is contained in:
Steffen committed 2026-09-30 22:34:44 +02:00
1 parent d6f79a91c0
commit eb2cf2e54a
30 files changed
+792

No files matched your search

@@ -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);
}
}
@@ -0,0 +1,79 @@
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 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.ConfigureKestrel(options => options.Listen(IPAddress.Loopback, 0));
builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(
new Dictionary<string, string?> { ["ConnectionStrings:PatientDatabase"] = ConnectionString }));
});
service.UseKestrel(0);
using var serviceClient = service.CreateClient();
gateway = new WebApplicationFactory<ApiGateway.Program>().WithWebHostBuilder(builder =>
builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(
new Dictionary<string, string?> { ["Services:PatientProfile:BaseUrl"] = serviceClient.BaseAddress!.ToString() })));
Client = gateway.CreateClient();
}
public async Task RestartHostsAsync()
{
Client.Dispose();
await gateway!.DisposeAsync();
await service!.DisposeAsync();
StartHosts();
}
public async Task DisposeAsync()
{
Client?.Dispose();
if (gateway is not null) await gateway.DisposeAsync();
if (service is not null) await service.DisposeAsync();
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();
}
}
@@ -0,0 +1,17 @@
<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>
</Project>