From d516e943461d472c2e42131b78375eb05e01dc67 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Tue, 17 Nov 2026 10:36:54 +0200 Subject: [PATCH] Adds integration tests for EventualConsistencyMiddleware transaction atomicity --- .../EventualConsistencyMiddlewareTests.cs | 209 ++++++++++++++++++ .../Setup/DomainEventPublicationProbe.cs | 78 +++++++ .../Common/Setup/DomainEventsQueueProbe.cs | 170 ++++++++++++++ .../Setup/EventualConsistencyApiFactory.cs | 79 +++++++ .../Common/Setup/LuminaApiFactory.cs | 16 ++ .../Common/Setup/ProbingDomainEventsQueue.cs | 55 +++++ ...ecordingFavoriteAddedDomainEventHandler.cs | 51 +++++ .../Common/Setup/TransactionProbe.cs | 78 +++++++ .../Setup/TransactionProbeInterceptor.cs | 63 ++++++ 9 files changed, 799 insertions(+) create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Middlewares/EventualConsistencyMiddlewareTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/DomainEventPublicationProbe.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/DomainEventsQueueProbe.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/EventualConsistencyApiFactory.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/ProbingDomainEventsQueue.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/RecordingFavoriteAddedDomainEventHandler.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/TransactionProbe.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/TransactionProbeInterceptor.cs diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Middlewares/EventualConsistencyMiddlewareTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Middlewares/EventualConsistencyMiddlewareTests.cs new file mode 100644 index 00000000..c0c2d2df --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Middlewares/EventualConsistencyMiddlewareTests.cs @@ -0,0 +1,209 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Common.Middlewares; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Common.Middlewares; + +/// +/// Contains integration tests for the class through the real HTTP pipeline. +/// +[ExcludeFromCodeCoverage] +public class EventualConsistencyMiddlewareTests : IClassFixture, IAsyncLifetime +{ + private const string FAVORITES_PATH = "/api/v1/users/me/favorites"; + private const string LOGIN_PATH = "/api/v1/auth/login"; + + private static readonly TimeSpan s_probeTimeout = TimeSpan.FromSeconds(10); + + private HttpClient _client; + private readonly EventualConsistencyApiFactory _apiFactory; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly BookEntityFixture _bookEntityFixture = new(); + private readonly List _seededLibraryIds = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory with observable transactions and domain events. + public EventualConsistencyMiddlewareTests(EventualConsistencyApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + } + + /// + /// Initializes the authenticated API client, and clears the probes after the login request completed. + /// + public async Task InitializeAsync() + { + _apiFactory.ResetProbes(); + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + // The login request runs through the same middleware, so its dequeue of the response completion must finish before the probes observe the test request. + await _apiFactory.QueueProbe.WaitForDequeueAsync(LOGIN_PATH, s_probeTimeout); + _apiFactory.ResetProbes(); + } + + [Fact] + public async Task AddFavorite_WhenTheResponseSucceeds_ShouldPublishTheQueuedEventAfterCommittingTheTransaction() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid bookId = await SeedBookAsync(userId); + _apiFactory.ResetProbes(); + _apiFactory.QueueProbe.ShouldBlockOnEnqueue = true; + Task responseTask; + + try + { + // Act + // The POST runs on a dedicated task, so that a blocking domain event queue can never block the test thread that must release it. + responseTask = Task.Run(async () => await _client.PostAsJsonAsync(FAVORITES_PATH, new { mediaKind = "Book", mediaItemId = bookId })); + await _apiFactory.QueueProbe.WaitForEnqueueAsync(s_probeTimeout); + + // Assert + // The event is queued while the endpoint still runs, so it must not be published yet. + Assert.Equal(0, _apiFactory.PublicationProbe.PublicationCount); + } + finally + { + _apiFactory.QueueProbe.ReleaseEnqueue(); + _apiFactory.QueueProbe.ShouldBlockOnEnqueue = false; + } + + HttpResponseMessage response = await responseTask; + await _apiFactory.PublicationProbe.WaitForPublicationAsync(s_probeTimeout); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.True(_apiFactory.PublicationProbe.WasFavoriteVisible); + Assert.Equal(1, _apiFactory.QueueProbe.EnqueueCount); + Assert.Equal(1, _apiFactory.QueueProbe.DequeueCount); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.True(await dbContext.Favorites.AnyAsync(favorite => favorite.UserId == userId && favorite.MediaItemId == bookId)); + } + + [Fact] + public async Task AddFavorite_WhenTheRequestFailsAfterQueueingTheEvent_ShouldRollBackTheTransactionAndNotPublishTheEvent() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid bookId = await SeedBookAsync(userId); + _apiFactory.ResetProbes(); + _apiFactory.QueueProbe.ShouldThrowOnEnqueue = true; + + try + { + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync(FAVORITES_PATH, new { mediaKind = "Book", mediaItemId = bookId }); + await _apiFactory.TransactionProbe.WaitForRollbackAsync(FAVORITES_PATH, s_probeTimeout); + + // Assert + Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); + Assert.Equal(1, _apiFactory.QueueProbe.EnqueueCount); + Assert.Equal(0, _apiFactory.QueueProbe.DequeueCount); + Assert.Equal(0, _apiFactory.QueueProbe.GetDequeueAttemptCount(FAVORITES_PATH)); + Assert.Equal(0, _apiFactory.PublicationProbe.PublicationCount); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.False(await dbContext.Favorites.AnyAsync(favorite => favorite.UserId == userId && favorite.MediaItemId == bookId)); + } + finally + { + _apiFactory.QueueProbe.ShouldThrowOnEnqueue = false; + } + } + + [Fact] + public async Task GetFavorites_WhenCalled_ShouldRunThroughTheEventualConsistencyMiddleware() + { + // Act + HttpResponseMessage response = await _client.GetAsync(FAVORITES_PATH); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + // The middleware dequeues the events only after committing a successful request, so a dequeue attempt for this path proves the pipeline ran through it. + await _apiFactory.QueueProbe.WaitForDequeueAsync(FAVORITES_PATH, s_probeTimeout); + Assert.True(_apiFactory.QueueProbe.GetDequeueAttemptCount(FAVORITES_PATH) > 0); + } + + /// + /// Seeds a book of a book library owned by . + /// + /// The Id of the user that owns the seeded library. + /// The Id of the seeded book. + private async Task SeedBookAsync(Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.CreateVersion7(); + dbContext.Libraries.Add(_libraryEntityFixture.Create( + id: libraryId, + userId: userId, + title: $"Eventual Consistency Library-{Guid.NewGuid():N}", + libraryType: LibraryType.EBook, + contentLocations: [])); + Guid bookId = Guid.CreateVersion7(); + dbContext.Books.Add(_bookEntityFixture.Create( + id: bookId, + libraryId: libraryId, + title: $"Eventual Consistency Book-{Guid.NewGuid():N}", + includeMetadata: false)); + await dbContext.SaveChangesAsync(); + _seededLibraryIds.Add(libraryId); + return bookId; + } + + /// + /// Gets the Id of the currently authenticated test user. + /// + /// The Id of the authenticated test user. + private Guid GetCurrentUserId() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + UserEntity user = dbContext.Users.First(candidate => candidate.Username == _apiFactory.TestUsername); + return user.Id; + } + + /// + /// Removes the data seeded by the test and the API factory test user. + /// + public async Task DisposeAsync() + { + using (IServiceScope scope = _apiFactory.Services.CreateScope()) + { + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List libraryIds = [.. _seededLibraryIds]; + List bookIds = await dbContext.Books.Where(book => libraryIds.Contains(book.LibraryId)).Select(book => book.Id).ToListAsync(); + Guid? userId = await dbContext.Users + .Where(user => user.Username == _apiFactory.TestUsername) + .Select(user => (Guid?)user.Id) + .FirstOrDefaultAsync(); + if (userId is not null) + dbContext.Favorites.RemoveRange(dbContext.Favorites.Where(favorite => favorite.UserId == userId.Value)); + dbContext.Books.RemoveRange(dbContext.Books.Where(book => bookIds.Contains(book.Id))); + dbContext.Libraries.RemoveRange(dbContext.Libraries.Where(library => libraryIds.Contains(library.Id))); + await dbContext.SaveChangesAsync(); + } + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/DomainEventPublicationProbe.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/DomainEventPublicationProbe.cs new file mode 100644 index 00000000..51256d03 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/DomainEventPublicationProbe.cs @@ -0,0 +1,78 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup; + +/// +/// Observes the domain events published through the real domain event publisher. +/// +[ExcludeFromCodeCoverage] +public sealed class DomainEventPublicationProbe +{ + private readonly Lock _signalLock = new(); + private TaskCompletionSource _publishedSignal = CreateSignal(); + private int _publicationCount; + + /// + /// Gets the number of domain events that were published. + /// + public int PublicationCount => Volatile.Read(ref _publicationCount); + + /// + /// Gets whether the favorite of the last published event was visible from a separate database scope. + /// + public bool WasFavoriteVisible { get; private set; } + + /// + /// Clears the recorded observations, so that a test observes only the events published after the reset. + /// + public void Reset() + { + Interlocked.Exchange(ref _publicationCount, 0); + WasFavoriteVisible = false; + lock (_signalLock) + _publishedSignal = CreateSignal(); + } + + /// + /// Records that a domain event was published, together with whether its favorite was visible at publication time. + /// + /// Whether the favorite was visible from a separate database scope. + public void RecordPublication(bool wasFavoriteVisible) + { + WasFavoriteVisible = wasFavoriteVisible; + Interlocked.Increment(ref _publicationCount); + TaskCompletionSource signal; + lock (_signalLock) + signal = _publishedSignal; + signal.TrySetResult(true); + } + + /// + /// Waits until a domain event is published. + /// + /// The maximum time to wait. + /// A task that represents the asynchronous operation. + public async Task WaitForPublicationAsync(TimeSpan timeout) + { + Task signal; + lock (_signalLock) + signal = _publishedSignal.Task; + Task completedTask = await Task.WhenAny(signal, Task.Delay(timeout)).ConfigureAwait(false); + if (completedTask != signal) + throw new TimeoutException($"A domain event was not published within {timeout}."); + } + + /// + /// Creates a completion source that resumes its continuations asynchronously. + /// + /// The created completion source. + private static TaskCompletionSource CreateSignal() + { + return new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/DomainEventsQueueProbe.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/DomainEventsQueueProbe.cs new file mode 100644 index 00000000..1ae2810a --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/DomainEventsQueueProbe.cs @@ -0,0 +1,170 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Concurrent; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup; + +/// +/// Controls and observes the domain events handled through the . +/// +[ExcludeFromCodeCoverage] +public sealed class DomainEventsQueueProbe +{ + private readonly Lock _signalLock = new(); + private readonly ConcurrentDictionary _dequeueAttemptsByPath = new(); + private readonly ConcurrentDictionary> _dequeueSignalsByPath = new(); + private TaskCompletionSource _enqueuedSignal = CreateSignal(); + private TaskCompletionSource _enqueueReleaseSignal = CreateSignal(); + private volatile bool _shouldBlockOnEnqueue; + private volatile bool _shouldThrowOnEnqueue; + private int _enqueueCount; + private int _dequeueCount; + + /// + /// Gets or sets whether enqueuing a domain event waits until the test releases it. + /// + public bool ShouldBlockOnEnqueue + { + get { return _shouldBlockOnEnqueue; } + set { _shouldBlockOnEnqueue = value; } + } + + /// + /// Gets or sets whether enqueuing a domain event fails after the event is queued. + /// + public bool ShouldThrowOnEnqueue + { + get { return _shouldThrowOnEnqueue; } + set { _shouldThrowOnEnqueue = value; } + } + + /// + /// Gets or sets how long a blocked enqueuing request waits for the test to release it. + /// + public TimeSpan BlockTimeout { get; set; } = TimeSpan.FromSeconds(5); + + /// + /// Gets the number of domain events that were enqueued. + /// + public int EnqueueCount => Volatile.Read(ref _enqueueCount); + + /// + /// Gets the number of domain events that were dequeued for publication. + /// + public int DequeueCount => Volatile.Read(ref _dequeueCount); + + /// + /// Clears the recorded counts and signals, so that a test observes only the events handled after the reset. + /// + public void Reset() + { + ShouldBlockOnEnqueue = false; + ShouldThrowOnEnqueue = false; + Interlocked.Exchange(ref _enqueueCount, 0); + Interlocked.Exchange(ref _dequeueCount, 0); + _dequeueAttemptsByPath.Clear(); + _dequeueSignalsByPath.Clear(); + lock (_signalLock) + { + _enqueuedSignal = CreateSignal(); + _enqueueReleaseSignal = CreateSignal(); + } + } + + /// + /// Records that a domain event was enqueued, optionally blocking or failing the enqueuing request. + /// + public void RecordEnqueue() + { + Interlocked.Increment(ref _enqueueCount); + TaskCompletionSource enqueuedSignal; + TaskCompletionSource releaseSignal; + lock (_signalLock) + { + enqueuedSignal = _enqueuedSignal; + releaseSignal = _enqueueReleaseSignal; + } + enqueuedSignal.TrySetResult(true); + if (ShouldBlockOnEnqueue && !releaseSignal.Task.Wait(BlockTimeout)) + throw new TimeoutException("The test did not release the queued domain event in time."); + if (ShouldThrowOnEnqueue) + throw new InvalidOperationException("The test forces the request to fail after its domain event was queued."); + } + + /// + /// Records that the queue was asked for a domain event on the request of . + /// + /// The path of the request whose middleware dequeued the queue. + /// Whether the queue actually contained an event. + public void RecordDequeue(string path, bool wasDequeued) + { + _dequeueAttemptsByPath.AddOrUpdate(path, 1, (_, attemptCount) => attemptCount + 1); + TaskCompletionSource signal = _dequeueSignalsByPath.GetOrAdd(path, _ => CreateSignal()); + signal.TrySetResult(true); + if (wasDequeued) + Interlocked.Increment(ref _dequeueCount); + } + + /// + /// Gets the number of dequeue attempts made for the request of . + /// + /// The path of the request. + /// The number of dequeue attempts made for the request. + public int GetDequeueAttemptCount(string path) + { + return _dequeueAttemptsByPath.TryGetValue(path, out int attemptCount) ? attemptCount : 0; + } + + /// + /// Waits until a dequeue attempt is made for the request of . + /// + /// The path of the request to observe. + /// The maximum time to wait. + /// A task that represents the asynchronous operation. + public async Task WaitForDequeueAsync(string path, TimeSpan timeout) + { + Task signal = _dequeueSignalsByPath.GetOrAdd(path, _ => CreateSignal()).Task; + Task completedTask = await Task.WhenAny(signal, Task.Delay(timeout)).ConfigureAwait(false); + if (completedTask != signal) + throw new TimeoutException($"The domain events queue was not dequeued for '{path}' within {timeout}."); + } + + /// + /// Waits until a domain event is enqueued. + /// + /// The maximum time to wait. + /// A task that represents the asynchronous operation. + public async Task WaitForEnqueueAsync(TimeSpan timeout) + { + Task signal; + lock (_signalLock) + signal = _enqueuedSignal.Task; + Task completedTask = await Task.WhenAny(signal, Task.Delay(timeout)).ConfigureAwait(false); + if (completedTask != signal) + throw new TimeoutException($"A domain event was not enqueued within {timeout}."); + } + + /// + /// Releases an enqueuing request blocked by . + /// + public void ReleaseEnqueue() + { + TaskCompletionSource releaseSignal; + lock (_signalLock) + releaseSignal = _enqueueReleaseSignal; + releaseSignal.TrySetResult(true); + } + + /// + /// Creates a completion source that resumes its continuations asynchronously. + /// + /// The created completion source. + private static TaskCompletionSource CreateSignal() + { + return new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/EventualConsistencyApiFactory.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/EventualConsistencyApiFactory.cs new file mode 100644 index 00000000..2053975e --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/EventualConsistencyApiFactory.cs @@ -0,0 +1,79 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DomainEvents; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.Events; +using Microsoft.AspNetCore.Hosting; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup; + +/// +/// Authenticated API factory whose database transactions and domain events are observable through probes. +/// +[ExcludeFromCodeCoverage] +public sealed class EventualConsistencyApiFactory : AuthenticatedLuminaApiFactory +{ + /// + /// Gets the probe that controls and observes the domain events queue. + /// + public DomainEventsQueueProbe QueueProbe { get; } = new(); + + /// + /// Gets the probe that observes the published domain events. + /// + public DomainEventPublicationProbe PublicationProbe { get; } = new(); + + /// + /// Gets the probe that observes the database transaction lifecycle. + /// + public TransactionProbe TransactionProbe { get; } = new(); + + /// + /// Clears every probe, so that a test observes only the activity started after the reset. + /// + public void ResetProbes() + { + QueueProbe.Reset(); + PublicationProbe.Reset(); + TransactionProbe.Reset(); + } + + /// + /// Adds the transaction probe to the database context options. + /// + /// The service provider used to resolve the options of the database context. + /// The options builder of the database context being configured. + protected override void ConfigureDbContextOptions(IServiceProvider serviceProvider, DbContextOptionsBuilder options) + { + base.ConfigureDbContextOptions(serviceProvider, options); + // The test services are registered before the shared factory configures the database, so the interceptor is available even from the + // throwaway provider the shared factory uses to migrate the database, and a missing registration fails host construction loudly. + options.AddInterceptors(serviceProvider.GetRequiredService()); + } + + /// + /// Configures the web host, replacing the domain events queue and registering the recording event handler. + /// + /// The web host builder to configure. + protected override void ConfigureWebHost(IWebHostBuilder builder) + { + // Registering the test services before the shared factory configures the database makes them available to its migration provider too. + builder.ConfigureServices(services => + { + services.AddHttpContextAccessor(); + services.AddSingleton(QueueProbe); + services.AddSingleton(PublicationProbe); + services.AddSingleton(TransactionProbe); + services.AddSingleton(); + services.RemoveAll(); + services.AddScoped(); + services.AddScoped, RecordingFavoriteAddedDomainEventHandler>(); + }); + base.ConfigureWebHost(builder); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/LuminaApiFactory.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/LuminaApiFactory.cs index 4d793645..e13297d6 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/LuminaApiFactory.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/LuminaApiFactory.cs @@ -84,6 +84,7 @@ public class LuminaApiFactory : WebApplicationFactory, IDisposable { options.UseSqlite(_sharedInMemoryConnectionString); options.AddInterceptors(serviceProvider.GetRequiredService()); + ConfigureDbContextOptions(serviceProvider, options); }); // Configure JWT authentication for testing. services.PostConfigure(JwtBearerDefaults.AuthenticationScheme, options => @@ -110,6 +111,21 @@ public class LuminaApiFactory : WebApplicationFactory, IDisposable }); } + /// + /// Configures additional options of the database context used by the tests. + /// + /// + /// The hook is invoked every time the options of a database context are built, including once for the throwaway provider that migrates the + /// database while the host is configured and once for the final provider of the host. Derived factories that resolve test services from the + /// provided must register those services before the shared factory configures the database, and must call + /// this base implementation so that options added here are never silently skipped. + /// + /// The service provider used to resolve the options of the database context. + /// The options builder of the database context being configured. + protected virtual void ConfigureDbContextOptions(IServiceProvider serviceProvider, DbContextOptionsBuilder options) + { + } + /// /// Resets the in-memory SQLite database to its original state. /// diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/ProbingDomainEventsQueue.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/ProbingDomainEventsQueue.cs new file mode 100644 index 00000000..99af4dc6 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/ProbingDomainEventsQueue.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DomainEvents; +using Lumina.Domain.Common.Events; +using Microsoft.AspNetCore.Http; +using System.Collections.Concurrent; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup; + +/// +/// Domain events queue that exposes its enqueuing and dequeuing to a . +/// +[ExcludeFromCodeCoverage] +public sealed class ProbingDomainEventsQueue : IDomainEventsQueue +{ + private readonly ConcurrentQueue _queue = new(); + private readonly DomainEventsQueueProbe _probe; + private readonly IHttpContextAccessor _httpContextAccessor; + + /// + /// Initializes a new instance of the class. + /// + /// The probe that controls and observes the queue. + /// Injected accessor used to identify the request that dequeues the queue. + public ProbingDomainEventsQueue(DomainEventsQueueProbe probe, IHttpContextAccessor httpContextAccessor) + { + _probe = probe; + _httpContextAccessor = httpContextAccessor; + } + + /// + /// Adds a domain event to the queue, before reporting it to the probe. + /// + /// The domain event to enqueue. + public void Enqueue(IDomainEvent domainEvent) + { + _queue.Enqueue(domainEvent); + _probe.RecordEnqueue(); + } + + /// + /// Attempts to remove and return the domain event at the beginning of the queue, reporting the attempt to the probe. + /// + /// When this method returns, contains the domain event removed from the queue, or the default value of if the queue is empty. + /// + /// if a domain event was successfully dequeued, otherwise. + public bool TryDequeue(out IDomainEvent domainEvent) + { + bool wasDequeued = _queue.TryDequeue(out domainEvent!); + string path = _httpContextAccessor.HttpContext?.Request.Path.Value ?? string.Empty; + _probe.RecordDequeue(path, wasDequeued); + return wasDequeued; + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/RecordingFavoriteAddedDomainEventHandler.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/RecordingFavoriteAddedDomainEventHandler.cs new file mode 100644 index 00000000..62d904ad --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/RecordingFavoriteAddedDomainEventHandler.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.Events; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup; + +/// +/// Domain event handler that records the publication of a , together with the state visible at publication time. +/// +[ExcludeFromCodeCoverage] +public sealed class RecordingFavoriteAddedDomainEventHandler : IDomainEventHandler +{ + private readonly IServiceScopeFactory _scopeFactory; + private readonly DomainEventPublicationProbe _publicationProbe; + + /// + /// Initializes a new instance of the class. + /// + /// Injected factory used to create a database scope independent from the request scope. + /// Injected probe that records the published event. + public RecordingFavoriteAddedDomainEventHandler(IServiceScopeFactory scopeFactory, DomainEventPublicationProbe publicationProbe) + { + _scopeFactory = scopeFactory; + _publicationProbe = publicationProbe; + } + + /// + /// Records the published , checking whether its favorite was already committed. + /// + /// The domain event being published. + /// Cancellation token that can be used to stop the execution. + /// A task that represents the asynchronous operation. + public async ValueTask HandleAsync(FavoriteAddedDomainEvent domainEvent, CancellationToken cancellationToken) + { + // A separate scope and context prove that the row is visible to other connections, which is only true after the request transaction was committed. + using IServiceScope scope = _scopeFactory.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + bool wasFavoriteVisible = await dbContext.Favorites + .AsNoTracking() + .AnyAsync(favorite => favorite.Id == domainEvent.FavoriteId.Value, cancellationToken).ConfigureAwait(false); + + _publicationProbe.RecordPublication(wasFavoriteVisible); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/TransactionProbe.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/TransactionProbe.cs new file mode 100644 index 00000000..8126a040 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/TransactionProbe.cs @@ -0,0 +1,78 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup; + +/// +/// Observes the database transactions rolled back on each request through the . +/// +[ExcludeFromCodeCoverage] +public sealed class TransactionProbe +{ + private readonly Lock _signalLock = new(); + private readonly Dictionary> _rollbackSignalsByPath = []; + + /// + /// Clears the recorded signals, so that a test observes only the rollbacks that happen after the reset. + /// + public void Reset() + { + lock (_signalLock) + _rollbackSignalsByPath.Clear(); + } + + /// + /// Records that the transaction of the request of was rolled back. + /// + /// The path of the request whose transaction was rolled back. + public void RecordRolledBack(string path) + { + TaskCompletionSource signal; + lock (_signalLock) + { + if (!_rollbackSignalsByPath.TryGetValue(path, out signal!)) + { + signal = CreateSignal(); + _rollbackSignalsByPath[path] = signal; + } + } + signal.TrySetResult(true); + } + + /// + /// Waits until the transaction of the request of is rolled back. + /// + /// The path of the request to observe. + /// The maximum time to wait. + /// A task that represents the asynchronous operation. + public async Task WaitForRollbackAsync(string path, TimeSpan timeout) + { + Task signal; + lock (_signalLock) + { + if (!_rollbackSignalsByPath.TryGetValue(path, out TaskCompletionSource? signalSource)) + { + signalSource = CreateSignal(); + _rollbackSignalsByPath[path] = signalSource; + } + signal = signalSource.Task; + } + Task completedTask = await Task.WhenAny(signal, Task.Delay(timeout)).ConfigureAwait(false); + if (completedTask != signal) + throw new TimeoutException($"The transaction of '{path}' was not rolled back within {timeout}."); + } + + /// + /// Creates a completion source that resumes its continuations asynchronously. + /// + /// The created completion source. + private static TaskCompletionSource CreateSignal() + { + return new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/TransactionProbeInterceptor.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/TransactionProbeInterceptor.cs new file mode 100644 index 00000000..18580e70 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/TransactionProbeInterceptor.cs @@ -0,0 +1,63 @@ +#region ========================================================================= USING ===================================================================================== +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore.Diagnostics; +using System.Data.Common; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup; + +/// +/// Database transaction interceptor that reports the rolled back transactions to a . +/// +[ExcludeFromCodeCoverage] +public sealed class TransactionProbeInterceptor : DbTransactionInterceptor +{ + private readonly TransactionProbe _probe; + private readonly IHttpContextAccessor _httpContextAccessor; + + /// + /// Initializes a new instance of the class. + /// + /// The probe that records the rolled back transactions. + /// Injected accessor used to identify the request whose transaction was rolled back. + public TransactionProbeInterceptor(TransactionProbe probe, IHttpContextAccessor httpContextAccessor) + { + _probe = probe; + _httpContextAccessor = httpContextAccessor; + } + + /// + /// Records that a transaction was rolled back. + /// + /// The rolled back transaction. + /// The data of the transaction event. + /// Cancellation token that can be used to stop the execution. + /// A completed task. + public override Task TransactionRolledBackAsync(DbTransaction transaction, TransactionEndEventData eventData, CancellationToken cancellationToken = default) + { + RecordRolledBack(); + return Task.CompletedTask; + } + + /// + /// Records that a transaction was rolled back synchronously. + /// + /// The rolled back transaction. + /// The data of the transaction event. + public override void TransactionRolledBack(DbTransaction transaction, TransactionEndEventData eventData) + { + RecordRolledBack(); + } + + /// + /// Reports the rolled back transaction of the current request to the probe. + /// + private void RecordRolledBack() + { + string path = _httpContextAccessor.HttpContext?.Request.Path.Value ?? string.Empty; + _probe.RecordRolledBack(path); + } +}