Adds the unit tests for the theming feature

This commit is contained in:
BinaryAlley committed 2026-08-21 09:43:10 -07:00
1 parent 9c83e5dfa7
commit baa6450406
47 files changed
+8234 -8

No files matched your search

@@ -0,0 +1,80 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.Themes;
using Lumina.Application.Core.Themes.Management.Commands.DeleteTheme;
using Lumina.Contracts.Fixtures.Core.Requests.Themes;
using Lumina.Contracts.Requests.Themes;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.Themes;
/// <summary>
/// Contains unit tests for the <see cref="DeleteThemeRequestMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeleteThemeRequestMappingTests
{
private readonly DeleteThemeRequestFixture _deleteThemeRequestFixture = new();
[Fact]
public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly()
{
// Arrange
DeleteThemeRequest request = _deleteThemeRequestFixture.Create();
// Act
DeleteThemeCommand result = request.ToCommand();
// Assert
Assert.NotNull(result);
Assert.Equal(request.ThemeId, result.ThemeId);
}
[Theory]
[InlineData("default-theme")]
[InlineData("my-uploaded-theme")]
[InlineData("T-123")]
public void ToCommand_WhenMappingDifferentThemeIds_ShouldMapCorrectly(string themeId)
{
// Arrange
DeleteThemeRequest request = new(themeId);
// Act
DeleteThemeCommand result = request.ToCommand();
// Assert
Assert.NotNull(result);
Assert.Equal(themeId, result.ThemeId);
}
[Fact]
public void ToCommand_WhenThemeIdIsNull_ShouldMapNull()
{
// Arrange
DeleteThemeRequest request = new(null);
// Act
DeleteThemeCommand result = request.ToCommand();
// Assert
Assert.NotNull(result);
Assert.Null(result.ThemeId);
}
[Fact]
public void ToCommand_WhenMappingMultipleRequests_ShouldMapAllCorrectly()
{
// Arrange
List<DeleteThemeRequest> requests = _deleteThemeRequestFixture.CreateMany();
// Act
List<DeleteThemeCommand> results = [.. requests.Select(r => r.ToCommand())];
// Assert
Assert.Equal(requests.Count, results.Count);
for (int i = 0; i < requests.Count; i++)
Assert.Equal(requests[i].ThemeId, results[i].ThemeId);
}
}
@@ -0,0 +1,80 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.Themes;
using Lumina.Application.Core.Themes.Management.Queries.GetThemeArchive;
using Lumina.Contracts.Fixtures.Core.Requests.Themes;
using Lumina.Contracts.Requests.Themes;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.Themes;
/// <summary>
/// Contains unit tests for the <see cref="GetThemeArchiveRequestMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetThemeArchiveRequestMappingTests
{
private readonly GetThemeArchiveRequestFixture _getThemeArchiveRequestFixture = new();
[Fact]
public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly()
{
// Arrange
GetThemeArchiveRequest request = _getThemeArchiveRequestFixture.Create();
// Act
GetThemeArchiveQuery result = request.ToQuery();
// Assert
Assert.NotNull(result);
Assert.Equal(request.ThemeId, result.ThemeId);
}
[Theory]
[InlineData("default-theme")]
[InlineData("my-uploaded-theme")]
[InlineData("T-123")]
public void ToQuery_WhenMappingDifferentThemeIds_ShouldMapCorrectly(string themeId)
{
// Arrange
GetThemeArchiveRequest request = new(themeId);
// Act
GetThemeArchiveQuery result = request.ToQuery();
// Assert
Assert.NotNull(result);
Assert.Equal(themeId, result.ThemeId);
}
[Fact]
public void ToQuery_WhenThemeIdIsNull_ShouldMapNull()
{
// Arrange
GetThemeArchiveRequest request = new(null);
// Act
GetThemeArchiveQuery result = request.ToQuery();
// Assert
Assert.NotNull(result);
Assert.Null(result.ThemeId);
}
[Fact]
public void ToQuery_WhenMappingMultipleRequests_ShouldMapAllCorrectly()
{
// Arrange
List<GetThemeArchiveRequest> requests = _getThemeArchiveRequestFixture.CreateMany();
// Act
List<GetThemeArchiveQuery> results = [.. requests.Select(r => r.ToQuery())];
// Assert
Assert.Equal(requests.Count, results.Count);
for (int i = 0; i < requests.Count; i++)
Assert.Equal(requests[i].ThemeId, results[i].ThemeId);
}
}
@@ -0,0 +1,86 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.Themes;
using Lumina.Application.Core.Themes.Management.Queries.GetThemeAsset;
using Lumina.Contracts.Fixtures.Core.Requests.Themes;
using Lumina.Contracts.Requests.Themes;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.Themes;
/// <summary>
/// Contains unit tests for the <see cref="GetThemeAssetRequestMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetThemeAssetRequestMappingTests
{
private readonly GetThemeAssetRequestFixture _getThemeAssetRequestFixture = new();
[Fact]
public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly()
{
// Arrange
GetThemeAssetRequest request = _getThemeAssetRequestFixture.Create();
// Act
GetThemeAssetQuery result = request.ToQuery();
// Assert
Assert.NotNull(result);
Assert.Equal(request.ThemeId, result.ThemeId);
Assert.Equal(request.AssetPath, result.AssetPath);
}
[Theory]
[InlineData("default-theme", "assets/logo.png")]
[InlineData("my-theme", "css/main.css")]
[InlineData("T-123", "js/app.js")]
public void ToQuery_WhenMappingDifferentThemeIdsAndAssetPaths_ShouldMapCorrectly(string themeId, string assetPath)
{
// Arrange
GetThemeAssetRequest request = new(themeId, assetPath);
// Act
GetThemeAssetQuery result = request.ToQuery();
// Assert
Assert.NotNull(result);
Assert.Equal(themeId, result.ThemeId);
Assert.Equal(assetPath, result.AssetPath);
}
[Fact]
public void ToQuery_WhenFieldsAreNull_ShouldMapNull()
{
// Arrange
GetThemeAssetRequest request = new(null, null);
// Act
GetThemeAssetQuery result = request.ToQuery();
// Assert
Assert.NotNull(result);
Assert.Null(result.ThemeId);
Assert.Null(result.AssetPath);
}
[Fact]
public void ToQuery_WhenMappingMultipleRequests_ShouldMapAllCorrectly()
{
// Arrange
List<GetThemeAssetRequest> requests = _getThemeAssetRequestFixture.CreateMany();
// Act
List<GetThemeAssetQuery> results = [.. requests.Select(r => r.ToQuery())];
// Assert
Assert.Equal(requests.Count, results.Count);
for (int i = 0; i < requests.Count; i++)
{
Assert.Equal(requests[i].ThemeId, results[i].ThemeId);
Assert.Equal(requests[i].AssetPath, results[i].AssetPath);
}
}
}
@@ -0,0 +1,86 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.Themes;
using Lumina.Application.Core.Themes.Management.Queries.GetThemeTemplate;
using Lumina.Contracts.Fixtures.Core.Requests.Themes;
using Lumina.Contracts.Requests.Themes;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.Themes;
/// <summary>
/// Contains unit tests for the <see cref="GetThemeTemplateRequestMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetThemeTemplateRequestMappingTests
{
private readonly GetThemeTemplateRequestFixture _getThemeTemplateRequestFixture = new();
[Fact]
public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly()
{
// Arrange
GetThemeTemplateRequest request = _getThemeTemplateRequestFixture.Create();
// Act
GetThemeTemplateQuery result = request.ToQuery();
// Assert
Assert.NotNull(result);
Assert.Equal(request.ThemeId, result.ThemeId);
Assert.Equal(request.PageKey, result.PageKey);
}
[Theory]
[InlineData("default-theme", "home")]
[InlineData("my-theme", "library")]
[InlineData("T-123", "settings")]
public void ToQuery_WhenMappingDifferentThemeIdsAndPageKeys_ShouldMapCorrectly(string themeId, string pageKey)
{
// Arrange
GetThemeTemplateRequest request = new(themeId, pageKey);
// Act
GetThemeTemplateQuery result = request.ToQuery();
// Assert
Assert.NotNull(result);
Assert.Equal(themeId, result.ThemeId);
Assert.Equal(pageKey, result.PageKey);
}
[Fact]
public void ToQuery_WhenFieldsAreNull_ShouldMapNull()
{
// Arrange
GetThemeTemplateRequest request = new(null, null);
// Act
GetThemeTemplateQuery result = request.ToQuery();
// Assert
Assert.NotNull(result);
Assert.Null(result.ThemeId);
Assert.Null(result.PageKey);
}
[Fact]
public void ToQuery_WhenMappingMultipleRequests_ShouldMapAllCorrectly()
{
// Arrange
List<GetThemeTemplateRequest> requests = _getThemeTemplateRequestFixture.CreateMany();
// Act
List<GetThemeTemplateQuery> results = [.. requests.Select(r => r.ToQuery())];
// Assert
Assert.Equal(requests.Count, results.Count);
for (int i = 0; i < requests.Count; i++)
{
Assert.Equal(requests[i].ThemeId, results[i].ThemeId);
Assert.Equal(requests[i].PageKey, results[i].PageKey);
}
}
}
@@ -0,0 +1,80 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.Themes;
using Lumina.Application.Core.Themes.Management.Commands.SetCurrentTheme;
using Lumina.Contracts.Fixtures.Core.Requests.Themes;
using Lumina.Contracts.Requests.Themes;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.Themes;
/// <summary>
/// Contains unit tests for the <see cref="SetCurrentThemeRequestMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetCurrentThemeRequestMappingTests
{
private readonly SetCurrentThemeRequestFixture _setCurrentThemeRequestFixture = new();
[Fact]
public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly()
{
// Arrange
SetCurrentThemeRequest request = _setCurrentThemeRequestFixture.Create();
// Act
SetCurrentThemeCommand result = request.ToCommand();
// Assert
Assert.NotNull(result);
Assert.Equal(request.ThemeId, result.ThemeId);
}
[Theory]
[InlineData("default-theme")]
[InlineData("my-uploaded-theme")]
[InlineData("T-123")]
public void ToCommand_WhenMappingDifferentThemeIds_ShouldMapCorrectly(string themeId)
{
// Arrange
SetCurrentThemeRequest request = new(themeId);
// Act
SetCurrentThemeCommand result = request.ToCommand();
// Assert
Assert.NotNull(result);
Assert.Equal(themeId, result.ThemeId);
}
[Fact]
public void ToCommand_WhenThemeIdIsNull_ShouldMapNull()
{
// Arrange
SetCurrentThemeRequest request = new(null);
// Act
SetCurrentThemeCommand result = request.ToCommand();
// Assert
Assert.NotNull(result);
Assert.Null(result.ThemeId);
}
[Fact]
public void ToCommand_WhenMappingMultipleRequests_ShouldMapAllCorrectly()
{
// Arrange
List<SetCurrentThemeRequest> requests = _setCurrentThemeRequestFixture.CreateMany();
// Act
List<SetCurrentThemeCommand> results = [.. requests.Select(r => r.ToCommand())];
// Assert
Assert.Equal(requests.Count, results.Count);
for (int i = 0; i < requests.Count; i++)
Assert.Equal(requests[i].ThemeId, results[i].ThemeId);
}
}
@@ -0,0 +1,93 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Themes;
using Lumina.Application.Common.Mapping.Themes;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes;
using Lumina.Contracts.Responses.Themes;
using Lumina.Domain.SharedKernel.Common.Enums.Themes;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.Themes;
/// <summary>
/// Contains unit tests for the <see cref="ThemeEntityMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ThemeEntityMappingTests
{
private readonly ThemeEntityFixture _themeEntityFixture = new();
[Fact]
public void ToResponse_WhenMappingValidThemeEntity_ShouldMapAllFields()
{
// Arrange
ThemeEntity theme = _themeEntityFixture.Create(
themeId: "my-theme",
name: "My Theme",
description: "A nice theme",
author: "Jane Doe",
version: "1.2.3",
previewPath: "preview.png",
installSource: ThemeInstallSource.Bundled,
isCurrent: true,
isDeleted: false);
// Act
ThemeResponse result = theme.ToResponse();
// Assert
Assert.NotNull(result);
Assert.Equal(theme.Id, result.Id);
Assert.Equal(theme.ThemeId, result.ThemeId);
Assert.Equal(theme.Name, result.Name);
Assert.Equal(theme.Description, result.Description);
Assert.Equal(theme.Author, result.Author);
Assert.Equal(theme.Version, result.Version);
Assert.Equal(theme.PreviewPath, result.PreviewPath);
Assert.Equal(theme.InstallSource, result.InstallSource);
Assert.Equal(theme.IsCurrent, result.IsCurrent);
Assert.Equal(theme.InstalledAtUtc, result.InstalledAtUtc);
}
[Fact]
public void ToResponse_WhenPreviewPathIsNull_ShouldMapNullPreviewPath()
{
// Arrange
ThemeEntity theme = _themeEntityFixture.Create();
theme.PreviewPath = null;
// Act
ThemeResponse result = theme.ToResponse();
// Assert
Assert.Null(result.PreviewPath);
}
[Fact]
public void ToResponse_WhenIsCurrentIsNull_ShouldMapNullIsCurrent()
{
// Arrange
ThemeEntity theme = _themeEntityFixture.Create();
theme.IsCurrent = null;
// Act
ThemeResponse result = theme.ToResponse();
// Assert
Assert.Null(result.IsCurrent);
}
[Fact]
public void ToResponse_WhenMappingUploadedTheme_ShouldMapInstallSourceAsUploaded()
{
// Arrange
ThemeEntity theme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Uploaded, isCurrent: null);
// Act
ThemeResponse result = theme.ToResponse();
// Assert
Assert.Equal(ThemeInstallSource.Uploaded, result.InstallSource);
}
}
@@ -0,0 +1,406 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Themes;
using Lumina.Application.Common.DataAccess.Repositories.Themes;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Themes;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.Themes.Management.Commands.DeleteTheme;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes;
using Lumina.Application.Fixtures.Core.Themes.Management.Commands.DeleteTheme;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Themes;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.Themes.Management.Commands.DeleteTheme;
/// <summary>
/// Contains unit tests for the <see cref="DeleteThemeCommandHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeleteThemeCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IThemeService _mockThemeService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly IValidator<DeleteThemeCommand> _mockValidator;
private readonly IThemeRepository _mockThemeRepository;
private readonly DeleteThemeCommandHandler _sut;
private readonly DeleteThemeCommandFixture _deleteThemeCommandFixture = new();
private readonly ThemeEntityFixture _themeEntityFixture = new();
private readonly Guid _userId;
/// <summary>
/// Initializes a new instance of the <see cref="DeleteThemeCommandHandlerTests"/> class.
/// </summary>
public DeleteThemeCommandHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockThemeService = Substitute.For<IThemeService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockValidator = Substitute.For<IValidator<DeleteThemeCommand>>();
_mockThemeRepository = Substitute.For<IThemeRepository>();
_userId = Guid.NewGuid();
_mockValidator.Validate(Arg.Any<DeleteThemeCommand>())
.Returns([]);
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>())
.Returns(true);
_mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository);
_mockThemeService.DeleteAsync(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(Result.Success);
_sut = new DeleteThemeCommandHandler(
_mockUnitOfWork,
_mockThemeService,
_mockCurrentUserService,
_mockAuthorizationService,
_mockValidator);
}
[Fact]
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutAnyDownstreamCalls()
{
// Arrange
DeleteThemeCommand command = _deleteThemeCommandFixture.Create();
_mockValidator.Validate(Arg.Any<DeleteThemeCommand>())
.Returns([Errors.Themes.ThemeIdCannotBeEmpty]);
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Themes.ThemeIdCannotBeEmpty, result.FirstError);
await _mockThemeRepository.DidNotReceive().GetByThemeIdAsync(Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
DeleteThemeCommand command = _deleteThemeCommandFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockThemeRepository.DidNotReceive().GetByThemeIdAsync(Arg.Any<string>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError()
{
// Arrange
DeleteThemeCommand command = _deleteThemeCommandFixture.Create();
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockThemeRepository.DidNotReceive().GetByThemeIdAsync(Arg.Any<string>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetThemeFails_ShouldReturnError()
{
// Arrange
DeleteThemeCommand command = _deleteThemeCommandFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to get theme");
_mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenThemeDoesNotExist_ShouldReturnThemeNotFoundError()
{
// Arrange
DeleteThemeCommand command = _deleteThemeCommandFixture.Create();
_mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(null));
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Themes.ThemeNotFound, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenThemeIsAlreadyDeleted_ShouldReturnThemeNotFoundError()
{
// Arrange
DeleteThemeCommand command = _deleteThemeCommandFixture.Create();
ThemeEntity theme = _themeEntityFixture.Create(themeId: command.ThemeId, isDeleted: true);
_mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(theme));
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Themes.ThemeNotFound, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetAllThemesFails_ShouldReturnError()
{
// Arrange
DeleteThemeCommand command = _deleteThemeCommandFixture.Create();
ThemeEntity theme = _themeEntityFixture.Create(themeId: command.ThemeId, installSource: ThemeInstallSource.Uploaded, isDeleted: false);
Error error = Error.Failure("Database.Error", "Failed to get all themes");
_mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(theme));
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenDeletingLastBundledTheme_ShouldReturnLastBundledThemeCannotBeDeletedError()
{
// Arrange
DeleteThemeCommand command = _deleteThemeCommandFixture.Create();
ThemeEntity theme = _themeEntityFixture.Create(themeId: command.ThemeId, installSource: ThemeInstallSource.Bundled, isDeleted: false);
ThemeEntity userTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Uploaded, isDeleted: false);
_mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(theme));
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(Result.From<IEnumerable<ThemeEntity>>([theme, userTheme]));
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Themes.LastBundledThemeCannotBeDeleted, result.FirstError);
await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockThemeService.DidNotReceive().DeleteAsync(Arg.Any<string>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenDeletingCurrentThemeWithoutReplacement_ShouldReturnThemeCannotBeDeletedError()
{
// Arrange
DeleteThemeCommand command = _deleteThemeCommandFixture.Create();
ThemeEntity theme = _themeEntityFixture.Create(themeId: command.ThemeId, installSource: ThemeInstallSource.Uploaded, isCurrent: true, includeIsCurrent: true, isDeleted: false);
_mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(theme));
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(Result.From<IEnumerable<ThemeEntity>>([theme]));
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Themes.ThemeCannotBeDeleted, result.FirstError);
await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockThemeService.DidNotReceive().DeleteAsync(Arg.Any<string>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenDeletingBundledTheme_ShouldSoftDeleteItAndRemoveStoredFiles()
{
// Arrange
DeleteThemeCommand command = _deleteThemeCommandFixture.Create();
ThemeEntity theme = _themeEntityFixture.Create(themeId: command.ThemeId, installSource: ThemeInstallSource.Bundled, isCurrent: false, includeIsCurrent: true, isDeleted: false);
ThemeEntity otherBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false);
_mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(theme));
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(Result.From<IEnumerable<ThemeEntity>>([theme, otherBundledTheme]));
_mockThemeRepository.UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockThemeRepository.Received(1).UpdateAsync(
Arg.Is<ThemeEntity>(entity => entity.Id == theme.Id && entity.IsDeleted && entity.IsCurrent == null && entity.UpdatedBy == _userId),
Arg.Any<CancellationToken>());
await _mockThemeRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockThemeService.Received(1).DeleteAsync(theme.ThemeId, Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenDeletingUserTheme_ShouldHardDeleteItAndRemoveStoredFiles()
{
// Arrange
DeleteThemeCommand command = _deleteThemeCommandFixture.Create();
ThemeEntity theme = _themeEntityFixture.Create(themeId: command.ThemeId, installSource: ThemeInstallSource.Uploaded, isCurrent: false, includeIsCurrent: true, isDeleted: false);
ThemeEntity bundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false);
_mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(theme));
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(Result.From<IEnumerable<ThemeEntity>>([theme, bundledTheme]));
_mockThemeRepository.DeleteByIdAsync(theme.Id, Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockThemeRepository.Received(1).DeleteByIdAsync(theme.Id, Arg.Any<CancellationToken>());
await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockThemeService.Received(1).DeleteAsync(theme.ThemeId, Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenHardDeleteFails_ShouldReturnErrorWithoutRemovingStoredFiles()
{
// Arrange
DeleteThemeCommand command = _deleteThemeCommandFixture.Create();
ThemeEntity theme = _themeEntityFixture.Create(themeId: command.ThemeId, installSource: ThemeInstallSource.Uploaded, isCurrent: false, includeIsCurrent: true, isDeleted: false);
ThemeEntity bundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false);
Error error = Error.Failure("Database.Error", "Failed to delete theme");
_mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(theme));
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(Result.From<IEnumerable<ThemeEntity>>([theme, bundledTheme]));
_mockThemeRepository.DeleteByIdAsync(theme.Id, Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockThemeService.DidNotReceive().DeleteAsync(Arg.Any<string>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenDeletingCurrentBundledTheme_ShouldSwitchToDefaultReplacementThemeAndSoftDelete()
{
// Arrange
DeleteThemeCommand command = _deleteThemeCommandFixture.Create();
ThemeEntity theme = _themeEntityFixture.Create(themeId: command.ThemeId, installSource: ThemeInstallSource.Bundled, isCurrent: true, includeIsCurrent: true, isDeleted: false);
ThemeEntity replacementTheme = _themeEntityFixture.Create(themeId: "default-theme", installSource: ThemeInstallSource.Bundled, isCurrent: false, includeIsCurrent: true, isDeleted: false);
_mockThemeService.DefaultThemeId.Returns(replacementTheme.ThemeId);
_mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(theme));
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(Result.From<IEnumerable<ThemeEntity>>([theme, replacementTheme]));
_mockThemeRepository.UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockThemeRepository.Received(1).UpdateAsync(
Arg.Is<ThemeEntity>(entity => entity.Id == replacementTheme.Id && entity.IsCurrent == true),
Arg.Any<CancellationToken>());
await _mockThemeRepository.Received(1).UpdateAsync(
Arg.Is<ThemeEntity>(entity => entity.Id == theme.Id && entity.IsDeleted && entity.IsCurrent == null),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockThemeService.Received(1).DeleteAsync(theme.ThemeId, Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenNoDefaultThemeMatches_ShouldSwitchToAlphabeticallyFirstReplacementTheme()
{
// Arrange
DeleteThemeCommand command = _deleteThemeCommandFixture.Create();
ThemeEntity theme = _themeEntityFixture.Create(themeId: command.ThemeId, installSource: ThemeInstallSource.Bundled, isCurrent: true, includeIsCurrent: true, isDeleted: false);
ThemeEntity alphaTheme = _themeEntityFixture.Create(themeId: "alpha", installSource: ThemeInstallSource.Bundled, isCurrent: false, includeIsCurrent: true, isDeleted: false);
ThemeEntity betaTheme = _themeEntityFixture.Create(themeId: "beta", installSource: ThemeInstallSource.Bundled, isCurrent: false, includeIsCurrent: true, isDeleted: false);
_mockThemeService.DefaultThemeId.Returns("no-such-default");
_mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(theme));
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(Result.From<IEnumerable<ThemeEntity>>([theme, betaTheme, alphaTheme]));
_mockThemeRepository.UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockThemeRepository.Received(1).UpdateAsync(
Arg.Is<ThemeEntity>(entity => entity.Id == alphaTheme.Id && entity.IsCurrent == true),
Arg.Any<CancellationToken>());
await _mockThemeRepository.Received(1).UpdateAsync(
Arg.Is<ThemeEntity>(entity => entity.Id == theme.Id && entity.IsDeleted),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenFileDeletionFails_ShouldReturnError()
{
// Arrange
DeleteThemeCommand command = _deleteThemeCommandFixture.Create();
ThemeEntity theme = _themeEntityFixture.Create(themeId: command.ThemeId, installSource: ThemeInstallSource.Uploaded, isCurrent: false, includeIsCurrent: true, isDeleted: false);
ThemeEntity bundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false);
Error error = Error.Failure("Theme.DeleteFailed", "Failed to delete theme files");
_mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(theme));
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(Result.From<IEnumerable<ThemeEntity>>([theme, bundledTheme]));
_mockThemeRepository.DeleteByIdAsync(theme.Id, Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockThemeService.DeleteAsync(theme.ThemeId, Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,74 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Themes.Management.Commands.DeleteTheme;
using Lumina.Application.Fixtures.Core.Themes.Management.Commands.DeleteTheme;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.Themes.Management.Commands.DeleteTheme;
/// <summary>
/// Contains unit tests for the <see cref="DeleteThemeCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeleteThemeCommandValidatorTests
{
private readonly DeleteThemeCommandValidator _validator = new();
private readonly DeleteThemeCommandFixture _deleteThemeCommandFixture = new();
[Fact]
public void Validate_WhenThemeIdIsNull_ShouldHaveValidationError()
{
// Arrange
DeleteThemeCommand command = _deleteThemeCommandFixture.Create();
command = command with { ThemeId = null };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Themes.ThemeIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenThemeIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
DeleteThemeCommand command = _deleteThemeCommandFixture.Create(themeId: string.Empty);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Themes.ThemeIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenThemeIdIsWhiteSpace_ShouldHaveValidationError()
{
// Arrange
DeleteThemeCommand command = _deleteThemeCommandFixture.Create(themeId: " ");
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Themes.ThemeIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenThemeIdIsValid_ShouldNotHaveAnyValidationErrors()
{
// Arrange
DeleteThemeCommand command = _deleteThemeCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -0,0 +1,302 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Themes;
using Lumina.Application.Common.DataAccess.Repositories.Themes;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Models.DTO.Themes;
using Lumina.Application.Common.Infrastructure.Themes;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.Themes.Management.Commands.InstallTheme;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes;
using Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.Themes;
using Lumina.Application.Fixtures.Core.Themes.Management.Commands.InstallTheme;
using Lumina.Contracts.Responses.Themes;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Themes;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.Themes.Management.Commands.InstallTheme;
/// <summary>
/// Contains unit tests for the <see cref="InstallThemeCommandHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class InstallThemeCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IThemeService _mockThemeService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly IValidator<InstallThemeCommand> _mockValidator;
private readonly IThemeRepository _mockThemeRepository;
private readonly InstallThemeCommandHandler _sut;
private readonly InstallThemeCommandFixture _installThemeCommandFixture = new();
private readonly ThemeManifestDtoFixture _themeManifestDtoFixture = new();
private readonly ThemeEntityFixture _themeEntityFixture = new();
private readonly Guid _userId;
/// <summary>
/// Initializes a new instance of the <see cref="InstallThemeCommandHandlerTests"/> class.
/// </summary>
public InstallThemeCommandHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockThemeService = Substitute.For<IThemeService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockValidator = Substitute.For<IValidator<InstallThemeCommand>>();
_mockThemeRepository = Substitute.For<IThemeRepository>();
_userId = Guid.NewGuid();
_mockValidator.Validate(Arg.Any<InstallThemeCommand>())
.Returns([]);
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>())
.Returns(true);
_mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository);
_sut = new InstallThemeCommandHandler(
_mockUnitOfWork,
_mockThemeService,
_mockCurrentUserService,
_mockAuthorizationService,
_mockValidator);
}
[Fact]
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutAnyDownstreamCalls()
{
// Arrange
InstallThemeCommand command = _installThemeCommandFixture.Create();
_mockValidator.Validate(Arg.Any<InstallThemeCommand>())
.Returns([Errors.Themes.ThemeArchiveCannotBeNull]);
// Act
Result<ThemeResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Themes.ThemeArchiveCannotBeNull, result.FirstError);
await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>());
await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
InstallThemeCommand command = _installThemeCommandFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<ThemeResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError()
{
// Arrange
InstallThemeCommand command = _installThemeCommandFixture.Create();
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<ThemeResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenThemeInstallFails_ShouldReturnError()
{
// Arrange
InstallThemeCommand command = _installThemeCommandFixture.Create();
Error error = Error.Failure("Theme.InstallFailed", "Failed to install theme");
_mockThemeService.InstallAsync(command.Archive!, Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<ThemeResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockThemeRepository.DidNotReceive().GetByThemeIdAsync(Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetThemeFails_ShouldReturnError()
{
// Arrange
InstallThemeCommand command = _installThemeCommandFixture.Create();
ThemeManifestDto manifest = _themeManifestDtoFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to get theme");
_mockThemeService.InstallAsync(command.Archive!, Arg.Any<CancellationToken>())
.Returns(Result.From(manifest));
_mockThemeRepository.GetByThemeIdAsync(manifest.Id, Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<ThemeResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenThemeDoesNotExist_ShouldInsertNewUploadedTheme()
{
// Arrange
InstallThemeCommand command = _installThemeCommandFixture.Create();
ThemeManifestDto manifest = _themeManifestDtoFixture.Create();
_mockThemeService.InstallAsync(command.Archive!, Arg.Any<CancellationToken>())
.Returns(Result.From(manifest));
_mockThemeRepository.GetByThemeIdAsync(manifest.Id, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(null));
_mockThemeRepository.InsertAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Created);
// Act
Result<ThemeResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(manifest.Id, result.Value.ThemeId);
Assert.Equal(manifest.Name, result.Value.Name);
Assert.Equal(manifest.Description, result.Value.Description);
Assert.Equal(manifest.Author, result.Value.Author);
Assert.Equal(manifest.Version, result.Value.Version);
Assert.Equal(manifest.Preview, result.Value.PreviewPath);
Assert.Equal(ThemeInstallSource.Uploaded, result.Value.InstallSource);
Assert.Null(result.Value.IsCurrent);
await _mockThemeRepository.Received(1).InsertAsync(
Arg.Is<ThemeEntity>(theme =>
theme.ThemeId == manifest.Id &&
theme.Name == manifest.Name &&
theme.Description == manifest.Description &&
theme.Author == manifest.Author &&
theme.Version == manifest.Version &&
theme.PreviewPath == manifest.Preview &&
theme.InstallSource == ThemeInstallSource.Uploaded &&
theme.IsDeleted == false &&
theme.CreatedBy == _userId &&
theme.UpdatedBy == _userId),
Arg.Any<CancellationToken>());
await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenInsertFails_ShouldRollBackStoredThemeFiles()
{
// Arrange
InstallThemeCommand command = _installThemeCommandFixture.Create();
ThemeManifestDto manifest = _themeManifestDtoFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to insert theme");
_mockThemeService.InstallAsync(command.Archive!, Arg.Any<CancellationToken>())
.Returns(Result.From(manifest));
_mockThemeRepository.GetByThemeIdAsync(manifest.Id, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(null));
_mockThemeRepository.InsertAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<ThemeResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockThemeService.Received(1).DeleteAsync(manifest.Id, Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenThemeAlreadyExists_ShouldUpdateExistingThemeAndResurrectIt()
{
// Arrange
InstallThemeCommand command = _installThemeCommandFixture.Create();
ThemeManifestDto manifest = _themeManifestDtoFixture.Create();
ThemeEntity existingTheme = _themeEntityFixture.Create(
themeId: manifest.Id,
installSource: ThemeInstallSource.Bundled,
isCurrent: true, includeIsCurrent: true,
isDeleted: true);
_mockThemeService.InstallAsync(command.Archive!, Arg.Any<CancellationToken>())
.Returns(Result.From(manifest));
_mockThemeRepository.GetByThemeIdAsync(manifest.Id, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(existingTheme));
_mockThemeRepository.UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
// Act
Result<ThemeResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(existingTheme.Id, result.Value.Id);
Assert.Equal(manifest.Name, result.Value.Name);
Assert.Equal(ThemeInstallSource.Bundled, result.Value.InstallSource);
Assert.True(result.Value.IsCurrent);
await _mockThemeRepository.Received(1).UpdateAsync(
Arg.Is<ThemeEntity>(theme =>
theme.Id == existingTheme.Id &&
theme.ThemeId == manifest.Id &&
theme.Name == manifest.Name &&
theme.InstallSource == existingTheme.InstallSource &&
theme.IsCurrent == existingTheme.IsCurrent &&
theme.IsDeleted == false &&
theme.CreatedOnUtc == existingTheme.CreatedOnUtc &&
theme.CreatedBy == existingTheme.CreatedBy &&
theme.UpdatedBy == _userId),
Arg.Any<CancellationToken>());
await _mockThemeRepository.DidNotReceive().InsertAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUpdateFails_ShouldReturnError()
{
// Arrange
InstallThemeCommand command = _installThemeCommandFixture.Create();
ThemeManifestDto manifest = _themeManifestDtoFixture.Create();
ThemeEntity existingTheme = _themeEntityFixture.Create(themeId: manifest.Id, installSource: ThemeInstallSource.Bundled, isCurrent: null, isDeleted: false);
Error error = Error.Failure("Database.Error", "Failed to update theme");
_mockThemeService.InstallAsync(command.Archive!, Arg.Any<CancellationToken>())
.Returns(Result.From(manifest));
_mockThemeRepository.GetByThemeIdAsync(manifest.Id, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(existingTheme));
_mockThemeRepository.UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<ThemeResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,62 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Themes.Management.Commands.InstallTheme;
using Lumina.Application.Fixtures.Core.Themes.Management.Commands.InstallTheme;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
#endregion
namespace Lumina.Application.UnitTests.Core.Themes.Management.Commands.InstallTheme;
/// <summary>
/// Contains unit tests for the <see cref="InstallThemeCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class InstallThemeCommandValidatorTests
{
private readonly InstallThemeCommandValidator _validator = new();
private readonly InstallThemeCommandFixture _installThemeCommandFixture = new();
[Fact]
public void Validate_WhenArchiveIsNull_ShouldHaveValidationError()
{
// Arrange
InstallThemeCommand command = _installThemeCommandFixture.Create();
command = command with { Archive = null };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Themes.ThemeArchiveCannotBeNull);
}
[Fact]
public void Validate_WhenArchiveIsProvided_ShouldNotHaveValidationError()
{
// Arrange
InstallThemeCommand command = _installThemeCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Themes.ThemeArchiveCannotBeNull);
}
[Fact]
public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationErrors()
{
// Arrange
InstallThemeCommand command = _installThemeCommandFixture.Create(new MemoryStream());
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -0,0 +1,296 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Themes;
using Lumina.Application.Common.DataAccess.Repositories.Themes;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.Themes.Management.Commands.SetCurrentTheme;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes;
using Lumina.Application.Fixtures.Core.Themes.Management.Commands.SetCurrentTheme;
using Lumina.Contracts.Responses.Themes;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.Themes.Management.Commands.SetCurrentTheme;
/// <summary>
/// Contains unit tests for the <see cref="SetCurrentThemeCommandHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetCurrentThemeCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly IValidator<SetCurrentThemeCommand> _mockValidator;
private readonly IThemeRepository _mockThemeRepository;
private readonly SetCurrentThemeCommandHandler _sut;
private readonly SetCurrentThemeCommandFixture _setCurrentThemeCommandFixture = new();
private readonly ThemeEntityFixture _themeEntityFixture = new();
private readonly Guid _userId;
/// <summary>
/// Initializes a new instance of the <see cref="SetCurrentThemeCommandHandlerTests"/> class.
/// </summary>
public SetCurrentThemeCommandHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockValidator = Substitute.For<IValidator<SetCurrentThemeCommand>>();
_mockThemeRepository = Substitute.For<IThemeRepository>();
_userId = Guid.NewGuid();
_mockValidator.Validate(Arg.Any<SetCurrentThemeCommand>())
.Returns([]);
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>())
.Returns(true);
_mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository);
_sut = new SetCurrentThemeCommandHandler(
_mockUnitOfWork,
_mockCurrentUserService,
_mockAuthorizationService,
_mockValidator);
}
[Fact]
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutAnyDownstreamCalls()
{
// Arrange
SetCurrentThemeCommand command = _setCurrentThemeCommandFixture.Create();
_mockValidator.Validate(Arg.Any<SetCurrentThemeCommand>())
.Returns([Errors.Themes.ThemeIdCannotBeEmpty]);
// Act
Result<ThemeResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Themes.ThemeIdCannotBeEmpty, result.FirstError);
await _mockThemeRepository.DidNotReceive().GetByThemeIdAsync(Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
SetCurrentThemeCommand command = _setCurrentThemeCommandFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<ThemeResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockThemeRepository.DidNotReceive().GetByThemeIdAsync(Arg.Any<string>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError()
{
// Arrange
SetCurrentThemeCommand command = _setCurrentThemeCommandFixture.Create();
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<ThemeResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockThemeRepository.DidNotReceive().GetByThemeIdAsync(Arg.Any<string>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetThemeFails_ShouldReturnError()
{
// Arrange
SetCurrentThemeCommand command = _setCurrentThemeCommandFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to get theme");
_mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<ThemeResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenThemeDoesNotExist_ShouldReturnThemeNotFoundError()
{
// Arrange
SetCurrentThemeCommand command = _setCurrentThemeCommandFixture.Create();
_mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(null));
// Act
Result<ThemeResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Themes.ThemeNotFound, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenThemeIsDeleted_ShouldReturnThemeNotFoundError()
{
// Arrange
SetCurrentThemeCommand command = _setCurrentThemeCommandFixture.Create();
ThemeEntity theme = _themeEntityFixture.Create(themeId: command.ThemeId, isDeleted: true);
_mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(theme));
// Act
Result<ThemeResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Themes.ThemeNotFound, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenThemeIsAlreadyCurrent_ShouldReturnResponseWithoutAnyPersistence()
{
// Arrange
SetCurrentThemeCommand command = _setCurrentThemeCommandFixture.Create();
ThemeEntity theme = _themeEntityFixture.Create(themeId: command.ThemeId, isCurrent: true, includeIsCurrent: true, isDeleted: false);
_mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(theme));
// Act
Result<ThemeResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(theme.Id, result.Value.Id);
Assert.Equal(theme.ThemeId, result.Value.ThemeId);
Assert.True(result.Value.IsCurrent);
await _mockThemeRepository.DidNotReceive().GetCurrentAsync(Arg.Any<CancellationToken>());
await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetCurrentThemeFails_ShouldReturnError()
{
// Arrange
SetCurrentThemeCommand command = _setCurrentThemeCommandFixture.Create();
ThemeEntity theme = _themeEntityFixture.Create(themeId: command.ThemeId, isCurrent: false, includeIsCurrent: true, isDeleted: false);
Error error = Error.Failure("Database.Error", "Failed to get current theme");
_mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(theme));
_mockThemeRepository.GetCurrentAsync(Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<ThemeResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenAnotherThemeIsCurrent_ShouldUnsetPreviousThemeAndActivateNewOne()
{
// Arrange
SetCurrentThemeCommand command = _setCurrentThemeCommandFixture.Create();
ThemeEntity theme = _themeEntityFixture.Create(themeId: command.ThemeId, isCurrent: false, includeIsCurrent: true, isDeleted: false);
ThemeEntity currentTheme = _themeEntityFixture.Create(isCurrent: true, includeIsCurrent: true, isDeleted: false);
_mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(theme));
_mockThemeRepository.GetCurrentAsync(Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(currentTheme));
_mockThemeRepository.UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
// Act
Result<ThemeResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(theme.Id, result.Value.Id);
Assert.True(result.Value.IsCurrent);
await _mockThemeRepository.Received(1).UpdateAsync(
Arg.Is<ThemeEntity>(entity => entity.Id == currentTheme.Id && entity.IsCurrent == null),
Arg.Any<CancellationToken>());
await _mockThemeRepository.Received(1).UpdateAsync(
Arg.Is<ThemeEntity>(entity => entity.Id == theme.Id && entity.IsCurrent == true && entity.UpdatedBy == _userId),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenCurrentThemeIsTheSameTheme_ShouldNotUpdateCurrentThemeTwice()
{
// Arrange
SetCurrentThemeCommand command = _setCurrentThemeCommandFixture.Create();
ThemeEntity theme = _themeEntityFixture.Create(themeId: command.ThemeId, isCurrent: false, includeIsCurrent: true, isDeleted: false);
_mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(theme));
_mockThemeRepository.GetCurrentAsync(Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(theme));
_mockThemeRepository.UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
// Act
Result<ThemeResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(theme.Id, result.Value.Id);
Assert.True(result.Value.IsCurrent);
await _mockThemeRepository.Received(1).UpdateAsync(
Arg.Is<ThemeEntity>(entity => entity.Id == theme.Id && entity.IsCurrent == true),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenNoThemeIsCurrentlySet_ShouldActivateThemeWithoutUnsettingAnything()
{
// Arrange
SetCurrentThemeCommand command = _setCurrentThemeCommandFixture.Create();
ThemeEntity theme = _themeEntityFixture.Create(themeId: command.ThemeId, isCurrent: false, includeIsCurrent: true, isDeleted: false);
_mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(theme));
_mockThemeRepository.GetCurrentAsync(Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(null));
_mockThemeRepository.UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
// Act
Result<ThemeResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(theme.Id, result.Value.Id);
Assert.True(result.Value.IsCurrent);
await _mockThemeRepository.Received(1).UpdateAsync(
Arg.Is<ThemeEntity>(entity => entity.Id == theme.Id && entity.IsCurrent == true && entity.UpdatedBy == _userId),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,74 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Themes.Management.Commands.SetCurrentTheme;
using Lumina.Application.Fixtures.Core.Themes.Management.Commands.SetCurrentTheme;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.Themes.Management.Commands.SetCurrentTheme;
/// <summary>
/// Contains unit tests for the <see cref="SetCurrentThemeCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetCurrentThemeCommandValidatorTests
{
private readonly SetCurrentThemeCommandValidator _validator = new();
private readonly SetCurrentThemeCommandFixture _setCurrentThemeCommandFixture = new();
[Fact]
public void Validate_WhenThemeIdIsNull_ShouldHaveValidationError()
{
// Arrange
SetCurrentThemeCommand command = _setCurrentThemeCommandFixture.Create();
command = command with { ThemeId = null };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Themes.ThemeIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenThemeIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
SetCurrentThemeCommand command = _setCurrentThemeCommandFixture.Create(themeId: string.Empty);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Themes.ThemeIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenThemeIdIsWhiteSpace_ShouldHaveValidationError()
{
// Arrange
SetCurrentThemeCommand command = _setCurrentThemeCommandFixture.Create(themeId: " ");
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Themes.ThemeIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenThemeIdIsValid_ShouldNotHaveAnyValidationErrors()
{
// Arrange
SetCurrentThemeCommand command = _setCurrentThemeCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -0,0 +1,101 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Themes;
using Lumina.Application.Common.DataAccess.Repositories.Themes;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Core.Themes.Management.Queries.GetCurrentTheme;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes;
using Lumina.Application.Fixtures.Core.Themes.Management.Queries.GetCurrentTheme;
using Lumina.Contracts.Responses.Themes;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.Themes.Management.Queries.GetCurrentTheme;
/// <summary>
/// Contains unit tests for the <see cref="GetCurrentThemeQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetCurrentThemeQueryHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IThemeRepository _mockThemeRepository;
private readonly GetCurrentThemeQueryHandler _sut;
private readonly GetCurrentThemeQueryFixture _getCurrentThemeQueryFixture = new();
private readonly ThemeEntityFixture _themeEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetCurrentThemeQueryHandlerTests"/> class.
/// </summary>
public GetCurrentThemeQueryHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockThemeRepository = Substitute.For<IThemeRepository>();
_mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository);
_sut = new GetCurrentThemeQueryHandler(_mockUnitOfWork);
}
[Fact]
public async Task HandleAsync_WhenCurrentThemeExists_ShouldReturnItsResponse()
{
// Arrange
GetCurrentThemeQuery query = _getCurrentThemeQueryFixture.Create();
ThemeEntity theme = _themeEntityFixture.Create(isCurrent: true, includeIsCurrent: true);
_mockThemeRepository.GetCurrentAsync(Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(theme));
// Act
Result<ThemeResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(theme.Id, result.Value.Id);
Assert.Equal(theme.ThemeId, result.Value.ThemeId);
Assert.Equal(theme.Name, result.Value.Name);
Assert.Equal(theme.Description, result.Value.Description);
Assert.Equal(theme.Author, result.Value.Author);
Assert.Equal(theme.Version, result.Value.Version);
Assert.Equal(theme.PreviewPath, result.Value.PreviewPath);
Assert.Equal(theme.InstallSource, result.Value.InstallSource);
Assert.True(result.Value.IsCurrent);
Assert.Equal(theme.InstalledAtUtc, result.Value.InstalledAtUtc);
}
[Fact]
public async Task HandleAsync_WhenNoCurrentThemeExists_ShouldReturnThemeNotFoundError()
{
// Arrange
GetCurrentThemeQuery query = _getCurrentThemeQueryFixture.Create();
_mockThemeRepository.GetCurrentAsync(Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(null));
// Act
Result<ThemeResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Themes.ThemeNotFound, result.FirstError);
}
[Fact]
public async Task HandleAsync_WhenRepositoryReturnsError_ShouldReturnError()
{
// Arrange
GetCurrentThemeQuery query = _getCurrentThemeQueryFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to get current theme");
_mockThemeRepository.GetCurrentAsync(Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<ThemeResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
}
}
@@ -0,0 +1,170 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Themes;
using Lumina.Application.Common.DataAccess.Repositories.Themes;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Models.DTO.Themes;
using Lumina.Application.Common.Infrastructure.Themes;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.Themes.Management.Queries.GetThemeArchive;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes;
using Lumina.Application.Fixtures.Core.Themes.Management.Queries.GetThemeArchive;
using Lumina.Contracts.Responses.Themes;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.Themes.Management.Queries.GetThemeArchive;
/// <summary>
/// Contains unit tests for the <see cref="GetThemeArchiveQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetThemeArchiveQueryHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IThemeService _mockThemeService;
private readonly IValidator<GetThemeArchiveQuery> _mockValidator;
private readonly IThemeRepository _mockThemeRepository;
private readonly GetThemeArchiveQueryHandler _sut;
private readonly GetThemeArchiveQueryFixture _getThemeArchiveQueryFixture = new();
private readonly ThemeEntityFixture _themeEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetThemeArchiveQueryHandlerTests"/> class.
/// </summary>
public GetThemeArchiveQueryHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockThemeService = Substitute.For<IThemeService>();
_mockValidator = Substitute.For<IValidator<GetThemeArchiveQuery>>();
_mockThemeRepository = Substitute.For<IThemeRepository>();
_mockValidator.Validate(Arg.Any<GetThemeArchiveQuery>())
.Returns([]);
_mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository);
_sut = new GetThemeArchiveQueryHandler(_mockUnitOfWork, _mockThemeService, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutAnyDownstreamCalls()
{
// Arrange
GetThemeArchiveQuery query = _getThemeArchiveQueryFixture.Create();
_mockValidator.Validate(Arg.Any<GetThemeArchiveQuery>())
.Returns([Errors.Themes.ThemeIdCannotBeEmpty]);
// Act
Result<ThemeArchiveResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Themes.ThemeIdCannotBeEmpty, result.FirstError);
await _mockThemeRepository.DidNotReceive().GetByThemeIdAsync(Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockThemeService.DidNotReceive().BuildArchiveAsync(Arg.Any<string>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetThemeFails_ShouldReturnError()
{
// Arrange
GetThemeArchiveQuery query = _getThemeArchiveQueryFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to get theme");
_mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<ThemeArchiveResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockThemeService.DidNotReceive().BuildArchiveAsync(Arg.Any<string>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenThemeDoesNotExist_ShouldReturnThemeNotFoundError()
{
// Arrange
GetThemeArchiveQuery query = _getThemeArchiveQueryFixture.Create();
_mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(null));
// Act
Result<ThemeArchiveResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Themes.ThemeNotFound, result.FirstError);
await _mockThemeService.DidNotReceive().BuildArchiveAsync(Arg.Any<string>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenThemeIsDeleted_ShouldReturnThemeNotFoundError()
{
// Arrange
GetThemeArchiveQuery query = _getThemeArchiveQueryFixture.Create();
ThemeEntity theme = _themeEntityFixture.Create(themeId: query.ThemeId, isDeleted: true);
_mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(theme));
// Act
Result<ThemeArchiveResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Themes.ThemeNotFound, result.FirstError);
await _mockThemeService.DidNotReceive().BuildArchiveAsync(Arg.Any<string>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenArchiveBuildsSuccessfully_ShouldReturnArchiveResponse()
{
// Arrange
GetThemeArchiveQuery query = _getThemeArchiveQueryFixture.Create();
ThemeEntity theme = _themeEntityFixture.Create(themeId: query.ThemeId, isDeleted: false);
byte[] bytes = Encoding.UTF8.GetBytes("archive-content");
string fileName = $"{theme.ThemeId}.zip";
string contentType = "application/zip";
_mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(theme));
_mockThemeService.BuildArchiveAsync(theme.ThemeId, Arg.Any<CancellationToken>())
.Returns(Result.From(new ThemeArchiveDto(bytes, fileName, contentType)));
// Act
Result<ThemeArchiveResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(bytes, result.Value.Bytes);
Assert.Equal(fileName, result.Value.FileName);
Assert.Equal(contentType, result.Value.ContentType);
}
[Fact]
public async Task HandleAsync_WhenArchiveBuildFails_ShouldReturnError()
{
// Arrange
GetThemeArchiveQuery query = _getThemeArchiveQueryFixture.Create();
ThemeEntity theme = _themeEntityFixture.Create(themeId: query.ThemeId, isDeleted: false);
Error error = Error.Failure("Theme.ArchiveBuildFailed", "Failed to build archive");
_mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(theme));
_mockThemeService.BuildArchiveAsync(theme.ThemeId, Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<ThemeArchiveResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
}
}
@@ -0,0 +1,74 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Themes.Management.Queries.GetThemeArchive;
using Lumina.Application.Fixtures.Core.Themes.Management.Queries.GetThemeArchive;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.Themes.Management.Queries.GetThemeArchive;
/// <summary>
/// Contains unit tests for the <see cref="GetThemeArchiveQueryValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetThemeArchiveQueryValidatorTests
{
private readonly GetThemeArchiveQueryValidator _validator = new();
private readonly GetThemeArchiveQueryFixture _getThemeArchiveQueryFixture = new();
[Fact]
public void Validate_WhenThemeIdIsNull_ShouldHaveValidationError()
{
// Arrange
GetThemeArchiveQuery query = _getThemeArchiveQueryFixture.Create();
query = query with { ThemeId = null };
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Themes.ThemeIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenThemeIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
GetThemeArchiveQuery query = _getThemeArchiveQueryFixture.Create(themeId: string.Empty);
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Themes.ThemeIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenThemeIdIsWhiteSpace_ShouldHaveValidationError()
{
// Arrange
GetThemeArchiveQuery query = _getThemeArchiveQueryFixture.Create(themeId: " ");
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Themes.ThemeIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenThemeIdIsValid_ShouldNotHaveAnyValidationErrors()
{
// Arrange
GetThemeArchiveQuery query = _getThemeArchiveQueryFixture.Create();
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -0,0 +1,243 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Themes;
using Lumina.Application.Common.DataAccess.Repositories.Themes;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Models.DTO.Themes;
using Lumina.Application.Common.Infrastructure.Themes;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.Themes.Management.Queries.GetThemeAsset;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes;
using Lumina.Application.Fixtures.Core.Themes.Management.Queries.GetThemeAsset;
using Lumina.Contracts.Responses.Themes;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Themes;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.Themes.Management.Queries.GetThemeAsset;
/// <summary>
/// Contains unit tests for the <see cref="GetThemeAssetQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetThemeAssetQueryHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IThemeService _mockThemeService;
private readonly IValidator<GetThemeAssetQuery> _mockValidator;
private readonly IThemeRepository _mockThemeRepository;
private readonly GetThemeAssetQueryHandler _sut;
private readonly GetThemeAssetQueryFixture _getThemeAssetQueryFixture = new();
private readonly ThemeEntityFixture _themeEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetThemeAssetQueryHandlerTests"/> class.
/// </summary>
public GetThemeAssetQueryHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockThemeService = Substitute.For<IThemeService>();
_mockValidator = Substitute.For<IValidator<GetThemeAssetQuery>>();
_mockThemeRepository = Substitute.For<IThemeRepository>();
_mockValidator.Validate(Arg.Any<GetThemeAssetQuery>())
.Returns([]);
_mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository);
_sut = new GetThemeAssetQueryHandler(_mockUnitOfWork, _mockThemeService, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutAnyDownstreamCalls()
{
// Arrange
GetThemeAssetQuery query = _getThemeAssetQueryFixture.Create();
_mockValidator.Validate(Arg.Any<GetThemeAssetQuery>())
.Returns([Errors.Themes.ThemeIdCannotBeEmpty]);
// Act
Result<ThemeAssetResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Themes.ThemeIdCannotBeEmpty, result.FirstError);
await _mockThemeRepository.DidNotReceive().GetByThemeIdAsync(Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockThemeService.DidNotReceive().GetAssetAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetThemeFails_ShouldReturnError()
{
// Arrange
GetThemeAssetQuery query = _getThemeAssetQueryFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to get theme");
_mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<ThemeAssetResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockThemeService.DidNotReceive().GetAssetAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenThemeDoesNotExist_ShouldReturnThemeNotFoundError()
{
// Arrange
GetThemeAssetQuery query = _getThemeAssetQueryFixture.Create();
_mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(null));
// Act
Result<ThemeAssetResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Themes.ThemeNotFound, result.FirstError);
}
[Fact]
public async Task HandleAsync_WhenThemeIsDeleted_ShouldReturnThemeNotFoundError()
{
// Arrange
GetThemeAssetQuery query = _getThemeAssetQueryFixture.Create();
ThemeEntity theme = _themeEntityFixture.Create(themeId: query.ThemeId, isDeleted: true);
_mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(theme));
// Act
Result<ThemeAssetResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Themes.ThemeNotFound, result.FirstError);
await _mockThemeService.DidNotReceive().GetAssetAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenAssetLoadsSuccessfully_ShouldReturnAssetResponse()
{
// Arrange
GetThemeAssetQuery query = _getThemeAssetQueryFixture.Create();
ThemeEntity theme = _themeEntityFixture.Create(themeId: query.ThemeId, isDeleted: false);
byte[] bytes = Encoding.UTF8.GetBytes("asset-content");
string contentType = "image/png";
_mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(theme));
_mockThemeService.GetAssetAsync(theme.ThemeId, query.AssetPath!, Arg.Any<CancellationToken>())
.Returns(Result.From(new ThemeAssetDto(bytes, contentType)));
// Act
Result<ThemeAssetResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(bytes, result.Value.Bytes);
Assert.Equal(contentType, result.Value.ContentType);
await _mockThemeService.DidNotReceive().RestoreBundledThemeAsync(Arg.Any<string>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenAssetLoadFailsForUserTheme_ShouldReturnAssetErrorWithoutRestoring()
{
// Arrange
GetThemeAssetQuery query = _getThemeAssetQueryFixture.Create();
ThemeEntity theme = _themeEntityFixture.Create(themeId: query.ThemeId, installSource: ThemeInstallSource.Uploaded, isDeleted: false);
Error error = Error.Failure("Theme.AssetMissing", "Asset missing");
_mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(theme));
_mockThemeService.GetAssetAsync(theme.ThemeId, query.AssetPath!, Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<ThemeAssetResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockThemeService.DidNotReceive().RestoreBundledThemeAsync(Arg.Any<string>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenAssetLoadFailsAndRestoreFails_ShouldReturnRestoreError()
{
// Arrange
GetThemeAssetQuery query = _getThemeAssetQueryFixture.Create();
ThemeEntity theme = _themeEntityFixture.Create(themeId: query.ThemeId, installSource: ThemeInstallSource.Bundled, isDeleted: false);
Error assetError = Error.Failure("Theme.AssetMissing", "Asset missing");
Error restoreError = Error.Failure("Theme.RestoreFailed", "Restore failed");
_mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(theme));
_mockThemeService.GetAssetAsync(theme.ThemeId, query.AssetPath!, Arg.Any<CancellationToken>())
.Returns(assetError);
_mockThemeService.RestoreBundledThemeAsync(theme.ThemeId, Arg.Any<CancellationToken>())
.Returns(restoreError);
// Act
Result<ThemeAssetResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(restoreError, result.FirstError);
}
[Fact]
public async Task HandleAsync_WhenAssetLoadFailsAndRestoreSucceeds_ShouldRetryAndReturnAssetResponse()
{
// Arrange
GetThemeAssetQuery query = _getThemeAssetQueryFixture.Create();
ThemeEntity theme = _themeEntityFixture.Create(themeId: query.ThemeId, installSource: ThemeInstallSource.Bundled, isDeleted: false);
Error assetError = Error.Failure("Theme.AssetMissing", "Asset missing");
byte[] restoredBytes = Encoding.UTF8.GetBytes("restored-asset");
string contentType = "text/css";
_mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(theme));
_mockThemeService.GetAssetAsync(theme.ThemeId, query.AssetPath!, Arg.Any<CancellationToken>())
.Returns(assetError, Result.From(new ThemeAssetDto(restoredBytes, contentType)));
_mockThemeService.RestoreBundledThemeAsync(theme.ThemeId, Arg.Any<CancellationToken>())
.Returns(Result.Success);
// Act
Result<ThemeAssetResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(restoredBytes, result.Value.Bytes);
Assert.Equal(contentType, result.Value.ContentType);
await _mockThemeService.Received(2).GetAssetAsync(theme.ThemeId, query.AssetPath!, Arg.Any<CancellationToken>());
await _mockThemeService.Received(1).RestoreBundledThemeAsync(theme.ThemeId, Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenRestoreSucceedsButRetryFails_ShouldReturnAssetError()
{
// Arrange
GetThemeAssetQuery query = _getThemeAssetQueryFixture.Create();
ThemeEntity theme = _themeEntityFixture.Create(themeId: query.ThemeId, installSource: ThemeInstallSource.Bundled, isDeleted: false);
Error assetError = Error.Failure("Theme.AssetMissing", "Asset missing");
Error retryError = Error.Failure("Theme.AssetMissingAgain", "Asset still missing");
_mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(theme));
_mockThemeService.GetAssetAsync(theme.ThemeId, query.AssetPath!, Arg.Any<CancellationToken>())
.Returns(assetError, retryError);
_mockThemeService.RestoreBundledThemeAsync(theme.ThemeId, Arg.Any<CancellationToken>())
.Returns(Result.Success);
// Act
Result<ThemeAssetResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(retryError, result.FirstError);
}
}
@@ -0,0 +1,114 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Themes.Management.Queries.GetThemeAsset;
using Lumina.Application.Fixtures.Core.Themes.Management.Queries.GetThemeAsset;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.Themes.Management.Queries.GetThemeAsset;
/// <summary>
/// Contains unit tests for the <see cref="GetThemeAssetQueryValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetThemeAssetQueryValidatorTests
{
private readonly GetThemeAssetQueryValidator _validator = new();
private readonly GetThemeAssetQueryFixture _getThemeAssetQueryFixture = new();
[Fact]
public void Validate_WhenThemeIdIsNull_ShouldHaveValidationError()
{
// Arrange
GetThemeAssetQuery query = _getThemeAssetQueryFixture.Create();
query = query with { ThemeId = null };
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Themes.ThemeIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenThemeIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
GetThemeAssetQuery query = _getThemeAssetQueryFixture.Create(themeId: string.Empty);
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Themes.ThemeIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenThemeIdIsWhiteSpace_ShouldHaveValidationError()
{
// Arrange
GetThemeAssetQuery query = _getThemeAssetQueryFixture.Create(themeId: " ");
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Themes.ThemeIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenAssetPathIsNull_ShouldHaveValidationError()
{
// Arrange
GetThemeAssetQuery query = _getThemeAssetQueryFixture.Create();
query = query with { AssetPath = null };
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Themes.ThemeAssetPathCannotBeEmpty);
}
[Fact]
public void Validate_WhenAssetPathIsEmpty_ShouldHaveValidationError()
{
// Arrange
GetThemeAssetQuery query = _getThemeAssetQueryFixture.Create(assetPath: string.Empty);
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Themes.ThemeAssetPathCannotBeEmpty);
}
[Fact]
public void Validate_WhenAssetPathIsWhiteSpace_ShouldHaveValidationError()
{
// Arrange
GetThemeAssetQuery query = _getThemeAssetQueryFixture.Create(assetPath: " ");
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Themes.ThemeAssetPathCannotBeEmpty);
}
[Fact]
public void Validate_WhenQueryIsValid_ShouldNotHaveAnyValidationErrors()
{
// Arrange
GetThemeAssetQuery query = _getThemeAssetQueryFixture.Create();
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -0,0 +1,55 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Themes;
using Lumina.Application.Core.Themes.Management.Queries.GetThemeSettings;
using Lumina.Application.Fixtures.Core.Themes.Management.Queries.GetThemeSettings;
using Lumina.Contracts.Responses.Themes;
using Lumina.Domain.Common.Primitives;
using NSubstitute;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.Themes.Management.Queries.GetThemeSettings;
/// <summary>
/// Contains unit tests for the <see cref="GetThemeSettingsQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetThemeSettingsQueryHandlerTests
{
private readonly IThemeService _mockThemeService;
private readonly GetThemeSettingsQueryHandler _sut;
private readonly GetThemeSettingsQueryFixture _getThemeSettingsQueryFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetThemeSettingsQueryHandlerTests"/> class.
/// </summary>
public GetThemeSettingsQueryHandlerTests()
{
_mockThemeService = Substitute.For<IThemeService>();
_sut = new GetThemeSettingsQueryHandler(_mockThemeService);
}
[Fact]
public async Task HandleAsync_WhenCalled_ShouldReturnThemeSettingsFromThemeService()
{
// Arrange
GetThemeSettingsQuery query = _getThemeSettingsQueryFixture.Create();
long maxArchiveBytes = 50_000_000;
bool allowThemeScripts = false;
string defaultThemeId = "default-theme";
_mockThemeService.MaxArchiveBytes.Returns(maxArchiveBytes);
_mockThemeService.AllowThemeScripts.Returns(allowThemeScripts);
_mockThemeService.DefaultThemeId.Returns(defaultThemeId);
// Act
Result<ThemeSettingsResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(maxArchiveBytes, result.Value.MaxArchiveBytes);
Assert.Equal(allowThemeScripts, result.Value.AllowThemeScripts);
Assert.Equal(defaultThemeId, result.Value.DefaultThemeId);
}
}
@@ -0,0 +1,333 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Themes;
using Lumina.Application.Common.DataAccess.Repositories.Themes;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Themes;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.Themes.Management.Queries.GetThemeTemplate;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes;
using Lumina.Application.Fixtures.Core.Themes.Management.Queries.GetThemeTemplate;
using Lumina.Contracts.Responses.Themes;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Themes;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.Themes.Management.Queries.GetThemeTemplate;
/// <summary>
/// Contains unit tests for the <see cref="GetThemeTemplateQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetThemeTemplateQueryHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IThemeService _mockThemeService;
private readonly IValidator<GetThemeTemplateQuery> _mockValidator;
private readonly IThemeRepository _mockThemeRepository;
private readonly GetThemeTemplateQueryHandler _sut;
private readonly GetThemeTemplateQueryFixture _getThemeTemplateQueryFixture = new();
private readonly ThemeEntityFixture _themeEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetThemeTemplateQueryHandlerTests"/> class.
/// </summary>
public GetThemeTemplateQueryHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockThemeService = Substitute.For<IThemeService>();
_mockValidator = Substitute.For<IValidator<GetThemeTemplateQuery>>();
_mockThemeRepository = Substitute.For<IThemeRepository>();
_mockValidator.Validate(Arg.Any<GetThemeTemplateQuery>())
.Returns([]);
_mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository);
_sut = new GetThemeTemplateQueryHandler(_mockUnitOfWork, _mockThemeService, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutAnyDownstreamCalls()
{
// Arrange
GetThemeTemplateQuery query = _getThemeTemplateQueryFixture.Create();
_mockValidator.Validate(Arg.Any<GetThemeTemplateQuery>())
.Returns([Errors.Themes.ThemeIdCannotBeEmpty]);
// Act
Result<ThemeTemplateResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Themes.ThemeIdCannotBeEmpty, result.FirstError);
await _mockThemeRepository.DidNotReceive().GetByThemeIdAsync(Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockThemeService.DidNotReceive().GetTemplateAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetThemeFails_ShouldReturnError()
{
// Arrange
GetThemeTemplateQuery query = _getThemeTemplateQueryFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to get theme");
_mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<ThemeTemplateResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockThemeService.DidNotReceive().GetTemplateAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenThemeDoesNotExist_ShouldReturnThemeNotFoundError()
{
// Arrange
GetThemeTemplateQuery query = _getThemeTemplateQueryFixture.Create();
_mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(null));
// Act
Result<ThemeTemplateResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Themes.ThemeNotFound, result.FirstError);
}
[Fact]
public async Task HandleAsync_WhenThemeIsDeleted_ShouldReturnThemeNotFoundError()
{
// Arrange
GetThemeTemplateQuery query = _getThemeTemplateQueryFixture.Create();
ThemeEntity theme = _themeEntityFixture.Create(themeId: query.ThemeId, isDeleted: true);
_mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(theme));
// Act
Result<ThemeTemplateResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Themes.ThemeNotFound, result.FirstError);
await _mockThemeService.DidNotReceive().GetTemplateAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenTemplateLoadsSuccessfully_ShouldReturnTemplateResponse()
{
// Arrange
GetThemeTemplateQuery query = _getThemeTemplateQueryFixture.Create();
ThemeEntity theme = _themeEntityFixture.Create(themeId: query.ThemeId, isDeleted: false);
string template = "<html>Hello</html>";
_mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(theme));
_mockThemeService.GetTemplateAsync(theme.ThemeId, query.PageKey!, Arg.Any<CancellationToken>())
.Returns(Result.From(template));
// Act
Result<ThemeTemplateResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(theme.Id, result.Value.Theme.Id);
Assert.Equal(theme.ThemeId, result.Value.Theme.ThemeId);
Assert.Equal(template, result.Value.Template);
await _mockThemeService.DidNotReceive().RestoreBundledThemeAsync(Arg.Any<string>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenTemplateLoadFailsForUserTheme_ShouldReturnTemplateErrorWithoutRestoring()
{
// Arrange
GetThemeTemplateQuery query = _getThemeTemplateQueryFixture.Create();
ThemeEntity theme = _themeEntityFixture.Create(themeId: query.ThemeId, installSource: ThemeInstallSource.Uploaded, isDeleted: false);
Error error = Error.Failure("Theme.TemplateMissing", "Template missing");
_mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(theme));
_mockThemeService.GetTemplateAsync(theme.ThemeId, query.PageKey!, Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<ThemeTemplateResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockThemeService.DidNotReceive().RestoreBundledThemeAsync(Arg.Any<string>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenTemplateLoadFailsAndRestoreFails_ShouldReturnTemplateError()
{
// Arrange
GetThemeTemplateQuery query = _getThemeTemplateQueryFixture.Create();
ThemeEntity theme = _themeEntityFixture.Create(themeId: query.ThemeId, installSource: ThemeInstallSource.Bundled, isDeleted: false);
Error templateError = Error.Failure("Theme.TemplateMissing", "Template missing");
Error restoreError = Error.Failure("Theme.RestoreFailed", "Restore failed");
_mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(theme));
_mockThemeService.GetTemplateAsync(theme.ThemeId, query.PageKey!, Arg.Any<CancellationToken>())
.Returns(templateError);
_mockThemeService.RestoreBundledThemeAsync(theme.ThemeId, Arg.Any<CancellationToken>())
.Returns(restoreError);
// Act
Result<ThemeTemplateResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(templateError, result.FirstError);
}
[Fact]
public async Task HandleAsync_WhenTemplateLoadFailsAndRestoreSucceeds_ShouldRetryAndReturnTemplateResponse()
{
// Arrange
GetThemeTemplateQuery query = _getThemeTemplateQueryFixture.Create();
ThemeEntity theme = _themeEntityFixture.Create(themeId: query.ThemeId, installSource: ThemeInstallSource.Bundled, isCurrent: false, includeIsCurrent: true, isDeleted: false);
Error templateError = Error.Failure("Theme.TemplateMissing", "Template missing");
string restoredTemplate = "<html>Restored</html>";
_mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(theme));
_mockThemeService.GetTemplateAsync(theme.ThemeId, query.PageKey!, Arg.Any<CancellationToken>())
.Returns(templateError, Result.From(restoredTemplate));
_mockThemeService.RestoreBundledThemeAsync(theme.ThemeId, Arg.Any<CancellationToken>())
.Returns(Result.Success);
// Act
Result<ThemeTemplateResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(restoredTemplate, result.Value.Template);
await _mockThemeService.Received(2).GetTemplateAsync(theme.ThemeId, query.PageKey!, Arg.Any<CancellationToken>());
await _mockThemeService.Received(1).RestoreBundledThemeAsync(theme.ThemeId, Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenRestoreSucceedsButRetryFails_ShouldReturnTemplateError()
{
// Arrange
GetThemeTemplateQuery query = _getThemeTemplateQueryFixture.Create();
ThemeEntity theme = _themeEntityFixture.Create(themeId: query.ThemeId, installSource: ThemeInstallSource.Bundled, isDeleted: false);
Error templateError = Error.Failure("Theme.TemplateMissing", "Template missing");
Error retryError = Error.Failure("Theme.TemplateMissingAgain", "Template still missing");
_mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(theme));
_mockThemeService.GetTemplateAsync(theme.ThemeId, query.PageKey!, Arg.Any<CancellationToken>())
.Returns(templateError, retryError);
_mockThemeService.RestoreBundledThemeAsync(theme.ThemeId, Arg.Any<CancellationToken>())
.Returns(Result.Success);
// Act
Result<ThemeTemplateResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(retryError, result.FirstError);
}
[Fact]
public async Task HandleAsync_WhenRestoringCurrentBundledTheme_ShouldSwitchActiveThemeToDefaultTheme()
{
// Arrange
GetThemeTemplateQuery query = _getThemeTemplateQueryFixture.Create();
ThemeEntity theme = _themeEntityFixture.Create(themeId: query.ThemeId, installSource: ThemeInstallSource.Bundled, isCurrent: true, includeIsCurrent: true, isDeleted: false);
ThemeEntity defaultTheme = _themeEntityFixture.Create(themeId: "default-theme", isDeleted: false);
Error templateError = Error.Failure("Theme.TemplateMissing", "Template missing");
string restoredTemplate = "<html>Restored</html>";
_mockThemeService.DefaultThemeId.Returns(defaultTheme.ThemeId);
_mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(theme));
_mockThemeRepository.GetByThemeIdAsync(defaultTheme.ThemeId, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(defaultTheme));
_mockThemeRepository.UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
_mockThemeService.GetTemplateAsync(theme.ThemeId, query.PageKey!, Arg.Any<CancellationToken>())
.Returns(templateError, Result.From(restoredTemplate));
_mockThemeService.RestoreBundledThemeAsync(theme.ThemeId, Arg.Any<CancellationToken>())
.Returns(Result.Success);
// Act
Result<ThemeTemplateResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(restoredTemplate, result.Value.Template);
await _mockThemeRepository.Received(1).UpdateAsync(
Arg.Is<ThemeEntity>(entity => entity.Id == theme.Id && entity.IsCurrent == null),
Arg.Any<CancellationToken>());
await _mockThemeRepository.Received(1).UpdateAsync(
Arg.Is<ThemeEntity>(entity => entity.Id == defaultTheme.Id && entity.IsCurrent == true),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenRestoringCurrentBundledThemeWithNoDefaultTheme_ShouldNotSwitchActiveTheme()
{
// Arrange
GetThemeTemplateQuery query = _getThemeTemplateQueryFixture.Create();
ThemeEntity theme = _themeEntityFixture.Create(themeId: query.ThemeId, installSource: ThemeInstallSource.Bundled, isCurrent: true, includeIsCurrent: true, isDeleted: false);
Error templateError = Error.Failure("Theme.TemplateMissing", "Template missing");
string restoredTemplate = "<html>Restored</html>";
_mockThemeService.DefaultThemeId.Returns("missing-default");
_mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(theme));
_mockThemeRepository.GetByThemeIdAsync("missing-default", Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(null));
_mockThemeService.GetTemplateAsync(theme.ThemeId, query.PageKey!, Arg.Any<CancellationToken>())
.Returns(templateError, Result.From(restoredTemplate));
_mockThemeService.RestoreBundledThemeAsync(theme.ThemeId, Arg.Any<CancellationToken>())
.Returns(Result.Success);
// Act
Result<ThemeTemplateResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(restoredTemplate, result.Value.Template);
await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGettingDefaultThemeFails_ShouldNotSwitchActiveThemeButStillRestore()
{
// Arrange
GetThemeTemplateQuery query = _getThemeTemplateQueryFixture.Create();
ThemeEntity theme = _themeEntityFixture.Create(themeId: query.ThemeId, installSource: ThemeInstallSource.Bundled, isCurrent: true, includeIsCurrent: true, isDeleted: false);
Error templateError = Error.Failure("Theme.TemplateMissing", "Template missing");
Error defaultError = Error.Failure("Database.Error", "Failed to get default theme");
string restoredTemplate = "<html>Restored</html>";
_mockThemeService.DefaultThemeId.Returns("default-theme");
_mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(theme));
_mockThemeRepository.GetByThemeIdAsync("default-theme", Arg.Any<CancellationToken>())
.Returns(defaultError);
_mockThemeService.GetTemplateAsync(theme.ThemeId, query.PageKey!, Arg.Any<CancellationToken>())
.Returns(templateError, Result.From(restoredTemplate));
_mockThemeService.RestoreBundledThemeAsync(theme.ThemeId, Arg.Any<CancellationToken>())
.Returns(Result.Success);
// Act
Result<ThemeTemplateResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(restoredTemplate, result.Value.Template);
await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,114 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Themes.Management.Queries.GetThemeTemplate;
using Lumina.Application.Fixtures.Core.Themes.Management.Queries.GetThemeTemplate;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.Themes.Management.Queries.GetThemeTemplate;
/// <summary>
/// Contains unit tests for the <see cref="GetThemeTemplateQueryValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetThemeTemplateQueryValidatorTests
{
private readonly GetThemeTemplateQueryValidator _validator = new();
private readonly GetThemeTemplateQueryFixture _getThemeTemplateQueryFixture = new();
[Fact]
public void Validate_WhenThemeIdIsNull_ShouldHaveValidationError()
{
// Arrange
GetThemeTemplateQuery query = _getThemeTemplateQueryFixture.Create();
query = query with { ThemeId = null };
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Themes.ThemeIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenThemeIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
GetThemeTemplateQuery query = _getThemeTemplateQueryFixture.Create(themeId: string.Empty);
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Themes.ThemeIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenThemeIdIsWhiteSpace_ShouldHaveValidationError()
{
// Arrange
GetThemeTemplateQuery query = _getThemeTemplateQueryFixture.Create(themeId: " ");
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Themes.ThemeIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenPageKeyIsNull_ShouldHaveValidationError()
{
// Arrange
GetThemeTemplateQuery query = _getThemeTemplateQueryFixture.Create();
query = query with { PageKey = null };
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Themes.PageKeyCannotBeEmpty);
}
[Fact]
public void Validate_WhenPageKeyIsEmpty_ShouldHaveValidationError()
{
// Arrange
GetThemeTemplateQuery query = _getThemeTemplateQueryFixture.Create(pageKey: string.Empty);
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Themes.PageKeyCannotBeEmpty);
}
[Fact]
public void Validate_WhenPageKeyIsWhiteSpace_ShouldHaveValidationError()
{
// Arrange
GetThemeTemplateQuery query = _getThemeTemplateQueryFixture.Create(pageKey: " ");
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Themes.PageKeyCannotBeEmpty);
}
[Fact]
public void Validate_WhenQueryIsValid_ShouldNotHaveAnyValidationErrors()
{
// Arrange
GetThemeTemplateQuery query = _getThemeTemplateQueryFixture.Create();
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -0,0 +1,101 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Themes;
using Lumina.Application.Common.DataAccess.Repositories.Themes;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Core.Themes.Management.Queries.GetThemes;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes;
using Lumina.Application.Fixtures.Core.Themes.Management.Queries.GetThemes;
using Lumina.Contracts.Responses.Themes;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Themes;
using NSubstitute;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.Themes.Management.Queries.GetThemes;
/// <summary>
/// Contains unit tests for the <see cref="GetThemesQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetThemesQueryHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IThemeRepository _mockThemeRepository;
private readonly GetThemesQueryHandler _sut;
private readonly GetThemesQueryFixture _getThemesQueryFixture = new();
private readonly ThemeEntityFixture _themeEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetThemesQueryHandlerTests"/> class.
/// </summary>
public GetThemesQueryHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockThemeRepository = Substitute.For<IThemeRepository>();
_mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository);
_sut = new GetThemesQueryHandler(_mockUnitOfWork);
}
[Fact]
public async Task HandleAsync_WhenCalled_ShouldReturnAllAvailableThemesOrderedBundledFirstThenByName()
{
// Arrange
GetThemesQuery query = _getThemesQueryFixture.Create();
ThemeEntity uploadedTheme = _themeEntityFixture.Create(themeId: "user-theme", name: "Zeta", installSource: ThemeInstallSource.Uploaded, isDeleted: false);
ThemeEntity bundledLowerTheme = _themeEntityFixture.Create(themeId: "bundled-lower", name: "apple", installSource: ThemeInstallSource.Bundled, isDeleted: false);
ThemeEntity bundledUpperTheme = _themeEntityFixture.Create(themeId: "bundled-upper", name: "Banana", installSource: ThemeInstallSource.Bundled, isDeleted: false);
ThemeEntity deletedTheme = _themeEntityFixture.Create(themeId: "deleted-theme", name: "Deleted", installSource: ThemeInstallSource.Uploaded, isDeleted: true);
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(Result.From<IEnumerable<ThemeEntity>>([uploadedTheme, bundledLowerTheme, bundledUpperTheme, deletedTheme]));
// Act
Result<IReadOnlyList<ThemeResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(3, result.Value.Count);
Assert.Equal(bundledLowerTheme.Id, result.Value[0].Id);
Assert.Equal(bundledUpperTheme.Id, result.Value[1].Id);
Assert.Equal(uploadedTheme.Id, result.Value[2].Id);
Assert.Equal(ThemeInstallSource.Bundled, result.Value[0].InstallSource);
Assert.Equal(ThemeInstallSource.Bundled, result.Value[1].InstallSource);
Assert.Equal(ThemeInstallSource.Uploaded, result.Value[2].InstallSource);
}
[Fact]
public async Task HandleAsync_WhenNoThemesExist_ShouldReturnEmptyList()
{
// Arrange
GetThemesQuery query = _getThemesQueryFixture.Create();
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(Result.From<IEnumerable<ThemeEntity>>([]));
// Act
Result<IReadOnlyList<ThemeResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Empty(result.Value);
}
[Fact]
public async Task HandleAsync_WhenRepositoryReturnsError_ShouldReturnError()
{
// Arrange
GetThemesQuery query = _getThemesQueryFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to get all themes");
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<IReadOnlyList<ThemeResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
}
}
@@ -3,6 +3,7 @@ using Lumina.Domain.Common.Primitives;
using Lumina.Infrastructure.Common.Errors;
using Lumina.Infrastructure.Common.Models.DTO.Configuration;
using Lumina.Infrastructure.Common.Validators;
using Lumina.Infrastructure.Fixtures.Common.Models.DTO.Configuration;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
@@ -16,12 +17,13 @@ namespace Lumina.Infrastructure.UnitTests.Common.Validators;
public class ThemeEngineOptionsDtoValidatorTests
{
private readonly ThemeEngineOptionsDtoValidator _validator = new();
private readonly ThemeEngineOptionsDtoFixture _themeEngineOptionsDtoFixture = new();
[Fact]
public void Validate_WhenAllPropertiesValid_ShouldNotHaveValidationError()
{
// Arrange
ThemeEngineOptionsDto options = new();
ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create();
// Act
List<Error> result = _validator.Validate(options);
@@ -34,7 +36,7 @@ public class ThemeEngineOptionsDtoValidatorTests
public void Validate_WhenStoragePathIsEmpty_ShouldHaveValidationError()
{
// Arrange
ThemeEngineOptionsDto options = new() { StoragePath = string.Empty };
ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create(storagePath: string.Empty);
// Act
List<Error> result = _validator.Validate(options);
@@ -48,7 +50,7 @@ public class ThemeEngineOptionsDtoValidatorTests
public void Validate_WhenBundledThemesPathIsEmpty_ShouldHaveValidationError()
{
// Arrange
ThemeEngineOptionsDto options = new() { BundledThemesPath = string.Empty };
ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create(bundledThemesPath: string.Empty);
// Act
List<Error> result = _validator.Validate(options);
@@ -62,7 +64,7 @@ public class ThemeEngineOptionsDtoValidatorTests
public void Validate_WhenDefaultThemeIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
ThemeEngineOptionsDto options = new() { DefaultThemeId = string.Empty };
ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create(defaultThemeId: string.Empty);
// Act
List<Error> result = _validator.Validate(options);
@@ -78,7 +80,7 @@ public class ThemeEngineOptionsDtoValidatorTests
public void Validate_WhenMaxArchiveBytesIsNotPositive_ShouldHaveValidationError(long maxArchiveBytes)
{
// Arrange
ThemeEngineOptionsDto options = new() { MaxArchiveBytes = maxArchiveBytes };
ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create(maxArchiveBytes: maxArchiveBytes);
// Act
List<Error> result = _validator.Validate(options);
@@ -94,7 +96,7 @@ public class ThemeEngineOptionsDtoValidatorTests
public void Validate_WhenMaxExpandedBytesIsNotPositive_ShouldHaveValidationError(long maxExpandedBytes)
{
// Arrange
ThemeEngineOptionsDto options = new() { MaxExpandedBytes = maxExpandedBytes };
ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create(maxExpandedBytes: maxExpandedBytes);
// Act
List<Error> result = _validator.Validate(options);
@@ -110,7 +112,7 @@ public class ThemeEngineOptionsDtoValidatorTests
public void Validate_WhenMaxSingleFileBytesIsNotPositive_ShouldHaveValidationError(long maxSingleFileBytes)
{
// Arrange
ThemeEngineOptionsDto options = new() { MaxSingleFileBytes = maxSingleFileBytes };
ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create(maxSingleFileBytes: maxSingleFileBytes);
// Act
List<Error> result = _validator.Validate(options);
@@ -126,7 +128,7 @@ public class ThemeEngineOptionsDtoValidatorTests
public void Validate_WhenMaxEntriesIsNotPositive_ShouldHaveValidationError(int maxEntries)
{
// Arrange
ThemeEngineOptionsDto options = new() { MaxEntries = maxEntries };
ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create(maxEntries: maxEntries);
// Act
List<Error> result = _validator.Validate(options);
@@ -0,0 +1,402 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Themes;
using Lumina.Application.Common.DataAccess.Repositories.Themes;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Models.DTO.Themes;
using Lumina.Application.Common.Infrastructure.Themes;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes;
using Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.Themes;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Themes;
using Lumina.Infrastructure.Core.Themes;
using Lumina.Infrastructure.Fixtures.Core.Themes;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.Themes;
/// <summary>
/// Contains unit tests for the <see cref="ThemeDetectionSyncJob"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ThemeDetectionSyncJobTests : IDisposable
{
private readonly IServiceScopeFactory _mockServiceScopeFactory;
private readonly IServiceScope _mockServiceScope;
private readonly IServiceProvider _mockServiceProvider;
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IThemeRepository _mockThemeRepository;
private readonly IThemeService _mockThemeService;
private readonly ILogger<ThemeDetectionSyncJob> _mockLogger;
private readonly ThemePackFixture _themePackFixture = new();
private readonly ThemeEntityFixture _themeEntityFixture = new();
private readonly ThemeManifestDtoFixture _themeManifestDtoFixture = new();
private readonly string _testRootPath;
/// <summary>
/// Initializes a new instance of the <see cref="ThemeDetectionSyncJobTests"/> class.
/// </summary>
public ThemeDetectionSyncJobTests()
{
_testRootPath = Path.Combine(Path.GetTempPath(), $"lumina-theme-job-{Guid.NewGuid():N}");
Directory.CreateDirectory(_testRootPath);
_mockServiceScopeFactory = Substitute.For<IServiceScopeFactory>();
_mockServiceScope = Substitute.For<IServiceScope>();
_mockServiceProvider = Substitute.For<IServiceProvider>();
_mockServiceScopeFactory.CreateAsyncScope().Returns(new AsyncServiceScope(_mockServiceScope));
_mockServiceScope.ServiceProvider.Returns(_mockServiceProvider);
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockThemeRepository = Substitute.For<IThemeRepository>();
_mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository);
_mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork);
_mockThemeService = Substitute.For<IThemeService>();
_mockThemeService.HasThemePack(Arg.Any<string>()).Returns(true);
_mockLogger = Substitute.For<ILogger<ThemeDetectionSyncJob>>();
}
/// <summary>
/// Cleans up the temporary storage used by the tests.
/// </summary>
public void Dispose()
{
try
{
if (Directory.Exists(_testRootPath))
Directory.Delete(_testRootPath, recursive: true);
}
catch (IOException)
{
// best effort cleanup of the per-test temp directory
}
catch (UnauthorizedAccessException)
{
// best effort cleanup of the per-test temp directory
}
}
[Fact]
public async Task StartAsync_WhenThereAreNoBundledThemesAndNoInstalledThemes_ShouldOnlySaveChanges()
{
// Arrange
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ThemeEntity>>([]));
_mockThemeService.GetBundledThemeArchivePaths().Returns([]);
// Act
await StartAndWaitForExecutionAsync(CreateSut());
// Assert
await _mockThemeRepository.DidNotReceiveWithAnyArgs().InsertAsync(default!, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task StartAsync_WhenBundledThemeIsNotYetInstalled_ShouldInstallAndPersistTheTheme()
{
// Arrange
string archivePath = CreateBundledArchiveFile("bundled-theme");
ThemeManifestDto manifest = _themeManifestDtoFixture.Create(id: "bundled-theme");
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ThemeEntity>>([]));
_mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]);
_mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any<CancellationToken>()).Returns(manifest);
_mockThemeService.InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>()).Returns(manifest);
_mockThemeRepository.InsertAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>()).Returns(Result.From(Result.Created));
// Act
await StartAndWaitForExecutionAsync(CreateSut());
// Assert
await _mockThemeService.Received(1).InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>());
await _mockThemeRepository.Received(1).InsertAsync(
Arg.Is<ThemeEntity>(theme => theme.ThemeId == "bundled-theme"
&& theme.Name == manifest.Name
&& theme.Description == manifest.Description
&& theme.Version == manifest.Version
&& theme.InstallSource == ThemeInstallSource.Bundled),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task StartAsync_WhenBundledThemeIsAlreadyInstalled_ShouldSkipInstallingIt()
{
// Arrange
ThemeEntity existingTheme = _themeEntityFixture.Create(themeId: "bundled-theme", isCurrent: true, includeIsCurrent: true, installSource: ThemeInstallSource.Bundled, isDeleted: false);
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ThemeEntity>>([existingTheme]));
_mockThemeService.GetBundledThemeArchivePaths().Returns(["C:\\bundled\\bundled-theme.zip"]);
_mockThemeService.ReadManifestFromArchiveAsync("C:\\bundled\\bundled-theme.zip", Arg.Any<CancellationToken>()).Returns(_themeManifestDtoFixture.Create(id: "bundled-theme"));
// Act
await StartAndWaitForExecutionAsync(CreateSut());
// Assert
await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>());
await _mockThemeRepository.DidNotReceiveWithAnyArgs().InsertAsync(default!, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task StartAsync_WhenBundledThemeWasSoftDeletedByTheUser_ShouldNotReinstallIt()
{
// Arrange
ThemeEntity deletedTheme = _themeEntityFixture.Create(themeId: "bundled-theme", isDeleted: true, installSource: ThemeInstallSource.Bundled);
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ThemeEntity>>([deletedTheme]));
_mockThemeService.GetBundledThemeArchivePaths().Returns(["C:\\bundled\\bundled-theme.zip"]);
_mockThemeService.ReadManifestFromArchiveAsync("C:\\bundled\\bundled-theme.zip", Arg.Any<CancellationToken>()).Returns(_themeManifestDtoFixture.Create(id: "bundled-theme"));
// Act
await StartAndWaitForExecutionAsync(CreateSut());
// Assert
await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>());
await _mockThemeRepository.DidNotReceiveWithAnyArgs().InsertAsync(default!, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task StartAsync_WhenBundledArchiveManifestCannotBeRead_ShouldSkipTheArchive()
{
// Arrange
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ThemeEntity>>([]));
_mockThemeService.GetBundledThemeArchivePaths().Returns(["C:\\bundled\\broken.zip"]);
_mockThemeService.ReadManifestFromArchiveAsync("C:\\bundled\\broken.zip", Arg.Any<CancellationToken>()).Returns(Error.Failure("Theme.Files", "unreadable"));
// Act
await StartAndWaitForExecutionAsync(CreateSut());
// Assert
await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>());
await _mockThemeRepository.DidNotReceiveWithAnyArgs().InsertAsync(default!, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task StartAsync_WhenBundledThemeInstallFails_ShouldNotPersistTheTheme()
{
// Arrange
string archivePath = CreateBundledArchiveFile("bundled-theme");
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ThemeEntity>>([]));
_mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]);
_mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any<CancellationToken>()).Returns(_themeManifestDtoFixture.Create(id: "bundled-theme"));
_mockThemeService.InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>()).Returns(Error.Failure("Theme.Install", "install failed"));
// Act
await StartAndWaitForExecutionAsync(CreateSut());
// Assert
await _mockThemeRepository.DidNotReceiveWithAnyArgs().InsertAsync(default!, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task StartAsync_WhenPersistingDetectedThemeFails_ShouldLogWarningAndContinue()
{
// Arrange
string archivePath = CreateBundledArchiveFile("bundled-theme");
ThemeManifestDto manifest = _themeManifestDtoFixture.Create(id: "bundled-theme");
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ThemeEntity>>([]));
_mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]);
_mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any<CancellationToken>()).Returns(manifest);
_mockThemeService.InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>()).Returns(manifest);
_mockThemeRepository.InsertAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>()).Returns(Error.Failure("Database.Error", "failed to persist"));
// Act
await StartAndWaitForExecutionAsync(CreateSut());
// Assert
await _mockThemeRepository.Received(1).InsertAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task StartAsync_WhenReadingInstalledThemesFails_ShouldReturnWithoutPersistingChanges()
{
// Arrange
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Error.Failure("Database.Error", "failed to read themes"));
// Act
await StartAndWaitForExecutionAsync(CreateSut());
// Assert
_mockThemeService.DidNotReceive().GetBundledThemeArchivePaths();
await _mockUnitOfWork.DidNotReceiveWithAnyArgs().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task StartAsync_WhenMissingBundledThemePackCanBeRestored_ShouldRestoreTheFiles()
{
// Arrange
ThemeEntity brokenTheme = _themeEntityFixture.Create(themeId: "bundled-theme", isCurrent: true, includeIsCurrent: true, installSource: ThemeInstallSource.Bundled, isDeleted: false);
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ThemeEntity>>([brokenTheme]));
_mockThemeService.HasThemePack("bundled-theme").Returns(false);
_mockThemeService.GetBundledThemeArchivePaths().Returns([]);
_mockThemeService.RestoreBundledThemeAsync("bundled-theme", Arg.Any<CancellationToken>()).Returns(Result.Success);
// Act
await StartAndWaitForExecutionAsync(CreateSut());
// Assert
await _mockThemeService.Received(1).RestoreBundledThemeAsync("bundled-theme", Arg.Any<CancellationToken>());
await _mockThemeRepository.DidNotReceiveWithAnyArgs().UpdateAsync(default!, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task StartAsync_WhenMissingBundledThemePackCannotBeRestored_ShouldSoftDeleteTheTheme()
{
// Arrange
ThemeEntity brokenTheme = _themeEntityFixture.Create(themeId: "bundled-theme", installSource: ThemeInstallSource.Bundled, isDeleted: false);
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ThemeEntity>>([brokenTheme]));
_mockThemeService.HasThemePack("bundled-theme").Returns(false);
_mockThemeService.GetBundledThemeArchivePaths().Returns([]);
_mockThemeService.RestoreBundledThemeAsync("bundled-theme", Arg.Any<CancellationToken>()).Returns(Error.Failure("Theme.Files", "restore failed"));
_mockThemeRepository.UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>()).Returns(Result.From(Result.Updated));
// Act
await StartAndWaitForExecutionAsync(CreateSut());
// Assert
await _mockThemeRepository.Received(1).UpdateAsync(
Arg.Is<ThemeEntity>(theme => theme.ThemeId == "bundled-theme" && theme.IsDeleted && theme.IsCurrent == null),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task StartAsync_WhenMissingUserThemePackExists_ShouldDeleteTheTheme()
{
// Arrange
ThemeEntity brokenTheme = _themeEntityFixture.Create(themeId: "user-theme", installSource: ThemeInstallSource.Uploaded, isDeleted: false);
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ThemeEntity>>([brokenTheme]));
_mockThemeService.HasThemePack("user-theme").Returns(false);
_mockThemeService.GetBundledThemeArchivePaths().Returns([]);
_mockThemeRepository.DeleteByIdAsync(brokenTheme.Id, Arg.Any<CancellationToken>()).Returns(Result.From(Result.Deleted));
// Act
await StartAndWaitForExecutionAsync(CreateSut());
// Assert
await _mockThemeRepository.Received(1).DeleteByIdAsync(brokenTheme.Id, Arg.Any<CancellationToken>());
await _mockThemeService.DidNotReceive().RestoreBundledThemeAsync(Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task StartAsync_WhenDeletingMissingUserThemeFails_ShouldLogWarningAndContinue()
{
// Arrange
ThemeEntity brokenTheme = _themeEntityFixture.Create(themeId: "user-theme", installSource: ThemeInstallSource.Uploaded, isDeleted: false);
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ThemeEntity>>([brokenTheme]));
_mockThemeService.HasThemePack("user-theme").Returns(false);
_mockThemeService.GetBundledThemeArchivePaths().Returns([]);
_mockThemeRepository.DeleteByIdAsync(brokenTheme.Id, Arg.Any<CancellationToken>()).Returns(Error.Failure("Database.Error", "delete failed"));
// Act
await StartAndWaitForExecutionAsync(CreateSut());
// Assert
await _mockThemeRepository.Received(1).DeleteByIdAsync(brokenTheme.Id, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task StartAsync_WhenNoThemeIsCurrent_ShouldActivateTheDefaultTheme()
{
// Arrange
ThemeEntity theme = _themeEntityFixture.Create(themeId: "default-theme", installSource: ThemeInstallSource.Bundled, isDeleted: false);
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ThemeEntity>>([theme]));
_mockThemeService.DefaultThemeId.Returns("default-theme");
_mockThemeService.GetBundledThemeArchivePaths().Returns([]);
_mockThemeRepository.UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>()).Returns(Result.From(Result.Updated));
// Act
await StartAndWaitForExecutionAsync(CreateSut());
// Assert
await _mockThemeRepository.Received(1).UpdateAsync(
Arg.Is<ThemeEntity>(candidate => candidate.ThemeId == "default-theme" && candidate.IsCurrent == true),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task StartAsync_WhenNoThemeIsCurrent_ShouldPreferTheConfiguredDefaultTheme()
{
// Arrange
ThemeEntity firstTheme = _themeEntityFixture.Create(themeId: "alpha-theme", installSource: ThemeInstallSource.Bundled, isDeleted: false);
ThemeEntity defaultTheme = _themeEntityFixture.Create(themeId: "default-theme", installSource: ThemeInstallSource.Bundled, isDeleted: false);
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ThemeEntity>>([firstTheme, defaultTheme]));
_mockThemeService.DefaultThemeId.Returns("default-theme");
_mockThemeService.GetBundledThemeArchivePaths().Returns([]);
_mockThemeRepository.UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>()).Returns(Result.From(Result.Updated));
// Act
await StartAndWaitForExecutionAsync(CreateSut());
// Assert
await _mockThemeRepository.Received(1).UpdateAsync(
Arg.Is<ThemeEntity>(candidate => candidate.ThemeId == "default-theme" && candidate.IsCurrent == true),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task StartAsync_WhenAThemeIsAlreadyCurrent_ShouldNotChangeActivation()
{
// Arrange
ThemeEntity theme = _themeEntityFixture.Create(themeId: "current-theme", isCurrent: true, includeIsCurrent: true, installSource: ThemeInstallSource.Bundled, isDeleted: false);
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ThemeEntity>>([theme]));
_mockThemeService.GetBundledThemeArchivePaths().Returns([]);
// Act
await StartAndWaitForExecutionAsync(CreateSut());
// Assert
await _mockThemeRepository.DidNotReceiveWithAnyArgs().UpdateAsync(default!, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
/// <summary>
/// Invokes the protected <see cref="BackgroundService.ExecuteAsync"/> of the job and awaits its completion.
/// </summary>
/// <param name="sut">The job to execute.</param>
private static async Task StartAndWaitForExecutionAsync(ThemeDetectionSyncJob sut)
{
MethodInfo executeAsyncMethod = typeof(ThemeDetectionSyncJob).GetMethod("ExecuteAsync", BindingFlags.Instance | BindingFlags.NonPublic)!;
Task executingTask = (Task)executeAsyncMethod.Invoke(sut, [CancellationToken.None])!;
await executingTask;
}
/// <summary>
/// Creates the system under test wired to the mocked dependencies.
/// </summary>
/// <returns>The created job instance.</returns>
private ThemeDetectionSyncJob CreateSut()
{
return new ThemeDetectionSyncJob(_mockServiceScopeFactory, _mockThemeService, _mockLogger);
}
/// <summary>
/// Writes a bundled theme archive file into the per-test temporary directory.
/// </summary>
/// <param name="themeId">The theme id of the bundled archive.</param>
/// <returns>The path of the written archive.</returns>
private string CreateBundledArchiveFile(string themeId)
{
string bundledPath = Path.Combine(_testRootPath, "bundled");
Directory.CreateDirectory(bundledPath);
string archivePath = Path.Combine(bundledPath, $"{themeId}.zip");
File.WriteAllBytes(archivePath, _themePackFixture.Create(themeId: themeId));
return archivePath;
}
}
@@ -0,0 +1,81 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Infrastructure.Core.Themes;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.Themes;
/// <summary>
/// Contains unit tests for the <see cref="ThemeMimeTypes"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ThemeMimeTypesTests
{
[Theory]
[InlineData("index.html", "text/html")]
[InlineData("index.htm", "text/html")]
[InlineData("style.css", "text/css")]
[InlineData("app.js", "application/javascript")]
[InlineData("manifest.json", "application/json")]
[InlineData("image.png", "image/png")]
[InlineData("photo.jpg", "image/jpeg")]
[InlineData("photo.jpeg", "image/jpeg")]
[InlineData("animation.gif", "image/gif")]
[InlineData("graphic.webp", "image/webp")]
[InlineData("icon.svg", "image/svg+xml")]
[InlineData("favicon.ico", "image/x-icon")]
[InlineData("font.woff", "font/woff")]
[InlineData("font.woff2", "font/woff2")]
[InlineData("font.ttf", "font/ttf")]
[InlineData("readme.txt", "text/plain")]
public void GetMimeType_WhenExtensionIsKnown_ShouldReturnMappedContentType(string filePath, string expectedContentType)
{
// Arrange
// filePath and expectedContentType are provided by the test data
// Act
string result = ThemeMimeTypes.GetMimeType(filePath);
// Assert
Assert.Equal(expectedContentType, result);
}
[Fact]
public void GetMimeType_WhenExtensionIsUnknown_ShouldReturnApplicationOctetStream()
{
// Arrange
string filePath = "archive.unknown";
// Act
string result = ThemeMimeTypes.GetMimeType(filePath);
// Assert
Assert.Equal("application/octet-stream", result);
}
[Fact]
public void GetMimeType_WhenFileHasNoExtension_ShouldReturnApplicationOctetStream()
{
// Arrange
string filePath = "README";
// Act
string result = ThemeMimeTypes.GetMimeType(filePath);
// Assert
Assert.Equal("application/octet-stream", result);
}
[Fact]
public void GetMimeType_WhenExtensionIsMixedCase_ShouldResolveCaseInsensitively()
{
// Arrange
string filePath = "Photo.PNG";
// Act
string result = ThemeMimeTypes.GetMimeType(filePath);
// Assert
Assert.Equal("image/png", result);
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,202 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Core.Themes.Management.Commands.DeleteTheme;
using Lumina.Contracts.Fixtures.Core.Requests.Themes;
using Lumina.Contracts.Requests.Themes;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Core.Endpoints.Themes.Management.DeleteTheme;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Themes.Management.DeleteTheme;
/// <summary>
/// Contains unit tests for the <see cref="DeleteThemeEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeleteThemeEndpointTests
{
private readonly Application.Common.CQRS.ICommandHandler<DeleteThemeCommand, Result<Success>> _mockHandler;
private readonly DeleteThemeEndpoint _sut;
private readonly DeleteThemeRequestFixture _deleteThemeRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="DeleteThemeEndpointTests"/> class.
/// </summary>
public DeleteThemeEndpointTests()
{
_mockHandler = Substitute.For<Application.Common.CQRS.ICommandHandler<DeleteThemeCommand, Result<Success>>>();
_sut = Factory.Create<DeleteThemeEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnNoContentResult()
{
// Arrange
DeleteThemeRequest request = _deleteThemeRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<DeleteThemeCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Success));
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
Assert.IsType<NoContent>(result);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult()
{
// Arrange
DeleteThemeRequest request = _deleteThemeRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = DomainErrors.Themes.ThemeNotFound;
_mockHandler.HandleAsync(Arg.Any<DeleteThemeCommand>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status);
Assert.Equal("General.NotFound", problemDetailsBody.Title);
Assert.Equal("ThemeNotFound", problemDetailsBody.Detail);
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetailsBody.Type);
Assert.NotNull(problemDetailsBody.Extensions["traceId"]);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult()
{
// Arrange
DeleteThemeRequest request = _deleteThemeRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = ApplicationErrors.Authorization.NotAuthorized;
_mockHandler.HandleAsync(Arg.Any<DeleteThemeCommand>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status);
Assert.Equal("General.Unauthorized", problemDetailsBody.Title);
Assert.Equal("NotAuthorized", problemDetailsBody.Detail);
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type);
Assert.NotNull(problemDetailsBody.Extensions["traceId"]);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsForbiddenError_ShouldReturnProblemResult()
{
// Arrange
DeleteThemeRequest request = _deleteThemeRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = DomainErrors.Themes.LastBundledThemeCannotBeDeleted;
_mockHandler.HandleAsync(Arg.Any<DeleteThemeCommand>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status);
Assert.Equal("General.Forbidden", problemDetailsBody.Title);
Assert.Equal("LastBundledThemeCannotBeDeleted", problemDetailsBody.Detail);
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type);
Assert.NotNull(problemDetailsBody.Extensions["traceId"]);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult()
{
// Arrange
DeleteThemeRequest request = _deleteThemeRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = DomainErrors.Themes.ThemeIdCannotBeEmpty;
_mockHandler.HandleAsync(Arg.Any<DeleteThemeCommand>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status);
Assert.Equal("General.Validation", validationProblemDetails.Title);
Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail);
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type);
Assert.Single(validationProblemDetails.Errors);
Assert.Equal(new[] { "ThemeIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendDeleteThemeCommandToHandler()
{
// Arrange
DeleteThemeRequest request = _deleteThemeRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<DeleteThemeCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Success));
// Act
await _sut.ExecuteAsync(request, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<DeleteThemeCommand>(command => command.ThemeId == request.ThemeId),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
DeleteThemeRequest request = _deleteThemeRequestFixture.Create();
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<DeleteThemeCommand>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From(Result.Success);
}, callInfo.Arg<CancellationToken>()));
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
}
@@ -0,0 +1,178 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Core.Themes.Management.Commands.InstallTheme;
using Lumina.Contracts.Fixtures.Core.Responses.Themes;
using Lumina.Contracts.Responses.Themes;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Core.Endpoints.Themes.Management.InstallTheme;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.Extensions.Primitives;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Themes.Management.InstallTheme;
/// <summary>
/// Contains unit tests for the <see cref="InstallThemeEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class InstallThemeEndpointTests
{
private readonly Application.Common.CQRS.ICommandHandler<InstallThemeCommand, Result<ThemeResponse>> _mockHandler;
private readonly InstallThemeEndpoint _sut;
private readonly ThemeResponseFixture _themeResponseFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="InstallThemeEndpointTests"/> class.
/// </summary>
public InstallThemeEndpointTests()
{
_mockHandler = Substitute.For<Application.Common.CQRS.ICommandHandler<InstallThemeCommand, Result<ThemeResponse>>>();
_sut = Factory.Create<InstallThemeEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenArchiveUploaded_ShouldReturnOkResultWithInstalledTheme()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
ThemeResponse expectedResponse = _themeResponseFixture.Create();
_mockHandler.HandleAsync(Arg.Any<InstallThemeCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(expectedResponse));
ConfigureFormWithArchive([1, 2, 3, 4], "theme-pack.zip");
// Act
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken);
// Assert
Ok<ThemeResponse> okResult = Assert.IsType<Ok<ThemeResponse>>(result);
Assert.Equal(expectedResponse, okResult.Value);
}
[Fact]
public async Task ExecuteAsync_WhenArchiveUploaded_ShouldSendInstallThemeCommandWithUploadedStreamAndFileName()
{
// Arrange
byte[] content = [1, 2, 3, 4];
string fileName = "theme-pack.zip";
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<InstallThemeCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_themeResponseFixture.Create()));
ConfigureFormWithArchive(content, fileName);
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<InstallThemeCommand>(command =>
command.FileName == fileName &&
command.Archive != null),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenNoArchiveUploaded_ShouldSendInstallThemeCommandWithNullArchiveAndFileName()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
ThemeResponse expectedResponse = _themeResponseFixture.Create();
_mockHandler.HandleAsync(Arg.Any<InstallThemeCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(expectedResponse));
ConfigureFormWithoutFiles();
// Act
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken);
// Assert
Ok<ThemeResponse> okResult = Assert.IsType<Ok<ThemeResponse>>(result);
Assert.Equal(expectedResponse, okResult.Value);
await _mockHandler.Received(1).HandleAsync(
Arg.Is<InstallThemeCommand>(command =>
command.Archive == null &&
command.FileName == null),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = ApplicationErrors.Authorization.NotAuthorized;
_mockHandler.HandleAsync(Arg.Any<InstallThemeCommand>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
ConfigureFormWithArchive([1, 2, 3, 4], "theme-pack.zip");
// Act
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status);
Assert.Equal("General.Unauthorized", problemDetailsBody.Title);
Assert.Equal("NotAuthorized", problemDetailsBody.Detail);
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type);
Assert.NotNull(problemDetailsBody.Extensions["traceId"]);
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<InstallThemeCommand>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From(_themeResponseFixture.Create());
}, callInfo.Arg<CancellationToken>()));
ConfigureFormWithArchive([1, 2, 3, 4], "theme-pack.zip");
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(EmptyRequest.Instance, cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
private void ConfigureFormWithArchive(byte[] content, string fileName)
{
// the stream stays open for the duration of the test, since the endpoint reads it through the form file during execution
MemoryStream archiveStream = new(content);
IFormFile formFile = new FormFile(archiveStream, 0, content.Length, "archive", fileName);
FormFileCollection files = [formFile];
IFormCollection form = new FormCollection([], files);
_sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test";
// a real FormFeature is used instead of a substitute, because the endpoint execution reads the form through the
// request machinery, which would bypass a mocked feature and parse the (empty) request body
_sut.HttpContext.Features.Set<IFormFeature>(new FormFeature(form));
}
private void ConfigureFormWithoutFiles()
{
IFormCollection form = new FormCollection([]);
_sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test";
_sut.HttpContext.Features.Set<IFormFeature>(new FormFeature(form));
}
}
@@ -0,0 +1,183 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.Themes.Management.Commands.SetCurrentTheme;
using Lumina.Contracts.Fixtures.Core.Requests.Themes;
using Lumina.Contracts.Fixtures.Core.Responses.Themes;
using Lumina.Contracts.Requests.Themes;
using Lumina.Contracts.Responses.Themes;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Core.Endpoints.Themes.Management.SetCurrentTheme;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Themes.Management.SetCurrentTheme;
/// <summary>
/// Contains unit tests for the <see cref="SetCurrentThemeEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetCurrentThemeEndpointTests
{
private readonly Application.Common.CQRS.ICommandHandler<SetCurrentThemeCommand, Result<ThemeResponse>> _mockHandler;
private readonly SetCurrentThemeEndpoint _sut;
private readonly SetCurrentThemeRequestFixture _setCurrentThemeRequestFixture = new();
private readonly ThemeResponseFixture _themeResponseFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="SetCurrentThemeEndpointTests"/> class.
/// </summary>
public SetCurrentThemeEndpointTests()
{
_mockHandler = Substitute.For<Application.Common.CQRS.ICommandHandler<SetCurrentThemeCommand, Result<ThemeResponse>>>();
_sut = Factory.Create<SetCurrentThemeEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithActivatedTheme()
{
// Arrange
SetCurrentThemeRequest request = _setCurrentThemeRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
ThemeResponse expectedResponse = _themeResponseFixture.Create();
_mockHandler.HandleAsync(Arg.Any<SetCurrentThemeCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(expectedResponse));
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
Ok<ThemeResponse> okResult = Assert.IsType<Ok<ThemeResponse>>(result);
Assert.Equal(expectedResponse, okResult.Value);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult()
{
// Arrange
SetCurrentThemeRequest request = _setCurrentThemeRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = DomainErrors.Themes.ThemeNotFound;
_mockHandler.HandleAsync(Arg.Any<SetCurrentThemeCommand>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status);
Assert.Equal("General.NotFound", problemDetailsBody.Title);
Assert.Equal("ThemeNotFound", problemDetailsBody.Detail);
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetailsBody.Type);
Assert.NotNull(problemDetailsBody.Extensions["traceId"]);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult()
{
// Arrange
SetCurrentThemeRequest request = _setCurrentThemeRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = ApplicationErrors.Authorization.NotAuthorized;
_mockHandler.HandleAsync(Arg.Any<SetCurrentThemeCommand>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status);
Assert.Equal("General.Unauthorized", problemDetailsBody.Title);
Assert.Equal("NotAuthorized", problemDetailsBody.Detail);
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type);
Assert.NotNull(problemDetailsBody.Extensions["traceId"]);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult()
{
// Arrange
SetCurrentThemeRequest request = _setCurrentThemeRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = DomainErrors.Themes.ThemeIdCannotBeEmpty;
_mockHandler.HandleAsync(Arg.Any<SetCurrentThemeCommand>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status);
Assert.Equal("General.Validation", validationProblemDetails.Title);
Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail);
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type);
Assert.Single(validationProblemDetails.Errors);
Assert.Equal(new[] { "ThemeIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendSetCurrentThemeCommandToHandler()
{
// Arrange
SetCurrentThemeRequest request = _setCurrentThemeRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<SetCurrentThemeCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_themeResponseFixture.Create()));
// Act
await _sut.ExecuteAsync(request, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<SetCurrentThemeCommand>(command => command.ThemeId == request.ThemeId),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
SetCurrentThemeRequest request = _setCurrentThemeRequestFixture.Create();
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<SetCurrentThemeCommand>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From(_themeResponseFixture.Create());
}, callInfo.Arg<CancellationToken>()));
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
}
@@ -0,0 +1,124 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.Themes.Management.Queries.GetCurrentTheme;
using Lumina.Contracts.Fixtures.Core.Responses.Themes;
using Lumina.Contracts.Responses.Themes;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Core.Endpoints.Themes.Queries.GetCurrentTheme;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Themes.Queries.GetCurrentTheme;
/// <summary>
/// Contains unit tests for the <see cref="GetCurrentThemeEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetCurrentThemeEndpointTests
{
private readonly IQueryHandler<GetCurrentThemeQuery, Result<ThemeResponse>> _mockHandler;
private readonly GetCurrentThemeEndpoint _sut;
private readonly ThemeResponseFixture _themeResponseFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetCurrentThemeEndpointTests"/> class.
/// </summary>
public GetCurrentThemeEndpointTests()
{
_mockHandler = Substitute.For<IQueryHandler<GetCurrentThemeQuery, Result<ThemeResponse>>>();
_sut = Factory.Create<GetCurrentThemeEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithCurrentTheme()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
ThemeResponse expectedResponse = _themeResponseFixture.Create();
_mockHandler.HandleAsync(Arg.Any<GetCurrentThemeQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(expectedResponse));
// Act
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken);
// Assert
Ok<ThemeResponse> okResult = Assert.IsType<Ok<ThemeResponse>>(result);
Assert.Equal(expectedResponse, okResult.Value);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = DomainErrors.Themes.ThemeNotFound;
_mockHandler.HandleAsync(Arg.Any<GetCurrentThemeQuery>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status);
Assert.Equal("General.NotFound", problemDetailsBody.Title);
Assert.Equal("ThemeNotFound", problemDetailsBody.Detail);
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetailsBody.Type);
Assert.NotNull(problemDetailsBody.Extensions["traceId"]);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendGetCurrentThemeQueryToHandler()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<GetCurrentThemeQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_themeResponseFixture.Create()));
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<GetCurrentThemeQuery>(query => query != null),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<GetCurrentThemeQuery>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From(_themeResponseFixture.Create());
}, callInfo.Arg<CancellationToken>()));
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(EmptyRequest.Instance, cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
}
@@ -0,0 +1,160 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.Themes.Management.Queries.GetThemeArchive;
using Lumina.Contracts.Fixtures.Core.Requests.Themes;
using Lumina.Contracts.Fixtures.Core.Responses.Themes;
using Lumina.Contracts.Requests.Themes;
using Lumina.Contracts.Responses.Themes;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Core.Endpoints.Themes.Queries.GetThemeArchive;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Themes.Queries.GetThemeArchive;
/// <summary>
/// Contains unit tests for the <see cref="GetThemeArchiveEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetThemeArchiveEndpointTests
{
private readonly IQueryHandler<GetThemeArchiveQuery, Result<ThemeArchiveResponse>> _mockHandler;
private readonly GetThemeArchiveEndpoint _sut;
private readonly GetThemeArchiveRequestFixture _getThemeArchiveRequestFixture = new();
private readonly ThemeArchiveResponseFixture _themeArchiveResponseFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetThemeArchiveEndpointTests"/> class.
/// </summary>
public GetThemeArchiveEndpointTests()
{
_mockHandler = Substitute.For<IQueryHandler<GetThemeArchiveQuery, Result<ThemeArchiveResponse>>>();
_sut = Factory.Create<GetThemeArchiveEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnFileResultWithThemeArchive()
{
// Arrange
GetThemeArchiveRequest request = _getThemeArchiveRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
ThemeArchiveResponse expectedResponse = _themeArchiveResponseFixture.Create();
_mockHandler.HandleAsync(Arg.Any<GetThemeArchiveQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(expectedResponse));
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
FileContentHttpResult fileResult = Assert.IsType<FileContentHttpResult>(result);
Assert.Equal(expectedResponse.Bytes, fileResult.FileContents.ToArray());
Assert.Equal(expectedResponse.ContentType, fileResult.ContentType);
Assert.Equal(expectedResponse.FileName, fileResult.FileDownloadName);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult()
{
// Arrange
GetThemeArchiveRequest request = _getThemeArchiveRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = DomainErrors.Themes.ThemeNotFound;
_mockHandler.HandleAsync(Arg.Any<GetThemeArchiveQuery>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status);
Assert.Equal("General.NotFound", problemDetailsBody.Title);
Assert.Equal("ThemeNotFound", problemDetailsBody.Detail);
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetailsBody.Type);
Assert.NotNull(problemDetailsBody.Extensions["traceId"]);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult()
{
// Arrange
GetThemeArchiveRequest request = _getThemeArchiveRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = DomainErrors.Themes.ThemeIdCannotBeEmpty;
_mockHandler.HandleAsync(Arg.Any<GetThemeArchiveQuery>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status);
Assert.Equal("General.Validation", validationProblemDetails.Title);
Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail);
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type);
Assert.Single(validationProblemDetails.Errors);
Assert.Equal(new[] { "ThemeIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendGetThemeArchiveQueryToHandler()
{
// Arrange
GetThemeArchiveRequest request = _getThemeArchiveRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<GetThemeArchiveQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_themeArchiveResponseFixture.Create()));
// Act
await _sut.ExecuteAsync(request, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<GetThemeArchiveQuery>(query => query.ThemeId == request.ThemeId),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
GetThemeArchiveRequest request = _getThemeArchiveRequestFixture.Create();
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<GetThemeArchiveQuery>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From(_themeArchiveResponseFixture.Create());
}, callInfo.Arg<CancellationToken>()));
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
}
@@ -0,0 +1,161 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.Themes.Management.Queries.GetThemeAsset;
using Lumina.Contracts.Fixtures.Core.Requests.Themes;
using Lumina.Contracts.Fixtures.Core.Responses.Themes;
using Lumina.Contracts.Requests.Themes;
using Lumina.Contracts.Responses.Themes;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Core.Endpoints.Themes.Queries.GetThemeAsset;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Themes.Queries.GetThemeAsset;
/// <summary>
/// Contains unit tests for the <see cref="GetThemeAssetEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetThemeAssetEndpointTests
{
private readonly IQueryHandler<GetThemeAssetQuery, Result<ThemeAssetResponse>> _mockHandler;
private readonly GetThemeAssetEndpoint _sut;
private readonly GetThemeAssetRequestFixture _getThemeAssetRequestFixture = new();
private readonly ThemeAssetResponseFixture _themeAssetResponseFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetThemeAssetEndpointTests"/> class.
/// </summary>
public GetThemeAssetEndpointTests()
{
_mockHandler = Substitute.For<IQueryHandler<GetThemeAssetQuery, Result<ThemeAssetResponse>>>();
_sut = Factory.Create<GetThemeAssetEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnFileResultWithThemeAsset()
{
// Arrange
GetThemeAssetRequest request = _getThemeAssetRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
ThemeAssetResponse expectedResponse = _themeAssetResponseFixture.Create();
_mockHandler.HandleAsync(Arg.Any<GetThemeAssetQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(expectedResponse));
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
FileContentHttpResult fileResult = Assert.IsType<FileContentHttpResult>(result);
Assert.Equal(expectedResponse.Bytes, fileResult.FileContents.ToArray());
Assert.Equal(expectedResponse.ContentType, fileResult.ContentType);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult()
{
// Arrange
GetThemeAssetRequest request = _getThemeAssetRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = DomainErrors.Themes.ThemeNotFound;
_mockHandler.HandleAsync(Arg.Any<GetThemeAssetQuery>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status);
Assert.Equal("General.NotFound", problemDetailsBody.Title);
Assert.Equal("ThemeNotFound", problemDetailsBody.Detail);
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetailsBody.Type);
Assert.NotNull(problemDetailsBody.Extensions["traceId"]);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult()
{
// Arrange
GetThemeAssetRequest request = _getThemeAssetRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = DomainErrors.Themes.ThemeAssetPathCannotBeEmpty;
_mockHandler.HandleAsync(Arg.Any<GetThemeAssetQuery>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status);
Assert.Equal("General.Validation", validationProblemDetails.Title);
Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail);
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type);
Assert.Single(validationProblemDetails.Errors);
Assert.Equal(new[] { "ThemeAssetPathCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendGetThemeAssetQueryToHandler()
{
// Arrange
GetThemeAssetRequest request = _getThemeAssetRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<GetThemeAssetQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_themeAssetResponseFixture.Create()));
// Act
await _sut.ExecuteAsync(request, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<GetThemeAssetQuery>(query =>
query.ThemeId == request.ThemeId &&
query.AssetPath == request.AssetPath),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
GetThemeAssetRequest request = _getThemeAssetRequestFixture.Create();
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<GetThemeAssetQuery>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From(_themeAssetResponseFixture.Create());
}, callInfo.Arg<CancellationToken>()));
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
}
@@ -0,0 +1,124 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.Themes.Management.Queries.GetThemeSettings;
using Lumina.Contracts.Fixtures.Core.Responses.Themes;
using Lumina.Contracts.Responses.Themes;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Core.Endpoints.Themes.Queries.GetThemeSettings;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Themes.Queries.GetThemeSettings;
/// <summary>
/// Contains unit tests for the <see cref="GetThemeSettingsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetThemeSettingsEndpointTests
{
private readonly IQueryHandler<GetThemeSettingsQuery, Result<ThemeSettingsResponse>> _mockHandler;
private readonly GetThemeSettingsEndpoint _sut;
private readonly ThemeSettingsResponseFixture _themeSettingsResponseFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetThemeSettingsEndpointTests"/> class.
/// </summary>
public GetThemeSettingsEndpointTests()
{
_mockHandler = Substitute.For<IQueryHandler<GetThemeSettingsQuery, Result<ThemeSettingsResponse>>>();
_sut = Factory.Create<GetThemeSettingsEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithThemeSettings()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
ThemeSettingsResponse expectedResponse = _themeSettingsResponseFixture.Create();
_mockHandler.HandleAsync(Arg.Any<GetThemeSettingsQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(expectedResponse));
// Act
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken);
// Assert
Ok<ThemeSettingsResponse> okResult = Assert.IsType<Ok<ThemeSettingsResponse>>(result);
Assert.Equal(expectedResponse, okResult.Value);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = DomainErrors.Themes.ThemeNotFound;
_mockHandler.HandleAsync(Arg.Any<GetThemeSettingsQuery>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status);
Assert.Equal("General.NotFound", problemDetailsBody.Title);
Assert.Equal("ThemeNotFound", problemDetailsBody.Detail);
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetailsBody.Type);
Assert.NotNull(problemDetailsBody.Extensions["traceId"]);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendGetThemeSettingsQueryToHandler()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<GetThemeSettingsQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_themeSettingsResponseFixture.Create()));
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<GetThemeSettingsQuery>(query => query != null),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<GetThemeSettingsQuery>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From(_themeSettingsResponseFixture.Create());
}, callInfo.Arg<CancellationToken>()));
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(EmptyRequest.Instance, cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
}
@@ -0,0 +1,159 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.Themes.Management.Queries.GetThemeTemplate;
using Lumina.Contracts.Fixtures.Core.Requests.Themes;
using Lumina.Contracts.Fixtures.Core.Responses.Themes;
using Lumina.Contracts.Requests.Themes;
using Lumina.Contracts.Responses.Themes;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Core.Endpoints.Themes.Queries.GetThemeTemplate;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Themes.Queries.GetThemeTemplate;
/// <summary>
/// Contains unit tests for the <see cref="GetThemeTemplateEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetThemeTemplateEndpointTests
{
private readonly IQueryHandler<GetThemeTemplateQuery, Result<ThemeTemplateResponse>> _mockHandler;
private readonly GetThemeTemplateEndpoint _sut;
private readonly GetThemeTemplateRequestFixture _getThemeTemplateRequestFixture = new();
private readonly ThemeTemplateResponseFixture _themeTemplateResponseFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetThemeTemplateEndpointTests"/> class.
/// </summary>
public GetThemeTemplateEndpointTests()
{
_mockHandler = Substitute.For<IQueryHandler<GetThemeTemplateQuery, Result<ThemeTemplateResponse>>>();
_sut = Factory.Create<GetThemeTemplateEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithThemeTemplate()
{
// Arrange
GetThemeTemplateRequest request = _getThemeTemplateRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
ThemeTemplateResponse expectedResponse = _themeTemplateResponseFixture.Create();
_mockHandler.HandleAsync(Arg.Any<GetThemeTemplateQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(expectedResponse));
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
Ok<ThemeTemplateResponse> okResult = Assert.IsType<Ok<ThemeTemplateResponse>>(result);
Assert.Equal(expectedResponse, okResult.Value);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult()
{
// Arrange
GetThemeTemplateRequest request = _getThemeTemplateRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = DomainErrors.Themes.ThemeNotFound;
_mockHandler.HandleAsync(Arg.Any<GetThemeTemplateQuery>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status);
Assert.Equal("General.NotFound", problemDetailsBody.Title);
Assert.Equal("ThemeNotFound", problemDetailsBody.Detail);
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetailsBody.Type);
Assert.NotNull(problemDetailsBody.Extensions["traceId"]);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult()
{
// Arrange
GetThemeTemplateRequest request = _getThemeTemplateRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = DomainErrors.Themes.ThemeIdCannotBeEmpty;
_mockHandler.HandleAsync(Arg.Any<GetThemeTemplateQuery>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status);
Assert.Equal("General.Validation", validationProblemDetails.Title);
Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail);
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type);
Assert.Single(validationProblemDetails.Errors);
Assert.Equal(new[] { "ThemeIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendGetThemeTemplateQueryToHandler()
{
// Arrange
GetThemeTemplateRequest request = _getThemeTemplateRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<GetThemeTemplateQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_themeTemplateResponseFixture.Create()));
// Act
await _sut.ExecuteAsync(request, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<GetThemeTemplateQuery>(query =>
query.ThemeId == request.ThemeId &&
query.PageKey == request.PageKey),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
GetThemeTemplateRequest request = _getThemeTemplateRequestFixture.Create();
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<GetThemeTemplateQuery>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From(_themeTemplateResponseFixture.Create());
}, callInfo.Arg<CancellationToken>()));
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
}
@@ -0,0 +1,126 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.Themes.Management.Queries.GetThemes;
using Lumina.Contracts.Fixtures.Core.Responses.Themes;
using Lumina.Contracts.Responses.Themes;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Core.Endpoints.Themes.Queries.GetThemes;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Themes.Queries.GetThemes;
/// <summary>
/// Contains unit tests for the <see cref="GetThemesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetThemesEndpointTests
{
private readonly IQueryHandler<GetThemesQuery, Result<IReadOnlyList<ThemeResponse>>> _mockHandler;
private readonly GetThemesEndpoint _sut;
private readonly ThemeResponseFixture _themeResponseFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetThemesEndpointTests"/> class.
/// </summary>
public GetThemesEndpointTests()
{
_mockHandler = Substitute.For<IQueryHandler<GetThemesQuery, Result<IReadOnlyList<ThemeResponse>>>>();
_sut = Factory.Create<GetThemesEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithThemes()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
IReadOnlyList<ThemeResponse> expectedResponse = _themeResponseFixture.CreateMany();
_mockHandler.HandleAsync(Arg.Any<GetThemesQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(expectedResponse));
// Act
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken);
// Assert
Ok<IReadOnlyList<ThemeResponse>> okResult = Assert.IsType<Ok<IReadOnlyList<ThemeResponse>>>(result);
Assert.Equal(expectedResponse, okResult.Value);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = DomainErrors.Themes.ThemeNotFound;
_mockHandler.HandleAsync(Arg.Any<GetThemesQuery>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status);
Assert.Equal("General.NotFound", problemDetailsBody.Title);
Assert.Equal("ThemeNotFound", problemDetailsBody.Detail);
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetailsBody.Type);
Assert.NotNull(problemDetailsBody.Extensions["traceId"]);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendGetThemesQueryToHandler()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<GetThemesQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<ThemeResponse>>([]));
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<GetThemesQuery>(query => query != null),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<GetThemesQuery>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From<IReadOnlyList<ThemeResponse>>([]);
}, callInfo.Arg<CancellationToken>()));
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(EmptyRequest.Instance, cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
}
@@ -0,0 +1,104 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Services;
using Microsoft.Extensions.Caching.Hybrid;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Common.Services;
/// <summary>
/// Contains unit tests for the <see cref="ThemeCachePreferenceService"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ThemeCachePreferenceServiceTests
{
private readonly HybridCache _hybridCache;
private readonly ThemeCachePreferenceService _sut;
/// <summary>
/// Initializes a new instance of the <see cref="ThemeCachePreferenceService"/> class.
/// </summary>
public ThemeCachePreferenceServiceTests()
{
ServiceCollection services = new();
services.AddHybridCache();
_hybridCache = services.BuildServiceProvider().GetRequiredService<HybridCache>();
_sut = new ThemeCachePreferenceService(_hybridCache);
}
[Fact]
public async Task GetAsync_WhenNoPreferenceStored_ShouldReturnDefaultValue()
{
// Arrange
Guid userId = Guid.NewGuid();
// Act
bool result = await _sut.GetAsync(userId, defaultValue: true, CancellationToken.None);
// Assert
Assert.True(result);
}
[Fact]
public async Task GetAsync_WhenNoPreferenceStoredAndDefaultIsFalse_ShouldReturnFalse()
{
// Arrange
Guid userId = Guid.NewGuid();
// Act
bool result = await _sut.GetAsync(userId, defaultValue: false, CancellationToken.None);
// Assert
Assert.False(result);
}
[Fact]
public async Task SetAsync_WhenPreferenceStored_ShouldReturnTheStoredValue()
{
// Arrange
Guid userId = Guid.NewGuid();
// Act
await _sut.SetAsync(userId, isEnabled: true, CancellationToken.None);
bool result = await _sut.GetAsync(userId, defaultValue: false, CancellationToken.None);
// Assert
Assert.True(result);
}
[Fact]
public async Task SetAsync_WhenPreferenceOverwritten_ShouldReturnTheNewValue()
{
// Arrange
Guid userId = Guid.NewGuid();
// Act
await _sut.SetAsync(userId, isEnabled: true, CancellationToken.None);
await _sut.SetAsync(userId, isEnabled: false, CancellationToken.None);
bool result = await _sut.GetAsync(userId, defaultValue: true, CancellationToken.None);
// Assert
Assert.False(result);
}
[Fact]
public async Task SetAsync_WhenStoredForOneUser_ShouldNotAffectAnotherUser()
{
// Arrange
Guid firstUserId = Guid.NewGuid();
Guid secondUserId = Guid.NewGuid();
// Act
await _sut.SetAsync(firstUserId, isEnabled: true, CancellationToken.None);
bool firstUserResult = await _sut.GetAsync(firstUserId, defaultValue: false, CancellationToken.None);
bool secondUserResult = await _sut.GetAsync(secondUserId, defaultValue: false, CancellationToken.None);
// Assert
Assert.True(firstUserResult);
Assert.False(secondUserResult);
}
}
@@ -0,0 +1,84 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Requests.Themes;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.DeleteTheme;
using Lumina.Presentation.Web.Core.Themes;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Themes.DeleteTheme;
/// <summary>
/// Contains unit tests for the <see cref="DeleteThemeEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeleteThemeEndpointTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly DeleteThemeEndpoint _sut;
/// <summary>
/// Initializes a new instance of the <see cref="DeleteThemeEndpointTests"/> class.
/// </summary>
public DeleteThemeEndpointTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
ThemeService themeService = new(_mockApiHttpClient);
_sut = Factory.Create<DeleteThemeEndpoint>(themeService);
}
[Fact]
public async Task ExecuteAsync_WhenThemeIdProvided_ShouldDeleteThemeAndReturnSuccessJson()
{
// Arrange
string themeId = "editorial-paper";
// Act
IResult result = await _sut.ExecuteAsync(new DeleteThemeRequest(themeId), CancellationToken.None);
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
// Assert
using (System.Text.Json.JsonDocument jsonDocument = System.Text.Json.JsonDocument.Parse(body))
{
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
}
}
[Fact]
public async Task ExecuteAsync_WhenThemeIdProvided_ShouldDeleteThemeWithResolvedEndpoint()
{
// Arrange
string themeId = "editorial-paper";
string expectedEndpoint = ApiRoutes.Themes.DELETE_THEME.Replace("{themeId}", themeId);
// Act
await _sut.ExecuteAsync(new DeleteThemeRequest(themeId), CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).DeleteAsync(expectedEndpoint, Arg.Any<CancellationToken>());
}
[Theory]
[InlineData(null)] // missing theme id
[InlineData("")] // empty theme id
[InlineData(" ")] // whitespace theme id
public async Task ExecuteAsync_WhenThemeIdIsBlank_ShouldReturnProblemWithBadRequest(string? themeId)
{
// Act
IResult result = await _sut.ExecuteAsync(new DeleteThemeRequest(themeId), CancellationToken.None);
// Assert
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status400BadRequest, problemResult.StatusCode);
await _mockApiHttpClient.DidNotReceive().DeleteAsync(Arg.Any<string>(), Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,87 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.FileSystemManagement;
using Lumina.Presentation.Web.Common.Requests.Themes;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.DownloadTheme;
using Lumina.Presentation.Web.Core.Themes;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Themes.DownloadTheme;
/// <summary>
/// Contains unit tests for the <see cref="DownloadThemeEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DownloadThemeEndpointTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly DownloadThemeEndpoint _sut;
/// <summary>
/// Initializes a new instance of the <see cref="DownloadThemeEndpointTests"/> class.
/// </summary>
public DownloadThemeEndpointTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
ThemeService themeService = new(_mockApiHttpClient);
_sut = Factory.Create<DownloadThemeEndpoint>(themeService);
}
[Fact]
public async Task ExecuteAsync_WhenThemeIdProvided_ShouldReturnZipFileWithResolvedFileName()
{
// Arrange
string themeId = "editorial-paper";
_mockApiHttpClient.GetBlobAsync(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(new BlobDataDto { Data = [0x50, 0x4B, 0x03, 0x04], ContentType = "application/zip" });
// Act
IResult result = await _sut.ExecuteAsync(new GetThemeArchiveRequest(themeId), CancellationToken.None);
// Assert
FileStreamHttpResult fileResult = Assert.IsType<FileStreamHttpResult>(result);
Assert.Equal("application/zip", fileResult.ContentType);
Assert.Equal($"{themeId}.zip", fileResult.FileDownloadName);
}
[Fact]
public async Task ExecuteAsync_WhenThemeIdProvided_ShouldFetchArchiveWithResolvedEndpoint()
{
// Arrange
string themeId = "editorial-paper";
string expectedEndpoint = ApiRoutes.Themes.GET_THEME_ARCHIVE.Replace("{themeId}", themeId);
_mockApiHttpClient.GetBlobAsync(expectedEndpoint, Arg.Any<CancellationToken>())
.Returns(new BlobDataDto { Data = [1, 2, 3], ContentType = "application/zip" });
// Act
await _sut.ExecuteAsync(new GetThemeArchiveRequest(themeId), CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).GetBlobAsync(expectedEndpoint, Arg.Any<CancellationToken>());
}
[Theory]
[InlineData(null)] // missing theme id
[InlineData("")] // empty theme id
[InlineData(" ")] // whitespace theme id
public async Task ExecuteAsync_WhenThemeIdIsBlank_ShouldReturnProblemWithBadRequest(string? themeId)
{
// Act
IResult result = await _sut.ExecuteAsync(new GetThemeArchiveRequest(themeId), CancellationToken.None);
// Assert
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status400BadRequest, problemResult.StatusCode);
await _mockApiHttpClient.DidNotReceive().GetBlobAsync(Arg.Any<string>(), Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,95 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.Themes;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.GetThemes;
using Lumina.Presentation.Web.Core.Themes;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Microsoft.AspNetCore.Http;
using NSubstitute;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Themes.GetThemes;
/// <summary>
/// Contains unit tests for the <see cref="GetThemesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetThemesEndpointTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly GetThemesEndpoint _sut;
private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new();
private readonly ThemeSettingsResponseDtoFixture _themeSettingsResponseDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetThemesEndpointTests"/> class.
/// </summary>
public GetThemesEndpointTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
ThemeService themeService = new(_mockApiHttpClient);
_sut = Factory.Create<GetThemesEndpoint>(themeService);
}
[Fact]
public async Task ExecuteAsync_WhenApiReturnsThemes_ShouldReturnSuccessJsonWithThemeAdminData()
{
// Arrange
ThemeResponseDto[] themes =
[
_themeResponseDtoFixture.Create(themeId: "editorial-paper"),
_themeResponseDtoFixture.Create(themeId: "lumina-default")
];
ThemeResponseDto currentTheme = _themeResponseDtoFixture.Create(themeId: "lumina-default");
_mockApiHttpClient.GetAsync<ThemeResponseDto[]>(ApiRoutes.Themes.GET_THEMES, Arg.Any<CancellationToken>())
.Returns(themes);
_mockApiHttpClient.GetAsync<ThemeResponseDto>(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any<CancellationToken>())
.Returns(currentTheme);
_mockApiHttpClient.GetAsync<ThemeSettingsResponseDto>(ApiRoutes.Themes.GET_THEME_SETTINGS, Arg.Any<CancellationToken>())
.Returns(_themeSettingsResponseDtoFixture.Create(maxArchiveBytes: 10 * 1024 * 1024, allowThemeScripts: true));
// Act
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
// Assert
using (JsonDocument jsonDocument = JsonDocument.Parse(body))
{
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
JsonElement data = jsonDocument.RootElement.GetProperty("data");
Assert.Equal(2, data.GetProperty("themes").GetArrayLength());
Assert.Equal("editorial-paper", data.GetProperty("themes")[0].GetProperty("id").GetString());
Assert.Equal("lumina-default", data.GetProperty("currentThemeId").GetString());
Assert.True(data.GetProperty("allowThemeScripts").GetBoolean());
Assert.Equal(10 * 1024 * 1024, data.GetProperty("maxArchiveBytes").GetInt64());
Assert.Equal(10.0, data.GetProperty("maxArchiveMegabytes").GetDouble());
}
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldLoadThemesCurrentThemeAndSettings()
{
// Arrange
_mockApiHttpClient.GetAsync<ThemeResponseDto[]>(ApiRoutes.Themes.GET_THEMES, Arg.Any<CancellationToken>())
.Returns([.. _themeResponseDtoFixture.CreateMany(2)]);
_mockApiHttpClient.GetAsync<ThemeResponseDto>(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any<CancellationToken>())
.Returns(_themeResponseDtoFixture.Create());
_mockApiHttpClient.GetAsync<ThemeSettingsResponseDto>(ApiRoutes.Themes.GET_THEME_SETTINGS, Arg.Any<CancellationToken>())
.Returns(_themeSettingsResponseDtoFixture.Create());
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).GetAsync<ThemeResponseDto[]>(ApiRoutes.Themes.GET_THEMES, Arg.Any<CancellationToken>());
await _mockApiHttpClient.Received(1).GetAsync<ThemeResponseDto>(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any<CancellationToken>());
await _mockApiHttpClient.Received(1).GetAsync<ThemeSettingsResponseDto>(ApiRoutes.Themes.GET_THEME_SETTINGS, Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,103 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.Themes;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.InstallTheme;
using Lumina.Presentation.Web.Core.Themes;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.Extensions.Primitives;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Themes.InstallTheme;
/// <summary>
/// Contains unit tests for the <see cref="InstallThemeEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class InstallThemeEndpointTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly InstallThemeEndpoint _sut;
private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="InstallThemeEndpointTests"/> class.
/// </summary>
public InstallThemeEndpointTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
ThemeService themeService = new(_mockApiHttpClient);
_sut = Factory.Create<InstallThemeEndpoint>(themeService);
}
[Fact]
public async Task ExecuteAsync_WhenArchiveUploaded_ShouldInstallThemeAndReturnSuccessJson()
{
// Arrange
ThemeResponseDto installedTheme = _themeResponseDtoFixture.Create(themeId: "installed-theme");
_mockApiHttpClient.PostMultipartAsync<ThemeResponseDto>(ApiRoutes.Themes.INSTALL_THEME, Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(installedTheme);
ConfigureFormWithArchive([1, 2, 3, 4], "theme-pack.zip");
// Act
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
// Assert
using (JsonDocument jsonDocument = JsonDocument.Parse(body))
{
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
Assert.Equal("installed-theme", jsonDocument.RootElement.GetProperty("data").GetProperty("id").GetString());
}
await _mockApiHttpClient.Received(1).PostMultipartAsync<ThemeResponseDto>(
ApiRoutes.Themes.INSTALL_THEME,
Arg.Any<Stream>(),
"theme-pack.zip",
"archive",
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenNoArchiveUploaded_ShouldReturnProblemWithBadRequest()
{
// Arrange
IFormFeature formFeature = Substitute.For<IFormFeature>();
formFeature.Form.Returns(new FormCollection([]));
_sut.HttpContext.Features.Set(formFeature);
// Act
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status400BadRequest, problemResult.StatusCode);
await _mockApiHttpClient.DidNotReceive().PostMultipartAsync<ThemeResponseDto>(Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
}
private void ConfigureFormWithArchive(byte[] content, string fileName)
{
// the stream stays open for the duration of the test, since the endpoint reads it through the form file during execution
MemoryStream archiveStream = new(content);
IFormFile formFile = new FormFile(archiveStream, 0, content.Length, "archive", fileName);
FormFileCollection files = [formFile];
IFormCollection form = new FormCollection([], files);
_sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test";
// a real FormFeature is used instead of a substitute, because the endpoint execution reads the form through the
// request machinery, which would bypass a mocked feature and parse the (empty) request body
_sut.HttpContext.Features.Set<IFormFeature>(new FormFeature(form));
}
}
@@ -0,0 +1,78 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.Themes;
using Lumina.Presentation.Web.Common.Requests.Themes;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.SetCurrentTheme;
using Lumina.Presentation.Web.Core.Themes;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Themes.SetCurrentTheme;
/// <summary>
/// Contains unit tests for the <see cref="SetCurrentThemeEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetCurrentThemeEndpointTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly SetCurrentThemeEndpoint _sut;
private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="SetCurrentThemeEndpointTests"/> class.
/// </summary>
public SetCurrentThemeEndpointTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
ThemeService themeService = new(_mockApiHttpClient);
_sut = Factory.Create<SetCurrentThemeEndpoint>(themeService);
}
[Fact]
public async Task ExecuteAsync_WhenThemeIdProvided_ShouldSetCurrentThemeAndReturnSuccessJson()
{
// Arrange
string themeId = "editorial-paper";
_mockApiHttpClient.PutAsync<ThemeResponseDto, object>(Arg.Any<string>(), Arg.Any<object>(), Arg.Any<CancellationToken>())
.Returns(_themeResponseDtoFixture.Create());
// Act
IResult result = await _sut.ExecuteAsync(new SetCurrentThemeRequest(themeId), CancellationToken.None);
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
// Assert
using (System.Text.Json.JsonDocument jsonDocument = System.Text.Json.JsonDocument.Parse(body))
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
await _mockApiHttpClient.Received(1).PutAsync<ThemeResponseDto, object>(
ApiRoutes.Themes.SET_CURRENT_THEME,
Arg.Is<object>(payload => (payload.GetType().GetProperty("ThemeId")!.GetValue(payload) as string) == themeId),
Arg.Any<CancellationToken>());
}
[Theory]
[InlineData(null)] // missing theme id
[InlineData("")] // empty theme id
[InlineData(" ")] // whitespace theme id
public async Task ExecuteAsync_WhenThemeIdIsBlank_ShouldReturnProblemWithBadRequest(string? themeId)
{
// Act
IResult result = await _sut.ExecuteAsync(new SetCurrentThemeRequest(themeId), CancellationToken.None);
// Assert
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status400BadRequest, problemResult.StatusCode);
await _mockApiHttpClient.DidNotReceive().PutAsync<ThemeResponseDto, object>(Arg.Any<string>(), Arg.Any<object>(), Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,73 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.Themes;
using Lumina.Presentation.Web.Common.Http;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes;
using Lumina.Presentation.Web.Core.Themes;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Microsoft.AspNetCore.Http;
using NSubstitute;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Themes;
/// <summary>
/// Contains unit tests for the <see cref="ThemesIndexViewEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ThemesIndexViewEndpointTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly ThemesIndexViewEndpoint _sut;
private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ThemesIndexViewEndpointTests"/> class.
/// </summary>
public ThemesIndexViewEndpointTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
ThemeService themeService = new(_mockApiHttpClient);
_sut = Factory.Create<ThemesIndexViewEndpoint>(themeService);
TestHttpContextFactory.ConfigureSession(_sut.HttpContext, TestHttpContextFactory.CreateSession());
}
[Fact]
public async Task ExecuteAsync_WhenThemesAvailable_ShouldReturnRazorViewResult()
{
// Arrange
_mockApiHttpClient.GetAsync<ThemeResponseDto[]>(ApiRoutes.Themes.GET_THEMES, Arg.Any<CancellationToken>())
.Returns([.. _themeResponseDtoFixture.CreateMany(2)]);
_mockApiHttpClient.GetAsync<ThemeResponseDto>(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any<CancellationToken>())
.Returns(_themeResponseDtoFixture.Create());
// Act
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
Assert.IsType<RazorViewResult>(result);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldLoadThemesAndCurrentThemeFromService()
{
// Arrange
_mockApiHttpClient.GetAsync<ThemeResponseDto[]>(ApiRoutes.Themes.GET_THEMES, Arg.Any<CancellationToken>())
.Returns([.. _themeResponseDtoFixture.CreateMany(2)]);
_mockApiHttpClient.GetAsync<ThemeResponseDto>(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any<CancellationToken>())
.Returns(_themeResponseDtoFixture.Create());
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).GetAsync<ThemeResponseDto[]>(ApiRoutes.Themes.GET_THEMES, Arg.Any<CancellationToken>());
await _mockApiHttpClient.Received(1).GetAsync<ThemeResponseDto>(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,195 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Authorization;
using Lumina.Presentation.Web.Common.DTO.Themes;
using Lumina.Presentation.Web.Common.Enums.Authorization;
using Lumina.Presentation.Web.Common.Primitives;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Common.Services;
using Lumina.Presentation.Web.Core.Themes;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewEngines;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.Extensions.Localization;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Themes;
/// <summary>
/// Contains unit tests for the <see cref="ThemeLayoutRenderer"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ThemeLayoutRendererTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly ICompositeViewEngine _mockViewEngine;
private readonly ITempDataProvider _mockTempDataProvider;
private readonly IServiceProvider _mockServiceProvider;
private readonly IHttpContextAccessor _mockHttpContextAccessor;
private readonly IUrlService _mockUrlService;
private readonly IStringLocalizerFactory _mockStringLocalizerFactory;
private readonly IStringLocalizer _mockStringLocalizer;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly IView _mockHeadView;
private readonly IView _mockAudioPlayerView;
private readonly IView _mockScriptsView;
private readonly IView _mockNavMenuView;
private readonly ThemeLayoutRenderer _sut;
/// <summary>
/// Initializes a new instance of the <see cref="ThemeLayoutRendererTests"/> class.
/// </summary>
public ThemeLayoutRendererTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
_mockViewEngine = Substitute.For<ICompositeViewEngine>();
_mockTempDataProvider = Substitute.For<ITempDataProvider>();
_mockTempDataProvider.LoadTempData(Arg.Any<HttpContext>()).Returns(new Dictionary<string, object>());
_mockServiceProvider = Substitute.For<IServiceProvider>();
_mockServiceProvider.GetService(typeof(IModelMetadataProvider)).Returns(new EmptyModelMetadataProvider());
_mockHttpContextAccessor = Substitute.For<IHttpContextAccessor>();
_mockUrlService = Substitute.For<IUrlService>();
_mockUrlService.GetAbsoluteUrl(Arg.Any<string>(), Arg.Any<object?>()).Returns("http://localhost/en-us");
_mockStringLocalizer = CreateLocalizer();
_mockStringLocalizerFactory = Substitute.For<IStringLocalizerFactory>();
_mockStringLocalizerFactory.Create(Arg.Any<string>(), Arg.Any<string>()).Returns(_mockStringLocalizer);
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockAuthorizationService.IsInRoleAsync("Admin", Arg.Any<CancellationToken>()).Returns(false);
_mockAuthorizationService.HasPermissionAsync(Arg.Any<AuthorizationPermission>(), Arg.Any<CancellationToken>()).Returns(false);
_mockHeadView = CreateView("<head-fragment>");
_mockAudioPlayerView = CreateView("<audio-fragment>");
_mockScriptsView = CreateView("<scripts-fragment>");
_mockNavMenuView = CreateView("<nav-menu-fragment>");
_mockViewEngine.FindView(Arg.Any<ActionContext>(), "_ThemeLayoutHead", false).Returns(ViewEngineResult.Found("_ThemeLayoutHead", _mockHeadView));
_mockViewEngine.FindView(Arg.Any<ActionContext>(), "_AudioPlayer", false).Returns(ViewEngineResult.Found("_AudioPlayer", _mockAudioPlayerView));
_mockViewEngine.FindView(Arg.Any<ActionContext>(), "_ThemeLayoutScripts", false).Returns(ViewEngineResult.Found("_ThemeLayoutScripts", _mockScriptsView));
_mockViewEngine.FindView(Arg.Any<ActionContext>(), "_NavMenu", false).Returns(ViewEngineResult.Found("_NavMenu", _mockNavMenuView));
RazorViewToStringRenderer viewRenderer = new(_mockViewEngine, _mockTempDataProvider, _mockServiceProvider, _mockHttpContextAccessor);
ThemeNavBuilder navBuilder = new(_mockUrlService, _mockStringLocalizerFactory, _mockAuthorizationService, _mockHttpContextAccessor);
ThemeService themeService = new(_mockApiHttpClient);
_sut = new ThemeLayoutRenderer(themeService, new ThemeTemplateEngine(), viewRenderer, navBuilder, _mockHttpContextAccessor);
}
[Fact]
public async Task RenderAsync_WhenUserIsAuthenticated_ShouldRenderLayoutWithAllPlaceholders()
{
// Arrange
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: TestHttpContextFactory.CreateAuthenticatedUser()));
ThemeResponseDto theme = new ThemeResponseDtoFixture().Create(themeId: "editorial");
SetupRenderDocuments(theme, layoutTemplate: "{{title}}|{{assetBase}}|{{{appHead}}}|{{{nav}}}|{{{content}}}|{{{audioPlayer}}}|{{{appScripts}}}|{{{scripts}}}|{{mainStyle}}", navTemplate: "nav:{{siteName}}");
ThemeLayoutPageDto page = new("My Page", "<main>", "<page-script>");
// Act
Result<string> result = await _sut.RenderAsync(page, "editorial", CancellationToken.None);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal("My Page|/theme-assets/editorial/assets|<head-fragment>|nav:Lumina|<main>|<audio-fragment>|<scripts-fragment>|<page-script>|", result.Value);
}
[Fact]
public async Task RenderAsync_WhenUserIsAnonymous_ShouldRenderEmptyAudioPlayerAndBottomMainStyle()
{
// Arrange
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: null));
ThemeResponseDto theme = new ThemeResponseDtoFixture().Create(themeId: "editorial");
SetupRenderDocuments(theme, layoutTemplate: "{{title}}|{{assetBase}}|{{{appHead}}}|{{{nav}}}|{{{content}}}|{{{audioPlayer}}}|{{{appScripts}}}|{{{scripts}}}|{{mainStyle}}", navTemplate: "nav:{{siteName}}");
ThemeLayoutPageDto page = new("My Page", "<main>", "<page-script>");
// Act
Result<string> result = await _sut.RenderAsync(page, "editorial", CancellationToken.None);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal("My Page|/theme-assets/editorial/assets|<head-fragment>|nav:Lumina|<main>||<scripts-fragment>|<page-script>|bottom: 0px;", result.Value);
}
[Fact]
public async Task RenderAsync_WhenNavTemplateCannotBeRendered_ShouldFallBackToApplicationNavMenu()
{
// Arrange
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: null));
ThemeResponseDto theme = new ThemeResponseDtoFixture().Create(themeId: "editorial");
SetupRenderDocuments(theme, layoutTemplate: "{{title}}|{{{nav}}}", navTemplate: "{{#unclosed}}");
ThemeLayoutPageDto page = new("My Page", "<main>", string.Empty);
// Act
Result<string> result = await _sut.RenderAsync(page, "editorial", CancellationToken.None);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal("My Page|<nav-menu-fragment>", result.Value);
_mockViewEngine.Received(1).FindView(Arg.Any<ActionContext>(), "_NavMenu", false);
}
[Fact]
public async Task RenderAsync_WhenCalled_ShouldResolveLayoutAndNavDocumentsFromTheme()
{
// Arrange
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: null));
ThemeResponseDto theme = new ThemeResponseDtoFixture().Create(themeId: "editorial");
SetupRenderDocuments(theme, layoutTemplate: "{{title}}", navTemplate: "nav:{{siteName}}");
ThemeLayoutPageDto page = new("My Page", "<main>", string.Empty);
string layoutEndpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE
.Replace("{themeId}", "editorial")
.Replace("{*pageKey}", "shared/layout");
string navEndpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE
.Replace("{themeId}", "editorial")
.Replace("{*pageKey}", "shared/nav-menu");
// Act
await _sut.RenderAsync(page, "editorial", CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).GetAsync<ThemeTemplateResponseDto>(layoutEndpoint, Arg.Any<CancellationToken>());
await _mockApiHttpClient.Received(1).GetAsync<ThemeTemplateResponseDto>(navEndpoint, Arg.Any<CancellationToken>());
}
private void SetupRenderDocuments(ThemeResponseDto theme, string layoutTemplate, string navTemplate)
{
string layoutEndpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE
.Replace("{themeId}", theme.ThemeId)
.Replace("{*pageKey}", "shared/layout");
string navEndpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE
.Replace("{themeId}", theme.ThemeId)
.Replace("{*pageKey}", "shared/nav-menu");
_mockApiHttpClient.GetAsync<ThemeTemplateResponseDto>(layoutEndpoint, Arg.Any<CancellationToken>())
.Returns(new ThemeTemplateResponseDto(theme, layoutTemplate));
_mockApiHttpClient.GetAsync<ThemeTemplateResponseDto>(navEndpoint, Arg.Any<CancellationToken>())
.Returns(new ThemeTemplateResponseDto(theme, navTemplate));
}
private static IView CreateView(string markup)
{
IView view = Substitute.For<IView>();
view.RenderAsync(Arg.Any<ViewContext>())
.Returns(callInfo =>
{
callInfo.Arg<ViewContext>().Writer.Write(markup);
return Task.CompletedTask;
});
return view;
}
private static IStringLocalizer CreateLocalizer()
{
IStringLocalizer localizer = Substitute.For<IStringLocalizer>();
localizer[Arg.Any<string>()].Returns(callInfo => new LocalizedString(callInfo.Arg<string>(), $"Localized-{callInfo.Arg<string>()}"));
return localizer;
}
}
@@ -0,0 +1,251 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Authorization;
using Lumina.Presentation.Web.Common.DTO.Themes;
using Lumina.Presentation.Web.Common.Enums.Authorization;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Common.Services;
using Lumina.Presentation.Web.Core.Themes;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Localization;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Themes;
/// <summary>
/// Contains unit tests for the <see cref="ThemeNavBuilder"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ThemeNavBuilderTests
{
private readonly IUrlService _mockUrlService;
private readonly IStringLocalizerFactory _mockStringLocalizerFactory;
private readonly IStringLocalizer _mockStringLocalizer;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly IHttpContextAccessor _mockHttpContextAccessor;
private readonly ThemeNavBuilder _sut;
/// <summary>
/// Initializes a new instance of the <see cref="ThemeNavBuilderTests"/> class.
/// </summary>
public ThemeNavBuilderTests()
{
_mockUrlService = Substitute.For<IUrlService>();
_mockStringLocalizer = Substitute.For<IStringLocalizer>();
_mockStringLocalizer[Arg.Any<string>()].Returns(callInfo => new LocalizedString(callInfo.Arg<string>(), $"Localized-{callInfo.Arg<string>()}"));
_mockStringLocalizerFactory = Substitute.For<IStringLocalizerFactory>();
_mockStringLocalizerFactory.Create(Arg.Any<string>(), Arg.Any<string>()).Returns(_mockStringLocalizer);
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockHttpContextAccessor = Substitute.For<IHttpContextAccessor>();
_sut = new ThemeNavBuilder(_mockUrlService, _mockStringLocalizerFactory, _mockAuthorizationService, _mockHttpContextAccessor);
StubSiteUrls();
_mockAuthorizationService.IsInRoleAsync("Admin", Arg.Any<CancellationToken>()).Returns(false);
_mockAuthorizationService.HasPermissionAsync(Arg.Any<AuthorizationPermission>(), Arg.Any<CancellationToken>()).Returns(false);
}
[Fact]
public async Task BuildAsync_WhenUserIsAnonymous_ShouldNotIncludeAdministratorLibraryOrToolsSections()
{
// Arrange
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: null));
// Act
ThemeNavMenuDto result = await _sut.BuildAsync(CancellationToken.None);
// Assert
Assert.Null(FindSection(result, "Localized-Administrator"));
Assert.Null(FindSection(result, "Localized-Library"));
Assert.Null(FindSection(result, "Localized-Tools"));
Assert.NotNull(FindSection(result, "Localized-Language"));
Assert.NotNull(FindSection(result, "Localized-Help"));
}
[Fact]
public async Task BuildAsync_WhenUserIsAnonymous_ShouldIncludeLoginEntryInsteadOfLogoutEntry()
{
// Arrange
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: null));
// Act
ThemeNavMenuDto result = await _sut.BuildAsync(CancellationToken.None);
// Assert
ThemeNavSectionDto accountSection = FindSection(result, "Localized-Account")!;
Assert.Contains(accountSection.Items, entry => entry.Label == "Localized-Login");
Assert.DoesNotContain(accountSection.Items, entry => entry.Label == "Localized-Logout");
Assert.Equal("http://localhost/en-us/auth/login", accountSection.Items.First(entry => entry.Label == "Localized-Login").Url);
}
[Fact]
public async Task BuildAsync_WhenUserIsAuthenticated_ShouldIncludeAccountLinksAndLibrarySection()
{
// Arrange
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: TestHttpContextFactory.CreateAuthenticatedUser()));
// Act
ThemeNavMenuDto result = await _sut.BuildAsync(CancellationToken.None);
// Assert
ThemeNavSectionDto accountSection = FindSection(result, "Localized-Account")!;
Assert.Contains(accountSection.Items, entry => entry.Label == "Localized-Logout");
Assert.Contains(accountSection.Items, entry => entry.Label == "Localized-Register");
Assert.Contains(accountSection.Items, entry => entry.Label == "Localized-ChangePassword");
Assert.Contains(accountSection.Items, entry => entry.Label == "Localized-Profile");
Assert.DoesNotContain(accountSection.Items, entry => entry.Label == "Localized-Login");
ThemeNavSectionDto librarySection = FindSection(result, "Localized-Library")!;
Assert.Contains(librarySection.Items, entry => entry.Label == "Localized-ManageLibraries");
Assert.DoesNotContain(librarySection.Items, entry => entry.Label == "Localized-AddNewLibrary");
}
[Fact]
public async Task BuildAsync_WhenUserIsAdmin_ShouldIncludeAdministratorSection()
{
// Arrange
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: TestHttpContextFactory.CreateAuthenticatedUser()));
_mockAuthorizationService.IsInRoleAsync("Admin", Arg.Any<CancellationToken>()).Returns(true);
// Act
ThemeNavMenuDto result = await _sut.BuildAsync(CancellationToken.None);
// Assert
ThemeNavSectionDto administratorSection = FindSection(result, "Localized-Administrator")!;
Assert.Contains(administratorSection.Items, entry => entry.Label == "Localized-ManageRoles" && entry.Url == "http://localhost/en-us/admin/manage-roles");
Assert.Contains(administratorSection.Items, entry => entry.Label == "Localized-ManagePermissions" && entry.Url == "http://localhost/en-us/admin/manage-permissions");
Assert.Contains(administratorSection.Items, entry => entry.Label == "Localized-Plugins" && entry.Url == "http://localhost/en-us/admin/manage-plugins");
Assert.Contains(administratorSection.Items, entry => entry.Label == "Localized-Themes" && entry.Url == "http://localhost/en-us/admin/manage-themes");
await _mockAuthorizationService.Received(1).IsInRoleAsync("Admin", Arg.Any<CancellationToken>());
}
[Fact]
public async Task BuildAsync_WhenUserCanCreateLibraries_ShouldIncludeAddNewLibraryEntry()
{
// Arrange
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: TestHttpContextFactory.CreateAuthenticatedUser()));
_mockAuthorizationService.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, Arg.Any<CancellationToken>()).Returns(true);
// Act
ThemeNavMenuDto result = await _sut.BuildAsync(CancellationToken.None);
// Assert
ThemeNavSectionDto librarySection = FindSection(result, "Localized-Library")!;
Assert.Contains(librarySection.Items, entry => entry.Label == "Localized-AddNewLibrary" && entry.Url == "http://localhost/en-us/libraries/manage/item");
await _mockAuthorizationService.Received(1).HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, Arg.Any<CancellationToken>());
}
[Fact]
public async Task BuildAsync_WhenUserCannotCreateLibraries_ShouldNotIncludeAddNewLibraryEntry()
{
// Arrange
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: TestHttpContextFactory.CreateAuthenticatedUser()));
// Act
ThemeNavMenuDto result = await _sut.BuildAsync(CancellationToken.None);
// Assert
ThemeNavSectionDto librarySection = FindSection(result, "Localized-Library")!;
Assert.DoesNotContain(librarySection.Items, entry => entry.Label == "Localized-AddNewLibrary");
}
[Fact]
public async Task BuildAsync_WhenRequestHasPathAndQuery_ShouldKeepEscapedReturnUrlInLanguageEntries()
{
// Arrange
DefaultHttpContext httpContext = TestHttpContextFactory.Create(user: null);
httpContext.Request.Path = "/en-us";
httpContext.Request.QueryString = new QueryString("?page=1");
_mockHttpContextAccessor.HttpContext.Returns(httpContext);
// Act
ThemeNavMenuDto result = await _sut.BuildAsync(CancellationToken.None);
// Assert
ThemeNavSectionDto languageSection = FindSection(result, "Localized-Language")!;
Assert.Equal(9, languageSection.Items.Count);
Assert.All(languageSection.Items, entry =>
{
Assert.Equal("lang-set", entry.CssClass);
Assert.Contains("returnUrl=%2Fen-us%3Fpage%3D1", entry.Url);
});
Assert.Contains(languageSection.Items, entry => entry.Label == "English" && entry.Url!.StartsWith("http://localhost/en-us/tools/language/set-language?newCulture=en-us", StringComparison.Ordinal));
}
[Fact]
public async Task BuildAsync_WhenAuthenticated_ShouldIncludeSettingsEntryInDesktopToolsSection()
{
// Arrange
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: TestHttpContextFactory.CreateAuthenticatedUser()));
// Act
ThemeNavMenuDto result = await _sut.BuildAsync(CancellationToken.None);
// Assert
ThemeNavSectionDto toolsSection = FindSection(result, "Localized-Tools", isMobile: false)!;
Assert.Contains(toolsSection.Items, entry => entry.Label == "Localized-Settings" && entry.Url == "http://localhost/en-us/tools/settings");
// the desktop tools section hosts the language submenu while the mobile menu has a dedicated language section
Assert.Contains(toolsSection.Items, entry => entry.Label == "Localized-Language" && entry.Children.Count == 9);
}
[Fact]
public async Task BuildAsync_WhenCalled_ShouldCreateLocalizerForTheNavigationResources()
{
// Arrange
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: null));
// Act
await _sut.BuildAsync(CancellationToken.None);
// Assert
_mockStringLocalizerFactory.Received(1).Create("Lumina.Presentation.Web.Views.Shared._NavMenu", "Lumina.Presentation.Web");
}
[Fact]
public async Task BuildAsync_WhenAdminCreatesLibraries_ShouldAddAddNewLibraryEntryOnce()
{
// Arrange
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: TestHttpContextFactory.CreateAuthenticatedUser()));
_mockAuthorizationService.IsInRoleAsync("Admin", Arg.Any<CancellationToken>()).Returns(true);
_mockAuthorizationService.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, Arg.Any<CancellationToken>()).Returns(true);
// Act
ThemeNavMenuDto result = await _sut.BuildAsync(CancellationToken.None);
// Assert
ThemeNavSectionDto librarySection = FindSection(result, "Localized-Library")!;
Assert.Single(librarySection.Items, entry => entry.Label == "Localized-AddNewLibrary");
}
private void StubSiteUrls()
{
_mockUrlService.GetAbsoluteUrl(WebRoutes.Home.INDEX_CULTURED).Returns("http://localhost/en-us");
_mockUrlService.GetAbsoluteUrl(WebRoutes.Authentication.LOGIN_VIEW).Returns("http://localhost/en-us/auth/login");
_mockUrlService.GetAbsoluteUrl(WebRoutes.Authentication.RECOVER_PASSWORD_VIEW).Returns("http://localhost/en-us/auth/recover-password");
_mockUrlService.GetAbsoluteUrl(WebRoutes.Authentication.LOGOUT).Returns("http://localhost/en-us/auth/logout");
_mockUrlService.GetAbsoluteUrl(WebRoutes.Authentication.REGISTER_VIEW).Returns("http://localhost/en-us/auth/register");
_mockUrlService.GetAbsoluteUrl(WebRoutes.Authentication.CHANGE_PASSWORD_VIEW).Returns("http://localhost/en-us/auth/change-password");
_mockUrlService.GetAbsoluteUrl(WebRoutes.Authentication.PROFILE_VIEW).Returns("http://localhost/en-us/auth/profile");
_mockUrlService.GetAbsoluteUrl(WebRoutes.Admin.MANAGE_ROLES).Returns("http://localhost/en-us/admin/manage-roles");
_mockUrlService.GetAbsoluteUrl(WebRoutes.Admin.MANAGE_PERMISSIONS).Returns("http://localhost/en-us/admin/manage-permissions");
_mockUrlService.GetAbsoluteUrl(WebRoutes.Plugins.INDEX).Returns("http://localhost/en-us/admin/manage-plugins");
_mockUrlService.GetAbsoluteUrl(WebRoutes.Admin.MANAGE_THEMES).Returns("http://localhost/en-us/admin/manage-themes");
_mockUrlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.INDEX).Returns("http://localhost/en-us/libraries/manage");
_mockUrlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.ADD_LIBRARY).Returns("http://localhost/en-us/libraries/manage/item");
_mockUrlService.GetAbsoluteUrl(WebRoutes.Settings.INDEX).Returns("http://localhost/en-us/tools/settings");
_mockUrlService.GetAbsoluteUrl(WebRoutes.Language.SET_LANGUAGE).Returns("http://localhost/en-us/tools/language/set-language");
}
private static ThemeNavSectionDto? FindSection(ThemeNavMenuDto menu, string label, bool isMobile = true)
{
IReadOnlyList<ThemeNavSectionDto> sections = isMobile ? menu.MobileSections : menu.MenubarSections;
return sections.FirstOrDefault(section => section.Label == label);
}
}
@@ -0,0 +1,61 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Core.Themes;
using Microsoft.Extensions.Localization;
using NSubstitute;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Themes;
/// <summary>
/// Contains unit tests for the <see cref="ThemePageDataFactory"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ThemePageDataFactoryTests
{
private readonly IStringLocalizer _mockStringLocalizer;
/// <summary>
/// Initializes a new instance of the <see cref="ThemePageDataFactoryTests"/> class.
/// </summary>
public ThemePageDataFactoryTests()
{
_mockStringLocalizer = Substitute.For<IStringLocalizer>();
}
[Fact]
public void CreateLocalizedStrings_WhenLocalizerProvidesStrings_ShouldReturnDictionaryKeyedByName()
{
// Arrange
LocalizedString[] localizedStrings =
[
new("Title", "The Title"),
new("Search", "Search")
];
_mockStringLocalizer.GetAllStrings(Arg.Any<bool>()).Returns(localizedStrings);
// Act
Dictionary<string, object?> result = ThemePageDataFactory.CreateLocalizedStrings(_mockStringLocalizer);
// Assert
Assert.Equal(2, result.Count);
Assert.Equal("The Title", result["Title"]);
Assert.Equal("Search", result["Search"]);
_mockStringLocalizer.Received(1).GetAllStrings(includeParentCultures: true);
}
[Fact]
public void CreateLocalizedStrings_WhenLocalizerProvidesNoStrings_ShouldReturnEmptyDictionary()
{
// Arrange
_mockStringLocalizer.GetAllStrings(Arg.Any<bool>()).Returns([]);
// Act
Dictionary<string, object?> result = ThemePageDataFactory.CreateLocalizedStrings(_mockStringLocalizer);
// Assert
Assert.Empty(result);
}
}
@@ -0,0 +1,110 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.Themes;
using Lumina.Presentation.Web.Common.Primitives;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Themes;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Themes;
/// <summary>
/// Contains unit tests for the <see cref="ThemePageRenderer"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ThemePageRendererTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly ThemePageRenderer _sut;
private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new();
private readonly ThemePageDtoFixture _themePageDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ThemePageRendererTests"/> class.
/// </summary>
public ThemePageRendererTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
ThemeService themeService = new(_mockApiHttpClient);
_sut = new ThemePageRenderer(themeService, new ThemeTemplateEngine());
}
[Fact]
public async Task RenderAsync_WhenThemeIdProvided_ShouldRenderPageAndPopulateThemeMetadata()
{
// Arrange
ThemeResponseDto theme = _themeResponseDtoFixture.Create(themeId: "editorial-paper");
string pageKey = "home/index";
string template = "<h1>{{title}}</h1>{{#scripts}}<script>init();</script>{{/scripts}}";
string expectedEndpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE
.Replace("{themeId}", "editorial-paper")
.Replace("{*pageKey}", pageKey);
_mockApiHttpClient.GetAsync<ThemeTemplateResponseDto>(expectedEndpoint, Arg.Any<CancellationToken>())
.Returns(new ThemeTemplateResponseDto(theme, template));
ThemePageDto model = _themePageDtoFixture.Create(pageKey: pageKey, title: "Home");
// Act
Result<ThemePageRenderResultDto> result = await _sut.RenderAsync(model, "editorial-paper", CancellationToken.None);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal("<h1>Home</h1>", result.Value.Content);
Assert.Equal("<script>init();</script>", result.Value.Script);
Assert.Equal("editorial-paper", model.ThemeId);
Assert.Equal("/theme-assets/editorial-paper/assets", model.AssetBase);
Assert.StartsWith("script_", model.ScriptId);
await _mockApiHttpClient.DidNotReceive().GetAsync<ThemeResponseDto>(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any<CancellationToken>());
}
[Fact]
public async Task RenderAsync_WhenThemeIdMissing_ShouldResolveCurrentThemeBeforeRendering()
{
// Arrange
ThemeResponseDto currentTheme = _themeResponseDtoFixture.Create(themeId: "lumina-default");
string pageKey = "home/index";
string expectedEndpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE
.Replace("{themeId}", "lumina-default")
.Replace("{*pageKey}", pageKey);
_mockApiHttpClient.GetAsync<ThemeResponseDto>(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any<CancellationToken>())
.Returns(currentTheme);
_mockApiHttpClient.GetAsync<ThemeTemplateResponseDto>(expectedEndpoint, Arg.Any<CancellationToken>())
.Returns(new ThemeTemplateResponseDto(currentTheme, "{{title}}"));
ThemePageDto model = _themePageDtoFixture.Create(pageKey: pageKey, title: "Home");
// Act
Result<ThemePageRenderResultDto> result = await _sut.RenderAsync(model, null, CancellationToken.None);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal("lumina-default", model.ThemeId);
Assert.Equal("Home", result.Value.Content);
await _mockApiHttpClient.Received(1).GetAsync<ThemeResponseDto>(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any<CancellationToken>());
}
[Fact]
public async Task RenderAsync_WhenTemplateRenderingFails_ShouldReturnFailure()
{
// Arrange
ThemeResponseDto theme = _themeResponseDtoFixture.Create(themeId: "editorial-paper");
string pageKey = "home/index";
string expectedEndpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE
.Replace("{themeId}", "editorial-paper")
.Replace("{*pageKey}", pageKey);
_mockApiHttpClient.GetAsync<ThemeTemplateResponseDto>(expectedEndpoint, Arg.Any<CancellationToken>())
.Returns(new ThemeTemplateResponseDto(theme, "{{#unclosed}}"));
ThemePageDto model = _themePageDtoFixture.Create(pageKey: pageKey, title: "Home");
// Act
Result<ThemePageRenderResultDto> result = await _sut.RenderAsync(model, "editorial-paper", CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal("Theme.Template.Invalid", result.FirstError.Code);
}
}
@@ -0,0 +1,245 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.FileSystemManagement;
using Lumina.Presentation.Web.Common.DTO.Themes;
using Lumina.Presentation.Web.Common.Enums.Themes;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Themes;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Themes;
/// <summary>
/// Contains unit tests for the <see cref="ThemeService"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ThemeServiceTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly ThemeService _sut;
private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new();
private readonly ThemeSettingsResponseDtoFixture _themeSettingsResponseDtoFixture = new();
private readonly ThemeTemplateResponseDtoFixture _themeTemplateResponseDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ThemeServiceTests"/> class.
/// </summary>
public ThemeServiceTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
_sut = new ThemeService(_mockApiHttpClient);
}
[Fact]
public async Task GetThemesAsync_WhenApiReturnsThemes_ShouldReturnMappedThemeInfoList()
{
// Arrange
ThemeResponseDto[] themes =
[
_themeResponseDtoFixture.Create(themeId: "editorial-paper", name: "Editorial Paper", previewPath: "preview.png", includePreviewPath: true, installSource: ThemeInstallSource.Bundled),
_themeResponseDtoFixture.Create(themeId: "lumina-default", name: "Lumina Default", previewPath: "preview.png", includePreviewPath: true, installSource: ThemeInstallSource.Uploaded)
];
_mockApiHttpClient.GetAsync<ThemeResponseDto[]>(ApiRoutes.Themes.GET_THEMES, Arg.Any<CancellationToken>())
.Returns(themes);
// Act
IReadOnlyList<ThemeInfoDto> result = await _sut.GetThemesAsync(CancellationToken.None);
// Assert
Assert.Equal(2, result.Count);
Assert.Equal("editorial-paper", result[0].Id);
Assert.Equal("Editorial Paper", result[0].Name);
Assert.Equal(themes[0].Description, result[0].Description);
Assert.Equal(themes[0].Author, result[0].Author);
Assert.Equal(themes[0].Version, result[0].Version);
Assert.Equal("/theme-assets/editorial-paper/preview.png", result[0].PreviewUrl);
Assert.True(result[0].IsBundled);
Assert.False(result[1].IsBundled);
await _mockApiHttpClient.Received(1).GetAsync<ThemeResponseDto[]>(ApiRoutes.Themes.GET_THEMES, Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetThemesAsync_WhenThemeHasNoPreviewPath_ShouldReturnPlaceholderPreviewUrl()
{
// Arrange
ThemeResponseDto theme = _themeResponseDtoFixture.Create(themeId: "editorial-paper", previewPath: null);
_mockApiHttpClient.GetAsync<ThemeResponseDto[]>(ApiRoutes.Themes.GET_THEMES, Arg.Any<CancellationToken>())
.Returns([theme]);
// Act
IReadOnlyList<ThemeInfoDto> result = await _sut.GetThemesAsync(CancellationToken.None);
// Assert
Assert.Equal("/admin/theme-placeholder.svg", result[0].PreviewUrl);
}
[Fact]
public async Task GetCurrentThemeAsync_WhenApiReturnsCurrentTheme_ShouldReturnMappedThemeInfo()
{
// Arrange
ThemeResponseDto theme = _themeResponseDtoFixture.Create(themeId: "editorial-paper", previewPath: "preview.png", includePreviewPath: true);
_mockApiHttpClient.GetAsync<ThemeResponseDto>(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any<CancellationToken>())
.Returns(theme);
// Act
ThemeInfoDto result = await _sut.GetCurrentThemeAsync(CancellationToken.None);
// Assert
Assert.Equal("editorial-paper", result.Id);
Assert.Equal(theme.Name, result.Name);
Assert.Equal("/theme-assets/editorial-paper/preview.png", result.PreviewUrl);
await _mockApiHttpClient.Received(1).GetAsync<ThemeResponseDto>(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetThemeSettingsAsync_WhenApiReturnsSettings_ShouldReturnSettings()
{
// Arrange
ThemeSettingsResponseDto settings = _themeSettingsResponseDtoFixture.Create(maxArchiveBytes: 10 * 1024 * 1024, allowThemeScripts: true);
_mockApiHttpClient.GetAsync<ThemeSettingsResponseDto>(ApiRoutes.Themes.GET_THEME_SETTINGS, Arg.Any<CancellationToken>())
.Returns(settings);
// Act
ThemeSettingsResponseDto result = await _sut.GetThemeSettingsAsync(CancellationToken.None);
// Assert
Assert.Equal(settings, result);
await _mockApiHttpClient.Received(1).GetAsync<ThemeSettingsResponseDto>(ApiRoutes.Themes.GET_THEME_SETTINGS, Arg.Any<CancellationToken>());
}
[Fact]
public async Task SetCurrentThemeAsync_WhenCalled_ShouldSendThemeIdToApi()
{
// Arrange
string themeId = "editorial-paper";
_mockApiHttpClient.PutAsync<ThemeResponseDto, object>(Arg.Any<string>(), Arg.Any<object>(), Arg.Any<CancellationToken>())
.Returns(_themeResponseDtoFixture.Create());
// Act
await _sut.SetCurrentThemeAsync(themeId, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).PutAsync<ThemeResponseDto, object>(
ApiRoutes.Themes.SET_CURRENT_THEME,
Arg.Is<object>(payload => payload.GetType().GetProperty("ThemeId")!.GetValue(payload)!.ToString()! == themeId),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task InstallAsync_WhenCalled_ShouldUploadArchiveToInstallEndpoint()
{
// Arrange
ThemeResponseDto installedTheme = _themeResponseDtoFixture.Create(themeId: "installed-theme");
using (MemoryStream archiveStream = new([1, 2, 3, 4]))
{
string fileName = "theme-pack.zip";
_mockApiHttpClient.PostMultipartAsync<ThemeResponseDto>(Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(installedTheme);
// Act
ThemeInfoDto result = await _sut.InstallAsync(archiveStream, fileName, CancellationToken.None);
// Assert
Assert.Equal("installed-theme", result.Id);
await _mockApiHttpClient.Received(1).PostMultipartAsync<ThemeResponseDto>(
ApiRoutes.Themes.INSTALL_THEME,
archiveStream,
fileName,
"archive",
Arg.Any<CancellationToken>());
}
}
[Fact]
public async Task DeleteThemeAsync_WhenCalled_ShouldDeleteThemeWithResolvedEndpoint()
{
// Arrange
string themeId = "editorial-paper";
string expectedEndpoint = ApiRoutes.Themes.DELETE_THEME.Replace("{themeId}", themeId);
// Act
await _sut.DeleteThemeAsync(themeId, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).DeleteAsync(expectedEndpoint, Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetRenderDocumentAsync_WhenThemeIdProvided_ShouldFetchTemplateWithResolvedRoute()
{
// Arrange
string themeId = "editorial-paper";
string pageKey = "shared/layout";
ThemeTemplateResponseDto templateResponse = _themeTemplateResponseDtoFixture.Create(theme: _themeResponseDtoFixture.Create(themeId: themeId), template: "Hello {{title}}");
string expectedEndpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE
.Replace("{themeId}", themeId)
.Replace("{*pageKey}", pageKey);
_mockApiHttpClient.GetAsync<ThemeTemplateResponseDto>(expectedEndpoint, Arg.Any<CancellationToken>())
.Returns(templateResponse);
// Act
ThemeRenderDocumentDto result = await _sut.GetRenderDocumentAsync(pageKey, themeId, CancellationToken.None);
// Assert
Assert.Equal(themeId, result.Theme.Id);
Assert.Equal("Hello {{title}}", result.Template);
await _mockApiHttpClient.DidNotReceive().GetAsync<ThemeResponseDto>(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any<CancellationToken>());
await _mockApiHttpClient.Received(1).GetAsync<ThemeTemplateResponseDto>(expectedEndpoint, Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetRenderDocumentAsync_WhenThemeIdMissing_ShouldResolveCurrentThemeFirst()
{
// Arrange
string pageKey = "home/index";
ThemeResponseDto currentTheme = _themeResponseDtoFixture.Create(themeId: "lumina-default");
ThemeTemplateResponseDto templateResponse = _themeTemplateResponseDtoFixture.Create(theme: _themeResponseDtoFixture.Create(themeId: "lumina-default"), template: "Home");
string expectedEndpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE
.Replace("{themeId}", "lumina-default")
.Replace("{*pageKey}", pageKey);
_mockApiHttpClient.GetAsync<ThemeResponseDto>(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any<CancellationToken>())
.Returns(currentTheme);
_mockApiHttpClient.GetAsync<ThemeTemplateResponseDto>(expectedEndpoint, Arg.Any<CancellationToken>())
.Returns(templateResponse);
// Act
ThemeRenderDocumentDto result = await _sut.GetRenderDocumentAsync(pageKey, null, CancellationToken.None);
// Assert
Assert.Equal("lumina-default", result.Theme.Id);
await _mockApiHttpClient.Received(1).GetAsync<ThemeResponseDto>(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any<CancellationToken>());
await _mockApiHttpClient.Received(1).GetAsync<ThemeTemplateResponseDto>(expectedEndpoint, Arg.Any<CancellationToken>());
}
[Fact]
public async Task BuildArchiveAsync_WhenApiReturnsBlob_ShouldReturnZipArchiveWithResolvedFileName()
{
// Arrange
string themeId = "editorial-paper";
byte[] data = [0x50, 0x4B, 0x03, 0x04];
_mockApiHttpClient.GetBlobAsync(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(new BlobDataDto { Data = data, ContentType = "application/zip" });
string expectedEndpoint = ApiRoutes.Themes.GET_THEME_ARCHIVE.Replace("{themeId}", themeId);
// Act
ThemeArchiveDto result = await _sut.BuildArchiveAsync(themeId, CancellationToken.None);
// Assert
Assert.Equal($"{themeId}.zip", result.FileName);
using (MemoryStream content = new())
{
await result.Content.CopyToAsync(content);
Assert.Equal(data, content.ToArray());
}
await _mockApiHttpClient.Received(1).GetBlobAsync(expectedEndpoint, Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,478 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.DTO.Themes;
using Lumina.Presentation.Web.Common.Primitives;
using Lumina.Presentation.Web.Core.Themes;
using Lumina.Presentation.Web.Fixtures.Common.Models;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Themes;
/// <summary>
/// Contains unit tests for the <see cref="ThemeTemplateEngine"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ThemeTemplateEngineTests
{
private readonly ThemeTemplateEngine _sut;
private readonly SectionModelFixture _sectionModelFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ThemeTemplateEngineTests"/> class.
/// </summary>
public ThemeTemplateEngineTests()
{
_sut = new ThemeTemplateEngine();
}
[Fact]
public void RenderPage_WhenVariableValueContainsHtml_ShouldEscapeOutput()
{
// Arrange
Dictionary<string, object?> model = new() { ["value"] = "<b>&\"quote\"" };
string template = "{{value}}";
// Act
Result<ThemePageRenderResultDto> result = _sut.RenderPage(template, model);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal("&lt;b&gt;&amp;&quot;quote&quot;", result.Value.Content);
Assert.Equal(string.Empty, result.Value.Script);
}
[Fact]
public void RenderPage_WhenRawVariableTagUsed_ShouldNotEscapeOutput()
{
// Arrange
Dictionary<string, object?> model = new() { ["value"] = "<b>raw</b>" };
// Act
Result<ThemePageRenderResultDto> ampersandResult = _sut.RenderPage("{{&value}}", model);
Result<ThemePageRenderResultDto> tripleResult = _sut.RenderPage("{{{value}}}", model);
// Assert
Assert.True(ampersandResult.IsSuccess);
Assert.Equal("<b>raw</b>", ampersandResult.Value.Content);
Assert.True(tripleResult.IsSuccess);
Assert.Equal("<b>raw</b>", tripleResult.Value.Content);
}
[Fact]
public void RenderPage_WhenVariableMissing_ShouldRenderEmptyString()
{
// Arrange
Dictionary<string, object?> model = new() { ["title"] = "Present" };
// Act
Result<ThemePageRenderResultDto> result = _sut.RenderPage("{{title}}|{{missing}}", model);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal("Present|", result.Value.Content);
}
[Fact]
public void RenderPage_WhenVariableIsBoolean_ShouldRenderLowercaseLiteral()
{
// Arrange
Dictionary<string, object?> model = new() { ["enabled"] = true, ["disabled"] = false };
// Act
Result<ThemePageRenderResultDto> result = _sut.RenderPage("{{enabled}}/{{disabled}}", model);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal("true/false", result.Value.Content);
}
[Fact]
public void RenderPage_WhenDottedExpressionUsed_ShouldResolveNestedProperty()
{
// Arrange
Dictionary<string, object?> model = new()
{
["user"] = new Dictionary<string, object?> { ["name"] = "Ada" }
};
// Act
Result<ThemePageRenderResultDto> result = _sut.RenderPage("Hello {{user.name}}", model);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal("Hello Ada", result.Value.Content);
}
[Fact]
public void RenderPage_WhenCollectionCountRequested_ShouldRenderCollectionCount()
{
// Arrange
Dictionary<string, object?> model = new() { ["items"] = new List<object> { "a", "b", "c" } };
// Act
Result<ThemePageRenderResultDto> result = _sut.RenderPage("{{items.Count}}", model);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal("3", result.Value.Content);
}
[Fact]
public void RenderPage_WhenSectionIsTruthy_ShouldRenderChildren()
{
// Arrange
Dictionary<string, object?> model = new() { ["section"] = true, ["text"] = "inside" };
// Act
Result<ThemePageRenderResultDto> result = _sut.RenderPage("{{#section}}{{text}}{{/section}}", model);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal("inside", result.Value.Content);
}
[Fact]
public void RenderPage_WhenSectionIsObject_ShouldRenderChildrenWithObjectScope()
{
// Arrange
Dictionary<string, object?> model = new()
{
["section"] = _sectionModelFixture.Create(text: "scoped")
};
// Act
Result<ThemePageRenderResultDto> result = _sut.RenderPage("{{#section}}{{text}}{{/section}}", model);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal("scoped", result.Value.Content);
}
[Theory]
[InlineData(null)] // unresolved section
[InlineData(false)] // boolean false
[InlineData("")] // empty string
public void RenderPage_WhenSectionIsFalsy_ShouldSkipChildren(object? sectionValue)
{
// Arrange
Dictionary<string, object?> model = new() { ["section"] = sectionValue, ["text"] = "hidden" };
// Act
Result<ThemePageRenderResultDto> result = _sut.RenderPage("before{{#section}}{{text}}{{/section}}after", model);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal("beforeafter", result.Value.Content);
}
[Fact]
public void RenderPage_WhenSectionIsEmptyCollection_ShouldSkipChildren()
{
// Arrange
Dictionary<string, object?> model = new() { ["section"] = new List<object>() };
// Act
Result<ThemePageRenderResultDto> result = _sut.RenderPage("a{{#section}}x{{/section}}b", model);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal("ab", result.Value.Content);
}
[Fact]
public void RenderPage_WhenSectionIsCollection_ShouldRenderChildrenPerItem()
{
// Arrange
Dictionary<string, object?> model = new()
{
["items"] = new List<object>
{
new Dictionary<string, object?> { ["name"] = "A" },
new Dictionary<string, object?> { ["name"] = "B" }
}
};
// Act
Result<ThemePageRenderResultDto> result = _sut.RenderPage("{{#items}}[{{name}}]{{/items}}", model);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal("[A][B]", result.Value.Content);
}
[Fact]
public void RenderPage_WhenSectionIteratesScalarItems_ShouldRenderCurrentScopeValue()
{
// Arrange
Dictionary<string, object?> model = new() { ["items"] = new List<object> { "one", "two" } };
// Act
Result<ThemePageRenderResultDto> result = _sut.RenderPage("{{#items}}{{.}};{{/items}}", model);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal("one;two;", result.Value.Content);
}
[Fact]
public void RenderPage_WhenParentTraversalUsed_ShouldResolveFromParentScope()
{
// Arrange
Dictionary<string, object?> model = new()
{
["title"] = "Parent",
["items"] = new List<object>
{
new Dictionary<string, object?> { ["name"] = "A" },
new Dictionary<string, object?> { ["name"] = "B" }
}
};
// Act
Result<ThemePageRenderResultDto> result = _sut.RenderPage("{{#items}}{{../title}}/{{name}};{{/items}}", model);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal("Parent/A;Parent/B;", result.Value.Content);
}
[Fact]
public void RenderPage_WhenInvertedSectionIsFalsy_ShouldRenderChildren()
{
// Arrange
Dictionary<string, object?> model = new() { ["section"] = null };
// Act
Result<ThemePageRenderResultDto> result = _sut.RenderPage("{{^section}}fallback{{/section}}", model);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal("fallback", result.Value.Content);
}
[Fact]
public void RenderPage_WhenInvertedSectionIsTruthy_ShouldSkipChildren()
{
// Arrange
Dictionary<string, object?> model = new() { ["section"] = "present" };
// Act
Result<ThemePageRenderResultDto> result = _sut.RenderPage("a{{^section}}fallback{{/section}}b", model);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal("ab", result.Value.Content);
}
[Fact]
public void RenderPage_WhenTopLevelScriptsSectionPresent_ShouldSeparateScriptFromContent()
{
// Arrange
Dictionary<string, object?> model = new() { ["title"] = "Page", ["script"] = "console.log('x');" };
// Act
Result<ThemePageRenderResultDto> result = _sut.RenderPage(
"<h1>{{title}}</h1>{{#scripts}}<script>{{{script}}}</script>{{/scripts}}",
model);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal("<h1>Page</h1>", result.Value.Content);
Assert.Equal("<script>console.log('x');</script>", result.Value.Script);
}
[Fact]
public void RenderPage_WhenScriptsSectionIsNamedDifferentlyInCase_ShouldStillSplitIt()
{
// Arrange
Dictionary<string, object?> model = new() { ["title"] = "Page" };
// Act
Result<ThemePageRenderResultDto> result = _sut.RenderPage(
"content{{#SCRIPTS}}script{{/SCRIPTS}}",
model);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal("content", result.Value.Content);
Assert.Equal("script", result.Value.Script);
}
[Fact]
public void RenderPage_WhenScriptsSectionIsNestedInsideAnotherSection_ShouldKeepItInContent()
{
// Arrange
Dictionary<string, object?> model = new()
{
["items"] = new List<object>
{
new Dictionary<string, object?> { ["name"] = "A", ["scripts"] = true, ["script"] = "x" }
}
};
// Act
Result<ThemePageRenderResultDto> result = _sut.RenderPage(
"{{#items}}{{name}}{{#scripts}}{{script}}{{/scripts}}{{/items}}",
model);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal("Ax", result.Value.Content);
}
[Fact]
public void RenderPage_WhenTemplateContainsOnlyComments_ShouldReturnEmptyContent()
{
// Arrange
Dictionary<string, object?> model = new() { ["title"] = "Page" };
// Act
Result<ThemePageRenderResultDto> result = _sut.RenderPage("{{! this is a comment }}", model);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal(string.Empty, result.Value.Content);
Assert.Equal(string.Empty, result.Value.Script);
}
[Fact]
public void RenderPage_WhenSectionIsNotClosed_ShouldReturnTemplateError()
{
// Arrange
Dictionary<string, object?> model = new() { ["section"] = true };
// Act
Result<ThemePageRenderResultDto> result = _sut.RenderPage("{{#section}}content", model);
// Assert
Assert.True(result.IsFailure);
Assert.Equal("Theme.Template.Invalid", result.FirstError.Code);
Assert.Contains("not closed", result.FirstError.Description);
}
[Fact]
public void RenderPage_WhenClosingTagHasNoOpeningSection_ShouldReturnTemplateError()
{
// Act
Result<ThemePageRenderResultDto> result = _sut.RenderPage("{{/section}}", new Dictionary<string, object?>());
// Assert
Assert.True(result.IsFailure);
Assert.Equal("Theme.Template.Invalid", result.FirstError.Code);
Assert.Contains("no matching opening section", result.FirstError.Description);
}
[Fact]
public void RenderPage_WhenClosingTagMismatchesOpeningSection_ShouldReturnTemplateError()
{
// Act
Result<ThemePageRenderResultDto> result = _sut.RenderPage("{{#first}}x{{/second}}", new Dictionary<string, object?>());
// Assert
Assert.True(result.IsFailure);
Assert.Equal("Theme.Template.Invalid", result.FirstError.Code);
Assert.Contains("closed by", result.FirstError.Description);
}
[Fact]
public void RenderPage_WhenEmptyTagUsed_ShouldReturnTemplateError()
{
// Act
Result<ThemePageRenderResultDto> result = _sut.RenderPage("before{{}}after", new Dictionary<string, object?>());
// Assert
Assert.True(result.IsFailure);
Assert.Equal("Theme.Template.Invalid", result.FirstError.Code);
Assert.Contains("Empty template tags", result.FirstError.Description);
}
[Fact]
public void RenderPage_WhenTagIsNotClosed_ShouldReturnTemplateError()
{
// Act
Result<ThemePageRenderResultDto> result = _sut.RenderPage("before{{value", new Dictionary<string, object?>());
// Assert
Assert.True(result.IsFailure);
Assert.Equal("Theme.Template.Invalid", result.FirstError.Code);
Assert.Contains("not closed", result.FirstError.Description);
}
[Fact]
public void RenderPage_WhenRawTagIsNotClosed_ShouldReturnTemplateError()
{
// Act
Result<ThemePageRenderResultDto> result = _sut.RenderPage("before{{{value", new Dictionary<string, object?>());
// Assert
Assert.True(result.IsFailure);
Assert.Equal("Theme.Template.Invalid", result.FirstError.Code);
Assert.Contains("not closed", result.FirstError.Description);
}
[Fact]
public void RenderPage_WhenExpressionIsTooLong_ShouldReturnTemplateError()
{
// Arrange
string expression = new('a', 121);
string template = $"{{{{{expression}}}}}";
// Act
Result<ThemePageRenderResultDto> result = _sut.RenderPage(template, new Dictionary<string, object?>());
// Assert
Assert.True(result.IsFailure);
Assert.Equal("Theme.Template.Invalid", result.FirstError.Code);
Assert.Contains("too long", result.FirstError.Description);
}
[Theory]
[InlineData("{{bad-name}}")] // hyphen is not a valid name part character
[InlineData("{{two words}}")] // whitespace inside the expression
[InlineData("{{a..b}}")] // empty name part
public void RenderPage_WhenExpressionIsInvalid_ShouldReturnTemplateError(string template)
{
// Act
Result<ThemePageRenderResultDto> result = _sut.RenderPage(template, new Dictionary<string, object?>());
// Assert
Assert.True(result.IsFailure);
Assert.Equal("Theme.Template.Invalid", result.FirstError.Code);
Assert.Contains("is invalid", result.FirstError.Description);
}
[Fact]
public void RenderPage_WhenSectionsAreNestedDeeperThanTheLimit_ShouldReturnTemplateError()
{
// Arrange
string template = string.Concat(Enumerable.Repeat("{{#section}}", 33))
+ string.Concat(Enumerable.Repeat("{{/section}}", 33));
// Act
Result<ThemePageRenderResultDto> result = _sut.RenderPage(template, new Dictionary<string, object?>());
// Assert
Assert.True(result.IsFailure);
Assert.Equal("Theme.Template.Invalid", result.FirstError.Code);
Assert.Contains("nested more than", result.FirstError.Description);
}
[Fact]
public void RenderPage_WhenRenderedOutputExceedsTheSafetyLimit_ShouldReturnTemplateError()
{
// Arrange
int limit = 4 * 1024 * 1024;
Dictionary<string, object?> model = new() { ["text"] = new string('a', limit + 1) };
// Act
Result<ThemePageRenderResultDto> result = _sut.RenderPage("{{text}}", model);
// Assert
Assert.True(result.IsFailure);
Assert.Equal("Theme.Template.Invalid", result.FirstError.Code);
Assert.Contains("safety limit", result.FirstError.Description);
}
}