using System.Net; using System.Net.Http.Headers; using System.Net.Http.Json; using HealthApp.TestSupport; using Microsoft.EntityFrameworkCore; using Npgsql; using PatientProfile.AcceptanceTests; using Xunit; namespace HealthApp.AcceptanceTests; public sealed class ProfileLifecycleTests(PatientApiFixture fixture) : IClassFixture { [Fact] public async Task Concurrent_creation_lost_response_and_restart_preserve_one_accessible_profile() { var token=await AuthenticatedTestClient.LoginAsync(fixture.RawClient,"test-200"); async Task Create(){using var r=new HttpRequestMessage(HttpMethod.Post,"/api/patients"){Content=JsonContent.Create(new{name="Concurrent",dateOfBirth="1980-01-01"})};r.Headers.Authorization=new AuthenticationHeaderValue("Bearer",token);return await fixture.RawClient.SendAsync(r);} var responses=await Task.WhenAll(Create(),Create()); Assert.Single(responses,r=>r.StatusCode==HttpStatusCode.Created);Assert.Single(responses,r=>r.StatusCode==HttpStatusCode.Conflict); using var retry=await Create();Assert.Equal(HttpStatusCode.Conflict,retry.StatusCode); await using(var db=fixture.CreateDbContext()){Assert.Equal(1,await db.Patients.CountAsync(p=>p.AccountId=="test-200"));} await fixture.RestartHostsAsync();using var read=new HttpRequestMessage(HttpMethod.Get,"/api/patients/me");read.Headers.Authorization=new AuthenticationHeaderValue("Bearer",token); using var found=await fixture.RawClient.SendAsync(read);Assert.Equal(HttpStatusCode.OK,found.StatusCode); foreach(var response in responses)response.Dispose(); } [Fact] public async Task Runtime_role_cannot_create_or_drop_health_objects() { await using var c=new NpgsqlConnection(fixture.RuntimeConnectionString);await c.OpenAsync(); var e=await Assert.ThrowsAsync(()=>new NpgsqlCommand("CREATE TABLE profile.forbidden(id integer)",c).ExecuteNonQueryAsync());Assert.Equal("42501",e.SqlState); e=await Assert.ThrowsAsync(()=>new NpgsqlCommand("DROP TABLE profile.patient",c).ExecuteNonQueryAsync());Assert.Equal("42501",e.SqlState); } }