From 64ef3a1e2259ffe1c26a34da97831de9de82ab94 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Sat, 26 Sep 2026 12:59:17 +0300 Subject: [PATCH] Returns the unit of work save changes result --- .../Common/DataAccess/UoW/IUnitOfWork.cs | 24 ++++- .../Commands/AddRole/AddRoleCommandHandler.cs | 16 ++-- .../DeleteRole/DeleteRoleCommandHandler.cs | 25 +++--- .../UpdateRole/UpdateRoleCommandHandler.cs | 25 +++--- .../SetupApplicationCommandHandler.cs | 21 +++-- .../AddLibrary/AddLibraryCommandHandler.cs | 29 +++--- .../CancelLibrariesScanCommandHandler.cs | 26 +++--- .../CancelLibraryScanCommandHandler.cs | 20 +++-- .../DeleteLibraryCommandHandler.cs | 23 ++--- .../ScanLibrariesCommandHandler.cs | 30 ++++--- .../ScanLibrary/ScanLibraryCommandHandler.cs | 26 +++--- .../UpdateLibraryCommandHandler.cs | 34 +++---- ...braryMediaItemDeletedDomainEventHandler.cs | 14 +-- .../Events/LibrarySavedDomainEventHandler.cs | 46 +++++----- .../LibraryScanFailedDomainEventHandler.cs | 22 ++--- .../LibraryScanFinishedDomainEventHandler.cs | 20 +++-- .../LibraryScanStartedDomainEventHandler.cs | 6 +- ...erLibraryArtworkProvidersCommandHandler.cs | 12 ++- ...rLibraryMetadataProvidersCommandHandler.cs | 12 ++- ...aryArtworkProviderEnabledCommandHandler.cs | 14 ++- ...ryMetadataProviderEnabledCommandHandler.cs | 14 ++- .../UpdatePluginSettingsCommandHandler.cs | 6 +- .../AddScheduledJobCommandHandler.cs | 5 +- .../RemoveScheduledJobCommandHandler.cs | 7 +- .../StartScheduledJobCommandHandler.cs | 7 +- .../StopScheduledJobCommandHandler.cs | 7 +- ...hedulerDisplayPreferencesCommandHandler.cs | 6 +- ...JobExecutionCompletedDomainEventHandler.cs | 73 +++------------ ...edJobExecutionStartedDomainEventHandler.cs | 45 ++-------- ...edJobExecutionStoppedDomainEventHandler.cs | 25 ++---- .../DeleteTheme/DeleteThemeCommandHandler.cs | 20 +++-- .../InstallThemeCommandHandler.cs | 12 +-- .../RestoreThemeCommandHandler.cs | 10 ++- .../SetCurrentThemeCommandHandler.cs | 10 ++- .../GetThemeTemplateQueryHandler.cs | 15 ++-- .../ChangePasswordCommandHandler.cs | 17 +++- .../RecoverPasswordCommandHandler.cs | 28 +++--- .../RegisterUserCommandHandler.cs | 26 ++++-- .../LoginUser/LoginUserQueryHandler.cs | 29 +++--- ...ateUserRoleAndPermissionsCommandHandler.cs | 35 +++++--- .../UpdateUserSettingsCommandHandler.cs | 5 +- .../Core/Seed/DataSeedService.cs | 28 ++++-- .../MediaLibraryScanArtworkEnrichmentJob.cs | 80 ++++++++--------- .../MediaLibraryScanMetadataEnrichmentJob.cs | 89 ++++++++++--------- ...canProviderConfigurationInvalidationJob.cs | 40 +++++---- .../Common/MediaLibraryScanResultsSaveJob.cs | 36 ++++---- .../Core/Plugins/PluginDetectionSyncJob.cs | 14 +-- .../Execution/ScheduledJobSchedulerJob.cs | 83 ++++------------- .../MediaLibraryScanTaskExecutor.cs | 4 +- .../Core/Themes/ThemeSynchronizer.cs | 10 ++- .../Core/UoW/UnitOfWorkTests.cs | 39 ++++++++ .../GetPermissionsQueryHandlerTests.cs | 27 +++--- .../AddRole/AddRoleCommandHandlerTests.cs | 1 + .../DeleteRoleCommandHandlerTests.cs | 13 +-- .../UpdateRoleCommandHandlerTests.cs | 7 +- .../GetRolePermissionsQueryHandlerTests.cs | 11 +-- .../GetRoles/GetRolesQueryHandlerTests.cs | 15 ++-- .../SetupApplicationCommandHandlerTests.cs | 83 +++++++++-------- .../CheckInitializationQueryHandlerTests.cs | 20 +++-- .../AddLibraryCommandHandlerTests.cs | 7 +- .../CancelLibrariesScanCommandHandlerTests.cs | 1 + .../CancelLibraryScanCommandHandlerTests.cs | 17 ++-- .../DeleteLibraryCommandHandlerTests.cs | 19 ++-- .../ScanLibrariesCommandHandlerTests.cs | 1 + .../ScanLibraryCommandHandlerTests.cs | 25 +++--- .../UpdateLibraryCommandHandlerTests.cs | 43 ++++----- ...MediaItemDeletedDomainEventHandlerTests.cs | 26 +++--- .../LibrarySavedDomainEventHandlerTests.cs | 5 +- ...aryScanCancelledDomainEventHandlerTests.cs | 11 +-- ...ibraryScanFailedDomainEventHandlerTests.cs | 13 +-- ...raryScanFinishedDomainEventHandlerTests.cs | 11 +-- ...ibraryScanQueuedDomainEventHandlerTests.cs | 9 +- ...braryScanStartedDomainEventHandlerTests.cs | 1 + .../GetEnabledLibrariesQueryHandlerTests.cs | 1 + .../GetLibrariesQueryHandlerTests.cs | 11 ++- .../GetLibrary/GetLibraryQueryHandlerTests.cs | 11 +-- ...GetLibraryScanProgressQueryHandlerTests.cs | 15 ++-- ...GetRunningLibraryScansQueryHandlerTests.cs | 1 + ...raryArtworkProvidersCommandHandlerTests.cs | 1 + ...aryMetadataProvidersCommandHandlerTests.cs | 1 + ...tworkProviderEnabledCommandHandlerTests.cs | 1 + ...adataProviderEnabledCommandHandlerTests.cs | 1 + ...UpdatePluginSettingsCommandHandlerTests.cs | 1 + ...ibraryArtworkProvidersQueryHandlerTests.cs | 20 +++-- ...braryMetadataProvidersQueryHandlerTests.cs | 20 +++-- .../GetPluginSettingsQueryHandlerTests.cs | 11 +-- .../GetPlugins/GetPluginsQueryHandlerTests.cs | 8 +- .../AddScheduledJobCommandHandlerTests.cs | 1 + .../FireScheduledJobCommandHandlerTests.cs | 17 ++-- .../RemoveScheduledJobCommandHandlerTests.cs | 19 ++-- .../StartScheduledJobCommandHandlerTests.cs | 19 ++-- .../StopScheduledJobCommandHandlerTests.cs | 21 ++--- ...erDisplayPreferencesCommandHandlerTests.cs | 1 + ...cheduledJobAddedDomainEventHandlerTests.cs | 9 +- ...dJobCycleStartedDomainEventHandlerTests.cs | 7 +- ...dJobCycleStoppedDomainEventHandlerTests.cs | 9 +- ...ecutionCompletedDomainEventHandlerTests.cs | 31 ++++--- ...ExecutionStartedDomainEventHandlerTests.cs | 19 ++-- ...ExecutionStoppedDomainEventHandlerTests.cs | 7 +- ...eduledJobRemovedDomainEventHandlerTests.cs | 9 +- ...GetScheduledJobHistoryQueryHandlerTests.cs | 1 + .../GetScheduledJobsQueryHandlerTests.cs | 17 ++-- ...ulerDisplayPreferencesQueryHandlerTests.cs | 1 + .../DeleteThemeCommandHandlerTests.cs | 37 ++++---- .../InstallThemeCommandHandlerTests.cs | 1 + .../RestoreThemeCommandHandlerTests.cs | 1 + .../SetCurrentThemeCommandHandlerTests.cs | 1 + .../GetCurrentThemeQueryHandlerTests.cs | 1 + .../GetThemeArchiveQueryHandlerTests.cs | 1 + .../GetThemeAssetQueryHandlerTests.cs | 1 + .../GetThemeTemplateQueryHandlerTests.cs | 1 + .../GetThemes/GetThemesQueryHandlerTests.cs | 13 +-- .../ChangePasswordCommandHandlerTests.cs | 1 + .../RecoverPasswordCommandHandlerTests.cs | 1 + .../RegisterUserCommandHandlerTests.cs | 1 + .../GetUsers/GetUsersQueryHandlerTests.cs | 15 ++-- .../LoginUser/LoginUserQueryHandlerTests.cs | 1 + ...erRoleAndPermissionsCommandHandlerTests.cs | 39 ++++---- .../GetUserPermissionsQueryHandlerTests.cs | 11 +-- .../GetUserRoleQueryHandlerTests.cs | 13 +-- .../UpdateUserSettingsCommandHandlerTests.cs | 1 + .../GetUserSettingsQueryHandlerTests.cs | 1 + .../Core/Seed/DataSeedServiceTests.cs | 35 ++++++-- .../Core/UoW/UnitOfWorkTests.cs | 5 +- .../AuthorizationServiceTests.cs | 73 +++++++-------- .../LibraryOwnershipPolicyTests.cs | 33 +++---- .../Policies/Over18/Over18PolicyTests.cs | 9 +- ...diaLibraryScanArtworkEnrichmentJobTests.cs | 60 ++++++------- .../Common/MediaLibraryScanDiffJobTests.cs | 1 + .../Common/MediaLibraryScanHashJobTests.cs | 1 + ...iaLibraryScanMetadataEnrichmentJobTests.cs | 60 ++++++------- ...oviderConfigurationInvalidationJobTests.cs | 10 +-- .../MediaLibraryScanResultsSaveJobTests.cs | 12 +-- ...aLibraryProviderConfigurationStoreTests.cs | 3 +- .../Plugins/PluginDetectionSyncJobTests.cs | 15 ++-- .../Core/Plugins/PluginSettingsStoreTests.cs | 9 +- .../ScheduledJobSchedulerJobTests.cs | 88 +++++++++--------- ...ledJobExecutionHistoryTaskExecutorTests.cs | 1 + .../MediaLibraryScanTaskExecutorTests.cs | 2 +- .../RepairThemesTaskExecutorTests.cs | 20 +++-- .../Core/Themes/ThemeSynchronizerTests.cs | 34 +++---- 141 files changed, 1388 insertions(+), 1151 deletions(-) diff --git a/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs b/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs index 9c4c7407..f944b9f4 100644 --- a/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs +++ b/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs @@ -1,12 +1,14 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Repositories.Authorization; -using Lumina.Application.Common.DataAccess.Repositories.Books; +using Lumina.Application.Common.DataAccess.Repositories.BookLibrary; using Lumina.Application.Common.DataAccess.Repositories.MediaContributors; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Scheduling; using Lumina.Application.Common.DataAccess.Repositories.Themes; using Lumina.Application.Common.DataAccess.Repositories.Users; +using Lumina.Domain.Common.Primitives; using System.Threading; using System.Threading.Tasks; #endregion @@ -43,6 +45,21 @@ public interface IUnitOfWork /// IBookRepository BookRepository { get; } + /// + /// Gets the artist repository. + /// + IArtistRepository ArtistRepository { get; } + + /// + /// Gets the album repository. + /// + IAlbumRepository AlbumRepository { get; } + + /// + /// Gets the track repository. + /// + ITrackRepository TrackRepository { get; } + /// /// Gets the media contributor repository. /// @@ -124,10 +141,11 @@ public interface IUnitOfWork IUserSettingsRepository UserSettingsRepository { get; } /// - /// Saves all changes made to the database. + /// Saves the changes made to the database. /// /// Cancellation token that can be used to stop the execution. - Task SaveChangesAsync(CancellationToken cancellationToken); + /// An representing either a successful operation, or an error. + Task> SaveChangesAsync(CancellationToken cancellationToken); /// /// Detaches all the entities tracked by the unit of work, freeing the memory they occupy. diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandler.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandler.cs index 82d1ba69..aeeaf41e 100644 --- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandler.cs +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandler.cs @@ -58,18 +58,18 @@ public class AddRoleCommandHandler : ICommandHandler 0) return validationResult; - // an authenticated request must always carry a user identity + // An authenticated request must always carry a user identity. Guid? currentUserId = _currentUserService.UserId; if (currentUserId is null) return Errors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // only admins can create authorization roles + // Only admins can create authorization roles. bool isAdmin = await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false); if (!isAdmin) return Errors.Authorization.NotAuthorized; - // create the new role, with its permissions + // Create the new role, with its permissions. RoleEntity newRole = new() { RoleName = request.RoleName, @@ -81,12 +81,16 @@ public class AddRoleCommandHandler : ICommandHandler insertRoleResult = await _unitOfWork.RoleRepository.InsertAsync(newRole, cancellationToken).ConfigureAwait(false); if (insertRoleResult.IsFailure) return insertRoleResult.Errors; - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); - // retrieve the newly saved authorization role from the persistence medium and return it + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + + // Retrieve the newly saved authorization role from the persistence medium and return it. Result getRoleResult = await _unitOfWork.RoleRepository.GetByNameAsync(request.RoleName, cancellationToken).ConfigureAwait(false); if (getRoleResult.IsFailure) return getRoleResult.Errors; diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandler.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandler.cs index c330ce1a..8363bb3a 100644 --- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandler.cs +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandler.cs @@ -1,20 +1,16 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Authorization; -using Lumina.Application.Common.DataAccess.Repositories.Authorization; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Validation; -using Lumina.Contracts.Responses.Authorization; +using Lumina.Domain.Common.Primitives; using System; using System.Collections.Generic; -using System.Linq; using System.Threading; using System.Threading.Tasks; -using Lumina.Application.Common.Mapping.Authorization; -using Lumina.Application.Common.Infrastructure.Authorization; #endregion namespace Lumina.Application.Core.Admin.Authorization.Roles.Commands.DeleteRole; @@ -56,7 +52,7 @@ public class DeleteRoleCommandHandler : ICommandHandler 0) return validationResult; - // an authenticated request must always carry a user identity + // An authenticated request must always carry a user identity. Guid? currentUserId = _currentUserService.UserId; if (currentUserId is null) return Errors.Authorization.NotAuthorized; @@ -67,19 +63,24 @@ public class DeleteRoleCommandHandler : ICommandHandler getExistingRoleResult = await _unitOfWork.RoleRepository.GetByIdAsync(command.RoleId, cancellationToken).ConfigureAwait(false); + // Check if a role with the requested Id exists. + Result getExistingRoleResult = await _unitOfWork.RoleRepository.GetByIdAsync(command.RoleId, cancellationToken: cancellationToken).ConfigureAwait(false); if (getExistingRoleResult.IsFailure) return getExistingRoleResult.Errors; else if (getExistingRoleResult.Value is null) return Errors.Authorization.RoleNotFound; else if (getExistingRoleResult.Value.RoleName == "Admin") return Errors.Authorization.AdminRoleCannotBeDeleted; - // delete the role and its permissions + + // Delete the role and its permissions. Result deleteRoleResult = await _unitOfWork.RoleRepository.DeleteByIdAsync(command.RoleId, cancellationToken).ConfigureAwait(false); if (deleteRoleResult.IsFailure) return deleteRoleResult.Errors; - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); - return deleteRoleResult.Value; + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + + return Result.Deleted; } } diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandler.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandler.cs index a5d4cc94..e97a5cd1 100644 --- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandler.cs +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandler.cs @@ -1,8 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Authorization; -using Lumina.Application.Common.DataAccess.Repositories.Authorization; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; @@ -10,6 +8,7 @@ using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Mapping.Authorization; using Lumina.Contracts.Responses.Authorization; +using Lumina.Domain.Common.Primitives; using System; using System.Collections.Generic; using System.Linq; @@ -58,37 +57,41 @@ public class UpdateRoleCommandHandler : ICommandHandler 0) return validationResult; - // an authenticated request must always carry a user identity + // An authenticated request must always carry a user identity. Guid? currentUserId = _currentUserService.UserId; if (currentUserId is null) return Errors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // only admins can update authorization roles + // Only admins can update authorization roles. bool isAdmin = await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false); if (!isAdmin) return Errors.Authorization.NotAuthorized; - // update the role and its permissions + // Update the role and its permissions. RoleEntity newRole = new() { Id = command.RoleId, RoleName = command.RoleName, - RolePermissions = command.Permissions.Select(permissionId => new RolePermissionEntity() + RolePermissions = [.. command.Permissions.Select(permissionId => new RolePermissionEntity() { PermissionId = permissionId, Permission = null!, Role = null!, RoleId = default - }).ToList() + })] }; - // save the updated role in the repository + // Save the updated role in the repository. Result updateRoleResult = await _unitOfWork.RoleRepository.UpdateAsync(newRole, cancellationToken).ConfigureAwait(false); if (updateRoleResult.IsFailure) return updateRoleResult.Errors; - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); - // retrieve the updated authorization role from the persistence medium and return it - Result getRoleResult = await _unitOfWork.RoleRepository.GetByIdAsync(command.RoleId, cancellationToken).ConfigureAwait(false); + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + + // Retrieve the updated authorization role from the persistence medium and return it. + Result getRoleResult = await _unitOfWork.RoleRepository.GetByIdAsync(command.RoleId, cancellationToken: cancellationToken).ConfigureAwait(false); if (getRoleResult.IsFailure) return getRoleResult.Errors; if (getRoleResult.Value is null) diff --git a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs index 47a8a836..6b74fee9 100644 --- a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs +++ b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs @@ -1,18 +1,19 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Scheduling; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; -using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.Seed; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.DomainEvents; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Security; using Lumina.Application.Common.Infrastructure.Time; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Contracts.Responses.Authentication; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; @@ -89,12 +90,12 @@ public class SetupApplicationCommandHandler : ICommandHandler> selectUsersResult = await _unitOfWork.UserRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + Result> selectUsersResult = await _unitOfWork.UserRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false); if (selectUsersResult.IsFailure) return selectUsersResult.Errors; - else if (selectUsersResult.Value.Any()) + else if (selectUsersResult.Value.Data.Any()) return Errors.Authorization.AdminAccountAlreadyCreated; - // no users are present, register the admin one + // No users are present, register the admin one. string? totpSecret = null; Guid id = Guid.NewGuid(); UserEntity user = new() @@ -123,7 +124,9 @@ public class SetupApplicationCommandHandler : ICommandHandler insertUserResult = await _unitOfWork.UserRepository.InsertAsync(user, cancellationToken).ConfigureAwait(false); if (insertUserResult.IsFailure) return insertUserResult.Errors; - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; // Set the default permissions, roles, roles permissions. Result setPermissionsResult = await _dataSeedService.SetDefaultAuthorizationPermissionsAsync(id, cancellationToken).ConfigureAwait(false); @@ -150,15 +153,15 @@ public class SetupApplicationCommandHandler : ICommandHandler> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + Result> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false); if (getScheduledJobsResult.IsFailure) return getScheduledJobsResult.Errors; - foreach (ScheduledJobEntity scheduledJob in getScheduledJobsResult.Value) + foreach (ScheduledJobEntity scheduledJob in getScheduledJobsResult.Value.Data) if (scheduledJob.Status == ScheduledJobStatus.Active) _domainEventsQueue.Enqueue(new ScheduledJobCycleStartedDomainEvent(Guid.NewGuid(), ScheduledJobId.Create(scheduledJob.Id), DateTime.UtcNow)); // TODO: insert the default admin profile preferences when they are implemented. - // If 2FA was enabled during registration, the TOTP secret needs to be delivered to the client unhashed, so it can be displayed + // If 2FA was enabled during registration, the TOTP secret needs to be delivered to the client unhashed, so it can be displayed. return new RegistrationResponse(user.Id, user.Username, totpSecret); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs index 983bdf9e..44e6272e 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs @@ -83,18 +83,18 @@ public class AddLibraryCommandHandler : ICommandHandler 0) return validationResult; - // an authenticated request must always carry a user identity + // An authenticated request must always carry a user identity. Guid? currentUserId = _currentUserService.UserId; if (currentUserId is null) return ApplicationErrors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // only admins or users with the permission to manage media libraries can create them + // Only admins or users with the permission to manage media libraries can create them. if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false) && !await _authorizationService.HasPermissionAsync(userId, AuthorizationPermission.CanCreateLibraries, cancellationToken).ConfigureAwait(false)) return ApplicationErrors.Authorization.NotAuthorized; - // make sure the file is an actual supported image + // Make sure the file is an actual supported image. if (command.CoverImage is not null) { Result fileSystemPathIdResult = FileSystemPathId.Create(command.CoverImage); @@ -108,13 +108,13 @@ public class AddLibraryCommandHandler : ICommandHandler createLibraryResult = Library.Create( UserId.Create(userId), command.Title!, Enum.Parse(command.LibraryType!), command.ContentLocations!, - command.CoverImage, + Optional.FromNullable(command.CoverImage), command.IsEnabled, command.IsLocked, command.CanDownloadMetadataFromWeb, @@ -126,10 +126,10 @@ public class AddLibraryCommandHandler : ICommandHandler insertLibraryResult = await _unitOfWork.LibraryRepository.InsertAsync(persistenceLibrary, cancellationToken).ConfigureAwait(false); if (insertLibraryResult.IsFailure) return insertLibraryResult.Errors; @@ -137,19 +137,22 @@ public class AddLibraryCommandHandler : ICommandHandler(command.LibraryType!), cancellationToken).ConfigureAwait(false); if (ensureProviderConfigurationsResult.IsFailure) return ensureProviderConfigurationsResult.Errors; - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); - // retrieve the newly saved media library from the persistence medium and return it - Result getCreatedLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + + // Retrieve the newly saved media library from the persistence medium and return it. + Result getCreatedLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken: cancellationToken).ConfigureAwait(false); if (getCreatedLibraryResult.IsFailure) return getCreatedLibraryResult.Errors; if (getCreatedLibraryResult.Value is null) return ApplicationErrors.Persistence.ErrorPersistingMediaLibrary; - // mark the media library as saved + // Mark the media library as saved. createLibraryResult.Value.Save(); - // queue any domain events + // Queue any domain events. foreach (IDomainEvent domainEvent in createLibraryResult.Value.GetDomainEvents()) _domainEventsQueue.Enqueue(domainEvent); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandler.cs index 42ceb8d3..c32ba282 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandler.cs @@ -58,53 +58,55 @@ public class CancelLibrariesScanCommandHandler : ICommandHandlerAn representing either a successful operation, or an error. public async Task> HandleAsync(CancelLibrariesScanCommand command, CancellationToken cancellationToken) { - // an authenticated request must always carry a user identity + // An authenticated request must always carry a user identity. Guid? currentUserId = _currentUserService.UserId; if (currentUserId is null) return Errors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // get the running library scans of the current user from the repository + // Get the running library scans of the current user from the repository. Result> getRunningLibraryScansResult = await _unitOfWork.LibraryScanRepository.GetRunningScansAsync(cancellationToken).ConfigureAwait(false); if (getRunningLibraryScansResult.IsFailure) return getRunningLibraryScansResult.Errors; - // filter the library scans to process + // Filter the library scans to process. List authorizedLibraryScans = []; - // admins can see all library scans + // Admins can see all library scans. if (await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false)) authorizedLibraryScans.AddRange(getRunningLibraryScansResult.Value); - else // for regular users, only take the library scans that belong to them + else // For regular users, only take the library scans that belong to them. authorizedLibraryScans.AddRange(getRunningLibraryScansResult.Value.Where(libraryScan => libraryScan.UserId == userId)); - // convert persistence library scans to domain entities + // Convert persistence library scans to domain entities. IEnumerable> libraryScansDomainResult = authorizedLibraryScans.ToDomainEntities(); List domainEvents = []; - // for each library scan, perform the cancellation + // For each library scan, perform the cancellation. foreach (Result libraryScanDomainResult in libraryScansDomainResult) { if (libraryScanDomainResult.IsFailure) return libraryScanDomainResult.Errors; - // cancel the media library scan + // Cancel the media library scan. Result cancelScanResult = libraryScanDomainResult.Value.CancelScan(); if (cancelScanResult.IsFailure) return cancelScanResult.Errors; - // update the status of the library scan in the repository + // Update the status of the library scan in the repository. Result updateLibraryScanResult = await _unitOfWork.LibraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); if (updateLibraryScanResult.IsFailure) return updateLibraryScanResult.Errors; - // collect all the domain events created during this library scan start + // Collect all the domain events created during this library scan start. domainEvents.AddRange(libraryScanDomainResult.Value.GetDomainEvents()); } - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; - // queue any domain events + // Queue any domain events. foreach (IDomainEvent domainEvent in domainEvents) _domainEventsQueue.Enqueue(domainEvent); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandHandler.cs index f4d0e4bb..57ce568e 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandHandler.cs @@ -67,43 +67,45 @@ public class CancelLibraryScanCommandHandler : ICommandHandler 0) return validationResult; - // an authenticated request must always carry a user identity + // An authenticated request must always carry a user identity. Guid? currentUserId = _currentUserService.UserId; if (currentUserId is null) return ApplicationErrors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // get the library scan from the repository - Result getLibraryScansResult = await _unitOfWork.LibraryScanRepository.GetByIdAsync(command.ScanId, cancellationToken).ConfigureAwait(false); + // Get the library scan from the repository. + Result getLibraryScansResult = await _unitOfWork.LibraryScanRepository.GetByIdAsync(command.ScanId, cancellationToken: cancellationToken).ConfigureAwait(false); if (getLibraryScansResult.IsFailure) return getLibraryScansResult.Errors; if (getLibraryScansResult.Value is null) return DomainErrors.LibraryScanning.LibraryScanNotFound; - // admins can cancel any library scan; for everyone else, only the ones of the libraries they own + // Admins can cancel any library scan; for everyone else, only the ones of the libraries they own. bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( userId, new LibraryOwnershipPolicyContext(getLibraryScansResult.Value.LibraryId), cancellationToken).ConfigureAwait(false); if (!canAccessLibrary) return ApplicationErrors.Authorization.NotAuthorized; - // convert the repository scan to a domain object + // Convert the repository scan to a domain object. Result libraryScanDomainResult = getLibraryScansResult.Value.ToDomainEntity(); if (libraryScanDomainResult.IsFailure) return libraryScanDomainResult.Errors; - // cancel the media library scan + // Cancel the media library scan. Result cancelScanResult = libraryScanDomainResult.Value.CancelScan(); if (cancelScanResult.IsFailure) return cancelScanResult.Errors; - // update the status of the library scan in the repository + // Update the status of the library scan in the repository. Result updateLibraryScanResult = await _unitOfWork.LibraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); if (updateLibraryScanResult.IsFailure) return updateLibraryScanResult.Errors; - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; - // queue any domain events + // Queue any domain events. foreach (IDomainEvent domainEvent in libraryScanDomainResult.Value.GetDomainEvents()) _domainEventsQueue.Enqueue(domainEvent); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandler.cs index 968f92d4..ae7b4e06 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandler.cs @@ -72,48 +72,51 @@ public class DeleteLibraryCommandHandler : ICommandHandler 0) return validationResult; - // an authenticated request must always carry a user identity + // An authenticated request must always carry a user identity. Guid? currentUserId = _currentUserService.UserId; if (currentUserId is null) return ApplicationErrors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // get the library with the specified id from the repository - Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false); + // Get the library with the specified id from the repository. + Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(command.Id, cancellationToken: cancellationToken).ConfigureAwait(false); if (getLibraryResult.IsFailure) return getLibraryResult.Errors; else if (getLibraryResult.Value is null) return DomainErrors.Library.LibraryNotFound; - // admins can delete any library; for everyone else, only the libraries they own + // Admins can delete any library; for everyone else, only the libraries they own. bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( userId, new LibraryOwnershipPolicyContext(command.Id), cancellationToken).ConfigureAwait(false); if (!canAccessLibrary) return ApplicationErrors.Authorization.NotAuthorized; - // create a domain library object + // Create a domain library object. Result createLibraryResult = getLibraryResult.Value.ToDomainEntity(); if (createLibraryResult.IsFailure) return createLibraryResult.Errors; - // delete the domain aggregate + // Delete the domain aggregate. Result deleteDomainLibraryResult = createLibraryResult.Value.Delete(); if (deleteDomainLibraryResult.IsFailure) return deleteDomainLibraryResult.Errors; - // queue any domain events + // Queue any domain events. foreach (IDomainEvent domainEvent in createLibraryResult.Value.GetDomainEvents()) _domainEventsQueue.Enqueue(domainEvent); - // remove the provider configurations of the library, so that they are not orphaned, and delete the library + // Remove the provider configurations of the library, so that they are not orphaned, and delete the library. Result removeProviderConfigurationsResult = await _providerConfigurationStore.RemoveProviderConfigurationsForLibraryAsync(command.Id, cancellationToken).ConfigureAwait(false); if (removeProviderConfigurationsResult.IsFailure) return removeProviderConfigurationsResult.Errors; Result deletePersistenceLibraryResult = await _unitOfWork.LibraryRepository.DeleteByIdAsync(command.Id, cancellationToken).ConfigureAwait(false); if (deletePersistenceLibraryResult.IsFailure) return deletePersistenceLibraryResult.Errors; - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); - return deletePersistenceLibraryResult; + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + + return Result.Deleted; } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandHandler.cs index ded8c73b..139ab583 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandHandler.cs @@ -61,46 +61,46 @@ public class ScanLibrariesCommandHandler : ICommandHandlerAn representing either a successful operation, or an error. public async Task>> HandleAsync(ScanLibrariesCommand command, CancellationToken cancellationToken) { - // an authenticated request must always carry a user identity + // An authenticated request must always carry a user identity. Guid? currentUserId = _currentUserService.UserId; if (currentUserId is null) return Errors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // get all media libraries that are enabled and unlocked from the persistence medium + // Get all media libraries that are enabled and unlocked from the persistence medium. Result> getLibrariesResult = await _unitOfWork.LibraryRepository.GetAllEnabledAndUnlockedAsync(cancellationToken).ConfigureAwait(false); if (getLibrariesResult.IsFailure) return getLibrariesResult.Errors; - // convert persistence libraries to domain entities + // Convert persistence libraries to domain entities. IEnumerable> domainEntitiesResult = getLibrariesResult.Value.ToDomainEntities(); - // if the current user is not an admin, they can only scan the libraries that belong to them + // If the current user is not an admin, they can only scan the libraries that belong to them. if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false)) domainEntitiesResult = domainEntitiesResult.Where(libraryResult => libraryResult.Value.UserId.Value == userId); List responses = []; List domainEvents = []; - // for each library, start the scan + // For each library, start the scan. foreach (Result domainLibraryResult in domainEntitiesResult) { if (domainLibraryResult.IsFailure) return domainLibraryResult.Errors; - // get the past month's scans for this library + // Get the past month's scans for this library. Result> pastLibraryScansResult = await _unitOfWork.LibraryScanRepository.GetPastMonthScansByLibraryIdAsync(domainLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false); if (pastLibraryScansResult.IsFailure) return pastLibraryScansResult.Errors; - // convert the repository scans history to domain objects + // Convert the repository scans history to domain objects. IEnumerable> pastLibraryScansDomainResult = pastLibraryScansResult.Value.ToDomainEntities(); foreach (Result pastLibraryScanDomainResult in pastLibraryScansDomainResult) if (pastLibraryScanDomainResult.IsFailure) return pastLibraryScanDomainResult.Errors; - // start the media library scan + // Start the media library scan. Result libraryScanResult = LibraryScan.Create( LibraryId.Create(domainLibraryResult.Value.Id.Value), UserId.Create(userId), @@ -110,25 +110,27 @@ public class ScanLibrariesCommandHandler : ICommandHandler startScanResult = libraryScanResult.Value.QueueScan(); - // when the user demands a "scan all libraries" action, it would be annoying to receive an error if a library is already being scanned. - // instead, just don't start the scan on such a library, and start it on the others that can be started + // When the user demands a "scan all libraries" action, it would be annoying to receive an error if a library is already being scanned. + // Instead, just don't start the scan on such a library, and start it on the others that can be started. if (startScanResult.IsFailure) continue; - // add the library scan to the persistence medium + // Add the library scan to the persistence medium. Result insertLibraryScanResult = await _unitOfWork.LibraryScanRepository.InsertAsync(libraryScanResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); if (insertLibraryScanResult.IsFailure) return insertLibraryScanResult.Errors; - // collect all the domain events created during this library scan start + // Collect all the domain events created during this library scan start. domainEvents.AddRange(libraryScanResult.Value.GetDomainEvents()); responses.Add(new MediaLibraryScanResponse(libraryScanResult.Value.Id.Value, domainLibraryResult.Value.Id.Value)); } - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; - // queue any domain events + // Queue any domain events. foreach (IDomainEvent domainEvent in domainEvents) _domainEventsQueue.Enqueue(domainEvent); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandHandler.cs index 1f0763d1..d3ad0b32 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandHandler.cs @@ -73,50 +73,50 @@ public class ScanLibraryCommandHandler : ICommandHandler 0) return validationResult; - // an authenticated request must always carry a user identity + // An authenticated request must always carry a user identity. Guid? currentUserId = _currentUserService.UserId; if (currentUserId is null) return ApplicationErrors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // get the media library from the persistence medium - Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false); + // Get the media library from the persistence medium. + Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(command.Id, cancellationToken: cancellationToken).ConfigureAwait(false); if (getLibraryResult.IsFailure) return getLibraryResult.Errors; if (getLibraryResult.Value is null) return DomainErrors.Library.LibraryNotFound; - // admins can scan any library; for everyone else, only the libraries they own + // Admins can scan any library; for everyone else, only the libraries they own. bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( userId, new LibraryOwnershipPolicyContext(command.Id), cancellationToken).ConfigureAwait(false); if (!canAccessLibrary) return ApplicationErrors.Authorization.NotAuthorized; - // check if the library is enabled and unlocked, before scanning it + // Check if the library is enabled and unlocked, before scanning it. if (!getLibraryResult.Value.IsEnabled) return DomainErrors.Library.CannotScanDisabledLibrary; if (getLibraryResult.Value.IsLocked) return DomainErrors.Library.CannotScanLockedLibrary; - // convert the persistence library to a domain entity + // Convert the persistence library to a domain entity. Result domainLibraryResult = getLibraryResult.Value.ToDomainEntity(); if (domainLibraryResult.IsFailure) return domainLibraryResult.Errors; - // get the past month's scans for this library + // Get the past month's scans for this library. Result> pastLibraryScansResult = await _unitOfWork.LibraryScanRepository.GetPastMonthScansByLibraryIdAsync(command.Id, cancellationToken).ConfigureAwait(false); if (pastLibraryScansResult.IsFailure) return pastLibraryScansResult.Errors; - // convert the repository scans history to domain objects + // Convert the repository scans history to domain objects. IEnumerable> pastLibraryScansDomainResult = pastLibraryScansResult.Value.ToDomainEntities(); foreach (Result pastLibraryScanDomainResult in pastLibraryScansDomainResult) if (pastLibraryScanDomainResult.IsFailure) return pastLibraryScanDomainResult.Errors; - // queue the media library scan + // Queue the media library scan. Result libraryScanResult = LibraryScan.Create( LibraryId.Create(command.Id), UserId.Create(userId), @@ -129,14 +129,16 @@ public class ScanLibraryCommandHandler : ICommandHandler insertLibraryScanResult = await _unitOfWork.LibraryScanRepository.InsertAsync(libraryScanResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); if (insertLibraryScanResult.IsFailure) return insertLibraryScanResult.Errors; - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; - // queue any domain events + // Queue any domain events. foreach (IDomainEvent domainEvent in libraryScanResult.Value.GetDomainEvents()) _domainEventsQueue.Enqueue(domainEvent); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs index 52de01c6..42fe46cb 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs @@ -87,21 +87,21 @@ public class UpdateLibraryCommandHandler : ICommandHandler 0) return validationResult; - // an authenticated request must always carry a user identity + // An authenticated request must always carry a user identity. Guid? currentUserId = _currentUserService.UserId; if (currentUserId is null) return ApplicationErrors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // get a library repository and retrieve the library to update - Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false); + // Get a library repository and retrieve the library to update. + Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(command.Id, cancellationToken: cancellationToken).ConfigureAwait(false); if (getLibraryResult.IsFailure) return getLibraryResult.Errors; else if (getLibraryResult.Value is null) return DomainErrors.Library.LibraryNotFound; - // make sure the file is an actual supported image, but only when a new cover image was chosen; the stored cover image is - // relative to the application base directory and is already validated, so it must not block saving unrelated changes + // Make sure the file is an actual supported image, but only when a new cover image was chosen; the stored cover image is + // relative to the application base directory and is already validated, so it must not block saving unrelated changes. if (command.CoverImage is not null && command.CoverImage != getLibraryResult.Value.CoverImage) { Result fileSystemPathIdResult = FileSystemPathId.Create(command.CoverImage); @@ -115,14 +115,14 @@ public class UpdateLibraryCommandHandler : ICommandHandler( userId, new LibraryOwnershipPolicyContext(command.Id), cancellationToken).ConfigureAwait(false); if (!hasManagePermission && !canAccessLibrary) return ApplicationErrors.Authorization.NotAuthorized; - // create a domain library object + // Create a domain library object. LibraryType newLibraryType = Enum.Parse(command.LibraryType!); Result createLibraryResult = Library.Create( LibraryId.Create(command.Id), @@ -130,7 +130,7 @@ public class UpdateLibraryCommandHandler : ICommandHandler.FromNullable(command.CoverImage), command.IsEnabled, command.IsLocked, command.CanDownloadMetadataFromWeb, @@ -140,11 +140,11 @@ public class UpdateLibraryCommandHandler : ICommandHandler updateLibraryResult = await _unitOfWork.LibraryRepository.UpdateAsync(persistenceLibrary, cancellationToken).ConfigureAwait(false); if (updateLibraryResult.IsFailure) return updateLibraryResult.Errors; @@ -154,19 +154,21 @@ public class UpdateLibraryCommandHandler : ICommandHandler saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; - // retrieve the updated media library from the persistence medium and return it - Result getCreatedLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false); + // Retrieve the updated media library from the persistence medium and return it. + Result getCreatedLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken: cancellationToken).ConfigureAwait(false); if (getCreatedLibraryResult.IsFailure) return getCreatedLibraryResult.Errors; if (getCreatedLibraryResult.Value is null) return ApplicationErrors.Persistence.ErrorPersistingMediaLibrary; - // mark the media library as saved + // Mark the media library as saved. createLibraryResult.Value.Save(); - // queue any domain events + // Queue any domain events. foreach (IDomainEvent domainEvent in createLibraryResult.Value.GetDomainEvents()) _domainEventsQueue.Enqueue(domainEvent); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryMediaItemDeletedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryMediaItemDeletedDomainEventHandler.cs index 551cd269..7c68e86b 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryMediaItemDeletedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryMediaItemDeletedDomainEventHandler.cs @@ -48,7 +48,7 @@ public class LibraryMediaItemDeletedDomainEventHandler : IDomainEventHandler getBookResult = await _unitOfWork.BookRepository.GetByPathAsync(libraryId, domainEvent.Path, cancellationToken).ConfigureAwait(false); if (getBookResult.IsFailure) throw new EventualConsistencyException(getBookResult.FirstError, getBookResult.Errors); @@ -56,8 +56,8 @@ public class LibraryMediaItemDeletedDomainEventHandler : IDomainEventHandler getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(libraryId, cancellationToken).ConfigureAwait(false); + // Delete the stored artwork of the book, best-effort, since a stale cover must not prevent the book from being removed. + Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(libraryId, cancellationToken: cancellationToken).ConfigureAwait(false); if (getLibraryResult.IsFailure || getLibraryResult.Value is null) throw new EventualConsistencyException(getLibraryResult.FirstError, getLibraryResult.Errors); LibraryEntity library = getLibraryResult.Value; @@ -71,11 +71,13 @@ public class LibraryMediaItemDeletedDomainEventHandler : IDomainEventHandler deleteBookResult = await _unitOfWork.BookRepository.DeleteAsync(book.Id, cancellationToken).ConfigureAwait(false); + // Delete the book, whose stored artwork and participations are removed by the database cascade. + Result deleteBookResult = await _unitOfWork.BookRepository.DeleteByIdAsync(book.Id, cancellationToken).ConfigureAwait(false); if (deleteBookResult.IsFailure) throw new EventualConsistencyException(deleteBookResult.FirstError, deleteBookResult.Errors); - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + throw new EventualConsistencyException(saveChangesResult.FirstError, saveChangesResult.Errors); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandler.cs index 9772737d..59f79bdc 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandler.cs @@ -58,21 +58,23 @@ public class LibrarySavedDomainEventHandler : IDomainEventHandlerCancellation token that can be used to stop the execution. public async ValueTask HandleAsync(LibrarySavedDomainEvent domainEvent, CancellationToken cancellationToken) { - if (domainEvent.Library.CoverImage is not null) + if (domainEvent.Library.CoverImage.HasValue) { - // attempt to copy the image from the original location provided by the user to the internal location for media library files - Result saveCoverImageResult = await SaveCoverImageToMediaDirectoryAsync(domainEvent.Library.Id.Value, domainEvent.Library.CoverImage, cancellationToken).ConfigureAwait(false); + // Attempt to copy the image from the original location provided by the user to the internal location for media library files. + Result saveCoverImageResult = await SaveCoverImageToMediaDirectoryAsync(domainEvent.Library.Id.Value, domainEvent.Library.CoverImage.Value, cancellationToken).ConfigureAwait(false); if (saveCoverImageResult.IsFailure) throw new EventualConsistencyException(saveCoverImageResult.FirstError, saveCoverImageResult.Errors); domainEvent.Library.SetInternalLibraryCoverImagePath(saveCoverImageResult.Value); - // update the media library with the new cover location + // Update the media library with the new cover location. Result updateLibraryResult = await _unitOfWork.LibraryRepository.UpdateAsync(domainEvent.Library.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); if (updateLibraryResult.IsFailure) throw new EventualConsistencyException(updateLibraryResult.FirstError, updateLibraryResult.Errors); - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + throw new EventualConsistencyException(saveChangesResult.FirstError, saveChangesResult.Errors); } - else // no cover image is provided, delete any cover image that might exist in the internal location for media library files + else // No cover image is provided, delete any cover image that might exist in the internal location for media library files. { Result libraryPathResult = GetLibraryPath(domainEvent.Library.Id.Value); if (libraryPathResult.IsFailure) @@ -90,17 +92,17 @@ public class LibrarySavedDomainEventHandler : IDomainEventHandler private Result GetLibraryPath(Guid libraryId) { - // root directory for media + // Root directory for media. Result rootPathResult = _pathService.CombinePath(AppContext.BaseDirectory, _mediaSettingsModel.RootDirectory); if (rootPathResult.IsFailure) return rootPathResult.Errors; - // libraries directory + // Libraries directory. Result librariesPathResult = _pathService.CombinePath(rootPathResult.Value, _mediaSettingsModel.LibrariesDirectory); if (librariesPathResult.IsFailure) return librariesPathResult.Errors; - // this new particular library' directory + // This new particular library's directory. Result libraryPathResult = _pathService.CombinePath(librariesPathResult.Value, libraryId.ToString()); if (libraryPathResult.IsFailure) return libraryPathResult.Errors; @@ -142,8 +144,8 @@ public class LibrarySavedDomainEventHandler : IDomainEventHandler internalImagePathIdResult = ResolveInternalMediaPathId(imagePath); @@ -157,19 +159,19 @@ public class LibrarySavedDomainEventHandler : IDomainEventHandler imageCheckResult = await _environmentContext.FileTypeService.GetImageTypeAsync(fileSystemPathIdResult.Value, cancellationToken).ConfigureAwait(false); if (imageCheckResult.IsFailure) return imageCheckResult.Errors; if (imageCheckResult.Value == ImageType.None) return Errors.Library.CoverFileMustBeAnImage; - // the provided cover image path exists and is a valid image, store it in the media directory - Result rootPathResult = _pathService.CombinePath(AppContext.BaseDirectory, _mediaSettingsModel.RootDirectory); // root directory for media + // The provided cover image path exists and is a valid image, store it in the media directory. + Result rootPathResult = _pathService.CombinePath(AppContext.BaseDirectory, _mediaSettingsModel.RootDirectory); // Root directory for media. if (rootPathResult.IsFailure) return rootPathResult.Errors; - Result librariesPathResult = _pathService.CombinePath(rootPathResult.Value, _mediaSettingsModel.LibrariesDirectory); // libraries directory + Result librariesPathResult = _pathService.CombinePath(rootPathResult.Value, _mediaSettingsModel.LibrariesDirectory); // Libraries directory. if (librariesPathResult.IsFailure) return librariesPathResult.Errors; @@ -181,7 +183,7 @@ public class LibrarySavedDomainEventHandler : IDomainEventHandler libraryPathResult = GetLibraryPath(libraryId); if (libraryPathResult.IsFailure) return libraryPathResult.Errors; @@ -190,7 +192,7 @@ public class LibrarySavedDomainEventHandler : IDomainEventHandler directoryExistsResult = _environmentContext.DirectoryProviderService.DirectoryExists(newLibraryPathIdResult.Value); if (directoryExistsResult.IsFailure) return directoryExistsResult.Errors; @@ -203,24 +205,24 @@ public class LibrarySavedDomainEventHandler : IDomainEventHandler deleteExistingCoverImageResult = DeleteCoverImageFromMediaDirectory(libraryPathResult.Value); if (deleteExistingCoverImageResult.IsFailure) return deleteExistingCoverImageResult.Errors; } - // copy the new cover file from the location provided by the user + // Copy the new cover file from the location provided by the user. Result copyFileResult = _environmentContext.FileProviderService.CopyFile(fileSystemPathIdResult.Value, newLibraryPathIdResult.Value, true); if (copyFileResult.IsFailure) return copyFileResult.Errors; - // rename the new cover file to the standard naming + // Rename the new cover file to the standard naming. Result renameFileResult = _environmentContext.FileProviderService.RenameFile(copyFileResult.Value, $"cover.{imageCheckResult.Value.ToString().ToLower()}"); if (renameFileResult.IsFailure) return renameFileResult.Errors; - // get the internal relative path for the copied file + // Get the internal relative path for the copied file. string relativePath = renameFileResult.Value.Path[AppContext.BaseDirectory.Length..]; if (!relativePath.StartsWith(_pathService.PathSeparator)) relativePath = $"{_pathService.PathSeparator}{relativePath}"; @@ -239,7 +241,7 @@ public class LibrarySavedDomainEventHandler : IDomainEventHandler> getExistingLibraryFilesResult = _environmentContext.FileProviderService.GetFilePaths(newLibraryPathIdResult.Value, true); if (getExistingLibraryFilesResult.IsFailure) return getExistingLibraryFilesResult.Errors; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandler.cs index 483bbccf..f56f5bcd 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandler.cs @@ -54,41 +54,43 @@ public class LibraryScanFailedDomainEventHandler : IDomainEventHandlerCancellation token that can be used to stop the execution. public async ValueTask HandleAsync(LibraryScanFailedDomainEvent domainEvent, CancellationToken cancellationToken) { - // get the library scan from the repository + // Get the library scan from the repository. Result getLibraryScanResult = await _unitOfWork.LibraryScanRepository.GetByIdAsync( - domainEvent.MediaLibraryScanCompositeId.ScanId.Value, cancellationToken).ConfigureAwait(false); + domainEvent.MediaLibraryScanCompositeId.ScanId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); if (getLibraryScanResult.IsFailure) throw new EventualConsistencyException(getLibraryScanResult.FirstError, getLibraryScanResult.Errors); if (getLibraryScanResult.Value is null) throw new EventualConsistencyException(Errors.LibraryScanning.LibraryScanNotFound); - // convert the repository scan to a domain object + // Convert the repository scan to a domain object. Result libraryScanDomainResult = getLibraryScanResult.Value.ToDomainEntity(); if (libraryScanDomainResult.IsFailure) throw new EventualConsistencyException(libraryScanDomainResult.FirstError, libraryScanDomainResult.Errors); - // mark the media library scan as failed + // Mark the media library scan as failed. Result failScanResult = libraryScanDomainResult.Value.FailScan(); - // we're going to ignore errors in this point, because scan jobs run in parallel, and two concurrent jobs of the same scan might trigger this domain event, - // trying to set as failed a scan that has already been marked as failed by a concurrent job + // We're going to ignore errors in this point, because scan jobs run in parallel, and two concurrent jobs of the same scan might trigger this domain event, + // trying to set as failed a scan that has already been marked as failed by a concurrent job. if (!failScanResult.IsFailure) { - // update the status of the library scan in the repository + // Update the status of the library scan in the repository. Result updateLibraryScanResult = await _unitOfWork.LibraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); if (updateLibraryScanResult.IsFailure) throw new EventualConsistencyException(updateLibraryScanResult.FirstError, updateLibraryScanResult.Errors); - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + throw new EventualConsistencyException(saveChangesResult.FirstError, saveChangesResult.Errors); } - // release the scan processing resources, regardless of whether the scan was already marked as failed by a concurrent job + // Release the scan processing resources, regardless of whether the scan was already marked as failed by a concurrent job. _mediaLibrariesScanCancellationTracker.RemoveScan(domainEvent.MediaLibraryScanCompositeId); _mediaLibrariesScanProgressTracker.RemoveScanProgress(domainEvent.MediaLibraryScanCompositeId); Result clearStagingResult = await _unitOfWork.LibraryScanStagingResultsRepository.ClearForScanAsync(domainEvent.MediaLibraryScanCompositeId.ScanId.Value, cancellationToken).ConfigureAwait(false); if (clearStagingResult.IsFailure) throw new EventualConsistencyException(clearStagingResult.FirstError, clearStagingResult.Errors); - // notify SignalR clients that the library scan failed + // Notify SignalR clients that the library scan failed. await _debouncedLibraryScanProgressNotifier.SendLibraryScanFailedEventAsync(domainEvent.MediaLibraryScanCompositeId, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFinishedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFinishedDomainEventHandler.cs index c541f390..034c50ba 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFinishedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFinishedDomainEventHandler.cs @@ -54,36 +54,38 @@ public class LibraryScanFinishedDomainEventHandler : IDomainEventHandlerCancellation token that can be used to stop the execution. public async ValueTask HandleAsync(LibraryScanFinishedDomainEvent domainEvent, CancellationToken cancellationToken) { - // get the library scan from the repository + // Get the library scan from the repository. Result getLibraryScansResult = await _unitOfWork.LibraryScanRepository.GetByIdAsync( - domainEvent.MediaLibraryScanCompositeId.ScanId.Value, cancellationToken).ConfigureAwait(false); + domainEvent.MediaLibraryScanCompositeId.ScanId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); if (getLibraryScansResult.IsFailure) throw new EventualConsistencyException(getLibraryScansResult.FirstError, getLibraryScansResult.Errors); if (getLibraryScansResult.Value is null) throw new EventualConsistencyException(Errors.LibraryScanning.LibraryScanNotFound); - // convert the repository scan to a domain object + // Convert the repository scan to a domain object. Result libraryScanDomainResult = getLibraryScansResult.Value.ToDomainEntity(); if (libraryScanDomainResult.IsFailure) throw new EventualConsistencyException(libraryScanDomainResult.FirstError, libraryScanDomainResult.Errors); - // mark the media library scan as finished + // Mark the media library scan as finished. Result finishScanResult = libraryScanDomainResult.Value.FinishScan(); if (finishScanResult.IsFailure) throw new EventualConsistencyException(finishScanResult.FirstError, finishScanResult.Errors); - // update the library scan in the repository + // Update the library scan in the repository. Result updateLibraryScanResult = await _unitOfWork.LibraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); if (updateLibraryScanResult.IsFailure) throw new EventualConsistencyException(updateLibraryScanResult.FirstError, updateLibraryScanResult.Errors); - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + throw new EventualConsistencyException(saveChangesResult.FirstError, saveChangesResult.Errors); - // mark the scan progress as finished + // Mark the scan progress as finished. _mediaLibrariesScanProgressTracker.UpdateScanProgress(libraryScanDomainResult.Value.LibraryId, domainEvent.MediaLibraryScanCompositeId); - // notify SignalR clients that the library scan finished + // Notify SignalR clients that the library scan finished. await _debouncedLibraryScanProgressNotifier.SendLibraryScanFinishedEventAsync(domainEvent.MediaLibraryScanCompositeId, cancellationToken).ConfigureAwait(false); - // only when everything is done, this needs to be called in order to dispose cancellation token sources, etc + // Only when everything is done, this needs to be called in order to dispose cancellation token sources, etc. _mediaLibrariesScanCancellationTracker.RemoveScan(domainEvent.MediaLibraryScanCompositeId); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanStartedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanStartedDomainEventHandler.cs index ac2140c8..3f17b5d9 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanStartedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanStartedDomainEventHandler.cs @@ -35,11 +35,13 @@ public class LibraryScanStartedDomainEventHandler : IDomainEventHandlerCancellation token that can be used to stop the execution. public async ValueTask HandleAsync(LibraryScanStartedDomainEvent domainEvent, CancellationToken cancellationToken) { - // update the status of the library scan in the repository + // Update the status of the library scan in the repository. Result updateLibraryScanResult = await _unitOfWork.LibraryScanRepository.UpdateAsync(domainEvent.LibraryScan.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); if (updateLibraryScanResult.IsFailure) throw new EventualConsistencyException(updateLibraryScanResult.FirstError, updateLibraryScanResult.Errors); - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + throw new EventualConsistencyException(saveChangesResult.FirstError, saveChangesResult.Errors); } } diff --git a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandHandler.cs b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandHandler.cs index eff8b941..8c713a6b 100644 --- a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandHandler.cs +++ b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandHandler.cs @@ -57,23 +57,26 @@ public class ReorderLibraryArtworkProvidersCommandHandler : ICommandHandler 0) return validationResult; - // an authenticated request must always carry a user identity + // An authenticated request must always carry a user identity. Guid? currentUserId = _currentUserService.UserId; if (currentUserId is null) return ApplicationErrors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // admins can reorder the artwork providers of any library; for everyone else, only their own libraries + // Admins can reorder the artwork providers of any library; for everyone else, only their own libraries. bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( userId, new LibraryOwnershipPolicyContext(command.LibraryId), cancellationToken).ConfigureAwait(false); if (!canAccessLibrary) return ApplicationErrors.Authorization.NotAuthorized; + // Load the artwork provider configurations that are currently registered for the library, so that only providers it actually has are reordered. Result> getConfigurationsResult = await _unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false); if (getConfigurationsResult.IsFailure) return getConfigurationsResult.Errors; + // Index the configurations by plugin id, so that each requested plugin can be matched without repeatedly searching the list. Dictionary configurationsByPluginId = getConfigurationsResult.Value.ToDictionary(configuration => configuration.PluginId); + // Walk the requested order and assign each provider the 1-based rank that matches its position in the command, so the persisted order follows the user's choice. for (int rank = 0; rank < command.PluginIds.Count; rank++) { Guid pluginId = command.PluginIds[rank]; @@ -86,7 +89,10 @@ public class ReorderLibraryArtworkProvidersCommandHandler : ICommandHandler saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; return Result.Success; } } diff --git a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandler.cs b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandler.cs index 8fc10e5b..3b3133c8 100644 --- a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandler.cs +++ b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandler.cs @@ -56,23 +56,26 @@ public class ReorderLibraryMetadataProvidersCommandHandler : ICommandHandler 0) return validationResult; - // an authenticated request must always carry a user identity + // An authenticated request must always carry a user identity. Guid? currentUserId = _currentUserService.UserId; if (currentUserId is null) return ApplicationErrors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // admins can reorder the metadata providers of any library; for everyone else, only their own libraries + // Admins can reorder the metadata providers of any library; for everyone else, only their own libraries. bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( userId, new LibraryOwnershipPolicyContext(command.LibraryId), cancellationToken).ConfigureAwait(false); if (!canAccessLibrary) return ApplicationErrors.Authorization.NotAuthorized; + // Load the metadata provider configurations that are currently registered for the library, so that only providers it actually has are reordered. Result> getConfigurationsResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false); if (getConfigurationsResult.IsFailure) return getConfigurationsResult.Errors; + // Index the configurations by plugin id, so that each requested plugin can be matched without repeatedly searching the list. Dictionary configurationsByPluginId = getConfigurationsResult.Value.ToDictionary(configuration => configuration.PluginId); + // Walk the requested order and assign each provider the 1-based rank that matches its position in the command, so the persisted order follows the user's choice. for (int rank = 0; rank < command.PluginIds.Count; rank++) { Guid pluginId = command.PluginIds[rank]; @@ -85,7 +88,10 @@ public class ReorderLibraryMetadataProvidersCommandHandler : ICommandHandler saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; return Result.Success; } } diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandHandler.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandHandler.cs index c1974e81..09b304db 100644 --- a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandHandler.cs +++ b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandHandler.cs @@ -56,18 +56,19 @@ public class SetLibraryArtworkProviderEnabledCommandHandler : ICommandHandler 0) return validationResult; - // an authenticated request must always carry a user identity + // An authenticated request must always carry a user identity. Guid? currentUserId = _currentUserService.UserId; if (currentUserId is null) return ApplicationErrors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // admins can configure the artwork providers of any library; for everyone else, only their own libraries + // Admins can configure the artwork providers of any library; for everyone else, only their own libraries. bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( userId, new LibraryOwnershipPolicyContext(command.LibraryId), cancellationToken).ConfigureAwait(false); if (!canAccessLibrary) return ApplicationErrors.Authorization.NotAuthorized; + // Look up the configuration of this provider for the library, so that an existing one is toggled instead of duplicated. Result getConfigurationResult = await _unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, cancellationToken).ConfigureAwait(false); if (getConfigurationResult.IsFailure) return getConfigurationResult.Errors; @@ -75,12 +76,13 @@ public class SetLibraryArtworkProviderEnabledCommandHandler : ICommandHandler> getConfigurationsResult = await _unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false); if (getConfigurationsResult.IsFailure) return getConfigurationsResult.Errors; @@ -98,10 +100,14 @@ public class SetLibraryArtworkProviderEnabledCommandHandler : ICommandHandler upsertResult = await _unitOfWork.ArtworkProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false); if (upsertResult.IsFailure) return upsertResult.Errors; - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; return Result.Success; } } diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandler.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandler.cs index 21e21978..526852b2 100644 --- a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandler.cs +++ b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandler.cs @@ -56,18 +56,19 @@ public class SetLibraryMetadataProviderEnabledCommandHandler : ICommandHandler 0) return validationResult; - // an authenticated request must always carry a user identity + // An authenticated request must always carry a user identity. Guid? currentUserId = _currentUserService.UserId; if (currentUserId is null) return ApplicationErrors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // admins can configure the metadata providers of any library; for everyone else, only their own libraries + // Admins can configure the metadata providers of any library; for everyone else, only their own libraries. bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( userId, new LibraryOwnershipPolicyContext(command.LibraryId), cancellationToken).ConfigureAwait(false); if (!canAccessLibrary) return ApplicationErrors.Authorization.NotAuthorized; + // Look up the configuration of this provider for the library, so that an existing one is toggled instead of duplicated. Result getConfigurationResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, cancellationToken).ConfigureAwait(false); if (getConfigurationResult.IsFailure) return getConfigurationResult.Errors; @@ -75,12 +76,13 @@ public class SetLibraryMetadataProviderEnabledCommandHandler : ICommandHandler> getConfigurationsResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false); if (getConfigurationsResult.IsFailure) return getConfigurationsResult.Errors; @@ -98,10 +100,14 @@ public class SetLibraryMetadataProviderEnabledCommandHandler : ICommandHandler upsertResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false); if (upsertResult.IsFailure) return upsertResult.Errors; - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; return Result.Success; } } diff --git a/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandler.cs b/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandler.cs index 780748dc..5231bd97 100644 --- a/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandler.cs +++ b/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandler.cs @@ -49,7 +49,11 @@ public class UpdatePluginSettingsCommandHandler : ICommandHandler updateResult = await _unitOfWork.PluginRepository.UpdateSettingsAsync(command.PluginId, settingsJson, cancellationToken).ConfigureAwait(false); if (updateResult.IsFailure) return updateResult.Errors; - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + return Result.Success; } } diff --git a/src/Lumina.Application/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandHandler.cs b/src/Lumina.Application/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandHandler.cs index 02151efa..64cb0016 100644 --- a/src/Lumina.Application/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandHandler.cs +++ b/src/Lumina.Application/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandHandler.cs @@ -118,7 +118,10 @@ public class AddScheduledJobCommandHandler : ICommandHandler insertScheduledJobResult = await _unitOfWork.ScheduledJobRepository.InsertAsync(persistenceScheduledJob, cancellationToken).ConfigureAwait(false); if (insertScheduledJobResult.IsFailure) return insertScheduledJobResult.Errors; - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; // Queue any domain events. foreach (IDomainEvent domainEvent in createScheduledJobResult.Value.GetDomainEvents()) diff --git a/src/Lumina.Application/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommandHandler.cs b/src/Lumina.Application/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommandHandler.cs index ba19721c..7c843186 100644 --- a/src/Lumina.Application/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommandHandler.cs +++ b/src/Lumina.Application/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommandHandler.cs @@ -83,7 +83,7 @@ public class RemoveScheduledJobCommandHandler : ICommandHandler getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken).ConfigureAwait(false); + Result getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: cancellationToken).ConfigureAwait(false); if (getScheduledJobResult.IsFailure) return getScheduledJobResult.Errors; if (getScheduledJobResult.Value is null) @@ -102,7 +102,10 @@ public class RemoveScheduledJobCommandHandler : ICommandHandler deleteScheduledJobResult = await _unitOfWork.ScheduledJobRepository.DeleteByIdAsync(command.ScheduledJobId, cancellationToken).ConfigureAwait(false); if (deleteScheduledJobResult.IsFailure) return deleteScheduledJobResult.Errors; - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; // Queue any domain events. scheduledJobDomainResult.Value.Remove(); diff --git a/src/Lumina.Application/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommandHandler.cs b/src/Lumina.Application/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommandHandler.cs index f5c0be2f..d69614f7 100644 --- a/src/Lumina.Application/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommandHandler.cs +++ b/src/Lumina.Application/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommandHandler.cs @@ -80,7 +80,7 @@ public class StartScheduledJobCommandHandler : ICommandHandler getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken).ConfigureAwait(false); + Result getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: cancellationToken).ConfigureAwait(false); if (getScheduledJobResult.IsFailure) return getScheduledJobResult.Errors; if (getScheduledJobResult.Value is null) @@ -98,7 +98,10 @@ public class StartScheduledJobCommandHandler : ICommandHandler updateScheduledJobResult = await _unitOfWork.ScheduledJobRepository.UpdateAsync(scheduledJobDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); if (updateScheduledJobResult.IsFailure) return updateScheduledJobResult.Errors; - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; // Queue any domain events. foreach (IDomainEvent domainEvent in scheduledJobDomainResult.Value.GetDomainEvents()) diff --git a/src/Lumina.Application/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommandHandler.cs b/src/Lumina.Application/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommandHandler.cs index 177e0865..af1b937c 100644 --- a/src/Lumina.Application/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommandHandler.cs +++ b/src/Lumina.Application/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommandHandler.cs @@ -84,7 +84,7 @@ public class StopScheduledJobCommandHandler : ICommandHandler getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken).ConfigureAwait(false); + Result getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: cancellationToken).ConfigureAwait(false); if (getScheduledJobResult.IsFailure) return getScheduledJobResult.Errors; if (getScheduledJobResult.Value is null) @@ -102,7 +102,10 @@ public class StopScheduledJobCommandHandler : ICommandHandler updateScheduledJobResult = await _unitOfWork.ScheduledJobRepository.UpdateAsync(scheduledJobDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); if (updateScheduledJobResult.IsFailure) return updateScheduledJobResult.Errors; - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; // Stop the execution cycle in the scheduler service. await _scheduledJobScheduler.StopCycleAsync(scheduledJobDomainResult.Value.Id, cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Application/Core/Scheduling/Commands/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesCommandHandler.cs b/src/Lumina.Application/Core/Scheduling/Commands/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesCommandHandler.cs index 54c6fa4b..c3634b7e 100644 --- a/src/Lumina.Application/Core/Scheduling/Commands/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesCommandHandler.cs +++ b/src/Lumina.Application/Core/Scheduling/Commands/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesCommandHandler.cs @@ -80,7 +80,11 @@ public class UpdateSchedulerDisplayPreferencesCommandHandler : ICommandHandler upsertResult = await _unitOfWork.SchedulerDisplayPreferencesRepository.UpsertAsync(displayPreferences, cancellationToken).ConfigureAwait(false); if (upsertResult.IsFailure) return upsertResult.Errors; - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + return Result.Updated; } } diff --git a/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionCompletedDomainEventHandler.cs b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionCompletedDomainEventHandler.cs index 6d2df8ee..b2dd7aa8 100644 --- a/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionCompletedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionCompletedDomainEventHandler.cs @@ -1,6 +1,8 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Scheduling; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Mapping.Scheduling; using Lumina.Application.Core.Scheduling.Notifications; using Lumina.Contracts.Responses.Scheduling; @@ -10,7 +12,6 @@ using Lumina.Domain.Common.Exceptions; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; -using System; using System.Collections.Generic; using System.Linq; using System.Threading; @@ -46,7 +47,7 @@ public class ScheduledJobExecutionCompletedDomainEventHandler : IDomainEventHand public async ValueTask HandleAsync(ScheduledJobExecutionCompletedDomainEvent domainEvent, CancellationToken cancellationToken) { // Get the scheduled job from the repository. - Result getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, cancellationToken).ConfigureAwait(false); + Result getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); if (getScheduledJobResult.IsFailure) throw new EventualConsistencyException(getScheduledJobResult.FirstError, getScheduledJobResult.Errors); if (getScheduledJobResult.Value is null) @@ -55,94 +56,42 @@ public class ScheduledJobExecutionCompletedDomainEventHandler : IDomainEventHand // A cycle run returns the scheduled job to its active status, a one time execution completes it. ScheduledJobStatus status = domainEvent.IsCycleRun ? ScheduledJobStatus.Active : ScheduledJobStatus.Completed; - ScheduledJobEntity updatedScheduledJob = CreateUpdatedScheduledJob(scheduledJob, status, scheduledJob.LastStartedOnUtc, domainEvent.CompletedOnUtc); + ScheduledJobEntity updatedScheduledJob = scheduledJob.ToUpdatedRepositoryEntity(status, scheduledJob.LastStartedOnUtc, domainEvent.CompletedOnUtc); Result updateScheduledJobResult = await _unitOfWork.ScheduledJobRepository.UpdateAsync(updatedScheduledJob, cancellationToken).ConfigureAwait(false); if (updateScheduledJobResult.IsFailure) throw new EventualConsistencyException(updateScheduledJobResult.FirstError, updateScheduledJobResult.Errors); // Mark the execution of the task of the scheduled job as completed. - Result getExecutionResult = await _unitOfWork.ScheduledJobExecutionRepository.GetByIdAsync(domainEvent.RunId, cancellationToken).ConfigureAwait(false); + Result getExecutionResult = await _unitOfWork.ScheduledJobExecutionRepository.GetByIdAsync(domainEvent.RunId, cancellationToken: cancellationToken).ConfigureAwait(false); if (getExecutionResult.IsFailure) throw new EventualConsistencyException(getExecutionResult.FirstError, getExecutionResult.Errors); if (getExecutionResult.Value is null) throw new EventualConsistencyException(Errors.Scheduling.ScheduledJobExecutionNotFound); ScheduledJobExecutionEntity execution = getExecutionResult.Value; - ScheduledJobExecutionEntity updatedExecution = CreateUpdatedExecution(execution, domainEvent.CompletedOnUtc); + ScheduledJobExecutionEntity updatedExecution = execution.ToUpdatedRepositoryEntity(domainEvent.CompletedOnUtc); Result updateExecutionResult = await _unitOfWork.ScheduledJobExecutionRepository.UpdateAsync(updatedExecution, cancellationToken).ConfigureAwait(false); if (updateExecutionResult.IsFailure) throw new EventualConsistencyException(updateExecutionResult.FirstError, updateExecutionResult.Errors); - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + throw new EventualConsistencyException(saveChangesResult.FirstError, saveChangesResult.Errors); // Notify the SignalR clients about the current scheduled jobs and the completed execution. await NotifyCurrentScheduledJobsAsync(cancellationToken).ConfigureAwait(false); await _scheduledJobNotifier.SendScheduledJobExecutionCompletedAsync(updatedExecution.ToResponse(), cancellationToken).ConfigureAwait(false); } - /// - /// Creates a copy of with the provided status and timestamps. - /// - /// The scheduled job to copy. - /// The status of the copy. - /// The last start time of the copy. - /// The last completion time of the copy. - /// The copy of the scheduled job. - private static ScheduledJobEntity CreateUpdatedScheduledJob(ScheduledJobEntity scheduledJob, ScheduledJobStatus status, DateTime? lastStartedOnUtc, DateTime? lastCompletedOnUtc) - { - return new ScheduledJobEntity - { - Id = scheduledJob.Id, - Name = scheduledJob.Name, - TaskType = scheduledJob.TaskType, - ScheduleType = scheduledJob.ScheduleType, - IntervalMinutes = scheduledJob.IntervalMinutes, - Hour = scheduledJob.Hour, - Minute = scheduledJob.Minute, - Status = status, - OwnerUserId = scheduledJob.OwnerUserId, - LastStartedOnUtc = lastStartedOnUtc, - LastCompletedOnUtc = lastCompletedOnUtc, - CreatedOnUtc = scheduledJob.CreatedOnUtc, - CreatedBy = scheduledJob.CreatedBy, - UpdatedOnUtc = scheduledJob.UpdatedOnUtc, - UpdatedBy = scheduledJob.UpdatedBy - }; - } - - /// - /// Creates a copy of with the provided completion time. - /// - /// The execution to copy. - /// The completion time of the copy. - /// The copy of the execution. - private static ScheduledJobExecutionEntity CreateUpdatedExecution(ScheduledJobExecutionEntity execution, DateTime? completedOnUtc) - { - return new ScheduledJobExecutionEntity - { - Id = execution.Id, - ScheduledJobId = execution.ScheduledJobId, - TaskType = execution.TaskType, - IsCycleRun = execution.IsCycleRun, - WasCycleActive = execution.WasCycleActive, - StartedOnUtc = execution.StartedOnUtc, - CompletedOnUtc = completedOnUtc, - CreatedOnUtc = execution.CreatedOnUtc, - CreatedBy = execution.CreatedBy, - UpdatedOnUtc = execution.UpdatedOnUtc, - UpdatedBy = execution.UpdatedBy - }; - } - /// /// Notifies the SignalR clients about the current list of scheduled jobs. /// /// Cancellation token that can be used to stop the execution. private async Task NotifyCurrentScheduledJobsAsync(CancellationToken cancellationToken) { - Result> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + Result> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false); if (getScheduledJobsResult.IsFailure) throw new EventualConsistencyException(getScheduledJobsResult.FirstError, getScheduledJobsResult.Errors); - IReadOnlyList scheduledJobResponses = [.. getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse())]; + IReadOnlyList scheduledJobResponses = [.. getScheduledJobsResult.Value.Data.Select(scheduledJob => scheduledJob.ToResponse())]; await _scheduledJobNotifier.SendScheduledJobsAsync(scheduledJobResponses, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionStartedDomainEventHandler.cs b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionStartedDomainEventHandler.cs index 2e81591f..19dba01a 100644 --- a/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionStartedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionStartedDomainEventHandler.cs @@ -1,6 +1,8 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Scheduling; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Mapping.Scheduling; using Lumina.Application.Core.Scheduling.Notifications; using Lumina.Contracts.Responses.Scheduling; @@ -10,7 +12,6 @@ using Lumina.Domain.Common.Exceptions; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; -using System; using System.Collections.Generic; using System.Linq; using System.Threading; @@ -46,7 +47,7 @@ public class ScheduledJobExecutionStartedDomainEventHandler : IDomainEventHandle public async ValueTask HandleAsync(ScheduledJobExecutionStartedDomainEvent domainEvent, CancellationToken cancellationToken) { // Get the scheduled job from the repository. - Result getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, cancellationToken).ConfigureAwait(false); + Result getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); if (getScheduledJobResult.IsFailure) throw new EventualConsistencyException(getScheduledJobResult.FirstError, getScheduledJobResult.Errors); if (getScheduledJobResult.Value is null) @@ -57,7 +58,7 @@ public class ScheduledJobExecutionStartedDomainEventHandler : IDomainEventHandle bool wasCycleActive = scheduledJob.Status == ScheduledJobStatus.Active; // Update the scheduled job with its running status and the start time of the execution. - ScheduledJobEntity updatedScheduledJob = CreateUpdatedScheduledJob(scheduledJob, ScheduledJobStatus.Running, domainEvent.StartedOnUtc, scheduledJob.LastCompletedOnUtc); + ScheduledJobEntity updatedScheduledJob = scheduledJob.ToUpdatedRepositoryEntity(ScheduledJobStatus.Running, domainEvent.StartedOnUtc, scheduledJob.LastCompletedOnUtc); Result updateScheduledJobResult = await _unitOfWork.ScheduledJobRepository.UpdateAsync(updatedScheduledJob, cancellationToken).ConfigureAwait(false); if (updateScheduledJobResult.IsFailure) throw new EventualConsistencyException(updateScheduledJobResult.FirstError, updateScheduledJobResult.Errors); @@ -81,53 +82,25 @@ public class ScheduledJobExecutionStartedDomainEventHandler : IDomainEventHandle if (insertExecutionResult.IsFailure) throw new EventualConsistencyException(insertExecutionResult.FirstError, insertExecutionResult.Errors); - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + throw new EventualConsistencyException(saveChangesResult.FirstError, saveChangesResult.Errors); // Notify the SignalR clients about the current scheduled jobs and the started execution. await NotifyCurrentScheduledJobsAsync(cancellationToken).ConfigureAwait(false); await _scheduledJobNotifier.SendScheduledJobExecutionStartedAsync(execution.ToResponse(), cancellationToken).ConfigureAwait(false); } - /// - /// Creates a copy of with the provided status and timestamps. - /// - /// The scheduled job to copy. - /// The status of the copy. - /// The last start time of the copy. - /// The last completion time of the copy. - /// The copy of the scheduled job. - private static ScheduledJobEntity CreateUpdatedScheduledJob(ScheduledJobEntity scheduledJob, ScheduledJobStatus status, DateTime? lastStartedOnUtc, DateTime? lastCompletedOnUtc) - { - return new ScheduledJobEntity - { - Id = scheduledJob.Id, - Name = scheduledJob.Name, - TaskType = scheduledJob.TaskType, - ScheduleType = scheduledJob.ScheduleType, - IntervalMinutes = scheduledJob.IntervalMinutes, - Hour = scheduledJob.Hour, - Minute = scheduledJob.Minute, - Status = status, - OwnerUserId = scheduledJob.OwnerUserId, - LastStartedOnUtc = lastStartedOnUtc, - LastCompletedOnUtc = lastCompletedOnUtc, - CreatedOnUtc = scheduledJob.CreatedOnUtc, - CreatedBy = scheduledJob.CreatedBy, - UpdatedOnUtc = scheduledJob.UpdatedOnUtc, - UpdatedBy = scheduledJob.UpdatedBy - }; - } - /// /// Notifies the SignalR clients about the current list of scheduled jobs. /// /// Cancellation token that can be used to stop the execution. private async Task NotifyCurrentScheduledJobsAsync(CancellationToken cancellationToken) { - Result> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + Result> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false); if (getScheduledJobsResult.IsFailure) throw new EventualConsistencyException(getScheduledJobsResult.FirstError, getScheduledJobsResult.Errors); - IReadOnlyList scheduledJobResponses = [.. getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse())]; + IReadOnlyList scheduledJobResponses = [.. getScheduledJobsResult.Value.Data.Select(scheduledJob => scheduledJob.ToResponse())]; await _scheduledJobNotifier.SendScheduledJobsAsync(scheduledJobResponses, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionStoppedDomainEventHandler.cs b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionStoppedDomainEventHandler.cs index cc735453..3e98c4a5 100644 --- a/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionStoppedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionStoppedDomainEventHandler.cs @@ -1,6 +1,8 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Scheduling; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Mapping.Scheduling; using Lumina.Application.Core.Scheduling.Notifications; using Lumina.Contracts.Responses.Scheduling; @@ -50,31 +52,20 @@ public class ScheduledJobExecutionStoppedDomainEventHandler : IDomainEventHandle if (getOpenExecutionResult.Value is not null) { ScheduledJobExecutionEntity execution = getOpenExecutionResult.Value; - ScheduledJobExecutionEntity updatedExecution = new() - { - Id = execution.Id, - ScheduledJobId = execution.ScheduledJobId, - TaskType = execution.TaskType, - IsCycleRun = execution.IsCycleRun, - WasCycleActive = execution.WasCycleActive, - StartedOnUtc = execution.StartedOnUtc, - CompletedOnUtc = domainEvent.OccurredOnUtc, - CreatedOnUtc = execution.CreatedOnUtc, - CreatedBy = execution.CreatedBy, - UpdatedOnUtc = execution.UpdatedOnUtc, - UpdatedBy = execution.UpdatedBy - }; + ScheduledJobExecutionEntity updatedExecution = execution.ToUpdatedRepositoryEntity(domainEvent.OccurredOnUtc); Result updateExecutionResult = await _unitOfWork.ScheduledJobExecutionRepository.UpdateAsync(updatedExecution, cancellationToken).ConfigureAwait(false); if (updateExecutionResult.IsFailure) throw new EventualConsistencyException(updateExecutionResult.FirstError, updateExecutionResult.Errors); - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + throw new EventualConsistencyException(saveChangesResult.FirstError, saveChangesResult.Errors); } // Notify the SignalR clients about the current list of scheduled jobs. - Result> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + Result> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false); if (getScheduledJobsResult.IsFailure) throw new EventualConsistencyException(getScheduledJobsResult.FirstError, getScheduledJobsResult.Errors); - IReadOnlyList scheduledJobResponses = [.. getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse())]; + IReadOnlyList scheduledJobResponses = [.. getScheduledJobsResult.Value.Data.Select(scheduledJob => scheduledJob.ToResponse())]; await _scheduledJobNotifier.SendScheduledJobsAsync(scheduledJobResponses, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Lumina.Application/Core/Themes/Management/Commands/DeleteTheme/DeleteThemeCommandHandler.cs b/src/Lumina.Application/Core/Themes/Management/Commands/DeleteTheme/DeleteThemeCommandHandler.cs index ec859146..99517c85 100644 --- a/src/Lumina.Application/Core/Themes/Management/Commands/DeleteTheme/DeleteThemeCommandHandler.cs +++ b/src/Lumina.Application/Core/Themes/Management/Commands/DeleteTheme/DeleteThemeCommandHandler.cs @@ -2,6 +2,8 @@ using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Themes; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Themes; @@ -71,7 +73,7 @@ public class DeleteThemeCommandHandler : ICommandHandler> getAllResult = await _unitOfWork.ThemeRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + Result> getAllResult = await _unitOfWork.ThemeRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false); if (getAllResult.IsFailure) return getAllResult.Errors; - List availableThemes = getAllResult.Value.Where(availableTheme => !availableTheme.IsDeleted).ToList(); + List availableThemes = getAllResult.Value.Data.Where(availableTheme => !availableTheme.IsDeleted).ToList(); - // at least one bundled theme must always remain available, so the application never ends up without any theme + // At least one bundled theme must always remain available, so the application never ends up without any theme. if (theme.InstallSource == ThemeInstallSource.Bundled) { int availableBundledThemes = availableThemes.Count(availableTheme => availableTheme.InstallSource == ThemeInstallSource.Bundled); @@ -97,7 +99,7 @@ public class DeleteThemeCommandHandler : ICommandHandler deleteResult = await _unitOfWork.ThemeRepository.DeleteByIdAsync(theme.Id, cancellationToken).ConfigureAwait(false); if (deleteResult.IsFailure) return deleteResult.Errors; } - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; Result deleteFilesResult = await _themeService.DeleteAsync(theme.ThemeId, cancellationToken).ConfigureAwait(false); if (deleteFilesResult.IsFailure) diff --git a/src/Lumina.Application/Core/Themes/Management/Commands/InstallTheme/InstallThemeCommandHandler.cs b/src/Lumina.Application/Core/Themes/Management/Commands/InstallTheme/InstallThemeCommandHandler.cs index e914fa89..1f9e1268 100644 --- a/src/Lumina.Application/Core/Themes/Management/Commands/InstallTheme/InstallThemeCommandHandler.cs +++ b/src/Lumina.Application/Core/Themes/Management/Commands/InstallTheme/InstallThemeCommandHandler.cs @@ -74,11 +74,11 @@ public class InstallThemeCommandHandler : ICommandHandler installResult = await _themeService.InstallAsync(command.Archive!, cancellationToken).ConfigureAwait(false); if (installResult.IsFailure) return installResult.Errors; @@ -103,7 +103,7 @@ public class InstallThemeCommandHandler : ICommandHandler insertResult = await _unitOfWork.ThemeRepository.InsertAsync(themeEntity, cancellationToken).ConfigureAwait(false); if (insertResult.IsFailure) { - // roll back the stored files so a failed install leaves no orphaned theme pack behind + // Roll back the stored files so a failed install leaves no orphaned theme pack behind. await _themeService.DeleteAsync(manifest.Id, cancellationToken).ConfigureAwait(false); return insertResult.Errors; } } - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; return themeEntity.ToResponse(); } } diff --git a/src/Lumina.Application/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandHandler.cs b/src/Lumina.Application/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandHandler.cs index c092f1ac..ec4b1a68 100644 --- a/src/Lumina.Application/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandHandler.cs +++ b/src/Lumina.Application/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandHandler.cs @@ -70,7 +70,7 @@ public class RestoreThemeCommandHandler : ICommandHandler restoreFilesResult = await _themeService.RestoreBundledThemeAsync(theme.ThemeId, cancellationToken).ConfigureAwait(false); if (restoreFilesResult.IsFailure) return restoreFilesResult.Errors; @@ -99,7 +99,9 @@ public class RestoreThemeCommandHandler : ICommandHandler saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; return Result.Success; } diff --git a/src/Lumina.Application/Core/Themes/Management/Commands/SetCurrentTheme/SetCurrentThemeCommandHandler.cs b/src/Lumina.Application/Core/Themes/Management/Commands/SetCurrentTheme/SetCurrentThemeCommandHandler.cs index 3269b174..0fa7bb67 100644 --- a/src/Lumina.Application/Core/Themes/Management/Commands/SetCurrentTheme/SetCurrentThemeCommandHandler.cs +++ b/src/Lumina.Application/Core/Themes/Management/Commands/SetCurrentTheme/SetCurrentThemeCommandHandler.cs @@ -66,7 +66,7 @@ public class SetCurrentThemeCommandHandler : ICommandHandler getCurrentResult = await _unitOfWork.ThemeRepository.GetCurrentAsync(cancellationToken).ConfigureAwait(false); if (getCurrentResult.IsFailure) return getCurrentResult.Errors; @@ -92,12 +94,16 @@ public class SetCurrentThemeCommandHandler : ICommandHandler saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + return theme.ToResponse(); } } diff --git a/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeTemplate/GetThemeTemplateQueryHandler.cs b/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeTemplate/GetThemeTemplateQueryHandler.cs index 419d1d9a..57402dfb 100644 --- a/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeTemplate/GetThemeTemplateQueryHandler.cs +++ b/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeTemplate/GetThemeTemplateQueryHandler.cs @@ -58,6 +58,7 @@ public class GetThemeTemplateQueryHandler : IQueryHandler 0) return validationResult; + // Load the requested theme, so that a missing or soft deleted theme is reported before its template is read. Result getThemeResult = await _unitOfWork.ThemeRepository.GetByThemeIdAsync(query.ThemeId!, cancellationToken).ConfigureAwait(false); if (getThemeResult.IsFailure) return getThemeResult.Errors; @@ -69,10 +70,10 @@ public class GetThemeTemplateQueryHandler : IQueryHandler templateResult = await _themeService.GetTemplateAsync(theme.ThemeId, query.PageKey!, cancellationToken).ConfigureAwait(false); if (templateResult.IsFailure) { - // the stored files of a bundled theme removed externally are restored, and if the broken theme was the + // The stored files of a bundled theme removed externally are restored, and if the broken theme was the // active one, the configured default theme is activated, so clients always have a renderable theme; a // theme that simply does not provide a template for the page is not broken, so it is not restored and the - // caller falls back to the application's default unstyled Razor view instead + // caller falls back to the application's default unstyled Razor view instead. if (templateResult.FirstError != DomainErrors.Themes.ThemeTemplateNotFound && theme.InstallSource == ThemeInstallSource.Bundled && await TryRestoreBundledThemeAsync(theme, cancellationToken).ConfigureAwait(false)) @@ -99,6 +100,7 @@ public class GetThemeTemplateQueryHandler : IQueryHandler getDefaultResult = await _unitOfWork.ThemeRepository.GetByThemeIdAsync(_themeService.DefaultThemeId, cancellationToken).ConfigureAwait(false); @@ -114,7 +116,10 @@ public class GetThemeTemplateQueryHandler : IQueryHandler saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return false; } } @@ -126,8 +131,8 @@ public class GetThemeTemplateQueryHandler : IQueryHandler 0) return validationResult; + // Load the account by its username, so the current password can be verified before it is replaced. Result getUserResult = await _unitOfWork.UserRepository.GetByUsernameAsync(command.Username!, cancellationToken).ConfigureAwait(false); if (getUserResult.IsFailure) return getUserResult.Errors; else if (getUserResult.Value is null) return Errors.Authentication.UsernameDoesNotExist; - // validate if the current password is correct + + // Validate that the provided current password matches the stored hash, so a request with only a valid username cannot overwrite the password. if (!_hashService.CheckStringAgainstHash(command.CurrentPassword!, Uri.UnescapeDataString(getUserResult.Value.Password!))) return Errors.Authentication.InvalidCurrentPassword; + + // The stored hash is URI escaped, so the new hash is escaped the same way before it is stored. getUserResult.Value.Password = Uri.EscapeDataString(_hashService.HashString(command.NewPassword!)); - // if the password change was initiated via a password reset, remote the temporary password that was generated in the process + + // If the password change was initiated via a password reset, remove the temporary password that was generated in the process. getUserResult.Value.TempPassword = null; getUserResult.Value.TempPasswordCreated = null; - // update the user + + // Update the user and persist the change. Result updateUserResult = await _unitOfWork.UserRepository.UpdateAsync(getUserResult.Value, cancellationToken).ConfigureAwait(false); if (updateUserResult.IsFailure) return updateUserResult.Errors; - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; return new ChangePasswordResponse(true); } } diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandler.cs index e97e1704..28c7d4ca 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandler.cs @@ -64,31 +64,37 @@ public class RecoverPasswordCommandHandler : ICommandHandler 0) return validationResult; - // check if any users already exists + // Load the account by its username, so its existing recovery state and TOTP configuration can be checked. Result getUserResult = await _unitOfWork.UserRepository.GetByUsernameAsync(command.Username!, cancellationToken).ConfigureAwait(false); if (getUserResult.IsFailure) return getUserResult.Errors; else if (getUserResult.Value is null) return Errors.Authentication.UsernameDoesNotExist; - else if (getUserResult.Value.TempPassword is not null) // if a temp password is present, a password request was already requested + else if (getUserResult.Value.TempPassword is not null) // If a temporary password is present, a password reset was already requested. return Errors.Authentication.PasswordResetAlreadyRequested; - // check if the user uses TOTP - bool usesTotp = !string.IsNullOrEmpty(getUserResult.Value.TotpSecret); - if (!usesTotp) + + // Check if the user uses TOTP. + bool doesUseTotp = !string.IsNullOrEmpty(getUserResult.Value.TotpSecret); + if (!doesUseTotp) return Errors.Authentication.InvalidTotpCode; - if (usesTotp && string.IsNullOrEmpty(command.TotpCode)) + if (doesUseTotp && string.IsNullOrEmpty(command.TotpCode)) return Errors.Authentication.InvalidTotpCode; - else if (usesTotp && !string.IsNullOrEmpty(command.TotpCode)) // and if they do, validate it + else if (doesUseTotp && !string.IsNullOrEmpty(command.TotpCode)) // When the user uses TOTP, validate the provided code before allowing the reset. if (!_totpTokenGenerator.ValidateToken(Convert.FromBase64String(_cryptographyService.Decrypt(getUserResult.Value.TotpSecret!)), command.TotpCode)) return Errors.Authentication.InvalidTotpCode; - // hash the new password and assign it to a temporary password that will be valid 15 minutes - getUserResult.Value.TempPassword = Uri.EscapeDataString(_hashService.HashString("Abcd123$")); // TODO: replace with random password generator + + // Generate the hash of a temporary password and record when it was created, so that the reset flow can expire it after 15 minutes. + getUserResult.Value.TempPassword = Uri.EscapeDataString(_hashService.HashString("Abcd123$")); // TODO: Replace the hardcoded password with a randomly generated one. getUserResult.Value.TempPasswordCreated = DateTime.UtcNow; - // update the user + + // Update the user and persist the temporary password. Result updateUserResult = await _unitOfWork.UserRepository.UpdateAsync(getUserResult.Value, cancellationToken).ConfigureAwait(false); if (updateUserResult.IsFailure) return updateUserResult.Errors; - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; return new RecoverPasswordResponse(true); } } diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandler.cs index 7777826d..6f5b83b6 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandler.cs @@ -73,12 +73,14 @@ public class RegisterUserCommandHandler : ICommandHandler 0) return validationResult; - // check if any users already exists (admin account is only set once!) + // Check if a user with this username already exists, since the admin account can only be created once. Result getUserResult = await _unitOfWork.UserRepository.GetByUsernameAsync(command.Username!, cancellationToken).ConfigureAwait(false); if (getUserResult.IsFailure) return getUserResult.Errors; else if (getUserResult.Value is not null) return Errors.Authentication.UsernameAlreadyExists; + + // Build the account, hashing the password and URI escaping it the same way as the stored form. string? totpSecret = null; Guid id = Guid.NewGuid(); UserEntity user = new() @@ -93,23 +95,29 @@ public class RegisterUserCommandHandler : ICommandHandler insertUserResult = await _unitOfWork.UserRepository.InsertAsync(user, cancellationToken).ConfigureAwait(false); if (insertUserResult.IsFailure) return insertUserResult.Errors; - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); - // TODO: insert the default admin profile preferences when they are implemented - // if 2FA was enabled, the TOTP secret needs to be delivered to the client unhashed, so it can be displayed + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + + // TODO: Insert the default admin profile preferences when they are implemented. + // If 2FA was enabled, the TOTP secret needs to be delivered to the client unencrypted, so it can be displayed. return new RegistrationResponse(user.Id, user.Username, totpSecret); } } diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandler.cs index 919a348d..1b0910ee 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandler.cs @@ -73,28 +73,31 @@ public class LoginUserQueryHandler : IQueryHandler 0) return validationResult; - // check if any users already exists + // Load the account by its username, so the password and two factor state can be verified. Result getUserResult = await _unitOfWork.UserRepository.GetByUsernameAsync(query.Username!, cancellationToken).ConfigureAwait(false); if (getUserResult.IsFailure) return getUserResult.Errors; else if (getUserResult.Value is null) return Errors.Authentication.InvalidUsernameOrPassword; - // validate that the password is correct + + // Validate that the password matches the stored hash. if (!_hashService.CheckStringAgainstHash(query.Password!, Uri.UnescapeDataString(getUserResult.Value.Password!))) { - // if a password reset was requested, a temp password is being used - if the hash check failed against the regular password, try against the temp one too + // If a password reset was requested, a temporary password is in use; when the check against the regular password failed, try the temporary one too. if (getUserResult.Value.TempPassword is not null) { - // the temporary password should only be valid for 15 minutes, if its obsolete, remove it and return error + // The temporary password is only valid for 15 minutes; when it is obsolete, remove it and return an error. if (getUserResult.Value.TempPasswordCreated!.Value.AddMinutes(15) < _dateTimeProvider.UtcNow) { getUserResult.Value.TempPassword = null; getUserResult.Value.TempPasswordCreated = null; await _unitOfWork.UserRepository.UpdateAsync(getUserResult.Value, cancellationToken); - await _unitOfWork.SaveChangesAsync(cancellationToken); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; return Errors.Authentication.TempPasswordExpired; } - else // temporary password is still valid, validate password against it + else // The temporary password is still valid, so validate the password against it. { if (!_hashService.CheckStringAgainstHash(query.Password!, Uri.UnescapeDataString(getUserResult.Value.TempPassword!))) return Errors.Authentication.InvalidUsernameOrPassword; @@ -103,15 +106,17 @@ public class LoginUserQueryHandler : IQueryHandler 0) return validationResult; - // an authenticated request must always carry a user identity + // An authenticated request must always carry a user identity. Guid? currentUserId = _currentUserService.UserId; if (currentUserId is null) return ApplicationErrors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // only admins can update user authorizations + // Only admins can update user authorizations. bool isAdmin = await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false); if (!isAdmin) return ApplicationErrors.Authorization.NotAuthorized; - // get the user to update - Result getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(command.UserId, cancellationToken).ConfigureAwait(false); + // Get the user to update. + Result getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(command.UserId, cancellationToken: cancellationToken).ConfigureAwait(false); if (getUserResult.IsFailure || getUserResult.Value is null) return DomainErrors.Users.UserDoesNotExist; Result getRoleResult = default; if (command.RoleId is not null) { - // get the new role - getRoleResult = await _unitOfWork.RoleRepository.GetByIdAsync(command.RoleId!.Value, cancellationToken).ConfigureAwait(false); + // Get the new role. + getRoleResult = await _unitOfWork.RoleRepository.GetByIdAsync(command.RoleId!.Value, cancellationToken: cancellationToken).ConfigureAwait(false); if (getRoleResult.IsFailure || getRoleResult.Value is null) return ApplicationErrors.Authorization.RoleNotFound; - // check if we're changing an admin's role and if this would leave us without admins + // Check if changing the role of an admin would leave the application without any admin. if (getUserResult.Value.UserRole?.Role.RoleName == "Admin" && getRoleResult.Value.RoleName != "Admin") { - // count how many admins we have - Result> getAllUsersResult = await _unitOfWork.UserRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + // Count how many admins exist, so the last one is never demoted. + Result> getAllUsersResult = await _unitOfWork.UserRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false); if (getAllUsersResult.IsFailure) return getAllUsersResult.Errors; - int adminCount = getAllUsersResult.Value.Count(user => user.UserRole?.Role.RoleName == "Admin"); + int adminCount = getAllUsersResult.Value.Data.Count(user => user.UserRole?.Role.RoleName == "Admin"); if (adminCount <= 1) return ApplicationErrors.Authorization.CannotRemoveLastAdmin; } } - // get the permissions to assign + + // Get the permissions to assign. Result> getPermissionsResult = await _unitOfWork.PermissionRepository.GetByIdsAsync(command.Permissions, cancellationToken).ConfigureAwait(false); if (getPermissionsResult.IsFailure) return getPermissionsResult.Errors; - // update the user + // Update the user. UserEntity userToUpdate = getUserResult.Value; + // Build the role link for the requested role, leaving the current role untouched when no role was provided. UserRoleEntity? userRole = default!; if (command.RoleId is not null) { @@ -118,6 +122,7 @@ public class UpdateUserRoleAndPermissionsCommandHandler : ICommandHandler updateResult = await _unitOfWork.UserRepository.UpdateAsync(updatedUser, cancellationToken).ConfigureAwait(false); if (updateResult.IsFailure) return updateResult.Errors; - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; return new AuthorizationResponse( userToUpdate.Id, diff --git a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandler.cs b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandler.cs index 8b7bf775..af92e828 100644 --- a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandler.cs @@ -106,7 +106,10 @@ public class UpdateUserSettingsCommandHandler : ICommandHandler saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + return Result.Updated; } } diff --git a/src/Lumina.DataAccess/Core/Seed/DataSeedService.cs b/src/Lumina.DataAccess/Core/Seed/DataSeedService.cs index f37fceba..c49fa627 100644 --- a/src/Lumina.DataAccess/Core/Seed/DataSeedService.cs +++ b/src/Lumina.DataAccess/Core/Seed/DataSeedService.cs @@ -4,6 +4,8 @@ using Lumina.Application.Common.DataAccess.Entities.Scheduling; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Seed; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Time; using Lumina.Domain.Common.Primitives; @@ -58,7 +60,9 @@ public class DataSeedService : IDataSeedService if (insertPermissionResult.IsFailure) return insertPermissionResult.Errors; } - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; return Result.Created; } @@ -81,7 +85,9 @@ public class DataSeedService : IDataSeedService if (insertRoleResult.IsFailure) return insertRoleResult.Errors; } - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; return Result.Created; } @@ -102,12 +108,12 @@ public class DataSeedService : IDataSeedService return Errors.Authorization.AdminAccountNotFound; // Get all permissions. - Result> getPermissionsResult = await _unitOfWork.PermissionRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + Result> getPermissionsResult = await _unitOfWork.PermissionRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false); if (getPermissionsResult.IsFailure) return getPermissionsResult.Errors; // Add each permission to the admin role. - foreach (PermissionEntity permission in getPermissionsResult.Value) + foreach (PermissionEntity permission in getPermissionsResult.Value.Data) { RolePermissionEntity rolePermissionEntity = new() { @@ -122,7 +128,9 @@ public class DataSeedService : IDataSeedService if (insertRolePermissionResult.IsFailure) return insertRolePermissionResult.Errors; } - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; return Result.Created; } @@ -143,7 +151,7 @@ public class DataSeedService : IDataSeedService return Errors.Authorization.AdminRoleNotFound; // Get admin user. - Result getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false); + Result getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(userId, cancellationToken: cancellationToken).ConfigureAwait(false); if (getUserResult.IsFailure) return getUserResult.Errors; @@ -164,7 +172,9 @@ public class DataSeedService : IDataSeedService if (insertUserRoleResult.IsFailure) return insertUserRoleResult.Errors; - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; return Result.Created; } @@ -196,7 +206,9 @@ public class DataSeedService : IDataSeedService if (insertScheduledJobResult.IsFailure) return insertScheduledJobResult.Errors; } - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; return Result.Created; } diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJob.cs index af0d994a..31d7f468 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJob.cs @@ -33,7 +33,7 @@ namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Commo /// internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob, IMediaLibraryScanArtworkEnrichmentJob { - private const int ENRICHMENT_PAGE_SIZE = 1000; // the number of books that are enriched in a single batch, keeping the peak memory bounded regardless of the library size + private const int ENRICHMENT_PAGE_SIZE = 1000; // The number of books that are enriched in a single batch, keeping the peak memory bounded regardless of the library size. private readonly IServiceScopeFactory _serviceScopeFactory; private readonly ILogger _logger; @@ -62,30 +62,30 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob { try { - // increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel) + // Increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel). int parentsCompleted = Interlocked.Increment(ref parentsPayloadsExecuted); - // only execute this job's payload when it has no parents, or when all the parents finished their execution + // Only execute this job's payload when it has no parents, or when all the parents finished their execution. if (Parents.Count == 0 || parentsCompleted == Parents.Count) { - // this needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous - // processing that takes time, and would block the processing of scan jobs in the in-memory queue + // This needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous + // processing that takes time, and would block the processing of scan jobs in the in-memory queue. await Task.Run(async () => { Status = LibraryScanJobStatus.Running; - // see docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details: + // See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details. await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!; MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); - // load the media library, whose name is used to build the directory of the book artwork, and whose setting determines - // whether the providers that require access to the web are used during the enrichment + // Load the media library, whose name is used to build the directory of the book artwork, and whose setting determines + // whether the providers that require access to the web are used during the enrichment. string libraryName = string.Empty; bool canDownloadMetadataFromWeb = false; if (unitOfWork.LibraryRepository is not null) { - Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); + Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); if (getLibraryResult.IsFailure || getLibraryResult.Value is null) _logger.LogWarning("Failed to read the media library, the book artwork will not be stored and the providers requiring the web will not be used."); else @@ -95,8 +95,8 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob } } - // get the artwork providers configured for the media library, in their configured order, that support the media library type. - // the artwork resolution is best-effort, so a failure to read the artwork configurations must not prevent the enrichment from proceeding + // Get the artwork providers configured for the media library, in their configured order, that support the media library type. + // The artwork resolution is best-effort, so a failure to read the artwork configurations must not prevent the enrichment from proceeding. List artworkProviders = []; if (unitOfWork.ArtworkProviderConfigurationRepository is not null) { @@ -118,7 +118,7 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob } } - // when no artwork provider is available, the books must not be marked as failed to resolve, so the enrichment is skipped entirely + // When no artwork provider is available, the books must not be marked as failed to resolve, so the enrichment is skipped entirely. if (artworkProviders.Count > 0) { IBookArtworkService? bookArtworkService = asyncServiceScope.ServiceProvider.GetService(); @@ -129,7 +129,7 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob throw new InvalidOperationException(getBooksToEnrichCountResult.FirstError.Description); int totalBooksToEnrich = getBooksToEnrichCountResult.Value; - // set the initial progress of the scan job + // Set the initial progress of the scan job. Result publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, totalBooksToEnrich, cancellationToken).ConfigureAwait(false); if (publishJobProgressResult.IsFailure) throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); @@ -138,7 +138,7 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob int minUpdateIntervalMs = 100; int processedBooksCount = 0; - // process the books that need their artwork resolved in pages, keeping the peak memory bounded regardless of the library size + // Process the books that need their artwork resolved in pages, keeping the peak memory bounded regardless of the library size. string? lastPath = null; while (true) { @@ -151,7 +151,7 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob if (booksPage.Count == 0) break; - // load the display names of the authors of the books of this page, in one query, since they are used to build the artwork directory + // Load the display names of the authors of the books of this page, in one query, since they are used to build the artwork directory. Result> getAuthorsResult = await unitOfWork.BookRepository.GetAuthorsDisplayNamesByBookIdsAsync([.. booksPage.Select(bookEntity => bookEntity.Id)], cancellationToken).ConfigureAwait(false); if (getAuthorsResult.IsFailure) throw new InvalidOperationException(getAuthorsResult.FirstError.Description); @@ -162,11 +162,11 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob await EnrichBookArtworkAsync(bookEntity, artworkProviders, bookArtworkService, fileHashService, libraryName, getAuthorsResult.Value, cancellationToken).ConfigureAwait(false); - // check if enough time has passed since last update + // Check if enough time has passed since the last update. DateTime now = DateTime.UtcNow; if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs) { - // increment the number of processed elements progress + // Increment the number of processed elements progress. publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, Interlocked.Increment(ref processedBooksCount), totalBooksToEnrich, cancellationToken).ConfigureAwait(false); if (publishJobProgressResult.IsFailure) throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); @@ -174,24 +174,24 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob } } - // persist the enriched books of this page, then detach them from the change tracker, keeping the peak memory bounded regardless of the library size - await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + // Persist the enriched books of this page, then detach them from the change tracker, keeping the peak memory bounded regardless of the library size. + Result saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + throw new InvalidOperationException(saveChangesResult.FirstError.Description); unitOfWork.ClearTrackedEntities(); lastPath = booksPage[^1].Path; } } else - { _logger.LogWarning("No artwork provider is configured for the media library with Id '{LibraryId}', the artwork enrichment will be skipped.", LibraryId.Value); - } - + Status = LibraryScanJobStatus.Completed; - // when this job has no linked children, it's the last job in the directed acyclic job graph, and the scan is completed + // When this job has no linked children, it is the last job in the directed acyclic job graph, and the scan is completed. if (Children.Count == 0) await domainEventPublisher.PublishAsync(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - // call each linked child with the obtained payload + // Call each linked child with the obtained payload. foreach (IMediaLibraryScanJob child in Children) await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false); }, cancellationToken).ConfigureAwait(false); @@ -222,19 +222,17 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob /// Cancellation token that can be used to stop the execution. private async Task EnrichBookArtworkAsync(BookEntity bookEntity, IReadOnlyList artworkProviders, IBookArtworkService? bookArtworkService, IFileHashService fileHashService, string libraryName, IReadOnlyDictionary authorsDisplayNamesByBookId, CancellationToken cancellationToken) { - // when no artwork provider is available, the book must not be marked as failed to resolve, so the enrichment is skipped + // When no artwork provider is available, the book must not be marked as failed to resolve, so the enrichment is skipped. if (bookArtworkService is null || artworkProviders.Count == 0) return; ResolvedArtwork? resolvedArtwork = await ResolveArtworkAsync(bookEntity, artworkProviders, cancellationToken).ConfigureAwait(false); if (resolvedArtwork is null) { - // no artwork provider returned usable artwork, mark the cover artwork of the book as failed to resolve - BookArtworkEntity? coverArtwork = bookEntity.BookArtwork.FirstOrDefault(artwork => artwork.ArtworkType == ArtworkType.Cover && artwork.Ordinal == 0); + // No artwork provider returned usable artwork, so the cover artwork of the book is marked as failed to resolve. + BookArtworkEntity? coverArtwork = bookEntity.Artwork.FirstOrDefault(artwork => artwork.ArtworkType == ArtworkType.Cover && artwork.Ordinal == 0); if (coverArtwork is null) - { - bookEntity.BookArtwork.Add(CreateCoverArtworkEntity(bookEntity.Id, ArtworkStatus.Failed, null, 0, null, null)); - } + bookEntity.Artwork.Add(CreateCoverArtworkEntity(bookEntity.Id, ArtworkStatus.Failed, null, 0, null, null)); else { coverArtwork.Status = ArtworkStatus.Failed; @@ -244,9 +242,9 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob return; } - BookArtworkEntity? existingCoverArtwork = bookEntity.BookArtwork.FirstOrDefault(artwork => artwork.ArtworkType == ArtworkType.Cover && artwork.Ordinal == 0); + BookArtworkEntity? existingCoverArtwork = bookEntity.Artwork.FirstOrDefault(artwork => artwork.ArtworkType == ArtworkType.Cover && artwork.Ordinal == 0); - // when the artwork comes from a local file, its content hash can be computed before storing it, so that an artwork identical to the stored one + // When the artwork comes from a local file, its content hash can be computed before storing it, so that an artwork identical to the stored one // is not copied again. For remote artwork, the content hash of the stored artwork is computed after storing it. ulong contentHash = 0; bool shouldStoreArtwork = true; @@ -262,11 +260,9 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob Result saveArtworkResult = await bookArtworkService.SaveBookArtworkAsync(bookEntity.LibraryId, bookEntity.Id, libraryName, authorName, bookEntity.Title, resolvedArtwork.Artwork, cancellationToken).ConfigureAwait(false); if (saveArtworkResult.IsFailure) { - // a failing artwork storage must not prevent the book from being tracked as failed to resolve + // A failing artwork storage must not prevent the book from being tracked as failed to resolve. if (existingCoverArtwork is null) - { - bookEntity.BookArtwork.Add(CreateCoverArtworkEntity(bookEntity.Id, ArtworkStatus.Failed, null, 0, null, null)); - } + bookEntity.Artwork.Add(CreateCoverArtworkEntity(bookEntity.Id, ArtworkStatus.Failed, null, 0, null, null)); else { existingCoverArtwork.Status = ArtworkStatus.Failed; @@ -276,7 +272,7 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob return; } - // for remote artwork, compute the content hash of the stored artwork, which is a copy of the resolved one + // For remote artwork, compute the content hash of the stored artwork, which is a copy of the resolved one. if (contentHash == 0) { string storedArtworkPath = Path.Combine(AppContext.BaseDirectory, saveArtworkResult.Value.TrimStart('/', '\\')); @@ -284,9 +280,7 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob } if (existingCoverArtwork is null) - { - bookEntity.BookArtwork.Add(CreateCoverArtworkEntity(bookEntity.Id, ArtworkStatus.Enriched, saveArtworkResult.Value, contentHash, resolvedArtwork.ProviderName, DateTime.UtcNow)); - } + bookEntity.Artwork.Add(CreateCoverArtworkEntity(bookEntity.Id, ArtworkStatus.Enriched, saveArtworkResult.Value, contentHash, resolvedArtwork.ProviderName, DateTime.UtcNow)); else { existingCoverArtwork.FileName = saveArtworkResult.Value; @@ -300,7 +294,7 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob } else { - // the resolved artwork is identical to the stored one, so the stored artwork is kept and the book is marked as enriched + // The resolved artwork is identical to the stored one, so the stored artwork is kept and the book is marked as enriched. existingCoverArtwork!.Status = ArtworkStatus.Enriched; existingCoverArtwork.Provider = resolvedArtwork.ProviderName; existingCoverArtwork.LastUpdateUtc = DateTime.UtcNow; @@ -338,13 +332,13 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob } catch (Exception) { - // a failing artwork provider must not prevent the other providers from being tried + // A failing artwork provider must not prevent the other providers from being tried. } if (artwork is null) continue; - // a provider that returns remote artwork must declare that it requires web access, otherwise downloading it would contradict the provider's contract + // A provider that returns remote artwork must declare that it requires web access, otherwise downloading it would contradict the provider's contract. if (!string.IsNullOrWhiteSpace(artwork.RemoteUrl) && !provider.RequiresWebAccess) continue; diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJob.cs index a861002a..7db6d886 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJob.cs @@ -4,7 +4,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; -using Lumina.Application.Common.DataAccess.Repositories.Books; +using Lumina.Application.Common.DataAccess.Repositories.BookLibrary; using Lumina.Application.Common.DataAccess.Repositories.MediaContributors; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; @@ -17,9 +17,12 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Metadata; using Lumina.Plugins.Contracts.Core.Metadata; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; @@ -38,7 +41,7 @@ namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Commo /// internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJob, IMediaLibraryScanMetadataEnrichmentJob { - private const int ENRICHMENT_PAGE_SIZE = 1000; // the number of books that are enriched in a single batch, keeping the peak memory bounded regardless of the library size + private const int ENRICHMENT_PAGE_SIZE = 1000; // The number of books that are enriched in a single batch, keeping the peak memory bounded regardless of the library size. private readonly IServiceScopeFactory _serviceScopeFactory; private readonly ILogger _logger; @@ -67,36 +70,36 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo { try { - // increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel) + // Increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel). int parentsCompleted = Interlocked.Increment(ref parentsPayloadsExecuted); - // only execute this job's payload when it has no parents, or when all the parents finished their execution + // Only execute this job's payload when it has no parents, or when all the parents finished their execution. if (Parents.Count == 0 || parentsCompleted == Parents.Count) { - // this needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous - // processing that takes time, and would block the processing of scan jobs in the in-memory queue + // This needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous + // processing that takes time, and would block the processing of scan jobs in the in-memory queue. await Task.Run(async () => { Status = LibraryScanJobStatus.Running; - // see docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details: + // See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details. await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!; MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); - // load the media library, whose setting determines whether the providers that require access to the web are used during the enrichment + // Load the media library, whose setting determines whether the providers that require access to the web are used during the enrichment. bool canDownloadMetadataFromWeb = false; if (unitOfWork.LibraryRepository is not null) { - Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); + Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); if (getLibraryResult.IsFailure || getLibraryResult.Value is null) _logger.LogWarning("Failed to read the media library, the providers requiring the web will not be used."); else canDownloadMetadataFromWeb = getLibraryResult.Value.CanDownloadMetadataFromWeb; } - // get the metadata providers configured for the media library, in their configured order, that support the media library type, - // skipping the providers that require access to the web when the media library does not permit downloading data from the web + // Get the metadata providers configured for the media library, in their configured order, that support the media library type, + // skipping the providers that require access to the web when the media library does not permit downloading data from the web. Result> getConfigurationsResult = await unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); if (getConfigurationsResult.IsFailure) throw new InvalidOperationException(getConfigurationsResult.FirstError.Description); @@ -112,7 +115,7 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo providers.AddRange(configuredProviders); } - // read whether the metadata of the books of the user is aggregated from multiple providers, when fields are missing + // Read whether the metadata of the books of the user is aggregated from multiple providers, when fields are missing. bool shouldAggregateMetadataWhenMissing = false; if (unitOfWork.UserSettingsRepository is not null) { @@ -123,7 +126,7 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo shouldAggregateMetadataWhenMissing = getUserSettingsResult.Value?.ShouldAggregateMetadataWhenMissing ?? false; } - // when no metadata provider is available, the books must not be marked as failed to enrich, so the enrichment is skipped entirely + // When no metadata provider is available, the books must not be marked as failed to enrich, so the enrichment is skipped entirely. if (providers.Count > 0) { Result getBooksToEnrichCountResult = await unitOfWork.BookRepository.GetBooksNeedingMetadataCountAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); @@ -131,7 +134,7 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo throw new InvalidOperationException(getBooksToEnrichCountResult.FirstError.Description); int totalBooksToEnrich = getBooksToEnrichCountResult.Value; - // set the initial progress of the scan job + // Set the initial progress of the scan job. Result publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, totalBooksToEnrich, cancellationToken).ConfigureAwait(false); if (publishJobProgressResult.IsFailure) throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); @@ -140,11 +143,11 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo int minUpdateIntervalMs = 100; int processedBooksCount = 0; - // the contributors discovered while enriching a page are cached by normalized display name, so that a contributor is only - // created once even when the same person is discovered for many books of the same page + // The contributors discovered while enriching a page are cached by normalized display name, so that a contributor is only + // created once even when the same person is discovered for many books of the same page. Dictionary contributorsByNormalizedName = []; - // process the books that need their metadata enriched in pages, keeping the peak memory bounded regardless of the library size + // Process the books that need their metadata enriched in pages, keeping the peak memory bounded regardless of the library size. string? lastPath = null; while (true) { @@ -163,11 +166,11 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo await EnrichBookAsync(bookEntity, providers, shouldAggregateMetadataWhenMissing, unitOfWork.BookRepository, unitOfWork.MediaContributorRepository, contributorsByNormalizedName, cancellationToken).ConfigureAwait(false); - // check if enough time has passed since last update + // Check if enough time has passed since the last update. DateTime now = DateTime.UtcNow; if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs) { - // increment the number of processed elements progress + // Increment the number of processed elements progress. publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, Interlocked.Increment(ref processedBooksCount), totalBooksToEnrich, cancellationToken).ConfigureAwait(false); if (publishJobProgressResult.IsFailure) throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); @@ -175,8 +178,10 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo } } - // persist the enriched books of this page, then detach them from the change tracker, keeping the peak memory bounded regardless of the library size - await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + // Persist the enriched books of this page, then detach them from the change tracker, keeping the peak memory bounded regardless of the library size. + Result saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + throw new InvalidOperationException(saveChangesResult.FirstError.Description); unitOfWork.ClearTrackedEntities(); contributorsByNormalizedName.Clear(); @@ -184,16 +189,14 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo } } else - { _logger.LogWarning("No metadata provider is configured for the media library with Id '{LibraryId}', the metadata enrichment will be skipped.", LibraryId.Value); - } - + Status = LibraryScanJobStatus.Completed; - // when this job has no linked children, it's the last job in the directed acyclic job graph, and the scan is completed + // When this job has no linked children, it is the last job in the directed acyclic job graph, and the scan is completed. if (Children.Count == 0) await domainEventPublisher.PublishAsync(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - // call each linked child with the obtained payload + // Call each linked child with the obtained payload. foreach (IMediaLibraryScanJob child in Children) await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false); }, cancellationToken).ConfigureAwait(false); @@ -224,7 +227,7 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo /// Cancellation token that can be used to stop the execution. private async Task EnrichBookAsync(BookEntity bookEntity, IReadOnlyList metadataProviders, bool shouldAggregateMetadataWhenMissing, IBookRepository bookRepository, IMediaContributorRepository mediaContributorRepository, Dictionary contributorsByNormalizedName, CancellationToken cancellationToken) { - // convert the book to a domain object + // Convert the book to a domain object. Result getBookResult = bookEntity.ToDomainEntity(); if (getBookResult.IsFailure) return; @@ -233,7 +236,7 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo BookMetadataLookupDto bookMetadataLookup = new( LibraryId: bookEntity.LibraryId, Path: bookEntity.Path, - Isbn: bookEntity.ISBNs.Count > 0 ? bookEntity.ISBNs.Where(isbn => isbn.Value is not null).Select(isbn => isbn.Value!).First() : null, // TODO: this should not take just the first ISBN, it should ask the metadata plugin to retry with the next ISBN, if the first one returned no results + Isbn: bookEntity.ISBNs.Count > 0 ? bookEntity.ISBNs.Where(isbn => isbn.Value is not null).Select(isbn => isbn.Value!).First() : null, // TODO: This should not take just the first ISBN, it should ask the metadata plugin to retry with the next ISBN, if the first one returned no results. OpenLibraryId: bookEntity.OpenLibraryId, Title: bookEntity.Title, Author: null, @@ -246,19 +249,20 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo if (resolvedMetadata is null) { - // no metadata provider returned usable metadata, mark the book as failed to enrich, keeping its previous metadata + // No metadata provider returned usable metadata, so the book is marked as failed to enrich, keeping its previous metadata. bookEntity.MetadataStatus = MetadataStatus.Failed; bookEntity.UpdatedOnUtc = DateTime.UtcNow; bookEntity.UpdatedBy = Guid.NewGuid(); return; } - // apply the enriched metadata to the book, and copy it onto the tracked entity, without touching the enrichment tracking columns + // Apply the enriched metadata to the book, and copy it onto the tracked entity, without touching the enrichment tracking columns. book.ApplyMetadata(resolvedMetadata.Metadata); bookEntity.ApplyMetadataToEntity(book); - // link the media contributors discovered while enriching to the book, finding or creating a single contributor per person + // Link the media contributors discovered while enriching to the book, finding or creating a single contributor per person. List linkedContributors = []; + List domainContributors = []; foreach (MediaContributorDto contributor in resolvedMetadata.Metadata.Contributors ?? []) { if (contributor.Name?.DisplayName is null) @@ -266,25 +270,26 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo MediaContributorEntity contributorEntity = await FindOrCreateContributorAsync(mediaContributorRepository, contributorsByNormalizedName, contributor, cancellationToken).ConfigureAwait(false); - string roleName = contributor.Role?.Name ?? "Contributor"; - MediaContributorRoleCategory roleCategory = contributor.Role?.Category ?? MediaContributorRoleCategory.Other; + MediaContributorRole role = contributor.Role ?? MediaContributorRole.Author; + if (linkedContributors.Any(linkedContributor => linkedContributor.MediaContributorId == contributorEntity.Id && linkedContributor.Role == role)) + continue; linkedContributors.Add(new BookContributorEntity { Id = Guid.NewGuid(), BookId = bookEntity.Id, MediaContributorId = contributorEntity.Id, - RoleName = roleName, - RoleCategory = roleCategory, + Role = role, CreatedOnUtc = DateTime.UtcNow, CreatedBy = Guid.Empty, UpdatedBy = null }); + domainContributors.Add(BookMediaContributor.Create(MediaContributorId.Create(contributorEntity.Id), role).Value); } - bookEntity.BookContributors.Clear(); - bookEntity.BookContributors.AddRange(linkedContributors); - book.UpdateContributors([.. linkedContributors.Select(linkedContributor => Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects.MediaContributorId.Create(linkedContributor.MediaContributorId))]); + bookEntity.Contributors.Clear(); + bookEntity.Contributors.AddRange(linkedContributors); + book.UpdateContributors(domainContributors); - // mark the book as enriched by the provider, directly on the tracked entity, since the enrichment state is a persistence concern + // Mark the book as enriched by the provider, directly on the tracked entity, since the enrichment state is a persistence concern. bookEntity.MetadataStatus = MetadataStatus.Enriched; bookEntity.MetadataProvider = resolvedMetadata.ProviderName; bookEntity.LastMetadataUpdateUtc = DateTime.UtcNow; @@ -340,7 +345,7 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo } catch (Exception) { - // a failing metadata provider must not prevent the other providers from being tried + // A failing metadata provider must not prevent the other providers from being tried. } } return null; @@ -369,12 +374,12 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo mergedMetadata = mergedMetadata is null ? bookMetadata : MetadataAggregator.Merge(mergedMetadata, bookMetadata); contributingProviders.Add(metadataProvider.Name); - // the identifiers and the title discovered by the earlier providers are fed to the later ones, so that they can look up the book precisely + // The identifiers and the title discovered by the earlier providers are fed to the later ones, so that they can look up the book precisely. bookMetadataLookup = EnrichLookup(bookMetadataLookup, mergedMetadata); } catch (Exception) { - // a failing metadata provider must not prevent the other providers from being tried + // A failing metadata provider must not prevent the other providers from being tried. } } diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanProviderConfigurationInvalidationJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanProviderConfigurationInvalidationJob.cs index 487e3e38..40b350c9 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanProviderConfigurationInvalidationJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanProviderConfigurationInvalidationJob.cs @@ -53,36 +53,36 @@ internal sealed class MediaLibraryScanProviderConfigurationInvalidationJob : Med { try { - // increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel) + // Increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel). int parentsCompleted = Interlocked.Increment(ref parentsPayloadsExecuted); - // only execute this job's payload when it has no parents, or when all the parents finished their execution + // Only execute this job's payload when it has no parents, or when all the parents finished their execution. if (Parents.Count == 0 || parentsCompleted == Parents.Count) { - // this needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous - // processing that takes time, and would block the processing of scan jobs in the in-memory queue + // This needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous + // processing that takes time, and would block the processing of scan jobs in the in-memory queue. await Task.Run(async () => { Status = LibraryScanJobStatus.Running; - // see docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details: + // See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details. await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!; MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); - // set the initial progress of the scan job, it's a 1 step job - invalidating the stale enrichment state + // Set the initial progress of the scan job; it is a single step job, invalidating the stale enrichment state. Result publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false); if (publishJobProgressResult.IsFailure) throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); - // load the media library, whose web access setting determines the effective provider set, and whose stored fingerprints - // are compared against the current provider configuration to detect whether it changed since the last scan - Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); + // Load the media library, whose web access setting determines the effective provider set, and whose stored fingerprints + // are compared against the current provider configuration to detect whether it changed since the last scan. + Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); if (getLibraryResult.IsFailure || getLibraryResult.Value is null) throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found."); LibraryEntity library = getLibraryResult.Value; - // load the provider configurations of the media library, whose fingerprint is compared against the stored one + // Load the provider configurations of the media library, whose fingerprint is compared against the stored one. Result> getMetadataConfigurationsResult = await unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); if (getMetadataConfigurationsResult.IsFailure) throw new InvalidOperationException(getMetadataConfigurationsResult.FirstError.Description); @@ -91,7 +91,7 @@ internal sealed class MediaLibraryScanProviderConfigurationInvalidationJob : Med if (getArtworkConfigurationsResult.IsFailure) throw new InvalidOperationException(getArtworkConfigurationsResult.FirstError.Description); - // read whether the metadata of the books of the user is aggregated from multiple providers, when fields are missing + // Read whether the metadata of the books of the user is aggregated from multiple providers, when fields are missing. bool shouldAggregateMetadataWhenMissing = false; if (unitOfWork.UserSettingsRepository is not null) { @@ -102,7 +102,7 @@ internal sealed class MediaLibraryScanProviderConfigurationInvalidationJob : Med shouldAggregateMetadataWhenMissing = getUserSettingsResult.Value?.ShouldAggregateMetadataWhenMissing ?? false; } - // compare the current fingerprints against the stored ones, resetting the enrichment state of the channel whose configuration + // Compare the current fingerprints against the stored ones, resetting the enrichment state of the channel whose configuration // changed, so that the enrichment jobs that follow re-enrich the books. A missing stored fingerprint means the configuration // was never recorded yet, so the current state of the books is trusted, and only the new fingerprint is stored. string metadataFingerprint = ProviderConfigurationFingerprint.ComputeMetadataFingerprint(getMetadataConfigurationsResult.Value, shouldAggregateMetadataWhenMissing, library.CanDownloadMetadataFromWeb); @@ -122,27 +122,29 @@ internal sealed class MediaLibraryScanProviderConfigurationInvalidationJob : Med throw new InvalidOperationException(resetArtworkResult.FirstError.Description); } - // store the current fingerprints, so that the next scan can detect whether the provider configuration changed again. - // the library is already tracked by the change tracker, so the modifications are persisted directly, without going through the repository - // update action, whose clearing and re-adding of the owned content locations would drop them when the same tracked instance is passed + // Store the current fingerprints, so that the next scan can detect whether the provider configuration changed again. + // The library is already tracked by the change tracker, so the modifications are persisted directly, without going through the repository + // update action, whose clearing and re-adding of the owned content locations would drop them when the same tracked instance is passed. library.MetadataProvidersConfigurationFingerprint = metadataFingerprint; library.ArtworkProvidersConfigurationFingerprint = artworkFingerprint; library.UpdatedOnUtc = DateTime.UtcNow; library.UpdatedBy = Guid.NewGuid(); - await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + throw new InvalidOperationException(saveChangesResult.FirstError.Description); - // increment the number of processed elements progress + // Increment the number of processed elements progress. publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 1, 1, cancellationToken).ConfigureAwait(false); if (publishJobProgressResult.IsFailure) throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); Status = LibraryScanJobStatus.Completed; - // when this job has no linked children, it's the last job in the directed acyclic job graph, and the scan is completed + // When this job has no linked children, it is the last job in the directed acyclic job graph, and the scan is completed. if (Children.Count == 0) await domainEventPublisher.PublishAsync(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - // call each linked child with the obtained payload + // Call each linked child with the obtained payload. foreach (IMediaLibraryScanJob child in Children) await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false); }, cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJob.cs index a00ae9ba..b78a12d1 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJob.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; -using Lumina.Application.Common.DataAccess.Repositories.Books; +using Lumina.Application.Common.DataAccess.Repositories.BookLibrary; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; @@ -52,17 +52,17 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed { try { - // increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel) + // Increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel). int parentsCompleted = Interlocked.Increment(ref parentsPayloadsExecuted); - // only execute this job's payload when it has no parents, or when all the parents finished their execution + // Only execute this job's payload when it has no parents, or when all the parents finished their execution. if (Parents.Count == 0 || parentsCompleted == Parents.Count) { - // this needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous - // processing that takes time, and would block the processing of scan jobs in the in-memory queue + // This needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous + // processing that takes time, and would block the processing of scan jobs in the in-memory queue. await Task.Run(async () => { Status = LibraryScanJobStatus.Running; - // see docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details: + // See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details. await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!; @@ -70,27 +70,27 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); - // set the initial progress of the scan job, it's a 1 step job - applying the scan results to the storage medium + // Set the initial progress of the scan job; it is a single step job, applying the scan results to the storage medium. Result publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false); if (publishJobProgressResult.IsFailure) throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); - // get the paths of the media library scan snapshot items that are no longer present in the current scan, so that deletion events can be raised for them + // Get the paths of the media library scan snapshot items that are no longer present in the current scan, so that deletion events can be raised for them. Result> getDeletedPathsResult = await unitOfWork.LibraryScanSnapshotRepository.GetDeletedPathsAsync(LibraryId.Value, ScanId.Value, cancellationToken).ConfigureAwait(false); if (getDeletedPathsResult.IsFailure) throw new InvalidOperationException(getDeletedPathsResult.FirstError.Description); - // get the paths of the media library scan staging results that changed since the previous scan, so that the books stored at those paths are re-enriched + // Get the paths of the media library scan staging results that changed since the previous scan, so that the books stored at those paths are re-enriched. Result> getChangedPathsResult = await unitOfWork.LibraryScanStagingResultsRepository.GetChangedPathsAsync(ScanId.Value, cancellationToken).ConfigureAwait(false); if (getChangedPathsResult.IsFailure) throw new InvalidOperationException(getChangedPathsResult.FirstError.Description); - // apply the results of the current scan to the storage medium, atomically replacing the media library scan snapshot of the previous scan + // Apply the results of the current scan to the storage medium, atomically replacing the media library scan snapshot of the previous scan. Result applySnapshotSwapResult = await unitOfWork.LibraryScanSnapshotRepository.ApplySnapshotSwapAsync(LibraryId.Value, ScanId.Value, UserId.Value, cancellationToken).ConfigureAwait(false); if (applySnapshotSwapResult.IsFailure) throw new InvalidOperationException(applySnapshotSwapResult.FirstError.Description); - // reset the enrichment state of the books whose content changed, so that they are re-enriched by the enrichment jobs that follow + // Reset the enrichment state of the books whose content changed, so that they are re-enriched by the enrichment jobs that follow. if (getChangedPathsResult.Value.Count > 0) { Result resetEnrichmentStateResult = await unitOfWork.BookRepository.ResetEnrichmentStateForPathsAsync(LibraryId.Value, getChangedPathsResult.Value, cancellationToken).ConfigureAwait(false); @@ -98,14 +98,14 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed throw new InvalidOperationException(resetEnrichmentStateResult.FirstError.Description); } - // raise a deletion event for every media library scan snapshot item that is no longer present on disk + // Raise a deletion event for every media library scan snapshot item that is no longer present on disk. foreach (string deletedPath in getDeletedPathsResult.Value) { cancellationToken.ThrowIfCancellationRequested(); await domainEventPublisher.PublishAsync(new LibraryMediaItemDeletedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, deletedPath, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); } - // materialize the books of the media library from the scan snapshot, so that they are browsable even without web metadata + // Materialize the books of the media library from the scan snapshot, so that they are browsable even without web metadata. Result> getPathsResult = await unitOfWork.LibraryScanSnapshotRepository.GetPathsAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); if (getPathsResult.IsFailure) throw new InvalidOperationException(getPathsResult.FirstError.Description); @@ -124,19 +124,21 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed if (insertBookResult.IsFailure) throw new InvalidOperationException(insertBookResult.FirstError.Description); } - await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + throw new InvalidOperationException(saveChangesResult.FirstError.Description); - // increment the number of processed elements progress + // Increment the number of processed elements progress. publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 1, 1, cancellationToken).ConfigureAwait(false); if (publishJobProgressResult.IsFailure) throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); Status = LibraryScanJobStatus.Completed; - // when this job has no linked children, it's the last job in the directed acyclic job graph, and the scan is completed + // When this job has no linked children, it is the last job in the directed acyclic job graph, and the scan is completed. if (Children.Count == 0) await domainEventPublisher.PublishAsync(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - // call each linked child with the obtained payload + // Call each linked child with the obtained payload. foreach (IMediaLibraryScanJob child in Children) await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false); }, cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Infrastructure/Core/Plugins/PluginDetectionSyncJob.cs b/src/Lumina.Infrastructure/Core/Plugins/PluginDetectionSyncJob.cs index 19602b01..c31213fa 100644 --- a/src/Lumina.Infrastructure/Core/Plugins/PluginDetectionSyncJob.cs +++ b/src/Lumina.Infrastructure/Core/Plugins/PluginDetectionSyncJob.cs @@ -2,6 +2,8 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Infrastructure.Plugins; using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.Plugins; @@ -109,12 +111,12 @@ internal sealed class PluginDetectionSyncJob : BackgroundService // Remove the rows of the plugins that are no longer detected, so that each plugin assembly has exactly one row regardless of its load status, // and delete the provider configurations of the removed plugins, since their configuration only makes sense while the plugin is installed. IMediaLibraryProviderConfigurationStore providerConfigurationStore = asyncServiceScope.ServiceProvider.GetRequiredService(); - Result> getPluginsResult = await unitOfWork.PluginRepository.GetAllAsync(stoppingToken).ConfigureAwait(false); + Result> getPluginsResult = await unitOfWork.PluginRepository.GetAllAsync(cancellationToken: stoppingToken).ConfigureAwait(false); if (getPluginsResult.IsFailure) _logger.LogError("Failed to get the detected plugins while reconciling the plugin rows."); else { - foreach (PluginEntity plugin in getPluginsResult.Value) + foreach (PluginEntity plugin in getPluginsResult.Value.Data) { if (detectedPluginIds.Contains(plugin.Id)) continue; @@ -128,12 +130,12 @@ internal sealed class PluginDetectionSyncJob : BackgroundService } // Seed the provider configurations of the media libraries, so that every library lists the plugins providing metadata or artwork for its type. - Result> getLibrariesResult = await unitOfWork.LibraryRepository.GetAllAsync(stoppingToken).ConfigureAwait(false); + Result> getLibrariesResult = await unitOfWork.LibraryRepository.GetAllAsync(cancellationToken: stoppingToken).ConfigureAwait(false); if (getLibrariesResult.IsFailure) _logger.LogError("Failed to get the media libraries while seeding the provider configurations."); else { - foreach (LibraryEntity library in getLibrariesResult.Value) + foreach (LibraryEntity library in getLibrariesResult.Value.Data) { Result ensureResult = await providerConfigurationStore.EnsureProviderConfigurationsAsync(library.Id, library.LibraryType, stoppingToken).ConfigureAwait(false); if (ensureResult.IsFailure) @@ -144,7 +146,9 @@ internal sealed class PluginDetectionSyncJob : BackgroundService } } - await unitOfWork.SaveChangesAsync(stoppingToken).ConfigureAwait(false); + Result saveChangesResult = await unitOfWork.SaveChangesAsync(stoppingToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + throw new InvalidOperationException(saveChangesResult.FirstError.Description); } /// diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledJobSchedulerJob.cs b/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledJobSchedulerJob.cs index 15511ac3..968685da 100644 --- a/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledJobSchedulerJob.cs +++ b/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledJobSchedulerJob.cs @@ -68,7 +68,7 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS /// A task that represents the asynchronous operation. public Task StartCycleAsync(ScheduledJobId scheduledJobId, CancellationToken cancellationToken) { - RunCycleWorkerAsync(scheduledJobId, runImmediately: true, cancellationToken).FireAndForgetSafeAsync(); + RunCycleWorkerAsync(scheduledJobId, shouldRunImmediately: true, cancellationToken).FireAndForgetSafeAsync(); return Task.CompletedTask; } @@ -174,8 +174,8 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS continue; } // A once at startup scheduled job fires immediately when its cycle is resumed at startup; the other scheduled jobs wait for their next scheduled execution. - bool runImmediately = scheduledJob.ScheduleType == ScheduleType.OnceAtStartup; - RunCycleWorkerAsync(scheduledJobId, runImmediately, cancellationToken).FireAndForgetSafeAsync(); + bool shouldRunImmediately = scheduledJob.ScheduleType == ScheduleType.OnceAtStartup; + RunCycleWorkerAsync(scheduledJobId, shouldRunImmediately, cancellationToken).FireAndForgetSafeAsync(); } } @@ -183,9 +183,9 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS /// Runs the execution cycle worker of the scheduled job identified by . /// /// The object representing the unique identifier of the scheduled job whose cycle is run. - /// Whether the task of the scheduled job is run immediately when the cycle starts. + /// Whether the task of the scheduled job is run immediately when the cycle starts. /// Cancellation token that can be used to stop the execution. - private async Task RunCycleWorkerAsync(ScheduledJobId scheduledJobId, bool runImmediately, CancellationToken stoppingToken) + private async Task RunCycleWorkerAsync(ScheduledJobId scheduledJobId, bool shouldRunImmediately, CancellationToken stoppingToken) { // Each cycle owns its own cancellation token source: it is the handle the runtime registry stores, so stopping one // scheduled job cancels exactly this cycle and no other job's cycle, even though the cycle worker itself runs "fire and forget" on another thread. @@ -203,7 +203,7 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS CancellationToken cycleToken = linkedCancellationTokenSource.Token; // An immediate run is executed as a cycle run, so it completes the scheduled job back to its active state and is // recorded as part of the cycle; this is the path taken by an admin start, by the resume at startup and by the seed of the default jobs. - if (runImmediately) + if (shouldRunImmediately) await RunScheduledJobAsync(scheduledJobId, isCycleRun: true, cycleToken).ConfigureAwait(false); // The schedule is read from the storage medium for every cycle, so the delay until the next run is always @@ -320,7 +320,7 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS IDomainEventPublisher domainEventPublisher = services.GetRequiredService(); // Load the scheduled job, and mark its task as started. - Result getScheduledJobResult = await unitOfWork.ScheduledJobRepository.GetByIdAsync(scheduledJobId.Value, cancellationToken).ConfigureAwait(false); + Result getScheduledJobResult = await unitOfWork.ScheduledJobRepository.GetByIdAsync(scheduledJobId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); if (getScheduledJobResult.IsFailure || getScheduledJobResult.Value is null) return; Result scheduledJobDomainResult = getScheduledJobResult.Value.ToDomainEntity(); @@ -383,8 +383,8 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS // A one time execution returns the scheduled job to its active state when its execution cycle is still running, so the // running cycle keeps scheduling executions and the job can still be stopped; the same applies to a once at startup job, // whose active state is what makes it fire again at the next application startup. - bool completesTheCycleRun = isCycleRun || _runtimeRegistry.HasActiveCycle(scheduledJob.Id) || scheduledJob.Schedule.ScheduleType == ScheduleType.OnceAtStartup; - Result completeExecutionResult = scheduledJob.MarkExecutionCompleted(completesTheCycleRun); + bool doesCompleteTheCycleRun = isCycleRun || _runtimeRegistry.HasActiveCycle(scheduledJob.Id) || scheduledJob.Schedule.ScheduleType == ScheduleType.OnceAtStartup; + Result completeExecutionResult = scheduledJob.MarkExecutionCompleted(doesCompleteTheCycleRun); if (completeExecutionResult.IsFailure) return; foreach (IDomainEvent domainEvent in scheduledJob.GetDomainEvents()) @@ -412,7 +412,7 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS { await using AsyncServiceScope scope = _serviceScopeFactory.CreateAsyncScope(); IUnitOfWork unitOfWork = scope.ServiceProvider.GetRequiredService(); - Result getScheduledJobResult = await unitOfWork.ScheduledJobRepository.GetByIdAsync(scheduledJobId.Value, cancellationToken).ConfigureAwait(false); + Result getScheduledJobResult = await unitOfWork.ScheduledJobRepository.GetByIdAsync(scheduledJobId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); if (getScheduledJobResult.IsFailure || getScheduledJobResult.Value is null) return ScheduledJobStatus.Added; ScheduledJobEntity scheduledJob = getScheduledJobResult.Value; @@ -433,17 +433,19 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS ScheduledJobStatus reconciledStatus = (openExecution?.WasCycleActive ?? true) ? ScheduledJobStatus.Active : ScheduledJobStatus.Added; Result updateScheduledJobResult = await unitOfWork.ScheduledJobRepository.UpdateAsync( - CreateUpdatedScheduledJob(scheduledJob, reconciledStatus, scheduledJob.LastStartedOnUtc, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + scheduledJob.ToUpdatedRepositoryEntity(reconciledStatus, scheduledJob.LastStartedOnUtc, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); if (updateScheduledJobResult.IsFailure) return ScheduledJobStatus.Added; if (openExecution is not null) { Result updateExecutionResult = await unitOfWork.ScheduledJobExecutionRepository.UpdateAsync( - CreateClosedExecution(openExecution, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + openExecution.ToUpdatedRepositoryEntity(DateTime.UtcNow), cancellationToken).ConfigureAwait(false); if (updateExecutionResult.IsFailure) return ScheduledJobStatus.Added; } - await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + throw new InvalidOperationException(saveChangesResult.FirstError.Description); _logger.LogInformation("The interrupted execution of the scheduled job '{ScheduledJobName}' was closed.", scheduledJob.Name); return reconciledStatus; } @@ -468,7 +470,7 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS { await using AsyncServiceScope scope = _serviceScopeFactory.CreateAsyncScope(); IUnitOfWork unitOfWork = scope.ServiceProvider.GetRequiredService(); - Result getScheduledJobResult = await unitOfWork.ScheduledJobRepository.GetByIdAsync(scheduledJobId.Value, cancellationToken).ConfigureAwait(false); + Result getScheduledJobResult = await unitOfWork.ScheduledJobRepository.GetByIdAsync(scheduledJobId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); if (getScheduledJobResult.IsFailure || getScheduledJobResult.Value is null) return null; Result scheduledJobDomainResult = getScheduledJobResult.Value.ToDomainEntity(); @@ -488,57 +490,4 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS return schedule.GetDelayUntilNextExecution(dateTimeProvider.UtcNow, TimeZoneInfo.Local); } - /// - /// Creates a copy of with the provided status and timestamps. - /// - /// The scheduled job to copy. - /// The status of the copy. - /// The last start time of the copy. - /// The last completion time of the copy. - /// The copy of the scheduled job. - private static ScheduledJobEntity CreateUpdatedScheduledJob(ScheduledJobEntity scheduledJob, ScheduledJobStatus status, DateTime? lastStartedOnUtc, DateTime? lastCompletedOnUtc) - { - return new ScheduledJobEntity - { - Id = scheduledJob.Id, - Name = scheduledJob.Name, - TaskType = scheduledJob.TaskType, - ScheduleType = scheduledJob.ScheduleType, - IntervalMinutes = scheduledJob.IntervalMinutes, - Hour = scheduledJob.Hour, - Minute = scheduledJob.Minute, - Status = status, - OwnerUserId = scheduledJob.OwnerUserId, - LastStartedOnUtc = lastStartedOnUtc, - LastCompletedOnUtc = lastCompletedOnUtc, - CreatedOnUtc = scheduledJob.CreatedOnUtc, - CreatedBy = scheduledJob.CreatedBy, - UpdatedOnUtc = scheduledJob.UpdatedOnUtc, - UpdatedBy = scheduledJob.UpdatedBy - }; - } - - /// - /// Creates a copy of with the provided completion time. - /// - /// The execution to copy. - /// The completion time of the copy. - /// The copy of the execution. - private static ScheduledJobExecutionEntity CreateClosedExecution(ScheduledJobExecutionEntity execution, DateTime? completedOnUtc) - { - return new ScheduledJobExecutionEntity - { - Id = execution.Id, - ScheduledJobId = execution.ScheduledJobId, - TaskType = execution.TaskType, - IsCycleRun = execution.IsCycleRun, - WasCycleActive = execution.WasCycleActive, - StartedOnUtc = execution.StartedOnUtc, - CompletedOnUtc = completedOnUtc, - CreatedOnUtc = execution.CreatedOnUtc, - CreatedBy = execution.CreatedBy, - UpdatedOnUtc = execution.UpdatedOnUtc, - UpdatedBy = execution.UpdatedBy - }; - } } diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/MediaLibraryScanTaskExecutor.cs b/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/MediaLibraryScanTaskExecutor.cs index ed8bfaaf..5af50bcb 100644 --- a/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/MediaLibraryScanTaskExecutor.cs +++ b/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/MediaLibraryScanTaskExecutor.cs @@ -98,7 +98,9 @@ public class MediaLibraryScanTaskExecutor : IScheduledTaskExecutor domainEvents.AddRange(libraryScanResult.Value.GetDomainEvents()); } - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + throw new InvalidOperationException(saveChangesResult.FirstError.Description); // Publish the domain events of the queued media library scans. foreach (IDomainEvent domainEvent in domainEvents) diff --git a/src/Lumina.Infrastructure/Core/Themes/ThemeSynchronizer.cs b/src/Lumina.Infrastructure/Core/Themes/ThemeSynchronizer.cs index 7a0e94b4..278e3175 100644 --- a/src/Lumina.Infrastructure/Core/Themes/ThemeSynchronizer.cs +++ b/src/Lumina.Infrastructure/Core/Themes/ThemeSynchronizer.cs @@ -1,6 +1,8 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Themes; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Infrastructure.Models.DTO.Themes; using Lumina.Application.Common.Infrastructure.Themes; using Lumina.Domain.Common.Primitives; @@ -30,7 +32,7 @@ internal static class ThemeSynchronizer /// Cancellation token that can be used to stop the execution. internal static async Task SynchronizeAsync(IThemeService themeService, IUnitOfWork unitOfWork, ILogger logger, CancellationToken cancellationToken) { - Result> getThemesResult = await unitOfWork.ThemeRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + Result> getThemesResult = await unitOfWork.ThemeRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false); if (getThemesResult.IsFailure) { logger.LogWarning("Failed to read the installed themes: {Error}", getThemesResult.FirstError.Description); @@ -38,7 +40,7 @@ internal static class ThemeSynchronizer } // Themes that were soft deleted by the user must not be reinstalled automatically. - List themes = [.. getThemesResult.Value]; + List themes = [.. getThemesResult.Value.Data]; foreach (string archivePath in themeService.GetBundledThemeArchivePaths()) { @@ -107,7 +109,9 @@ internal static class ThemeSynchronizer await CleanUpMissingThemePacksAsync(themeService, unitOfWork, themes, logger, cancellationToken).ConfigureAwait(false); await EnsureCurrentThemeExistsAsync(themeService, unitOfWork, themes, cancellationToken).ConfigureAwait(false); - await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + throw new InvalidOperationException(saveChangesResult.FirstError.Description); } /// diff --git a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/UoW/UnitOfWorkTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/UoW/UnitOfWorkTests.cs index c8adc54e..0192ef7b 100644 --- a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/UoW/UnitOfWorkTests.cs +++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/UoW/UnitOfWorkTests.cs @@ -1,7 +1,10 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Authorization; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Primitives; using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; using System; @@ -9,6 +12,7 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; #endregion namespace Lumina.DataAccess.IntegrationTests.Core.UoW; @@ -20,6 +24,7 @@ namespace Lumina.DataAccess.IntegrationTests.Core.UoW; public class UnitOfWorkTests { private readonly RoleEntityFixture _roleEntityFixture = new(); + private readonly BookEntityFixture _bookEntityFixture = new(); [Fact] public async Task BeginTransactionAsync_WhenCalled_ShouldBeginTransactionOnTheDatabase() @@ -177,6 +182,40 @@ public class UnitOfWorkTests } } + [Fact] + public async Task SaveChangesAsync_WhenInsertingTwoBooksWithTheSameLibraryAndPath_ShouldReturnUniqueConstraintViolationError() + { + // Arrange + (SqliteConnection anchorConnection, LuminaDbContext dbContext) = CreateSqliteContext(); + using (anchorConnection) + { + using (dbContext) + { + UnitOfWork sut = new(dbContext); + Guid libraryId = Guid.NewGuid(); + BookEntity firstBook = _bookEntityFixture.Create(); + firstBook.LibraryId = libraryId; + firstBook.Path = "/books/duplicate.epub"; + _ = await sut.BookRepository.InsertAsync(firstBook, CancellationToken.None); + Result firstSaveResult = await sut.SaveChangesAsync(CancellationToken.None); + Assert.False(firstSaveResult.IsFailure); + + // stage a second book with the same library and path directly, bypassing the application level pre-check, so that the unique index of the storage medium is the one that rejects it + BookEntity secondBook = _bookEntityFixture.Create(); + secondBook.LibraryId = libraryId; + secondBook.Path = "/books/duplicate.epub"; + dbContext.Books.Add(secondBook); + + // Act + Result result = await sut.SaveChangesAsync(CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + } + } + } + /// /// Creates a real SQLite in-memory context, kept alive by an anchor connection, because transactions are not supported by the in-memory provider. /// diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandlerTests.cs index f43abf85..fbaa8787 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandlerTests.cs @@ -2,6 +2,8 @@ using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Repositories.Authorization; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; @@ -46,6 +48,7 @@ public class GetPermissionsQueryHandlerTests _mockAuthorizationService = Substitute.For(); _mockPermissionRepository = Substitute.For(); _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _userId = Guid.NewGuid(); _mockCurrentUserService.UserId.Returns(_userId); @@ -62,7 +65,7 @@ public class GetPermissionsQueryHandlerTests { // Arrange GetPermissionsQuery query = _getPermissionsQueryFixture.Create(); - IEnumerable permissions = + List permissions = [ _permissionEntityFixture.Create(permissionName: AuthorizationPermission.CanViewUsers), _permissionEntityFixture.Create(permissionName: AuthorizationPermission.CanDeleteUsers) @@ -70,8 +73,8 @@ public class GetPermissionsQueryHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockPermissionRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From(permissions)); + _mockPermissionRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = permissions, CurrentPage = 1, PerPage = permissions.Count, Count = permissions.Count, NumberOfPages = 1 })); // Act Result> result = await _sut.HandleAsync(query, CancellationToken.None); @@ -80,7 +83,7 @@ public class GetPermissionsQueryHandlerTests Assert.False(result.IsFailure); Assert.Equal(2, result.Value.Count()); await _mockAuthorizationService.Received(1).IsInRoleAsync(_userId, "Admin", Arg.Any()); - await _mockPermissionRepository.Received(1).GetAllAsync(Arg.Any()); + await _mockPermissionRepository.Received(1).GetAllAsync(cancellationToken: Arg.Any()); } [Fact] @@ -99,7 +102,7 @@ public class GetPermissionsQueryHandlerTests Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError); await _mockAuthorizationService.Received(1).IsInRoleAsync(_userId, "Admin", Arg.Any()); - await _mockPermissionRepository.DidNotReceive().GetAllAsync(Arg.Any()); + await _mockPermissionRepository.DidNotReceive().GetAllAsync(cancellationToken: Arg.Any()); } [Fact] @@ -116,7 +119,7 @@ public class GetPermissionsQueryHandlerTests Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError); await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockPermissionRepository.DidNotReceive().GetAllAsync(Arg.Any()); + await _mockPermissionRepository.DidNotReceive().GetAllAsync(cancellationToken: Arg.Any()); } [Fact] @@ -128,7 +131,7 @@ public class GetPermissionsQueryHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockPermissionRepository.GetAllAsync(Arg.Any()) + _mockPermissionRepository.GetAllAsync(cancellationToken: Arg.Any()) .Returns(error); // Act @@ -138,7 +141,7 @@ public class GetPermissionsQueryHandlerTests Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); await _mockAuthorizationService.Received(1).IsInRoleAsync(_userId, "Admin", Arg.Any()); - await _mockPermissionRepository.Received(1).GetAllAsync(Arg.Any()); + await _mockPermissionRepository.Received(1).GetAllAsync(cancellationToken: Arg.Any()); } [Fact] @@ -146,7 +149,7 @@ public class GetPermissionsQueryHandlerTests { // Arrange GetPermissionsQuery query = _getPermissionsQueryFixture.Create(); - IEnumerable permissions = + List permissions = [ _permissionEntityFixture.Create(permissionName: AuthorizationPermission.CanViewUsers) ]; @@ -154,8 +157,8 @@ public class GetPermissionsQueryHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockPermissionRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From(permissions)); + _mockPermissionRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = permissions, CurrentPage = 1, PerPage = permissions.Count, Count = permissions.Count, NumberOfPages = 1 })); // Act Result> result = await _sut.HandleAsync(query, cancellationToken); @@ -164,6 +167,6 @@ public class GetPermissionsQueryHandlerTests Assert.False(result.IsFailure); Assert.Single(result.Value); await _mockAuthorizationService.Received(1).IsInRoleAsync(_userId, "Admin", Arg.Any()); - await _mockPermissionRepository.Received(1).GetAllAsync(Arg.Any()); + await _mockPermissionRepository.Received(1).GetAllAsync(cancellationToken: Arg.Any()); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandlerTests.cs index aadc14c4..b892e1c4 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandlerTests.cs @@ -49,6 +49,7 @@ public class AddRoleCommandHandlerTests mockValidator.Validate(Arg.Any()) .Returns([]); _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockAuthorizationService = Substitute.For(); _mockCurrentUserService = Substitute.For(); _mockRoleRepository = Substitute.For(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandlerTests.cs index 5976f727..4e51668b 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandlerTests.cs @@ -43,6 +43,7 @@ public class DeleteRoleCommandHandlerTests mockValidator.Validate(Arg.Any()) .Returns([]); _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockAuthorizationService = Substitute.For(); _mockCurrentUserService = Substitute.For(); _mockRoleRepository = Substitute.For(); @@ -89,7 +90,7 @@ public class DeleteRoleCommandHandlerTests Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError); await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockRoleRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockRoleRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -100,7 +101,7 @@ public class DeleteRoleCommandHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockRoleRepository.GetByIdAsync(command.RoleId, Arg.Any()) + _mockRoleRepository.GetByIdAsync(command.RoleId, cancellationToken: Arg.Any()) .Returns((RoleEntity?)null); // Act @@ -121,7 +122,7 @@ public class DeleteRoleCommandHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockRoleRepository.GetByIdAsync(command.RoleId, Arg.Any()) + _mockRoleRepository.GetByIdAsync(command.RoleId, cancellationToken: Arg.Any()) .Returns(adminRole); // Act @@ -142,7 +143,7 @@ public class DeleteRoleCommandHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockRoleRepository.GetByIdAsync(command.RoleId, Arg.Any()) + _mockRoleRepository.GetByIdAsync(command.RoleId, cancellationToken: Arg.Any()) .Returns(error); // Act @@ -164,7 +165,7 @@ public class DeleteRoleCommandHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockRoleRepository.GetByIdAsync(command.RoleId, Arg.Any()) + _mockRoleRepository.GetByIdAsync(command.RoleId, cancellationToken: Arg.Any()) .Returns(role); _mockRoleRepository.DeleteByIdAsync(command.RoleId, Arg.Any()) .Returns(error); @@ -187,7 +188,7 @@ public class DeleteRoleCommandHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockRoleRepository.GetByIdAsync(command.RoleId, Arg.Any()) + _mockRoleRepository.GetByIdAsync(command.RoleId, cancellationToken: Arg.Any()) .Returns(role); _mockRoleRepository.DeleteByIdAsync(command.RoleId, Arg.Any()) .Returns(Result.Deleted); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandlerTests.cs index 25e4bc67..4bfdef9a 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandlerTests.cs @@ -49,6 +49,7 @@ public class UpdateRoleCommandHandlerTests mockValidator.Validate(Arg.Any()) .Returns([]); _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockAuthorizationService = Substitute.For(); _mockCurrentUserService = Substitute.For(); _mockRoleRepository = Substitute.For(); @@ -130,7 +131,7 @@ public class UpdateRoleCommandHandlerTests .Returns(true); _mockRoleRepository.UpdateAsync(Arg.Any(), Arg.Any()) .Returns(Result.Updated); - _mockRoleRepository.GetByIdAsync(command.RoleId, Arg.Any()) + _mockRoleRepository.GetByIdAsync(command.RoleId, cancellationToken: Arg.Any()) .Returns(error); // Act @@ -151,7 +152,7 @@ public class UpdateRoleCommandHandlerTests .Returns(true); _mockRoleRepository.UpdateAsync(Arg.Any(), Arg.Any()) .Returns(Result.Updated); - _mockRoleRepository.GetByIdAsync(command.RoleId, Arg.Any()) + _mockRoleRepository.GetByIdAsync(command.RoleId, cancellationToken: Arg.Any()) .Returns((RoleEntity?)null); // Act @@ -178,7 +179,7 @@ public class UpdateRoleCommandHandlerTests .Returns(true); _mockRoleRepository.UpdateAsync(Arg.Any(), Arg.Any()) .Returns(Result.Updated); - _mockRoleRepository.GetByIdAsync(command.RoleId, Arg.Any()) + _mockRoleRepository.GetByIdAsync(command.RoleId, cancellationToken: Arg.Any()) .Returns(role); // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandlerTests.cs index 2692d0bc..773b3828 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandlerTests.cs @@ -47,6 +47,7 @@ public class GetRolePermissionsQueryHandlerTests mockValidator.Validate(Arg.Any()) .Returns([]); _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockAuthorizationService = Substitute.For(); _mockCurrentUserService = Substitute.For(); _mockRoleRepository = Substitute.For(); @@ -76,7 +77,7 @@ public class GetRolePermissionsQueryHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError); - await _mockRoleRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockRoleRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -93,7 +94,7 @@ public class GetRolePermissionsQueryHandlerTests Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError); await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockRoleRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockRoleRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -105,7 +106,7 @@ public class GetRolePermissionsQueryHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockRoleRepository.GetByIdAsync(query.RoleId, Arg.Any()) + _mockRoleRepository.GetByIdAsync(query.RoleId, cancellationToken: Arg.Any()) .Returns(error); // Act @@ -124,7 +125,7 @@ public class GetRolePermissionsQueryHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockRoleRepository.GetByIdAsync(query.RoleId, Arg.Any()) + _mockRoleRepository.GetByIdAsync(query.RoleId, cancellationToken: Arg.Any()) .Returns((RoleEntity?)null); // Act @@ -153,7 +154,7 @@ public class GetRolePermissionsQueryHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockRoleRepository.GetByIdAsync(query.RoleId, Arg.Any()) + _mockRoleRepository.GetByIdAsync(query.RoleId, cancellationToken: Arg.Any()) .Returns(role); // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandlerTests.cs index ddec5b2f..7569ad9f 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandlerTests.cs @@ -2,6 +2,8 @@ using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Repositories.Authorization; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; @@ -41,6 +43,7 @@ public class GetRolesQueryHandlerTests public GetRolesQueryHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockAuthorizationService = Substitute.For(); _mockCurrentUserService = Substitute.For(); _mockRoleRepository = Substitute.For(); @@ -69,7 +72,7 @@ public class GetRolesQueryHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError); - await _mockRoleRepository.DidNotReceive().GetAllAsync(Arg.Any()); + await _mockRoleRepository.DidNotReceive().GetAllAsync(cancellationToken: Arg.Any()); } [Fact] @@ -86,7 +89,7 @@ public class GetRolesQueryHandlerTests Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError); await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockRoleRepository.DidNotReceive().GetAllAsync(Arg.Any()); + await _mockRoleRepository.DidNotReceive().GetAllAsync(cancellationToken: Arg.Any()); } [Fact] @@ -98,7 +101,7 @@ public class GetRolesQueryHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockRoleRepository.GetAllAsync(Arg.Any()) + _mockRoleRepository.GetAllAsync(cancellationToken: Arg.Any()) .Returns(error); // Act @@ -114,7 +117,7 @@ public class GetRolesQueryHandlerTests { // Arrange GetRolesQuery query = _getRolesQueryFixture.Create(); - IEnumerable roles = + List roles = [ _roleEntityFixture.Create(roleName: "Admin"), _roleEntityFixture.Create(roleName: "User") @@ -122,8 +125,8 @@ public class GetRolesQueryHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockRoleRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From(roles)); + _mockRoleRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = roles, CurrentPage = 1, PerPage = roles.Count, Count = roles.Count, NumberOfPages = 1 })); // Act Result> result = await _sut.HandleAsync(query, CancellationToken.None); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandlerTests.cs index 685422b6..7e22e841 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandlerTests.cs @@ -5,6 +5,8 @@ using Lumina.Application.Common.DataAccess.Repositories.Scheduling; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.Seed; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.DomainEvents; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; @@ -22,7 +24,6 @@ using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; using NSubstitute; using System; using System.Diagnostics.CodeAnalysis; -using System.Linq; using System.Threading; using System.Threading.Tasks; #endregion @@ -57,6 +58,7 @@ public class SetupApplicationCommandHandlerTests public SetupApplicationCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockHashService = Substitute.For(); _mockCryptographyService = Substitute.For(); _mockTotpTokenGenerator = Substitute.For(); @@ -75,8 +77,8 @@ public class SetupApplicationCommandHandlerTests _mockDateTimeProvider.UtcNow.Returns(DateTime.UtcNow); _mockDataSeedService.SetDefaultScheduledJobsAsync(Arg.Any(), Arg.Any()) .Returns(Result.Created); - _mockScheduledJobRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From(Enumerable.Empty())); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); _sut = new SetupApplicationCommandHandler( _mockUnitOfWork, @@ -97,8 +99,8 @@ public class SetupApplicationCommandHandlerTests SetupApplicationCommand command = _setupApplicationCommandFixture.Create() with { Use2fa = false }; string hashedPassword = Uri.EscapeDataString("hashedPassword"); - _mockUserRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From(Enumerable.Empty())); + _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); _mockHashService.HashString(command.Password!) .Returns(hashedPassword); _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) @@ -121,7 +123,7 @@ public class SetupApplicationCommandHandlerTests Assert.Equal(command.Username, result.Value.Username); Assert.Null(result.Value.TotpSecret); - await _mockUserRepository.Received(1).GetAllAsync(Arg.Any()); + await _mockUserRepository.Received(1).GetAllAsync(cancellationToken: Arg.Any()); await _mockUserRepository.Received(1).InsertAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); } @@ -136,8 +138,8 @@ public class SetupApplicationCommandHandlerTests string qrCodeUri = "data:image/png;base64,test"; string encryptedSecret = "encryptedSecret"; - _mockUserRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From(Enumerable.Empty())); + _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); _mockHashService.HashString(command.Password!) .Returns(hashedPassword); _mockTotpTokenGenerator.GenerateSecret() @@ -166,7 +168,7 @@ public class SetupApplicationCommandHandlerTests Assert.Equal(command.Username, result.Value.Username); Assert.Equal(qrCodeUri, result.Value.TotpSecret); - await _mockUserRepository.Received(1).GetAllAsync(Arg.Any()); + await _mockUserRepository.Received(1).GetAllAsync(cancellationToken: Arg.Any()); await _mockUserRepository.Received(1).InsertAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); } @@ -178,8 +180,8 @@ public class SetupApplicationCommandHandlerTests SetupApplicationCommand command = _setupApplicationCommandFixture.Create(); UserEntity existingUser = _userEntityFixture.Create(); - _mockUserRepository.GetAllAsync(Arg.Any()) - .Returns(new[] { existingUser }); + _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [existingUser], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 })); // Act Result result = await _sut.HandleAsync(command, CancellationToken.None); @@ -188,7 +190,7 @@ public class SetupApplicationCommandHandlerTests Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.AdminAccountAlreadyCreated, result.FirstError); - await _mockUserRepository.Received(1).GetAllAsync(Arg.Any()); + await _mockUserRepository.Received(1).GetAllAsync(cancellationToken: Arg.Any()); await _mockUserRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -200,7 +202,7 @@ public class SetupApplicationCommandHandlerTests SetupApplicationCommand command = _setupApplicationCommandFixture.Create(); Error error = Error.Failure("Database.Error", "Failed to retrieve users"); - _mockUserRepository.GetAllAsync(Arg.Any()) + _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) .Returns(error); // Act @@ -210,7 +212,7 @@ public class SetupApplicationCommandHandlerTests Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); - await _mockUserRepository.Received(1).GetAllAsync(Arg.Any()); + await _mockUserRepository.Received(1).GetAllAsync(cancellationToken: Arg.Any()); await _mockUserRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -222,8 +224,8 @@ public class SetupApplicationCommandHandlerTests SetupApplicationCommand command = _setupApplicationCommandFixture.Create(); Error error = Error.Failure("Database.Error", "Failed to insert user"); - _mockUserRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From(Enumerable.Empty())); + _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(error); @@ -234,7 +236,7 @@ public class SetupApplicationCommandHandlerTests Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); - await _mockUserRepository.Received(1).GetAllAsync(Arg.Any()); + await _mockUserRepository.Received(1).GetAllAsync(cancellationToken: Arg.Any()); await _mockUserRepository.Received(1).InsertAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -246,8 +248,8 @@ public class SetupApplicationCommandHandlerTests SetupApplicationCommand command = _setupApplicationCommandFixture.Create(); Error error = Error.Failure("Database.Error", "Failed to set default permissions"); - _mockUserRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From(Enumerable.Empty())); + _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.Created); _mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any(), Arg.Any()) @@ -271,8 +273,8 @@ public class SetupApplicationCommandHandlerTests SetupApplicationCommand command = _setupApplicationCommandFixture.Create(); Error error = Error.Failure("Database.Error", "Failed to set default roles"); - _mockUserRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From(Enumerable.Empty())); + _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.Created); _mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any(), Arg.Any()) @@ -299,8 +301,8 @@ public class SetupApplicationCommandHandlerTests SetupApplicationCommand command = _setupApplicationCommandFixture.Create(); Error error = Error.Failure("Database.Error", "Failed to set admin role permissions"); - _mockUserRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From(Enumerable.Empty())); + _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.Created); _mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any(), Arg.Any()) @@ -330,8 +332,8 @@ public class SetupApplicationCommandHandlerTests SetupApplicationCommand command = _setupApplicationCommandFixture.Create(); Error error = Error.Failure("Database.Error", "Failed to set admin role to administrator account"); - _mockUserRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From(Enumerable.Empty())); + _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.Created); _mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any(), Arg.Any()) @@ -364,8 +366,8 @@ public class SetupApplicationCommandHandlerTests SetupApplicationCommand command = _setupApplicationCommandFixture.Create(); Error error = Error.Failure("Database.Error", "Failed to seed default scheduled jobs"); - _mockUserRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From(Enumerable.Empty())); + _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.Created); _mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any(), Arg.Any()) @@ -396,8 +398,8 @@ public class SetupApplicationCommandHandlerTests // Arrange SetupApplicationCommand command = _setupApplicationCommandFixture.Create(); - _mockUserRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From(Enumerable.Empty())); + _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.Created); _mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any(), Arg.Any()) @@ -433,8 +435,8 @@ public class SetupApplicationCommandHandlerTests ScheduledJobEntity activeScheduledJob2 = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active); ScheduledJobEntity addedScheduledJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added); - _mockUserRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From(Enumerable.Empty())); + _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.Created); _mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any(), Arg.Any()) @@ -445,8 +447,15 @@ public class SetupApplicationCommandHandlerTests .Returns(Result.Created); _mockDataSeedService.SetAdminRoleToAdministratorAccount(Arg.Any(), Arg.Any()) .Returns(Result.Created); - _mockScheduledJobRepository.GetAllAsync(Arg.Any()) - .Returns(new[] { activeScheduledJob1, activeScheduledJob2, addedScheduledJob }); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto + { + Data = [activeScheduledJob1, activeScheduledJob2, addedScheduledJob], + CurrentPage = 1, + PerPage = 3, + Count = 3, + NumberOfPages = 1 + })); // Act Result result = await _sut.HandleAsync(command, CancellationToken.None); @@ -472,7 +481,7 @@ public class SetupApplicationCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(validationError, result.FirstError); - await _mockUserRepository.DidNotReceive().GetAllAsync(Arg.Any()); + await _mockUserRepository.DidNotReceive().GetAllAsync(cancellationToken: Arg.Any()); await _mockUserRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); } @@ -481,8 +490,8 @@ public class SetupApplicationCommandHandlerTests { // Arrange SetupApplicationCommand command = _setupApplicationCommandFixture.Create(); - _mockUserRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From(Enumerable.Empty())); + _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); _mockHashService.HashString(command.Password!) .Returns("hashedPassword"); _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) @@ -496,7 +505,7 @@ public class SetupApplicationCommandHandlerTests _mockDataSeedService.SetAdminRoleToAdministratorAccount(Arg.Any(), Arg.Any()) .Returns(Result.Created); Error expectedError = Error.Failure("ScheduledJobs.NotFound", "Failed to read the scheduled jobs"); - _mockScheduledJobRepository.GetAllAsync(Arg.Any()) + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()) .Returns(expectedError); // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryHandlerTests.cs index 7771223e..c53ae29f 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryHandlerTests.cs @@ -2,6 +2,8 @@ using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Core.Maintenance.ApplicationSetup.Queries.CheckInitialization; using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Fixtures.Core.Maintenance.ApplicationSetup.Queries.CheckInitialization; @@ -10,7 +12,6 @@ using Lumina.Domain.Common.Primitives; using NSubstitute; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.Linq; using System.Threading; using System.Threading.Tasks; #endregion @@ -35,6 +36,7 @@ public class CheckInitializationQueryHandlerTests public CheckInitializationQueryHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockUserRepository = Substitute.For(); _mockUnitOfWork.UserRepository.Returns(_mockUserRepository); @@ -47,30 +49,30 @@ public class CheckInitializationQueryHandlerTests { // Arrange List users = _userEntityFixture.CreateMany(); - _mockUserRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From(users.AsEnumerable())); + _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = users, CurrentPage = 1, PerPage = users.Count, Count = users.Count, NumberOfPages = 1 })); // Act InitializationResponse result = await _sut.HandleAsync(_checkInitializationQueryFixture.Create(), CancellationToken.None); // Assert Assert.True(result.IsInitialized); - await _mockUserRepository.Received(1).GetAllAsync(Arg.Any()); + await _mockUserRepository.Received(1).GetAllAsync(cancellationToken: Arg.Any()); } [Fact] public async Task HandleAsync_WhenNoUsersExist_ShouldReturnNotInitialized() { // Arrange - _mockUserRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From(Enumerable.Empty())); + _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); // Act InitializationResponse result = await _sut.HandleAsync(_checkInitializationQueryFixture.Create(), CancellationToken.None); // Assert Assert.False(result.IsInitialized); - await _mockUserRepository.Received(1).GetAllAsync(Arg.Any()); + await _mockUserRepository.Received(1).GetAllAsync(cancellationToken: Arg.Any()); } [Fact] @@ -78,7 +80,7 @@ public class CheckInitializationQueryHandlerTests { // Arrange Error error = Error.Failure("Database.Error", "Failed to retrieve users"); - _mockUserRepository.GetAllAsync(Arg.Any()) + _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) .Returns(error); // Act @@ -86,6 +88,6 @@ public class CheckInitializationQueryHandlerTests // Assert Assert.False(result.IsInitialized); - await _mockUserRepository.Received(1).GetAllAsync(Arg.Any()); + await _mockUserRepository.Received(1).GetAllAsync(cancellationToken: Arg.Any()); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandlerTests.cs index fc0ce989..153e4fe7 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandlerTests.cs @@ -54,6 +54,7 @@ public class AddLibraryCommandHandlerTests public AddLibraryCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockLibraryRepository = Substitute.For(); _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); _mockAuthorizationService = Substitute.For(); @@ -84,7 +85,7 @@ public class AddLibraryCommandHandlerTests // Arrange AddLibraryCommand command = _addLibraryCommandFixture.Create(); LibraryEntity persistedLibrary = _libraryEntityFixture.Create(userId: _userId); - _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.From(persistedLibrary)); // Act @@ -123,7 +124,7 @@ public class AddLibraryCommandHandlerTests AddLibraryCommand command = _addLibraryCommandFixture.Create(); command = command with { CoverImage = null }; LibraryEntity persistedLibrary = _libraryEntityFixture.Create(userId: _userId); - _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.From(persistedLibrary)); // Act @@ -261,7 +262,7 @@ public class AddLibraryCommandHandlerTests { // Arrange AddLibraryCommand command = _addLibraryCommandFixture.Create(); - _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.Success(null)); // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandlerTests.cs index cd47937e..a665f741 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandlerTests.cs @@ -44,6 +44,7 @@ public class CancelLibrariesScanCommandHandlerTests public CancelLibrariesScanCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockLibraryScanRepository = Substitute.For(); _mockUnitOfWork.LibraryScanRepository.Returns(_mockLibraryScanRepository); _mockAuthorizationService = Substitute.For(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandHandlerTests.cs index 6c9d3a7e..d8b40e6d 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandHandlerTests.cs @@ -49,6 +49,7 @@ public class CancelLibraryScanCommandHandlerTests public CancelLibraryScanCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockLibraryScanRepository = Substitute.For(); _mockUnitOfWork.LibraryScanRepository.Returns(_mockLibraryScanRepository); _mockAuthorizationService = Substitute.For(); @@ -74,7 +75,7 @@ public class CancelLibraryScanCommandHandlerTests // Arrange CancelLibraryScanCommand command = _cancelLibraryScanCommandFixture.Create(); LibraryScanEntity runningScan = _libraryScanEntityFixture.Create(id: command.ScanId, libraryId: command.LibraryId, userId: _userId); - _mockLibraryScanRepository.GetByIdAsync(command.ScanId, Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(command.ScanId, cancellationToken: Arg.Any()) .Returns(Result.From(runningScan)); // Act @@ -93,7 +94,7 @@ public class CancelLibraryScanCommandHandlerTests { // Arrange CancelLibraryScanCommand command = _cancelLibraryScanCommandFixture.Create(); - _mockLibraryScanRepository.GetByIdAsync(command.ScanId, Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(command.ScanId, cancellationToken: Arg.Any()) .Returns(Result.Success(null)); // Act @@ -111,7 +112,7 @@ public class CancelLibraryScanCommandHandlerTests { // Arrange CancelLibraryScanCommand command = _cancelLibraryScanCommandFixture.Create(); - _mockLibraryScanRepository.GetByIdAsync(command.ScanId, Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(command.ScanId, cancellationToken: Arg.Any()) .Returns(Error.Failure(description: "Failed to get library scan")); // Act @@ -129,7 +130,7 @@ public class CancelLibraryScanCommandHandlerTests // Arrange CancelLibraryScanCommand command = _cancelLibraryScanCommandFixture.Create(); LibraryScanEntity runningScan = _libraryScanEntityFixture.Create(id: command.ScanId, libraryId: command.LibraryId, userId: _userId); - _mockLibraryScanRepository.GetByIdAsync(command.ScanId, Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(command.ScanId, cancellationToken: Arg.Any()) .Returns(Result.From(runningScan)); _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) .Returns(false); @@ -157,7 +158,7 @@ public class CancelLibraryScanCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockLibraryScanRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockLibraryScanRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -167,7 +168,7 @@ public class CancelLibraryScanCommandHandlerTests // Arrange CancelLibraryScanCommand command = _cancelLibraryScanCommandFixture.Create(); LibraryScanEntity completedScan = _libraryScanEntityFixture.Create(id: command.ScanId, libraryId: command.LibraryId, userId: _userId, status: LibraryScanJobStatus.Completed); - _mockLibraryScanRepository.GetByIdAsync(command.ScanId, Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(command.ScanId, cancellationToken: Arg.Any()) .Returns(Result.From(completedScan)); // Act @@ -186,7 +187,7 @@ public class CancelLibraryScanCommandHandlerTests // Arrange CancelLibraryScanCommand command = _cancelLibraryScanCommandFixture.Create(); LibraryScanEntity runningScan = _libraryScanEntityFixture.Create(id: command.ScanId, libraryId: command.LibraryId, userId: _userId); - _mockLibraryScanRepository.GetByIdAsync(command.ScanId, Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(command.ScanId, cancellationToken: Arg.Any()) .Returns(Result.From(runningScan)); _mockLibraryScanRepository.UpdateAsync(Arg.Any(), Arg.Any()) .Returns(Error.Failure(description: "Failed to update library scan")); @@ -212,7 +213,7 @@ public class CancelLibraryScanCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(DomainErrors.LibraryScanning.LibraryScanIdCannotBeEmpty, result.FirstError); - await _mockLibraryScanRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockLibraryScanRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); await _mockLibraryScanRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandlerTests.cs index dae15900..7305b45a 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandlerTests.cs @@ -50,6 +50,7 @@ public class DeleteLibraryCommandHandlerTests public DeleteLibraryCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockLibraryRepository = Substitute.For(); _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); _mockAuthorizationService = Substitute.For(); @@ -78,7 +79,7 @@ public class DeleteLibraryCommandHandlerTests // Arrange DeleteLibraryCommand command = _deleteLibraryCommandFixture.Create(); LibraryEntity library = _libraryEntityFixture.Create(id: command.Id, userId: _userId); - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(library)); // Act @@ -99,7 +100,7 @@ public class DeleteLibraryCommandHandlerTests // Arrange DeleteLibraryCommand command = _deleteLibraryCommandFixture.Create(); LibraryEntity library = _libraryEntityFixture.Create(id: command.Id, userId: _userId); - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(library)); _mockProviderConfigurationStore.RemoveProviderConfigurationsForLibraryAsync(command.Id, Arg.Any()) .Returns(Error.Failure(description: "Failed to remove provider configurations")); @@ -118,7 +119,7 @@ public class DeleteLibraryCommandHandlerTests { // Arrange DeleteLibraryCommand command = _deleteLibraryCommandFixture.Create(); - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.Success(null)); // Act @@ -136,7 +137,7 @@ public class DeleteLibraryCommandHandlerTests { // Arrange DeleteLibraryCommand command = _deleteLibraryCommandFixture.Create(); - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Error.Failure(description: "Failed to get library")); // Act @@ -154,7 +155,7 @@ public class DeleteLibraryCommandHandlerTests // Arrange DeleteLibraryCommand command = _deleteLibraryCommandFixture.Create(); LibraryEntity library = _libraryEntityFixture.Create(id: command.Id, userId: _userId); - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(library)); _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) .Returns(false); @@ -182,7 +183,7 @@ public class DeleteLibraryCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -192,7 +193,7 @@ public class DeleteLibraryCommandHandlerTests // Arrange DeleteLibraryCommand command = _deleteLibraryCommandFixture.Create(); LibraryEntity library = _libraryEntityFixture.Create(id: command.Id, userId: _userId, contentLocations: [""]); - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(library)); // Act @@ -211,7 +212,7 @@ public class DeleteLibraryCommandHandlerTests // Arrange DeleteLibraryCommand command = _deleteLibraryCommandFixture.Create(); LibraryEntity library = _libraryEntityFixture.Create(id: command.Id, userId: _userId); - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(library)); _mockLibraryRepository.DeleteByIdAsync(command.Id, Arg.Any()) .Returns(Error.Failure(description: "Failed to delete library")); @@ -237,7 +238,7 @@ public class DeleteLibraryCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(DomainErrors.Library.LibraryIdCannotBeEmpty, result.FirstError); - await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); await _mockLibraryRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandHandlerTests.cs index 9fe9a29d..026ac2fd 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandHandlerTests.cs @@ -48,6 +48,7 @@ public class ScanLibrariesCommandHandlerTests public ScanLibrariesCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockLibraryRepository = Substitute.For(); _mockLibraryScanRepository = Substitute.For(); _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandHandlerTests.cs index 66b45d40..8398d34b 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandHandlerTests.cs @@ -52,6 +52,7 @@ public class ScanLibraryCommandHandlerTests public ScanLibraryCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockLibraryRepository = Substitute.For(); _mockLibraryScanRepository = Substitute.For(); _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); @@ -81,7 +82,7 @@ public class ScanLibraryCommandHandlerTests // Arrange ScanLibraryCommand command = _scanLibraryCommandFixture.Create(); LibraryEntity library = _libraryEntityFixture.Create(id: command.Id, userId: _userId); - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(library)); // Act @@ -100,7 +101,7 @@ public class ScanLibraryCommandHandlerTests { // Arrange ScanLibraryCommand command = _scanLibraryCommandFixture.Create(); - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.Success(null)); // Act @@ -118,7 +119,7 @@ public class ScanLibraryCommandHandlerTests { // Arrange ScanLibraryCommand command = _scanLibraryCommandFixture.Create(); - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Error.Failure(description: "Failed to get library")); // Act @@ -136,7 +137,7 @@ public class ScanLibraryCommandHandlerTests // Arrange ScanLibraryCommand command = _scanLibraryCommandFixture.Create(); LibraryEntity library = _libraryEntityFixture.Create(id: command.Id, userId: _userId); - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(library)); _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) .Returns(false); @@ -164,7 +165,7 @@ public class ScanLibraryCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -174,7 +175,7 @@ public class ScanLibraryCommandHandlerTests // Arrange ScanLibraryCommand command = _scanLibraryCommandFixture.Create(); LibraryEntity library = _libraryEntityFixture.Create(id: command.Id, userId: _userId, isEnabled: false); - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(library)); // Act @@ -193,7 +194,7 @@ public class ScanLibraryCommandHandlerTests // Arrange ScanLibraryCommand command = _scanLibraryCommandFixture.Create(); LibraryEntity library = _libraryEntityFixture.Create(id: command.Id, userId: _userId, isLocked: true); - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(library)); // Act @@ -212,7 +213,7 @@ public class ScanLibraryCommandHandlerTests // Arrange ScanLibraryCommand command = _scanLibraryCommandFixture.Create(); LibraryEntity library = _libraryEntityFixture.Create(id: command.Id, userId: _userId, contentLocations: [""]); - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(library)); // Act @@ -231,7 +232,7 @@ public class ScanLibraryCommandHandlerTests // Arrange ScanLibraryCommand command = _scanLibraryCommandFixture.Create(); LibraryEntity library = _libraryEntityFixture.Create(id: command.Id, userId: _userId); - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(library)); _mockLibraryScanRepository.GetPastMonthScansByLibraryIdAsync(command.Id, Arg.Any()) .Returns(Error.Failure(description: "Failed to get past month scans")); @@ -251,7 +252,7 @@ public class ScanLibraryCommandHandlerTests // Arrange ScanLibraryCommand command = _scanLibraryCommandFixture.Create(); LibraryEntity library = _libraryEntityFixture.Create(id: command.Id, userId: _userId); - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(library)); LibraryScanEntity runningScan = _libraryScanEntityFixture.Create(libraryId: command.Id, userId: _userId, status: LibraryScanJobStatus.Running); _mockLibraryScanRepository.GetPastMonthScansByLibraryIdAsync(command.Id, Arg.Any()) @@ -273,7 +274,7 @@ public class ScanLibraryCommandHandlerTests // Arrange ScanLibraryCommand command = _scanLibraryCommandFixture.Create(); LibraryEntity library = _libraryEntityFixture.Create(id: command.Id, userId: _userId); - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(library)); _mockLibraryScanRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Error.Failure(description: "Failed to insert library scan")); @@ -299,7 +300,7 @@ public class ScanLibraryCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(DomainErrors.Library.LibraryIdCannotBeEmpty, result.FirstError); - await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); await _mockLibraryScanRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandlerTests.cs index 075425c5..942f528f 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandlerTests.cs @@ -56,6 +56,7 @@ public class UpdateLibraryCommandHandlerTests public UpdateLibraryCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockLibraryRepository = Substitute.For(); _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); _mockAuthorizationService = Substitute.For(); @@ -89,7 +90,7 @@ public class UpdateLibraryCommandHandlerTests LibraryType commandLibraryType = Enum.Parse(command.LibraryType); LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); existingLibrary.LibraryType = commandLibraryType == LibraryType.Book ? LibraryType.EBook : LibraryType.Book; - _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); // Act @@ -112,7 +113,7 @@ public class UpdateLibraryCommandHandlerTests UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); existingLibrary.LibraryType = Enum.Parse(command.LibraryType); - _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); // Act @@ -131,7 +132,7 @@ public class UpdateLibraryCommandHandlerTests LibraryType commandLibraryType = Enum.Parse(command.LibraryType); LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); existingLibrary.LibraryType = commandLibraryType == LibraryType.Book ? LibraryType.EBook : LibraryType.Book; - _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); _mockProviderConfigurationStore.ReconcileProviderConfigurationsAsync(Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Error.Failure(description: "Failed to reconcile provider configurations")); @@ -151,7 +152,7 @@ public class UpdateLibraryCommandHandlerTests UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); command = command with { CoverImage = null }; LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); - _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); // Act @@ -171,7 +172,7 @@ public class UpdateLibraryCommandHandlerTests command = command with { CoverImage = "C:/Users/user/cover.jpg" }; LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); existingLibrary.CoverImage = null; - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); _mockEnvironmentContext.FileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(ImageType.None)); @@ -182,7 +183,7 @@ public class UpdateLibraryCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(DomainErrors.Library.CoverFileMustBeAnImage, result.FirstError); - await _mockLibraryRepository.Received(1).GetByIdAsync(command.Id, Arg.Any()); + await _mockLibraryRepository.Received(1).GetByIdAsync(command.Id, cancellationToken: Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -194,7 +195,7 @@ public class UpdateLibraryCommandHandlerTests command = command with { CoverImage = "C:/Users/user/cover.jpg" }; LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); existingLibrary.CoverImage = null; - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); _mockEnvironmentContext.FileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) .Returns(Error.Failure(description: "Failed to determine image type")); @@ -204,7 +205,7 @@ public class UpdateLibraryCommandHandlerTests // Assert Assert.True(result.IsFailure); - await _mockLibraryRepository.Received(1).GetByIdAsync(command.Id, Arg.Any()); + await _mockLibraryRepository.Received(1).GetByIdAsync(command.Id, cancellationToken: Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -216,7 +217,7 @@ public class UpdateLibraryCommandHandlerTests command = command with { CoverImage = " " }; LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); existingLibrary.CoverImage = null; - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); // Act @@ -225,7 +226,7 @@ public class UpdateLibraryCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(DomainErrors.FileSystemManagement.InvalidPath, result.FirstError); - await _mockLibraryRepository.Received(1).GetByIdAsync(command.Id, Arg.Any()); + await _mockLibraryRepository.Received(1).GetByIdAsync(command.Id, cancellationToken: Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -236,7 +237,7 @@ public class UpdateLibraryCommandHandlerTests UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); existingLibrary.CoverImage = command.CoverImage; - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); // Act @@ -246,7 +247,7 @@ public class UpdateLibraryCommandHandlerTests Assert.False(result.IsFailure); await _mockEnvironmentContext.FileTypeService.DidNotReceive() .GetImageTypeAsync(Arg.Any(), Arg.Any()); - await _mockLibraryRepository.Received(2).GetByIdAsync(command.Id, Arg.Any()); + await _mockLibraryRepository.Received(2).GetByIdAsync(command.Id, cancellationToken: Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); } @@ -255,7 +256,7 @@ public class UpdateLibraryCommandHandlerTests { // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.Success(null)); // Act @@ -273,7 +274,7 @@ public class UpdateLibraryCommandHandlerTests { // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Error.Failure(description: "Failed to get library")); // Act @@ -291,7 +292,7 @@ public class UpdateLibraryCommandHandlerTests // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); _mockAuthorizationService.HasPermissionAsync(_userId, Arg.Any(), Arg.Any()) .Returns(false); @@ -321,7 +322,7 @@ public class UpdateLibraryCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -331,7 +332,7 @@ public class UpdateLibraryCommandHandlerTests // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); command = command with { ContentLocations = [""] }; @@ -351,7 +352,7 @@ public class UpdateLibraryCommandHandlerTests // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); _mockLibraryRepository.UpdateAsync(Arg.Any(), Arg.Any()) .Returns(Error.Failure(description: "Failed to update library")); @@ -370,7 +371,7 @@ public class UpdateLibraryCommandHandlerTests // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); - _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary), Error.Failure(description: "Failed to retrieve updated library")); // Act @@ -386,7 +387,7 @@ public class UpdateLibraryCommandHandlerTests // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); - _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary), Result.Success(null)); // Act @@ -411,7 +412,7 @@ public class UpdateLibraryCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(DomainErrors.Library.LibraryIdCannotBeEmpty, result.FirstError); - await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryMediaItemDeletedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryMediaItemDeletedDomainEventHandlerTests.cs index aec3802f..18d28223 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryMediaItemDeletedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryMediaItemDeletedDomainEventHandlerTests.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; -using Lumina.Application.Common.DataAccess.Repositories.Books; +using Lumina.Application.Common.DataAccess.Repositories.BookLibrary; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Core.MediaLibrary.Management.Events; @@ -68,15 +68,15 @@ public class LibraryMediaItemDeletedDomainEventHandlerTests LibraryEntity library = _libraryEntityFixture.Create(id: libraryId.Value, title: "My Library"); _mockBookRepository.GetByPathAsync(libraryId.Value, book.Path, Arg.Any()) .Returns(Result.From(book)); - _mockLibraryRepository.GetByIdAsync(libraryId.Value, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(libraryId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(library)); _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); - _mockBookRepository.DeleteAsync(book.Id, Arg.Any()) + _mockBookRepository.DeleteByIdAsync(book.Id, Arg.Any()) .Returns(Result.From(Result.Deleted)); _mockBookArtworkService.DeleteBookArtwork(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Result.Deleted); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); LibraryMediaItemDeletedDomainEvent domainEvent = _libraryMediaItemDeletedDomainEventFixture.Create(libraryId: libraryId, path: book.Path); @@ -85,7 +85,7 @@ public class LibraryMediaItemDeletedDomainEventHandlerTests // Assert _mockBookArtworkService.Received(1).DeleteBookArtwork(libraryId.Value, book.Id, "My Library", "Frank Herbert", book.Title); - await _mockBookRepository.Received(1).DeleteAsync(book.Id, Arg.Any()); + await _mockBookRepository.Received(1).DeleteByIdAsync(book.Id, Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); } @@ -104,7 +104,7 @@ public class LibraryMediaItemDeletedDomainEventHandlerTests // Assert _mockBookArtworkService.DidNotReceive().DeleteBookArtwork(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); - await _mockBookRepository.DidNotReceive().DeleteAsync(Arg.Any(), Arg.Any()); + await _mockBookRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -117,15 +117,15 @@ public class LibraryMediaItemDeletedDomainEventHandlerTests LibraryEntity library = _libraryEntityFixture.Create(id: libraryId.Value, title: "My Library"); _mockBookRepository.GetByPathAsync(libraryId.Value, book.Path, Arg.Any()) .Returns(Result.From(book)); - _mockLibraryRepository.GetByIdAsync(libraryId.Value, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(libraryId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(library)); _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); _mockBookArtworkService.DeleteBookArtwork(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Error.Failure("Artwork.DeleteFailed", "Failed to delete the stored artwork")); - _mockBookRepository.DeleteAsync(book.Id, Arg.Any()) + _mockBookRepository.DeleteByIdAsync(book.Id, Arg.Any()) .Returns(Result.From(Result.Deleted)); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); LibraryMediaItemDeletedDomainEvent domainEvent = _libraryMediaItemDeletedDomainEventFixture.Create(libraryId: libraryId, path: book.Path); @@ -134,7 +134,7 @@ public class LibraryMediaItemDeletedDomainEventHandlerTests // Assert // a failing artwork deletion must not prevent the book from being removed, so the deletion is only logged - await _mockBookRepository.Received(1).DeleteAsync(book.Id, Arg.Any()); + await _mockBookRepository.Received(1).DeleteByIdAsync(book.Id, Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); } @@ -155,7 +155,7 @@ public class LibraryMediaItemDeletedDomainEventHandlerTests // Assert Assert.Equal(error, exception.EventualConsistencyError); - await _mockBookRepository.DidNotReceive().DeleteAsync(Arg.Any(), Arg.Any()); + await _mockBookRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); } [Fact] @@ -167,14 +167,14 @@ public class LibraryMediaItemDeletedDomainEventHandlerTests LibraryEntity library = _libraryEntityFixture.Create(id: libraryId.Value, title: "My Library"); _mockBookRepository.GetByPathAsync(libraryId.Value, book.Path, Arg.Any()) .Returns(Result.From(book)); - _mockLibraryRepository.GetByIdAsync(libraryId.Value, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(libraryId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(library)); _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); _mockBookArtworkService.DeleteBookArtwork(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Result.Deleted); Error error = Error.Failure("Database.Error", "Failed to delete the book"); - _mockBookRepository.DeleteAsync(book.Id, Arg.Any()) + _mockBookRepository.DeleteByIdAsync(book.Id, Arg.Any()) .Returns(error); LibraryMediaItemDeletedDomainEvent domainEvent = _libraryMediaItemDeletedDomainEventFixture.Create(libraryId: libraryId, path: book.Path); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandlerTests.cs index b156d8c5..2a8d4282 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandlerTests.cs @@ -55,6 +55,7 @@ public class LibrarySavedDomainEventHandlerTests public LibrarySavedDomainEventHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockLibraryRepository = Substitute.For(); _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); _mockEnvironmentContext = Substitute.For(); @@ -106,7 +107,7 @@ public class LibrarySavedDomainEventHandlerTests await _sut.HandleAsync(domainEvent, CancellationToken.None); // Assert - Assert.NotNull(domainEvent.Library.CoverImage); + Assert.True(domainEvent.Library.CoverImage.HasValue); await _mockLibraryRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); } @@ -177,7 +178,7 @@ public class LibrarySavedDomainEventHandlerTests await _sut.HandleAsync(domainEvent, CancellationToken.None); // Assert - Assert.Equal("/Media/Libraries/guid/cover.png", domainEvent.Library.CoverImage); + Assert.Equal("/Media/Libraries/guid/cover.png", domainEvent.Library.CoverImage.Value); _mockFileProviderService.DidNotReceive().CopyFile(Arg.Any(), Arg.Any(), Arg.Any()); await _mockLibraryRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandlerTests.cs index 0930c15e..2778b190 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandlerTests.cs @@ -46,6 +46,7 @@ public class LibraryScanCancelledDomainEventHandlerTests public LibraryScanCancelledDomainEventHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockLibraryScanRepository = Substitute.For(); _mockLibraryScanStagingResultsRepository = Substitute.For(); _mockUnitOfWork.LibraryScanRepository.Returns(_mockLibraryScanRepository); @@ -70,7 +71,7 @@ public class LibraryScanCancelledDomainEventHandlerTests LibraryScanEntity scan = _libraryScanEntityFixture.Create( id: domainEvent.ScanId.Value, libraryId: domainEvent.LibraryId.Value); - _mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(scan.Id, cancellationToken: Arg.Any()) .Returns(Result.From(scan)); // Act @@ -89,7 +90,7 @@ public class LibraryScanCancelledDomainEventHandlerTests // Arrange LibraryScanCancelledDomainEvent domainEvent = _libraryScanCancelledDomainEventFixture.Create(); Error error = Error.Failure(description: "Failed to get library scan"); - _mockLibraryScanRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(error); // Act @@ -106,7 +107,7 @@ public class LibraryScanCancelledDomainEventHandlerTests { // Arrange LibraryScanCancelledDomainEvent domainEvent = _libraryScanCancelledDomainEventFixture.Create(); - _mockLibraryScanRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.Success(null)); // Act @@ -126,7 +127,7 @@ public class LibraryScanCancelledDomainEventHandlerTests LibraryScanEntity scan = _libraryScanEntityFixture.Create( id: domainEvent.ScanId.Value, libraryId: domainEvent.LibraryId.Value); - _mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(scan.Id, cancellationToken: Arg.Any()) .Returns(Result.From(scan)); Error error = Error.Failure(description: "Failed to cancel scan"); _mockMediaLibraryScanningService.CancelScan(Arg.Any()).Returns(error); @@ -149,7 +150,7 @@ public class LibraryScanCancelledDomainEventHandlerTests LibraryScanEntity scan = _libraryScanEntityFixture.Create( id: domainEvent.ScanId.Value, libraryId: domainEvent.LibraryId.Value); - _mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(scan.Id, cancellationToken: Arg.Any()) .Returns(Result.From(scan)); Error error = Error.Failure(description: "Failed to clear staging results"); _mockLibraryScanStagingResultsRepository.ClearForScanAsync(Arg.Any(), Arg.Any()) diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandlerTests.cs index 1d6d4e17..d3bc6ab6 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandlerTests.cs @@ -47,6 +47,7 @@ public class LibraryScanFailedDomainEventHandlerTests public LibraryScanFailedDomainEventHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockLibraryScanRepository = Substitute.For(); _mockLibraryScanStagingResultsRepository = Substitute.For(); _mockUnitOfWork.LibraryScanRepository.Returns(_mockLibraryScanRepository); @@ -73,7 +74,7 @@ public class LibraryScanFailedDomainEventHandlerTests LibraryScanEntity scan = _libraryScanEntityFixture.Create( id: compositeId.ScanId.Value, userId: compositeId.UserId.Value); - _mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(scan.Id, cancellationToken: Arg.Any()) .Returns(Result.From(scan)); // Act @@ -98,7 +99,7 @@ public class LibraryScanFailedDomainEventHandlerTests id: compositeId.ScanId.Value, userId: compositeId.UserId.Value, status: LibraryScanJobStatus.Failed); - _mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(scan.Id, cancellationToken: Arg.Any()) .Returns(Result.From(scan)); // Act @@ -119,7 +120,7 @@ public class LibraryScanFailedDomainEventHandlerTests // Arrange LibraryScanFailedDomainEvent domainEvent = _libraryScanFailedDomainEventFixture.Create(); Error error = Error.Failure(description: "Failed to get library scan"); - _mockLibraryScanRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(error); // Act @@ -136,7 +137,7 @@ public class LibraryScanFailedDomainEventHandlerTests { // Arrange LibraryScanFailedDomainEvent domainEvent = _libraryScanFailedDomainEventFixture.Create(); - _mockLibraryScanRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.Success(null)); // Act @@ -157,7 +158,7 @@ public class LibraryScanFailedDomainEventHandlerTests LibraryScanEntity scan = _libraryScanEntityFixture.Create( id: compositeId.ScanId.Value, userId: compositeId.UserId.Value); - _mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(scan.Id, cancellationToken: Arg.Any()) .Returns(Result.From(scan)); Error error = Error.Failure(description: "Failed to update library scan"); _mockLibraryScanRepository.UpdateAsync(Arg.Any(), Arg.Any()) @@ -181,7 +182,7 @@ public class LibraryScanFailedDomainEventHandlerTests LibraryScanEntity scan = _libraryScanEntityFixture.Create( id: compositeId.ScanId.Value, userId: compositeId.UserId.Value); - _mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(scan.Id, cancellationToken: Arg.Any()) .Returns(Result.From(scan)); Error error = Error.Failure(description: "Failed to clear staging results"); _mockLibraryScanStagingResultsRepository.ClearForScanAsync(Arg.Any(), Arg.Any()) diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanFinishedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanFinishedDomainEventHandlerTests.cs index 8b7c7292..317bac60 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanFinishedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanFinishedDomainEventHandlerTests.cs @@ -46,6 +46,7 @@ public class LibraryScanFinishedDomainEventHandlerTests public LibraryScanFinishedDomainEventHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockLibraryScanRepository = Substitute.For(); _mockUnitOfWork.LibraryScanRepository.Returns(_mockLibraryScanRepository); _mockMediaLibrariesScanProgressTracker = Substitute.For(); @@ -68,7 +69,7 @@ public class LibraryScanFinishedDomainEventHandlerTests LibraryScanEntity scan = _libraryScanEntityFixture.Create( id: compositeId.ScanId.Value, userId: compositeId.UserId.Value); - _mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(scan.Id, cancellationToken: Arg.Any()) .Returns(Result.From(scan)); _mockMediaLibrariesScanProgressTracker.UpdateScanProgress(Arg.Any(), compositeId).Returns(Result.Updated); @@ -89,7 +90,7 @@ public class LibraryScanFinishedDomainEventHandlerTests // Arrange LibraryScanFinishedDomainEvent domainEvent = _libraryScanFinishedDomainEventFixture.Create(); Error error = Error.Failure(description: "Failed to get library scan"); - _mockLibraryScanRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(error); // Act @@ -106,7 +107,7 @@ public class LibraryScanFinishedDomainEventHandlerTests { // Arrange LibraryScanFinishedDomainEvent domainEvent = _libraryScanFinishedDomainEventFixture.Create(); - _mockLibraryScanRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.Success(null)); // Act @@ -128,7 +129,7 @@ public class LibraryScanFinishedDomainEventHandlerTests id: compositeId.ScanId.Value, userId: compositeId.UserId.Value, status: LibraryScanJobStatus.Pending); - _mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(scan.Id, cancellationToken: Arg.Any()) .Returns(Result.From(scan)); // Act @@ -150,7 +151,7 @@ public class LibraryScanFinishedDomainEventHandlerTests LibraryScanEntity scan = _libraryScanEntityFixture.Create( id: compositeId.ScanId.Value, userId: compositeId.UserId.Value); - _mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(scan.Id, cancellationToken: Arg.Any()) .Returns(Result.From(scan)); Error error = Error.Failure(description: "Failed to update library scan"); _mockLibraryScanRepository.UpdateAsync(Arg.Any(), Arg.Any()) diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandlerTests.cs index 7a868cf1..409bfbf3 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandlerTests.cs @@ -43,6 +43,7 @@ public class LibraryScanQueuedDomainEventHandlerTests public LibraryScanQueuedDomainEventHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockLibraryScanRepository = Substitute.For(); _mockUnitOfWork.LibraryScanRepository.Returns(_mockLibraryScanRepository); _mockMediaLibraryScanningService = Substitute.For(); @@ -63,7 +64,7 @@ public class LibraryScanQueuedDomainEventHandlerTests LibraryScanEntity scan = _libraryScanEntityFixture.Create( id: domainEvent.ScanId.Value, libraryId: domainEvent.LibraryId.Value); - _mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(scan.Id, cancellationToken: Arg.Any()) .Returns(Result.From(scan)); // Act @@ -82,7 +83,7 @@ public class LibraryScanQueuedDomainEventHandlerTests // Arrange LibraryScanQueuedDomainEvent domainEvent = _libraryScanQueuedDomainEventFixture.Create(); Error error = Error.Failure(description: "Failed to get library scan"); - _mockLibraryScanRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(error); // Act @@ -99,7 +100,7 @@ public class LibraryScanQueuedDomainEventHandlerTests { // Arrange LibraryScanQueuedDomainEvent domainEvent = _libraryScanQueuedDomainEventFixture.Create(); - _mockLibraryScanRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.Success(null)); // Act @@ -119,7 +120,7 @@ public class LibraryScanQueuedDomainEventHandlerTests LibraryScanEntity scan = _libraryScanEntityFixture.Create( id: domainEvent.ScanId.Value, libraryId: domainEvent.LibraryId.Value); - _mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(scan.Id, cancellationToken: Arg.Any()) .Returns(Result.From(scan)); Error error = Error.Failure(description: "Failed to start scan"); _mockMediaLibraryScanningService.StartScanAsync(Arg.Any(), Arg.Any(), Arg.Any()) diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanStartedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanStartedDomainEventHandlerTests.cs index 7fcc2a37..5c5e8d9c 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanStartedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanStartedDomainEventHandlerTests.cs @@ -34,6 +34,7 @@ public class LibraryScanStartedDomainEventHandlerTests public LibraryScanStartedDomainEventHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockLibraryScanRepository = Substitute.For(); _mockUnitOfWork.LibraryScanRepository.Returns(_mockLibraryScanRepository); _mockLibraryScanRepository.UpdateAsync(Arg.Any(), Arg.Any()) diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetEnabledLibraries/GetEnabledLibrariesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetEnabledLibraries/GetEnabledLibrariesQueryHandlerTests.cs index a1ed34ef..4106c121 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetEnabledLibraries/GetEnabledLibrariesQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetEnabledLibraries/GetEnabledLibrariesQueryHandlerTests.cs @@ -41,6 +41,7 @@ public class GetEnabledLibrariesQueryHandlerTests public GetEnabledLibrariesQueryHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockLibraryRepository = Substitute.For(); _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); _mockAuthorizationService = Substitute.For(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetLibraries/GetLibrariesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetLibraries/GetLibrariesQueryHandlerTests.cs index e69ccda4..fc3f6920 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetLibraries/GetLibrariesQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetLibraries/GetLibrariesQueryHandlerTests.cs @@ -2,6 +2,8 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; @@ -41,6 +43,7 @@ public class GetLibrariesQueryHandlerTests public GetLibrariesQueryHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockLibraryRepository = Substitute.For(); _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); _mockAuthorizationService = Substitute.For(); @@ -63,7 +66,7 @@ public class GetLibrariesQueryHandlerTests _libraryEntityFixture.Create(userId: _userId), _libraryEntityFixture.Create(userId: Guid.NewGuid()) ]; - _mockLibraryRepository.GetAllAsync(Arg.Any()).Returns(Result.From>(libraries)); + _mockLibraryRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = libraries, CurrentPage = 1, PerPage = libraries.Count, Count = libraries.Count, NumberOfPages = 1 })); // Act Result result = await _sut.HandleAsync(_getLibrariesQueryFixture.Create(), CancellationToken.None); @@ -85,7 +88,7 @@ public class GetLibrariesQueryHandlerTests _libraryEntityFixture.Create(userId: _userId), _libraryEntityFixture.Create(userId: otherUserId) ]; - _mockLibraryRepository.GetAllAsync(Arg.Any()).Returns(Result.From>(libraries)); + _mockLibraryRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = libraries, CurrentPage = 1, PerPage = libraries.Count, Count = libraries.Count, NumberOfPages = 1 })); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(false); // Act @@ -109,14 +112,14 @@ public class GetLibrariesQueryHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError); - await _mockLibraryRepository.DidNotReceive().GetAllAsync(Arg.Any()); + await _mockLibraryRepository.DidNotReceive().GetAllAsync(cancellationToken: Arg.Any()); } [Fact] public async Task HandleAsync_WhenGetAllFails_ShouldReturnError() { // Arrange - _mockLibraryRepository.GetAllAsync(Arg.Any()) + _mockLibraryRepository.GetAllAsync(cancellationToken: Arg.Any()) .Returns(Error.Failure(description: "Failed to get libraries")); // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQueryHandlerTests.cs index 45bf6b28..e0036c14 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQueryHandlerTests.cs @@ -47,6 +47,7 @@ public class GetLibraryQueryHandlerTests { _mockLibraryRepository = Substitute.For(); _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); _mockAuthorizationService = Substitute.For(); _mockCurrentUserService = Substitute.For(); @@ -57,7 +58,7 @@ public class GetLibraryQueryHandlerTests _mockCurrentUserService.UserId.Returns(_userId); _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) .Returns(true); - _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.From((LibraryEntity?)_libraryEntityFixture.Create(userId: _userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []))); _mockValidator.Validate(Arg.Any()).Returns([]); @@ -110,7 +111,7 @@ public class GetLibraryQueryHandlerTests Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -118,7 +119,7 @@ public class GetLibraryQueryHandlerTests { // Arrange GetLibraryQuery query = _getLibraryQueryFixture.Create(); - _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.Success(null)); // Act @@ -134,7 +135,7 @@ public class GetLibraryQueryHandlerTests { // Arrange GetLibraryQuery query = _getLibraryQueryFixture.Create(); - _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Errors.Library.LibraryNotFound); // Act @@ -159,6 +160,6 @@ public class GetLibraryQueryHandlerTests Assert.True(result.IsFailure); Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError); await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQueryHandlerTests.cs index f9a061fc..986e8dde 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQueryHandlerTests.cs @@ -53,6 +53,7 @@ public class GetLibraryScanProgressQueryHandlerTests public GetLibraryScanProgressQueryHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockLibraryRepository = Substitute.For(); _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); _mockAuthorizationService = Substitute.For(); @@ -82,7 +83,7 @@ public class GetLibraryScanProgressQueryHandlerTests // Arrange GetLibraryScanProgressQuery query = _getLibraryScanProgressQueryFixture.Create(); LibraryEntity library = _libraryEntityFixture.Create(id: query.LibraryId, userId: _userId); - _mockLibraryRepository.GetByIdAsync(query.LibraryId, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(query.LibraryId, cancellationToken: Arg.Any()) .Returns(Result.From(library)); // Act @@ -100,7 +101,7 @@ public class GetLibraryScanProgressQueryHandlerTests { // Arrange GetLibraryScanProgressQuery query = _getLibraryScanProgressQueryFixture.Create(); - _mockLibraryRepository.GetByIdAsync(query.LibraryId, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(query.LibraryId, cancellationToken: Arg.Any()) .Returns(Result.Success(null)); // Act @@ -117,7 +118,7 @@ public class GetLibraryScanProgressQueryHandlerTests { // Arrange GetLibraryScanProgressQuery query = _getLibraryScanProgressQueryFixture.Create(); - _mockLibraryRepository.GetByIdAsync(query.LibraryId, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(query.LibraryId, cancellationToken: Arg.Any()) .Returns(Error.Failure(description: "Failed to get library")); // Act @@ -134,7 +135,7 @@ public class GetLibraryScanProgressQueryHandlerTests // Arrange GetLibraryScanProgressQuery query = _getLibraryScanProgressQueryFixture.Create(); LibraryEntity library = _libraryEntityFixture.Create(id: query.LibraryId, userId: _userId); - _mockLibraryRepository.GetByIdAsync(query.LibraryId, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(query.LibraryId, cancellationToken: Arg.Any()) .Returns(Result.From(library)); _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) .Returns(false); @@ -161,7 +162,7 @@ public class GetLibraryScanProgressQueryHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -170,7 +171,7 @@ public class GetLibraryScanProgressQueryHandlerTests // Arrange GetLibraryScanProgressQuery query = _getLibraryScanProgressQueryFixture.Create(); LibraryEntity library = _libraryEntityFixture.Create(id: query.LibraryId, userId: _userId); - _mockLibraryRepository.GetByIdAsync(query.LibraryId, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(query.LibraryId, cancellationToken: Arg.Any()) .Returns(Result.From(library)); _mockMediaLibrariesScanProgressTracker.GetScanProgress(Arg.Any()) .Returns(Error.Failure(description: "Failed to get scan progress")); @@ -195,7 +196,7 @@ public class GetLibraryScanProgressQueryHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(DomainErrors.Library.LibraryIdCannotBeEmpty, result.FirstError); - await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); _mockMediaLibrariesScanProgressTracker.DidNotReceive().GetScanProgress(Arg.Any()); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQueryHandlerTests.cs index fea2650e..dd128719 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQueryHandlerTests.cs @@ -50,6 +50,7 @@ public class GetRunningLibraryScansQueryHandlerTests public GetRunningLibraryScansQueryHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockLibraryScanRepository = Substitute.For(); _mockUnitOfWork.LibraryScanRepository.Returns(_mockLibraryScanRepository); _mockAuthorizationService = Substitute.For(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandHandlerTests.cs index b733d3e8..032fc332 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandHandlerTests.cs @@ -44,6 +44,7 @@ public class ReorderLibraryArtworkProvidersCommandHandlerTests public ReorderLibraryArtworkProvidersCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockConfigurationRepository = Substitute.For(); _mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockConfigurationRepository); _mockAuthorizationService = Substitute.For(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandlerTests.cs index a26e0808..c21aa390 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandlerTests.cs @@ -44,6 +44,7 @@ public class ReorderLibraryMetadataProvidersCommandHandlerTests public ReorderLibraryMetadataProvidersCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockConfigurationRepository = Substitute.For(); _mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockConfigurationRepository); _mockAuthorizationService = Substitute.For(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandHandlerTests.cs index 8d6e2260..246bf924 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandHandlerTests.cs @@ -48,6 +48,7 @@ public class SetLibraryArtworkProviderEnabledCommandHandlerTests public SetLibraryArtworkProviderEnabledCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockConfigurationRepository = Substitute.For(); _mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockConfigurationRepository); _mockAuthorizationService = Substitute.For(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandlerTests.cs index 2fa3c5a7..d53f845c 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandlerTests.cs @@ -48,6 +48,7 @@ public class SetLibraryMetadataProviderEnabledCommandHandlerTests public SetLibraryMetadataProviderEnabledCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockConfigurationRepository = Substitute.For(); _mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockConfigurationRepository); _mockAuthorizationService = Substitute.For(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandlerTests.cs index d2b3ee7e..3dce9d21 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandlerTests.cs @@ -34,6 +34,7 @@ public class UpdatePluginSettingsCommandHandlerTests public UpdatePluginSettingsCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockPluginRepository = Substitute.For(); _mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository); _mockValidator = Substitute.For>(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryHandlerTests.cs index 052052ba..6b90b6d9 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryHandlerTests.cs @@ -2,6 +2,8 @@ using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; @@ -47,6 +49,7 @@ public class GetLibraryArtworkProvidersQueryHandlerTests public GetLibraryArtworkProvidersQueryHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockArtworkProviderConfigurationRepository = Substitute.For(); _mockPluginRepository = Substitute.For(); _mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockArtworkProviderConfigurationRepository); @@ -100,7 +103,8 @@ public class GetLibraryArtworkProvidersQueryHandlerTests _pluginEntityFixture.Create(firstPluginId), _pluginEntityFixture.Create(secondPluginId) ]; - _mockPluginRepository.GetAllAsync(Arg.Any()).Returns(plugins); + _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = plugins, CurrentPage = 1, PerPage = plugins.Count, Count = plugins.Count, NumberOfPages = 1 })); // Act Result> result = await _sut.HandleAsync(query, CancellationToken.None); @@ -127,8 +131,8 @@ public class GetLibraryArtworkProvidersQueryHandlerTests ]; _mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any()) .Returns(Result.From>(configurations)); - _mockPluginRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From>([_pluginEntityFixture.Create()])); + _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [_pluginEntityFixture.Create()], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 })); // Act Result> result = await _sut.HandleAsync(query, CancellationToken.None); @@ -147,8 +151,8 @@ public class GetLibraryArtworkProvidersQueryHandlerTests GetLibraryArtworkProvidersQuery query = _getLibraryArtworkProvidersQueryFixture.Create(); _mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any()) .Returns(Result.From>([])); - _mockPluginRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From>([])); + _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); // Act Result> result = await _sut.HandleAsync(query, CancellationToken.None); @@ -172,7 +176,7 @@ public class GetLibraryArtworkProvidersQueryHandlerTests // Assert Assert.True(result.IsFailure); - await _mockPluginRepository.DidNotReceive().GetAllAsync(Arg.Any()); + await _mockPluginRepository.DidNotReceive().GetAllAsync(cancellationToken: Arg.Any()); } [Fact] @@ -182,7 +186,7 @@ public class GetLibraryArtworkProvidersQueryHandlerTests GetLibraryArtworkProvidersQuery query = _getLibraryArtworkProvidersQueryFixture.Create(); _mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any()) .Returns(Result.From>([])); - _mockPluginRepository.GetAllAsync(Arg.Any()) + _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) .Returns(Error.Failure(description: "Failed to get plugins")); // Act @@ -209,7 +213,7 @@ public class GetLibraryArtworkProvidersQueryHandlerTests await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( _userId, Arg.Is(context => context.LibraryId == query.LibraryId), Arg.Any()); await _mockArtworkProviderConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); - await _mockPluginRepository.DidNotReceive().GetAllAsync(Arg.Any()); + await _mockPluginRepository.DidNotReceive().GetAllAsync(cancellationToken: Arg.Any()); } [Fact] diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandlerTests.cs index 16e3965f..6c456d79 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandlerTests.cs @@ -2,6 +2,8 @@ using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; @@ -48,6 +50,7 @@ public class GetLibraryMetadataProvidersQueryHandlerTests public GetLibraryMetadataProvidersQueryHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockPluginRepository = Substitute.For(); _mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository); _mockAuthorizationService = Substitute.For(); @@ -100,7 +103,8 @@ public class GetLibraryMetadataProvidersQueryHandlerTests _pluginEntityFixture.Create(firstPluginId), _pluginEntityFixture.Create(secondPluginId) ]; - _mockPluginRepository.GetAllAsync(Arg.Any()).Returns(plugins); + _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = plugins, CurrentPage = 1, PerPage = plugins.Count, Count = plugins.Count, NumberOfPages = 1 })); // Act Result> result = await _sut.HandleAsync(query, CancellationToken.None); @@ -127,8 +131,8 @@ public class GetLibraryMetadataProvidersQueryHandlerTests ]; _mockProviderConfigurationStore.GetConfigurationsAsync(query.LibraryId, Arg.Any()) .Returns(Result.From>(configurations)); - _mockPluginRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From>([_pluginEntityFixture.Create()])); + _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [_pluginEntityFixture.Create()], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 })); // Act Result> result = await _sut.HandleAsync(query, CancellationToken.None); @@ -147,8 +151,8 @@ public class GetLibraryMetadataProvidersQueryHandlerTests GetLibraryMetadataProvidersQuery query = _getLibraryMetadataProvidersQueryFixture.Create(); _mockProviderConfigurationStore.GetConfigurationsAsync(query.LibraryId, Arg.Any()) .Returns(Result.From>([])); - _mockPluginRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From>([])); + _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); // Act Result> result = await _sut.HandleAsync(query, CancellationToken.None); @@ -172,7 +176,7 @@ public class GetLibraryMetadataProvidersQueryHandlerTests // Assert Assert.True(result.IsFailure); - await _mockPluginRepository.DidNotReceive().GetAllAsync(Arg.Any()); + await _mockPluginRepository.DidNotReceive().GetAllAsync(cancellationToken: Arg.Any()); } [Fact] @@ -182,7 +186,7 @@ public class GetLibraryMetadataProvidersQueryHandlerTests GetLibraryMetadataProvidersQuery query = _getLibraryMetadataProvidersQueryFixture.Create(); _mockProviderConfigurationStore.GetConfigurationsAsync(query.LibraryId, Arg.Any()) .Returns(Result.From>([])); - _mockPluginRepository.GetAllAsync(Arg.Any()) + _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) .Returns(Error.Failure(description: "Failed to get plugins")); // Act @@ -209,7 +213,7 @@ public class GetLibraryMetadataProvidersQueryHandlerTests await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( _userId, Arg.Is(context => context.LibraryId == query.LibraryId), Arg.Any()); await _mockProviderConfigurationStore.DidNotReceive().GetConfigurationsAsync(Arg.Any(), Arg.Any()); - await _mockPluginRepository.DidNotReceive().GetAllAsync(Arg.Any()); + await _mockPluginRepository.DidNotReceive().GetAllAsync(cancellationToken: Arg.Any()); } [Fact] diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandlerTests.cs index db3a2b55..835bf264 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandlerTests.cs @@ -45,6 +45,7 @@ public class GetPluginSettingsQueryHandlerTests public GetPluginSettingsQueryHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockPluginRepository = Substitute.For(); _mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository); _mockPluginManager = Substitute.For(); @@ -67,7 +68,7 @@ public class GetPluginSettingsQueryHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(DomainErrors.Plugins.PluginIdCannotBeEmpty, result.FirstError); - await _mockPluginRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockPluginRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -76,7 +77,7 @@ public class GetPluginSettingsQueryHandlerTests // Arrange GetPluginSettingsQuery query = _getPluginSettingsQueryFixture.Create(); PluginEntity plugin = _pluginEntityFixture.Create(query.PluginId); - _mockPluginRepository.GetByIdAsync(query.PluginId, Arg.Any()) + _mockPluginRepository.GetByIdAsync(query.PluginId, cancellationToken: Arg.Any()) .Returns(Result.From(plugin)); IPlugin loadedPlugin = Substitute.For(); @@ -107,7 +108,7 @@ public class GetPluginSettingsQueryHandlerTests // Arrange GetPluginSettingsQuery query = _getPluginSettingsQueryFixture.Create(); PluginEntity plugin = _pluginEntityFixture.Create(query.PluginId); - _mockPluginRepository.GetByIdAsync(query.PluginId, Arg.Any()) + _mockPluginRepository.GetByIdAsync(query.PluginId, cancellationToken: Arg.Any()) .Returns(Result.From(plugin)); _mockPluginManager.GetPlugin(query.PluginId).Returns((IPlugin?)null); @@ -125,7 +126,7 @@ public class GetPluginSettingsQueryHandlerTests { // Arrange GetPluginSettingsQuery query = _getPluginSettingsQueryFixture.Create(); - _mockPluginRepository.GetByIdAsync(query.PluginId, Arg.Any()) + _mockPluginRepository.GetByIdAsync(query.PluginId, cancellationToken: Arg.Any()) .Returns(Result.Success(null)); // Act @@ -143,7 +144,7 @@ public class GetPluginSettingsQueryHandlerTests // Arrange GetPluginSettingsQuery query = _getPluginSettingsQueryFixture.Create(); Error error = Error.Failure(description: "Failed to get plugin"); - _mockPluginRepository.GetByIdAsync(query.PluginId, Arg.Any()) + _mockPluginRepository.GetByIdAsync(query.PluginId, cancellationToken: Arg.Any()) .Returns(error); // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandlerTests.cs index 45bd8263..e1387496 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandlerTests.cs @@ -2,6 +2,8 @@ using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Core.Plugins.Queries.GetPlugins; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; using Lumina.Application.Fixtures.Core.Plugins.Queries.GetPlugins; @@ -34,6 +36,7 @@ public class GetPluginsQueryHandlerTests public GetPluginsQueryHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockPluginRepository = Substitute.For(); _mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository); _sut = new GetPluginsQueryHandler(_mockUnitOfWork); @@ -44,7 +47,8 @@ public class GetPluginsQueryHandlerTests { // Arrange List plugins = [_pluginEntityFixture.Create(), _pluginEntityFixture.Create()]; - _mockPluginRepository.GetAllAsync(Arg.Any()).Returns(plugins); + _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = plugins, CurrentPage = 1, PerPage = plugins.Count, Count = plugins.Count, NumberOfPages = 1 })); // Act Result> result = await _sut.HandleAsync(_getPluginsQueryFixture.Create(), CancellationToken.None); @@ -60,7 +64,7 @@ public class GetPluginsQueryHandlerTests public async Task HandleAsync_WhenRepositoryReturnsError_ShouldReturnError() { // Arrange - _mockPluginRepository.GetAllAsync(Arg.Any()) + _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) .Returns(Error.Failure(description: "Failed to get plugins")); // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandHandlerTests.cs index 1ba576bb..3c2ce017 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandHandlerTests.cs @@ -49,6 +49,7 @@ public class AddScheduledJobCommandHandlerTests public AddScheduledJobCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockCurrentUserService = Substitute.For(); _mockAuthorizationService = Substitute.For(); _mockDomainEventsQueue = Substitute.For(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/FireScheduledJob/FireScheduledJobCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/FireScheduledJob/FireScheduledJobCommandHandlerTests.cs index 14effc81..3ca228e1 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/FireScheduledJob/FireScheduledJobCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/FireScheduledJob/FireScheduledJobCommandHandlerTests.cs @@ -48,6 +48,7 @@ public class FireScheduledJobCommandHandlerTests public FireScheduledJobCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockCurrentUserService = Substitute.For(); _mockAuthorizationService = Substitute.For(); _mockDomainEventsQueue = Substitute.For(); @@ -72,7 +73,7 @@ public class FireScheduledJobCommandHandlerTests id: command.ScheduledJobId, scheduleType: ScheduleType.WithIntervalInMinutes, status: ScheduledJobStatus.Active); - _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any()) .Returns(Result.From(scheduledJob)); // Act @@ -98,7 +99,7 @@ public class FireScheduledJobCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError); - await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); _mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any()); } @@ -115,7 +116,7 @@ public class FireScheduledJobCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -131,7 +132,7 @@ public class FireScheduledJobCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -140,7 +141,7 @@ public class FireScheduledJobCommandHandlerTests // Arrange FireScheduledJobCommand command = _fireScheduledJobCommandFixture.Create(); Error error = Error.Failure("Database.Error", "Failed to get the scheduled job"); - _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()).Returns(error); + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any()).Returns(error); // Act Result result = await _sut.HandleAsync(command, CancellationToken.None); @@ -156,7 +157,7 @@ public class FireScheduledJobCommandHandlerTests { // Arrange FireScheduledJobCommand command = _fireScheduledJobCommandFixture.Create(); - _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any()) .Returns(Result.From(null)); // Act @@ -179,7 +180,7 @@ public class FireScheduledJobCommandHandlerTests scheduleType: ScheduleType.DailyAtHourAndMinute, hour: 99, minute: 0); - _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any()) .Returns(Result.From(scheduledJob)); // Act @@ -199,7 +200,7 @@ public class FireScheduledJobCommandHandlerTests id: command.ScheduledJobId, scheduleType: ScheduleType.WithIntervalInMinutes, status: ScheduledJobStatus.Running); - _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any()) .Returns(Result.From(scheduledJob)); // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommandHandlerTests.cs index 93a48823..1f702fa3 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommandHandlerTests.cs @@ -51,6 +51,7 @@ public class RemoveScheduledJobCommandHandlerTests public RemoveScheduledJobCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockCurrentUserService = Substitute.For(); _mockAuthorizationService = Substitute.For(); _mockDomainEventsQueue = Substitute.For(); @@ -78,7 +79,7 @@ public class RemoveScheduledJobCommandHandlerTests id: command.ScheduledJobId, scheduleType: ScheduleType.WithIntervalInMinutes, status: ScheduledJobStatus.Active); - _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any()) .Returns(Result.From(scheduledJob)); _mockScheduledJobExecutionRepository.DeleteByScheduledJobIdAsync(command.ScheduledJobId, Arg.Any()) .Returns(Result.Success); @@ -113,7 +114,7 @@ public class RemoveScheduledJobCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError); - await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); await _mockScheduledJobRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); } @@ -130,7 +131,7 @@ public class RemoveScheduledJobCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -146,7 +147,7 @@ public class RemoveScheduledJobCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -154,7 +155,7 @@ public class RemoveScheduledJobCommandHandlerTests { // Arrange RemoveScheduledJobCommand command = _removeScheduledJobCommandFixture.Create(); - _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any()) .Returns(Result.From(null)); // Act @@ -175,7 +176,7 @@ public class RemoveScheduledJobCommandHandlerTests id: command.ScheduledJobId, scheduleType: ScheduleType.WithIntervalInMinutes, status: ScheduledJobStatus.Active); - _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any()) .Returns(Result.From(scheduledJob)); Error error = Error.Failure("Database.Error", "Failed to delete the executions"); _mockScheduledJobExecutionRepository.DeleteByScheduledJobIdAsync(command.ScheduledJobId, Arg.Any()) @@ -200,7 +201,7 @@ public class RemoveScheduledJobCommandHandlerTests id: command.ScheduledJobId, scheduleType: ScheduleType.WithIntervalInMinutes, status: ScheduledJobStatus.Active); - _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any()) .Returns(Result.From(scheduledJob)); _mockScheduledJobExecutionRepository.DeleteByScheduledJobIdAsync(command.ScheduledJobId, Arg.Any()) .Returns(Result.Success); @@ -223,7 +224,7 @@ public class RemoveScheduledJobCommandHandlerTests // Arrange RemoveScheduledJobCommand command = _removeScheduledJobCommandFixture.Create(); Error repositoryError = DomainErrors.Scheduling.ScheduledJobNotFound; - _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any()) .Returns(repositoryError); // Act @@ -247,7 +248,7 @@ public class RemoveScheduledJobCommandHandlerTests scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 0, status: ScheduledJobStatus.Active); - _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any()) .Returns(Result.From(invalidScheduledJob)); // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommandHandlerTests.cs index 453cc88f..538c9dbb 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommandHandlerTests.cs @@ -48,6 +48,7 @@ public class StartScheduledJobCommandHandlerTests public StartScheduledJobCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockCurrentUserService = Substitute.For(); _mockAuthorizationService = Substitute.For(); _mockDomainEventsQueue = Substitute.For(); @@ -72,7 +73,7 @@ public class StartScheduledJobCommandHandlerTests id: command.ScheduledJobId, scheduleType: ScheduleType.WithIntervalInMinutes, status: ScheduledJobStatus.Added); - _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any()) .Returns(Result.From(scheduledJob)); _mockScheduledJobRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.Updated); @@ -102,7 +103,7 @@ public class StartScheduledJobCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError); - await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -119,7 +120,7 @@ public class StartScheduledJobCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -135,7 +136,7 @@ public class StartScheduledJobCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -143,7 +144,7 @@ public class StartScheduledJobCommandHandlerTests { // Arrange StartScheduledJobCommand command = _startScheduledJobCommandFixture.Create(); - _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any()) .Returns(Result.From(null)); // Act @@ -164,7 +165,7 @@ public class StartScheduledJobCommandHandlerTests id: command.ScheduledJobId, scheduleType: ScheduleType.WithIntervalInMinutes, status: ScheduledJobStatus.Active); - _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any()) .Returns(Result.From(scheduledJob)); // Act @@ -186,7 +187,7 @@ public class StartScheduledJobCommandHandlerTests id: command.ScheduledJobId, scheduleType: ScheduleType.WithIntervalInMinutes, status: ScheduledJobStatus.Added); - _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any()) .Returns(Result.From(scheduledJob)); _mockScheduledJobRepository.UpdateAsync(Arg.Any(), Arg.Any()) .Returns(DomainErrors.Scheduling.ScheduledJobNotFound); @@ -207,7 +208,7 @@ public class StartScheduledJobCommandHandlerTests // Arrange StartScheduledJobCommand command = _startScheduledJobCommandFixture.Create(); Error repositoryError = DomainErrors.Scheduling.ScheduledJobNotFound; - _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any()) .Returns(repositoryError); // Act @@ -230,7 +231,7 @@ public class StartScheduledJobCommandHandlerTests scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 0, status: ScheduledJobStatus.Added); - _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any()) .Returns(Result.From(invalidScheduledJob)); // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommandHandlerTests.cs index 7c1d40e1..0ea40450 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommandHandlerTests.cs @@ -50,6 +50,7 @@ public class StopScheduledJobCommandHandlerTests public StopScheduledJobCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockCurrentUserService = Substitute.For(); _mockAuthorizationService = Substitute.For(); _mockDomainEventsQueue = Substitute.For(); @@ -75,7 +76,7 @@ public class StopScheduledJobCommandHandlerTests id: command.ScheduledJobId, scheduleType: ScheduleType.WithIntervalInMinutes, status: ScheduledJobStatus.Active); - _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any()) .Returns(Result.From(scheduledJob)); _mockScheduledJobRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.Updated); @@ -105,7 +106,7 @@ public class StopScheduledJobCommandHandlerTests scheduleType: ScheduleType.WithIntervalInMinutes, status: ScheduledJobStatus.Running, lastStartedOnUtc: DateTime.UtcNow.AddMinutes(-10)); - _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any()) .Returns(Result.From(scheduledJob)); _mockScheduledJobRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.Updated); @@ -132,7 +133,7 @@ public class StopScheduledJobCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError); - await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); await _mockScheduledJobScheduler.DidNotReceive().StopCycleAsync(Arg.Any(), Arg.Any()); } @@ -149,7 +150,7 @@ public class StopScheduledJobCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -165,7 +166,7 @@ public class StopScheduledJobCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -173,7 +174,7 @@ public class StopScheduledJobCommandHandlerTests { // Arrange StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create(); - _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any()) .Returns(Result.From(null)); // Act @@ -194,7 +195,7 @@ public class StopScheduledJobCommandHandlerTests id: command.ScheduledJobId, scheduleType: ScheduleType.WithIntervalInMinutes, status: ScheduledJobStatus.Added); - _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any()) .Returns(Result.From(scheduledJob)); // Act @@ -216,7 +217,7 @@ public class StopScheduledJobCommandHandlerTests id: command.ScheduledJobId, scheduleType: ScheduleType.WithIntervalInMinutes, status: ScheduledJobStatus.Active); - _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any()) .Returns(Result.From(scheduledJob)); _mockScheduledJobRepository.UpdateAsync(Arg.Any(), Arg.Any()) .Returns(DomainErrors.Scheduling.ScheduledJobNotFound); @@ -237,7 +238,7 @@ public class StopScheduledJobCommandHandlerTests // Arrange StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create(); Error repositoryError = DomainErrors.Scheduling.ScheduledJobNotFound; - _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any()) .Returns(repositoryError); // Act @@ -260,7 +261,7 @@ public class StopScheduledJobCommandHandlerTests scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 0, status: ScheduledJobStatus.Active); - _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any()) .Returns(Result.From(invalidScheduledJob)); // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesCommandHandlerTests.cs index 56b302ff..3e579bc9 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesCommandHandlerTests.cs @@ -41,6 +41,7 @@ public class UpdateSchedulerDisplayPreferencesCommandHandlerTests public UpdateSchedulerDisplayPreferencesCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockCurrentUserService = Substitute.For(); _mockAuthorizationService = Substitute.For(); _mockSchedulerDisplayPreferencesRepository = Substitute.For(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobAddedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobAddedDomainEventHandlerTests.cs index a26df0e4..bcb83c98 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobAddedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobAddedDomainEventHandlerTests.cs @@ -2,6 +2,8 @@ using Lumina.Application.Common.DataAccess.Entities.Scheduling; using Lumina.Application.Common.DataAccess.Repositories.Scheduling; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Core.Scheduling.Events; using Lumina.Application.Core.Scheduling.Notifications; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling; @@ -40,11 +42,12 @@ public class ScheduledJobAddedDomainEventHandlerTests public ScheduledJobAddedDomainEventHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockScheduledJobNotifier = Substitute.For(); _mockScheduledJobRepository = Substitute.For(); _mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository); - _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([])); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); _sut = new ScheduledJobAddedDomainEventHandler(_mockScheduledJobNotifier, _mockUnitOfWork); } @@ -56,7 +59,7 @@ public class ScheduledJobAddedDomainEventHandlerTests ScheduledJobAddedDomainEvent domainEvent = _scheduledJobAddedDomainEventFixture.Create(); ScheduledJobEntity scheduledJob1 = _scheduledJobEntityFixture.Create(name: "Job 1"); ScheduledJobEntity scheduledJob2 = _scheduledJobEntityFixture.Create(name: "Job 2"); - _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([scheduledJob1, scheduledJob2])); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [scheduledJob1, scheduledJob2], CurrentPage = 1, PerPage = 2, Count = 2, NumberOfPages = 1 })); // Act await _sut.HandleAsync(domainEvent, CancellationToken.None); @@ -73,7 +76,7 @@ public class ScheduledJobAddedDomainEventHandlerTests // Arrange ScheduledJobAddedDomainEvent domainEvent = _scheduledJobAddedDomainEventFixture.Create(); Error error = Error.Failure("Database.Error", "Failed to get the scheduled jobs"); - _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(error); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(error); // Act EventualConsistencyException exception = await Assert.ThrowsAsync( diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobCycleStartedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobCycleStartedDomainEventHandlerTests.cs index 1a19fd47..247f2aaa 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobCycleStartedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobCycleStartedDomainEventHandlerTests.cs @@ -2,6 +2,8 @@ using Lumina.Application.Common.DataAccess.Entities.Scheduling; using Lumina.Application.Common.DataAccess.Repositories.Scheduling; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Infrastructure.Scheduling; using Lumina.Application.Core.Scheduling.Events; using Lumina.Application.Core.Scheduling.Notifications; @@ -39,12 +41,13 @@ public class ScheduledJobCycleStartedDomainEventHandlerTests public ScheduledJobCycleStartedDomainEventHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockScheduledJobNotifier = Substitute.For(); _mockScheduledJobScheduler = Substitute.For(); _mockScheduledJobRepository = Substitute.For(); _mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository); - _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([])); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); _sut = new ScheduledJobCycleStartedDomainEventHandler(_mockScheduledJobNotifier, _mockScheduledJobScheduler, _mockUnitOfWork); } @@ -69,7 +72,7 @@ public class ScheduledJobCycleStartedDomainEventHandlerTests // Arrange ScheduledJobCycleStartedDomainEvent domainEvent = _scheduledJobCycleStartedDomainEventFixture.Create(); Error error = Error.Failure("Database.Error", "Failed to get the scheduled jobs"); - _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(error); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(error); // Act EventualConsistencyException exception = await Assert.ThrowsAsync( diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobCycleStoppedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobCycleStoppedDomainEventHandlerTests.cs index 2de58f22..79a52e25 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobCycleStoppedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobCycleStoppedDomainEventHandlerTests.cs @@ -2,6 +2,8 @@ using Lumina.Application.Common.DataAccess.Entities.Scheduling; using Lumina.Application.Common.DataAccess.Repositories.Scheduling; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Core.Scheduling.Events; using Lumina.Application.Core.Scheduling.Notifications; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling; @@ -39,11 +41,12 @@ public class ScheduledJobCycleStoppedDomainEventHandlerTests public ScheduledJobCycleStoppedDomainEventHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockScheduledJobNotifier = Substitute.For(); _mockScheduledJobRepository = Substitute.For(); _mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository); - _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([])); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); _sut = new ScheduledJobCycleStoppedDomainEventHandler(_mockScheduledJobNotifier, _mockUnitOfWork); } @@ -54,7 +57,7 @@ public class ScheduledJobCycleStoppedDomainEventHandlerTests // Arrange ScheduledJobCycleStoppedDomainEvent domainEvent = _scheduledJobCycleStoppedDomainEventFixture.Create(); ScheduledJobEntity stoppedJob = _scheduledJobEntityFixture.Create(name: "Stopped job", status: Lumina.Domain.SharedKernel.Common.Enums.Scheduling.ScheduledJobStatus.Added); - _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([stoppedJob])); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [stoppedJob], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 })); // Act await _sut.HandleAsync(domainEvent, CancellationToken.None); @@ -71,7 +74,7 @@ public class ScheduledJobCycleStoppedDomainEventHandlerTests // Arrange ScheduledJobCycleStoppedDomainEvent domainEvent = _scheduledJobCycleStoppedDomainEventFixture.Create(); Error error = Error.Failure("Database.Error", "Failed to get the scheduled jobs"); - _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(error); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(error); // Act EventualConsistencyException exception = await Assert.ThrowsAsync( diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobExecutionCompletedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobExecutionCompletedDomainEventHandlerTests.cs index 9f0ef999..58f87229 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobExecutionCompletedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobExecutionCompletedDomainEventHandlerTests.cs @@ -2,6 +2,8 @@ using Lumina.Application.Common.DataAccess.Entities.Scheduling; using Lumina.Application.Common.DataAccess.Repositories.Scheduling; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Core.Scheduling.Events; using Lumina.Application.Core.Scheduling.Notifications; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling; @@ -43,6 +45,7 @@ public class ScheduledJobExecutionCompletedDomainEventHandlerTests public ScheduledJobExecutionCompletedDomainEventHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockScheduledJobNotifier = Substitute.For(); _mockScheduledJobRepository = Substitute.For(); _mockScheduledJobExecutionRepository = Substitute.For(); @@ -51,7 +54,7 @@ public class ScheduledJobExecutionCompletedDomainEventHandlerTests _mockUnitOfWork.ScheduledJobExecutionRepository.Returns(_mockScheduledJobExecutionRepository); _mockScheduledJobRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.Updated); _mockScheduledJobExecutionRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.Updated); - _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([])); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); _sut = new ScheduledJobExecutionCompletedDomainEventHandler(_mockScheduledJobNotifier, _mockUnitOfWork); } @@ -68,14 +71,14 @@ public class ScheduledJobExecutionCompletedDomainEventHandlerTests id: domainEvent.ScheduledJobId.Value, status: ScheduledJobStatus.Running, lastStartedOnUtc: completedOnUtc.AddMinutes(-5)); - _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(scheduledJob)); ScheduledJobExecutionEntity execution = _scheduledJobExecutionEntityFixture.Create( id: domainEvent.RunId, scheduledJobId: scheduledJob.Id, isCycleRun: isCycleRun, completedOnUtc: null); - _mockScheduledJobExecutionRepository.GetByIdAsync(domainEvent.RunId, Arg.Any()) + _mockScheduledJobExecutionRepository.GetByIdAsync(domainEvent.RunId, cancellationToken: Arg.Any()) .Returns(Result.From(execution)); // Act @@ -100,7 +103,7 @@ public class ScheduledJobExecutionCompletedDomainEventHandlerTests { // Arrange ScheduledJobExecutionCompletedDomainEvent domainEvent = _scheduledJobExecutionCompletedDomainEventFixture.Create(isCycleRun: true); - _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(null)); // Act @@ -109,7 +112,7 @@ public class ScheduledJobExecutionCompletedDomainEventHandlerTests // Assert Assert.Equal(Errors.Scheduling.ScheduledJobNotFound, exception.EventualConsistencyError); - await _mockScheduledJobExecutionRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockScheduledJobExecutionRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -118,7 +121,7 @@ public class ScheduledJobExecutionCompletedDomainEventHandlerTests // Arrange ScheduledJobExecutionCompletedDomainEvent domainEvent = _scheduledJobExecutionCompletedDomainEventFixture.Create(isCycleRun: true); ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(id: domainEvent.ScheduledJobId.Value, status: ScheduledJobStatus.Running); - _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(scheduledJob)); Error error = Error.Failure("Database.Error", "Failed to update the scheduled job"); _mockScheduledJobRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(error); @@ -129,7 +132,7 @@ public class ScheduledJobExecutionCompletedDomainEventHandlerTests // Assert Assert.Equal(error, exception.EventualConsistencyError); - await _mockScheduledJobExecutionRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockScheduledJobExecutionRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -138,9 +141,9 @@ public class ScheduledJobExecutionCompletedDomainEventHandlerTests // Arrange ScheduledJobExecutionCompletedDomainEvent domainEvent = _scheduledJobExecutionCompletedDomainEventFixture.Create(isCycleRun: true); ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(id: domainEvent.ScheduledJobId.Value, status: ScheduledJobStatus.Running); - _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(scheduledJob)); - _mockScheduledJobExecutionRepository.GetByIdAsync(domainEvent.RunId, Arg.Any()) + _mockScheduledJobExecutionRepository.GetByIdAsync(domainEvent.RunId, cancellationToken: Arg.Any()) .Returns(Result.From(null)); // Act @@ -158,10 +161,10 @@ public class ScheduledJobExecutionCompletedDomainEventHandlerTests // Arrange ScheduledJobExecutionCompletedDomainEvent domainEvent = _scheduledJobExecutionCompletedDomainEventFixture.Create(isCycleRun: true); ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(id: domainEvent.ScheduledJobId.Value, status: ScheduledJobStatus.Running); - _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(scheduledJob)); ScheduledJobExecutionEntity execution = _scheduledJobExecutionEntityFixture.Create(id: domainEvent.RunId); - _mockScheduledJobExecutionRepository.GetByIdAsync(domainEvent.RunId, Arg.Any()) + _mockScheduledJobExecutionRepository.GetByIdAsync(domainEvent.RunId, cancellationToken: Arg.Any()) .Returns(Result.From(execution)); Error error = Error.Failure("Database.Error", "Failed to update the execution"); _mockScheduledJobExecutionRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(error); @@ -181,13 +184,13 @@ public class ScheduledJobExecutionCompletedDomainEventHandlerTests // Arrange ScheduledJobExecutionCompletedDomainEvent domainEvent = _scheduledJobExecutionCompletedDomainEventFixture.Create(isCycleRun: true); ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(id: domainEvent.ScheduledJobId.Value, status: ScheduledJobStatus.Running); - _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(scheduledJob)); ScheduledJobExecutionEntity execution = _scheduledJobExecutionEntityFixture.Create(id: domainEvent.RunId); - _mockScheduledJobExecutionRepository.GetByIdAsync(domainEvent.RunId, Arg.Any()) + _mockScheduledJobExecutionRepository.GetByIdAsync(domainEvent.RunId, cancellationToken: Arg.Any()) .Returns(Result.From(execution)); Error error = Error.Failure("Database.Error", "Failed to get the scheduled jobs"); - _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(error); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(error); // Act EventualConsistencyException exception = await Assert.ThrowsAsync( diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobExecutionStartedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobExecutionStartedDomainEventHandlerTests.cs index 8613b765..7c453083 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobExecutionStartedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobExecutionStartedDomainEventHandlerTests.cs @@ -2,6 +2,8 @@ using Lumina.Application.Common.DataAccess.Entities.Scheduling; using Lumina.Application.Common.DataAccess.Repositories.Scheduling; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Core.Scheduling.Events; using Lumina.Application.Core.Scheduling.Notifications; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling; @@ -44,6 +46,7 @@ public class ScheduledJobExecutionStartedDomainEventHandlerTests public ScheduledJobExecutionStartedDomainEventHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockScheduledJobNotifier = Substitute.For(); _mockScheduledJobRepository = Substitute.For(); _mockScheduledJobExecutionRepository = Substitute.For(); @@ -52,7 +55,7 @@ public class ScheduledJobExecutionStartedDomainEventHandlerTests _mockUnitOfWork.ScheduledJobExecutionRepository.Returns(_mockScheduledJobExecutionRepository); _mockScheduledJobRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.Updated); _mockScheduledJobExecutionRepository.InsertAsync(Arg.Any(), Arg.Any()).Returns(Result.Created); - _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([])); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); _sut = new ScheduledJobExecutionStartedDomainEventHandler(_mockScheduledJobNotifier, _mockUnitOfWork); } @@ -68,7 +71,7 @@ public class ScheduledJobExecutionStartedDomainEventHandlerTests taskType: domainEvent.TaskType, scheduleType: ScheduleType.WithIntervalInMinutes, status: ScheduledJobStatus.Active); - _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(scheduledJob)); // Act @@ -100,7 +103,7 @@ public class ScheduledJobExecutionStartedDomainEventHandlerTests // Arrange ScheduledJobExecutionStartedDomainEvent domainEvent = _scheduledJobExecutionStartedDomainEventFixture.Create(); Error error = Error.Failure("Database.Error", "Failed to get the scheduled job"); - _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any()).Returns(error); + _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, cancellationToken: Arg.Any()).Returns(error); // Act EventualConsistencyException exception = await Assert.ThrowsAsync( @@ -116,7 +119,7 @@ public class ScheduledJobExecutionStartedDomainEventHandlerTests { // Arrange ScheduledJobExecutionStartedDomainEvent domainEvent = _scheduledJobExecutionStartedDomainEventFixture.Create(); - _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(null)); // Act @@ -135,7 +138,7 @@ public class ScheduledJobExecutionStartedDomainEventHandlerTests ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create( id: domainEvent.ScheduledJobId.Value, status: ScheduledJobStatus.Active); - _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(scheduledJob)); Error error = Error.Failure("Database.Error", "Failed to update the scheduled job"); _mockScheduledJobRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(error); @@ -155,7 +158,7 @@ public class ScheduledJobExecutionStartedDomainEventHandlerTests // Arrange ScheduledJobExecutionStartedDomainEvent domainEvent = _scheduledJobExecutionStartedDomainEventFixture.Create(); ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(id: domainEvent.ScheduledJobId.Value); - _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(scheduledJob)); Error error = Error.Failure("Database.Error", "Failed to insert the execution"); _mockScheduledJobExecutionRepository.InsertAsync(Arg.Any(), Arg.Any()).Returns(error); @@ -175,10 +178,10 @@ public class ScheduledJobExecutionStartedDomainEventHandlerTests // Arrange ScheduledJobExecutionStartedDomainEvent domainEvent = _scheduledJobExecutionStartedDomainEventFixture.Create(); ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(id: domainEvent.ScheduledJobId.Value); - _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(scheduledJob)); Error error = Error.Failure("Database.Error", "Failed to get the scheduled jobs"); - _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(error); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(error); // Act EventualConsistencyException exception = await Assert.ThrowsAsync( diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobExecutionStoppedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobExecutionStoppedDomainEventHandlerTests.cs index 52c0b749..9daedcc6 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobExecutionStoppedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobExecutionStoppedDomainEventHandlerTests.cs @@ -2,6 +2,8 @@ using Lumina.Application.Common.DataAccess.Entities.Scheduling; using Lumina.Application.Common.DataAccess.Repositories.Scheduling; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Core.Scheduling.Events; using Lumina.Application.Core.Scheduling.Notifications; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling; @@ -40,6 +42,7 @@ public class ScheduledJobExecutionStoppedDomainEventHandlerTests public ScheduledJobExecutionStoppedDomainEventHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockScheduledJobNotifier = Substitute.For(); _mockScheduledJobRepository = Substitute.For(); _mockScheduledJobExecutionRepository = Substitute.For(); @@ -47,7 +50,7 @@ public class ScheduledJobExecutionStoppedDomainEventHandlerTests _mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository); _mockUnitOfWork.ScheduledJobExecutionRepository.Returns(_mockScheduledJobExecutionRepository); _mockScheduledJobExecutionRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.Updated); - _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([])); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); _sut = new ScheduledJobExecutionStoppedDomainEventHandler(_mockScheduledJobNotifier, _mockUnitOfWork); } @@ -140,7 +143,7 @@ public class ScheduledJobExecutionStoppedDomainEventHandlerTests _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any()) .Returns(Result.From(null)); Error error = Error.Failure("Database.Error", "Failed to get the scheduled jobs"); - _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(error); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(error); // Act EventualConsistencyException exception = await Assert.ThrowsAsync( diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobRemovedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobRemovedDomainEventHandlerTests.cs index 54ed5c7c..689fdd5d 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobRemovedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobRemovedDomainEventHandlerTests.cs @@ -2,6 +2,8 @@ using Lumina.Application.Common.DataAccess.Entities.Scheduling; using Lumina.Application.Common.DataAccess.Repositories.Scheduling; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Core.Scheduling.Events; using Lumina.Application.Core.Scheduling.Notifications; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling; @@ -39,11 +41,12 @@ public class ScheduledJobRemovedDomainEventHandlerTests public ScheduledJobRemovedDomainEventHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockScheduledJobNotifier = Substitute.For(); _mockScheduledJobRepository = Substitute.For(); _mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository); - _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([])); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); _sut = new ScheduledJobRemovedDomainEventHandler(_mockScheduledJobNotifier, _mockUnitOfWork); } @@ -54,7 +57,7 @@ public class ScheduledJobRemovedDomainEventHandlerTests // Arrange ScheduledJobRemovedDomainEvent domainEvent = _scheduledJobRemovedDomainEventFixture.Create(); ScheduledJobEntity remainingJob = _scheduledJobEntityFixture.Create(name: "Remaining job"); - _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([remainingJob])); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [remainingJob], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 })); // Act await _sut.HandleAsync(domainEvent, CancellationToken.None); @@ -71,7 +74,7 @@ public class ScheduledJobRemovedDomainEventHandlerTests // Arrange ScheduledJobRemovedDomainEvent domainEvent = _scheduledJobRemovedDomainEventFixture.Create(); Error error = Error.Failure("Database.Error", "Failed to get the scheduled jobs"); - _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(error); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(error); // Act EventualConsistencyException exception = await Assert.ThrowsAsync( diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Queries/GetScheduledJobHistory/GetScheduledJobHistoryQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Queries/GetScheduledJobHistory/GetScheduledJobHistoryQueryHandlerTests.cs index 45ed8366..94966872 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Queries/GetScheduledJobHistory/GetScheduledJobHistoryQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Queries/GetScheduledJobHistory/GetScheduledJobHistoryQueryHandlerTests.cs @@ -42,6 +42,7 @@ public class GetScheduledJobHistoryQueryHandlerTests public GetScheduledJobHistoryQueryHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockCurrentUserService = Substitute.For(); _mockAuthorizationService = Substitute.For(); _mockScheduledJobExecutionRepository = Substitute.For(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Queries/GetScheduledJobs/GetScheduledJobsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Queries/GetScheduledJobs/GetScheduledJobsQueryHandlerTests.cs index 146499ae..a3f47aaf 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Queries/GetScheduledJobs/GetScheduledJobsQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Queries/GetScheduledJobs/GetScheduledJobsQueryHandlerTests.cs @@ -2,6 +2,8 @@ using Lumina.Application.Common.DataAccess.Entities.Scheduling; using Lumina.Application.Common.DataAccess.Repositories.Scheduling; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Core.Scheduling.Queries.GetScheduledJobs; @@ -40,6 +42,7 @@ public class GetScheduledJobsQueryHandlerTests public GetScheduledJobsQueryHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockCurrentUserService = Substitute.For(); _mockAuthorizationService = Substitute.For(); _mockScheduledJobRepository = Substitute.For(); @@ -57,8 +60,8 @@ public class GetScheduledJobsQueryHandlerTests // Arrange ScheduledJobEntity scheduledJob1 = _scheduledJobEntityFixture.Create(name: "Job 1"); ScheduledJobEntity scheduledJob2 = _scheduledJobEntityFixture.Create(name: "Job 2"); - _mockScheduledJobRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From>([scheduledJob1, scheduledJob2])); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [scheduledJob1, scheduledJob2], CurrentPage = 1, PerPage = 2, Count = 2, NumberOfPages = 1 })); // Act Result> result = await _sut.HandleAsync(new GetScheduledJobsQuery(), CancellationToken.None); @@ -74,8 +77,8 @@ public class GetScheduledJobsQueryHandlerTests public async Task HandleAsync_WhenNoScheduledJobsExist_ShouldReturnEmptyCollection() { // Arrange - _mockScheduledJobRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From>([])); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); // Act Result> result = await _sut.HandleAsync(new GetScheduledJobsQuery(), CancellationToken.None); @@ -97,7 +100,7 @@ public class GetScheduledJobsQueryHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockScheduledJobRepository.DidNotReceive().GetAllAsync(Arg.Any()); + await _mockScheduledJobRepository.DidNotReceive().GetAllAsync(cancellationToken: Arg.Any()); } [Fact] @@ -112,7 +115,7 @@ public class GetScheduledJobsQueryHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockScheduledJobRepository.DidNotReceive().GetAllAsync(Arg.Any()); + await _mockScheduledJobRepository.DidNotReceive().GetAllAsync(cancellationToken: Arg.Any()); } [Fact] @@ -120,7 +123,7 @@ public class GetScheduledJobsQueryHandlerTests { // Arrange Error error = Error.Failure("Database.Error", "Failed to get the scheduled jobs"); - _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(error); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(error); // Act Result> result = await _sut.HandleAsync(new GetScheduledJobsQuery(), CancellationToken.None); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Queries/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Queries/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesQueryHandlerTests.cs index 4fa22ff1..fd00b036 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Queries/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Queries/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesQueryHandlerTests.cs @@ -42,6 +42,7 @@ public class GetSchedulerDisplayPreferencesQueryHandlerTests public GetSchedulerDisplayPreferencesQueryHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockCurrentUserService = Substitute.For(); _mockAuthorizationService = Substitute.For(); _mockSchedulerDisplayPreferencesRepository = Substitute.For(); 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 index f0d763af..acbe0343 100644 --- 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 @@ -2,6 +2,8 @@ using Lumina.Application.Common.DataAccess.Entities.Themes; using Lumina.Application.Common.DataAccess.Repositories.Themes; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Themes; @@ -47,6 +49,7 @@ public class DeleteThemeCommandHandlerTests public DeleteThemeCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockThemeService = Substitute.For(); _mockCurrentUserService = Substitute.For(); _mockAuthorizationService = Substitute.For(); @@ -185,7 +188,7 @@ public class DeleteThemeCommandHandlerTests 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()) + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()) .Returns(error); // Act @@ -206,8 +209,8 @@ public class DeleteThemeCommandHandlerTests 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])); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [theme, userTheme], CurrentPage = 1, PerPage = 2, Count = 2, NumberOfPages = 1 })); // Act Result result = await _sut.HandleAsync(command, CancellationToken.None); @@ -228,8 +231,8 @@ public class DeleteThemeCommandHandlerTests 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])); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [theme], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 })); // Act Result result = await _sut.HandleAsync(command, CancellationToken.None); @@ -251,8 +254,8 @@ public class DeleteThemeCommandHandlerTests 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.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [theme, otherBundledTheme], CurrentPage = 1, PerPage = 2, Count = 2, NumberOfPages = 1 })); _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()) .Returns(Result.Updated); @@ -278,8 +281,8 @@ public class DeleteThemeCommandHandlerTests 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.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [theme, bundledTheme], CurrentPage = 1, PerPage = 2, Count = 2, NumberOfPages = 1 })); _mockThemeRepository.DeleteByIdAsync(theme.Id, Arg.Any()) .Returns(Result.Deleted); @@ -304,8 +307,8 @@ public class DeleteThemeCommandHandlerTests 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.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [theme, bundledTheme], CurrentPage = 1, PerPage = 2, Count = 2, NumberOfPages = 1 })); _mockThemeRepository.DeleteByIdAsync(theme.Id, Arg.Any()) .Returns(error); @@ -329,8 +332,8 @@ public class DeleteThemeCommandHandlerTests _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.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [theme, replacementTheme], CurrentPage = 1, PerPage = 2, Count = 2, NumberOfPages = 1 })); _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()) .Returns(Result.Updated); @@ -360,8 +363,8 @@ public class DeleteThemeCommandHandlerTests _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.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [theme, betaTheme, alphaTheme], CurrentPage = 1, PerPage = 3, Count = 3, NumberOfPages = 1 })); _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()) .Returns(Result.Updated); @@ -388,8 +391,8 @@ public class DeleteThemeCommandHandlerTests 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.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [theme, bundledTheme], CurrentPage = 1, PerPage = 2, Count = 2, NumberOfPages = 1 })); _mockThemeRepository.DeleteByIdAsync(theme.Id, Arg.Any()) .Returns(Result.Deleted); _mockThemeService.DeleteAsync(theme.ThemeId, Arg.Any()) 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 index 833c6414..c202cf56 100644 --- 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 @@ -51,6 +51,7 @@ public class InstallThemeCommandHandlerTests public InstallThemeCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockThemeService = Substitute.For(); _mockCurrentUserService = Substitute.For(); _mockAuthorizationService = Substitute.For(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandHandlerTests.cs index 0a3ffd43..f8dcab50 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandHandlerTests.cs @@ -45,6 +45,7 @@ public class RestoreThemeCommandHandlerTests public RestoreThemeCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockThemeService = Substitute.For(); _mockCurrentUserService = Substitute.For(); _mockAuthorizationService = Substitute.For(); 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 index f63854be..9dcaa379 100644 --- 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 @@ -44,6 +44,7 @@ public class SetCurrentThemeCommandHandlerTests public SetCurrentThemeCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockCurrentUserService = Substitute.For(); _mockAuthorizationService = Substitute.For(); _mockValidator = Substitute.For>(); 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 index abb8cead..4185e99b 100644 --- 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 @@ -35,6 +35,7 @@ public class GetCurrentThemeQueryHandlerTests public GetCurrentThemeQueryHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockThemeRepository = Substitute.For(); _mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository); _sut = new GetCurrentThemeQueryHandler(_mockUnitOfWork); 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 index 2958bb72..4aff40af 100644 --- 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 @@ -41,6 +41,7 @@ public class GetThemeArchiveQueryHandlerTests public GetThemeArchiveQueryHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockThemeService = Substitute.For(); _mockValidator = Substitute.For>(); _mockThemeRepository = Substitute.For(); 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 index c3dfd888..50e10124 100644 --- 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 @@ -42,6 +42,7 @@ public class GetThemeAssetQueryHandlerTests public GetThemeAssetQueryHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockThemeService = Substitute.For(); _mockValidator = Substitute.For>(); _mockThemeRepository = Substitute.For(); 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 index 320395bf..235592d4 100644 --- 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 @@ -44,6 +44,7 @@ public class GetThemeTemplateQueryHandlerTests public GetThemeTemplateQueryHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockThemeService = Substitute.For(); _mockValidator = Substitute.For>(); _mockThemeRepository = Substitute.For(); 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 index a6e2b80c..bf076d7e 100644 --- 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 @@ -2,6 +2,8 @@ using Lumina.Application.Common.DataAccess.Entities.Themes; using Lumina.Application.Common.DataAccess.Repositories.Themes; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; 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; @@ -35,6 +37,7 @@ public class GetThemesQueryHandlerTests public GetThemesQueryHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockThemeRepository = Substitute.For(); _mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository); _sut = new GetThemesQueryHandler(_mockUnitOfWork); @@ -49,8 +52,8 @@ public class GetThemesQueryHandlerTests 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])); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [uploadedTheme, bundledLowerTheme, bundledUpperTheme, deletedTheme], CurrentPage = 1, PerPage = 4, Count = 4, NumberOfPages = 1 })); // Act Result> result = await _sut.HandleAsync(query, CancellationToken.None); @@ -73,8 +76,8 @@ public class GetThemesQueryHandlerTests { // Arrange GetThemesQuery query = _getThemesQueryFixture.Create(); - _mockThemeRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From>([])); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); // Act Result> result = await _sut.HandleAsync(query, CancellationToken.None); @@ -90,7 +93,7 @@ public class GetThemesQueryHandlerTests // Arrange GetThemesQuery query = _getThemesQueryFixture.Create(); Error error = Error.Failure("Database.Error", "Failed to get all themes"); - _mockThemeRepository.GetAllAsync(Arg.Any()) + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()) .Returns(error); // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandlerTests.cs index e38e7cc4..9cf3f7ee 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandlerTests.cs @@ -36,6 +36,7 @@ public class ChangePasswordCommandHandlerTests public ChangePasswordCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockHashService = Substitute.For(); _mockUserRepository = Substitute.For(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandlerTests.cs index e542116a..91a0a558 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandlerTests.cs @@ -39,6 +39,7 @@ public class RecoverPasswordCommandHandlerTests public RecoverPasswordCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockHashService = Substitute.For(); _mockTotpTokenGenerator = Substitute.For(); _mockCryptographyService = Substitute.For(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandlerTests.cs index 7818ddbb..d639f62f 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandlerTests.cs @@ -44,6 +44,7 @@ public class RegisterUserCommandHandlerTests public RegisterUserCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockHashService = Substitute.For(); _mockCryptographyService = Substitute.For(); _mockTotpTokenGenerator = Substitute.For(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryHandlerTests.cs index 4685623b..85c6267e 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryHandlerTests.cs @@ -2,6 +2,8 @@ using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; @@ -42,6 +44,7 @@ public class GetUsersQueryHandlerTests public GetUsersQueryHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockAuthorizationService = Substitute.For(); _mockCurrentUserService = Substitute.For(); _mockUserRepository = Substitute.For(); @@ -70,7 +73,7 @@ public class GetUsersQueryHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError); - await _mockUserRepository.DidNotReceive().GetAllAsync(Arg.Any()); + await _mockUserRepository.DidNotReceive().GetAllAsync(cancellationToken: Arg.Any()); } [Fact] @@ -87,7 +90,7 @@ public class GetUsersQueryHandlerTests Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError); await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockUserRepository.DidNotReceive().GetAllAsync(Arg.Any()); + await _mockUserRepository.DidNotReceive().GetAllAsync(cancellationToken: Arg.Any()); } [Fact] @@ -99,7 +102,7 @@ public class GetUsersQueryHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockUserRepository.GetAllAsync(Arg.Any()) + _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) .Returns(error); // Act @@ -115,13 +118,13 @@ public class GetUsersQueryHandlerTests { // Arrange GetUsersQuery query = _getUsersQueryFixture.Create(); - IEnumerable users = _userEntityFixture.CreateMany(2); + List users = _userEntityFixture.CreateMany(2); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockUserRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From(users)); + _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = users, CurrentPage = 1, PerPage = users.Count, Count = users.Count, NumberOfPages = 1 })); // Act Result> result = await _sut.HandleAsync(query, CancellationToken.None); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandlerTests.cs index 2d372046..2d2d6761 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandlerTests.cs @@ -42,6 +42,7 @@ public class LoginUserQueryHandlerTests public LoginUserQueryHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockHashService = Substitute.For(); _mockJwtTokenGenerator = Substitute.For(); _mockTotpTokenGenerator = Substitute.For(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandHandlerTests.cs index 0eec39ab..92cf2050 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandHandlerTests.cs @@ -4,6 +4,8 @@ using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Authorization; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Validation; @@ -54,6 +56,7 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests public UpdateUserRoleAndPermissionsCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockAuthorizationService = Substitute.For(); _mockCurrentUserService = Substitute.For(); _mockUserRepository = Substitute.For(); @@ -107,7 +110,7 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockUserRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockUserRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -117,7 +120,7 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.Create(); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockUserRepository.GetByIdAsync(command.UserId, Arg.Any()) + _mockUserRepository.GetByIdAsync(command.UserId, cancellationToken: Arg.Any()) .Returns((UserEntity?)null); // Act @@ -137,9 +140,9 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockUserRepository.GetByIdAsync(command.UserId, Arg.Any()) + _mockUserRepository.GetByIdAsync(command.UserId, cancellationToken: Arg.Any()) .Returns(user); - _mockRoleRepository.GetByIdAsync(command.RoleId!.Value, Arg.Any()) + _mockRoleRepository.GetByIdAsync(command.RoleId!.Value, cancellationToken: Arg.Any()) .Returns((RoleEntity?)null); // Act @@ -167,16 +170,16 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests includeUserRole: true); RoleEntity newRole = _roleEntityFixture.Create(roleName: "User"); - IEnumerable users = [user]; + List users = [user]; _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockUserRepository.GetByIdAsync(command.UserId, Arg.Any()) + _mockUserRepository.GetByIdAsync(command.UserId, cancellationToken: Arg.Any()) .Returns(user); - _mockRoleRepository.GetByIdAsync(command.RoleId!.Value, Arg.Any()) + _mockRoleRepository.GetByIdAsync(command.RoleId!.Value, cancellationToken: Arg.Any()) .Returns(newRole); - _mockUserRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From(users)); + _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = users, CurrentPage = 1, PerPage = users.Count, Count = users.Count, NumberOfPages = 1 })); // Act Result result = await _sut.HandleAsync(command, CancellationToken.None); @@ -199,9 +202,9 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockUserRepository.GetByIdAsync(command.UserId, Arg.Any()) + _mockUserRepository.GetByIdAsync(command.UserId, cancellationToken: Arg.Any()) .Returns(user); - _mockRoleRepository.GetByIdAsync(command.RoleId!.Value, Arg.Any()) + _mockRoleRepository.GetByIdAsync(command.RoleId!.Value, cancellationToken: Arg.Any()) .Returns(role); _mockPermissionRepository.GetByIdsAsync(command.Permissions, Arg.Any()) .Returns(Result.From(permissions)); @@ -237,9 +240,9 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockUserRepository.GetByIdAsync(command.UserId, Arg.Any()) + _mockUserRepository.GetByIdAsync(command.UserId, cancellationToken: Arg.Any()) .Returns(user); - _mockRoleRepository.GetByIdAsync(command.RoleId!.Value, Arg.Any()) + _mockRoleRepository.GetByIdAsync(command.RoleId!.Value, cancellationToken: Arg.Any()) .Returns(role); _mockPermissionRepository.GetByIdsAsync(command.Permissions, Arg.Any()) .Returns(Result.From(permissions)); @@ -276,11 +279,11 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockUserRepository.GetByIdAsync(command.UserId, Arg.Any()) + _mockUserRepository.GetByIdAsync(command.UserId, cancellationToken: Arg.Any()) .Returns(user); - _mockRoleRepository.GetByIdAsync(command.RoleId!.Value, Arg.Any()) + _mockRoleRepository.GetByIdAsync(command.RoleId!.Value, cancellationToken: Arg.Any()) .Returns(_roleEntityFixture.Create(roleName: "User")); - _mockUserRepository.GetAllAsync(Arg.Any()) + _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) .Returns(error); // Act @@ -301,9 +304,9 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockUserRepository.GetByIdAsync(command.UserId, Arg.Any()) + _mockUserRepository.GetByIdAsync(command.UserId, cancellationToken: Arg.Any()) .Returns(user); - _mockRoleRepository.GetByIdAsync(command.RoleId!.Value, Arg.Any()) + _mockRoleRepository.GetByIdAsync(command.RoleId!.Value, cancellationToken: Arg.Any()) .Returns(_roleEntityFixture.Create(roleName: "User")); _mockPermissionRepository.GetByIdsAsync(command.Permissions, Arg.Any()) .Returns(error); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandlerTests.cs index 8100d620..781f2a39 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandlerTests.cs @@ -47,6 +47,7 @@ public class GetUserPermissionsQueryHandlerTests public GetUserPermissionsQueryHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockAuthorizationService = Substitute.For(); _mockCurrentUserService = Substitute.For(); _mockUserRepository = Substitute.For(); @@ -79,7 +80,7 @@ public class GetUserPermissionsQueryHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError); - await _mockUserRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockUserRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -96,7 +97,7 @@ public class GetUserPermissionsQueryHandlerTests Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError); await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockUserRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockUserRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -108,7 +109,7 @@ public class GetUserPermissionsQueryHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockUserRepository.GetByIdAsync(query.UserId!.Value, Arg.Any()) + _mockUserRepository.GetByIdAsync(query.UserId!.Value, cancellationToken: Arg.Any()) .Returns(error); // Act @@ -127,7 +128,7 @@ public class GetUserPermissionsQueryHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockUserRepository.GetByIdAsync(query.UserId!.Value, Arg.Any()) + _mockUserRepository.GetByIdAsync(query.UserId!.Value, cancellationToken: Arg.Any()) .Returns((UserEntity?)null); // Act @@ -157,7 +158,7 @@ public class GetUserPermissionsQueryHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockUserRepository.GetByIdAsync(query.UserId!.Value, Arg.Any()) + _mockUserRepository.GetByIdAsync(query.UserId!.Value, cancellationToken: Arg.Any()) .Returns(user); // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandlerTests.cs index 15e3cde3..3d6dcddf 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandlerTests.cs @@ -44,6 +44,7 @@ public class GetUserRoleQueryHandlerTests public GetUserRoleQueryHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockAuthorizationService = Substitute.For(); _mockCurrentUserService = Substitute.For(); _mockUserRepository = Substitute.For(); @@ -76,7 +77,7 @@ public class GetUserRoleQueryHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError); - await _mockUserRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockUserRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -93,7 +94,7 @@ public class GetUserRoleQueryHandlerTests Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError); await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockUserRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockUserRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -105,7 +106,7 @@ public class GetUserRoleQueryHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockUserRepository.GetByIdAsync(query.UserId!.Value, Arg.Any()) + _mockUserRepository.GetByIdAsync(query.UserId!.Value, cancellationToken: Arg.Any()) .Returns(error); // Act @@ -124,7 +125,7 @@ public class GetUserRoleQueryHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockUserRepository.GetByIdAsync(query.UserId!.Value, Arg.Any()) + _mockUserRepository.GetByIdAsync(query.UserId!.Value, cancellationToken: Arg.Any()) .Returns((UserEntity?)null); // Act @@ -144,7 +145,7 @@ public class GetUserRoleQueryHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockUserRepository.GetByIdAsync(query.UserId!.Value, Arg.Any()) + _mockUserRepository.GetByIdAsync(query.UserId!.Value, cancellationToken: Arg.Any()) .Returns(user); // Act @@ -171,7 +172,7 @@ public class GetUserRoleQueryHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockUserRepository.GetByIdAsync(query.UserId!.Value, Arg.Any()) + _mockUserRepository.GetByIdAsync(query.UserId!.Value, cancellationToken: Arg.Any()) .Returns(user); // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandlerTests.cs index a3ad3a9c..9b4c7a08 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandlerTests.cs @@ -40,6 +40,7 @@ public class UpdateUserSettingsCommandHandlerTests public UpdateUserSettingsCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockCurrentUserService = Substitute.For(); _mockUserSettingsRepository = Substitute.For(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Queries/GetUserSettings/GetUserSettingsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Queries/GetUserSettings/GetUserSettingsQueryHandlerTests.cs index 81ce23ea..a0a0df49 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Queries/GetUserSettings/GetUserSettingsQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Queries/GetUserSettings/GetUserSettingsQueryHandlerTests.cs @@ -38,6 +38,7 @@ public class GetUserSettingsQueryHandlerTests public GetUserSettingsQueryHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockCurrentUserService = Substitute.For(); _mockUserSettingsRepository = Substitute.For(); diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Seed/DataSeedServiceTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Seed/DataSeedServiceTests.cs index 3ff2ee59..67b3fa86 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Seed/DataSeedServiceTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Seed/DataSeedServiceTests.cs @@ -6,6 +6,8 @@ using Lumina.Application.Common.DataAccess.Repositories.Authorization; using Lumina.Application.Common.DataAccess.Repositories.Scheduling; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Time; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; @@ -47,6 +49,7 @@ public class DataSeedServiceTests public DataSeedServiceTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockDateTimeProvider = Substitute.For(); _mockPermissionRepository = Substitute.For(); _fixedUtcNow = DateTime.UtcNow; @@ -252,7 +255,15 @@ public class DataSeedServiceTests _mockUnitOfWork.RolePermissionRepository.Returns(mockRolePermissionRepository); mockRoleRepository.GetByNameAsync("Admin", Arg.Any()).Returns(adminRole); - mockPermissionRepository.GetAllAsync(Arg.Any()).Returns(permissions); + mockPermissionRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(new PaginatedResultDto + { + Data = permissions, + CurrentPage = 1, + PerPage = permissions.Count, + Count = permissions.Count, + NumberOfPages = 1 + }); mockRolePermissionRepository.InsertAsync(Arg.Any(), Arg.Any()).Returns(Result.Created); // Act @@ -310,7 +321,7 @@ public class DataSeedServiceTests _mockUnitOfWork.PermissionRepository.Returns(mockPermissionRepository); mockRoleRepository.GetByNameAsync("Admin", Arg.Any()).Returns(adminRole); - mockPermissionRepository.GetAllAsync(Arg.Any()).Returns(expectedError); + mockPermissionRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(expectedError); // Act Result result = await _sut.SetAdminRolePermissionsAsync(userId, CancellationToken.None); @@ -340,7 +351,15 @@ public class DataSeedServiceTests _mockUnitOfWork.RolePermissionRepository.Returns(mockRolePermissionRepository); mockRoleRepository.GetByNameAsync("Admin", Arg.Any()).Returns(adminRole); - mockPermissionRepository.GetAllAsync(Arg.Any()).Returns(permissions); + mockPermissionRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(new PaginatedResultDto + { + Data = permissions, + CurrentPage = 1, + PerPage = permissions.Count, + Count = permissions.Count, + NumberOfPages = 1 + }); mockRolePermissionRepository.InsertAsync(Arg.Any(), Arg.Any()).Returns(expectedError); // Act @@ -396,7 +415,7 @@ public class DataSeedServiceTests _mockUnitOfWork.UserRoleRepository.Returns(mockUserRoleRepository); mockRoleRepository.GetByNameAsync("Admin", Arg.Any()).Returns(adminRole); - mockUserRepository.GetByIdAsync(userId, Arg.Any()).Returns(adminUser); + mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any()).Returns(adminUser); mockUserRoleRepository.InsertAsync(Arg.Any(), Arg.Any()).Returns(Result.Created); // Act @@ -454,7 +473,7 @@ public class DataSeedServiceTests _mockUnitOfWork.UserRepository.Returns(mockUserRepository); mockRoleRepository.GetByNameAsync("Admin", Arg.Any()).Returns(adminRole); - mockUserRepository.GetByIdAsync(userId, Arg.Any()).Returns((UserEntity?)null); + mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any()).Returns((UserEntity?)null); // Act Result result = await _sut.SetAdminRoleToAdministratorAccount(userId, CancellationToken.None); @@ -485,7 +504,7 @@ public class DataSeedServiceTests _mockUnitOfWork.UserRoleRepository.Returns(mockUserRoleRepository); mockRoleRepository.GetByNameAsync("Admin", Arg.Any()).Returns(adminRole); - mockUserRepository.GetByIdAsync(userId, Arg.Any()).Returns(adminUser); + mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any()).Returns(adminUser); mockUserRoleRepository.InsertAsync(Arg.Any(), Arg.Any()).Returns(expectedError); // Act @@ -537,7 +556,7 @@ public class DataSeedServiceTests _mockUnitOfWork.UserRepository.Returns(mockUserRepository); mockRoleRepository.GetByNameAsync("Admin", Arg.Any()).Returns(adminRole); - mockUserRepository.GetByIdAsync(userId, Arg.Any()).Returns(expectedError); + mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any()).Returns(expectedError); // Act Result result = await _sut.SetAdminRoleToAdministratorAccount(userId, CancellationToken.None); @@ -580,7 +599,7 @@ public class DataSeedServiceTests await mockScheduledJobRepository.Received(5).InsertAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - await mockScheduledJobRepository.DidNotReceive().GetAllAsync(Arg.Any()); + await mockScheduledJobRepository.DidNotReceive().GetAllAsync(cancellationToken: Arg.Any()); } [Fact] diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/UnitOfWorkTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/UnitOfWorkTests.cs index 4ae099c4..fbf4cc39 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/UnitOfWorkTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/UnitOfWorkTests.cs @@ -8,6 +8,7 @@ using Lumina.Application.Common.Infrastructure.Time; using Lumina.DataAccess.Common.DependencyInjection; using Lumina.DataAccess.Core.UoW; using Lumina.DataAccess.UnitTests.Common.Setup; +using Lumina.Domain.Common.Primitives; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using NSubstitute; @@ -96,9 +97,11 @@ public class UnitOfWorkTests CancellationToken cancellationToken = new(); // Act - await unitOfWork.SaveChangesAsync(cancellationToken); + Result result = await unitOfWork.SaveChangesAsync(cancellationToken); // Assert + Assert.True(result.IsSuccess); + Assert.Equal(Result.Success, result.Value); await dbContext.Received(1).SaveChangesAsync(cancellationToken); } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/AuthorizationServiceTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/AuthorizationServiceTests.cs index c5a2ade0..99208074 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/AuthorizationServiceTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/AuthorizationServiceTests.cs @@ -40,6 +40,7 @@ public class AuthorizationServiceTests public AuthorizationServiceTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockUserRepository = Substitute.For(); _mockAuthorizationPolicyFactory = Substitute.For(); @@ -53,7 +54,7 @@ public class AuthorizationServiceTests { // Arrange Guid userId = Guid.NewGuid(); - _mockUserRepository.GetByIdAsync(userId, Arg.Any()) + _mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any()) .Returns(Result.From(null)); // Act @@ -61,7 +62,7 @@ public class AuthorizationServiceTests // Assert Assert.False(result); - await _mockUserRepository.Received(1).GetByIdAsync(userId, Arg.Any()); + await _mockUserRepository.Received(1).GetByIdAsync(userId, cancellationToken: Arg.Any()); } [Fact] @@ -70,7 +71,7 @@ public class AuthorizationServiceTests // Arrange Guid userId = Guid.NewGuid(); Error error = Error.Failure("Database.Error", "Failed to retrieve user"); - _mockUserRepository.GetByIdAsync(userId, Arg.Any()) + _mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any()) .Returns(error); // Act @@ -78,7 +79,7 @@ public class AuthorizationServiceTests // Assert Assert.False(result); - await _mockUserRepository.Received(1).GetByIdAsync(userId, Arg.Any()); + await _mockUserRepository.Received(1).GetByIdAsync(userId, cancellationToken: Arg.Any()); } [Fact] @@ -88,7 +89,7 @@ public class AuthorizationServiceTests UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions( directPermissions: [AuthorizationPermission.CanViewUsers]); - _mockUserRepository.GetByIdAsync(user.Id, Arg.Any()) + _mockUserRepository.GetByIdAsync(user.Id, cancellationToken: Arg.Any()) .Returns(Result.From(user)); // Act @@ -96,7 +97,7 @@ public class AuthorizationServiceTests // Assert Assert.True(result); - await _mockUserRepository.Received(1).GetByIdAsync(user.Id, Arg.Any()); + await _mockUserRepository.Received(1).GetByIdAsync(user.Id, cancellationToken: Arg.Any()); } [Fact] @@ -111,7 +112,7 @@ public class AuthorizationServiceTests UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions( rolePermissions: rolePermissions); - _mockUserRepository.GetByIdAsync(user.Id, Arg.Any()) + _mockUserRepository.GetByIdAsync(user.Id, cancellationToken: Arg.Any()) .Returns(Result.From(user)); // Act @@ -119,7 +120,7 @@ public class AuthorizationServiceTests // Assert Assert.True(result); - await _mockUserRepository.Received(1).GetByIdAsync(user.Id, Arg.Any()); + await _mockUserRepository.Received(1).GetByIdAsync(user.Id, cancellationToken: Arg.Any()); } [Fact] @@ -128,7 +129,7 @@ public class AuthorizationServiceTests // Arrange UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions(); - _mockUserRepository.GetByIdAsync(user.Id, Arg.Any()) + _mockUserRepository.GetByIdAsync(user.Id, cancellationToken: Arg.Any()) .Returns(Result.From(user)); // Act @@ -136,7 +137,7 @@ public class AuthorizationServiceTests // Assert Assert.False(result); - await _mockUserRepository.Received(1).GetByIdAsync(user.Id, Arg.Any()); + await _mockUserRepository.Received(1).GetByIdAsync(user.Id, cancellationToken: Arg.Any()); } [Fact] @@ -146,7 +147,7 @@ public class AuthorizationServiceTests UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions( directPermissions: [AuthorizationPermission.CanDeleteUsers]); - _mockUserRepository.GetByIdAsync(user.Id, Arg.Any()) + _mockUserRepository.GetByIdAsync(user.Id, cancellationToken: Arg.Any()) .Returns(Result.From(user)); // Act @@ -154,7 +155,7 @@ public class AuthorizationServiceTests // Assert Assert.False(result); - await _mockUserRepository.Received(1).GetByIdAsync(user.Id, Arg.Any()); + await _mockUserRepository.Received(1).GetByIdAsync(user.Id, cancellationToken: Arg.Any()); } [Fact] @@ -170,7 +171,7 @@ public class AuthorizationServiceTests directPermissions: [AuthorizationPermission.CanViewUsers], rolePermissions: rolePermissions); - _mockUserRepository.GetByIdAsync(user.Id, Arg.Any()) + _mockUserRepository.GetByIdAsync(user.Id, cancellationToken: Arg.Any()) .Returns(Result.From(user)); // Act @@ -178,7 +179,7 @@ public class AuthorizationServiceTests // Assert Assert.True(result); - await _mockUserRepository.Received(1).GetByIdAsync(user.Id, Arg.Any()); + await _mockUserRepository.Received(1).GetByIdAsync(user.Id, cancellationToken: Arg.Any()); } [Fact] @@ -186,7 +187,7 @@ public class AuthorizationServiceTests { // Arrange Guid userId = Guid.NewGuid(); - _mockUserRepository.GetByIdAsync(userId, Arg.Any()) + _mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any()) .Returns(Result.From(null)); // Act @@ -194,7 +195,7 @@ public class AuthorizationServiceTests // Assert Assert.False(result); - await _mockUserRepository.Received(1).GetByIdAsync(userId, Arg.Any()); + await _mockUserRepository.Received(1).GetByIdAsync(userId, cancellationToken: Arg.Any()); } [Fact] @@ -203,7 +204,7 @@ public class AuthorizationServiceTests // Arrange Guid userId = Guid.NewGuid(); Error error = Error.Failure("Database.Error", "Failed to retrieve user"); - _mockUserRepository.GetByIdAsync(userId, Arg.Any()) + _mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any()) .Returns(error); // Act @@ -211,7 +212,7 @@ public class AuthorizationServiceTests // Assert Assert.False(result); - await _mockUserRepository.Received(1).GetByIdAsync(userId, Arg.Any()); + await _mockUserRepository.Received(1).GetByIdAsync(userId, cancellationToken: Arg.Any()); } [Fact] @@ -226,7 +227,7 @@ public class AuthorizationServiceTests UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions( rolePermissions: rolePermissions); - _mockUserRepository.GetByIdAsync(user.Id, Arg.Any()) + _mockUserRepository.GetByIdAsync(user.Id, cancellationToken: Arg.Any()) .Returns(Result.From(user)); // Act @@ -234,7 +235,7 @@ public class AuthorizationServiceTests // Assert Assert.True(result); - await _mockUserRepository.Received(1).GetByIdAsync(user.Id, Arg.Any()); + await _mockUserRepository.Received(1).GetByIdAsync(user.Id, cancellationToken: Arg.Any()); } [Fact] @@ -249,7 +250,7 @@ public class AuthorizationServiceTests UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions( rolePermissions: rolePermissions); - _mockUserRepository.GetByIdAsync(user.Id, Arg.Any()) + _mockUserRepository.GetByIdAsync(user.Id, cancellationToken: Arg.Any()) .Returns(Result.From(user)); // Act @@ -257,7 +258,7 @@ public class AuthorizationServiceTests // Assert Assert.False(result); - await _mockUserRepository.Received(1).GetByIdAsync(user.Id, Arg.Any()); + await _mockUserRepository.Received(1).GetByIdAsync(user.Id, cancellationToken: Arg.Any()); } [Fact] @@ -266,7 +267,7 @@ public class AuthorizationServiceTests // Arrange UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions(); - _mockUserRepository.GetByIdAsync(user.Id, Arg.Any()) + _mockUserRepository.GetByIdAsync(user.Id, cancellationToken: Arg.Any()) .Returns(Result.From(user)); // Act @@ -274,7 +275,7 @@ public class AuthorizationServiceTests // Assert Assert.False(result); - await _mockUserRepository.Received(1).GetByIdAsync(user.Id, Arg.Any()); + await _mockUserRepository.Received(1).GetByIdAsync(user.Id, cancellationToken: Arg.Any()); } [Fact] @@ -409,7 +410,7 @@ public class AuthorizationServiceTests { // Arrange Guid userId = Guid.NewGuid(); - _mockUserRepository.GetByIdAsync(userId, Arg.Any()) + _mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any()) .Returns(Result.From(null)); // Act @@ -418,7 +419,7 @@ public class AuthorizationServiceTests // Assert Assert.True(result.IsFailure); Assert.Equal(Errors.Users.UserDoesNotExist, result.FirstError); - await _mockUserRepository.Received(1).GetByIdAsync(userId, Arg.Any()); + await _mockUserRepository.Received(1).GetByIdAsync(userId, cancellationToken: Arg.Any()); } [Fact] @@ -427,7 +428,7 @@ public class AuthorizationServiceTests // Arrange Guid userId = Guid.NewGuid(); Error error = Error.Failure("Database.Error", "Failed to retrieve user"); - _mockUserRepository.GetByIdAsync(userId, Arg.Any()) + _mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any()) .Returns(error); // Act @@ -436,7 +437,7 @@ public class AuthorizationServiceTests // Assert Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); - await _mockUserRepository.Received(1).GetByIdAsync(userId, Arg.Any()); + await _mockUserRepository.Received(1).GetByIdAsync(userId, cancellationToken: Arg.Any()); } [Fact] @@ -444,7 +445,7 @@ public class AuthorizationServiceTests { // Arrange UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions(); - _mockUserRepository.GetByIdAsync(user.Id, Arg.Any()) + _mockUserRepository.GetByIdAsync(user.Id, cancellationToken: Arg.Any()) .Returns(Result.From(user)); // Act @@ -455,7 +456,7 @@ public class AuthorizationServiceTests Assert.Equal(user.Id, result.Value.UserId); Assert.Null(result.Value.Role); Assert.Empty(result.Value.Permissions); - await _mockUserRepository.Received(1).GetByIdAsync(user.Id, Arg.Any()); + await _mockUserRepository.Received(1).GetByIdAsync(user.Id, cancellationToken: Arg.Any()); } [Fact] @@ -469,7 +470,7 @@ public class AuthorizationServiceTests AuthorizationPermission.CanDeleteUsers ]); - _mockUserRepository.GetByIdAsync(user.Id, Arg.Any()) + _mockUserRepository.GetByIdAsync(user.Id, cancellationToken: Arg.Any()) .Returns(Result.From(user)); // Act @@ -481,7 +482,7 @@ public class AuthorizationServiceTests Assert.Null(result.Value.Role); Assert.Equal([AuthorizationPermission.CanViewUsers, AuthorizationPermission.CanDeleteUsers], result.Value.Permissions); - await _mockUserRepository.Received(1).GetByIdAsync(user.Id, Arg.Any()); + await _mockUserRepository.Received(1).GetByIdAsync(user.Id, cancellationToken: Arg.Any()); } [Fact] @@ -499,7 +500,7 @@ public class AuthorizationServiceTests UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions( rolePermissions: rolePermissions); - _mockUserRepository.GetByIdAsync(user.Id, Arg.Any()) + _mockUserRepository.GetByIdAsync(user.Id, cancellationToken: Arg.Any()) .Returns(Result.From(user)); // Act @@ -511,7 +512,7 @@ public class AuthorizationServiceTests Assert.Equal("Admin", result.Value.Role); Assert.Equal([AuthorizationPermission.CanViewUsers, AuthorizationPermission.CanDeleteUsers], result.Value.Permissions); - await _mockUserRepository.Received(1).GetByIdAsync(user.Id, Arg.Any()); + await _mockUserRepository.Received(1).GetByIdAsync(user.Id, cancellationToken: Arg.Any()); } [Fact] @@ -530,7 +531,7 @@ public class AuthorizationServiceTests directPermissions: [AuthorizationPermission.CanRegisterUsers], rolePermissions: rolePermissions); - _mockUserRepository.GetByIdAsync(user.Id, Arg.Any()) + _mockUserRepository.GetByIdAsync(user.Id, cancellationToken: Arg.Any()) .Returns(Result.From(user)); // Act @@ -549,6 +550,6 @@ public class AuthorizationServiceTests }, result.Value.Permissions ); - await _mockUserRepository.Received(1).GetByIdAsync(user.Id, Arg.Any()); + await _mockUserRepository.Received(1).GetByIdAsync(user.Id, cancellationToken: Arg.Any()); } } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/Policies/LibraryOwnership/LibraryOwnershipPolicyTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/Policies/LibraryOwnership/LibraryOwnershipPolicyTests.cs index 352f2f8b..022605c9 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/Policies/LibraryOwnership/LibraryOwnershipPolicyTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/Policies/LibraryOwnership/LibraryOwnershipPolicyTests.cs @@ -40,6 +40,7 @@ public class LibraryOwnershipPolicyTests public LibraryOwnershipPolicyTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockUserRepository = Substitute.For(); _mockLibraryRepository = Substitute.For(); _mockUnitOfWork.UserRepository.Returns(_mockUserRepository); @@ -59,8 +60,8 @@ public class LibraryOwnershipPolicyTests // Assert Assert.False(result); - await _mockUserRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); - await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockUserRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -69,7 +70,7 @@ public class LibraryOwnershipPolicyTests // Arrange Guid userId = Guid.NewGuid(); LibraryOwnershipPolicyContext context = new(Guid.NewGuid()); - _mockUserRepository.GetByIdAsync(userId, Arg.Any()) + _mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any()) .Returns(Result.From(null)); // Act @@ -77,7 +78,7 @@ public class LibraryOwnershipPolicyTests // Assert Assert.False(result); - await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -86,7 +87,7 @@ public class LibraryOwnershipPolicyTests // Arrange Guid userId = Guid.NewGuid(); LibraryOwnershipPolicyContext context = new(Guid.NewGuid()); - _mockUserRepository.GetByIdAsync(userId, Arg.Any()) + _mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any()) .Returns(Error.Failure("Database.Error", "Failed to retrieve user")); // Act @@ -94,7 +95,7 @@ public class LibraryOwnershipPolicyTests // Assert Assert.False(result); - await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -107,7 +108,7 @@ public class LibraryOwnershipPolicyTests { "Admin", [] } }); LibraryOwnershipPolicyContext context = new(Guid.NewGuid()); - _mockUserRepository.GetByIdAsync(adminUser.Id, Arg.Any()) + _mockUserRepository.GetByIdAsync(adminUser.Id, cancellationToken: Arg.Any()) .Returns(Result.From(adminUser)); // Act @@ -115,7 +116,7 @@ public class LibraryOwnershipPolicyTests // Assert Assert.True(result); - await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -125,9 +126,9 @@ public class LibraryOwnershipPolicyTests Guid userId = Guid.NewGuid(); UserEntity regularUser = _authorizationServiceFixture.CreateUserWithPermissions(); LibraryOwnershipPolicyContext context = new(Guid.NewGuid()); - _mockUserRepository.GetByIdAsync(userId, Arg.Any()) + _mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any()) .Returns(Result.From(regularUser)); - _mockLibraryRepository.GetByIdAsync(context.LibraryId, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(context.LibraryId, cancellationToken: Arg.Any()) .Returns(Result.Success(null)); // Act @@ -144,9 +145,9 @@ public class LibraryOwnershipPolicyTests Guid userId = Guid.NewGuid(); UserEntity regularUser = _authorizationServiceFixture.CreateUserWithPermissions(); LibraryOwnershipPolicyContext context = new(Guid.NewGuid()); - _mockUserRepository.GetByIdAsync(userId, Arg.Any()) + _mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any()) .Returns(Result.From(regularUser)); - _mockLibraryRepository.GetByIdAsync(context.LibraryId, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(context.LibraryId, cancellationToken: Arg.Any()) .Returns(Error.Failure("Database.Error", "Failed to retrieve library")); // Act @@ -164,9 +165,9 @@ public class LibraryOwnershipPolicyTests UserEntity regularUser = _authorizationServiceFixture.CreateUserWithPermissions(); LibraryEntity library = _libraryEntityFixture.Create(userId: userId); LibraryOwnershipPolicyContext context = new(library.Id); - _mockUserRepository.GetByIdAsync(userId, Arg.Any()) + _mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any()) .Returns(Result.From(regularUser)); - _mockLibraryRepository.GetByIdAsync(context.LibraryId, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(context.LibraryId, cancellationToken: Arg.Any()) .Returns(Result.From(library)); // Act @@ -184,9 +185,9 @@ public class LibraryOwnershipPolicyTests UserEntity regularUser = _authorizationServiceFixture.CreateUserWithPermissions(); LibraryEntity library = _libraryEntityFixture.Create(userId: Guid.NewGuid()); LibraryOwnershipPolicyContext context = new(library.Id); - _mockUserRepository.GetByIdAsync(userId, Arg.Any()) + _mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any()) .Returns(Result.From(regularUser)); - _mockLibraryRepository.GetByIdAsync(context.LibraryId, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(context.LibraryId, cancellationToken: Arg.Any()) .Returns(Result.From(library)); // Act diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/Policies/Over18/Over18PolicyTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/Policies/Over18/Over18PolicyTests.cs index e21aec33..81eb3640 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/Policies/Over18/Over18PolicyTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/Policies/Over18/Over18PolicyTests.cs @@ -32,6 +32,7 @@ public class Over18PolicyTests public Over18PolicyTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockUserRepository = Substitute.For(); _mockUnitOfWork.UserRepository.Returns(_mockUserRepository); @@ -43,7 +44,7 @@ public class Over18PolicyTests { // Arrange UserEntity user = _userEntityFixture.Create(); - _mockUserRepository.GetByIdAsync(user.Id, Arg.Any()) + _mockUserRepository.GetByIdAsync(user.Id, cancellationToken: Arg.Any()) .Returns(Result.From(user)); // Act @@ -58,7 +59,7 @@ public class Over18PolicyTests { // Arrange Guid userId = Guid.NewGuid(); - _mockUserRepository.GetByIdAsync(userId, Arg.Any()) + _mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any()) .Returns(Result.From(null)); // Act @@ -73,7 +74,7 @@ public class Over18PolicyTests { // Arrange Guid userId = Guid.NewGuid(); - _mockUserRepository.GetByIdAsync(userId, Arg.Any()) + _mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any()) .Returns(Error.Failure("Database.Error", "Failed to retrieve user")); // Act @@ -88,7 +89,7 @@ public class Over18PolicyTests { // Arrange Guid userId = Guid.NewGuid(); - _mockUserRepository.GetByIdAsync(userId, Arg.Any()) + _mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any()) .Returns(Result.Success(null)); // Act diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJobTests.cs index 0a23ca9f..5a2e3bc1 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJobTests.cs @@ -2,7 +2,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Common.DataAccess.Repositories.Books; +using Lumina.Application.Common.DataAccess.Repositories.BookLibrary; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; @@ -139,7 +139,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests "Test Title", Arg.Any(), Arg.Any()); - BookArtworkEntity coverArtwork = Assert.Single(book.BookArtwork); + BookArtworkEntity coverArtwork = Assert.Single(book.Artwork); Assert.Equal(ArtworkType.Cover, coverArtwork.ArtworkType); Assert.Equal(0, coverArtwork.Ordinal); Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status); @@ -168,7 +168,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); // the book already has a stored cover with the same content hash as the resolved artwork - book.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, fileName: "existing\\cover.jpeg", contentHash: 123ul, status: ArtworkStatus.Pending, provider: "Old Provider", lastUpdateUtc: DateTime.UtcNow.AddDays(-1))]; + book.Artwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, fileName: "existing\\cover.jpeg", contentHash: 123ul, status: ArtworkStatus.Pending, provider: "Old Provider", lastUpdateUtc: DateTime.UtcNow.AddDays(-1))]; SetupSingleBookPage(book, artworkPluginId); _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); @@ -179,7 +179,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests // Assert // the identical artwork is not copied again, so the artwork storage service is not called and the stored file name is kept await mockBookArtworkService.DidNotReceive().SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); - BookArtworkEntity coverArtwork = Assert.Single(book.BookArtwork); + BookArtworkEntity coverArtwork = Assert.Single(book.Artwork); Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status); Assert.Equal("existing\\cover.jpeg", coverArtwork.FileName); Assert.Equal("Artwork Provider", coverArtwork.Provider); @@ -212,7 +212,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests // Assert await mockBookArtworkService.DidNotReceive().SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); - BookArtworkEntity coverArtwork = Assert.Single(book.BookArtwork); + BookArtworkEntity coverArtwork = Assert.Single(book.Artwork); Assert.Equal(ArtworkType.Cover, coverArtwork.ArtworkType); Assert.Equal(0, coverArtwork.Ordinal); Assert.Equal(ArtworkStatus.Failed, coverArtwork.Status); @@ -226,7 +226,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests // Arrange _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) .Returns(Result.From>([])); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); // Act await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); @@ -330,7 +330,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests _mockServiceScopeFactory.CreateAsyncScope().Returns(asyncServiceScope); ILibraryRepository mockLibraryRepository = Substitute.For(); - mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(_libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", canDownloadMetadataFromWeb: false))); _mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository); @@ -346,7 +346,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests .Returns(Result.From>([book]), Result.From>([])); _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); // Act await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); @@ -354,7 +354,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests // Assert // the provider that requires access to the web is skipped when the library does not permit web downloads await webProvider.DidNotReceive().GetArtworkAsync(Arg.Any(), Arg.Any()); - BookArtworkEntity coverArtwork = Assert.Single(book.BookArtwork); + BookArtworkEntity coverArtwork = Assert.Single(book.Artwork); Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status); Assert.Equal("Local Provider", coverArtwork.Provider); Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); @@ -377,7 +377,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests .Returns(Result.From>([_artworkConfigurationEntityFixture.Create(_libraryId.Value, artworkPluginId, 1)])); _mockBookRepository.GetBooksNeedingArtworkCountAsync(_libraryId.Value, Arg.Any()) .Returns(Error.Failure("Database.Error", "Failed to count the books that need artwork")); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); // Act await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); @@ -405,7 +405,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests .Returns(Result.From(1)); _mockBookRepository.GetBooksNeedingArtworkAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Error.Failure("Database.Error", "Failed to get the books that need artwork")); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); // Act await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); @@ -429,7 +429,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); ILibraryRepository mockLibraryRepository = Substitute.For(); - mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(_libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", canDownloadMetadataFromWeb: true))); _mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository); _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) @@ -440,7 +440,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests .Returns(Result.From>([book]), Result.From>([])); _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) .Returns(Error.Failure("Database.Error", "Failed to get the author display names")); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); // Act await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); @@ -465,7 +465,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - book.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, fileName: "existing\\cover.jpeg", contentHash: 123ul, status: ArtworkStatus.Pending, provider: "Old Provider", lastUpdateUtc: DateTime.UtcNow.AddDays(-1))]; + book.Artwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, fileName: "existing\\cover.jpeg", contentHash: 123ul, status: ArtworkStatus.Pending, provider: "Old Provider", lastUpdateUtc: DateTime.UtcNow.AddDays(-1))]; SetupSingleBookPage(book, artworkPluginId); _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); @@ -474,7 +474,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); // Assert - BookArtworkEntity coverArtwork = Assert.Single(book.BookArtwork); + BookArtworkEntity coverArtwork = Assert.Single(book.Artwork); Assert.Equal(ArtworkStatus.Failed, coverArtwork.Status); Assert.Equal("existing\\cover.jpeg", coverArtwork.FileName); Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); @@ -507,7 +507,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); // Assert - BookArtworkEntity coverArtwork = Assert.Single(book.BookArtwork); + BookArtworkEntity coverArtwork = Assert.Single(book.Artwork); Assert.Equal(ArtworkStatus.Failed, coverArtwork.Status); Assert.Null(coverArtwork.FileName); Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); @@ -532,7 +532,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - book.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, fileName: "existing\\cover.jpeg", contentHash: 111ul, status: ArtworkStatus.Pending, provider: "Old Provider", lastUpdateUtc: DateTime.UtcNow.AddDays(-1))]; + book.Artwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, fileName: "existing\\cover.jpeg", contentHash: 111ul, status: ArtworkStatus.Pending, provider: "Old Provider", lastUpdateUtc: DateTime.UtcNow.AddDays(-1))]; SetupSingleBookPage(book, artworkPluginId); _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); @@ -541,7 +541,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); // Assert - BookArtworkEntity coverArtwork = Assert.Single(book.BookArtwork); + BookArtworkEntity coverArtwork = Assert.Single(book.Artwork); Assert.Equal(ArtworkStatus.Failed, coverArtwork.Status); Assert.Equal("existing\\cover.jpeg", coverArtwork.FileName); Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); @@ -577,7 +577,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests // Assert // for remote artwork, the content hash is computed on the stored copy, so it is only known after the artwork is stored await mockBookArtworkService.Received(1).SaveBookArtworkAsync(_libraryId.Value, book.Id, "My Library", "Frank Herbert", Arg.Any(), Arg.Any(), Arg.Any()); - BookArtworkEntity coverArtwork = Assert.Single(book.BookArtwork); + BookArtworkEntity coverArtwork = Assert.Single(book.Artwork); Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status); Assert.Equal("\\media\\books\\Library\\Author\\Title\\cover.jpeg", coverArtwork.FileName); Assert.Equal(999ul, coverArtwork.ContentHash); @@ -605,7 +605,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); // the book has no known ISBNs of its own, so the artwork lookup is built without an ISBN BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub", title: "Test Title", includeMetadata: false); - book.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, fileName: "existing\\cover.jpeg", contentHash: 111ul, status: ArtworkStatus.Pending, provider: "Old Provider", lastUpdateUtc: DateTime.UtcNow.AddDays(-1))]; + book.Artwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, fileName: "existing\\cover.jpeg", contentHash: 111ul, status: ArtworkStatus.Pending, provider: "Old Provider", lastUpdateUtc: DateTime.UtcNow.AddDays(-1))]; SetupSingleBookPage(book, artworkPluginId); // the author of the book is not known, so its artwork directory falls back to an empty author name _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) @@ -623,7 +623,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests "Test Title", Arg.Any(), Arg.Any()); - BookArtworkEntity coverArtwork = Assert.Single(book.BookArtwork); + BookArtworkEntity coverArtwork = Assert.Single(book.Artwork); Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status); Assert.Equal("\\media\\books\\Library\\Author\\Title\\cover.jpeg", coverArtwork.FileName); Assert.Equal(222ul, coverArtwork.ContentHash); @@ -669,7 +669,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); ILibraryRepository mockLibraryRepository = Substitute.For(); - mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(_libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", canDownloadMetadataFromWeb: true))); _mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository); @@ -682,7 +682,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests .Returns(Result.From(1)); _mockBookRepository.GetBooksNeedingArtworkAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Result.From>([book]), Result.From>([])); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); @@ -691,7 +691,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests // Assert // a failing artwork provider must not prevent the artwork of the other provider from being used - BookArtworkEntity coverArtwork = Assert.Single(book.BookArtwork); + BookArtworkEntity coverArtwork = Assert.Single(book.Artwork); Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status); Assert.Equal("Second Provider", coverArtwork.Provider); Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); @@ -735,7 +735,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); ILibraryRepository mockLibraryRepository = Substitute.For(); - mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(_libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", canDownloadMetadataFromWeb: true))); _mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository); @@ -748,7 +748,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests .Returns(Result.From(1)); _mockBookRepository.GetBooksNeedingArtworkAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Result.From>([book]), Result.From>([])); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); @@ -757,7 +757,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests // Assert // a provider that returns remote artwork must require web access, so its artwork is skipped and the next provider is used - BookArtworkEntity coverArtwork = Assert.Single(book.BookArtwork); + BookArtworkEntity coverArtwork = Assert.Single(book.Artwork); Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status); Assert.Equal("Second Provider", coverArtwork.Provider); Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); @@ -769,7 +769,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests // Arrange _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) .Returns(Result.From>([])); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); IMediaLibraryScanJob mockChildJob = Substitute.For(); mockChildJob.ExecuteAsync(Arg.Any(), Arg.Any(), Arg.Any()) @@ -815,7 +815,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests private void SetupSingleBookPage(BookEntity book, Guid artworkPluginId) { ILibraryRepository mockLibraryRepository = Substitute.For(); - mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(_libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", canDownloadMetadataFromWeb: true))); _mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository); @@ -827,6 +827,6 @@ public class MediaLibraryScanArtworkEnrichmentJobTests .Returns(Result.From(1)); _mockBookRepository.GetBooksNeedingArtworkAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Result.From>([book]), Result.From>([])); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); } } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanDiffJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanDiffJobTests.cs index 8b60619f..d9b0fd19 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanDiffJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanDiffJobTests.cs @@ -55,6 +55,7 @@ public class MediaLibraryScanDiffJobTests _mockServiceScope.ServiceProvider.Returns(_mockServiceProvider); _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockStagingResultsRepository = Substitute.For(); _mockUnitOfWork.LibraryScanStagingResultsRepository.Returns(_mockStagingResultsRepository); _mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork); diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanHashJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanHashJobTests.cs index 8fb60013..8630e88d 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanHashJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanHashJobTests.cs @@ -62,6 +62,7 @@ public class MediaLibraryScanHashJobTests _mockServiceScope.ServiceProvider.Returns(_mockServiceProvider); _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockStagingResultsRepository = Substitute.For(); _mockUnitOfWork.LibraryScanStagingResultsRepository.Returns(_mockStagingResultsRepository); _mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork); diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJobTests.cs index 01776927..d315fb11 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJobTests.cs @@ -4,7 +4,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; -using Lumina.Application.Common.DataAccess.Repositories.Books; +using Lumina.Application.Common.DataAccess.Repositories.BookLibrary; using Lumina.Application.Common.DataAccess.Repositories.MediaContributors; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.Repositories.Plugins; @@ -127,7 +127,7 @@ public class MediaLibraryScanMetadataEnrichmentJobTests .Returns(Result.From(0)); _mockBookRepository.GetBooksNeedingMetadataAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Result.From>([])); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); // Act await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); @@ -144,7 +144,7 @@ public class MediaLibraryScanMetadataEnrichmentJobTests // Arrange _mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) .Returns(Result.From>([])); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); // Act await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); @@ -339,8 +339,8 @@ public class MediaLibraryScanMetadataEnrichmentJobTests IMetadataProvider firstProvider = Substitute.For(); firstProvider.Name.Returns("First Provider"); firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - MediaContributorDto author = _mediaContributorDtoFixture.Create(displayName: "Frank Herbert", roleName: "Author", roleCategory: MediaContributorRoleCategory.Author); - MediaContributorDto translator = _mediaContributorDtoFixture.Create(displayName: "Jane Translator", roleName: "Translator", roleCategory: MediaContributorRoleCategory.Translator); + MediaContributorDto author = _mediaContributorDtoFixture.Create(displayName: "Frank Herbert", role: MediaContributorRole.Author); + MediaContributorDto translator = _mediaContributorDtoFixture.Create(displayName: "Jane Translator", role: MediaContributorRole.Translator); firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) .Returns(_bookMetadataDtoFixture.Create(title: "First Title", contributors: [author, translator])); @@ -362,15 +362,13 @@ public class MediaLibraryScanMetadataEnrichmentJobTests await _mockMediaContributorRepository.Received(1).FindOrCreateByDisplayNameAsync("Frank Herbert", Arg.Any(), Arg.Any()); await _mockMediaContributorRepository.Received(1).FindOrCreateByDisplayNameAsync("Jane Translator", Arg.Any(), Arg.Any()); - // the participation rows are replaced on the entity, carrying the role and the category of each contributor - Assert.Equal(2, book.BookContributors.Count); - BookContributorEntity linkedAuthor = Assert.Single(book.BookContributors, contributor => contributor.MediaContributorId == authorEntity.Id); - Assert.Equal("Author", linkedAuthor.RoleName); - Assert.Equal(MediaContributorRoleCategory.Author, linkedAuthor.RoleCategory); + // the participation rows are replaced on the entity, carrying the canonical role of each contributor + Assert.Equal(2, book.Contributors.Count); + BookContributorEntity linkedAuthor = Assert.Single(book.Contributors, contributor => contributor.MediaContributorId == authorEntity.Id); + Assert.Equal(MediaContributorRole.Author, linkedAuthor.Role); Assert.Equal(book.Id, linkedAuthor.BookId); - BookContributorEntity linkedTranslator = Assert.Single(book.BookContributors, contributor => contributor.MediaContributorId == translatorEntity.Id); - Assert.Equal("Translator", linkedTranslator.RoleName); - Assert.Equal(MediaContributorRoleCategory.Translator, linkedTranslator.RoleCategory); + BookContributorEntity linkedTranslator = Assert.Single(book.Contributors, contributor => contributor.MediaContributorId == translatorEntity.Id); + Assert.Equal(MediaContributorRole.Translator, linkedTranslator.Role); Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus); } @@ -382,7 +380,7 @@ public class MediaLibraryScanMetadataEnrichmentJobTests IMetadataProvider firstProvider = Substitute.For(); firstProvider.Name.Returns("First Provider"); firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - MediaContributorDto author = _mediaContributorDtoFixture.Create(displayName: "Frank Herbert", roleName: "Author", roleCategory: MediaContributorRoleCategory.Author); + MediaContributorDto author = _mediaContributorDtoFixture.Create(displayName: "Frank Herbert", role: MediaContributorRole.Author); firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) .Returns(_bookMetadataDtoFixture.Create(title: "First Title", contributors: [author])); @@ -396,7 +394,7 @@ public class MediaLibraryScanMetadataEnrichmentJobTests .Returns(Result.From(2)); _mockBookRepository.GetBooksNeedingMetadataAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Result.From>([firstBook, secondBook]), Result.From>([])); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); MediaContributorEntity authorEntity = _mediaContributorEntityFixture.Create(displayName: "Frank Herbert"); _mockMediaContributorRepository.FindOrCreateByDisplayNameAsync("Frank Herbert", Arg.Any(), Arg.Any()) @@ -408,10 +406,10 @@ public class MediaLibraryScanMetadataEnrichmentJobTests // Assert // the contributor cache of the page guarantees a single contributor per person, so the repository is queried only once await _mockMediaContributorRepository.Received(1).FindOrCreateByDisplayNameAsync("Frank Herbert", Arg.Any(), Arg.Any()); - Assert.Single(firstBook.BookContributors); - Assert.Single(secondBook.BookContributors); - Assert.Equal(authorEntity.Id, firstBook.BookContributors[0].MediaContributorId); - Assert.Equal(authorEntity.Id, secondBook.BookContributors[0].MediaContributorId); + Assert.Single(firstBook.Contributors); + Assert.Single(secondBook.Contributors); + Assert.Equal(authorEntity.Id, firstBook.Contributors[0].MediaContributorId); + Assert.Equal(authorEntity.Id, secondBook.Contributors[0].MediaContributorId); } [Fact] @@ -435,7 +433,7 @@ public class MediaLibraryScanMetadataEnrichmentJobTests SetupRealServiceProviderForProviders(localPluginId, localProvider, webPluginId, webProvider, shouldAggregateMetadataWhenMissing: false); ILibraryRepository mockLibraryRepository = Substitute.For(); - mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(_libraryEntityFixture.Create(title: "My Library", canDownloadMetadataFromWeb: false))); _mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository); @@ -473,7 +471,7 @@ public class MediaLibraryScanMetadataEnrichmentJobTests SetupRealServiceProviderForProviders(localPluginId, localProvider, webPluginId, webProvider, shouldAggregateMetadataWhenMissing: false); ILibraryRepository mockLibraryRepository = Substitute.For(); - mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(_libraryEntityFixture.Create(title: "My Library", canDownloadMetadataFromWeb: true))); _mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository); @@ -503,7 +501,7 @@ public class MediaLibraryScanMetadataEnrichmentJobTests .Returns(Result.From>([_configurationEntityFixture.Create(_libraryId.Value, firstPluginId, 1)])); _mockBookRepository.GetBooksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any()) .Returns(Error.Failure("Database.Error", "Failed to count the books to enrich")); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); // Act await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); @@ -528,7 +526,7 @@ public class MediaLibraryScanMetadataEnrichmentJobTests .Returns(Result.From(1)); _mockBookRepository.GetBooksNeedingMetadataAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Error.Failure("Database.Error", "Failed to get the books to enrich")); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); // Act await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); @@ -607,7 +605,7 @@ public class MediaLibraryScanMetadataEnrichmentJobTests IMetadataProvider firstProvider = Substitute.For(); firstProvider.Name.Returns("First Provider"); firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - MediaContributorDto namelessContributor = _mediaContributorDtoFixture.Create(roleName: "Author", roleCategory: MediaContributorRoleCategory.Author) with { Name = null }; + MediaContributorDto namelessContributor = _mediaContributorDtoFixture.Create(role: MediaContributorRole.Author) with { Name = null }; firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) .Returns(_bookMetadataDtoFixture.Create(title: "First Title", contributors: [namelessContributor])); @@ -621,7 +619,7 @@ public class MediaLibraryScanMetadataEnrichmentJobTests // Assert // a contributor without a display name cannot be linked to the book, so no contributor is queried or created await _mockMediaContributorRepository.DidNotReceive().FindOrCreateByDisplayNameAsync(Arg.Any(), Arg.Any(), Arg.Any()); - Assert.Empty(book.BookContributors); + Assert.Empty(book.Contributors); Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus); Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); } @@ -650,9 +648,9 @@ public class MediaLibraryScanMetadataEnrichmentJobTests await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); // Assert - BookContributorEntity linkedContributor = Assert.Single(book.BookContributors); - Assert.Equal("Contributor", linkedContributor.RoleName); - Assert.Equal(MediaContributorRoleCategory.Other, linkedContributor.RoleCategory); + // a contributor without a role is linked with the default canonical role + BookContributorEntity linkedContributor = Assert.Single(book.Contributors); + Assert.Equal(MediaContributorRole.Author, linkedContributor.Role); Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus); Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); } @@ -665,7 +663,7 @@ public class MediaLibraryScanMetadataEnrichmentJobTests IMetadataProvider firstProvider = Substitute.For(); firstProvider.Name.Returns("First Provider"); firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - MediaContributorDto author = _mediaContributorDtoFixture.Create(displayName: "Frank Herbert", roleName: "Author", roleCategory: MediaContributorRoleCategory.Author); + MediaContributorDto author = _mediaContributorDtoFixture.Create(displayName: "Frank Herbert", role: MediaContributorRole.Author); firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) .Returns(_bookMetadataDtoFixture.Create(title: "First Title", contributors: [author])); @@ -689,7 +687,7 @@ public class MediaLibraryScanMetadataEnrichmentJobTests // Arrange _mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) .Returns(Result.From>([])); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); IMediaLibraryScanJob mockChildJob = Substitute.For(); mockChildJob.ExecuteAsync(Arg.Any(), Arg.Any(), Arg.Any()) @@ -747,6 +745,6 @@ public class MediaLibraryScanMetadataEnrichmentJobTests .Returns(Result.From(1)); _mockBookRepository.GetBooksNeedingMetadataAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Result.From>([book]), Result.From>([])); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); } } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanProviderConfigurationInvalidationJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanProviderConfigurationInvalidationJobTests.cs index ff984873..84ef1735 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanProviderConfigurationInvalidationJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanProviderConfigurationInvalidationJobTests.cs @@ -2,7 +2,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; -using Lumina.Application.Common.DataAccess.Repositories.Books; +using Lumina.Application.Common.DataAccess.Repositories.BookLibrary; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Users; @@ -219,7 +219,7 @@ public class MediaLibraryScanProviderConfigurationInvalidationJobTests public async Task ExecuteAsync_WhenGettingTheLibraryFails_ShouldMarkJobAsFailedAndPublishFailureEvent() { // Arrange - _mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) .Returns(Error.Failure("Database.Error", "Failed to get the media library")); SetupConfigurations(); @@ -254,7 +254,7 @@ public class MediaLibraryScanProviderConfigurationInvalidationJobTests public async Task ExecuteAsync_WhenLibraryDoesNotExist_ShouldMarkJobAsFailedAndPublishFailureEvent() { // Arrange - _mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(null)); // Act @@ -413,10 +413,10 @@ public class MediaLibraryScanProviderConfigurationInvalidationJobTests /// The artwork provider configurations of the media library. private void SetupLibraryAndConfigurations(LibraryEntity library, List? metadataConfigurations = null, List? artworkConfigurations = null) { - _mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(library)); SetupConfigurations(metadataConfigurations, artworkConfigurations); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); } /// diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJobTests.cs index 7704dc1a..ccc0f5ee 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJobTests.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; -using Lumina.Application.Common.DataAccess.Repositories.Books; +using Lumina.Application.Common.DataAccess.Repositories.BookLibrary; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Domain.Common.Events; @@ -106,7 +106,7 @@ public class MediaLibraryScanResultsSaveJobTests .Returns(Result.From(null)); _mockBookRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(Result.Created)); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); // Act await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); @@ -133,7 +133,7 @@ public class MediaLibraryScanResultsSaveJobTests .Returns(Result.From(Result.Updated)); _mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any()) .Returns(Result.From>([])); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); // Act await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); @@ -158,7 +158,7 @@ public class MediaLibraryScanResultsSaveJobTests .Returns(Result.From>(["existing.pdf"])); _mockBookRepository.GetByPathAsync(_libraryId.Value, "existing.pdf", Arg.Any()) .Returns(Result.From(_bookEntityFixture.Create(path: "existing.pdf"))); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); // Act await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); @@ -356,7 +356,7 @@ public class MediaLibraryScanResultsSaveJobTests .Returns(Result.From(Result.Updated)); _mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any()) .Returns(Result.From>([])); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); IMediaLibraryScanJob mockChild = Substitute.For(); mockChild.ExecuteAsync(Arg.Any(), Arg.Any(), Arg.Any()) @@ -389,7 +389,7 @@ public class MediaLibraryScanResultsSaveJobTests .Returns(Result.From(null)); _mockBookRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(Result.Created)); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); // Act await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/MediaLibraryProviderConfigurationStoreTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/MediaLibraryProviderConfigurationStoreTests.cs index d44a916c..6f31de34 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/MediaLibraryProviderConfigurationStoreTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/MediaLibraryProviderConfigurationStoreTests.cs @@ -1,4 +1,4 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; @@ -45,6 +45,7 @@ public class MediaLibraryProviderConfigurationStoreTests public MediaLibraryProviderConfigurationStoreTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockMetadataConfigurationRepository = Substitute.For(); _mockArtworkConfigurationRepository = Substitute.For(); _mockBookReaderConfigurationRepository = Substitute.For(); diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginDetectionSyncJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginDetectionSyncJobTests.cs index 864eb16e..ffb41c8d 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginDetectionSyncJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginDetectionSyncJobTests.cs @@ -4,6 +4,8 @@ using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Infrastructure.Plugins; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; @@ -62,6 +64,7 @@ public class PluginDetectionSyncJobTests _mockServiceScope.ServiceProvider.Returns(_mockServiceProvider); _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockPluginRepository = Substitute.For(); _mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository); _mockLibraryRepository = Substitute.For(); @@ -187,8 +190,8 @@ public class PluginDetectionSyncJobTests .Returns(Result.From(Result.Updated)); PluginEntity loadedPluginRow = _pluginEntityFixture.Create(id: loadedPlugin.Id, name: loadedPlugin.Name, loadStatus: PluginLoadStatus.Loaded); PluginEntity stalePluginRow = _pluginEntityFixture.Create(name: "Stale Plugin", loadStatus: PluginLoadStatus.Loaded); - _mockPluginRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From((IEnumerable)[loadedPluginRow, stalePluginRow])); + _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [loadedPluginRow, stalePluginRow], CurrentPage = 1, PerPage = 2, Count = 2, NumberOfPages = 1 })); _mockPluginRepository.DeleteByIdAsync(Arg.Any(), Arg.Any()) .Returns(Result.Deleted); PluginDetectionSyncJob sut = CreateSut(); @@ -213,8 +216,8 @@ public class PluginDetectionSyncJobTests _mockPluginRepository.UpsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(Result.Updated)); LibraryEntity bookLibrary = _libraryEntityFixture.Create(libraryType: LibraryType.Book); - _mockLibraryRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From((IEnumerable)[bookLibrary])); + _mockLibraryRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [bookLibrary], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 })); _mockProviderConfigurationStore.EnsureProviderConfigurationsAsync(Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Result.Success); PluginDetectionSyncJob sut = CreateSut(); @@ -240,8 +243,8 @@ public class PluginDetectionSyncJobTests assemblyName: "MyPlugin", errorMessage: "Failed to load plugin assembly 'MyPlugin.dll': unexpected error"); PluginEntity staleLoadedRow = _pluginEntityFixture.Create(id: previouslyLoadedPlugin.Id, name: previouslyLoadedPlugin.Name, loadStatus: PluginLoadStatus.Loaded); - _mockPluginRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From((IEnumerable)[staleLoadedRow])); + _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [staleLoadedRow], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 })); _mockPluginRepository.DeleteByIdAsync(previouslyLoadedPlugin.Id, Arg.Any()) .Returns(Result.Deleted); PluginDetectionSyncJob sut = CreateSut([loadError]); diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginSettingsStoreTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginSettingsStoreTests.cs index 2679838f..d181af21 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginSettingsStoreTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginSettingsStoreTests.cs @@ -35,6 +35,7 @@ public class PluginSettingsStoreTests public PluginSettingsStoreTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockPluginRepository = Substitute.For(); _mockLogger = Substitute.For>(); _mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository); @@ -49,7 +50,7 @@ public class PluginSettingsStoreTests Guid pluginId = Guid.NewGuid(); Dictionary expectedSettings = new() { ["ApiKey"] = "test-key", ["Enabled"] = "true" }; PluginEntity pluginEntity = _pluginEntityFixture.Create(id: pluginId, settingsJson: JsonSerializer.Serialize(expectedSettings)); - _mockPluginRepository.GetByIdAsync(pluginId, Arg.Any()) + _mockPluginRepository.GetByIdAsync(pluginId, cancellationToken: Arg.Any()) .Returns(Result.From(pluginEntity)); // Act @@ -66,7 +67,7 @@ public class PluginSettingsStoreTests // Arrange Guid pluginId = Guid.NewGuid(); PluginEntity pluginEntity = _pluginEntityFixture.Create(id: pluginId, includeSettingsJson: false); - _mockPluginRepository.GetByIdAsync(pluginId, Arg.Any()) + _mockPluginRepository.GetByIdAsync(pluginId, cancellationToken: Arg.Any()) .Returns(Result.From(pluginEntity)); // Act @@ -81,7 +82,7 @@ public class PluginSettingsStoreTests { // Arrange Guid pluginId = Guid.NewGuid(); - _mockPluginRepository.GetByIdAsync(pluginId, Arg.Any()) + _mockPluginRepository.GetByIdAsync(pluginId, cancellationToken: Arg.Any()) .Returns(Result.From(null)); // Act @@ -96,7 +97,7 @@ public class PluginSettingsStoreTests { // Arrange Guid pluginId = Guid.NewGuid(); - _mockPluginRepository.GetByIdAsync(pluginId, Arg.Any()) + _mockPluginRepository.GetByIdAsync(pluginId, cancellationToken: Arg.Any()) .Returns(Error.Failure("Database.Error", "Failed to retrieve the plugin")); // Act diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/ScheduledJobSchedulerJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/ScheduledJobSchedulerJobTests.cs index 63b116b2..5855411a 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/ScheduledJobSchedulerJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/ScheduledJobSchedulerJobTests.cs @@ -4,6 +4,8 @@ using Lumina.Application.Common.DataAccess.Entities.Themes; using Lumina.Application.Common.DataAccess.Repositories.Scheduling; using Lumina.Application.Common.DataAccess.Repositories.Themes; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Infrastructure.Themes; using Lumina.Application.Common.Infrastructure.Time; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling; @@ -73,7 +75,7 @@ public class ScheduledJobSchedulerJobTests _mockScheduledJobExecutionRepository = Substitute.For(); _mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository); _mockUnitOfWork.ScheduledJobExecutionRepository.Returns(_mockScheduledJobExecutionRepository); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockScheduledJobRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.Updated); _mockScheduledJobExecutionRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.Updated); @@ -132,7 +134,7 @@ public class ScheduledJobSchedulerJobTests { // Arrange ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(runningJob); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); // Act @@ -152,7 +154,7 @@ public class ScheduledJobSchedulerJobTests // Arrange ScheduledJobEntity addedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(addedJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(addedJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(addedJob); _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(_scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60)); // Act @@ -169,7 +171,7 @@ public class ScheduledJobSchedulerJobTests // Arrange ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(activeJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(activeJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(activeJob); _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(_scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60)); using CancellationTokenSource cycleCancellationTokenSource = new(); _runtimeRegistry.TryStartCycle(scheduledJobId, cycleCancellationTokenSource); @@ -190,7 +192,7 @@ public class ScheduledJobSchedulerJobTests ScheduledJobEntity addedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(addedJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(addedJob, runningJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(addedJob, runningJob); ScheduledJobExecutionEntity openExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: runningJob.Id, isCycleRun: false, wasCycleActive: true, completedOnUtc: null); _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(Arg.Any(), Arg.Any()).Returns(openExecution); _mockDomainEventPublisher.When(publisher => publisher.PublishAsync(Arg.Is(_ => true), Arg.Any())) @@ -213,7 +215,7 @@ public class ScheduledJobSchedulerJobTests // Arrange ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(runningJob); ScheduledJobExecutionEntity openExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: runningJob.Id, isCycleRun: false, wasCycleActive: true, completedOnUtc: null); _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(Arg.Any(), Arg.Any()).Returns(openExecution); @@ -233,7 +235,7 @@ public class ScheduledJobSchedulerJobTests // Arrange ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(runningJob); ScheduledJobExecutionEntity openExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: runningJob.Id, isCycleRun: false, wasCycleActive: false, completedOnUtc: null); _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(Arg.Any(), Arg.Any()).Returns(openExecution); @@ -252,7 +254,7 @@ public class ScheduledJobSchedulerJobTests // Arrange ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(activeJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(activeJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(activeJob); // Act ScheduledJobStatus result = await InvokeAsync("ReconcileInterruptedRunAsync", scheduledJobId, CancellationToken.None); @@ -269,7 +271,7 @@ public class ScheduledJobSchedulerJobTests // Arrange ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.OnceAtStartup); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(activeJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(activeJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(activeJob); _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(_scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.OnceAtStartup)); // Act @@ -288,7 +290,7 @@ public class ScheduledJobSchedulerJobTests ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.OnceAtStartup); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(activeJob.Id); _mockScheduledJobRepository.GetActiveOrRunningAsync(Arg.Any()).Returns(new[] { activeJob }); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(activeJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(activeJob); _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(_scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.OnceAtStartup)); // Act @@ -340,7 +342,7 @@ public class ScheduledJobSchedulerJobTests IThemeService mockThemeService = Substitute.For(); mockThemeService.GetBundledThemeArchivePaths().Returns([]); IThemeRepository mockThemeRepository = Substitute.For(); - mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From(Enumerable.Empty())); + mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); _mockUnitOfWork.ThemeRepository.Returns(mockThemeRepository); _services[typeof(IThemeService)] = mockThemeService; @@ -349,7 +351,7 @@ public class ScheduledJobSchedulerJobTests // Assert mockThemeService.Received(1).GetBundledThemeArchivePaths(); - await mockThemeRepository.Received(1).GetAllAsync(Arg.Any()); + await mockThemeRepository.Received(1).GetAllAsync(cancellationToken: Arg.Any()); } [Fact] @@ -391,7 +393,7 @@ public class ScheduledJobSchedulerJobTests IThemeService mockThemeService = Substitute.For(); mockThemeService.GetBundledThemeArchivePaths().Returns([]); IThemeRepository mockThemeRepository = Substitute.For(); - mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From(Enumerable.Empty())); + mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); _mockUnitOfWork.ThemeRepository.Returns(mockThemeRepository); _services[typeof(IThemeService)] = mockThemeService; using CancellationTokenSource cancellationTokenSource = new(); @@ -412,7 +414,7 @@ public class ScheduledJobSchedulerJobTests ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(activeJob.Id); Error error = Error.Failure("ScheduledJobs.NotFound", "Failed to read the scheduled job"); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(error); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(error); // Act await InvokeAsync("RunCycleWorkerAsync", scheduledJobId, false, CancellationToken.None); @@ -428,7 +430,7 @@ public class ScheduledJobSchedulerJobTests // Arrange ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(activeJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(activeJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(activeJob); using CancellationTokenSource cancellationTokenSource = new(); cancellationTokenSource.Cancel(); @@ -445,7 +447,7 @@ public class ScheduledJobSchedulerJobTests // Arrange ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(); Error error = Error.Failure("ScheduledJobs.NotFound", "Failed to read the scheduled job"); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(error); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(error); // Act await InvokeAsync("ExecuteScheduledJobRunAsync", scheduledJobId, false, CancellationToken.None); @@ -462,7 +464,7 @@ public class ScheduledJobSchedulerJobTests // An interval schedule whose interval is not positive cannot be converted to its domain object. ScheduledJobEntity invalidJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 0); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(invalidJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(invalidJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(invalidJob); // Act await InvokeAsync("ExecuteScheduledJobRunAsync", scheduledJobId, false, CancellationToken.None); @@ -478,7 +480,7 @@ public class ScheduledJobSchedulerJobTests // Arrange ScheduledJobEntity addedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(addedJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(addedJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(addedJob); using CancellationTokenSource cancellationTokenSource = new(); _mockDomainEventPublisher.When(publisher => publisher.PublishAsync(Arg.Any(), Arg.Any())) .Do(_ => cancellationTokenSource.Cancel()); @@ -496,7 +498,7 @@ public class ScheduledJobSchedulerJobTests // Arrange ScheduledJobEntity addedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(addedJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(addedJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(addedJob); _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(_scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60)); _mockTaskExecutor.ExecutePayloadAsync(Arg.Any(), Arg.Any()) .Returns(Error.Failure("Task.Failed", "The task of the scheduled job failed.")); @@ -515,7 +517,7 @@ public class ScheduledJobSchedulerJobTests // Arrange ScheduledJobEntity addedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(addedJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(addedJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(addedJob); _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(_scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60)); _mockTaskExecutor.ExecutePayloadAsync(Arg.Any(), Arg.Any()) .Returns(Task.FromException>(new InvalidOperationException("The task threw."))); @@ -533,7 +535,7 @@ public class ScheduledJobSchedulerJobTests // Arrange ScheduledJobEntity addedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(addedJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(addedJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(addedJob); _mockTaskExecutor.ExecutePayloadAsync(Arg.Any(), Arg.Any()) .Returns(Task.FromException>(new OperationCanceledException())); @@ -550,7 +552,7 @@ public class ScheduledJobSchedulerJobTests // Arrange ScheduledJobEntity addedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(addedJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(addedJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(addedJob); using CancellationTokenSource cancellationTokenSource = new(); _mockTaskExecutor.When(executor => executor.ExecutePayloadAsync(Arg.Any(), Arg.Any())) .Do(_ => cancellationTokenSource.Cancel()); @@ -570,7 +572,7 @@ public class ScheduledJobSchedulerJobTests // Arrange ScheduledJobEntity addedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(addedJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(addedJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(addedJob); Assert.True(_runtimeRegistry.TryAcquireRunSlot(scheduledJobId)); // Act @@ -589,7 +591,7 @@ public class ScheduledJobSchedulerJobTests ScheduledJobEntity addedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(addedJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(addedJob, runningJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(addedJob, runningJob); _mockDomainEventPublisher.When(publisher => publisher.PublishAsync(Arg.Any(), Arg.Any())) .Do(_ => throw new OperationCanceledException()); @@ -659,7 +661,7 @@ public class ScheduledJobSchedulerJobTests // Arrange ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(runningJob); _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(runningJob); ScheduledJobExecutionEntity openExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: runningJob.Id, isCycleRun: false, wasCycleActive: true, completedOnUtc: null); _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(Arg.Any(), Arg.Any()).Returns(openExecution); @@ -681,7 +683,7 @@ public class ScheduledJobSchedulerJobTests { // Arrange ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Error.Failure("ScheduledJobs.NotFound", "Failed to read the scheduled job")); // Act @@ -697,7 +699,7 @@ public class ScheduledJobSchedulerJobTests // Arrange ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(runningJob); _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(Arg.Any(), Arg.Any()) .Returns(Error.Failure("ScheduledJobExecutions.NotFound", "Failed to read the open execution")); @@ -736,7 +738,7 @@ public class ScheduledJobSchedulerJobTests // Arrange ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(runningJob); _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(null)); @@ -755,7 +757,7 @@ public class ScheduledJobSchedulerJobTests // Arrange ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(runningJob); ScheduledJobExecutionEntity openExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: runningJob.Id, isCycleRun: false, wasCycleActive: true, completedOnUtc: null); _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(Arg.Any(), Arg.Any()).Returns(openExecution); _mockScheduledJobRepository.UpdateAsync(Arg.Any(), Arg.Any()) @@ -775,7 +777,7 @@ public class ScheduledJobSchedulerJobTests // Arrange ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(runningJob); ScheduledJobExecutionEntity openExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: runningJob.Id, isCycleRun: false, wasCycleActive: true, completedOnUtc: null); _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(Arg.Any(), Arg.Any()).Returns(openExecution); _mockScheduledJobExecutionRepository.UpdateAsync(Arg.Any(), Arg.Any()) @@ -795,10 +797,10 @@ public class ScheduledJobSchedulerJobTests // Arrange ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(runningJob); ScheduledJobExecutionEntity openExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: runningJob.Id, isCycleRun: false, wasCycleActive: true, completedOnUtc: null); _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(Arg.Any(), Arg.Any()).Returns(openExecution); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.FromException(new InvalidOperationException("Save failed"))); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.FromException>(new InvalidOperationException("Save failed"))); // Act ScheduledJobStatus result = await InvokeAsync("ReconcileInterruptedRunAsync", scheduledJobId, CancellationToken.None); @@ -813,10 +815,10 @@ public class ScheduledJobSchedulerJobTests // Arrange ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(runningJob); ScheduledJobExecutionEntity openExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: runningJob.Id, isCycleRun: false, wasCycleActive: true, completedOnUtc: null); _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(Arg.Any(), Arg.Any()).Returns(openExecution); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.FromException(new OperationCanceledException())); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.FromException>(new OperationCanceledException())); // Act ScheduledJobStatus result = await InvokeAsync("ReconcileInterruptedRunAsync", scheduledJobId, CancellationToken.None); @@ -846,7 +848,7 @@ public class ScheduledJobSchedulerJobTests ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); _mockScheduledJobRepository.GetActiveOrRunningAsync(Arg.Any()).Returns(new[] { runningJob }); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(runningJob); ScheduledJobExecutionEntity openExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: runningJob.Id, isCycleRun: false, wasCycleActive: false, completedOnUtc: null); _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(Arg.Any(), Arg.Any()).Returns(openExecution); @@ -868,7 +870,7 @@ public class ScheduledJobSchedulerJobTests ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); _mockScheduledJobRepository.GetActiveOrRunningAsync(Arg.Any()).Returns(new[] { runningJob }); // The first read reconciles the interrupted run while the job is still running; the reads made by the resumed cycle observe the reconciled active status. - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(runningJob, activeJob, activeJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(runningJob, activeJob, activeJob); _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(_scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.OnceAtStartup)); ScheduledJobExecutionEntity openExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: runningJob.Id, isCycleRun: false, wasCycleActive: true, completedOnUtc: null); _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(Arg.Any(), Arg.Any()).Returns(openExecution); @@ -888,7 +890,7 @@ public class ScheduledJobSchedulerJobTests ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(activeJob.Id); _mockScheduledJobRepository.GetActiveOrRunningAsync(Arg.Any()).Returns(new[] { activeJob }); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(activeJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(activeJob); // Act await InvokeAsync("ResumeActiveCyclesAsync", CancellationToken.None); @@ -907,7 +909,7 @@ public class ScheduledJobSchedulerJobTests ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(activeJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(activeJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(activeJob); _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(runningJob); RegisterDateTimeProvider(); IScheduledJobCycleTicker mockCycleTicker = Substitute.For(); @@ -931,7 +933,7 @@ public class ScheduledJobSchedulerJobTests ScheduledJobEntity dailyJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.DailyAtHourAndMinute, hour: 10, minute: 30); ScheduledJobEntity runningDailyJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.DailyAtHourAndMinute, hour: 10, minute: 30); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(dailyJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(dailyJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(dailyJob); _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(runningDailyJob); RegisterDateTimeProvider(); IScheduledJobCycleTicker mockCycleTicker = Substitute.For(); @@ -955,7 +957,7 @@ public class ScheduledJobSchedulerJobTests ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(activeJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(activeJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(activeJob); _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(runningJob); RegisterDateTimeProvider(); _mockTaskExecutor.ExecutePayloadAsync(Arg.Any(), Arg.Any()) @@ -981,7 +983,7 @@ public class ScheduledJobSchedulerJobTests // Arrange ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(activeJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(activeJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(activeJob); RegisterDateTimeProvider(); using CancellationTokenSource cancellationTokenSource = new(); cancellationTokenSource.Cancel(); @@ -1000,7 +1002,7 @@ public class ScheduledJobSchedulerJobTests // Arrange ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(activeJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(activeJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(activeJob); RegisterDateTimeProvider(); IScheduledJobCycleTicker mockCycleTicker = Substitute.For(); mockCycleTicker.WaitForNextTickAsync(Arg.Any()) @@ -1038,7 +1040,7 @@ public class ScheduledJobSchedulerJobTests // An interval schedule whose interval is not positive cannot be converted to its domain object. ScheduledJobEntity invalidJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 0); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(invalidJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(invalidJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(invalidJob); // Act Schedule? result = await InvokeAsync("GetScheduleAsync", scheduledJobId, CancellationToken.None); diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/CleanScheduledJobExecutionHistoryTaskExecutorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/CleanScheduledJobExecutionHistoryTaskExecutorTests.cs index 0cbb40d1..cf830d78 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/CleanScheduledJobExecutionHistoryTaskExecutorTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/CleanScheduledJobExecutionHistoryTaskExecutorTests.cs @@ -37,6 +37,7 @@ public class CleanScheduledJobExecutionHistoryTaskExecutorTests { _mockDateTimeProvider = Substitute.For(); _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockScheduledJobExecutionRepository = Substitute.For(); _mockDateTimeProvider.UtcNow.Returns(_fixedUtcNow); _mockUnitOfWork.ScheduledJobExecutionRepository.Returns(_mockScheduledJobExecutionRepository); diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/MediaLibraryScanTaskExecutorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/MediaLibraryScanTaskExecutorTests.cs index ed5ca893..8e5ff46a 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/MediaLibraryScanTaskExecutorTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/MediaLibraryScanTaskExecutorTests.cs @@ -44,7 +44,7 @@ public class MediaLibraryScanTaskExecutorTests _mockLibraryRepository.GetAllEnabledAndUnlockedAsync(Arg.Any()) .Returns(Result.From>([])); _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockDomainEventPublisher = Substitute.For(); _sut = new MediaLibraryScanTaskExecutor(_mockDomainEventPublisher, Substitute.For>(), _mockUnitOfWork); } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/RepairThemesTaskExecutorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/RepairThemesTaskExecutorTests.cs index fc7632b1..da6291a3 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/RepairThemesTaskExecutorTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/RepairThemesTaskExecutorTests.cs @@ -2,6 +2,8 @@ using Lumina.Application.Common.DataAccess.Entities.Themes; using Lumina.Application.Common.DataAccess.Repositories.Themes; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Infrastructure.Models.DTO.Themes; using Lumina.Application.Common.Infrastructure.Themes; using Lumina.Domain.Common.Primitives; @@ -42,7 +44,7 @@ public class RepairThemesTaskExecutorTests _mockUnitOfWork = Substitute.For(); _mockThemeRepository = Substitute.For(); _mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); ILogger logger = Substitute.For>(); _sut = new RepairThemesTaskExecutor(_mockThemeService, logger, _mockUnitOfWork); } @@ -53,14 +55,14 @@ public class RepairThemesTaskExecutorTests // Arrange ScheduledJob scheduledJob = _scheduledJobFixture.Create(taskType: ScheduledTaskType.RepairThemes); _mockThemeService.GetBundledThemeArchivePaths().Returns([]); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From(Enumerable.Empty())); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); // Act Result result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None); // Assert Assert.False(result.IsFailure); - await _mockThemeRepository.Received(1).GetAllAsync(Arg.Any()); + await _mockThemeRepository.Received(1).GetAllAsync(cancellationToken: Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); } @@ -72,14 +74,14 @@ public class RepairThemesTaskExecutorTests _mockThemeService.GetBundledThemeArchivePaths().Returns(["missing.zip"]); _mockThemeService.ReadManifestFromArchiveAsync(Arg.Any(), Arg.Any()) .Returns(Error.Failure("Theme.Manifest", "Failed to read the theme manifest")); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From(Enumerable.Empty())); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); // Act Result result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None); // Assert Assert.False(result.IsFailure); - await _mockThemeRepository.Received(1).GetAllAsync(Arg.Any()); + await _mockThemeRepository.Received(1).GetAllAsync(cancellationToken: Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); } @@ -88,8 +90,8 @@ public class RepairThemesTaskExecutorTests { // Arrange ScheduledJob scheduledJob = _scheduledJobFixture.Create(taskType: ScheduledTaskType.RepairThemes); - _mockThemeRepository.GetAllAsync(Arg.Any()) - .Returns(Task.FromException>>(new InvalidOperationException("The database is unavailable."))); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Task.FromException>>(new InvalidOperationException("The database is unavailable."))); // Act Result result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None); @@ -104,8 +106,8 @@ public class RepairThemesTaskExecutorTests { // Arrange ScheduledJob scheduledJob = _scheduledJobFixture.Create(taskType: ScheduledTaskType.RepairThemes); - _mockThemeRepository.GetAllAsync(Arg.Any()) - .Returns(Task.FromException>>(new OperationCanceledException())); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Task.FromException>>(new OperationCanceledException())); // Act async Task Act() diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeSynchronizerTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeSynchronizerTests.cs index af45a663..5c7e7635 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeSynchronizerTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeSynchronizerTests.cs @@ -2,6 +2,8 @@ using Lumina.Application.Common.DataAccess.Entities.Themes; using Lumina.Application.Common.DataAccess.Repositories.Themes; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Infrastructure.Models.DTO.Themes; using Lumina.Application.Common.Infrastructure.Themes; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes; @@ -46,12 +48,12 @@ public class ThemeSynchronizerTests : IDisposable _mockUnitOfWork = Substitute.For(); _mockThemeRepository = Substitute.For(); _mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockLogger = Substitute.For(); _mockThemeService.GetBundledThemeArchivePaths().Returns([]); _mockThemeService.HasThemePack(Arg.Any()).Returns(true); _mockThemeService.DefaultThemeId.Returns("lumina-default"); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From(Enumerable.Empty())); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); _mockThemeRepository.InsertAsync(Arg.Any(), Arg.Any()).Returns(Result.Created); _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.Updated); _mockThemeRepository.DeleteByIdAsync(Arg.Any(), Arg.Any()).Returns(Result.Deleted); @@ -63,7 +65,7 @@ public class ThemeSynchronizerTests : IDisposable public async Task SynchronizeAsync_WhenTheInstalledThemesCannotBeRead_ShouldLogAndReturn() { // Arrange - _mockThemeRepository.GetAllAsync(Arg.Any()) + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()) .Returns(Error.Failure("Themes.NotFound", "Failed to read the installed themes")); _mockThemeService.GetBundledThemeArchivePaths().Returns(["bundled.zip"]); @@ -97,7 +99,7 @@ public class ThemeSynchronizerTests : IDisposable // Arrange ThemeManifestDto manifest = _themeManifestDtoFixture.Create(); ThemeEntity installedTheme = _themeEntityFixture.Create(themeId: manifest.Id, installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(new[] { installedTheme }); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [installedTheme], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 })); _mockThemeService.GetBundledThemeArchivePaths().Returns(["bundled.zip"]); _mockThemeService.ReadManifestFromArchiveAsync("bundled.zip", Arg.Any()).Returns(Result.From(manifest)); @@ -115,7 +117,7 @@ public class ThemeSynchronizerTests : IDisposable // Arrange ThemeManifestDto manifest = _themeManifestDtoFixture.Create(); ThemeEntity deletedTheme = _themeEntityFixture.Create(themeId: manifest.Id, installSource: ThemeInstallSource.Bundled, isDeleted: true); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(new[] { deletedTheme }); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [deletedTheme], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 })); _mockThemeService.GetBundledThemeArchivePaths().Returns(["bundled.zip"]); _mockThemeService.ReadManifestFromArchiveAsync("bundled.zip", Arg.Any()).Returns(Result.From(manifest)); @@ -133,7 +135,7 @@ public class ThemeSynchronizerTests : IDisposable // Arrange ThemeManifestDto manifest = _themeManifestDtoFixture.Create(); ThemeEntity damagedTheme = _themeEntityFixture.Create(themeId: manifest.Id, installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(new[] { damagedTheme }); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [damagedTheme], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 })); string archivePath = CreateArchiveFile(); _mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]); // The first pack check happens before the repair and reports the files as missing; the later checks report the files as present. @@ -155,7 +157,7 @@ public class ThemeSynchronizerTests : IDisposable // Arrange ThemeManifestDto manifest = _themeManifestDtoFixture.Create(); ThemeEntity damagedTheme = _themeEntityFixture.Create(themeId: manifest.Id, installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(new[] { damagedTheme }); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [damagedTheme], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 })); string archivePath = CreateArchiveFile(); _mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]); _mockThemeService.HasThemePack(damagedTheme.ThemeId).Returns(false, true); @@ -254,7 +256,7 @@ public class ThemeSynchronizerTests : IDisposable { // Arrange ThemeEntity healthyTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(new[] { healthyTheme }); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [healthyTheme], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 })); // Act await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None); @@ -269,7 +271,7 @@ public class ThemeSynchronizerTests : IDisposable { // Arrange ThemeEntity brokenTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(new[] { brokenTheme }); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [brokenTheme], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 })); _mockThemeService.HasThemePack(brokenTheme.ThemeId).Returns(false); _mockThemeService.RestoreBundledThemeAsync(brokenTheme.ThemeId, Arg.Any()).Returns(Result.Success); @@ -287,7 +289,7 @@ public class ThemeSynchronizerTests : IDisposable { // Arrange ThemeEntity lastBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(new[] { lastBundledTheme }); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [lastBundledTheme], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 })); _mockThemeService.HasThemePack(lastBundledTheme.ThemeId).Returns(false); _mockThemeService.RestoreBundledThemeAsync(lastBundledTheme.ThemeId, Arg.Any()) .Returns(Error.Failure("Theme.Restore", "Failed to restore the theme")); @@ -306,7 +308,7 @@ public class ThemeSynchronizerTests : IDisposable // Arrange ThemeEntity brokenBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false); ThemeEntity healthyBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(new[] { brokenBundledTheme, healthyBundledTheme }); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [brokenBundledTheme, healthyBundledTheme], CurrentPage = 1, PerPage = 2, Count = 2, NumberOfPages = 1 })); _mockThemeService.HasThemePack(brokenBundledTheme.ThemeId).Returns(false); _mockThemeService.RestoreBundledThemeAsync(brokenBundledTheme.ThemeId, Arg.Any()) .Returns(Error.Failure("Theme.Restore", "Failed to restore the theme")); @@ -326,7 +328,7 @@ public class ThemeSynchronizerTests : IDisposable // Arrange ThemeEntity brokenBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false); ThemeEntity healthyBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(new[] { brokenBundledTheme, healthyBundledTheme }); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [brokenBundledTheme, healthyBundledTheme], CurrentPage = 1, PerPage = 2, Count = 2, NumberOfPages = 1 })); _mockThemeService.HasThemePack(brokenBundledTheme.ThemeId).Returns(false); _mockThemeService.RestoreBundledThemeAsync(brokenBundledTheme.ThemeId, Arg.Any()) .Returns(Error.Failure("Theme.Restore", "Failed to restore the theme")); @@ -346,7 +348,7 @@ public class ThemeSynchronizerTests : IDisposable { // Arrange ThemeEntity brokenUserTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Uploaded, isDeleted: false, includeIsCurrent: true, isCurrent: true); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(new[] { brokenUserTheme }); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [brokenUserTheme], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 })); _mockThemeService.HasThemePack(brokenUserTheme.ThemeId).Returns(false); // Act @@ -361,7 +363,7 @@ public class ThemeSynchronizerTests : IDisposable { // Arrange ThemeEntity brokenUserTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Uploaded, isDeleted: false, includeIsCurrent: true, isCurrent: true); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(new[] { brokenUserTheme }); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [brokenUserTheme], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 })); _mockThemeService.HasThemePack(brokenUserTheme.ThemeId).Returns(false); _mockThemeRepository.DeleteByIdAsync(Arg.Any(), Arg.Any()) .Returns(Error.Failure("Themes.DeleteFailed", "Failed to delete the theme")); @@ -380,7 +382,7 @@ public class ThemeSynchronizerTests : IDisposable // Arrange ThemeEntity throwingBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false); ThemeEntity healthyBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(new[] { throwingBundledTheme, healthyBundledTheme }); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [throwingBundledTheme, healthyBundledTheme], CurrentPage = 1, PerPage = 2, Count = 2, NumberOfPages = 1 })); _mockThemeService.HasThemePack(Arg.Any()).Returns(false); _mockThemeService.RestoreBundledThemeAsync(throwingBundledTheme.ThemeId, Arg.Any()) .Returns(Task.FromException>(new InvalidOperationException("Unexpected failure"))); @@ -401,7 +403,7 @@ public class ThemeSynchronizerTests : IDisposable { // Arrange ThemeEntity brokenBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(new[] { brokenBundledTheme }); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [brokenBundledTheme], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 })); _mockThemeService.HasThemePack(brokenBundledTheme.ThemeId).Returns(false); _mockThemeService.RestoreBundledThemeAsync(brokenBundledTheme.ThemeId, Arg.Any()) .Returns(Task.FromException>(new OperationCanceledException()));