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,138 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Api.Common.Authentication;
using Microsoft.AspNetCore.Http;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Security.Claims;
#endregion
namespace Lumina.Presentation.Api.UnitTests.Common.Authentication;
/// <summary>
/// Contains unit tests for the <see cref="HttpContextCurrentUserService"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class HttpContextCurrentUserServiceTests
{
private readonly IHttpContextAccessor _mockHttpContextAccessor;
private readonly HttpContextCurrentUserService _sut;
/// <summary>
/// Initializes a new instance of the <see cref="HttpContextCurrentUserServiceTests"/> class.
/// </summary>
public HttpContextCurrentUserServiceTests()
{
_mockHttpContextAccessor = Substitute.For<IHttpContextAccessor>();
_sut = new HttpContextCurrentUserService(_mockHttpContextAccessor);
}
[Fact]
public void UserId_WhenHttpContextIsNull_ShouldReturnNull()
{
// Arrange
_mockHttpContextAccessor.HttpContext.Returns((HttpContext?)null);
// Act
Guid? result = _sut.UserId;
// Assert
Assert.Null(result);
}
[Fact]
public void UserId_WhenUserIsNull_ShouldReturnNull()
{
// Arrange
HttpContext mockHttpContext = new DefaultHttpContext
{
User = null
};
_mockHttpContextAccessor.HttpContext.Returns(mockHttpContext);
// Act
Guid? result = _sut.UserId;
// Assert
Assert.Null(result);
}
[Fact]
public void UserId_WhenNameIdentifierClaimIsMissing_ShouldReturnNull()
{
// Arrange
HttpContext mockHttpContext = new DefaultHttpContext();
ClaimsIdentity identity = new(
[
new(ClaimTypes.Name, "testuser")
]);
mockHttpContext.User = new ClaimsPrincipal(identity);
_mockHttpContextAccessor.HttpContext.Returns(mockHttpContext);
// Act
Guid? result = _sut.UserId;
// Assert
Assert.Null(result);
}
[Fact]
public void UserId_WhenNameIdentifierClaimIsInvalidGuid_ShouldReturnNull()
{
// Arrange
HttpContext mockHttpContext = new DefaultHttpContext();
ClaimsIdentity identity = new(
[
new(ClaimTypes.NameIdentifier, "not-a-guid")
]);
mockHttpContext.User = new ClaimsPrincipal(identity);
_mockHttpContextAccessor.HttpContext.Returns(mockHttpContext);
// Act
Guid? result = _sut.UserId;
// Assert
Assert.Null(result);
}
[Fact]
public void UserId_WhenNameIdentifierClaimIsValidGuid_ShouldReturnGuid()
{
// Arrange
Guid expectedUserId = Guid.NewGuid();
HttpContext mockHttpContext = new DefaultHttpContext();
ClaimsIdentity identity = new(
[
new(ClaimTypes.NameIdentifier, expectedUserId.ToString())
]);
mockHttpContext.User = new ClaimsPrincipal(identity);
_mockHttpContextAccessor.HttpContext.Returns(mockHttpContext);
// Act
Guid? result = _sut.UserId;
// Assert
Assert.Equal(expectedUserId, result);
}
[Fact]
public void UserId_WhenMultipleNameIdentifierClaimsExist_ShouldReturnFirstValidGuid()
{
// Arrange
Guid expectedUserId = Guid.NewGuid();
HttpContext mockHttpContext = new DefaultHttpContext();
ClaimsIdentity identity = new(
[
new(ClaimTypes.NameIdentifier, expectedUserId.ToString()),
new(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString())
]);
mockHttpContext.User = new ClaimsPrincipal(identity);
_mockHttpContextAccessor.HttpContext.Returns(mockHttpContext);
// Act
Guid? result = _sut.UserId;
// Assert
Assert.Equal(expectedUserId, result);
}
}
@@ -0,0 +1,258 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DomainEvents;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Events;
using Lumina.Presentation.Api.Common.Http;
using Lumina.Presentation.Api.Common.Middlewares;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.UnitTests.Common.Middlewares;
/// <summary>
/// Contains unit tests for the <see cref="EventualConsistencyMiddleware"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class EventualConsistencyMiddlewareTests
{
private readonly EventualConsistencyMiddleware _sut;
private bool _nextInvoked;
/// <summary>
/// Initializes a new instance of the <see cref="EventualConsistencyMiddlewareTests"/> class.
/// </summary>
public EventualConsistencyMiddlewareTests()
{
ILogger<EventualConsistencyMiddleware> mockLogger = Substitute.For<ILogger<EventualConsistencyMiddleware>>();
_sut = new EventualConsistencyMiddleware(
context =>
{
_nextInvoked = true;
return Task.CompletedTask;
},
mockLogger);
}
[Fact]
public async Task InvokeAsync_WhenEndpointOptsOutThroughMetadata_ShouldInvokeNextWithoutTouchingTheDatabase()
{
// Arrange
DefaultHttpContext context = new();
context.SetEndpoint(new Endpoint(
requestDelegate: null,
new EndpointMetadataCollection(new SkipEventualConsistencyMetadata()),
displayName: "GetTrackStream"));
// Act
// The database, the domain event publisher and the domain events queue are deliberately not supplied: an endpoint that opted out through
// metadata must invoke the next delegate without touching any of them, which is exactly what a long lived stream needs.
await _sut.InvokeAsync(context, null!, null!, null!);
// Assert
Assert.True(_nextInvoked);
}
[Fact]
public async Task InvokeAsync_WhenTheClientAbortsAfterASuccessfulOperation_ShouldStillCommitTheTransaction()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-eventual-consistency-abort-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext dbContext = CreateContext(anchorConnection);
using UnitOfWork unitOfWork = new(dbContext, Substitute.For<IDateTimeProvider>());
await dbContext.Database.ExecuteSqlRawAsync("CREATE TABLE CommitProbe (Id INTEGER NOT NULL PRIMARY KEY);");
CapturingHttpResponseFeature responseFeature = new();
DefaultHttpContext httpContext = new();
httpContext.Features.Set<IHttpResponseFeature>(responseFeature);
httpContext.Request.Path = "/api/v1/probe";
httpContext.Response.StatusCode = StatusCodes.Status200OK;
using CancellationTokenSource cancellationTokenSource = new();
httpContext.RequestAborted = cancellationTokenSource.Token;
ILogger<EventualConsistencyMiddleware> mockLogger = Substitute.For<ILogger<EventualConsistencyMiddleware>>();
EventualConsistencyMiddleware sut = new(
async requestContext =>
{
await dbContext.Database.ExecuteSqlRawAsync("INSERT INTO CommitProbe (Id) VALUES (1);");
// The abort happens after the operation has completed, which is exactly when the response token can already be cancelled as the completion callback runs.
cancellationTokenSource.Cancel();
},
mockLogger);
IDomainEventPublisher mockPublisher = Substitute.For<IDomainEventPublisher>();
IDomainEventsQueue mockQueue = Substitute.For<IDomainEventsQueue>();
// Act
await sut.InvokeAsync(httpContext, mockPublisher, unitOfWork, mockQueue);
await responseFeature.InvokeCompletedCallbacksAsync();
// Assert
using LuminaDbContext verificationContext = CreateContext(anchorConnection);
int committedCount = await verificationContext.Database
.SqlQueryRaw<int>("SELECT COUNT(*) AS \"Value\" FROM CommitProbe")
.SingleAsync();
Assert.Equal(1, committedCount);
}
[Fact]
public async Task InvokeAsync_WhenTheResponseIsNotSuccessful_ShouldRollBackTheTransactionAndTheEvents()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-eventual-consistency-rollback-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext dbContext = CreateContext(anchorConnection);
using UnitOfWork unitOfWork = new(dbContext, Substitute.For<IDateTimeProvider>());
await dbContext.Database.ExecuteSqlRawAsync("CREATE TABLE CommitProbe (Id INTEGER NOT NULL PRIMARY KEY);");
CapturingHttpResponseFeature responseFeature = new();
DefaultHttpContext httpContext = new();
httpContext.Features.Set<IHttpResponseFeature>(responseFeature);
httpContext.Request.Path = "/api/v1/probe";
ILogger<EventualConsistencyMiddleware> mockLogger = Substitute.For<ILogger<EventualConsistencyMiddleware>>();
EventualConsistencyMiddleware sut = new(
async requestContext =>
{
await dbContext.Database.ExecuteSqlRawAsync("INSERT INTO CommitProbe (Id) VALUES (1);");
// A client abort is reported by the exception handling middleware as a non-success status, even though the request reached the database.
requestContext.Response.StatusCode = StatusCodes.Status499ClientClosedRequest;
},
mockLogger);
IDomainEventPublisher mockPublisher = Substitute.For<IDomainEventPublisher>();
IDomainEventsQueue mockQueue = Substitute.For<IDomainEventsQueue>();
// Act
await sut.InvokeAsync(httpContext, mockPublisher, unitOfWork, mockQueue);
await responseFeature.InvokeCompletedCallbacksAsync();
// Assert
using LuminaDbContext verificationContext = CreateContext(anchorConnection);
int committedCount = await verificationContext.Database
.SqlQueryRaw<int>("SELECT COUNT(*) AS \"Value\" FROM CommitProbe")
.SingleAsync();
Assert.Equal(0, committedCount);
await mockPublisher.DidNotReceive().PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task InvokeAsync_WhenTheCommitFails_ShouldRollBackTheTransactionAndLogTheFailure()
{
// Arrange
CapturingHttpResponseFeature responseFeature = new();
DefaultHttpContext httpContext = new();
httpContext.Features.Set<IHttpResponseFeature>(responseFeature);
httpContext.Request.Path = "/api/v1/probe";
httpContext.Response.StatusCode = StatusCodes.Status200OK;
ILogger<EventualConsistencyMiddleware> mockLogger = Substitute.For<ILogger<EventualConsistencyMiddleware>>();
mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
EventualConsistencyMiddleware sut = new(_ => Task.CompletedTask, mockLogger);
IUnitOfWork mockUnitOfWork = Substitute.For<IUnitOfWork>();
mockUnitOfWork
.CommitTransactionAsync(Arg.Any<CancellationToken>())
.Returns(Task.FromException(new InvalidOperationException("commit failed")));
IDomainEventPublisher mockPublisher = Substitute.For<IDomainEventPublisher>();
IDomainEventsQueue mockQueue = Substitute.For<IDomainEventsQueue>();
// Act
await sut.InvokeAsync(httpContext, mockPublisher, mockUnitOfWork, mockQueue);
await responseFeature.InvokeCompletedCallbacksAsync();
// Assert
// The completion callback must never leave a transaction open after a failed commit, and it must never publish events that belong to a transaction that did not commit.
await mockUnitOfWork.Received(1).RollbackTransactionAsync(Arg.Any<CancellationToken>());
await mockPublisher.DidNotReceive().PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>());
mockLogger.Received(1).Log(
LogLevel.Error,
Arg.Any<EventId>(),
Arg.Any<object>(),
Arg.Is<Exception>(exception => exception is InvalidOperationException && exception.Message == "commit failed"),
Arg.Any<Func<object, Exception?, string>>());
}
/// <summary>
/// Creates a context backed by the provided in-memory SQLite connection.
/// </summary>
/// <param name="anchorConnection">The open in-memory SQLite connection that keeps the database alive for the duration of the test.</param>
/// <returns>The created context.</returns>
private static LuminaDbContext CreateContext(SqliteConnection anchorConnection)
{
LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>()
.UseSqlite(anchorConnection.ConnectionString)
.Options);
context.Database.EnsureCreated();
return context;
}
/// <summary>
/// Response feature that captures the completed callbacks so a test can run them when the response ends.
/// </summary>
private sealed class CapturingHttpResponseFeature : IHttpResponseFeature
{
private readonly List<Func<Task>> _completedCallbacks = [];
/// <summary>
/// Gets or sets the HTTP status code of the response.
/// </summary>
public int StatusCode { get; set; } = StatusCodes.Status200OK;
/// <summary>
/// Gets or sets the reason phrase of the response.
/// </summary>
public string? ReasonPhrase { get; set; }
/// <summary>
/// Gets or sets the response headers.
/// </summary>
public IHeaderDictionary Headers { get; set; } = new HeaderDictionary();
/// <summary>
/// Gets or sets the response body stream.
/// </summary>
public Stream Body { get; set; } = Stream.Null;
/// <summary>
/// Gets a value indicating whether the response has already started.
/// </summary>
public bool HasStarted => false;
/// <summary>
/// Registers a callback to be invoked when the response is about to start.
/// </summary>
/// <param name="callback">The callback to invoke.</param>
/// <param name="state">The state passed to the callback.</param>
public void OnStarting(Func<object, Task> callback, object state)
{
}
/// <summary>
/// Registers a callback to be invoked when the response has completed.
/// </summary>
/// <param name="callback">The callback to invoke.</param>
/// <param name="state">The state passed to the callback.</param>
public void OnCompleted(Func<object, Task> callback, object state)
{
_completedCallbacks.Add(() => callback(state));
}
/// <summary>
/// Invokes every callback that was registered through <see cref="OnCompleted"/>.
/// </summary>
/// <returns>A task representing the asynchronous operation.</returns>
public async Task InvokeCompletedCallbacksAsync()
{
foreach (Func<Task> callback in _completedCallbacks)
await callback();
}
}
}
@@ -0,0 +1,222 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Api.Common.Middlewares;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NSubstitute;
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.UnitTests.Common.Middlewares;
/// <summary>
/// Contains unit tests for the <see cref="ExceptionHandlingMiddleware"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ExceptionHandlingMiddlewareTests
{
private readonly ILogger<ExceptionHandlingMiddleware> _mockLogger;
private readonly ExceptionHandlingMiddleware _sut;
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
private RequestDelegate _nextDelegate = context => Task.CompletedTask;
/// <summary>
/// Initializes a new instance of the <see cref="ExceptionHandlingMiddlewareTests"/> class.
/// </summary>
public ExceptionHandlingMiddlewareTests()
{
_mockLogger = Substitute.For<ILogger<ExceptionHandlingMiddleware>>();
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
_sut = new ExceptionHandlingMiddleware(context => _nextDelegate(context), _mockLogger);
}
[Fact]
public async Task InvokeAsync_WhenNextThrowsException_ShouldWriteInternalServerErrorProblemDetails()
{
// Arrange
DefaultHttpContext context = new()
{
Response = { Body = new MemoryStream() }
};
_nextDelegate = _ => throw new InvalidOperationException("sensitive internal details");
// Act
await _sut.InvokeAsync(context);
// Assert
Assert.Equal(StatusCodes.Status500InternalServerError, context.Response.StatusCode);
Assert.Equal("application/problem+json", context.Response.ContentType);
context.Response.Body.Seek(0, SeekOrigin.Begin);
using StreamReader reader = new(context.Response.Body, Encoding.UTF8);
string responseBody = await reader.ReadToEndAsync();
ProblemDetails problemDetails = JsonSerializer.Deserialize<ProblemDetails>(responseBody, _jsonOptions)!;
Assert.Equal(StatusCodes.Status500InternalServerError, problemDetails.Status);
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.6.1", problemDetails.Type);
Assert.Equal("InternalServerError", problemDetails.Title);
Assert.Equal("An unexpected error occurred while processing the request.", problemDetails.Detail);
Assert.False(string.IsNullOrEmpty(problemDetails.Extensions["traceId"]?.ToString()));
Assert.DoesNotContain("sensitive internal details", responseBody);
}
[Fact]
public async Task InvokeAsync_WhenNextThrowsException_ShouldLogTheException()
{
// Arrange
DefaultHttpContext context = new()
{
Response = { Body = new MemoryStream() }
};
_nextDelegate = _ => throw new InvalidOperationException("sensitive internal details");
// Act
await _sut.InvokeAsync(context);
// Assert
_mockLogger.Received(1).Log(
LogLevel.Error,
Arg.Any<EventId>(),
Arg.Any<object>(),
Arg.Is<Exception>(exception => exception is InvalidOperationException && exception.Message == "sensitive internal details"),
Arg.Any<Func<object, Exception?, string>>());
}
[Fact]
public async Task InvokeAsync_WhenLoggingIsDisabledAndNextThrowsException_ShouldNotLogTheException()
{
// Arrange
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(false);
DefaultHttpContext context = new()
{
Response = { Body = new MemoryStream() }
};
_nextDelegate = _ => throw new InvalidOperationException("sensitive internal details");
// Act
await _sut.InvokeAsync(context);
// Assert
Assert.Equal(StatusCodes.Status500InternalServerError, context.Response.StatusCode);
_mockLogger.DidNotReceive().Log(
LogLevel.Error,
Arg.Any<EventId>(),
Arg.Any<object>(),
Arg.Any<Exception?>(),
Arg.Any<Func<object, Exception?, string>>());
}
[Fact]
public async Task InvokeAsync_WhenNextThrowsExceptionAndActivityIsCurrent_ShouldUseTheActivityIdAsTraceId()
{
// Arrange
using (Activity activity = new Activity("TestActivity"))
{
activity.Start();
DefaultHttpContext context = new()
{
Response = { Body = new MemoryStream() }
};
_nextDelegate = _ => throw new InvalidOperationException("sensitive internal details");
// Act
await _sut.InvokeAsync(context);
// Assert
context.Response.Body.Seek(0, SeekOrigin.Begin);
using StreamReader reader = new(context.Response.Body, Encoding.UTF8);
string responseBody = await reader.ReadToEndAsync();
ProblemDetails problemDetails = JsonSerializer.Deserialize<ProblemDetails>(responseBody, _jsonOptions)!;
Assert.Equal(activity.Id, problemDetails.Extensions["traceId"]?.ToString());
}
}
[Fact]
public async Task InvokeAsync_WhenNextThrowsOperationCanceledException_ShouldRethrowAndReportTheRequestAsAborted()
{
// Arrange
DefaultHttpContext context = new()
{
Response = { Body = new MemoryStream() }
};
_nextDelegate = _ => throw new OperationCanceledException();
// Act
await Assert.ThrowsAsync<OperationCanceledException>(() => _sut.InvokeAsync(context));
// Assert
// An aborted request is still reported as a non-success status, so the eventual consistency middleware rolls its writes back.
Assert.Equal(StatusCodes.Status499ClientClosedRequest, context.Response.StatusCode);
Assert.Equal(0, context.Response.Body.Length);
}
[Fact]
public async Task InvokeAsync_WhenResponseHasStarted_ShouldRethrowTheException()
{
// Arrange
DefaultHttpContext context = new();
context.Features.Set<IHttpResponseFeature>(new StartedHttpResponseFeature());
context.Response.Body = new MemoryStream();
_nextDelegate = _ => throw new InvalidOperationException("sensitive internal details");
// Act
await Assert.ThrowsAsync<InvalidOperationException>(() => _sut.InvokeAsync(context));
// Assert
Assert.Equal(0, context.Response.Body.Length);
_mockLogger.DidNotReceive().Log(
Arg.Any<LogLevel>(),
Arg.Any<EventId>(),
Arg.Any<object>(),
Arg.Any<Exception>(),
Arg.Any<Func<object, Exception?, string>>());
}
[Fact]
public async Task InvokeAsync_WhenNextCompletesSuccessfully_ShouldNotModifyTheResponse()
{
// Arrange
DefaultHttpContext context = new()
{
Response = { Body = new MemoryStream() }
};
_nextDelegate = context => Task.CompletedTask;
// Act
await _sut.InvokeAsync(context);
// Assert
Assert.Equal(StatusCodes.Status200OK, context.Response.StatusCode);
Assert.Equal(0, context.Response.Body.Length);
}
/// <summary>
/// Response feature that reports the response as already started, for simulating a response that cannot be replaced.
/// </summary>
private sealed class StartedHttpResponseFeature : IHttpResponseFeature
{
public int StatusCode { get; set; } = StatusCodes.Status200OK;
public string? ReasonPhrase { get; set; }
public IHeaderDictionary Headers { get; set; } = new HeaderDictionary();
public Stream Body { get; set; } = Stream.Null;
public bool HasStarted => true;
public void OnStarting(Func<object, Task> callback, object state)
{
}
public void OnCompleted(Func<object, Task> callback, object state)
{
}
}
}
@@ -0,0 +1,41 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary;
using Lumina.Presentation.Api.Common.MimeTypes;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.UnitTests.Common.MimeTypes;
/// <summary>
/// Contains unit tests for the <see cref="ImageMimeTypes"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ImageMimeTypesTests
{
[Theory]
[InlineData(ImageType.BMP, "image/bmp")] // BMP image type.
[InlineData(ImageType.JPEG, "image/jpeg")] // JPEG image type.
[InlineData(ImageType.JPEG_CANON, "image/jpeg")] // Canon JPEG image type.
[InlineData(ImageType.SVG, "image/svg+xml")] // SVG image type.
[InlineData(ImageType.TGA, "image/x-tga")] // TGA image type.
public void GetMimeType_WhenTypeIsKnown_ShouldReturnTheMappedMimeType(ImageType type, string expectedMimeType)
{
// Act
string result = ImageMimeTypes.GetMimeType(type);
// Assert
Assert.Equal(expectedMimeType, result);
}
[Theory]
[InlineData(ImageType.None)] // The none image type has no mime mapping.
[InlineData((ImageType)999)] // An unknown image type has no mime mapping.
public void GetMimeType_WhenTypeIsUnknown_ShouldReturnOpaqueBinaryMimeType(ImageType type)
{
// Act
string result = ImageMimeTypes.GetMimeType(type);
// Assert
Assert.Equal("application/octet-stream", result);
}
}
@@ -0,0 +1,110 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Presentation.Api.Common.MimeTypes;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.UnitTests.Common.MimeTypes;
/// <summary>
/// Contains unit tests for the <see cref="MusicMimeTypes"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MusicMimeTypesTests
{
[Theory]
[InlineData(AudioFileFormat.MP3, "audio/mpeg")] // MP3 audio format.
[InlineData(AudioFileFormat.FLAC, "audio/flac")] // FLAC audio format.
[InlineData(AudioFileFormat.M4A, "audio/mp4")] // M4A audio format.
[InlineData(AudioFileFormat.AAC, "audio/aac")] // AAC audio format.
[InlineData(AudioFileFormat.OGG, "audio/ogg")] // OGG audio format.
[InlineData(AudioFileFormat.OPUS, "audio/ogg")] // Opus audio format.
[InlineData(AudioFileFormat.WAV, "audio/wav")] // WAV audio format.
[InlineData(AudioFileFormat.WMA, "audio/x-ms-wma")] // WMA audio format.
[InlineData(AudioFileFormat.AIFF, "audio/aiff")] // AIFF audio format.
[InlineData(AudioFileFormat.APE, "audio/x-ape")] // APE audio format.
[InlineData(AudioFileFormat.WAVPACK, "audio/x-wavpack")] // WavPack audio format.
[InlineData(AudioFileFormat.DSF, "audio/x-dsf")] // DSF audio format.
[InlineData(AudioFileFormat.DFF, "audio/x-dff")] // DFF audio format.
[InlineData(AudioFileFormat.MATROSKA, "audio/x-matroska")] // Matroska audio format.
public void GetMimeType_WhenFormatIsKnown_ShouldReturnMappedMimeType(AudioFileFormat format, string expectedMimeType)
{
// Act
string result = MusicMimeTypes.GetMimeType(format);
// Assert
Assert.Equal(expectedMimeType, result);
}
[Theory]
[InlineData(AudioFileFormat.None)] // The none audio format has no mime mapping.
[InlineData((AudioFileFormat)999)] // An unknown audio format has no mime mapping.
public void GetMimeType_WhenFormatIsUnknown_ShouldReturnOpaqueBinaryMimeType(AudioFileFormat format)
{
// Act
string result = MusicMimeTypes.GetMimeType(format);
// Assert
Assert.Equal("application/octet-stream", result);
}
[Theory]
[InlineData("MP3", "audio/mpeg")] // MP3 container.
[InlineData("FLAC", "audio/flac")] // FLAC container.
[InlineData("MP4", "audio/mp4")] // MP4 container.
[InlineData("M4A", "audio/mp4")] // M4A container.
[InlineData("AAC", "audio/aac")] // AAC container.
[InlineData("OGG", "audio/ogg")] // OGG container.
[InlineData("OPUS", "audio/ogg")] // Opus container.
[InlineData("WAV", "audio/wav")] // WAV container.
public void GetContainerMimeType_WhenContainerIsMapped_ShouldReturnMappedMimeType(string container, string expectedMimeType)
{
// Act
string result = MusicMimeTypes.GetContainerMimeType(container);
// Assert
Assert.Equal(expectedMimeType, result);
}
[Theory]
[InlineData("mp3", "audio/mpeg")] // Lowercase MP3 container.
[InlineData("Flac", "audio/flac")] // Mixed case FLAC container.
[InlineData("mP4", "audio/mp4")] // Mixed case MP4 container.
[InlineData("opus", "audio/ogg")] // Lowercase Opus container.
public void GetContainerMimeType_WhenContainerDiffersInCase_ShouldReturnMappedMimeType(string container, string expectedMimeType)
{
// Act
string result = MusicMimeTypes.GetContainerMimeType(container);
// Assert
Assert.Equal(expectedMimeType, result);
}
[Theory]
[InlineData(" MP3 ", "audio/mpeg")] // Leading and trailing whitespace around MP3.
[InlineData("\tOGG", "audio/ogg")] // Leading tab around OGG.
[InlineData("WAV\n", "audio/wav")] // Trailing newline around WAV.
public void GetContainerMimeType_WhenContainerHasSurroundingWhitespace_ShouldReturnMappedMimeType(string container, string expectedMimeType)
{
// Act
string result = MusicMimeTypes.GetContainerMimeType(container);
// Assert
Assert.Equal(expectedMimeType, result);
}
[Theory]
[InlineData(null)] // An absent container has no mime mapping.
[InlineData("")] // An empty container has no mime mapping.
[InlineData(" ")] // A whitespace only container has no mime mapping.
[InlineData("WMA")] // A known file format that is not a mapped delivery container.
[InlineData("not-a-container")] // An unknown container has no mime mapping.
public void GetContainerMimeType_WhenContainerIsUnknown_ShouldReturnOpaqueBinaryMimeType(string? container)
{
// Act
string result = MusicMimeTypes.GetContainerMimeType(container);
// Assert
Assert.Equal("application/octet-stream", result);
}
}