125 lines
6.7 KiB
C#
125 lines
6.7 KiB
C#
using JobTrackerApi.Models;
|
|
using JobTrackerApi.Services;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.EntityFrameworkCore.Diagnostics;
|
|
using MySqlConnector;
|
|
using Xunit;
|
|
using Xunit.Abstractions;
|
|
|
|
namespace JobTrackerApi.MariaDb.Tests;
|
|
|
|
public sealed class ApplicationChecklistPersistenceTests(ITestOutputHelper output)
|
|
{
|
|
private const string Owner = "rd21-owner";
|
|
|
|
[Theory]
|
|
[InlineData("system-key")]
|
|
[InlineData("foreign-key")]
|
|
[InlineData("unrelated-unique")]
|
|
public async Task Seed_recovers_only_its_actual_unique_constraint(string scenario)
|
|
{
|
|
await using var database = await MariaDbDatabase.CreateAsync();
|
|
int jobId;
|
|
const string spoof = "IX_ApplicationChecklistItems_JobApplicationId_SystemKey";
|
|
await using (var seed = database.Context())
|
|
{
|
|
seed.Users.Add(new ApplicationUser { Id = Owner, UserName = spoof, NormalizedUserName = spoof });
|
|
var job = new JobApplication { OwnerUserId = Owner, Company = new Company { OwnerUserId = Owner, Name = "Synthetic checklist" }, Status = "Interview", Version = 7 };
|
|
seed.JobApplications.Add(job);
|
|
await seed.SaveChangesAsync();
|
|
jobId = job.Id;
|
|
seed.ApplicationChecklistItems.AddRange(
|
|
new ApplicationChecklistItem { OwnerUserId = Owner, JobApplicationId = jobId, SystemKey = "prepare-cv", AutoSignal = ChecklistSignalKeys.Cv,
|
|
IsSystemGenerated = true, Title = "Prepare CV", Category = ChecklistCategories.Preparation, Status = ChecklistStatuses.Dismissed },
|
|
new ApplicationChecklistItem { OwnerUserId = Owner, JobApplicationId = jobId, Title = "Manual decision", Category = ChecklistCategories.Custom,
|
|
Status = ChecklistStatuses.Done, SortOrder = 90 });
|
|
await seed.SaveChangesAsync();
|
|
}
|
|
var race = new Race();
|
|
await using var winner = database.Context(interceptor: new Gate(race, winner: true));
|
|
var losingGate = new Gate(race, winner: false, saveOtherFirst: scenario == "unrelated-unique");
|
|
await using var loser = database.Context(interceptor: losingGate);
|
|
if (scenario == "foreign-key")
|
|
loser.ApplicationChecklistItems.Add(new ApplicationChecklistItem { OwnerUserId = Owner, JobApplicationId = int.MaxValue,
|
|
Title = "Invalid parent must fail", Status = ChecklistStatuses.Done });
|
|
if (scenario == "unrelated-unique")
|
|
loser.Users.Add(new ApplicationUser { Id = "other-user", UserName = spoof, NormalizedUserName = spoof });
|
|
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30));
|
|
var winningRead = new ApplicationChecklistService(winner).GetAsync(Owner, jobId, timeout.Token);
|
|
var losingRead = new ApplicationChecklistService(loser).GetAsync(Owner, jobId, timeout.Token);
|
|
Assert.NotNull(await winningRead);
|
|
var observed = await Record.ExceptionAsync(async () => await losingRead);
|
|
var saveError = Assert.IsType<DbUpdateException>(losingGate.Failure);
|
|
var native = Assert.IsType<MySqlException>(saveError.InnerException);
|
|
output.WriteLine($"Server={database.ActualVersion}; scenario={scenario}; native={native.Number}; message={native.Message}; service={observed?.GetType().Name ?? "none"}");
|
|
if (scenario == "system-key")
|
|
{
|
|
Assert.Equal(1062, native.Number);
|
|
Assert.Null(observed);
|
|
var first = (await winningRead)!;
|
|
var second = (await losingRead)!;
|
|
Assert.Equal(first.Items.Select(item => item.Id).Order(), second.Items.Select(item => item.Id).Order());
|
|
Assert.Equal(ChecklistStatuses.Dismissed, second.Items.Single(item => item.SystemKey == "prepare-cv").Status);
|
|
Assert.Equal(ChecklistStatuses.Done, second.Items.Single(item => item.SystemKey == null).Status);
|
|
}
|
|
else
|
|
{
|
|
if (scenario == "unrelated-unique")
|
|
{
|
|
Assert.EndsWith("for key 'UserNameIndex'", native.Message);
|
|
Assert.Contains(spoof, native.Message, StringComparison.Ordinal);
|
|
}
|
|
Assert.IsType<DbUpdateException>(observed);
|
|
Assert.Equal(scenario == "foreign-key" ? 1452 : 1062, native.Number);
|
|
Assert.True(loser.ChangeTracker.Entries().Any(entry => entry.State == EntityState.Added));
|
|
}
|
|
await using var verify = database.Context();
|
|
Assert.Equal(15, await verify.ApplicationChecklistItems.CountAsync());
|
|
Assert.Equal(7, (await verify.JobApplications.SingleAsync()).Version);
|
|
Assert.Equal(1, await verify.Users.CountAsync());
|
|
}
|
|
|
|
private sealed class Race
|
|
{
|
|
private int _arrivals;
|
|
public TaskCompletionSource BothReady { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
public TaskCompletionSource Committed { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
public void Arrive() { if (Interlocked.Increment(ref _arrivals) == 2) BothReady.TrySetResult(); }
|
|
}
|
|
|
|
private sealed class Gate(Race race, bool winner, bool saveOtherFirst = false) : SaveChangesInterceptor
|
|
{
|
|
private bool _used;
|
|
public Exception? Failure { get; private set; }
|
|
public override async ValueTask<InterceptionResult<int>> SavingChangesAsync(DbContextEventData data, InterceptionResult<int> result, CancellationToken ct = default)
|
|
{
|
|
if (_used) return result;
|
|
_used = true;
|
|
race.Arrive();
|
|
await race.BothReady.Task.WaitAsync(ct);
|
|
if (!winner) await race.Committed.Task.WaitAsync(ct);
|
|
if (saveOtherFirst)
|
|
{
|
|
// Force the unrelated tracked write first; normal batch ordering hits checklist duplicates first.
|
|
var context = data.Context!;
|
|
var seeds = context.ChangeTracker.Entries<ApplicationChecklistItem>()
|
|
.Where(entry => entry.State == EntityState.Added).ToList();
|
|
foreach (var seed in seeds) seed.State = EntityState.Detached;
|
|
try { await context.SaveChangesAsync(ct); }
|
|
finally { foreach (var seed in seeds) context.Add(seed.Entity); }
|
|
}
|
|
return result;
|
|
}
|
|
public override ValueTask<int> SavedChangesAsync(SaveChangesCompletedEventData data, int result, CancellationToken ct = default)
|
|
{
|
|
if (winner) race.Committed.TrySetResult();
|
|
return ValueTask.FromResult(result);
|
|
}
|
|
public override Task SaveChangesFailedAsync(DbContextErrorEventData data, CancellationToken ct = default)
|
|
{
|
|
Failure = data.Exception;
|
|
return Task.CompletedTask;
|
|
}
|
|
}
|
|
}
|