diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/DeleteThemeRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/DeleteThemeRequestMappingTests.cs new file mode 100644 index 00000000..6dcb16ce --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/DeleteThemeRequestMappingTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[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 requests = _deleteThemeRequestFixture.CreateMany(); + + // Act + List 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); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/GetThemeArchiveRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/GetThemeArchiveRequestMappingTests.cs new file mode 100644 index 00000000..8c758111 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/GetThemeArchiveRequestMappingTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[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 requests = _getThemeArchiveRequestFixture.CreateMany(); + + // Act + List 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); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/GetThemeAssetRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/GetThemeAssetRequestMappingTests.cs new file mode 100644 index 00000000..d6775a90 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/GetThemeAssetRequestMappingTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[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 requests = _getThemeAssetRequestFixture.CreateMany(); + + // Act + List 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); + } + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/GetThemeTemplateRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/GetThemeTemplateRequestMappingTests.cs new file mode 100644 index 00000000..ff5f7043 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/GetThemeTemplateRequestMappingTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[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 requests = _getThemeTemplateRequestFixture.CreateMany(); + + // Act + List 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); + } + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/SetCurrentThemeRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/SetCurrentThemeRequestMappingTests.cs new file mode 100644 index 00000000..cdde81c5 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/SetCurrentThemeRequestMappingTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[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 requests = _setCurrentThemeRequestFixture.CreateMany(); + + // Act + List 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); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/ThemeEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/ThemeEntityMappingTests.cs new file mode 100644 index 00000000..17f390ee --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/ThemeEntityMappingTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[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); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/DeleteTheme/DeleteThemeCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/DeleteTheme/DeleteThemeCommandHandlerTests.cs new file mode 100644 index 00000000..f0d763af --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/DeleteTheme/DeleteThemeCommandHandlerTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteThemeCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IThemeService _mockThemeService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly IValidator _mockValidator; + private readonly IThemeRepository _mockThemeRepository; + private readonly DeleteThemeCommandHandler _sut; + private readonly DeleteThemeCommandFixture _deleteThemeCommandFixture = new(); + private readonly ThemeEntityFixture _themeEntityFixture = new(); + private readonly Guid _userId; + + /// + /// Initializes a new instance of the class. + /// + public DeleteThemeCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockThemeService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockAuthorizationService = Substitute.For(); + _mockValidator = Substitute.For>(); + _mockThemeRepository = Substitute.For(); + _userId = Guid.NewGuid(); + + _mockValidator.Validate(Arg.Any()) + .Returns([]); + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) + .Returns(true); + _mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository); + _mockThemeService.DeleteAsync(Arg.Any(), Arg.Any()) + .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()) + .Returns([Errors.Themes.ThemeIdCannotBeEmpty]); + + // Act + Result 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(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + DeleteThemeCommand command = _deleteThemeCommandFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result 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(), Arg.Any(), Arg.Any()); + await _mockThemeRepository.DidNotReceive().GetByThemeIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError() + { + // Arrange + DeleteThemeCommand command = _deleteThemeCommandFixture.Create(); + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) + .Returns(false); + + // Act + Result 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(), Arg.Any()); + } + + [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()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenThemeDoesNotExist_ShouldReturnThemeNotFoundError() + { + // Arrange + DeleteThemeCommand command = _deleteThemeCommandFixture.Create(); + _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result 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()); + } + + [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()) + .Returns(Result.From(theme)); + + // Act + Result 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()); + } + + [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()) + .Returns(Result.From(theme)); + _mockThemeRepository.GetAllAsync(Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [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()) + .Returns(Result.From(theme)); + _mockThemeRepository.GetAllAsync(Arg.Any()) + .Returns(Result.From>([theme, userTheme])); + + // Act + Result 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(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + await _mockThemeService.DidNotReceive().DeleteAsync(Arg.Any(), Arg.Any()); + } + + [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()) + .Returns(Result.From(theme)); + _mockThemeRepository.GetAllAsync(Arg.Any()) + .Returns(Result.From>([theme])); + + // Act + Result 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(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + await _mockThemeService.DidNotReceive().DeleteAsync(Arg.Any(), Arg.Any()); + } + + [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()) + .Returns(Result.From(theme)); + _mockThemeRepository.GetAllAsync(Arg.Any()) + .Returns(Result.From>([theme, otherBundledTheme])); + _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockThemeRepository.Received(1).UpdateAsync( + Arg.Is(entity => entity.Id == theme.Id && entity.IsDeleted && entity.IsCurrent == null && entity.UpdatedBy == _userId), + Arg.Any()); + await _mockThemeRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + await _mockThemeService.Received(1).DeleteAsync(theme.ThemeId, Arg.Any()); + } + + [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()) + .Returns(Result.From(theme)); + _mockThemeRepository.GetAllAsync(Arg.Any()) + .Returns(Result.From>([theme, bundledTheme])); + _mockThemeRepository.DeleteByIdAsync(theme.Id, Arg.Any()) + .Returns(Result.Deleted); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockThemeRepository.Received(1).DeleteByIdAsync(theme.Id, Arg.Any()); + await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + await _mockThemeService.Received(1).DeleteAsync(theme.ThemeId, Arg.Any()); + } + + [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()) + .Returns(Result.From(theme)); + _mockThemeRepository.GetAllAsync(Arg.Any()) + .Returns(Result.From>([theme, bundledTheme])); + _mockThemeRepository.DeleteByIdAsync(theme.Id, Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + await _mockThemeService.DidNotReceive().DeleteAsync(Arg.Any(), Arg.Any()); + } + + [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()) + .Returns(Result.From(theme)); + _mockThemeRepository.GetAllAsync(Arg.Any()) + .Returns(Result.From>([theme, replacementTheme])); + _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockThemeRepository.Received(1).UpdateAsync( + Arg.Is(entity => entity.Id == replacementTheme.Id && entity.IsCurrent == true), + Arg.Any()); + await _mockThemeRepository.Received(1).UpdateAsync( + Arg.Is(entity => entity.Id == theme.Id && entity.IsDeleted && entity.IsCurrent == null), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + await _mockThemeService.Received(1).DeleteAsync(theme.ThemeId, Arg.Any()); + } + + [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()) + .Returns(Result.From(theme)); + _mockThemeRepository.GetAllAsync(Arg.Any()) + .Returns(Result.From>([theme, betaTheme, alphaTheme])); + _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockThemeRepository.Received(1).UpdateAsync( + Arg.Is(entity => entity.Id == alphaTheme.Id && entity.IsCurrent == true), + Arg.Any()); + await _mockThemeRepository.Received(1).UpdateAsync( + Arg.Is(entity => entity.Id == theme.Id && entity.IsDeleted), + Arg.Any()); + } + + [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()) + .Returns(Result.From(theme)); + _mockThemeRepository.GetAllAsync(Arg.Any()) + .Returns(Result.From>([theme, bundledTheme])); + _mockThemeRepository.DeleteByIdAsync(theme.Id, Arg.Any()) + .Returns(Result.Deleted); + _mockThemeService.DeleteAsync(theme.ThemeId, Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/DeleteTheme/DeleteThemeCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/DeleteTheme/DeleteThemeCommandValidatorTests.cs new file mode 100644 index 00000000..533e428b --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/DeleteTheme/DeleteThemeCommandValidatorTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[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 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 result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Themes.ThemeIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenThemeIdIsWhiteSpace_ShouldHaveValidationError() + { + // Arrange + DeleteThemeCommand command = _deleteThemeCommandFixture.Create(themeId: " "); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Themes.ThemeIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenThemeIdIsValid_ShouldNotHaveAnyValidationErrors() + { + // Arrange + DeleteThemeCommand command = _deleteThemeCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/InstallTheme/InstallThemeCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/InstallTheme/InstallThemeCommandHandlerTests.cs new file mode 100644 index 00000000..833c6414 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/InstallTheme/InstallThemeCommandHandlerTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class InstallThemeCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IThemeService _mockThemeService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly IValidator _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; + + /// + /// Initializes a new instance of the class. + /// + public InstallThemeCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockThemeService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockAuthorizationService = Substitute.For(); + _mockValidator = Substitute.For>(); + _mockThemeRepository = Substitute.For(); + _userId = Guid.NewGuid(); + + _mockValidator.Validate(Arg.Any()) + .Returns([]); + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) + .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()) + .Returns([Errors.Themes.ThemeArchiveCannotBeNull]); + + // Act + Result 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(), Arg.Any()); + await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + InstallThemeCommand command = _installThemeCommandFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result 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(), Arg.Any(), Arg.Any()); + await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError() + { + // Arrange + InstallThemeCommand command = _installThemeCommandFixture.Create(); + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) + .Returns(false); + + // Act + Result 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(), Arg.Any()); + } + + [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()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockThemeRepository.DidNotReceive().GetByThemeIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [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()) + .Returns(Result.From(manifest)); + _mockThemeRepository.GetByThemeIdAsync(manifest.Id, Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenThemeDoesNotExist_ShouldInsertNewUploadedTheme() + { + // Arrange + InstallThemeCommand command = _installThemeCommandFixture.Create(); + ThemeManifestDto manifest = _themeManifestDtoFixture.Create(); + _mockThemeService.InstallAsync(command.Archive!, Arg.Any()) + .Returns(Result.From(manifest)); + _mockThemeRepository.GetByThemeIdAsync(manifest.Id, Arg.Any()) + .Returns(Result.From(null)); + _mockThemeRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + + // Act + Result 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(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()); + await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [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()) + .Returns(Result.From(manifest)); + _mockThemeRepository.GetByThemeIdAsync(manifest.Id, Arg.Any()) + .Returns(Result.From(null)); + _mockThemeRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(error); + + // Act + Result 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()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [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()) + .Returns(Result.From(manifest)); + _mockThemeRepository.GetByThemeIdAsync(manifest.Id, Arg.Any()) + .Returns(Result.From(existingTheme)); + _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + Result 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(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()); + await _mockThemeRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [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()) + .Returns(Result.From(manifest)); + _mockThemeRepository.GetByThemeIdAsync(manifest.Id, Arg.Any()) + .Returns(Result.From(existingTheme)); + _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/InstallTheme/InstallThemeCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/InstallTheme/InstallThemeCommandValidatorTests.cs new file mode 100644 index 00000000..7ccea36e --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/InstallTheme/InstallThemeCommandValidatorTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[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 result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Themes.ThemeArchiveCannotBeNull); + } + + [Fact] + public void Validate_WhenArchiveIsProvided_ShouldNotHaveValidationError() + { + // Arrange + InstallThemeCommand command = _installThemeCommandFixture.Create(); + + // Act + List 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 result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/SetCurrentTheme/SetCurrentThemeCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/SetCurrentTheme/SetCurrentThemeCommandHandlerTests.cs new file mode 100644 index 00000000..f63854be --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/SetCurrentTheme/SetCurrentThemeCommandHandlerTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SetCurrentThemeCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly IValidator _mockValidator; + private readonly IThemeRepository _mockThemeRepository; + private readonly SetCurrentThemeCommandHandler _sut; + private readonly SetCurrentThemeCommandFixture _setCurrentThemeCommandFixture = new(); + private readonly ThemeEntityFixture _themeEntityFixture = new(); + private readonly Guid _userId; + + /// + /// Initializes a new instance of the class. + /// + public SetCurrentThemeCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockAuthorizationService = Substitute.For(); + _mockValidator = Substitute.For>(); + _mockThemeRepository = Substitute.For(); + _userId = Guid.NewGuid(); + + _mockValidator.Validate(Arg.Any()) + .Returns([]); + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) + .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()) + .Returns([Errors.Themes.ThemeIdCannotBeEmpty]); + + // Act + Result 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(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + SetCurrentThemeCommand command = _setCurrentThemeCommandFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result 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(), Arg.Any(), Arg.Any()); + await _mockThemeRepository.DidNotReceive().GetByThemeIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError() + { + // Arrange + SetCurrentThemeCommand command = _setCurrentThemeCommandFixture.Create(); + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) + .Returns(false); + + // Act + Result 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(), Arg.Any()); + } + + [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()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenThemeDoesNotExist_ShouldReturnThemeNotFoundError() + { + // Arrange + SetCurrentThemeCommand command = _setCurrentThemeCommandFixture.Create(); + _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result 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()); + } + + [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()) + .Returns(Result.From(theme)); + + // Act + Result 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()); + } + + [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()) + .Returns(Result.From(theme)); + + // Act + Result 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()); + await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [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()) + .Returns(Result.From(theme)); + _mockThemeRepository.GetCurrentAsync(Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [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()) + .Returns(Result.From(theme)); + _mockThemeRepository.GetCurrentAsync(Arg.Any()) + .Returns(Result.From(currentTheme)); + _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + Result 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(entity => entity.Id == currentTheme.Id && entity.IsCurrent == null), + Arg.Any()); + await _mockThemeRepository.Received(1).UpdateAsync( + Arg.Is(entity => entity.Id == theme.Id && entity.IsCurrent == true && entity.UpdatedBy == _userId), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [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()) + .Returns(Result.From(theme)); + _mockThemeRepository.GetCurrentAsync(Arg.Any()) + .Returns(Result.From(theme)); + _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + Result 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(entity => entity.Id == theme.Id && entity.IsCurrent == true), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [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()) + .Returns(Result.From(theme)); + _mockThemeRepository.GetCurrentAsync(Arg.Any()) + .Returns(Result.From(null)); + _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + Result 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(entity => entity.Id == theme.Id && entity.IsCurrent == true && entity.UpdatedBy == _userId), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/SetCurrentTheme/SetCurrentThemeCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/SetCurrentTheme/SetCurrentThemeCommandValidatorTests.cs new file mode 100644 index 00000000..b4f86aeb --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/SetCurrentTheme/SetCurrentThemeCommandValidatorTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[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 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 result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Themes.ThemeIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenThemeIdIsWhiteSpace_ShouldHaveValidationError() + { + // Arrange + SetCurrentThemeCommand command = _setCurrentThemeCommandFixture.Create(themeId: " "); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Themes.ThemeIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenThemeIdIsValid_ShouldNotHaveAnyValidationErrors() + { + // Arrange + SetCurrentThemeCommand command = _setCurrentThemeCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetCurrentTheme/GetCurrentThemeQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetCurrentTheme/GetCurrentThemeQueryHandlerTests.cs new file mode 100644 index 00000000..abb8cead --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetCurrentTheme/GetCurrentThemeQueryHandlerTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[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(); + + /// + /// Initializes a new instance of the class. + /// + public GetCurrentThemeQueryHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockThemeRepository = Substitute.For(); + _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()) + .Returns(Result.From(theme)); + + // Act + Result 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()) + .Returns(Result.From(null)); + + // Act + Result 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()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeArchive/GetThemeArchiveQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeArchive/GetThemeArchiveQueryHandlerTests.cs new file mode 100644 index 00000000..051aecfa --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeArchive/GetThemeArchiveQueryHandlerTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetThemeArchiveQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IThemeService _mockThemeService; + private readonly IValidator _mockValidator; + private readonly IThemeRepository _mockThemeRepository; + private readonly GetThemeArchiveQueryHandler _sut; + private readonly GetThemeArchiveQueryFixture _getThemeArchiveQueryFixture = new(); + private readonly ThemeEntityFixture _themeEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetThemeArchiveQueryHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockThemeService = Substitute.For(); + _mockValidator = Substitute.For>(); + _mockThemeRepository = Substitute.For(); + + _mockValidator.Validate(Arg.Any()) + .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()) + .Returns([Errors.Themes.ThemeIdCannotBeEmpty]); + + // Act + Result 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(), Arg.Any()); + await _mockThemeService.DidNotReceive().BuildArchiveAsync(Arg.Any(), Arg.Any()); + } + + [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()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockThemeService.DidNotReceive().BuildArchiveAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenThemeDoesNotExist_ShouldReturnThemeNotFoundError() + { + // Arrange + GetThemeArchiveQuery query = _getThemeArchiveQueryFixture.Create(); + _mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result 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(), Arg.Any()); + } + + [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()) + .Returns(Result.From(theme)); + + // Act + Result 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(), Arg.Any()); + } + + [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()) + .Returns(Result.From(theme)); + _mockThemeService.BuildArchiveAsync(theme.ThemeId, Arg.Any()) + .Returns(Result.From(new ThemeArchiveDto(bytes, fileName, contentType))); + + // Act + Result 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()) + .Returns(Result.From(theme)); + _mockThemeService.BuildArchiveAsync(theme.ThemeId, Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeArchive/GetThemeArchiveQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeArchive/GetThemeArchiveQueryValidatorTests.cs new file mode 100644 index 00000000..64f57510 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeArchive/GetThemeArchiveQueryValidatorTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[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 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 result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Themes.ThemeIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenThemeIdIsWhiteSpace_ShouldHaveValidationError() + { + // Arrange + GetThemeArchiveQuery query = _getThemeArchiveQueryFixture.Create(themeId: " "); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Themes.ThemeIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenThemeIdIsValid_ShouldNotHaveAnyValidationErrors() + { + // Arrange + GetThemeArchiveQuery query = _getThemeArchiveQueryFixture.Create(); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeAsset/GetThemeAssetQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeAsset/GetThemeAssetQueryHandlerTests.cs new file mode 100644 index 00000000..073979b0 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeAsset/GetThemeAssetQueryHandlerTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetThemeAssetQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IThemeService _mockThemeService; + private readonly IValidator _mockValidator; + private readonly IThemeRepository _mockThemeRepository; + private readonly GetThemeAssetQueryHandler _sut; + private readonly GetThemeAssetQueryFixture _getThemeAssetQueryFixture = new(); + private readonly ThemeEntityFixture _themeEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetThemeAssetQueryHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockThemeService = Substitute.For(); + _mockValidator = Substitute.For>(); + _mockThemeRepository = Substitute.For(); + + _mockValidator.Validate(Arg.Any()) + .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()) + .Returns([Errors.Themes.ThemeIdCannotBeEmpty]); + + // Act + Result 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(), Arg.Any()); + await _mockThemeService.DidNotReceive().GetAssetAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [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()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockThemeService.DidNotReceive().GetAssetAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenThemeDoesNotExist_ShouldReturnThemeNotFoundError() + { + // Arrange + GetThemeAssetQuery query = _getThemeAssetQueryFixture.Create(); + _mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result 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()) + .Returns(Result.From(theme)); + + // Act + Result 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(), Arg.Any(), Arg.Any()); + } + + [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()) + .Returns(Result.From(theme)); + _mockThemeService.GetAssetAsync(theme.ThemeId, query.AssetPath!, Arg.Any()) + .Returns(Result.From(new ThemeAssetDto(bytes, contentType))); + + // Act + Result 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(), Arg.Any()); + } + + [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()) + .Returns(Result.From(theme)); + _mockThemeService.GetAssetAsync(theme.ThemeId, query.AssetPath!, Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockThemeService.DidNotReceive().RestoreBundledThemeAsync(Arg.Any(), Arg.Any()); + } + + [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()) + .Returns(Result.From(theme)); + _mockThemeService.GetAssetAsync(theme.ThemeId, query.AssetPath!, Arg.Any()) + .Returns(assetError); + _mockThemeService.RestoreBundledThemeAsync(theme.ThemeId, Arg.Any()) + .Returns(restoreError); + + // Act + Result 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()) + .Returns(Result.From(theme)); + _mockThemeService.GetAssetAsync(theme.ThemeId, query.AssetPath!, Arg.Any()) + .Returns(assetError, Result.From(new ThemeAssetDto(restoredBytes, contentType))); + _mockThemeService.RestoreBundledThemeAsync(theme.ThemeId, Arg.Any()) + .Returns(Result.Success); + + // Act + Result 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()); + await _mockThemeService.Received(1).RestoreBundledThemeAsync(theme.ThemeId, Arg.Any()); + } + + [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()) + .Returns(Result.From(theme)); + _mockThemeService.GetAssetAsync(theme.ThemeId, query.AssetPath!, Arg.Any()) + .Returns(assetError, retryError); + _mockThemeService.RestoreBundledThemeAsync(theme.ThemeId, Arg.Any()) + .Returns(Result.Success); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(retryError, result.FirstError); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeAsset/GetThemeAssetQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeAsset/GetThemeAssetQueryValidatorTests.cs new file mode 100644 index 00000000..2dee43e8 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeAsset/GetThemeAssetQueryValidatorTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[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 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 result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Themes.ThemeIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenThemeIdIsWhiteSpace_ShouldHaveValidationError() + { + // Arrange + GetThemeAssetQuery query = _getThemeAssetQueryFixture.Create(themeId: " "); + + // Act + List 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 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 result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Themes.ThemeAssetPathCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAssetPathIsWhiteSpace_ShouldHaveValidationError() + { + // Arrange + GetThemeAssetQuery query = _getThemeAssetQueryFixture.Create(assetPath: " "); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Themes.ThemeAssetPathCannotBeEmpty); + } + + [Fact] + public void Validate_WhenQueryIsValid_ShouldNotHaveAnyValidationErrors() + { + // Arrange + GetThemeAssetQuery query = _getThemeAssetQueryFixture.Create(); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeSettings/GetThemeSettingsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeSettings/GetThemeSettingsQueryHandlerTests.cs new file mode 100644 index 00000000..64904a3d --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeSettings/GetThemeSettingsQueryHandlerTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetThemeSettingsQueryHandlerTests +{ + private readonly IThemeService _mockThemeService; + private readonly GetThemeSettingsQueryHandler _sut; + private readonly GetThemeSettingsQueryFixture _getThemeSettingsQueryFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetThemeSettingsQueryHandlerTests() + { + _mockThemeService = Substitute.For(); + _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 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); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeTemplate/GetThemeTemplateQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeTemplate/GetThemeTemplateQueryHandlerTests.cs new file mode 100644 index 00000000..471af61e --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeTemplate/GetThemeTemplateQueryHandlerTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetThemeTemplateQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IThemeService _mockThemeService; + private readonly IValidator _mockValidator; + private readonly IThemeRepository _mockThemeRepository; + private readonly GetThemeTemplateQueryHandler _sut; + private readonly GetThemeTemplateQueryFixture _getThemeTemplateQueryFixture = new(); + private readonly ThemeEntityFixture _themeEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetThemeTemplateQueryHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockThemeService = Substitute.For(); + _mockValidator = Substitute.For>(); + _mockThemeRepository = Substitute.For(); + + _mockValidator.Validate(Arg.Any()) + .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()) + .Returns([Errors.Themes.ThemeIdCannotBeEmpty]); + + // Act + Result 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(), Arg.Any()); + await _mockThemeService.DidNotReceive().GetTemplateAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [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()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockThemeService.DidNotReceive().GetTemplateAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenThemeDoesNotExist_ShouldReturnThemeNotFoundError() + { + // Arrange + GetThemeTemplateQuery query = _getThemeTemplateQueryFixture.Create(); + _mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result 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()) + .Returns(Result.From(theme)); + + // Act + Result 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(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTemplateLoadsSuccessfully_ShouldReturnTemplateResponse() + { + // Arrange + GetThemeTemplateQuery query = _getThemeTemplateQueryFixture.Create(); + ThemeEntity theme = _themeEntityFixture.Create(themeId: query.ThemeId, isDeleted: false); + string template = "Hello"; + _mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any()) + .Returns(Result.From(theme)); + _mockThemeService.GetTemplateAsync(theme.ThemeId, query.PageKey!, Arg.Any()) + .Returns(Result.From(template)); + + // Act + Result 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(), Arg.Any()); + } + + [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()) + .Returns(Result.From(theme)); + _mockThemeService.GetTemplateAsync(theme.ThemeId, query.PageKey!, Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockThemeService.DidNotReceive().RestoreBundledThemeAsync(Arg.Any(), Arg.Any()); + } + + [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()) + .Returns(Result.From(theme)); + _mockThemeService.GetTemplateAsync(theme.ThemeId, query.PageKey!, Arg.Any()) + .Returns(templateError); + _mockThemeService.RestoreBundledThemeAsync(theme.ThemeId, Arg.Any()) + .Returns(restoreError); + + // Act + Result 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 = "Restored"; + _mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any()) + .Returns(Result.From(theme)); + _mockThemeService.GetTemplateAsync(theme.ThemeId, query.PageKey!, Arg.Any()) + .Returns(templateError, Result.From(restoredTemplate)); + _mockThemeService.RestoreBundledThemeAsync(theme.ThemeId, Arg.Any()) + .Returns(Result.Success); + + // Act + Result 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()); + await _mockThemeService.Received(1).RestoreBundledThemeAsync(theme.ThemeId, Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [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()) + .Returns(Result.From(theme)); + _mockThemeService.GetTemplateAsync(theme.ThemeId, query.PageKey!, Arg.Any()) + .Returns(templateError, retryError); + _mockThemeService.RestoreBundledThemeAsync(theme.ThemeId, Arg.Any()) + .Returns(Result.Success); + + // Act + Result 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 = "Restored"; + _mockThemeService.DefaultThemeId.Returns(defaultTheme.ThemeId); + _mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any()) + .Returns(Result.From(theme)); + _mockThemeRepository.GetByThemeIdAsync(defaultTheme.ThemeId, Arg.Any()) + .Returns(Result.From(defaultTheme)); + _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + _mockThemeService.GetTemplateAsync(theme.ThemeId, query.PageKey!, Arg.Any()) + .Returns(templateError, Result.From(restoredTemplate)); + _mockThemeService.RestoreBundledThemeAsync(theme.ThemeId, Arg.Any()) + .Returns(Result.Success); + + // Act + Result 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(entity => entity.Id == theme.Id && entity.IsCurrent == null), + Arg.Any()); + await _mockThemeRepository.Received(1).UpdateAsync( + Arg.Is(entity => entity.Id == defaultTheme.Id && entity.IsCurrent == true), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [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 = "Restored"; + _mockThemeService.DefaultThemeId.Returns("missing-default"); + _mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any()) + .Returns(Result.From(theme)); + _mockThemeRepository.GetByThemeIdAsync("missing-default", Arg.Any()) + .Returns(Result.From(null)); + _mockThemeService.GetTemplateAsync(theme.ThemeId, query.PageKey!, Arg.Any()) + .Returns(templateError, Result.From(restoredTemplate)); + _mockThemeService.RestoreBundledThemeAsync(theme.ThemeId, Arg.Any()) + .Returns(Result.Success); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(restoredTemplate, result.Value.Template); + await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [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 = "Restored"; + _mockThemeService.DefaultThemeId.Returns("default-theme"); + _mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any()) + .Returns(Result.From(theme)); + _mockThemeRepository.GetByThemeIdAsync("default-theme", Arg.Any()) + .Returns(defaultError); + _mockThemeService.GetTemplateAsync(theme.ThemeId, query.PageKey!, Arg.Any()) + .Returns(templateError, Result.From(restoredTemplate)); + _mockThemeService.RestoreBundledThemeAsync(theme.ThemeId, Arg.Any()) + .Returns(Result.Success); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(restoredTemplate, result.Value.Template); + await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeTemplate/GetThemeTemplateQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeTemplate/GetThemeTemplateQueryValidatorTests.cs new file mode 100644 index 00000000..bbc5ec3d --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeTemplate/GetThemeTemplateQueryValidatorTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[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 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 result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Themes.ThemeIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenThemeIdIsWhiteSpace_ShouldHaveValidationError() + { + // Arrange + GetThemeTemplateQuery query = _getThemeTemplateQueryFixture.Create(themeId: " "); + + // Act + List 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 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 result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Themes.PageKeyCannotBeEmpty); + } + + [Fact] + public void Validate_WhenPageKeyIsWhiteSpace_ShouldHaveValidationError() + { + // Arrange + GetThemeTemplateQuery query = _getThemeTemplateQueryFixture.Create(pageKey: " "); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Themes.PageKeyCannotBeEmpty); + } + + [Fact] + public void Validate_WhenQueryIsValid_ShouldNotHaveAnyValidationErrors() + { + // Arrange + GetThemeTemplateQuery query = _getThemeTemplateQueryFixture.Create(); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemes/GetThemesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemes/GetThemesQueryHandlerTests.cs new file mode 100644 index 00000000..3066d68c --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemes/GetThemesQueryHandlerTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[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(); + + /// + /// Initializes a new instance of the class. + /// + public GetThemesQueryHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockThemeRepository = Substitute.For(); + _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()) + .Returns(Result.From>([uploadedTheme, bundledLowerTheme, bundledUpperTheme, deletedTheme])); + + // Act + Result> 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()) + .Returns(Result.From>([])); + + // Act + Result> 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()) + .Returns(error); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/ThemeEngineOptionsDtoValidatorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/ThemeEngineOptionsDtoValidatorTests.cs index 05e9cc01..731f9845 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/ThemeEngineOptionsDtoValidatorTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/ThemeEngineOptionsDtoValidatorTests.cs @@ -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 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 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 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 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 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 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 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 result = _validator.Validate(options); diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeDetectionSyncJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeDetectionSyncJobTests.cs new file mode 100644 index 00000000..4ac21505 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeDetectionSyncJobTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[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 _mockLogger; + private readonly ThemePackFixture _themePackFixture = new(); + private readonly ThemeEntityFixture _themeEntityFixture = new(); + private readonly ThemeManifestDtoFixture _themeManifestDtoFixture = new(); + private readonly string _testRootPath; + + /// + /// Initializes a new instance of the class. + /// + public ThemeDetectionSyncJobTests() + { + _testRootPath = Path.Combine(Path.GetTempPath(), $"lumina-theme-job-{Guid.NewGuid():N}"); + Directory.CreateDirectory(_testRootPath); + _mockServiceScopeFactory = Substitute.For(); + _mockServiceScope = Substitute.For(); + _mockServiceProvider = Substitute.For(); + _mockServiceScopeFactory.CreateAsyncScope().Returns(new AsyncServiceScope(_mockServiceScope)); + _mockServiceScope.ServiceProvider.Returns(_mockServiceProvider); + + _mockUnitOfWork = Substitute.For(); + _mockThemeRepository = Substitute.For(); + _mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository); + _mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork); + + _mockThemeService = Substitute.For(); + _mockThemeService.HasThemePack(Arg.Any()).Returns(true); + _mockLogger = Substitute.For>(); + } + + /// + /// Cleans up the temporary storage used by the tests. + /// + 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()).Returns(Result.From>([])); + _mockThemeService.GetBundledThemeArchivePaths().Returns([]); + + // Act + await StartAndWaitForExecutionAsync(CreateSut()); + + // Assert + await _mockThemeRepository.DidNotReceiveWithAnyArgs().InsertAsync(default!, Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task StartAsync_WhenBundledThemeIsNotYetInstalled_ShouldInstallAndPersistTheTheme() + { + // Arrange + string archivePath = CreateBundledArchiveFile("bundled-theme"); + ThemeManifestDto manifest = _themeManifestDtoFixture.Create(id: "bundled-theme"); + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([])); + _mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]); + _mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any()).Returns(manifest); + _mockThemeService.InstallAsync(Arg.Any(), Arg.Any()).Returns(manifest); + _mockThemeRepository.InsertAsync(Arg.Any(), Arg.Any()).Returns(Result.From(Result.Created)); + + // Act + await StartAndWaitForExecutionAsync(CreateSut()); + + // Assert + await _mockThemeService.Received(1).InstallAsync(Arg.Any(), Arg.Any()); + await _mockThemeRepository.Received(1).InsertAsync( + Arg.Is(theme => theme.ThemeId == "bundled-theme" + && theme.Name == manifest.Name + && theme.Description == manifest.Description + && theme.Version == manifest.Version + && theme.InstallSource == ThemeInstallSource.Bundled), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [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()).Returns(Result.From>([existingTheme])); + _mockThemeService.GetBundledThemeArchivePaths().Returns(["C:\\bundled\\bundled-theme.zip"]); + _mockThemeService.ReadManifestFromArchiveAsync("C:\\bundled\\bundled-theme.zip", Arg.Any()).Returns(_themeManifestDtoFixture.Create(id: "bundled-theme")); + + // Act + await StartAndWaitForExecutionAsync(CreateSut()); + + // Assert + await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any(), Arg.Any()); + await _mockThemeRepository.DidNotReceiveWithAnyArgs().InsertAsync(default!, Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task StartAsync_WhenBundledThemeWasSoftDeletedByTheUser_ShouldNotReinstallIt() + { + // Arrange + ThemeEntity deletedTheme = _themeEntityFixture.Create(themeId: "bundled-theme", isDeleted: true, installSource: ThemeInstallSource.Bundled); + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([deletedTheme])); + _mockThemeService.GetBundledThemeArchivePaths().Returns(["C:\\bundled\\bundled-theme.zip"]); + _mockThemeService.ReadManifestFromArchiveAsync("C:\\bundled\\bundled-theme.zip", Arg.Any()).Returns(_themeManifestDtoFixture.Create(id: "bundled-theme")); + + // Act + await StartAndWaitForExecutionAsync(CreateSut()); + + // Assert + await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any(), Arg.Any()); + await _mockThemeRepository.DidNotReceiveWithAnyArgs().InsertAsync(default!, Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task StartAsync_WhenBundledArchiveManifestCannotBeRead_ShouldSkipTheArchive() + { + // Arrange + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([])); + _mockThemeService.GetBundledThemeArchivePaths().Returns(["C:\\bundled\\broken.zip"]); + _mockThemeService.ReadManifestFromArchiveAsync("C:\\bundled\\broken.zip", Arg.Any()).Returns(Error.Failure("Theme.Files", "unreadable")); + + // Act + await StartAndWaitForExecutionAsync(CreateSut()); + + // Assert + await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any(), Arg.Any()); + await _mockThemeRepository.DidNotReceiveWithAnyArgs().InsertAsync(default!, Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task StartAsync_WhenBundledThemeInstallFails_ShouldNotPersistTheTheme() + { + // Arrange + string archivePath = CreateBundledArchiveFile("bundled-theme"); + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([])); + _mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]); + _mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any()).Returns(_themeManifestDtoFixture.Create(id: "bundled-theme")); + _mockThemeService.InstallAsync(Arg.Any(), Arg.Any()).Returns(Error.Failure("Theme.Install", "install failed")); + + // Act + await StartAndWaitForExecutionAsync(CreateSut()); + + // Assert + await _mockThemeRepository.DidNotReceiveWithAnyArgs().InsertAsync(default!, Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task StartAsync_WhenPersistingDetectedThemeFails_ShouldLogWarningAndContinue() + { + // Arrange + string archivePath = CreateBundledArchiveFile("bundled-theme"); + ThemeManifestDto manifest = _themeManifestDtoFixture.Create(id: "bundled-theme"); + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([])); + _mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]); + _mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any()).Returns(manifest); + _mockThemeService.InstallAsync(Arg.Any(), Arg.Any()).Returns(manifest); + _mockThemeRepository.InsertAsync(Arg.Any(), Arg.Any()).Returns(Error.Failure("Database.Error", "failed to persist")); + + // Act + await StartAndWaitForExecutionAsync(CreateSut()); + + // Assert + await _mockThemeRepository.Received(1).InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task StartAsync_WhenReadingInstalledThemesFails_ShouldReturnWithoutPersistingChanges() + { + // Arrange + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Error.Failure("Database.Error", "failed to read themes")); + + // Act + await StartAndWaitForExecutionAsync(CreateSut()); + + // Assert + _mockThemeService.DidNotReceive().GetBundledThemeArchivePaths(); + await _mockUnitOfWork.DidNotReceiveWithAnyArgs().SaveChangesAsync(Arg.Any()); + } + + [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()).Returns(Result.From>([brokenTheme])); + _mockThemeService.HasThemePack("bundled-theme").Returns(false); + _mockThemeService.GetBundledThemeArchivePaths().Returns([]); + _mockThemeService.RestoreBundledThemeAsync("bundled-theme", Arg.Any()).Returns(Result.Success); + + // Act + await StartAndWaitForExecutionAsync(CreateSut()); + + // Assert + await _mockThemeService.Received(1).RestoreBundledThemeAsync("bundled-theme", Arg.Any()); + await _mockThemeRepository.DidNotReceiveWithAnyArgs().UpdateAsync(default!, Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task StartAsync_WhenMissingBundledThemePackCannotBeRestored_ShouldSoftDeleteTheTheme() + { + // Arrange + ThemeEntity brokenTheme = _themeEntityFixture.Create(themeId: "bundled-theme", installSource: ThemeInstallSource.Bundled, isDeleted: false); + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([brokenTheme])); + _mockThemeService.HasThemePack("bundled-theme").Returns(false); + _mockThemeService.GetBundledThemeArchivePaths().Returns([]); + _mockThemeService.RestoreBundledThemeAsync("bundled-theme", Arg.Any()).Returns(Error.Failure("Theme.Files", "restore failed")); + _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.From(Result.Updated)); + + // Act + await StartAndWaitForExecutionAsync(CreateSut()); + + // Assert + await _mockThemeRepository.Received(1).UpdateAsync( + Arg.Is(theme => theme.ThemeId == "bundled-theme" && theme.IsDeleted && theme.IsCurrent == null), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task StartAsync_WhenMissingUserThemePackExists_ShouldDeleteTheTheme() + { + // Arrange + ThemeEntity brokenTheme = _themeEntityFixture.Create(themeId: "user-theme", installSource: ThemeInstallSource.Uploaded, isDeleted: false); + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([brokenTheme])); + _mockThemeService.HasThemePack("user-theme").Returns(false); + _mockThemeService.GetBundledThemeArchivePaths().Returns([]); + _mockThemeRepository.DeleteByIdAsync(brokenTheme.Id, Arg.Any()).Returns(Result.From(Result.Deleted)); + + // Act + await StartAndWaitForExecutionAsync(CreateSut()); + + // Assert + await _mockThemeRepository.Received(1).DeleteByIdAsync(brokenTheme.Id, Arg.Any()); + await _mockThemeService.DidNotReceive().RestoreBundledThemeAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task StartAsync_WhenDeletingMissingUserThemeFails_ShouldLogWarningAndContinue() + { + // Arrange + ThemeEntity brokenTheme = _themeEntityFixture.Create(themeId: "user-theme", installSource: ThemeInstallSource.Uploaded, isDeleted: false); + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([brokenTheme])); + _mockThemeService.HasThemePack("user-theme").Returns(false); + _mockThemeService.GetBundledThemeArchivePaths().Returns([]); + _mockThemeRepository.DeleteByIdAsync(brokenTheme.Id, Arg.Any()).Returns(Error.Failure("Database.Error", "delete failed")); + + // Act + await StartAndWaitForExecutionAsync(CreateSut()); + + // Assert + await _mockThemeRepository.Received(1).DeleteByIdAsync(brokenTheme.Id, Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task StartAsync_WhenNoThemeIsCurrent_ShouldActivateTheDefaultTheme() + { + // Arrange + ThemeEntity theme = _themeEntityFixture.Create(themeId: "default-theme", installSource: ThemeInstallSource.Bundled, isDeleted: false); + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([theme])); + _mockThemeService.DefaultThemeId.Returns("default-theme"); + _mockThemeService.GetBundledThemeArchivePaths().Returns([]); + _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.From(Result.Updated)); + + // Act + await StartAndWaitForExecutionAsync(CreateSut()); + + // Assert + await _mockThemeRepository.Received(1).UpdateAsync( + Arg.Is(candidate => candidate.ThemeId == "default-theme" && candidate.IsCurrent == true), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [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()).Returns(Result.From>([firstTheme, defaultTheme])); + _mockThemeService.DefaultThemeId.Returns("default-theme"); + _mockThemeService.GetBundledThemeArchivePaths().Returns([]); + _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.From(Result.Updated)); + + // Act + await StartAndWaitForExecutionAsync(CreateSut()); + + // Assert + await _mockThemeRepository.Received(1).UpdateAsync( + Arg.Is(candidate => candidate.ThemeId == "default-theme" && candidate.IsCurrent == true), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [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()).Returns(Result.From>([theme])); + _mockThemeService.GetBundledThemeArchivePaths().Returns([]); + + // Act + await StartAndWaitForExecutionAsync(CreateSut()); + + // Assert + await _mockThemeRepository.DidNotReceiveWithAnyArgs().UpdateAsync(default!, Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + /// + /// Invokes the protected of the job and awaits its completion. + /// + /// The job to execute. + 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; + } + + /// + /// Creates the system under test wired to the mocked dependencies. + /// + /// The created job instance. + private ThemeDetectionSyncJob CreateSut() + { + return new ThemeDetectionSyncJob(_mockServiceScopeFactory, _mockThemeService, _mockLogger); + } + + /// + /// Writes a bundled theme archive file into the per-test temporary directory. + /// + /// The theme id of the bundled archive. + /// The path of the written archive. + 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; + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeMimeTypesTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeMimeTypesTests.cs new file mode 100644 index 00000000..8600181e --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeMimeTypesTests.cs @@ -0,0 +1,81 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Infrastructure.Core.Themes; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.Themes; + +/// +/// Contains unit tests for the class. +/// +[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); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeServiceTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeServiceTests.cs new file mode 100644 index 00000000..fd609d97 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeServiceTests.cs @@ -0,0 +1,1336 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Models.DTO.Themes; +using Lumina.Domain.Common.Primitives; +using Lumina.Infrastructure.Common.Models.DTO.Configuration; +using Lumina.Infrastructure.Core.Themes; +using Lumina.Infrastructure.Fixtures.Common.Models.DTO.Configuration; +using Lumina.Infrastructure.Fixtures.Core.Themes; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.IO.Compression; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.Themes; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ThemeServiceTests : IDisposable +{ + private const string DEFAULT_TEMPLATE = "default template"; + private const string HOME_TEMPLATE = "home template"; + private const string LIBRARY_TEMPLATE = "library template"; + + private readonly string _testRootPath; + private readonly ThemeEngineOptionsDto _options; + private readonly ThemeService _sut; + private readonly ThemePackFixture _themePackFixture = new(); + private readonly ThemeEngineOptionsDtoFixture _themeEngineOptionsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public ThemeServiceTests() + { + _testRootPath = Path.Combine(Path.GetTempPath(), $"lumina-themes-{Guid.NewGuid():N}"); + Directory.CreateDirectory(_testRootPath); + _options = _themeEngineOptionsDtoFixture.Create( + storagePath: Path.Combine(_testRootPath, "themes"), + bundledThemesPath: Path.Combine(_testRootPath, "bundled"), + defaultThemeId: "lumina-default", + maxArchiveBytes: 8 * 1024 * 1024, + maxExpandedBytes: 24 * 1024 * 1024, + maxSingleFileBytes: 6 * 1024 * 1024, + maxEntries: 250, + allowThemeScripts: false); + _sut = CreateSut(_options); + } + + /// + /// Cleans up the temporary storage used by the tests. + /// + 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 void AllowThemeScripts_WhenConfiguredFalse_ShouldReturnFalse() + { + // Arrange + ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create( + storagePath: Path.Combine(_testRootPath, "themes"), + bundledThemesPath: Path.Combine(_testRootPath, "bundled"), + defaultThemeId: "lumina-default", + maxArchiveBytes: 8 * 1024 * 1024, + maxExpandedBytes: 24 * 1024 * 1024, + maxSingleFileBytes: 6 * 1024 * 1024, + maxEntries: 250, + allowThemeScripts: false); + options.AllowThemeScripts = false; + ThemeService sut = CreateSut(options); + + // Act + bool result = sut.AllowThemeScripts; + + // Assert + Assert.False(result); + } + + [Fact] + public void AllowThemeScripts_WhenConfiguredTrue_ShouldReturnTrue() + { + // Arrange + ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create( + storagePath: Path.Combine(_testRootPath, "themes"), + bundledThemesPath: Path.Combine(_testRootPath, "bundled"), + defaultThemeId: "lumina-default", + maxArchiveBytes: 8 * 1024 * 1024, + maxExpandedBytes: 24 * 1024 * 1024, + maxSingleFileBytes: 6 * 1024 * 1024, + maxEntries: 250, + allowThemeScripts: false); + options.AllowThemeScripts = true; + ThemeService sut = CreateSut(options); + + // Act + bool result = sut.AllowThemeScripts; + + // Assert + Assert.True(result); + } + + [Fact] + public void MaxArchiveBytes_WhenConfigured_ShouldReturnConfiguredValue() + { + // Arrange + ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create( + storagePath: Path.Combine(_testRootPath, "themes"), + bundledThemesPath: Path.Combine(_testRootPath, "bundled"), + defaultThemeId: "lumina-default", + maxArchiveBytes: 8 * 1024 * 1024, + maxExpandedBytes: 24 * 1024 * 1024, + maxSingleFileBytes: 6 * 1024 * 1024, + maxEntries: 250, + allowThemeScripts: false); + options.MaxArchiveBytes = 12345; + ThemeService sut = CreateSut(options); + + // Act + long result = sut.MaxArchiveBytes; + + // Assert + Assert.Equal(12345, result); + } + + [Fact] + public void DefaultThemeId_WhenConfigured_ShouldReturnConfiguredValue() + { + // Arrange + ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create( + storagePath: Path.Combine(_testRootPath, "themes"), + bundledThemesPath: Path.Combine(_testRootPath, "bundled"), + defaultThemeId: "lumina-default", + maxArchiveBytes: 8 * 1024 * 1024, + maxExpandedBytes: 24 * 1024 * 1024, + maxSingleFileBytes: 6 * 1024 * 1024, + maxEntries: 250, + allowThemeScripts: false); + options.DefaultThemeId = "custom-default"; + ThemeService sut = CreateSut(options); + + // Act + string result = sut.DefaultThemeId; + + // Assert + Assert.Equal("custom-default", result); + } + + [Fact] + public void GetBundledThemeArchivePaths_WhenBundledDirectoryDoesNotExist_ShouldReturnEmptyList() + { + // Arrange + // the bundled directory of the default options never exists + + // Act + IReadOnlyList result = _sut.GetBundledThemeArchivePaths(); + + // Assert + Assert.Empty(result); + } + + [Fact] + public void GetBundledThemeArchivePaths_WhenBundledDirectoryContainsZips_ShouldReturnSortedZipPaths() + { + // Arrange + string bundledPath = Path.Combine(_testRootPath, "bundled"); + Directory.CreateDirectory(bundledPath); + File.WriteAllBytes(Path.Combine(bundledPath, "zeta.zip"), _themePackFixture.Create()); + File.WriteAllBytes(Path.Combine(bundledPath, "alpha.zip"), _themePackFixture.Create()); + File.WriteAllBytes(Path.Combine(bundledPath, "notes.txt"), Encoding.UTF8.GetBytes("not a theme archive")); + + // Act + IReadOnlyList result = _sut.GetBundledThemeArchivePaths(); + + // Assert + Assert.Equal(2, result.Count); + Assert.Equal(Path.Combine(bundledPath, "alpha.zip"), result[0]); + Assert.Equal(Path.Combine(bundledPath, "zeta.zip"), result[1]); + } + + [Fact] + public async Task HasThemePack_WhenThemeIsInstalled_ShouldReturnTrue() + { + // Arrange + await InstallValidThemeAsync(_themePackFixture.Create()); + + // Act + bool result = _sut.HasThemePack("test-theme"); + + // Assert + Assert.True(result); + } + + [Fact] + public void HasThemePack_WhenThemeIsNotInstalled_ShouldReturnFalse() + { + // Arrange + // nothing is installed + + // Act + bool result = _sut.HasThemePack("test-theme"); + + // Assert + Assert.False(result); + } + + [Fact] + public void HasThemePack_WhenThemeDirectoryExistsButManifestIsMissing_ShouldReturnFalse() + { + // Arrange + Directory.CreateDirectory(Path.Combine(_options.StoragePath, "test-theme")); + + // Act + bool result = _sut.HasThemePack("test-theme"); + + // Assert + Assert.False(result); + } + + [Fact] + public async Task InstallAsync_WhenArchiveIsValid_ShouldExtractThemeAndReturnManifest() + { + // Arrange + byte[] archive = _themePackFixture.Create(defaultTemplateContent: DEFAULT_TEMPLATE); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("test-theme", result.Value.Id); + Assert.Equal("Test Theme", result.Value.Name); + Assert.True(File.Exists(Path.Combine(_options.StoragePath, "test-theme", "theme.json"))); + Assert.True(File.Exists(Path.Combine(_options.StoragePath, "test-theme", "templates", "default.html"))); + Assert.True(File.Exists(Path.Combine(_options.StoragePath, "test-theme", "assets", "preview.png"))); + } + + [Fact] + public async Task InstallAsync_WhenThemeIsAlreadyInstalled_ShouldReplaceExistingThemeFiles() + { + // Arrange + byte[] firstArchive = _themePackFixture.Create(defaultTemplateContent: "first version"); + byte[] secondArchive = _themePackFixture.Create(defaultTemplateContent: "second version"); + + // Act + await InstallValidThemeAsync(firstArchive); + await InstallValidThemeAsync(secondArchive); + Result templateResult = await _sut.GetTemplateAsync("test-theme", "unknown-page", CancellationToken.None); + + // Assert + Assert.True(templateResult.IsSuccess); + Assert.Equal("second version", templateResult.Value); + string[] themeDirectories = [.. Directory.GetDirectories(_options.StoragePath).Where(path => Path.GetFileName(path) != ".staging")]; + Assert.Single(themeDirectories); + Assert.Equal("test-theme", Path.GetFileName(themeDirectories[0])); + } + + [Fact] + public async Task InstallAsync_WhenArchiveExceedsMaxArchiveBytes_ShouldReturnArchiveTooLargeError() + { + // Arrange + ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create( + storagePath: Path.Combine(_testRootPath, "themes"), + bundledThemesPath: Path.Combine(_testRootPath, "bundled"), + defaultThemeId: "lumina-default", + maxArchiveBytes: 8 * 1024 * 1024, + maxExpandedBytes: 24 * 1024 * 1024, + maxSingleFileBytes: 6 * 1024 * 1024, + maxEntries: 250, + allowThemeScripts: false); + options.MaxArchiveBytes = 128; + ThemeService sut = CreateSut(options); + byte[] archive = _themePackFixture.Create(); + + // Act + Result result = await sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Archive.TooLarge", result.FirstError.Code); + Assert.False(sut.HasThemePack("test-theme")); + } + + [Fact] + public async Task InstallAsync_WhenArchiveStreamIsEmpty_ShouldReturnPackageInvalidError() + { + // Arrange + using MemoryStream emptyStream = new(); + + // Act + Result result = await _sut.InstallAsync(emptyStream, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); + Assert.Contains("empty", result.FirstError.Description); + } + + [Fact] + public async Task InstallAsync_WhenArchiveContainsNoEntries_ShouldReturnPackageInvalidError() + { + // Arrange + byte[] archive = _themePackFixture.CreateArchive(); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); + Assert.Contains("no files", result.FirstError.Description); + } + + [Fact] + public async Task InstallAsync_WhenArchiveIsNotAZip_ShouldReturnThemeArchiveNotReadable() + { + // Arrange + byte[] archive = Encoding.UTF8.GetBytes("this is not a valid zip archive"); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("ThemeArchiveNotReadable", result.FirstError.Description); + Assert.False(_sut.HasThemePack("test-theme")); + } + + [Fact] + public async Task InstallAsync_WhenArchiveContainsPathTraversalEntry_ShouldReturnPackageInvalidError() + { + // Arrange + string manifestJson = _themePackFixture.CreateManifestJson(); + byte[] archive = _themePackFixture.CreateArchive( + new("theme.json", manifestJson), + new("templates/default.html", DEFAULT_TEMPLATE), + new("../evil.txt", "should not escape the package")); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); + Assert.False(_sut.HasThemePack("test-theme")); + } + + [Fact] + public async Task InstallAsync_WhenArchiveContainsBackslashPathEntry_ShouldReturnPackageInvalidError() + { + // Arrange + string manifestJson = _themePackFixture.CreateManifestJson(); + byte[] archive = _themePackFixture.CreateArchive( + new("theme.json", manifestJson), + new("templates/default.html", DEFAULT_TEMPLATE), + new("assets\\..\\evil.txt", "should not escape the package")); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); + } + + [Fact] + public async Task InstallAsync_WhenArchiveEntryIsOutsideAllowedLocations_ShouldReturnPackageInvalidError() + { + // Arrange + string manifestJson = _themePackFixture.CreateManifestJson(); + byte[] archive = _themePackFixture.CreateArchive( + new("theme.json", manifestJson), + new("templates/default.html", DEFAULT_TEMPLATE), + new("notes/readme.txt", "files must live under templates or assets")); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); + Assert.Contains("outside the allowed", result.FirstError.Description); + } + + [Fact] + public async Task InstallAsync_WhenArchiveContainsSymbolicLinkEntry_ShouldReturnPackageInvalidError() + { + // Arrange + string manifestJson = _themePackFixture.CreateManifestJson(); + byte[] archive = _themePackFixture.CreateArchive( + new("theme.json", manifestJson), + new("templates/default.html", DEFAULT_TEMPLATE), + new("assets/link.png", "symlink target", UnixFileType: 0xA000)); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); + Assert.Contains("Symbolic links", result.FirstError.Description); + } + + [Fact] + public async Task InstallAsync_WhenArchiveContainsDuplicateEntryPaths_ShouldReturnPackageInvalidError() + { + // Arrange + string manifestJson = _themePackFixture.CreateManifestJson(); + byte[] archive = _themePackFixture.CreateArchive( + new("theme.json", manifestJson), + new("templates/default.html", DEFAULT_TEMPLATE), + new("templates/default.html", "duplicate")); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); + Assert.Contains("duplicate path", result.FirstError.Description); + } + + [Fact] + public async Task InstallAsync_WhenArchiveExceedsMaxEntries_ShouldReturnTooManyEntriesError() + { + // Arrange + ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create( + storagePath: Path.Combine(_testRootPath, "themes"), + bundledThemesPath: Path.Combine(_testRootPath, "bundled"), + defaultThemeId: "lumina-default", + maxArchiveBytes: 8 * 1024 * 1024, + maxExpandedBytes: 24 * 1024 * 1024, + maxSingleFileBytes: 6 * 1024 * 1024, + maxEntries: 250, + allowThemeScripts: false); + options.MaxEntries = 2; + ThemeService sut = CreateSut(options); + byte[] archive = _themePackFixture.Create(); + + // Act + Result result = await sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Archive.TooManyEntries", result.FirstError.Code); + } + + [Fact] + public async Task InstallAsync_WhenArchiveFileExceedsMaxSingleFileBytes_ShouldReturnFileTooLargeError() + { + // Arrange + ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create( + storagePath: Path.Combine(_testRootPath, "themes"), + bundledThemesPath: Path.Combine(_testRootPath, "bundled"), + defaultThemeId: "lumina-default", + maxArchiveBytes: 8 * 1024 * 1024, + maxExpandedBytes: 24 * 1024 * 1024, + maxSingleFileBytes: 6 * 1024 * 1024, + maxEntries: 250, + allowThemeScripts: false); + options.MaxSingleFileBytes = 10; + ThemeService sut = CreateSut(options); + string manifestJson = _themePackFixture.CreateManifestJson(); + byte[] archive = _themePackFixture.CreateArchive( + new("theme.json", manifestJson), + new("templates/default.html", new string('a', 64))); + + // Act + Result result = await sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.File.TooLarge", result.FirstError.Code); + } + + [Fact] + public async Task InstallAsync_WhenExpandedSizeExceedsMaxExpandedBytes_ShouldReturnExpandedTooLargeError() + { + // Arrange + ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create( + storagePath: Path.Combine(_testRootPath, "themes"), + bundledThemesPath: Path.Combine(_testRootPath, "bundled"), + defaultThemeId: "lumina-default", + maxArchiveBytes: 8 * 1024 * 1024, + maxExpandedBytes: 24 * 1024 * 1024, + maxSingleFileBytes: 6 * 1024 * 1024, + maxEntries: 250, + allowThemeScripts: false); + options.MaxSingleFileBytes = 400; + options.MaxExpandedBytes = 300; + ThemeService sut = CreateSut(options); + byte[] archive = _themePackFixture.CreateArchive( + new("templates/default.html", new string('a', 200)), + new("templates/other.html", new string('b', 200))); + + // Act + Result result = await sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Archive.ExpandedTooLarge", result.FirstError.Code); + } + + [Fact] + public async Task InstallAsync_WhenSchemaVersionIsUnsupported_ShouldReturnPackageInvalidError() + { + // Arrange + byte[] archive = _themePackFixture.Create(schemaVersion: 2); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + AssertPackageInvalid(result, "schemaVersion"); + } + + [Fact] + public async Task InstallAsync_WhenThemeIdIsNotKebabCase_ShouldReturnPackageInvalidError() + { + // Arrange + byte[] archive = _themePackFixture.Create(themeId: "Test_Theme"); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + AssertPackageInvalid(result, "kebab-case"); + } + + [Fact] + public async Task InstallAsync_WhenThemeIdIsTooLong_ShouldReturnPackageInvalidError() + { + // Arrange + string longThemeId = string.Join('-', Enumerable.Repeat("a", 33)); + byte[] archive = _themePackFixture.Create(themeId: longThemeId); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + AssertPackageInvalid(result, "kebab-case"); + } + + [Fact] + public async Task InstallAsync_WhenNameIsMissing_ShouldReturnPackageInvalidError() + { + // Arrange + byte[] archive = _themePackFixture.Create(name: string.Empty); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + AssertPackageInvalid(result, "name"); + } + + [Fact] + public async Task InstallAsync_WhenDescriptionIsMissing_ShouldReturnPackageInvalidError() + { + // Arrange + byte[] archive = _themePackFixture.Create(description: string.Empty); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + AssertPackageInvalid(result, "description"); + } + + [Fact] + public async Task InstallAsync_WhenAuthorIsMissing_ShouldReturnPackageInvalidError() + { + // Arrange + byte[] archive = _themePackFixture.Create(author: string.Empty); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + AssertPackageInvalid(result, "author"); + } + + [Fact] + public async Task InstallAsync_WhenVersionIsMissing_ShouldReturnPackageInvalidError() + { + // Arrange + byte[] archive = _themePackFixture.Create(version: string.Empty); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + AssertPackageInvalid(result, "version"); + } + + [Fact] + public async Task InstallAsync_WhenVersionIsNotSemanticVersion_ShouldReturnPackageInvalidError() + { + // Arrange + byte[] archive = _themePackFixture.Create(version: "1.0"); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + AssertPackageInvalid(result, "semantic version"); + } + + [Fact] + public async Task InstallAsync_WhenManifestDeclaresNoTemplates_ShouldReturnPackageInvalidError() + { + // Arrange + byte[] archive = _themePackFixture.Create(templates: new Dictionary(StringComparer.OrdinalIgnoreCase)); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + AssertPackageInvalid(result, "between 1 and 32"); + } + + [Fact] + public async Task InstallAsync_WhenManifestDeclaresTooManyTemplates_ShouldReturnPackageInvalidError() + { + // Arrange + Dictionary manyTemplates = new(StringComparer.OrdinalIgnoreCase); + for (int index = 0; index < 33; index++) + manyTemplates[$"template-{index}"] = $"templates/template-{index}.html"; + byte[] archive = _themePackFixture.Create(templates: manyTemplates); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + AssertPackageInvalid(result, "between 1 and 32"); + } + + [Fact] + public async Task InstallAsync_WhenTemplateKeyIsInvalid_ShouldReturnPackageInvalidError() + { + // Arrange + Dictionary templates = new(StringComparer.OrdinalIgnoreCase) + { + ["default"] = "templates/default.html", + ["Bad Key"] = "templates/bad-key.html" + }; + byte[] archive = _themePackFixture.Create(templates: templates); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + AssertPackageInvalid(result, "Template key"); + } + + [Fact] + public async Task InstallAsync_WhenTemplatePathIsOutsideTemplatesDirectory_ShouldReturnPackageInvalidError() + { + // Arrange + string manifestJson = _themePackFixture.CreateManifestJson(templates: new Dictionary(StringComparer.OrdinalIgnoreCase) + { + ["default"] = "assets/not-a-template.html" + }); + byte[] archive = _themePackFixture.CreateArchive( + new("theme.json", manifestJson), + new("assets/not-a-template.html", DEFAULT_TEMPLATE)); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + AssertPackageInvalid(result, "under templates"); + } + + [Fact] + public async Task InstallAsync_WhenTemplateFileIsMissing_ShouldReturnPackageInvalidError() + { + // Arrange + string manifestJson = _themePackFixture.CreateManifestJson(templates: new Dictionary(StringComparer.OrdinalIgnoreCase) + { + ["default"] = "templates/missing.html" + }); + byte[] archive = _themePackFixture.CreateArchive(new ThemeArchiveEntry("theme.json", manifestJson)); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + AssertPackageInvalid(result, "missing file"); + } + + [Fact] + public async Task InstallAsync_WhenManifestLacksDefaultTemplate_ShouldReturnPackageInvalidError() + { + // Arrange + Dictionary templates = new(StringComparer.OrdinalIgnoreCase) + { + ["home"] = "templates/home.html" + }; + byte[] archive = _themePackFixture.Create(templates: templates); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + AssertPackageInvalid(result, "default"); + } + + [Fact] + public async Task InstallAsync_WhenPreviewIsOutsideAssetsDirectory_ShouldReturnPackageInvalidError() + { + // Arrange + byte[] archive = _themePackFixture.Create(preview: "templates/default.html"); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + AssertPackageInvalid(result, "preview"); + } + + [Fact] + public async Task InstallAsync_WhenPreviewFileIsMissing_ShouldReturnPackageInvalidError() + { + // Arrange + byte[] archive = _themePackFixture.Create(preview: "assets/missing.png", includePreviewAsset: false); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + AssertPackageInvalid(result, "preview"); + } + + [Fact] + public async Task InstallAsync_WhenManifestIsNotValidJson_ShouldReturnInvalidJsonError() + { + // Arrange + byte[] archive = _themePackFixture.CreateArchive(new ThemeArchiveEntry("theme.json", "this is not json")); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Manifest.InvalidJson", result.FirstError.Code); + } + + [Fact] + public async Task InstallAsync_WhenManifestExceedsMaximumSize_ShouldReturnManifestTooLargeError() + { + // Arrange + byte[] archive = _themePackFixture.Create(description: new string('a', 70 * 1024)); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Manifest.TooLarge", result.FirstError.Code); + } + + [Fact] + public async Task ReadManifestFromArchiveAsync_WhenArchiveIsValid_ShouldReturnManifest() + { + // Arrange + string archivePath = Path.Combine(_testRootPath, "valid-theme.zip"); + File.WriteAllBytes(archivePath, _themePackFixture.Create(themeId: "manifest-theme")); + + // Act + Result result = await _sut.ReadManifestFromArchiveAsync(archivePath, CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("manifest-theme", result.Value.Id); + } + + [Fact] + public async Task ReadManifestFromArchiveAsync_WhenManifestEntryIsMissing_ShouldReturnPackageInvalidError() + { + // Arrange + string archivePath = Path.Combine(_testRootPath, "no-manifest.zip"); + File.WriteAllBytes(archivePath, _themePackFixture.CreateArchive(new ThemeArchiveEntry("templates/default.html", DEFAULT_TEMPLATE))); + + // Act + Result result = await _sut.ReadManifestFromArchiveAsync(archivePath, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); + Assert.Contains("missing theme.json", result.FirstError.Description); + } + + [Fact] + public async Task ReadManifestFromArchiveAsync_WhenManifestIsNotValidJson_ShouldReturnInvalidJsonError() + { + // Arrange + string archivePath = Path.Combine(_testRootPath, "invalid-json.zip"); + File.WriteAllBytes(archivePath, _themePackFixture.CreateArchive(new ThemeArchiveEntry("theme.json", "not json"))); + + // Act + Result result = await _sut.ReadManifestFromArchiveAsync(archivePath, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Manifest.InvalidJson", result.FirstError.Code); + } + + [Fact] + public async Task ReadManifestFromArchiveAsync_WhenArchiveIsNotAZip_ShouldReturnThemeArchiveNotReadable() + { + // Arrange + string archivePath = Path.Combine(_testRootPath, "not-a-zip.zip"); + File.WriteAllBytes(archivePath, Encoding.UTF8.GetBytes("plain text file")); + + // Act + Result result = await _sut.ReadManifestFromArchiveAsync(archivePath, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("ThemeArchiveNotReadable", result.FirstError.Description); + } + + [Fact] + public async Task ReadManifestFromArchiveAsync_WhenArchiveFileDoesNotExist_ShouldReturnThemeFilesUnreadable() + { + // Arrange + string archivePath = Path.Combine(_testRootPath, "does-not-exist.zip"); + + // Act + Result result = await _sut.ReadManifestFromArchiveAsync(archivePath, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("ThemeFilesUnreadable", result.FirstError.Description); + } + + [Fact] + public async Task DeleteAsync_WhenThemeIsInstalled_ShouldRemoveThemePack() + { + // Arrange + await InstallValidThemeAsync(_themePackFixture.Create()); + + // Act + Result result = await _sut.DeleteAsync("test-theme", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.False(_sut.HasThemePack("test-theme")); + Assert.False(Directory.Exists(Path.Combine(_options.StoragePath, "test-theme"))); + } + + [Fact] + public async Task DeleteAsync_WhenThemeIsNotInstalled_ShouldReturnSuccess() + { + // Arrange + // nothing is installed + + // Act + Result result = await _sut.DeleteAsync("test-theme", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + } + + [Fact] + public async Task LoadManifestAsync_WhenThemeIsNotInstalled_ShouldReturnThemeFilesUnreadable() + { + // Arrange + // nothing is installed + + // Act + Result result = await _sut.LoadManifestAsync("test-theme", CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("ThemeFilesUnreadable", result.FirstError.Description); + } + + [Fact] + public async Task LoadManifestAsync_WhenThemeIsInstalled_ShouldReturnManifest() + { + // Arrange + await InstallValidThemeAsync(_themePackFixture.Create(themeId: "loaded-theme")); + + // Act + Result result = await _sut.LoadManifestAsync("loaded-theme", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("loaded-theme", result.Value.Id); + Assert.Equal("Test Theme", result.Value.Name); + } + + [Fact] + public async Task GetTemplateAsync_WhenPageKeyHasExplicitManifestTemplate_ShouldReturnExplicitTemplate() + { + // Arrange + byte[] archive = CreateThemeWithTemplates(); + await InstallValidThemeAsync(archive); + + // Act + Result result = await _sut.GetTemplateAsync("test-theme", "home", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal(HOME_TEMPLATE, result.Value); + } + + [Fact] + public async Task GetTemplateAsync_WhenPageKeyHasNoExplicitTemplate_ShouldUseMirroredTemplate() + { + // Arrange + byte[] archive = CreateThemeWithTemplates(); + await InstallValidThemeAsync(archive); + + // Act + Result result = await _sut.GetTemplateAsync("test-theme", "library", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal(LIBRARY_TEMPLATE, result.Value); + } + + [Fact] + public async Task GetTemplateAsync_WhenMirroredTemplateIsMissing_ShouldWalkUpToParentScope() + { + // Arrange + byte[] archive = CreateThemeWithTemplates(); + await InstallValidThemeAsync(archive); + + // Act + Result result = await _sut.GetTemplateAsync("test-theme", "library/book", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal(LIBRARY_TEMPLATE, result.Value); + } + + [Fact] + public async Task GetTemplateAsync_WhenNoTemplateResolves_ShouldFallBackToDefaultTemplate() + { + // Arrange + byte[] archive = CreateThemeWithTemplates(); + await InstallValidThemeAsync(archive); + + // Act + Result result = await _sut.GetTemplateAsync("test-theme", "unknown-page", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal(DEFAULT_TEMPLATE, result.Value); + } + + [Theory] + [InlineData("../secret")] // parent scope traversal attempt + [InlineData("/etc/passwd")] // rooted path attempt + [InlineData("templates//nested")] // empty segment attempt + public async Task GetTemplateAsync_WhenPageKeyAttemptsToEscapeTheThemePack_ShouldFallBackToDefaultTemplate(string pageKey) + { + // Arrange + byte[] archive = CreateThemeWithTemplates(); + await InstallValidThemeAsync(archive); + + // Act + Result result = await _sut.GetTemplateAsync("test-theme", pageKey, CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal(DEFAULT_TEMPLATE, result.Value); + } + + [Fact] + public async Task GetTemplateAsync_WhenThemeIsNotInstalled_ShouldReturnThemeFilesUnreadable() + { + // Arrange + // nothing is installed + + // Act + Result result = await _sut.GetTemplateAsync("test-theme", "home", CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("ThemeFilesUnreadable", result.FirstError.Description); + } + + [Fact] + public async Task GetTemplateAsync_WhenManifestTemplateFileWasRemoved_ShouldReturnPackageInvalidError() + { + // Arrange + byte[] archive = CreateThemeWithTemplates(); + await InstallValidThemeAsync(archive); + File.Delete(Path.Combine(_options.StoragePath, "test-theme", "templates", "default.html")); + + // Act + Result result = await _sut.GetTemplateAsync("test-theme", "unknown-page", CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); + Assert.Contains("missing file", result.FirstError.Description); + } + + [Fact] + public async Task GetTemplateAsync_WhenMirroredTemplateFileWasRemoved_ShouldFallBackToDefaultTemplate() + { + // Arrange + byte[] archive = CreateThemeWithTemplates(); + await InstallValidThemeAsync(archive); + File.Delete(Path.Combine(_options.StoragePath, "test-theme", "templates", "library.html")); + + // Act + Result result = await _sut.GetTemplateAsync("test-theme", "library/book", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal(DEFAULT_TEMPLATE, result.Value); + } + + [Fact] + public async Task GetTemplateAsync_WhenScriptsAreDisabled_ShouldStripScriptElements() + { + // Arrange + byte[] archive = _themePackFixture.Create(defaultTemplateContent: "

safe content

"); + await InstallValidThemeAsync(archive); + + // Act + Result result = await _sut.GetTemplateAsync("test-theme", "unknown-page", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("

safe content

", result.Value); + } + + [Fact] + public async Task GetTemplateAsync_WhenScriptsAreEnabled_ShouldPreserveScriptElements() + { + // Arrange + ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create( + storagePath: Path.Combine(_testRootPath, "themes"), + bundledThemesPath: Path.Combine(_testRootPath, "bundled"), + defaultThemeId: "lumina-default", + maxArchiveBytes: 8 * 1024 * 1024, + maxExpandedBytes: 24 * 1024 * 1024, + maxSingleFileBytes: 6 * 1024 * 1024, + maxEntries: 250, + allowThemeScripts: false); + options.AllowThemeScripts = true; + ThemeService sut = CreateSut(options); + const string TEMPLATE_WITH_SCRIPT = "

safe content

"; + byte[] archive = _themePackFixture.Create(defaultTemplateContent: TEMPLATE_WITH_SCRIPT); + await InstallValidThemeAsync(archive, sut); + + // Act + Result result = await sut.GetTemplateAsync("test-theme", "unknown-page", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal(TEMPLATE_WITH_SCRIPT, result.Value); + } + + [Fact] + public async Task GetAssetAsync_WhenAssetExists_ShouldReturnFileBytesAndContentType() + { + // Arrange + byte[] archive = _themePackFixture.Create(additionalFiles: new Dictionary + { + ["assets/style.css"] = "body { color: red; }" + }); + await InstallValidThemeAsync(archive); + + // Act + Result result = await _sut.GetAssetAsync("test-theme", "assets/style.css", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("text/css", result.Value.ContentType); + Assert.Equal("body { color: red; }", Encoding.UTF8.GetString(result.Value.Bytes)); + } + + [Fact] + public async Task GetAssetAsync_WhenAssetPathIsOutsideAssetsDirectory_ShouldReturnPackageInvalidError() + { + // Arrange + byte[] archive = CreateThemeWithTemplates(); + await InstallValidThemeAsync(archive); + + // Act + Result result = await _sut.GetAssetAsync("test-theme", "templates/default.html", CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); + } + + [Fact] + public async Task GetAssetAsync_WhenAssetPathAttemptsTraversal_ShouldReturnPackageInvalidError() + { + // Arrange + byte[] archive = _themePackFixture.Create(); + await InstallValidThemeAsync(archive); + + // Act + Result result = await _sut.GetAssetAsync("test-theme", "../secret.txt", CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); + } + + [Fact] + public async Task GetAssetAsync_WhenAssetFileIsMissing_ShouldReturnThemeFilesUnreadable() + { + // Arrange + byte[] archive = _themePackFixture.Create(); + await InstallValidThemeAsync(archive); + + // Act + Result result = await _sut.GetAssetAsync("test-theme", "assets/missing.png", CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("ThemeFilesUnreadable", result.FirstError.Description); + } + + [Fact] + public async Task GetAssetAsync_WhenScriptsAreDisabledAndAssetIsJavaScript_ShouldReturnThemeFilesUnreadable() + { + // Arrange + byte[] archive = _themePackFixture.Create(additionalFiles: new Dictionary + { + ["assets/app.js"] = "console.log('hello');" + }); + await InstallValidThemeAsync(archive); + + // Act + Result result = await _sut.GetAssetAsync("test-theme", "assets/app.js", CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("ThemeFilesUnreadable", result.FirstError.Description); + } + + [Fact] + public async Task GetAssetAsync_WhenScriptsAreEnabledAndAssetIsJavaScript_ShouldReturnJavaScriptContentType() + { + // Arrange + ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create( + storagePath: Path.Combine(_testRootPath, "themes"), + bundledThemesPath: Path.Combine(_testRootPath, "bundled"), + defaultThemeId: "lumina-default", + maxArchiveBytes: 8 * 1024 * 1024, + maxExpandedBytes: 24 * 1024 * 1024, + maxSingleFileBytes: 6 * 1024 * 1024, + maxEntries: 250, + allowThemeScripts: false); + options.AllowThemeScripts = true; + ThemeService sut = CreateSut(options); + byte[] archive = _themePackFixture.Create(additionalFiles: new Dictionary + { + ["assets/app.js"] = "console.log('hello');" + }); + await InstallValidThemeAsync(archive, sut); + + // Act + Result result = await sut.GetAssetAsync("test-theme", "assets/app.js", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("application/javascript", result.Value.ContentType); + } + + [Fact] + public async Task BuildArchiveAsync_WhenThemeIsInstalled_ShouldReturnDownloadableZipArchive() + { + // Arrange + byte[] archive = _themePackFixture.Create(); + await InstallValidThemeAsync(archive); + + // Act + Result result = await _sut.BuildArchiveAsync("test-theme", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("test-theme.zip", result.Value.FileName); + Assert.Equal("application/zip", result.Value.ContentType); + using MemoryStream stream = new(result.Value.Bytes); + using ZipArchive rebuiltArchive = new(stream, ZipArchiveMode.Read); + Assert.Contains(rebuiltArchive.Entries, entry => entry.FullName == "theme.json"); + Assert.Contains(rebuiltArchive.Entries, entry => entry.FullName == "templates/default.html"); + } + + [Fact] + public async Task BuildArchiveAsync_WhenThemeIsNotInstalled_ShouldReturnThemeFilesUnreadable() + { + // Arrange + // nothing is installed + + // Act + Result result = await _sut.BuildArchiveAsync("test-theme", CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("ThemeFilesUnreadable", result.FirstError.Description); + } + + [Fact] + public async Task RestoreBundledThemeAsync_WhenBundledArchiveMatchesThemeId_ShouldInstallTheme() + { + // Arrange + string bundledPath = Path.Combine(_testRootPath, "bundled"); + Directory.CreateDirectory(bundledPath); + File.WriteAllBytes(Path.Combine(bundledPath, "bundled-theme.zip"), _themePackFixture.Create(themeId: "bundled-theme")); + + // Act + Result result = await _sut.RestoreBundledThemeAsync("bundled-theme", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.True(_sut.HasThemePack("bundled-theme")); + } + + [Fact] + public async Task RestoreBundledThemeAsync_WhenNoBundledArchiveMatches_ShouldReturnThemeFilesUnreadable() + { + // Arrange + string bundledPath = Path.Combine(_testRootPath, "bundled"); + Directory.CreateDirectory(bundledPath); + File.WriteAllBytes(Path.Combine(bundledPath, "other-theme.zip"), _themePackFixture.Create(themeId: "other-theme")); + + // Act + Result result = await _sut.RestoreBundledThemeAsync("bundled-theme", CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("ThemeFilesUnreadable", result.FirstError.Description); + } + + [Fact] + public async Task RestoreBundledThemeAsync_WhenBundledArchiveManifestIsInvalid_ShouldSkipArchiveAndReturnThemeFilesUnreadable() + { + // Arrange + string bundledPath = Path.Combine(_testRootPath, "bundled"); + Directory.CreateDirectory(bundledPath); + File.WriteAllBytes(Path.Combine(bundledPath, "broken.zip"), _themePackFixture.CreateArchive(new ThemeArchiveEntry("templates/default.html", DEFAULT_TEMPLATE))); + + // Act + Result result = await _sut.RestoreBundledThemeAsync("bundled-theme", CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("ThemeFilesUnreadable", result.FirstError.Description); + Assert.False(_sut.HasThemePack("bundled-theme")); + } + + /// + /// Creates a valid theme pack that declares the default, home and library templates and their files. + /// + /// The created theme pack ZIP archive. + private byte[] CreateThemeWithTemplates() + { + Dictionary templates = new(StringComparer.OrdinalIgnoreCase) + { + ["default"] = "templates/default.html", + ["home"] = "templates/home.html" + }; + + return _themePackFixture.Create( + templates: templates, + additionalFiles: new Dictionary + { + ["templates/library.html"] = LIBRARY_TEMPLATE + }); + } + + /// + /// Installs the provided theme archive using the provided service and asserts that the install succeeds. + /// + /// The theme pack ZIP archive to install. + /// The service to install with, defaults to the shared system under test. + /// The task representing the asynchronous operation. + private async Task InstallValidThemeAsync(byte[] archive, ThemeService? service = null) + { + ThemeService themeService = service ?? _sut; + using MemoryStream stream = new(archive); + Result result = await themeService.InstallAsync(stream, CancellationToken.None); + Assert.True(result.IsSuccess, result.Match( + success => string.Empty, + errors => $"Expected a successful install but got: {errors.First().Code}: {errors.First().Description}")); + } + + /// + /// Asserts that the result is a package invalid failure whose description contains the provided fragment. + /// + /// The result to assert on. + /// The fragment the error description must contain. + private static void AssertPackageInvalid(Result result, string expectedDescriptionFragment) + { + Assert.True(result.IsFailure); + Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); + Assert.Contains(expectedDescriptionFragment, result.FirstError.Description); + } + + /// + /// Creates a instance using the provided options. + /// + /// The theme engine options to configure the service with. + /// The created service. + private static ThemeService CreateSut(ThemeEngineOptionsDto options) + { + ILogger logger = Substitute.For>(); + return new ThemeService(Options.Create(options), logger); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Management/DeleteTheme/DeleteThemeEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Management/DeleteTheme/DeleteThemeEndpointTests.cs new file mode 100644 index 00000000..18173544 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Management/DeleteTheme/DeleteThemeEndpointTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteThemeEndpointTests +{ + private readonly Application.Common.CQRS.ICommandHandler> _mockHandler; + private readonly DeleteThemeEndpoint _sut; + private readonly DeleteThemeRequestFixture _deleteThemeRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public DeleteThemeEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnNoContentResult() + { + // Arrange + DeleteThemeRequest request = _deleteThemeRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Success)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Assert.IsType(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(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType(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(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType(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(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType(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(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(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(), Arg.Any()) + .Returns(Result.From(Result.Success)); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => command.ThemeId == request.ThemeId), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + DeleteThemeRequest request = _deleteThemeRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(Result.Success); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointTests.cs new file mode 100644 index 00000000..65fe85bb --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class InstallThemeEndpointTests +{ + private readonly Application.Common.CQRS.ICommandHandler> _mockHandler; + private readonly InstallThemeEndpoint _sut; + private readonly ThemeResponseFixture _themeResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public InstallThemeEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenArchiveUploaded_ShouldReturnOkResultWithInstalledTheme() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + ThemeResponse expectedResponse = _themeResponseFixture.Create(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + ConfigureFormWithArchive([1, 2, 3, 4], "theme-pack.zip"); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(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(), Arg.Any()) + .Returns(Result.From(_themeResponseFixture.Create())); + ConfigureFormWithArchive(content, fileName); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(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(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + ConfigureFormWithoutFiles(); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, okResult.Value); + await _mockHandler.Received(1).HandleAsync( + Arg.Is(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(), Arg.Any()) + .Returns(expectedError); + ConfigureFormWithArchive([1, 2, 3, 4], "theme-pack.zip"); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType(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 operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(_themeResponseFixture.Create()); + }, callInfo.Arg())); + ConfigureFormWithArchive([1, 2, 3, 4], "theme-pack.zip"); + + // Act + Task operationTask = _sut.ExecuteAsync(EmptyRequest.Instance, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => 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(new FormFeature(form)); + } + + private void ConfigureFormWithoutFiles() + { + IFormCollection form = new FormCollection([]); + _sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test"; + _sut.HttpContext.Features.Set(new FormFeature(form)); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Management/SetCurrentTheme/SetCurrentThemeEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Management/SetCurrentTheme/SetCurrentThemeEndpointTests.cs new file mode 100644 index 00000000..301621b3 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Management/SetCurrentTheme/SetCurrentThemeEndpointTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SetCurrentThemeEndpointTests +{ + private readonly Application.Common.CQRS.ICommandHandler> _mockHandler; + private readonly SetCurrentThemeEndpoint _sut; + private readonly SetCurrentThemeRequestFixture _setCurrentThemeRequestFixture = new(); + private readonly ThemeResponseFixture _themeResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public SetCurrentThemeEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_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(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(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(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType(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(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType(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(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(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(), Arg.Any()) + .Returns(Result.From(_themeResponseFixture.Create())); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => command.ThemeId == request.ThemeId), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + SetCurrentThemeRequest request = _setCurrentThemeRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(_themeResponseFixture.Create()); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetCurrentTheme/GetCurrentThemeEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetCurrentTheme/GetCurrentThemeEndpointTests.cs new file mode 100644 index 00000000..e9cedbb9 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetCurrentTheme/GetCurrentThemeEndpointTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetCurrentThemeEndpointTests +{ + private readonly IQueryHandler> _mockHandler; + private readonly GetCurrentThemeEndpoint _sut; + private readonly ThemeResponseFixture _themeResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetCurrentThemeEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithCurrentTheme() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + ThemeResponse expectedResponse = _themeResponseFixture.Create(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(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(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType(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(), Arg.Any()) + .Returns(Result.From(_themeResponseFixture.Create())); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query != null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(_themeResponseFixture.Create()); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(EmptyRequest.Instance, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemeArchive/GetThemeArchiveEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemeArchive/GetThemeArchiveEndpointTests.cs new file mode 100644 index 00000000..97a35cd2 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemeArchive/GetThemeArchiveEndpointTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetThemeArchiveEndpointTests +{ + private readonly IQueryHandler> _mockHandler; + private readonly GetThemeArchiveEndpoint _sut; + private readonly GetThemeArchiveRequestFixture _getThemeArchiveRequestFixture = new(); + private readonly ThemeArchiveResponseFixture _themeArchiveResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetThemeArchiveEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_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(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + FileContentHttpResult fileResult = Assert.IsType(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(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType(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(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(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(), Arg.Any()) + .Returns(Result.From(_themeArchiveResponseFixture.Create())); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query.ThemeId == request.ThemeId), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetThemeArchiveRequest request = _getThemeArchiveRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(_themeArchiveResponseFixture.Create()); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemeAsset/GetThemeAssetEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemeAsset/GetThemeAssetEndpointTests.cs new file mode 100644 index 00000000..66443e2f --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemeAsset/GetThemeAssetEndpointTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetThemeAssetEndpointTests +{ + private readonly IQueryHandler> _mockHandler; + private readonly GetThemeAssetEndpoint _sut; + private readonly GetThemeAssetRequestFixture _getThemeAssetRequestFixture = new(); + private readonly ThemeAssetResponseFixture _themeAssetResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetThemeAssetEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_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(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + FileContentHttpResult fileResult = Assert.IsType(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(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType(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(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(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(), Arg.Any()) + .Returns(Result.From(_themeAssetResponseFixture.Create())); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(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 operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(_themeAssetResponseFixture.Create()); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemeSettings/GetThemeSettingsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemeSettings/GetThemeSettingsEndpointTests.cs new file mode 100644 index 00000000..ab0e92d8 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemeSettings/GetThemeSettingsEndpointTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetThemeSettingsEndpointTests +{ + private readonly IQueryHandler> _mockHandler; + private readonly GetThemeSettingsEndpoint _sut; + private readonly ThemeSettingsResponseFixture _themeSettingsResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetThemeSettingsEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithThemeSettings() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + ThemeSettingsResponse expectedResponse = _themeSettingsResponseFixture.Create(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(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(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType(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(), Arg.Any()) + .Returns(Result.From(_themeSettingsResponseFixture.Create())); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query != null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(_themeSettingsResponseFixture.Create()); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(EmptyRequest.Instance, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpointTests.cs new file mode 100644 index 00000000..80a3de9e --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpointTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetThemeTemplateEndpointTests +{ + private readonly IQueryHandler> _mockHandler; + private readonly GetThemeTemplateEndpoint _sut; + private readonly GetThemeTemplateRequestFixture _getThemeTemplateRequestFixture = new(); + private readonly ThemeTemplateResponseFixture _themeTemplateResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetThemeTemplateEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_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(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(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(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType(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(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(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(), Arg.Any()) + .Returns(Result.From(_themeTemplateResponseFixture.Create())); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(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 operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(_themeTemplateResponseFixture.Create()); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemes/GetThemesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemes/GetThemesEndpointTests.cs new file mode 100644 index 00000000..7af2cec2 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemes/GetThemesEndpointTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetThemesEndpointTests +{ + private readonly IQueryHandler>> _mockHandler; + private readonly GetThemesEndpoint _sut; + private readonly ThemeResponseFixture _themeResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetThemesEndpointTests() + { + _mockHandler = Substitute.For>>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithThemes() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + IReadOnlyList expectedResponse = _themeResponseFixture.CreateMany(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + Ok> okResult = Assert.IsType>>(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(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType(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(), Arg.Any()) + .Returns(Result.From>([])); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query != null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From>([]); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(EmptyRequest.Instance, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Services/ThemeCachePreferenceServiceTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Services/ThemeCachePreferenceServiceTests.cs new file mode 100644 index 00000000..8c588a76 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Services/ThemeCachePreferenceServiceTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ThemeCachePreferenceServiceTests +{ + private readonly HybridCache _hybridCache; + private readonly ThemeCachePreferenceService _sut; + + /// + /// Initializes a new instance of the class. + /// + public ThemeCachePreferenceServiceTests() + { + ServiceCollection services = new(); + services.AddHybridCache(); + _hybridCache = services.BuildServiceProvider().GetRequiredService(); + _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); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/DeleteTheme/DeleteThemeEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/DeleteTheme/DeleteThemeEndpointTests.cs new file mode 100644 index 00000000..f659d122 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/DeleteTheme/DeleteThemeEndpointTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteThemeEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly DeleteThemeEndpoint _sut; + + /// + /// Initializes a new instance of the class. + /// + public DeleteThemeEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + ThemeService themeService = new(_mockApiHttpClient); + _sut = Factory.Create(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()); + } + + [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(result); + Assert.Equal(StatusCodes.Status400BadRequest, problemResult.StatusCode); + await _mockApiHttpClient.DidNotReceive().DeleteAsync(Arg.Any(), Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/DownloadTheme/DownloadThemeEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/DownloadTheme/DownloadThemeEndpointTests.cs new file mode 100644 index 00000000..3176061a --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/DownloadTheme/DownloadThemeEndpointTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DownloadThemeEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly DownloadThemeEndpoint _sut; + + /// + /// Initializes a new instance of the class. + /// + public DownloadThemeEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + ThemeService themeService = new(_mockApiHttpClient); + _sut = Factory.Create(themeService); + } + + [Fact] + public async Task ExecuteAsync_WhenThemeIdProvided_ShouldReturnZipFileWithResolvedFileName() + { + // Arrange + string themeId = "editorial-paper"; + _mockApiHttpClient.GetBlobAsync(Arg.Any(), Arg.Any()) + .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(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()) + .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()); + } + + [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(result); + Assert.Equal(StatusCodes.Status400BadRequest, problemResult.StatusCode); + await _mockApiHttpClient.DidNotReceive().GetBlobAsync(Arg.Any(), Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/GetThemes/GetThemesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/GetThemes/GetThemesEndpointTests.cs new file mode 100644 index 00000000..896dc807 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/GetThemes/GetThemesEndpointTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetThemesEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly GetThemesEndpoint _sut; + private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new(); + private readonly ThemeSettingsResponseDtoFixture _themeSettingsResponseDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetThemesEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + ThemeService themeService = new(_mockApiHttpClient); + _sut = Factory.Create(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(ApiRoutes.Themes.GET_THEMES, Arg.Any()) + .Returns(themes); + _mockApiHttpClient.GetAsync(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any()) + .Returns(currentTheme); + _mockApiHttpClient.GetAsync(ApiRoutes.Themes.GET_THEME_SETTINGS, Arg.Any()) + .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(ApiRoutes.Themes.GET_THEMES, Arg.Any()) + .Returns([.. _themeResponseDtoFixture.CreateMany(2)]); + _mockApiHttpClient.GetAsync(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any()) + .Returns(_themeResponseDtoFixture.Create()); + _mockApiHttpClient.GetAsync(ApiRoutes.Themes.GET_THEME_SETTINGS, Arg.Any()) + .Returns(_themeSettingsResponseDtoFixture.Create()); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync(ApiRoutes.Themes.GET_THEMES, Arg.Any()); + await _mockApiHttpClient.Received(1).GetAsync(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any()); + await _mockApiHttpClient.Received(1).GetAsync(ApiRoutes.Themes.GET_THEME_SETTINGS, Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/InstallTheme/InstallThemeEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/InstallTheme/InstallThemeEndpointTests.cs new file mode 100644 index 00000000..b7678639 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/InstallTheme/InstallThemeEndpointTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class InstallThemeEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly InstallThemeEndpoint _sut; + private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public InstallThemeEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + ThemeService themeService = new(_mockApiHttpClient); + _sut = Factory.Create(themeService); + } + + [Fact] + public async Task ExecuteAsync_WhenArchiveUploaded_ShouldInstallThemeAndReturnSuccessJson() + { + // Arrange + ThemeResponseDto installedTheme = _themeResponseDtoFixture.Create(themeId: "installed-theme"); + _mockApiHttpClient.PostMultipartAsync(ApiRoutes.Themes.INSTALL_THEME, Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .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( + ApiRoutes.Themes.INSTALL_THEME, + Arg.Any(), + "theme-pack.zip", + "archive", + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenNoArchiveUploaded_ShouldReturnProblemWithBadRequest() + { + // Arrange + IFormFeature formFeature = Substitute.For(); + 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(result); + Assert.Equal(StatusCodes.Status400BadRequest, problemResult.StatusCode); + await _mockApiHttpClient.DidNotReceive().PostMultipartAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + 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(new FormFeature(form)); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs new file mode 100644 index 00000000..667c03a7 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SetCurrentThemeEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly SetCurrentThemeEndpoint _sut; + private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public SetCurrentThemeEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + ThemeService themeService = new(_mockApiHttpClient); + _sut = Factory.Create(themeService); + } + + [Fact] + public async Task ExecuteAsync_WhenThemeIdProvided_ShouldSetCurrentThemeAndReturnSuccessJson() + { + // Arrange + string themeId = "editorial-paper"; + _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .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( + ApiRoutes.Themes.SET_CURRENT_THEME, + Arg.Is(payload => (payload.GetType().GetProperty("ThemeId")!.GetValue(payload) as string) == themeId), + Arg.Any()); + } + + [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(result); + Assert.Equal(StatusCodes.Status400BadRequest, problemResult.StatusCode); + await _mockApiHttpClient.DidNotReceive().PutAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/ThemesIndexViewEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/ThemesIndexViewEndpointTests.cs new file mode 100644 index 00000000..cabba6af --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/ThemesIndexViewEndpointTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ThemesIndexViewEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly ThemesIndexViewEndpoint _sut; + private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public ThemesIndexViewEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + ThemeService themeService = new(_mockApiHttpClient); + _sut = Factory.Create(themeService); + TestHttpContextFactory.ConfigureSession(_sut.HttpContext, TestHttpContextFactory.CreateSession()); + } + + [Fact] + public async Task ExecuteAsync_WhenThemesAvailable_ShouldReturnRazorViewResult() + { + // Arrange + _mockApiHttpClient.GetAsync(ApiRoutes.Themes.GET_THEMES, Arg.Any()) + .Returns([.. _themeResponseDtoFixture.CreateMany(2)]); + _mockApiHttpClient.GetAsync(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any()) + .Returns(_themeResponseDtoFixture.Create()); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + Assert.IsType(result); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldLoadThemesAndCurrentThemeFromService() + { + // Arrange + _mockApiHttpClient.GetAsync(ApiRoutes.Themes.GET_THEMES, Arg.Any()) + .Returns([.. _themeResponseDtoFixture.CreateMany(2)]); + _mockApiHttpClient.GetAsync(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any()) + .Returns(_themeResponseDtoFixture.Create()); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync(ApiRoutes.Themes.GET_THEMES, Arg.Any()); + await _mockApiHttpClient.Received(1).GetAsync(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeLayoutRendererTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeLayoutRendererTests.cs new file mode 100644 index 00000000..f8d7080d --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeLayoutRendererTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[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; + + /// + /// Initializes a new instance of the class. + /// + public ThemeLayoutRendererTests() + { + _mockApiHttpClient = Substitute.For(); + _mockViewEngine = Substitute.For(); + _mockTempDataProvider = Substitute.For(); + _mockTempDataProvider.LoadTempData(Arg.Any()).Returns(new Dictionary()); + _mockServiceProvider = Substitute.For(); + _mockServiceProvider.GetService(typeof(IModelMetadataProvider)).Returns(new EmptyModelMetadataProvider()); + _mockHttpContextAccessor = Substitute.For(); + + _mockUrlService = Substitute.For(); + _mockUrlService.GetAbsoluteUrl(Arg.Any(), Arg.Any()).Returns("http://localhost/en-us"); + _mockStringLocalizer = CreateLocalizer(); + _mockStringLocalizerFactory = Substitute.For(); + _mockStringLocalizerFactory.Create(Arg.Any(), Arg.Any()).Returns(_mockStringLocalizer); + _mockAuthorizationService = Substitute.For(); + _mockAuthorizationService.IsInRoleAsync("Admin", Arg.Any()).Returns(false); + _mockAuthorizationService.HasPermissionAsync(Arg.Any(), Arg.Any()).Returns(false); + + _mockHeadView = CreateView(""); + _mockAudioPlayerView = CreateView(""); + _mockScriptsView = CreateView(""); + _mockNavMenuView = CreateView(""); + _mockViewEngine.FindView(Arg.Any(), "_ThemeLayoutHead", false).Returns(ViewEngineResult.Found("_ThemeLayoutHead", _mockHeadView)); + _mockViewEngine.FindView(Arg.Any(), "_AudioPlayer", false).Returns(ViewEngineResult.Found("_AudioPlayer", _mockAudioPlayerView)); + _mockViewEngine.FindView(Arg.Any(), "_ThemeLayoutScripts", false).Returns(ViewEngineResult.Found("_ThemeLayoutScripts", _mockScriptsView)); + _mockViewEngine.FindView(Arg.Any(), "_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", "
", ""); + + // Act + Result result = await _sut.RenderAsync(page, "editorial", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("My Page|/theme-assets/editorial/assets||nav:Lumina|
||||", 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", "
", ""); + + // Act + Result result = await _sut.RenderAsync(page, "editorial", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("My Page|/theme-assets/editorial/assets||nav:Lumina|
||||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", "
", string.Empty); + + // Act + Result result = await _sut.RenderAsync(page, "editorial", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("My Page|", result.Value); + _mockViewEngine.Received(1).FindView(Arg.Any(), "_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", "
", 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(layoutEndpoint, Arg.Any()); + await _mockApiHttpClient.Received(1).GetAsync(navEndpoint, Arg.Any()); + } + + 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(layoutEndpoint, Arg.Any()) + .Returns(new ThemeTemplateResponseDto(theme, layoutTemplate)); + _mockApiHttpClient.GetAsync(navEndpoint, Arg.Any()) + .Returns(new ThemeTemplateResponseDto(theme, navTemplate)); + } + + private static IView CreateView(string markup) + { + IView view = Substitute.For(); + view.RenderAsync(Arg.Any()) + .Returns(callInfo => + { + callInfo.Arg().Writer.Write(markup); + return Task.CompletedTask; + }); + return view; + } + + private static IStringLocalizer CreateLocalizer() + { + IStringLocalizer localizer = Substitute.For(); + localizer[Arg.Any()].Returns(callInfo => new LocalizedString(callInfo.Arg(), $"Localized-{callInfo.Arg()}")); + return localizer; + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeNavBuilderTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeNavBuilderTests.cs new file mode 100644 index 00000000..0ed4c0bc --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeNavBuilderTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[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; + + /// + /// Initializes a new instance of the class. + /// + public ThemeNavBuilderTests() + { + _mockUrlService = Substitute.For(); + _mockStringLocalizer = Substitute.For(); + _mockStringLocalizer[Arg.Any()].Returns(callInfo => new LocalizedString(callInfo.Arg(), $"Localized-{callInfo.Arg()}")); + _mockStringLocalizerFactory = Substitute.For(); + _mockStringLocalizerFactory.Create(Arg.Any(), Arg.Any()).Returns(_mockStringLocalizer); + _mockAuthorizationService = Substitute.For(); + _mockHttpContextAccessor = Substitute.For(); + _sut = new ThemeNavBuilder(_mockUrlService, _mockStringLocalizerFactory, _mockAuthorizationService, _mockHttpContextAccessor); + + StubSiteUrls(); + _mockAuthorizationService.IsInRoleAsync("Admin", Arg.Any()).Returns(false); + _mockAuthorizationService.HasPermissionAsync(Arg.Any(), Arg.Any()).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()).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()); + } + + [Fact] + public async Task BuildAsync_WhenUserCanCreateLibraries_ShouldIncludeAddNewLibraryEntry() + { + // Arrange + _mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: TestHttpContextFactory.CreateAuthenticatedUser())); + _mockAuthorizationService.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, Arg.Any()).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()); + } + + [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()).Returns(true); + _mockAuthorizationService.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, Arg.Any()).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 sections = isMobile ? menu.MobileSections : menu.MenubarSections; + return sections.FirstOrDefault(section => section.Label == label); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemePageDataFactoryTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemePageDataFactoryTests.cs new file mode 100644 index 00000000..4fc1b04b --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemePageDataFactoryTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ThemePageDataFactoryTests +{ + private readonly IStringLocalizer _mockStringLocalizer; + + /// + /// Initializes a new instance of the class. + /// + public ThemePageDataFactoryTests() + { + _mockStringLocalizer = Substitute.For(); + } + + [Fact] + public void CreateLocalizedStrings_WhenLocalizerProvidesStrings_ShouldReturnDictionaryKeyedByName() + { + // Arrange + LocalizedString[] localizedStrings = + [ + new("Title", "The Title"), + new("Search", "Search") + ]; + _mockStringLocalizer.GetAllStrings(Arg.Any()).Returns(localizedStrings); + + // Act + Dictionary 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()).Returns([]); + + // Act + Dictionary result = ThemePageDataFactory.CreateLocalizedStrings(_mockStringLocalizer); + + // Assert + Assert.Empty(result); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemePageRendererTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemePageRendererTests.cs new file mode 100644 index 00000000..cc4282f1 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemePageRendererTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ThemePageRendererTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly ThemePageRenderer _sut; + private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new(); + private readonly ThemePageDtoFixture _themePageDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public ThemePageRendererTests() + { + _mockApiHttpClient = Substitute.For(); + 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 = "

{{title}}

{{#scripts}}{{/scripts}}"; + string expectedEndpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE + .Replace("{themeId}", "editorial-paper") + .Replace("{*pageKey}", pageKey); + _mockApiHttpClient.GetAsync(expectedEndpoint, Arg.Any()) + .Returns(new ThemeTemplateResponseDto(theme, template)); + ThemePageDto model = _themePageDtoFixture.Create(pageKey: pageKey, title: "Home"); + + // Act + Result result = await _sut.RenderAsync(model, "editorial-paper", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("

Home

", result.Value.Content); + Assert.Equal("", 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(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any()); + } + + [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(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any()) + .Returns(currentTheme); + _mockApiHttpClient.GetAsync(expectedEndpoint, Arg.Any()) + .Returns(new ThemeTemplateResponseDto(currentTheme, "{{title}}")); + ThemePageDto model = _themePageDtoFixture.Create(pageKey: pageKey, title: "Home"); + + // Act + Result 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(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any()); + } + + [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(expectedEndpoint, Arg.Any()) + .Returns(new ThemeTemplateResponseDto(theme, "{{#unclosed}}")); + ThemePageDto model = _themePageDtoFixture.Create(pageKey: pageKey, title: "Home"); + + // Act + Result result = await _sut.RenderAsync(model, "editorial-paper", CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Template.Invalid", result.FirstError.Code); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeServiceTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeServiceTests.cs new file mode 100644 index 00000000..c24c55f0 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeServiceTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[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(); + + /// + /// Initializes a new instance of the class. + /// + public ThemeServiceTests() + { + _mockApiHttpClient = Substitute.For(); + _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(ApiRoutes.Themes.GET_THEMES, Arg.Any()) + .Returns(themes); + + // Act + IReadOnlyList 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(ApiRoutes.Themes.GET_THEMES, Arg.Any()); + } + + [Fact] + public async Task GetThemesAsync_WhenThemeHasNoPreviewPath_ShouldReturnPlaceholderPreviewUrl() + { + // Arrange + ThemeResponseDto theme = _themeResponseDtoFixture.Create(themeId: "editorial-paper", previewPath: null); + _mockApiHttpClient.GetAsync(ApiRoutes.Themes.GET_THEMES, Arg.Any()) + .Returns([theme]); + + // Act + IReadOnlyList 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(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any()) + .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(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any()); + } + + [Fact] + public async Task GetThemeSettingsAsync_WhenApiReturnsSettings_ShouldReturnSettings() + { + // Arrange + ThemeSettingsResponseDto settings = _themeSettingsResponseDtoFixture.Create(maxArchiveBytes: 10 * 1024 * 1024, allowThemeScripts: true); + _mockApiHttpClient.GetAsync(ApiRoutes.Themes.GET_THEME_SETTINGS, Arg.Any()) + .Returns(settings); + + // Act + ThemeSettingsResponseDto result = await _sut.GetThemeSettingsAsync(CancellationToken.None); + + // Assert + Assert.Equal(settings, result); + await _mockApiHttpClient.Received(1).GetAsync(ApiRoutes.Themes.GET_THEME_SETTINGS, Arg.Any()); + } + + [Fact] + public async Task SetCurrentThemeAsync_WhenCalled_ShouldSendThemeIdToApi() + { + // Arrange + string themeId = "editorial-paper"; + _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_themeResponseDtoFixture.Create()); + + // Act + await _sut.SetCurrentThemeAsync(themeId, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PutAsync( + ApiRoutes.Themes.SET_CURRENT_THEME, + Arg.Is(payload => payload.GetType().GetProperty("ThemeId")!.GetValue(payload)!.ToString()! == themeId), + Arg.Any()); + } + + [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(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(installedTheme); + + // Act + ThemeInfoDto result = await _sut.InstallAsync(archiveStream, fileName, CancellationToken.None); + + // Assert + Assert.Equal("installed-theme", result.Id); + await _mockApiHttpClient.Received(1).PostMultipartAsync( + ApiRoutes.Themes.INSTALL_THEME, + archiveStream, + fileName, + "archive", + Arg.Any()); + } + } + + [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()); + } + + [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(expectedEndpoint, Arg.Any()) + .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(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any()); + await _mockApiHttpClient.Received(1).GetAsync(expectedEndpoint, Arg.Any()); + } + + [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(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any()) + .Returns(currentTheme); + _mockApiHttpClient.GetAsync(expectedEndpoint, Arg.Any()) + .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(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any()); + await _mockApiHttpClient.Received(1).GetAsync(expectedEndpoint, Arg.Any()); + } + + [Fact] + public async Task BuildArchiveAsync_WhenApiReturnsBlob_ShouldReturnZipArchiveWithResolvedFileName() + { + // Arrange + string themeId = "editorial-paper"; + byte[] data = [0x50, 0x4B, 0x03, 0x04]; + _mockApiHttpClient.GetBlobAsync(Arg.Any(), Arg.Any()) + .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()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeTemplateEngineTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeTemplateEngineTests.cs new file mode 100644 index 00000000..e19b1753 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeTemplateEngineTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ThemeTemplateEngineTests +{ + private readonly ThemeTemplateEngine _sut; + private readonly SectionModelFixture _sectionModelFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public ThemeTemplateEngineTests() + { + _sut = new ThemeTemplateEngine(); + } + + [Fact] + public void RenderPage_WhenVariableValueContainsHtml_ShouldEscapeOutput() + { + // Arrange + Dictionary model = new() { ["value"] = "&\"quote\"" }; + string template = "{{value}}"; + + // Act + Result result = _sut.RenderPage(template, model); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("<b>&"quote"", result.Value.Content); + Assert.Equal(string.Empty, result.Value.Script); + } + + [Fact] + public void RenderPage_WhenRawVariableTagUsed_ShouldNotEscapeOutput() + { + // Arrange + Dictionary model = new() { ["value"] = "raw" }; + + // Act + Result ampersandResult = _sut.RenderPage("{{&value}}", model); + Result tripleResult = _sut.RenderPage("{{{value}}}", model); + + // Assert + Assert.True(ampersandResult.IsSuccess); + Assert.Equal("raw", ampersandResult.Value.Content); + Assert.True(tripleResult.IsSuccess); + Assert.Equal("raw", tripleResult.Value.Content); + } + + [Fact] + public void RenderPage_WhenVariableMissing_ShouldRenderEmptyString() + { + // Arrange + Dictionary model = new() { ["title"] = "Present" }; + + // Act + Result 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 model = new() { ["enabled"] = true, ["disabled"] = false }; + + // Act + Result 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 model = new() + { + ["user"] = new Dictionary { ["name"] = "Ada" } + }; + + // Act + Result 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 model = new() { ["items"] = new List { "a", "b", "c" } }; + + // Act + Result 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 model = new() { ["section"] = true, ["text"] = "inside" }; + + // Act + Result 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 model = new() + { + ["section"] = _sectionModelFixture.Create(text: "scoped") + }; + + // Act + Result 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 model = new() { ["section"] = sectionValue, ["text"] = "hidden" }; + + // Act + Result 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 model = new() { ["section"] = new List() }; + + // Act + Result 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 model = new() + { + ["items"] = new List + { + new Dictionary { ["name"] = "A" }, + new Dictionary { ["name"] = "B" } + } + }; + + // Act + Result 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 model = new() { ["items"] = new List { "one", "two" } }; + + // Act + Result 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 model = new() + { + ["title"] = "Parent", + ["items"] = new List + { + new Dictionary { ["name"] = "A" }, + new Dictionary { ["name"] = "B" } + } + }; + + // Act + Result 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 model = new() { ["section"] = null }; + + // Act + Result 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 model = new() { ["section"] = "present" }; + + // Act + Result 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 model = new() { ["title"] = "Page", ["script"] = "console.log('x');" }; + + // Act + Result result = _sut.RenderPage( + "

{{title}}

{{#scripts}}{{/scripts}}", + model); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("

Page

", result.Value.Content); + Assert.Equal("", result.Value.Script); + } + + [Fact] + public void RenderPage_WhenScriptsSectionIsNamedDifferentlyInCase_ShouldStillSplitIt() + { + // Arrange + Dictionary model = new() { ["title"] = "Page" }; + + // Act + Result 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 model = new() + { + ["items"] = new List + { + new Dictionary { ["name"] = "A", ["scripts"] = true, ["script"] = "x" } + } + }; + + // Act + Result 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 model = new() { ["title"] = "Page" }; + + // Act + Result 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 model = new() { ["section"] = true }; + + // Act + Result 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 result = _sut.RenderPage("{{/section}}", new Dictionary()); + + // 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 result = _sut.RenderPage("{{#first}}x{{/second}}", new Dictionary()); + + // 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 result = _sut.RenderPage("before{{}}after", new Dictionary()); + + // 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 result = _sut.RenderPage("before{{value", new Dictionary()); + + // 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 result = _sut.RenderPage("before{{{value", new Dictionary()); + + // 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 result = _sut.RenderPage(template, new Dictionary()); + + // 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 result = _sut.RenderPage(template, new Dictionary()); + + // 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 result = _sut.RenderPage(template, new Dictionary()); + + // 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 model = new() { ["text"] = new string('a', limit + 1) }; + + // Act + Result 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); + } +}