From bf17c5be5d6b01dd5d44e5a9c0e48d4ae0fdddb9 Mon Sep 17 00:00:00 2001 From: Paul Schneider Date: Thu, 12 Nov 2026 17:55:15 +0000 Subject: [PATCH] fix(api): restore SQLite test isolation and relief problem responses Recreate the anchored SQLite test schema before seeding, restore haircut command seeds, and preserve problem+json error responses with matching OpenAPI metadata. Add regression coverage for repeated resets and response contracts. Verified all 227 API SQLite tests pass. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- CHANGELOG.md | 4 + doc/testing.md | 15 ++++ .../ResourceUsageReliefApiController.cs | 9 +-- .../ApiWebServerFixtureTests.cs | 73 +++++++++++++++++ .../Fixtures/ApiWebServerFixture.cs | 81 ++++++++++++++++++- .../ResourceUsageReliefApiTests.cs | 14 ++++ 6 files changed, 190 insertions(+), 6 deletions(-) create mode 100644 src/test/Yavsc.Api.Tests/ApiWebServerFixtureTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 9be4be15f..6aa88a585 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,10 @@ ### Added +* [Yavsc.Api] Preserve `application/problem+json` for resource-usage relief errors instead of overriding it with a JSON-only Produces attribute; document success/error media types in OpenAPI and verify error payloads. Restore the haircut and grouped-haircut commands removed from the test seed while retaining its three catalog prestations, with repeated-reset coverage. + +* [Yavsc.Api/Tests] Reset the anchored shared SQLite in-memory database by dropping and recreating its tables before seeding, avoiding duplicate user emails across tests. Restore foreign-key enforcement after cleanup and cover repeated resets with a regression test; leave PostgreSQL cleanup unchanged. + * [Yavsc/Tests] Apply the class-level `Category=non-reg` trait to all test classes in Yavsc.Org.Tests, Yavsc.Api.Tests, Yavsc.Blogs.Tests and Yavsc.Server.Tests, including inherited tests, while preserving existing traits. Remove the empty Services class. * [PostIt/Tests] Add an xUnit collection fixture owning a headless UI session and its thread, with shared window creation, layout, closing and binding cleanup even after failures. Migrate the subscription page binding test as a pilot; retain per-dispatch application isolation and the parallelism guard during coexistence with legacy headless tests. diff --git a/doc/testing.md b/doc/testing.md index 6be3861e8..f1ed2bbd0 100644 --- a/doc/testing.md +++ b/doc/testing.md @@ -51,6 +51,21 @@ aussi les tests d'integration qui requierent leurs services/configurations ; il ne supprime ni ces prerequis ni les exclusions d'autres traits. Ajouter `--list-tests` pour verifier la selection sans executer les tests. +### Remise a zero SQLite des tests API + +`ApiWebServerFixture` conserve une connexion d'ancrage vers la base SQLite +en memoire partagee. `EnsureDeleted()` ne vide pas cette base tant que cette +connexion reste ouverte. Le reset supprime donc les tables, puis recree +explicitement le schema avant le peuplement ; `EnsureCreated()` seul ne suffit +pas car SQLite conserve sa table interne `sqlite_sequence`. +Les cles etrangeres sont desactivees uniquement pendant la suppression et +reactivees en `finally`. Le nettoyage PostgreSQL reste distinct. + +`ResetAndSeedHaircutGraph()` inclut le catalogue de trois prestations, une +commande `brush` et une commande groupee `mbrush`, toutes deux pour Alice. +Les tests de facturation s'appuient sur ces commandes initiales ; les tests +CRUD creent et manipulent leurs propres commandes par identifiant. + ## Isolation des tests PostIt L'assemblee `src/PostIt/PostIt.Tests` execute ses collections xUnit sans diff --git a/src/Yavsc.Api/Controllers/Administration/ResourceUsageReliefApiController.cs b/src/Yavsc.Api/Controllers/Administration/ResourceUsageReliefApiController.cs index 30e9bf626..f12030f75 100644 --- a/src/Yavsc.Api/Controllers/Administration/ResourceUsageReliefApiController.cs +++ b/src/Yavsc.Api/Controllers/Administration/ResourceUsageReliefApiController.cs @@ -10,7 +10,6 @@ namespace Yavsc.ApiControllers.Administration; [Authorize("AdministratorOnly")] [ResourceUsageExempt] [Route(Constants.APIPrefix + "/" + Constants.ResourceUsagePath + "/admin")] -[Produces("application/json")] [ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)] public sealed class ResourceUsageReliefApiController( IResourceUsageService usage, ILogger logger) : ControllerBase @@ -18,12 +17,12 @@ public sealed class ResourceUsageReliefApiController( [HttpPost("{userId}/erase")] [EndpointSummary("Effacer des points de consommation d’un utilisateur ayant atteint sa limite")] [EndpointDescription("Conserve les compteurs techniques, refuse les montants supérieurs à la consommation et les confirmations périmées, sans crédit futur.")] - [ProducesResponseType(200)] - [ProducesResponseType(400)] + [ProducesResponseType(200, "application/json")] + [ProducesResponseType(400, "application/problem+json")] [ProducesResponseType(401)] [ProducesResponseType(403)] - [ProducesResponseType(404)] - [ProducesResponseType(409)] + [ProducesResponseType(404, "application/problem+json")] + [ProducesResponseType(409, "application/problem+json")] public async Task> Erase( string userId, EraseResourceUsageRequest request, CancellationToken ct) { diff --git a/src/test/Yavsc.Api.Tests/ApiWebServerFixtureTests.cs b/src/test/Yavsc.Api.Tests/ApiWebServerFixtureTests.cs new file mode 100644 index 000000000..9bfaf1fa2 --- /dev/null +++ b/src/test/Yavsc.Api.Tests/ApiWebServerFixtureTests.cs @@ -0,0 +1,73 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Yavsc.Api.Test.Fixtures; +using Yavsc.Models; + +namespace Yavsc.Api.Test; + +[Trait("Category", "non-reg")] +[Collection("Yavsc Api")] +public sealed class ApiWebServerFixtureTests(ApiWebServerFixture fixture) : IClassFixture +{ + [Fact] + public void Haircut_reset_seeds_catalog_and_both_command_types() + { + for (var reset = 0; reset < 2; reset++) + { + fixture.ResetAndSeedHaircutGraph(); + using var scope = fixture.Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + Assert.Equal(3, db.HairPrestation.Count()); + var haircut = Assert.Single(db.HairCutQueries.Include(query => query.Prestation)); + Assert.Equal("brush", haircut.ActivityCode); + Assert.Equal("alice", haircut.PerformerId); + Assert.NotNull(haircut.Prestation); + var grouped = Assert.Single(db.HairMultiCutQueries.Include(query => query.Prestations)); + Assert.Equal("mbrush", grouped.ActivityCode); + Assert.Equal("alice", grouped.PerformerId); + Assert.Equal(2, grouped.Prestations.Count); + } + } + + [Fact] + public void Repeated_reset_removes_previous_data_and_reseeds_unique_users() + { + fixture.ResetAndSeedActivityGraph(); + using (var scope = fixture.Services.CreateScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + db.Users.Add(new ApplicationUser + { + Id = "previous-test-user", + UserName = "previous-test-user", + Email = "previous-test-user@example.test", + }); + db.SaveChanges(); + } + + for (var reset = 0; reset < 2; reset++) + { + fixture.ResetAndSeedActivityGraph(); + using var scope = fixture.Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + Assert.Equal(new[] { "alice", "bob" }, db.Users.OrderBy(user => user.Id).Select(user => user.Id).ToArray()); + Assert.Equal(2, db.Performers.Count()); + Assert.Single(db.Locations); + + if (db.Database.IsSqlite()) + { + db.Database.OpenConnection(); + try + { + using var command = db.Database.GetDbConnection().CreateCommand(); + command.CommandText = "PRAGMA foreign_keys;"; + Assert.Equal(1L, command.ExecuteScalar()); + } + finally + { + db.Database.CloseConnection(); + } + } + } + } +} diff --git a/src/test/Yavsc.Api.Tests/Fixtures/ApiWebServerFixture.cs b/src/test/Yavsc.Api.Tests/Fixtures/ApiWebServerFixture.cs index 0e807de19..8b1a5fcf5 100644 --- a/src/test/Yavsc.Api.Tests/Fixtures/ApiWebServerFixture.cs +++ b/src/test/Yavsc.Api.Tests/Fixtures/ApiWebServerFixture.cs @@ -1,7 +1,9 @@ using Microsoft.AspNetCore.Builder; using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Storage; using Microsoft.Extensions.DependencyInjection; using Microsoft.IdentityModel.Tokens; using Npgsql; @@ -375,7 +377,44 @@ public sealed class ApiWebServerFixture : WebHostFixture return; } - db.Database.EnsureDeleted(); + // EnsureDeleted cannot clear a shared in-memory database kept alive by the anchor. + db.Database.OpenConnection(); + try + { + using var command = db.Database.GetDbConnection().CreateCommand(); + command.CommandText = "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT GLOB 'sqlite_*';"; + var tables = new List(); + using (var reader = command.ExecuteReader()) + { + while (reader.Read()) + tables.Add(reader.GetString(0)); + } + command.CommandText = "PRAGMA foreign_keys = OFF;"; + command.ExecuteNonQuery(); + try + { + using var transaction = db.Database.BeginTransaction(); + command.Transaction = transaction.GetDbTransaction(); + foreach (var table in tables) + { + command.CommandText = $"DROP TABLE \"{table.Replace("\"", "\"\"")}\";"; + command.ExecuteNonQuery(); + } + transaction.Commit(); + } + finally + { + command.Transaction = null; + command.CommandText = "PRAGMA foreign_keys = ON;"; + command.ExecuteNonQuery(); + } + } + finally + { + db.Database.CloseConnection(); + } + // SQLite retains sqlite_sequence, so EnsureCreated would incorrectly see an existing schema. + db.GetService().CreateTables(); } public void ResetAndSeedRdvQueryGraph() @@ -491,6 +530,46 @@ public sealed class ApiWebServerFixture : WebHostFixture db.HairPrestation.AddRange(prestation1, prestation2, prestation3); db.SaveChanges(); + + db.HairCutQueries.Add(new HairCutQuery + { + ActivityCode = "brush", + ClientId = "alice", + PerformerId = "alice", + Consent = true, + UserCreated = "alice", + UserModified = "alice", + DateCreated = DateTime.UtcNow, + DateModified = DateTime.UtcNow, + EventDate = DateTime.UtcNow.AddDays(3), + Location = location, + PrestationId = prestation1.Id, + Prestation = prestation1, + AdditionalInfo = "Coupe test", + Status = Yavsc.QueryStatus.Inserted, + Description = "Haircut seed", + }); + + db.HairMultiCutQueries.Add(new HairMultiCutQuery + { + ActivityCode = "mbrush", + ClientId = "alice", + PerformerId = "alice", + Consent = true, + UserCreated = "alice", + UserModified = "alice", + DateCreated = DateTime.UtcNow, + DateModified = DateTime.UtcNow, + EventDate = DateTime.UtcNow.AddDays(4), + Location = location, + Prestations = new List + { + new() { PrestationId = prestation1.Id, Prestation = prestation1 }, + new() { PrestationId = prestation2.Id, Prestation = prestation2 }, + }, + Status = Yavsc.QueryStatus.Inserted, + }); + db.SaveChanges(); } public override void Dispose() diff --git a/src/test/Yavsc.Api.Tests/ResourceUsageReliefApiTests.cs b/src/test/Yavsc.Api.Tests/ResourceUsageReliefApiTests.cs index bc1a768e4..3c40b83c3 100644 --- a/src/test/Yavsc.Api.Tests/ResourceUsageReliefApiTests.cs +++ b/src/test/Yavsc.Api.Tests/ResourceUsageReliefApiTests.cs @@ -76,6 +76,7 @@ public sealed class ResourceUsageReliefApiTests(ApiWebServerFixture fixture) : I var request = new EraseResourceUsageRequest { Points = 200.12545678m, ExpectedCredits = 0m }; using var response = await admin.PostAsJsonAsync($"{Root}/{id}/erase", request, Ct); Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType); Assert.True(response.Headers.CacheControl?.NoStore); var summary = await response.Content.ReadFromJsonAsync(Ct); Assert.NotNull(summary); @@ -106,6 +107,10 @@ public sealed class ResourceUsageReliefApiTests(ApiWebServerFixture fixture) : I using var response = await client.PostAsync($"{Root}/{id}/erase", body, Ct); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + var problem = await response.Content.ReadFromJsonAsync(Ct); + Assert.NotNull(problem); + Assert.Equal((int)response.StatusCode, problem.Status); + Assert.False(string.IsNullOrWhiteSpace(problem.Title)); using var scope = fixture.Services.CreateScope(); Assert.Equal(0m, (await scope.ServiceProvider.GetRequiredService() .ResourceUsageRecords.SingleAsync(r => r.UserId == id, Ct)).CreditPoints); @@ -128,6 +133,10 @@ public sealed class ResourceUsageReliefApiTests(ApiWebServerFixture fixture) : I }, Ct); Assert.Equal(status, response.StatusCode); Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + var problem = await response.Content.ReadFromJsonAsync(Ct); + Assert.NotNull(problem); + Assert.Equal((int)status, problem.Status); + Assert.False(string.IsNullOrWhiteSpace(problem.Title)); } [Fact] @@ -152,5 +161,10 @@ public sealed class ResourceUsageReliefApiTests(ApiWebServerFixture fixture) : I Assert.False(string.IsNullOrWhiteSpace(operation.GetProperty("summary").GetString())); foreach (var status in new[] { "200", "400", "401", "403", "404", "409" }) Assert.True(operation.GetProperty("responses").TryGetProperty(status, out _)); + Assert.True(operation.GetProperty("responses").GetProperty("200").GetProperty("content") + .TryGetProperty("application/json", out _)); + foreach (var status in new[] { "400", "404", "409" }) + Assert.True(operation.GetProperty("responses").GetProperty(status).GetProperty("content") + .TryGetProperty("application/problem+json", out _)); } }