mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 11:11:10 +00:00
Renames project paths from Lumina to Nemera
This commit is contained in:
1 parent
ce6fddb4c9
commit
0f659a4877
6450 files changed
No files matched your search
+210
@@ -0,0 +1,210 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DataAccess.Seed;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Authentication;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using Lumina.Contracts.Responses.Authentication;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
|
||||
using Lumina.Infrastructure.Core.Security;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
|
||||
// <summary>
|
||||
/// Factory that extends <see cref="LuminaApiFactory"/> to provide authenticated HTTP clients for testing.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable
|
||||
{
|
||||
private readonly PasswordHashService _hashService = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly PermissionEntityFixture _permissionEntityFixture = new();
|
||||
private readonly UserPermissionEntityFixture _userPermissionEntityFixture = new();
|
||||
private readonly LoginRequestFixture _loginRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the username of the currently created test user.
|
||||
/// </summary>
|
||||
public string? TestUsername { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Creates an HTTP client with authentication headers and a test user.
|
||||
/// </summary>
|
||||
/// <param name="permissions">The permissions granted directly to the test user, if any.</param>
|
||||
/// <returns>An HTTP client configured with auth headers.</returns>
|
||||
public async Task<HttpClient> CreateAuthenticatedClientAsync(params AuthorizationPermission[] permissions)
|
||||
{
|
||||
HttpClient client = CreateClient();
|
||||
TestUsername = $"testuser_{Guid.NewGuid()}";
|
||||
|
||||
// Add the X-Forwarded-For header.
|
||||
client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.{Random.Shared.Next(0, 255)}.{Random.Shared.Next(0, 255)}.{Random.Shared.Next(0, 255)}");
|
||||
|
||||
// Perform authentication.
|
||||
await CreateAndAuthenticateUser(client, permissions);
|
||||
|
||||
return client;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates and authenticates a test user.
|
||||
/// </summary>
|
||||
/// <param name="client">The HTTP client to configure with auth.</param>
|
||||
/// <param name="permissions">The permissions granted directly to the test user.</param>
|
||||
/// <returns>The created user entity.</returns>
|
||||
private async Task<UserEntity> CreateAndAuthenticateUser(HttpClient client, AuthorizationPermission[] permissions)
|
||||
{
|
||||
using IServiceScope scope = Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
// Create test user, with the permissions granted directly to it.
|
||||
UserEntity user = _userEntityFixture.Create(username: TestUsername!, password: _hashService.HashString("TestPass123!"));
|
||||
user.TotpSecret = null;
|
||||
foreach (AuthorizationPermission permission in permissions)
|
||||
user.UserPermissions.Add(_userPermissionEntityFixture.Create(user, _permissionEntityFixture.Create(permissionName: permission, createdBy: user.Id)));
|
||||
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
// Authenticate user.
|
||||
LoginRequest loginRequest = _loginRequestFixture.Create(
|
||||
username: user.Username,
|
||||
password: "TestPass123!",
|
||||
includeTotpCode: false
|
||||
);
|
||||
|
||||
HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", loginRequest);
|
||||
string content = await loginResponse.Content.ReadAsStringAsync();
|
||||
LoginResponse? result = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
|
||||
|
||||
// Set auth header for subsequent requests.
|
||||
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result!.Token);
|
||||
|
||||
return user;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an HTTP client with authentication headers and an admin test user with all permissions.
|
||||
/// </summary>
|
||||
/// <returns>An HTTP client configured with admin auth headers.</returns>
|
||||
public async Task<HttpClient> CreateAuthenticatedAdminClientAsync()
|
||||
{
|
||||
HttpClient client = CreateClient();
|
||||
TestUsername = $"testuser_{Guid.NewGuid()}";
|
||||
|
||||
// Add the X-Forwarded-For header.
|
||||
client.DefaultRequestHeaders.Add("X-Forwarded-For",
|
||||
$"192.{Random.Shared.Next(0, 255)}.{Random.Shared.Next(0, 255)}.{Random.Shared.Next(0, 255)}");
|
||||
|
||||
// Create and authenticate admin user.
|
||||
await CreateAndAuthenticateAdminUser(client);
|
||||
|
||||
return client;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates and authenticates an admin test user with all permissions.
|
||||
/// </summary>
|
||||
/// <param name="client">The HTTP client to configure with auth.</param>
|
||||
/// <returns>The created user entity.</returns>
|
||||
private async Task<UserEntity> CreateAndAuthenticateAdminUser(HttpClient client)
|
||||
{
|
||||
using IServiceScope scope = Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
IDataSeedService dataSeedService = scope.ServiceProvider.GetRequiredService<IDataSeedService>();
|
||||
|
||||
// Create test user.
|
||||
UserEntity user = _userEntityFixture.Create(username: TestUsername!, password: _hashService.HashString("TestPass123!"));
|
||||
user.TotpSecret = null;
|
||||
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
// Set up admin permissions and roles.
|
||||
await dataSeedService.SetDefaultAuthorizationPermissionsAsync(CancellationToken.None);
|
||||
await dataSeedService.SetDefaultAuthorizationRolesAsync(CancellationToken.None);
|
||||
await dataSeedService.SetAdminRolePermissionsAsync(CancellationToken.None);
|
||||
await dataSeedService.SetAdminRoleToAdministratorAccount(user.Id, CancellationToken.None);
|
||||
|
||||
// Authenticate user.
|
||||
LoginRequest loginRequest = _loginRequestFixture.Create(
|
||||
username: user.Username,
|
||||
password: "TestPass123!",
|
||||
includeTotpCode: false
|
||||
);
|
||||
|
||||
HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", loginRequest);
|
||||
string content = await loginResponse.Content.ReadAsStringAsync();
|
||||
LoginResponse? result = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
|
||||
|
||||
// Set auth header for subsequent requests.
|
||||
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result!.Token);
|
||||
|
||||
return user;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the currently created test user from the database.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Test classes must call this in their per-test <c>DisposeAsync</c> instead of <see cref="Dispose"/>. The
|
||||
/// factory is a shared <see cref="IClassFixture{TFixture}"/>, created once per test class and disposed by
|
||||
/// xUnit only after all tests in the class have run. Calling <see cref="Dispose"/> from a per-test
|
||||
/// <c>DisposeAsync</c> would dispose the web host and its service provider after the first test, making
|
||||
/// every subsequent test in the class fail with an <see cref="ObjectDisposedException"/> when it resolves
|
||||
/// services. <see cref="Dispose"/> is therefore reserved for xUnit's own class-teardown and must never be
|
||||
/// invoked from a test.
|
||||
/// </remarks>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
public async Task RemoveTestUserAsync()
|
||||
{
|
||||
using IServiceScope scope = Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == TestUsername);
|
||||
if (user is not null)
|
||||
{
|
||||
dbContext.Users.Remove(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Called by xUnit when the test class completes. Do not call from tests; per-test cleanup must use
|
||||
/// <see cref="RemoveTestUserAsync"/>. See that method for the details.
|
||||
/// </remarks>
|
||||
public new void Dispose()
|
||||
{
|
||||
using IServiceScope scope = Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == TestUsername);
|
||||
if (user is not null)
|
||||
{
|
||||
dbContext.Users.Remove(user);
|
||||
dbContext.SaveChanges();
|
||||
}
|
||||
|
||||
base.Dispose();
|
||||
}
|
||||
}
|
||||
+78
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Observes the domain events published through the real domain event publisher.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public sealed class DomainEventPublicationProbe
|
||||
{
|
||||
private readonly Lock _signalLock = new();
|
||||
private TaskCompletionSource<bool> _publishedSignal = CreateSignal();
|
||||
private int _publicationCount;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of domain events that were published.
|
||||
/// </summary>
|
||||
public int PublicationCount => Volatile.Read(ref _publicationCount);
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether the favorite of the last published event was visible from a separate database scope.
|
||||
/// </summary>
|
||||
public bool WasFavoriteVisible { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Clears the recorded observations, so that a test observes only the events published after the reset.
|
||||
/// </summary>
|
||||
public void Reset()
|
||||
{
|
||||
Interlocked.Exchange(ref _publicationCount, 0);
|
||||
WasFavoriteVisible = false;
|
||||
lock (_signalLock)
|
||||
_publishedSignal = CreateSignal();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Records that a domain event was published, together with whether its favorite was visible at publication time.
|
||||
/// </summary>
|
||||
/// <param name="wasFavoriteVisible">Whether the favorite was visible from a separate database scope.</param>
|
||||
public void RecordPublication(bool wasFavoriteVisible)
|
||||
{
|
||||
WasFavoriteVisible = wasFavoriteVisible;
|
||||
Interlocked.Increment(ref _publicationCount);
|
||||
TaskCompletionSource<bool> signal;
|
||||
lock (_signalLock)
|
||||
signal = _publishedSignal;
|
||||
signal.TrySetResult(true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Waits until a domain event is published.
|
||||
/// </summary>
|
||||
/// <param name="timeout">The maximum time to wait.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
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}.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a completion source that resumes its continuations asynchronously.
|
||||
/// </summary>
|
||||
/// <returns>The created completion source.</returns>
|
||||
private static TaskCompletionSource<bool> CreateSignal()
|
||||
{
|
||||
return new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
}
|
||||
}
|
||||
+170
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Controls and observes the domain events handled through the <see cref="ProbingDomainEventsQueue"/>.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public sealed class DomainEventsQueueProbe
|
||||
{
|
||||
private readonly Lock _signalLock = new();
|
||||
private readonly ConcurrentDictionary<string, int> _dequeueAttemptsByPath = new();
|
||||
private readonly ConcurrentDictionary<string, TaskCompletionSource<bool>> _dequeueSignalsByPath = new();
|
||||
private TaskCompletionSource<bool> _enqueuedSignal = CreateSignal();
|
||||
private TaskCompletionSource<bool> _enqueueReleaseSignal = CreateSignal();
|
||||
private volatile bool _shouldBlockOnEnqueue;
|
||||
private volatile bool _shouldThrowOnEnqueue;
|
||||
private int _enqueueCount;
|
||||
private int _dequeueCount;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets whether enqueuing a domain event waits until the test releases it.
|
||||
/// </summary>
|
||||
public bool ShouldBlockOnEnqueue
|
||||
{
|
||||
get { return _shouldBlockOnEnqueue; }
|
||||
set { _shouldBlockOnEnqueue = value; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets whether enqueuing a domain event fails after the event is queued.
|
||||
/// </summary>
|
||||
public bool ShouldThrowOnEnqueue
|
||||
{
|
||||
get { return _shouldThrowOnEnqueue; }
|
||||
set { _shouldThrowOnEnqueue = value; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets how long a blocked enqueuing request waits for the test to release it.
|
||||
/// </summary>
|
||||
public TimeSpan BlockTimeout { get; set; } = TimeSpan.FromSeconds(5);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of domain events that were enqueued.
|
||||
/// </summary>
|
||||
public int EnqueueCount => Volatile.Read(ref _enqueueCount);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of domain events that were dequeued for publication.
|
||||
/// </summary>
|
||||
public int DequeueCount => Volatile.Read(ref _dequeueCount);
|
||||
|
||||
/// <summary>
|
||||
/// Clears the recorded counts and signals, so that a test observes only the events handled after the reset.
|
||||
/// </summary>
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Records that a domain event was enqueued, optionally blocking or failing the enqueuing request.
|
||||
/// </summary>
|
||||
public void RecordEnqueue()
|
||||
{
|
||||
Interlocked.Increment(ref _enqueueCount);
|
||||
TaskCompletionSource<bool> enqueuedSignal;
|
||||
TaskCompletionSource<bool> 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.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Records that the queue was asked for a domain event on the request of <paramref name="path"/>.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the request whose middleware dequeued the queue.</param>
|
||||
/// <param name="wasDequeued">Whether the queue actually contained an event.</param>
|
||||
public void RecordDequeue(string path, bool wasDequeued)
|
||||
{
|
||||
_dequeueAttemptsByPath.AddOrUpdate(path, 1, (_, attemptCount) => attemptCount + 1);
|
||||
TaskCompletionSource<bool> signal = _dequeueSignalsByPath.GetOrAdd(path, _ => CreateSignal());
|
||||
signal.TrySetResult(true);
|
||||
if (wasDequeued)
|
||||
Interlocked.Increment(ref _dequeueCount);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of dequeue attempts made for the request of <paramref name="path"/>.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the request.</param>
|
||||
/// <returns>The number of dequeue attempts made for the request.</returns>
|
||||
public int GetDequeueAttemptCount(string path)
|
||||
{
|
||||
return _dequeueAttemptsByPath.TryGetValue(path, out int attemptCount) ? attemptCount : 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Waits until a dequeue attempt is made for the request of <paramref name="path"/>.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the request to observe.</param>
|
||||
/// <param name="timeout">The maximum time to wait.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
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}.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Waits until a domain event is enqueued.
|
||||
/// </summary>
|
||||
/// <param name="timeout">The maximum time to wait.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
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}.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases an enqueuing request blocked by <see cref="ShouldBlockOnEnqueue"/>.
|
||||
/// </summary>
|
||||
public void ReleaseEnqueue()
|
||||
{
|
||||
TaskCompletionSource<bool> releaseSignal;
|
||||
lock (_signalLock)
|
||||
releaseSignal = _enqueueReleaseSignal;
|
||||
releaseSignal.TrySetResult(true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a completion source that resumes its continuations asynchronously.
|
||||
/// </summary>
|
||||
/// <returns>The created completion source.</returns>
|
||||
private static TaskCompletionSource<bool> CreateSignal()
|
||||
{
|
||||
return new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
}
|
||||
}
|
||||
+79
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Authenticated API factory whose database transactions and domain events are observable through probes.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public sealed class EventualConsistencyApiFactory : AuthenticatedLuminaApiFactory
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the probe that controls and observes the domain events queue.
|
||||
/// </summary>
|
||||
public DomainEventsQueueProbe QueueProbe { get; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the probe that observes the published domain events.
|
||||
/// </summary>
|
||||
public DomainEventPublicationProbe PublicationProbe { get; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the probe that observes the database transaction lifecycle.
|
||||
/// </summary>
|
||||
public TransactionProbe TransactionProbe { get; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// Clears every probe, so that a test observes only the activity started after the reset.
|
||||
/// </summary>
|
||||
public void ResetProbes()
|
||||
{
|
||||
QueueProbe.Reset();
|
||||
PublicationProbe.Reset();
|
||||
TransactionProbe.Reset();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds the transaction probe to the database context options.
|
||||
/// </summary>
|
||||
/// <param name="serviceProvider">The service provider used to resolve the options of the database context.</param>
|
||||
/// <param name="options">The options builder of the database context being configured.</param>
|
||||
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<TransactionProbeInterceptor>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures the web host, replacing the domain events queue and registering the recording event handler.
|
||||
/// </summary>
|
||||
/// <param name="builder">The web host builder to configure.</param>
|
||||
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<TransactionProbeInterceptor>();
|
||||
services.RemoveAll<IDomainEventsQueue>();
|
||||
services.AddScoped<IDomainEventsQueue, ProbingDomainEventsQueue>();
|
||||
services.AddScoped<IDomainEventHandler<FavoriteAddedDomainEvent>, RecordingFavoriteAddedDomainEventHandler>();
|
||||
});
|
||||
base.ConfigureWebHost(builder);
|
||||
}
|
||||
}
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.DataAccess.Common.Interceptors;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
|
||||
/// <summary>
|
||||
/// Factory for creating a web application for integration tests.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LuminaApiFactory : WebApplicationFactory<Program>, IDisposable
|
||||
{
|
||||
private readonly SqliteConnection _connection;
|
||||
private readonly string _sharedInMemoryConnectionString;
|
||||
private const string TEST_ENCRYPTION_KEY = "MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=";
|
||||
private const string SHARED_IN_MEMORY_CONNECTION_STRING_PREFIX = "Data Source=lumina-tests-{0};Mode=Memory;Cache=Shared";
|
||||
private static byte s_IpClass = 25;
|
||||
|
||||
public static byte IpClass => s_IpClass++;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LuminaApiFactory"/> class.
|
||||
/// </summary>
|
||||
public LuminaApiFactory()
|
||||
{
|
||||
// Each factory gets its own uniquely named shared in-memory database, so that parallel test classes remain isolated from one another;
|
||||
// the shared cache allows each DbContext to open its own pooled connection to the same database, instead of sharing a single connection,
|
||||
// which would otherwise serialize every request on one connection and cause nested transaction errors between requests.
|
||||
_sharedInMemoryConnectionString = string.Format(SHARED_IN_MEMORY_CONNECTION_STRING_PREFIX, Guid.NewGuid());
|
||||
// Keep a single anchor connection open, so that the shared in-memory database it refers to is not dropped.
|
||||
_connection = new SqliteConnection(_sharedInMemoryConnectionString);
|
||||
_connection.Open();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures the web host for the integration tests.
|
||||
/// </summary>
|
||||
/// <param name="builder">The web host builder to configure.</param>
|
||||
protected override void ConfigureWebHost(IWebHostBuilder builder)
|
||||
{
|
||||
builder.ConfigureAppConfiguration((context, config) =>
|
||||
{
|
||||
// Clear all existing configuration sources.
|
||||
config.Sources.Clear();
|
||||
|
||||
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
|
||||
config.AddJsonFile($"appsettings.test.json", optional: true, reloadOnChange: true);
|
||||
config.AddJsonFile("appsettings.shared.json", optional: true, reloadOnChange: true);
|
||||
config.AddJsonFile($"appsettings.shared.test.json", optional: true, reloadOnChange: true);
|
||||
// First add the test values directly.
|
||||
config.AddInMemoryCollection(initialData: new Dictionary<string, string?>
|
||||
{
|
||||
["JwtSettings:SecretKey"] = "test-key-thats-at-least-32-chars-long-for-jwt",
|
||||
["JwtSettings:ExpiryMinutes"] = "60",
|
||||
["JwtSettings:Issuer"] = "test-issuer",
|
||||
["JwtSettings:Audience"] = "test-audience",
|
||||
["CorsSettings:AllowedOrigins:0"] = "http://localhost:5012",
|
||||
["EncryptionSettings:SecretKey"] = TEST_ENCRYPTION_KEY // Base64 encoded test key.
|
||||
});
|
||||
});
|
||||
builder.ConfigureServices(services =>
|
||||
{
|
||||
// Remove existing DbContext configuration.
|
||||
ServiceDescriptor? descriptor = services.SingleOrDefault(serviceDescriptor => serviceDescriptor.ServiceType == typeof(DbContextOptions<LuminaDbContext>));
|
||||
if (descriptor is not null)
|
||||
services.Remove(descriptor);
|
||||
// Add SQLite DbContext configuration.
|
||||
services.AddDbContext<LuminaDbContext>((serviceProvider, options) =>
|
||||
{
|
||||
options.UseSqlite(_sharedInMemoryConnectionString);
|
||||
options.AddInterceptors(serviceProvider.GetRequiredService<UpdateAuditableEntitiesInterceptor>());
|
||||
ConfigureDbContextOptions(serviceProvider, options);
|
||||
});
|
||||
// Configure JWT authentication for testing.
|
||||
services.PostConfigure<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme, options =>
|
||||
{
|
||||
options.TokenValidationParameters = new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuer = true,
|
||||
ValidateAudience = true,
|
||||
ValidateLifetime = true,
|
||||
ValidateIssuerSigningKey = true,
|
||||
ValidIssuer = "test-issuer",
|
||||
ValidAudience = "test-audience",
|
||||
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("test-key-thats-at-least-32-chars-long-for-jwt"))
|
||||
};
|
||||
});
|
||||
// Build service provider and ensure database is created.
|
||||
ServiceProvider servicePreovider = services.BuildServiceProvider();
|
||||
using (IServiceScope scope = servicePreovider.CreateScope())
|
||||
{
|
||||
IServiceProvider scopedServices = scope.ServiceProvider;
|
||||
LuminaDbContext dbContext = scopedServices.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Database.Migrate();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures additional options of the database context used by the tests.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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 <paramref name="serviceProvider"/> 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.
|
||||
/// </remarks>
|
||||
/// <param name="serviceProvider">The service provider used to resolve the options of the database context.</param>
|
||||
/// <param name="options">The options builder of the database context being configured.</param>
|
||||
protected virtual void ConfigureDbContextOptions(IServiceProvider serviceProvider, DbContextOptionsBuilder options)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resets the in-memory SQLite database to its original state.
|
||||
/// </summary>
|
||||
public async Task ResetDatabaseAsync()
|
||||
{
|
||||
using IServiceScope scope = Services.CreateScope();
|
||||
LuminaDbContext context = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
context.Books.RemoveRange(context.Books);
|
||||
context.Libraries.RemoveRange(context.Libraries);
|
||||
context.RolePermissions.RemoveRange(context.RolePermissions);
|
||||
context.UserRoles.RemoveRange(context.UserRoles);
|
||||
context.Roles.RemoveRange(context.Roles);
|
||||
context.Permissions.RemoveRange(context.Permissions);
|
||||
context.Users.RemoveRange(context.Users);
|
||||
context.UserPermissions.RemoveRange(context.UserPermissions);
|
||||
|
||||
await context.SaveChangesAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the connection to the database.
|
||||
/// </summary>
|
||||
public new void Dispose()
|
||||
{
|
||||
_connection.Close();
|
||||
base.Dispose();
|
||||
}
|
||||
}
|
||||
+55
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Domain events queue that exposes its enqueuing and dequeuing to a <see cref="DomainEventsQueueProbe"/>.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public sealed class ProbingDomainEventsQueue : IDomainEventsQueue
|
||||
{
|
||||
private readonly ConcurrentQueue<IDomainEvent> _queue = new();
|
||||
private readonly DomainEventsQueueProbe _probe;
|
||||
private readonly IHttpContextAccessor _httpContextAccessor;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ProbingDomainEventsQueue"/> class.
|
||||
/// </summary>
|
||||
/// <param name="probe">The probe that controls and observes the queue.</param>
|
||||
/// <param name="httpContextAccessor">Injected accessor used to identify the request that dequeues the queue.</param>
|
||||
public ProbingDomainEventsQueue(DomainEventsQueueProbe probe, IHttpContextAccessor httpContextAccessor)
|
||||
{
|
||||
_probe = probe;
|
||||
_httpContextAccessor = httpContextAccessor;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a domain event to the queue, before reporting it to the probe.
|
||||
/// </summary>
|
||||
/// <param name="domainEvent">The domain event to enqueue.</param>
|
||||
public void Enqueue(IDomainEvent domainEvent)
|
||||
{
|
||||
_queue.Enqueue(domainEvent);
|
||||
_probe.RecordEnqueue();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Attempts to remove and return the domain event at the beginning of the queue, reporting the attempt to the probe.
|
||||
/// </summary>
|
||||
/// <param name="domainEvent">When this method returns, contains the domain event removed from the queue, or the default value of <see cref="IDomainEvent"/> if the queue is empty.
|
||||
/// </param>
|
||||
/// <returns><see langword="true"/> if a domain event was successfully dequeued, <see langword="false"/> otherwise.</returns>
|
||||
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;
|
||||
}
|
||||
}
|
||||
+51
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Domain event handler that records the publication of a <see cref="FavoriteAddedDomainEvent"/>, together with the state visible at publication time.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public sealed class RecordingFavoriteAddedDomainEventHandler : IDomainEventHandler<FavoriteAddedDomainEvent>
|
||||
{
|
||||
private readonly IServiceScopeFactory _scopeFactory;
|
||||
private readonly DomainEventPublicationProbe _publicationProbe;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RecordingFavoriteAddedDomainEventHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="scopeFactory">Injected factory used to create a database scope independent from the request scope.</param>
|
||||
/// <param name="publicationProbe">Injected probe that records the published event.</param>
|
||||
public RecordingFavoriteAddedDomainEventHandler(IServiceScopeFactory scopeFactory, DomainEventPublicationProbe publicationProbe)
|
||||
{
|
||||
_scopeFactory = scopeFactory;
|
||||
_publicationProbe = publicationProbe;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Records the published <paramref name="domainEvent"/>, checking whether its favorite was already committed.
|
||||
/// </summary>
|
||||
/// <param name="domainEvent">The domain event being published.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
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<LuminaDbContext>();
|
||||
bool wasFavoriteVisible = await dbContext.Favorites
|
||||
.AsNoTracking()
|
||||
.AnyAsync(favorite => favorite.Id == domainEvent.FavoriteId.Value, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
_publicationProbe.RecordPublication(wasFavoriteVisible);
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.Fixtures.Core.Responses.FileSystemManagement.Common;
|
||||
using Lumina.Presentation.Api.Fixtures.Core.Endpoints.FileSystemManagement;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using Xunit;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
|
||||
/// <summary>
|
||||
/// Marks a test to be skipped when the file system does not support the <see cref="FileAttributes.Hidden"/> attribute.
|
||||
/// </summary>
|
||||
[AttributeUsage(AttributeTargets.Method)]
|
||||
[ExcludeFromCodeCoverage]
|
||||
public sealed class SkipWhenHiddenAttributeNotSupportedFactAttribute : FactAttribute
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the reason to skip the test. If set, the test will be skipped instead of executed.
|
||||
/// </summary>
|
||||
public override string Skip => FileSystemStructureFixture.HiddenAttributeIsSupported
|
||||
? string.Empty
|
||||
: "The file system does not support the hidden file attribute, so the hidden elements scenario cannot be set up.";
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Xunit;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
|
||||
/// <summary>
|
||||
/// Helpers shared by the theme integration tests.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public static class ThemeTestHelpers
|
||||
{
|
||||
/// <summary>
|
||||
/// Waits until the bundled 'lumina-default' theme has been installed and activated by the theme detection job at startup.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">The shared API factory whose database is polled.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
public static async Task WaitForBundledThemeAsync(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
const int MAX_ATTEMPTS = 100;
|
||||
const int DELAY_MILLISECONDS = 100;
|
||||
|
||||
for (int attempt = 0; attempt < MAX_ATTEMPTS; attempt++)
|
||||
{
|
||||
using IServiceScope scope = apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
if (await dbContext.Themes.AnyAsync(theme => theme.ThemeId == "lumina-default" && theme.IsCurrent == true))
|
||||
return;
|
||||
|
||||
await Task.Delay(DELAY_MILLISECONDS);
|
||||
}
|
||||
|
||||
Assert.Fail("The bundled theme 'lumina-default' was not installed and activated within the expected time.");
|
||||
}
|
||||
}
|
||||
+78
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Observes the database transactions rolled back on each request through the <see cref="TransactionProbeInterceptor"/>.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public sealed class TransactionProbe
|
||||
{
|
||||
private readonly Lock _signalLock = new();
|
||||
private readonly Dictionary<string, TaskCompletionSource<bool>> _rollbackSignalsByPath = [];
|
||||
|
||||
/// <summary>
|
||||
/// Clears the recorded signals, so that a test observes only the rollbacks that happen after the reset.
|
||||
/// </summary>
|
||||
public void Reset()
|
||||
{
|
||||
lock (_signalLock)
|
||||
_rollbackSignalsByPath.Clear();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Records that the transaction of the request of <paramref name="path"/> was rolled back.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the request whose transaction was rolled back.</param>
|
||||
public void RecordRolledBack(string path)
|
||||
{
|
||||
TaskCompletionSource<bool> signal;
|
||||
lock (_signalLock)
|
||||
{
|
||||
if (!_rollbackSignalsByPath.TryGetValue(path, out signal!))
|
||||
{
|
||||
signal = CreateSignal();
|
||||
_rollbackSignalsByPath[path] = signal;
|
||||
}
|
||||
}
|
||||
signal.TrySetResult(true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Waits until the transaction of the request of <paramref name="path"/> is rolled back.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the request to observe.</param>
|
||||
/// <param name="timeout">The maximum time to wait.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
public async Task WaitForRollbackAsync(string path, TimeSpan timeout)
|
||||
{
|
||||
Task signal;
|
||||
lock (_signalLock)
|
||||
{
|
||||
if (!_rollbackSignalsByPath.TryGetValue(path, out TaskCompletionSource<bool>? 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}.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a completion source that resumes its continuations asynchronously.
|
||||
/// </summary>
|
||||
/// <returns>The created completion source.</returns>
|
||||
private static TaskCompletionSource<bool> CreateSignal()
|
||||
{
|
||||
return new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
}
|
||||
}
|
||||
+63
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Database transaction interceptor that reports the rolled back transactions to a <see cref="TransactionProbe"/>.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public sealed class TransactionProbeInterceptor : DbTransactionInterceptor
|
||||
{
|
||||
private readonly TransactionProbe _probe;
|
||||
private readonly IHttpContextAccessor _httpContextAccessor;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="TransactionProbeInterceptor"/> class.
|
||||
/// </summary>
|
||||
/// <param name="probe">The probe that records the rolled back transactions.</param>
|
||||
/// <param name="httpContextAccessor">Injected accessor used to identify the request whose transaction was rolled back.</param>
|
||||
public TransactionProbeInterceptor(TransactionProbe probe, IHttpContextAccessor httpContextAccessor)
|
||||
{
|
||||
_probe = probe;
|
||||
_httpContextAccessor = httpContextAccessor;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Records that a transaction was rolled back.
|
||||
/// </summary>
|
||||
/// <param name="transaction">The rolled back transaction.</param>
|
||||
/// <param name="eventData">The data of the transaction event.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>A completed task.</returns>
|
||||
public override Task TransactionRolledBackAsync(DbTransaction transaction, TransactionEndEventData eventData, CancellationToken cancellationToken = default)
|
||||
{
|
||||
RecordRolledBack();
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Records that a transaction was rolled back synchronously.
|
||||
/// </summary>
|
||||
/// <param name="transaction">The rolled back transaction.</param>
|
||||
/// <param name="eventData">The data of the transaction event.</param>
|
||||
public override void TransactionRolledBack(DbTransaction transaction, TransactionEndEventData eventData)
|
||||
{
|
||||
RecordRolledBack();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reports the rolled back transaction of the current request to the probe.
|
||||
/// </summary>
|
||||
private void RecordRolledBack()
|
||||
{
|
||||
string path = _httpContextAccessor.HttpContext?.Request.Path.Value ?? string.Empty;
|
||||
_probe.RecordRolledBack(path);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user