Renames project paths from Lumina to Nemera

This commit is contained in:
BinaryAlley committed 2026-11-27 15:34:43 +02:00
1 parent ce6fddb4c9
commit 0f659a4877
6450 files changed

No files matched your search

@@ -0,0 +1,42 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Infrastructure.Common.Models.DTO.Configuration;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Infrastructure.Fixtures.Common.Models.DTO.Configuration;
/// <summary>
/// Fixture class for the <see cref="CorsSettingsDto"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class CorsSettingsDtoFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a valid <see cref="CorsSettingsDto"/>.
/// </summary>
/// <param name="allowedOrigins">Optional. The allowed origins, or <see langword="null"/> to generate valid origins.</param>
/// <returns>The created <see cref="CorsSettingsDto"/>.</returns>
public CorsSettingsDto Create(string[]? allowedOrigins = null)
{
return new CorsSettingsDto
{
AllowedOrigins = allowedOrigins ?? [$"https://{_faker.Internet.DomainName()}", $"http://{_faker.Internet.DomainName()}"]
};
}
/// <summary>
/// Creates a list of <see cref="CorsSettingsDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="CorsSettingsDto"/> instances.</returns>
public List<CorsSettingsDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,43 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Infrastructure.Common.Models.DTO.Configuration;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Cryptography;
#endregion
namespace Lumina.Infrastructure.Fixtures.Common.Models.DTO.Configuration;
/// <summary>
/// Fixture class for the <see cref="EncryptionSettingsDto"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class EncryptionSettingsDtoFixture
{
/// <summary>
/// Creates a valid <see cref="EncryptionSettingsDto"/> with a random 256-bit key.
/// </summary>
/// <param name="secretKey">Optional. The secret key. If not provided, a valid 256-bit (32 byte) key for AES-256 is generated.</param>
/// <returns>The created <see cref="EncryptionSettingsDto"/>.</returns>
public EncryptionSettingsDto Create(string? secretKey = null)
{
byte[] key = new byte[32];
RandomNumberGenerator.Fill(key);
return new EncryptionSettingsDto
{
SecretKey = secretKey ?? Convert.ToBase64String(key)
};
}
/// <summary>
/// Creates a list of <see cref="EncryptionSettingsDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="EncryptionSettingsDto"/> instances.</returns>
public List<EncryptionSettingsDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,56 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Infrastructure.Common.Models.DTO.Configuration;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Cryptography;
#endregion
namespace Lumina.Infrastructure.Fixtures.Common.Models.DTO.Configuration;
/// <summary>
/// Fixture class for the <see cref="JwtSettingsDto"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class JwtSettingsDtoFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a valid <see cref="JwtSettingsDto"/>.
/// </summary>
/// <param name="secretKey">Optional. The secret key used to sign the JWT.</param>
/// <param name="expiryMinutes">Optional. The duration (in minutes) for which the JWT is valid.</param>
/// <param name="issuer">Optional. The issuer of the JWT.</param>
/// <param name="audience">Optional. The intended audience for the JWT.</param>
/// <returns>The created <see cref="JwtSettingsDto"/>.</returns>
public JwtSettingsDto Create(
string? secretKey = null,
int? expiryMinutes = null,
string? issuer = null,
string? audience = null)
{
byte[] key = new byte[32];
RandomNumberGenerator.Fill(key);
return new JwtSettingsDto
{
SecretKey = secretKey ?? Convert.ToBase64String(key),
ExpiryMinutes = expiryMinutes ?? _faker.Random.Int(1, 120),
Issuer = issuer ?? _faker.Company.CompanyName(),
Audience = audience ?? _faker.Company.CompanyName()
};
}
/// <summary>
/// Creates a list of <see cref="JwtSettingsDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="JwtSettingsDto"/> instances.</returns>
public List<JwtSettingsDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,41 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Infrastructure.Fixtures.Common.Models.DTO.Configuration;
/// <summary>
/// Fixture class for the <see cref="PluginsSettingsDto"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PluginsSettingsDtoFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a valid <see cref="PluginsSettingsDto"/>.
/// </summary>
/// <param name="directory">Optional. The directory where the plugin assemblies are located.</param>
/// <returns>The created <see cref="PluginsSettingsDto"/>.</returns>
public PluginsSettingsDto Create(string? directory = null)
{
return new PluginsSettingsDto
{
Directory = directory ?? _faker.System.DirectoryPath()
};
}
/// <summary>
/// Creates a list of <see cref="PluginsSettingsDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="PluginsSettingsDto"/> instances.</returns>
public List<PluginsSettingsDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,61 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Infrastructure.Common.Models.DTO.Configuration;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Infrastructure.Fixtures.Common.Models.DTO.Configuration;
/// <summary>
/// Fixture class for the <see cref="ThemeEngineOptionsDto"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ThemeEngineOptionsDtoFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="ThemeEngineOptionsDto"/>.
/// </summary>
/// <param name="storagePath">Optional directory where installed theme packs are stored.</param>
/// <param name="bundledThemesPath">Optional directory where the shipped theme pack archives are located.</param>
/// <param name="defaultThemeId">Optional identifier of the default theme.</param>
/// <param name="maxArchiveBytes">Optional maximum size of an uploaded theme archive, in bytes.</param>
/// <param name="maxExpandedBytes">Optional maximum total size of an extracted theme pack, in bytes.</param>
/// <param name="maxSingleFileBytes">Optional maximum size of a single file within a theme pack, in bytes.</param>
/// <param name="maxEntries">Optional maximum number of entries in a theme pack archive.</param>
/// <returns>A configured <see cref="ThemeEngineOptionsDto"/> instance.</returns>
public ThemeEngineOptionsDto Create(
string? storagePath = null,
string? bundledThemesPath = null,
string? defaultThemeId = null,
long? maxArchiveBytes = null,
long? maxExpandedBytes = null,
long? maxSingleFileBytes = null,
int? maxEntries = null)
{
return new ThemeEngineOptionsDto
{
StoragePath = storagePath ?? _faker.System.DirectoryPath(),
BundledThemesPath = bundledThemesPath ?? _faker.System.DirectoryPath(),
DefaultThemeId = defaultThemeId ?? _faker.Lorem.Word(),
MaxArchiveBytes = maxArchiveBytes ?? _faker.Random.Long(1_000_000, 100_000_000),
MaxExpandedBytes = maxExpandedBytes ?? _faker.Random.Long(10_000_000, 500_000_000),
MaxSingleFileBytes = maxSingleFileBytes ?? _faker.Random.Long(1_000_000, 50_000_000),
MaxEntries = maxEntries ?? _faker.Random.Int(1, 1000)
};
}
/// <summary>
/// Creates a list of <see cref="ThemeEngineOptionsDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="ThemeEngineOptionsDto"/> instances.</returns>
public List<ThemeEngineOptionsDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,71 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Infrastructure.Common.Models.DTO.Configuration;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Infrastructure.Fixtures.Common.Models.DTO.Configuration;
/// <summary>
/// Fixture class for the <see cref="TranscodingSettingsDto"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class TranscodingSettingsDtoFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="TranscodingSettingsDto"/>.
/// </summary>
/// <param name="ffmpegPath">Optional file name or path of the ffmpeg binary.</param>
/// <param name="maxConcurrentJobs">Optional maximum number of normalization jobs that may run at the same time.</param>
/// <param name="maxConcurrentJobsPerUser">Optional maximum number of normalization jobs a single user may have running at the same time.</param>
/// <param name="maxCacheBytes">Optional maximum total size of the normalized audio cache, in bytes.</param>
/// <param name="jobTimeoutSeconds">Optional maximum duration of a single normalization job, in seconds.</param>
/// <param name="evictionGraceSeconds">Optional period during which a cache entry is protected from eviction, in seconds.</param>
/// <param name="cacheDirectory">
/// Optional directory where normalized audio is cached. When it is not supplied, a generated directory is used. When
/// <paramref name="includeCacheDirectory"/> is <see langword="false"/>, the property stays <see langword="null"/>, which makes the pipeline use the
/// default temporary directory.
/// </param>
/// <param name="includeCacheDirectory">Whether to generate the optional cache directory, defaulting to <see langword="true"/>.</param>
/// <param name="includeFfmpegPath">Whether the ffmpeg path should be included, or forced to <see langword="null"/>, defaulting to <see langword="true"/>.</param>
/// <returns>A configured <see cref="TranscodingSettingsDto"/> instance.</returns>
public TranscodingSettingsDto Create(
string? ffmpegPath = null,
int? maxConcurrentJobs = null,
int? maxConcurrentJobsPerUser = null,
long? maxCacheBytes = null,
int? jobTimeoutSeconds = null,
int? evictionGraceSeconds = null,
string? cacheDirectory = null,
bool includeCacheDirectory = true,
bool includeFfmpegPath = true)
{
int resolvedMaxConcurrentJobs = maxConcurrentJobs ?? _faker.Random.Int(1, 16);
return new TranscodingSettingsDto
{
FfmpegPath = includeFfmpegPath ? (ffmpegPath ?? _faker.System.FileName("exe")) : null!,
MaxConcurrentJobs = resolvedMaxConcurrentJobs,
// A per-user limit above the global one is rejected by the validator, so the generated value never exceeds the global limit.
MaxConcurrentJobsPerUser = maxConcurrentJobsPerUser ?? _faker.Random.Int(1, Math.Max(1, resolvedMaxConcurrentJobs)),
MaxCacheBytes = maxCacheBytes ?? _faker.Random.Long(1_000_000_000, 8_589_934_592),
JobTimeoutSeconds = jobTimeoutSeconds ?? _faker.Random.Int(60, 3600),
EvictionGraceSeconds = evictionGraceSeconds ?? _faker.Random.Int(1, 600),
CacheDirectory = includeCacheDirectory ? cacheDirectory ?? _faker.System.DirectoryPath() : null
};
}
/// <summary>
/// Creates a list of <see cref="TranscodingSettingsDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="TranscodingSettingsDto"/> instances.</returns>
public List<TranscodingSettingsDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,68 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Domain.SharedKernel.Common.Enums.Playback;
using Lumina.Infrastructure.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Infrastructure.Fixtures.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// Fixture class for the <see cref="NormalizedTrackIndexDto"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
internal class NormalizedTrackIndexDtoFixture
{
private readonly Faker _faker = new();
private readonly NormalizedTrackSegmentIndexDtoFixture _normalizedTrackSegmentIndexDtoFixture = new();
/// <summary>
/// Creates a random valid <see cref="NormalizedTrackIndexDto"/>.
/// </summary>
/// <param name="version">Optional version of the index layout.</param>
/// <param name="trackId">Optional Id of the track the cached audio belongs to.</param>
/// <param name="mode">Optional way the audio is delivered.</param>
/// <param name="container">Optional container of the delivered audio.</param>
/// <param name="codec">Optional codec of the delivered audio.</param>
/// <param name="segmentDurationSeconds">Optional duration of each segment, in seconds.</param>
/// <param name="durationInSeconds">Optional duration of the produced and cached audio, in seconds.</param>
/// <param name="segments">
/// Optional segments that make up the delivered audio, in playback order. A caller can supply an explicit list, including an empty one; when it is not
/// supplied a random bounded list is generated.
/// </param>
/// <returns>The created <see cref="NormalizedTrackIndexDto"/>.</returns>
public NormalizedTrackIndexDto Create(
int? version = null,
Guid? trackId = null,
PlaybackDeliveryMode? mode = null,
string? container = null,
string? codec = null,
int? segmentDurationSeconds = null,
int? durationInSeconds = null,
IReadOnlyList<NormalizedTrackSegmentIndexDto>? segments = null)
{
return new NormalizedTrackIndexDto(
version ?? _faker.Random.Int(1, 10),
trackId ?? _faker.Random.Guid(),
mode ?? _faker.PickRandom(PlaybackDeliveryMode.DirectPlay, PlaybackDeliveryMode.Remux, PlaybackDeliveryMode.Transcode),
container ?? _faker.PickRandom("MP4", "OGG", "WAV", "FLAC"),
codec ?? _faker.PickRandom("AAC", "VORBIS", "PCM", "FLAC"),
segmentDurationSeconds ?? _faker.Random.Int(1, 60),
durationInSeconds ?? _faker.Random.Int(1, 100_000),
segments ?? [.. _normalizedTrackSegmentIndexDtoFixture.CreateMany(_faker.Random.Int(1, 5))]
);
}
/// <summary>
/// Creates a list of <see cref="NormalizedTrackIndexDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="NormalizedTrackIndexDto"/> instances.</returns>
public List<NormalizedTrackIndexDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,54 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Infrastructure.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Infrastructure.Fixtures.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// Fixture class for the <see cref="NormalizedTrackSegmentIndexDto"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
internal class NormalizedTrackSegmentIndexDtoFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="NormalizedTrackSegmentIndexDto"/>.
/// </summary>
/// <param name="index">Optional zero based position of the segment in the delivered audio.</param>
/// <param name="startSeconds">Optional time, in seconds from the start of the track, at which the segment starts.</param>
/// <param name="durationSeconds">Optional duration of the segment, in seconds.</param>
/// <param name="fileName">Optional file name of the segment inside the cache entry.</param>
/// <param name="length">Optional length of the segment, in bytes.</param>
/// <returns>The created <see cref="NormalizedTrackSegmentIndexDto"/>.</returns>
public NormalizedTrackSegmentIndexDto Create(
int? index = null,
decimal? startSeconds = null,
decimal? durationSeconds = null,
string? fileName = null,
long? length = null)
{
return new NormalizedTrackSegmentIndexDto(
index ?? _faker.Random.Int(0, 10_000),
startSeconds ?? _faker.Random.Decimal(0m, 100_000m),
durationSeconds ?? _faker.Random.Decimal(1m, 600m),
fileName ?? $"segment{_faker.Random.Int(0, 10_000):D6}{_faker.PickRandom(".m4s", ".mp4", ".ts")}",
length ?? _faker.Random.Long(1, 100_000_000)
);
}
/// <summary>
/// Creates a list of <see cref="NormalizedTrackSegmentIndexDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="NormalizedTrackSegmentIndexDto"/> instances.</returns>
public List<NormalizedTrackSegmentIndexDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(segmentIndex => Create(index: segmentIndex))];
}
}
@@ -0,0 +1,41 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Infrastructure.Common.Models.DTO.Plugins;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Infrastructure.Fixtures.Common.Models.DTO.Plugins;
/// <summary>
/// Fixture class for the <see cref="PluginLoadErrorDto"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
internal class PluginLoadErrorDtoFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a valid <see cref="PluginLoadErrorDto"/>.
/// </summary>
/// <param name="assemblyName">Optional. The file name of the plugin assembly that failed to load, without its extension.</param>
/// <param name="errorMessage">Optional. The error message describing the load failure.</param>
/// <returns>The created <see cref="PluginLoadErrorDto"/>.</returns>
public PluginLoadErrorDto Create(string? assemblyName = null, string? errorMessage = null)
{
return new PluginLoadErrorDto(
assemblyName ?? _faker.Hacker.Noun(),
errorMessage ?? $"Failed to load plugin assembly '{_faker.Hacker.Noun()}.dll': {_faker.Lorem.Sentence()}");
}
/// <summary>
/// Creates a list of <see cref="PluginLoadErrorDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="PluginLoadErrorDto"/> instances.</returns>
public List<PluginLoadErrorDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,55 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.Fixtures.Common.Setup;
/// <summary>
/// <see cref="HttpMessageHandler"/> test double that returns the configured response for every request, without performing any network I/O.
/// </summary>
[ExcludeFromCodeCoverage]
internal sealed class StubHttpMessageHandler : HttpMessageHandler
{
private HttpStatusCode _statusCode;
private byte[] _responseBody;
/// <summary>
/// Initializes a new instance of the <see cref="StubHttpMessageHandler"/> class.
/// </summary>
/// <param name="statusCode">The initial status code of the response to return.</param>
/// <param name="responseBody">The initial body of the response to return.</param>
public StubHttpMessageHandler(HttpStatusCode statusCode = HttpStatusCode.OK, byte[]? responseBody = null)
{
_statusCode = statusCode;
_responseBody = responseBody ?? [];
}
/// <summary>
/// Configures the response to return for every subsequent request.
/// </summary>
/// <param name="statusCode">The status code of the response to return.</param>
/// <param name="responseBody">The body of the response to return.</param>
public void SetResponse(HttpStatusCode statusCode, byte[] responseBody)
{
_statusCode = statusCode;
_responseBody = responseBody;
}
/// <summary>
/// Returns a response with the configured status code and body.
/// </summary>
/// <param name="request">The request, which is ignored.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The configured response.</returns>
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
return Task.FromResult(new HttpResponseMessage(_statusCode)
{
Content = new ByteArrayContent(_responseBody)
});
}
}
@@ -0,0 +1,14 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.Fixtures.Common.Utilities;
/// <summary>
/// Test-support placeholder class for options builder validation utilities tests.
/// </summary>
[ExcludeFromCodeCoverage]
public class OptionsBuilderValidationUtilitiesFixture
{
}
@@ -0,0 +1,21 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.Fixtures.Common.Validation;
/// <summary>
/// Test-support placeholder options type used as the validated options in validation options tests.
/// </summary>
[ExcludeFromCodeCoverage]
public class ValidationOptionsFixture
{
/// <summary>
/// Creates a new <see cref="ValidationOptionsFixture"/> instance.
/// </summary>
/// <returns>A configured <see cref="ValidationOptionsFixture"/> instance.</returns>
public ValidationOptionsFixture Create()
{
return new ValidationOptionsFixture();
}
}
@@ -0,0 +1,34 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Infrastructure.Common.Models.DTO.Configuration;
using Lumina.Infrastructure.Fixtures.Common.Models.DTO.Configuration;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.Fixtures.Core.Authentication;
/// <summary>
/// Test-support class for JWT token generation tests.
/// </summary>
[ExcludeFromCodeCoverage]
public class JwtTokenGeneratorFixture
{
/// <summary>
/// Creates a valid JWT settings model for testing.
/// </summary>
/// <returns>The created settings model.</returns>
public static JwtSettingsDto CreateJwtSettings()
{
return new JwtSettingsDtoFixture().Create();
}
/// <summary>
/// Creates test user credentials.
/// </summary>
/// <returns>A tuple containing the user ID and username.</returns>
public static (string Id, string Username) CreateUserCredentials()
{
return (Guid.NewGuid().ToString(), new Faker().Person.UserName);
}
}
@@ -0,0 +1,37 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.Fixtures.Core.Authentication;
/// <summary>
/// Test-support class for QR code generation tests.
/// </summary>
[ExcludeFromCodeCoverage]
public class QRCodeGeneratorFixture
{
/// <summary>
/// Creates test data for QR code generation.
/// </summary>
/// <returns>A tuple containing username and secret bytes.</returns>
public static (string Username, byte[] Secret) CreateQrCodeTestData()
{
string username = new Faker().Person.UserName;
byte[] secret = new byte[20]; // Standard TOTP secret length.
Random.Shared.NextBytes(secret);
return (username, secret);
}
/// <summary>
/// Gets the expected otpauth URI format for validation.
/// </summary>
/// <param name="username">The username to use in the URI.</param>
/// <param name="base32Secret">The Base32 encoded secret.</param>
/// <returns>The formatted otpauth URI.</returns>
public static string GetExpectedOtpauthUri(string username, string base32Secret)
{
return $"otpauth://totp/Lumina:{Uri.EscapeDataString(username)}?secret={base32Secret}&issuer=Lumina";
}
}
@@ -0,0 +1,109 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
using Lumina.Infrastructure.Core.Authorization;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.Fixtures.Core.Authorization;
/// <summary>
/// Test-support class for the <see cref="AuthorizationService"/> tests.
/// </summary>
[ExcludeFromCodeCoverage]
public class AuthorizationServiceFixture
{
private readonly UserEntityFixture _userEntityFixture = new();
private readonly RoleEntityFixture _roleEntityFixture = new();
private readonly PermissionEntityFixture _permissionEntityFixture = new();
private readonly RolePermissionEntityFixture _rolePermissionEntityFixture = new();
private readonly UserRoleEntityFixture _userRoleEntityFixture = new();
private readonly UserPermissionEntityFixture _userPermissionEntityFixture = new();
/// <summary>
/// Creates a user entity with specified permissions and roles.
/// </summary>
/// <param name="directPermissions">Direct permissions to assign to the user.</param>
/// <param name="rolePermissions">Permissions to assign through roles.</param>
/// <returns>The created user entity.</returns>
public UserEntity CreateUserWithPermissions(
IEnumerable<AuthorizationPermission>? directPermissions = null,
Dictionary<string, IEnumerable<AuthorizationPermission>>? rolePermissions = null)
{
Guid userId = Guid.NewGuid();
DateTime utcNow = DateTime.UtcNow;
UserRoleEntity? userRole = null;
if (rolePermissions is not null)
{
foreach (KeyValuePair<string, IEnumerable<AuthorizationPermission>> rolePerm in rolePermissions)
{
Guid roleId = Guid.NewGuid();
RoleEntity role = _roleEntityFixture.Create(
id: roleId,
roleName: rolePerm.Key,
createdBy: userId,
createdOnUtc: utcNow);
foreach (AuthorizationPermission permission in rolePerm.Value)
{
Guid permissionId = Guid.NewGuid();
PermissionEntity permissionEntity = _permissionEntityFixture.Create(
id: permissionId,
permissionName: permission,
createdBy: userId,
createdOnUtc: utcNow);
role.RolePermissions.Add(_rolePermissionEntityFixture.Create(
role: role,
permission: permissionEntity,
createdBy: userId,
createdOnUtc: utcNow));
}
userRole = _userRoleEntityFixture.Create(
userId: userId,
roleId: roleId,
role: role,
includeUser: false,
createdBy: userId,
createdOnUtc: utcNow);
}
}
UserEntity user = _userEntityFixture.Create(
username: "test-user",
password: "hashed-password",
id: userId,
userRole: userRole,
includeUserRole: true,
createdBy: userId,
createdOnUtc: utcNow);
if (directPermissions is not null)
{
foreach (AuthorizationPermission permission in directPermissions)
{
Guid permissionId = Guid.NewGuid();
PermissionEntity permissionEntity = _permissionEntityFixture.Create(
id: permissionId,
permissionName: permission,
createdBy: userId,
createdOnUtc: utcNow);
user.UserPermissions.Add(_userPermissionEntityFixture.Create(
user,
permissionEntity,
createdOnUtc: utcNow,
createdBy: userId));
}
}
return user;
}
}
@@ -0,0 +1,10 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Authorization.Policies.Common.Base;
#endregion
namespace Lumina.Infrastructure.Fixtures.Core.Authorization;
/// <summary>
/// Example concrete policy for testing generic constraint.
/// </summary>
public interface ITestAuthorizationPolicy : IAuthorizationPolicy { }
@@ -0,0 +1,10 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Authorization.Policies.Common.Base;
#endregion
namespace Lumina.Infrastructure.Fixtures.Core.Authorization;
/// <summary>
/// Test policy interface for unregistered policy scenarios.
/// </summary>
public interface IUnregisteredPolicy : IAuthorizationPolicy { }
@@ -0,0 +1,21 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Authorization.Policies.Common.Base;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.Fixtures.Core.Authorization;
/// <summary>
/// Test policy implementation for registered policy scenarios.
/// </summary>
[ExcludeFromCodeCoverage]
public class TestAuthorizationPolicy : IAuthorizationPolicy
{
public Task<bool> EvaluateAsync(Guid userId, PolicyContext? context, CancellationToken cancellationToken)
{
return Task.FromResult(true);
}
}
@@ -0,0 +1,49 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Infrastructure.Common.Models.DTO.Configuration;
using Lumina.Infrastructure.Fixtures.Common.Models.DTO.Configuration;
using Microsoft.Extensions.Options;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Security.Cryptography;
#endregion
namespace Lumina.Infrastructure.Fixtures.Core.Security;
/// <summary>
/// Test-support class for cryptography service tests.
/// </summary>
[ExcludeFromCodeCoverage]
public class CryptographyServiceFixture
{
private readonly EncryptionSettingsDtoFixture _encryptionSettingsDtoFixture = new();
/// <summary>
/// Creates a valid encryption settings model for testing.
/// </summary>
/// <returns>The configured options.</returns>
public IOptions<EncryptionSettingsDto> CreateEncryptionSettings()
{
// Generate a valid 256-bit (32 byte) key for AES-256.
byte[] key = new byte[32];
RandomNumberGenerator.Fill(key);
string base64Key = Convert.ToBase64String(key);
EncryptionSettingsDto settings = _encryptionSettingsDtoFixture.Create(secretKey: base64Key);
IOptions<EncryptionSettingsDto> options = Substitute.For<IOptions<EncryptionSettingsDto>>();
options.Value.Returns(settings);
return options;
}
/// <summary>
/// Creates test data for encryption/decryption.
/// </summary>
/// <returns>A string to be encrypted/decrypted.</returns>
public string CreateTestData()
{
return new Faker().Lorem.Sentence();
}
}
@@ -0,0 +1,14 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.Fixtures.Core.Themes;
/// <summary>
/// Describes a single entry of a theme pack ZIP archive built by the <see cref="ThemePackFixture"/>.
/// </summary>
/// <param name="Path">The entry path inside the archive.</param>
/// <param name="Content">The text content of the entry.</param>
/// <param name="UnixFileType">Optional Unix file type for the entry, used to simulate special file types such as symbolic links.</param>
[ExcludeFromCodeCoverage]
public sealed record ThemeArchiveEntry(string Path, string Content, int? UnixFileType = null);
@@ -0,0 +1,148 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text.Json;
#endregion
namespace Lumina.Infrastructure.Fixtures.Core.Themes;
/// <summary>
/// Fixture class for generating theme pack ZIP archives used by theme tests.
/// </summary>
[ExcludeFromCodeCoverage]
public sealed class ThemePackFixture
{
/// <summary>
/// Creates a valid theme pack ZIP archive containing a manifest, the template files referenced by it and a preview asset.
/// </summary>
/// <param name="themeId">Optional theme id written to the manifest.</param>
/// <param name="name">Optional display name written to the manifest.</param>
/// <param name="description">Optional description written to the manifest.</param>
/// <param name="author">Optional author written to the manifest.</param>
/// <param name="version">Optional version written to the manifest.</param>
/// <param name="schemaVersion">Optional schema version written to the manifest.</param>
/// <param name="templates">Optional template mappings written to the manifest.</param>
/// <param name="preview">Optional preview path written to the manifest, or <see langword="null"/> to omit the preview.</param>
/// <param name="defaultTemplateContent">Optional content for the default template file.</param>
/// <param name="additionalFiles">Optional additional files written into the archive.</param>
/// <param name="includePreviewAsset">Whether to include the preview asset file in the archive or not.</param>
/// <returns>The created theme pack ZIP archive.</returns>
public byte[] Create(
string themeId = "test-theme",
string? name = null,
string? description = null,
string? author = null,
string? version = null,
int? schemaVersion = null,
Dictionary<string, string>? templates = null,
string? preview = "assets/preview.png",
string? defaultTemplateContent = null,
IReadOnlyDictionary<string, string>? additionalFiles = null,
bool includePreviewAsset = true)
{
Dictionary<string, string> manifestTemplates = templates ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
["default"] = "templates/default.html"
};
string manifestJson = CreateManifestJson(
themeId,
name,
description,
author,
version,
schemaVersion,
manifestTemplates,
preview);
List<ThemeArchiveEntry> entries = [new("theme.json", manifestJson)];
foreach ((string key, string templatePath) in manifestTemplates)
entries.Add(new(templatePath, defaultTemplateContent ?? $"<html><body>{key} template</body></html>"));
if (preview is not null && includePreviewAsset)
entries.Add(new("assets/preview.png", "preview-image-bytes"));
if (additionalFiles is not null)
entries.AddRange(additionalFiles.Select(file => new ThemeArchiveEntry(file.Key, file.Value)));
return CreateArchive([.. entries]);
}
/// <summary>
/// Creates the JSON content of a theme manifest with test defaults that can be overridden per field.
/// </summary>
/// <param name="themeId">Optional theme id written to the manifest.</param>
/// <param name="name">Optional display name written to the manifest.</param>
/// <param name="description">Optional description written to the manifest.</param>
/// <param name="author">Optional author written to the manifest.</param>
/// <param name="version">Optional version written to the manifest.</param>
/// <param name="schemaVersion">Optional schema version written to the manifest.</param>
/// <param name="templates">Optional template mappings written to the manifest.</param>
/// <param name="preview">Optional preview path written to the manifest, or <see langword="null"/> to omit the preview.</param>
/// <returns>The created manifest JSON content.</returns>
public string CreateManifestJson(
string themeId = "test-theme",
string? name = null,
string? description = null,
string? author = null,
string? version = null,
int? schemaVersion = null,
Dictionary<string, string>? templates = null,
string? preview = "assets/preview.png")
{
object manifest = new
{
schemaVersion = schemaVersion ?? 1,
id = themeId,
name = name ?? "Test Theme",
description = description ?? "A theme used for testing.",
author = author ?? "Lumina Tests",
version = version ?? "1.0.0",
preview,
templates = templates ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
["default"] = "templates/default.html"
}
};
return JsonSerializer.Serialize(manifest);
}
/// <summary>
/// Creates a ZIP archive from the provided entries, allowing tests to build arbitrary valid and invalid theme packs.
/// </summary>
/// <param name="entries">The entries to write into the archive.</param>
/// <returns>The created ZIP archive bytes.</returns>
public byte[] CreateArchive(params ThemeArchiveEntry[] entries)
{
using MemoryStream output = new();
using (ZipArchive archive = new(output, ZipArchiveMode.Create, leaveOpen: true))
{
foreach (ThemeArchiveEntry entry in entries)
{
ZipArchiveEntry zipEntry = archive.CreateEntry(entry.Path);
if (entry.UnixFileType is not null)
zipEntry.ExternalAttributes = (entry.UnixFileType.Value << 16) | 0x81A4;
using StreamWriter writer = new(zipEntry.Open());
writer.Write(entry.Content);
}
}
return output.ToArray();
}
/// <summary>
/// Creates multiple valid theme pack ZIP archives with randomized test data.
/// </summary>
/// <param name="count">Number of archives to create.</param>
/// <returns>List of configured theme pack ZIP archives.</returns>
public List<byte[]> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(index => Create(themeId: $"test-theme-{index}"))];
}
}
@@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>enable</Nullable>
<BaseOutputPath>$(SolutionDir)..\bin\api\</BaseOutputPath>
<IsPackable>false</IsPackable>
<IsTestProject>false</IsTestProject>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoFixture" />
<PackageReference Include="AutoFixture.AutoNSubstitute" />
<PackageReference Include="AutoFixture.Xunit2" />
<PackageReference Include="Bogus" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\src\Lumina.Infrastructure\Lumina.Infrastructure.csproj" />
<ProjectReference Include="..\Lumina.Application.Fixtures\Lumina.Application.Fixtures.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,21 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Lumina.Infrastructure.Fixtures")]
[assembly: AssemblyProduct("Lumina.Infrastructure.Fixtures")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("A1B2C3D4-0004-4A5B-9C0D-444444444444")]
[assembly: InternalsVisibleTo("Lumina.Infrastructure.UnitTests")]
[assembly: InternalsVisibleTo("Lumina.Infrastructure.IntegrationTests")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]