#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; } }