Compare commits

..

1 Commits

Author SHA1 Message Date
cesnimda 2ec595db3b test: qualify concurrent preferences on MariaDB 2026-12-04 09:10:11 +01:00
5 changed files with 119 additions and 7 deletions
@@ -88,6 +88,7 @@ internal sealed class MariaDbDatabase : IAsyncDisposable
builder.Services.AddSingleton<IStartupReadiness, StartupReadiness>();
builder.Services.AddDbContext<JobTrackerContext>(options => database.Configure(options));
builder.Services.AddIdentityCore<ApplicationUser>().AddRoles<IdentityRole>().AddEntityFrameworkStores<JobTrackerContext>();
builder.Services.AddControllers();
database.App = builder.Build();
await database.App.InitializeJobTrackerAsync();
return database;
@@ -0,0 +1,111 @@
using System.Security.Claims;
using JobTrackerApi.Controllers;
using JobTrackerApi.Data;
using JobTrackerApi.Models;
using JobTrackerApi.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
using Xunit;
using Xunit.Abstractions;
namespace JobTrackerApi.MariaDb.Tests;
public sealed class PreferenceConcurrencyTests(ITestOutputHelper output)
{
[Fact]
public async Task Concurrent_language_and_notification_writes_preserve_the_winner_and_allow_a_fresh_retry()
{
await using var database = await MariaDbDatabase.CreateAsync();
await using (var seed = database.Context())
{
seed.Users.AddRange(
new ApplicationUser { Id = "preference-owner", UserName = "owner@example.test", UiLanguage = "en", EmailFollowUpRemindersEnabled = true },
new ApplicationUser { Id = "preference-other", UserName = "other@example.test", UiLanguage = "nb-NO", EmailFollowUpRemindersEnabled = false });
await seed.SaveChangesAsync();
}
await using var languageScope = database.App.Services.CreateAsyncScope();
await using var notificationScope = database.App.Services.CreateAsyncScope();
await using var otherScope = database.App.Services.CreateAsyncScope();
var language = LanguageController(languageScope.ServiceProvider, "preference-owner");
var notification = NotificationController(notificationScope.ServiceProvider, "preference-owner");
var otherLanguage = LanguageController(otherScope.ServiceProvider, "preference-other");
var otherNotification = NotificationController(otherScope.ServiceProvider, "preference-other");
// Model two requests that have read the same Identity version before either writes.
var languageSnapshot = await languageScope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>().GetUserAsync(language.User);
var notificationSnapshot = await notificationScope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>().GetUserAsync(notification.User);
Assert.NotNull(languageSnapshot);
Assert.NotNull(notificationSnapshot);
Assert.NotSame(languageSnapshot, notificationSnapshot);
var originalStamp = languageSnapshot.ConcurrencyStamp;
Assert.Equal(originalStamp, notificationSnapshot.ConcurrencyStamp);
var languageWrite = language.UpdateLanguagePreference(new("nb-NO"));
var notificationWrite = notification.Put(new(false));
var otherWrite = otherLanguage.UpdateLanguagePreference(new("en"));
await Task.WhenAll(languageWrite, notificationWrite, otherWrite);
Assert.IsType<NoContentResult>(await otherWrite);
Assert.IsType<BadRequestObjectResult>(await otherLanguage.UpdateLanguagePreference(new("fr-FR")));
Assert.IsType<OkObjectResult>((await otherNotification.Put(new(true))).Result);
var languageWon = await languageWrite is NoContentResult;
if (languageWon)
{
var error = Assert.IsType<ObjectResult>((await notificationWrite).Result);
Assert.Equal(StatusCodes.Status500InternalServerError, error.StatusCode);
}
else
{
var error = Assert.IsType<BadRequestObjectResult>(await languageWrite);
Assert.Contains(new IdentityErrorDescriber().ConcurrencyFailure().Description, Assert.IsType<string>(error.Value));
Assert.IsType<OkObjectResult>((await notificationWrite).Result);
}
await using (var read = database.Context())
{
var owner = await read.Users.AsNoTracking().SingleAsync(user => user.Id == "preference-owner");
Assert.Equal(languageWon ? "nb-NO" : "en", owner.UiLanguage);
Assert.Equal(languageWon, owner.EmailFollowUpRemindersEnabled);
Assert.NotEqual(originalStamp, owner.ConcurrencyStamp);
}
await using var retryScope = database.App.Services.CreateAsyncScope();
if (languageWon)
Assert.IsType<OkObjectResult>((await NotificationController(retryScope.ServiceProvider, "preference-owner").Put(new(false))).Result);
else
Assert.IsType<NoContentResult>(await LanguageController(retryScope.ServiceProvider, "preference-owner").UpdateLanguagePreference(new("nb-NO")));
await using var reload = database.Context();
var users = await reload.Users.AsNoTracking().Where(user => user.Id.StartsWith("preference-")).OrderBy(user => user.Id).ToListAsync();
Assert.Collection(users,
other => { Assert.Equal("preference-other", other.Id); Assert.Equal("en", other.UiLanguage); Assert.True(other.EmailFollowUpRemindersEnabled); },
owner => { Assert.Equal("preference-owner", owner.Id); Assert.Equal("nb-NO", owner.UiLanguage); Assert.False(owner.EmailFollowUpRemindersEnabled); });
output.WriteLine($"MariaDB {database.ActualVersion}: {(languageWon ? "language" : "notification")} won the overlapping writes; fresh retry preserved both preferences and the other owner's independent writes.");
}
private static AuthController LanguageController(IServiceProvider services, string owner) => new(
services.GetRequiredService<IConfiguration>(), services.GetRequiredService<UserManager<ApplicationUser>>(),
Mock.Of<ITokenService>(), Mock.Of<IAppEmailSender>(), Mock.Of<IGoogleTokenValidator>(), Mock.Of<IMicrosoftTokenValidator>(),
NullLogger<AuthController>.Instance, Mock.Of<ITwoFactorPendingTokenService>(), services.GetRequiredService<JobTrackerContext>(),
externalOrigin: ExternalOrigin.Parse("http://localhost:3300", production: false))
{ ControllerContext = Principal(services, owner) };
private static NotificationSettingsController NotificationController(IServiceProvider services, string owner) => new(
services.GetRequiredService<UserManager<ApplicationUser>>()) { ControllerContext = Principal(services, owner) };
private static ControllerContext Principal(IServiceProvider services, string owner) => new()
{
HttpContext = new DefaultHttpContext
{
RequestServices = services,
User = new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, owner)], "test")),
},
};
}
+3 -3
View File
@@ -1075,9 +1075,9 @@ tqdm==4.70.0 \
# via
# huggingface-hub
# transformers
transformers==5.10.4 \
--hash=sha256:8c5b99b141b53619435a76629b0284f04d27ff46d788b463fc0ecb23b8ff130e \
--hash=sha256:de37741509e64ccb88f7f5708beaf5b1914df447f5fe659f9c0fd95950413168
transformers==5.10.0 \
--hash=sha256:206c54d6d992bc35fef90f1252ac3f2746cdf549928b76e7c8c4f182684cee60 \
--hash=sha256:eae143e46d8e521da604bc4fdc45af7dd90e96eacbbc27f68d2754150aa5175a
# via -r requirements.txt
truststore==0.10.5 \
--hash=sha256:30d36967ccaded5cbb38d602c433f53600036c79d502f4533a49b60a03bbefcd \
+3 -3
View File
@@ -1049,9 +1049,9 @@ tqdm==4.70.0 \
# via
# huggingface-hub
# transformers
transformers==5.10.4 \
--hash=sha256:8c5b99b141b53619435a76629b0284f04d27ff46d788b463fc0ecb23b8ff130e \
--hash=sha256:de37741509e64ccb88f7f5708beaf5b1914df447f5fe659f9c0fd95950413168
transformers==5.10.0 \
--hash=sha256:206c54d6d992bc35fef90f1252ac3f2746cdf549928b76e7c8c4f182684cee60 \
--hash=sha256:eae143e46d8e521da604bc4fdc45af7dd90e96eacbbc27f68d2754150aa5175a
# via -r requirements.txt
typer==0.27.3 \
--hash=sha256:d0396f770a560ab1b0a8504e13b5f254b728cedb05c61cf0359e944e50ce8901 \
+1 -1
View File
@@ -1,7 +1,7 @@
fastapi==0.141.1
starlette==1.6.0
uvicorn[standard]==0.34.0
transformers==5.10.4
transformers==5.10.0
cachetools==5.5.2
pydantic==2.10.6
torch==2.13.0