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>
This commit is contained in:
Paul Schneider 2026-11-12 17:55:15 +00:00
commit bf17c5be5d
Signed by: notazof
GPG key ID: AD4B9B545FBD7D12
6 changed files with 190 additions and 6 deletions

View file

@ -6,6 +6,10 @@
### Added ### 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. * [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. * [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.

View file

@ -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. il ne supprime ni ces prerequis ni les exclusions d'autres traits.
Ajouter `--list-tests` pour verifier la selection sans executer les tests. 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 ## Isolation des tests PostIt
L'assemblee `src/PostIt/PostIt.Tests` execute ses collections xUnit sans L'assemblee `src/PostIt/PostIt.Tests` execute ses collections xUnit sans

View file

@ -10,7 +10,6 @@ namespace Yavsc.ApiControllers.Administration;
[Authorize("AdministratorOnly")] [Authorize("AdministratorOnly")]
[ResourceUsageExempt] [ResourceUsageExempt]
[Route(Constants.APIPrefix + "/" + Constants.ResourceUsagePath + "/admin")] [Route(Constants.APIPrefix + "/" + Constants.ResourceUsagePath + "/admin")]
[Produces("application/json")]
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)] [ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
public sealed class ResourceUsageReliefApiController( public sealed class ResourceUsageReliefApiController(
IResourceUsageService usage, ILogger<ResourceUsageReliefApiController> logger) : ControllerBase IResourceUsageService usage, ILogger<ResourceUsageReliefApiController> logger) : ControllerBase
@ -18,12 +17,12 @@ public sealed class ResourceUsageReliefApiController(
[HttpPost("{userId}/erase")] [HttpPost("{userId}/erase")]
[EndpointSummary("Effacer des points de consommation d’un utilisateur ayant atteint sa limite")] [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.")] [EndpointDescription("Conserve les compteurs techniques, refuse les montants supérieurs à la consommation et les confirmations périmées, sans crédit futur.")]
[ProducesResponseType<ResourceUsageSummary>(200)] [ProducesResponseType<ResourceUsageSummary>(200, "application/json")]
[ProducesResponseType<ProblemDetails>(400)] [ProducesResponseType<ProblemDetails>(400, "application/problem+json")]
[ProducesResponseType(401)] [ProducesResponseType(401)]
[ProducesResponseType(403)] [ProducesResponseType(403)]
[ProducesResponseType<ProblemDetails>(404)] [ProducesResponseType<ProblemDetails>(404, "application/problem+json")]
[ProducesResponseType<ProblemDetails>(409)] [ProducesResponseType<ProblemDetails>(409, "application/problem+json")]
public async Task<ActionResult<ResourceUsageSummary>> Erase( public async Task<ActionResult<ResourceUsageSummary>> Erase(
string userId, EraseResourceUsageRequest request, CancellationToken ct) string userId, EraseResourceUsageRequest request, CancellationToken ct)
{ {

View file

@ -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<ApiWebServerFixture>
{
[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<ApplicationDbContext>();
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<ApplicationDbContext>();
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<ApplicationDbContext>();
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();
}
}
}
}
}

View file

@ -1,7 +1,9 @@
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.Data.Sqlite; using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens; using Microsoft.IdentityModel.Tokens;
using Npgsql; using Npgsql;
@ -375,7 +377,44 @@ public sealed class ApiWebServerFixture : WebHostFixture
return; 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<string>();
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<IRelationalDatabaseCreator>().CreateTables();
} }
public void ResetAndSeedRdvQueryGraph() public void ResetAndSeedRdvQueryGraph()
@ -491,6 +530,46 @@ public sealed class ApiWebServerFixture : WebHostFixture
db.HairPrestation.AddRange(prestation1, prestation2, prestation3); db.HairPrestation.AddRange(prestation1, prestation2, prestation3);
db.SaveChanges(); 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<HairPrestationCollectionItem>
{
new() { PrestationId = prestation1.Id, Prestation = prestation1 },
new() { PrestationId = prestation2.Id, Prestation = prestation2 },
},
Status = Yavsc.QueryStatus.Inserted,
});
db.SaveChanges();
} }
public override void Dispose() public override void Dispose()

View file

@ -76,6 +76,7 @@ public sealed class ResourceUsageReliefApiTests(ApiWebServerFixture fixture) : I
var request = new EraseResourceUsageRequest { Points = 200.12545678m, ExpectedCredits = 0m }; var request = new EraseResourceUsageRequest { Points = 200.12545678m, ExpectedCredits = 0m };
using var response = await admin.PostAsJsonAsync($"{Root}/{id}/erase", request, Ct); using var response = await admin.PostAsJsonAsync($"{Root}/{id}/erase", request, Ct);
Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
Assert.True(response.Headers.CacheControl?.NoStore); Assert.True(response.Headers.CacheControl?.NoStore);
var summary = await response.Content.ReadFromJsonAsync<ResourceUsageSummary>(Ct); var summary = await response.Content.ReadFromJsonAsync<ResourceUsageSummary>(Ct);
Assert.NotNull(summary); 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); using var response = await client.PostAsync($"{Root}/{id}/erase", body, Ct);
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
var problem = await response.Content.ReadFromJsonAsync<Microsoft.AspNetCore.Mvc.ProblemDetails>(Ct);
Assert.NotNull(problem);
Assert.Equal((int)response.StatusCode, problem.Status);
Assert.False(string.IsNullOrWhiteSpace(problem.Title));
using var scope = fixture.Services.CreateScope(); using var scope = fixture.Services.CreateScope();
Assert.Equal(0m, (await scope.ServiceProvider.GetRequiredService<ApplicationDbContext>() Assert.Equal(0m, (await scope.ServiceProvider.GetRequiredService<ApplicationDbContext>()
.ResourceUsageRecords.SingleAsync(r => r.UserId == id, Ct)).CreditPoints); .ResourceUsageRecords.SingleAsync(r => r.UserId == id, Ct)).CreditPoints);
@ -128,6 +133,10 @@ public sealed class ResourceUsageReliefApiTests(ApiWebServerFixture fixture) : I
}, Ct); }, Ct);
Assert.Equal(status, response.StatusCode); Assert.Equal(status, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
var problem = await response.Content.ReadFromJsonAsync<Microsoft.AspNetCore.Mvc.ProblemDetails>(Ct);
Assert.NotNull(problem);
Assert.Equal((int)status, problem.Status);
Assert.False(string.IsNullOrWhiteSpace(problem.Title));
} }
[Fact] [Fact]
@ -152,5 +161,10 @@ public sealed class ResourceUsageReliefApiTests(ApiWebServerFixture fixture) : I
Assert.False(string.IsNullOrWhiteSpace(operation.GetProperty("summary").GetString())); Assert.False(string.IsNullOrWhiteSpace(operation.GetProperty("summary").GetString()));
foreach (var status in new[] { "200", "400", "401", "403", "404", "409" }) foreach (var status in new[] { "200", "400", "401", "403", "404", "409" })
Assert.True(operation.GetProperty("responses").TryGetProperty(status, out _)); 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 _));
} }
} }