Adds the scheduling module tests and centralizes domain event test fixtures

This commit is contained in:
BinaryAlley committed 2026-09-04 00:16:41 -07:00
1 parent 237be9e2c8
commit 99a6159f7f
135 files changed
+10203 -165

No files matched your search

@@ -10,6 +10,7 @@ using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.File
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events;
using Microsoft.Extensions.Options;
using NSubstitute;
using System;
@@ -31,6 +32,7 @@ public class LibraryDeletedDomainEventHandlerTests
private readonly IPathService _mockPathService;
private readonly LibraryDeletedDomainEventHandler _sut;
private readonly LibraryFixture _libraryFixture = new();
private readonly LibraryDeletedDomainEventFixture _libraryDeletedDomainEventFixture = new();
private readonly MediaSettingsDtoFixture _mediaSettingsDtoFixture = new();
/// <summary>
@@ -64,7 +66,7 @@ public class LibraryDeletedDomainEventHandlerTests
// Arrange
Guid libraryId = Guid.NewGuid();
Library library = _libraryFixture.Create(id: libraryId);
LibraryDeletedDomainEvent domainEvent = new(Guid.NewGuid(), library, DateTime.UtcNow);
LibraryDeletedDomainEvent domainEvent = _libraryDeletedDomainEventFixture.Create(library: library);
// Act
await _sut.HandleAsync(domainEvent, CancellationToken.None);
@@ -80,7 +82,7 @@ public class LibraryDeletedDomainEventHandlerTests
// Arrange
Guid libraryId = Guid.NewGuid();
Library library = _libraryFixture.Create(id: libraryId);
LibraryDeletedDomainEvent domainEvent = new(Guid.NewGuid(), library, DateTime.UtcNow);
LibraryDeletedDomainEvent domainEvent = _libraryDeletedDomainEventFixture.Create(library: library);
Error error = Error.Failure(description: "Failed to delete library directory");
_mockDirectoryProviderService.DeleteDirectory(Arg.Any<FileSystemPathId>()).Returns(error);
@@ -98,7 +100,7 @@ public class LibraryDeletedDomainEventHandlerTests
// Arrange
Guid libraryId = Guid.NewGuid();
Library library = _libraryFixture.Create(id: libraryId);
LibraryDeletedDomainEvent domainEvent = new(Guid.NewGuid(), library, DateTime.UtcNow);
LibraryDeletedDomainEvent domainEvent = _libraryDeletedDomainEventFixture.Create(library: library);
Error error = Error.Failure(description: "Failed to combine path");
_mockPathService.CombinePath(Arg.Any<string>(), Arg.Any<string>()).Returns(error);
@@ -12,10 +12,8 @@ using Lumina.Domain.Common.Exceptions;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Microsoft.Extensions.Logging;
using NSubstitute;
using System;
@@ -40,10 +38,9 @@ public class LibraryMediaItemDeletedDomainEventHandlerTests
private readonly ILogger<LibraryMediaItemDeletedDomainEventHandler> _mockLogger;
private readonly LibraryMediaItemDeletedDomainEventHandler _sut;
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly ScanIdFixture _scanIdFixture = new();
private readonly UserIdFixture _userIdFixture = new();
private readonly BookEntityFixture _bookEntityFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly LibraryMediaItemDeletedDomainEventFixture _libraryMediaItemDeletedDomainEventFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="LibraryMediaItemDeletedDomainEventHandlerTests"/> class.
@@ -81,12 +78,7 @@ public class LibraryMediaItemDeletedDomainEventHandlerTests
.Returns(Result.Deleted);
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
LibraryMediaItemDeletedDomainEvent domainEvent = new(
Guid.NewGuid(),
libraryId,
MediaLibraryScanCompositeId.Create(_scanIdFixture.Create(), _userIdFixture.Create()),
book.Path,
DateTime.UtcNow);
LibraryMediaItemDeletedDomainEvent domainEvent = _libraryMediaItemDeletedDomainEventFixture.Create(libraryId: libraryId, path: book.Path);
// Act
await _sut.HandleAsync(domainEvent, CancellationToken.None);
@@ -105,12 +97,7 @@ public class LibraryMediaItemDeletedDomainEventHandlerTests
_mockBookRepository.GetByPathAsync(libraryId.Value, "/books/deleted.epub", Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(null));
LibraryMediaItemDeletedDomainEvent domainEvent = new(
Guid.NewGuid(),
libraryId,
MediaLibraryScanCompositeId.Create(_scanIdFixture.Create(), _userIdFixture.Create()),
"/books/deleted.epub",
DateTime.UtcNow);
LibraryMediaItemDeletedDomainEvent domainEvent = _libraryMediaItemDeletedDomainEventFixture.Create(libraryId: libraryId, path: "/books/deleted.epub");
// Act
await _sut.HandleAsync(domainEvent, CancellationToken.None);
@@ -140,12 +127,7 @@ public class LibraryMediaItemDeletedDomainEventHandlerTests
.Returns(Result.From(Result.Deleted));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
LibraryMediaItemDeletedDomainEvent domainEvent = new(
Guid.NewGuid(),
libraryId,
MediaLibraryScanCompositeId.Create(_scanIdFixture.Create(), _userIdFixture.Create()),
book.Path,
DateTime.UtcNow);
LibraryMediaItemDeletedDomainEvent domainEvent = _libraryMediaItemDeletedDomainEventFixture.Create(libraryId: libraryId, path: book.Path);
// Act
await _sut.HandleAsync(domainEvent, CancellationToken.None);
@@ -165,12 +147,7 @@ public class LibraryMediaItemDeletedDomainEventHandlerTests
_mockBookRepository.GetByPathAsync(libraryId.Value, "/books/deleted.epub", Arg.Any<CancellationToken>())
.Returns(error);
LibraryMediaItemDeletedDomainEvent domainEvent = new(
Guid.NewGuid(),
libraryId,
MediaLibraryScanCompositeId.Create(_scanIdFixture.Create(), _userIdFixture.Create()),
"/books/deleted.epub",
DateTime.UtcNow);
LibraryMediaItemDeletedDomainEvent domainEvent = _libraryMediaItemDeletedDomainEventFixture.Create(libraryId: libraryId, path: "/books/deleted.epub");
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
@@ -200,12 +177,7 @@ public class LibraryMediaItemDeletedDomainEventHandlerTests
_mockBookRepository.DeleteAsync(book.Id, Arg.Any<CancellationToken>())
.Returns(error);
LibraryMediaItemDeletedDomainEvent domainEvent = new(
Guid.NewGuid(),
libraryId,
MediaLibraryScanCompositeId.Create(_scanIdFixture.Create(), _userIdFixture.Create()),
book.Path,
DateTime.UtcNow);
LibraryMediaItemDeletedDomainEvent domainEvent = _libraryMediaItemDeletedDomainEventFixture.Create(libraryId: libraryId, path: book.Path);
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
@@ -15,6 +15,7 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events;
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events;
using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary;
using Microsoft.Extensions.Options;
using NSubstitute;
@@ -43,6 +44,7 @@ public class LibrarySavedDomainEventHandlerTests
private readonly IPathService _mockPathService;
private readonly LibrarySavedDomainEventHandler _sut;
private readonly LibraryFixture _libraryFixture = new();
private readonly LibrarySavedDomainEventFixture _librarySavedDomainEventFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new();
private readonly MediaSettingsDtoFixture _mediaSettingsDtoFixture = new();
@@ -97,14 +99,14 @@ public class LibrarySavedDomainEventHandlerTests
// Arrange
Guid libraryId = Guid.NewGuid();
Library library = _libraryFixture.Create(id: libraryId, coverImage: "C:/Users/user/cover.jpg");
LibrarySavedDomainEvent domainEvent = new(Guid.NewGuid(), library, DateTime.UtcNow);
LibrarySavedDomainEvent domainEvent = _librarySavedDomainEventFixture.Create(library: library);
LibraryEntity updatedLibrary = _libraryEntityFixture.Create(id: libraryId);
// Act
await _sut.HandleAsync(domainEvent, CancellationToken.None);
// Assert
Assert.NotNull(library.CoverImage);
Assert.NotNull(domainEvent.Library.CoverImage);
await _mockLibraryRepository.Received(1).UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -115,7 +117,7 @@ public class LibrarySavedDomainEventHandlerTests
// Arrange
Guid libraryId = Guid.NewGuid();
Library library = _libraryFixture.Create(id: libraryId, coverImage: "C:/Users/user/cover.jpg");
LibrarySavedDomainEvent domainEvent = new(Guid.NewGuid(), library, DateTime.UtcNow);
LibrarySavedDomainEvent domainEvent = _librarySavedDomainEventFixture.Create(library: library);
_mockDirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockFileProviderService.GetFilePaths(Arg.Any<FileSystemPathId>(), true)
.Returns(Result.From<IEnumerable<FileSystemPathId>>(
@@ -140,7 +142,7 @@ public class LibrarySavedDomainEventHandlerTests
// Arrange
Guid libraryId = Guid.NewGuid();
Library library = _libraryFixture.Create(id: libraryId, includeCoverImage: false);
LibrarySavedDomainEvent domainEvent = new(Guid.NewGuid(), library, DateTime.UtcNow);
LibrarySavedDomainEvent domainEvent = _librarySavedDomainEventFixture.Create(library: library);
_mockFileProviderService.GetFilePaths(Arg.Any<FileSystemPathId>(), true)
.Returns(Result.From<IEnumerable<FileSystemPathId>>(
[
@@ -162,7 +164,7 @@ public class LibrarySavedDomainEventHandlerTests
// Arrange
Guid libraryId = Guid.NewGuid();
Library library = _libraryFixture.Create(id: libraryId, coverImage: "/Media/Libraries/guid/cover.png");
LibrarySavedDomainEvent domainEvent = new(Guid.NewGuid(), library, DateTime.UtcNow);
LibrarySavedDomainEvent domainEvent = _librarySavedDomainEventFixture.Create(library: library);
// mirror the real CombinePath behavior, which treats the combined name as a directory segment and appends a trailing
// separator; the internal cover path resolution must still yield the file path without that trailing separator
_mockPathService.CombinePath(Arg.Any<string>(), Arg.Any<string>())
@@ -175,7 +177,7 @@ public class LibrarySavedDomainEventHandlerTests
await _sut.HandleAsync(domainEvent, CancellationToken.None);
// Assert
Assert.Equal("/Media/Libraries/guid/cover.png", library.CoverImage);
Assert.Equal("/Media/Libraries/guid/cover.png", domainEvent.Library.CoverImage);
_mockFileProviderService.DidNotReceive().CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), Arg.Any<bool>());
await _mockLibraryRepository.Received(1).UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
}
@@ -186,7 +188,7 @@ public class LibrarySavedDomainEventHandlerTests
// Arrange
Guid libraryId = Guid.NewGuid();
Library library = _libraryFixture.Create(id: libraryId, coverImage: "C:/Users/user/cover.jpg");
LibrarySavedDomainEvent domainEvent = new(Guid.NewGuid(), library, DateTime.UtcNow);
LibrarySavedDomainEvent domainEvent = _librarySavedDomainEventFixture.Create(library: library);
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(false));
// Act
@@ -204,7 +206,7 @@ public class LibrarySavedDomainEventHandlerTests
// Arrange
Guid libraryId = Guid.NewGuid();
Library library = _libraryFixture.Create(id: libraryId, coverImage: "C:/Users/user/cover.jpg");
LibrarySavedDomainEvent domainEvent = new(Guid.NewGuid(), library, DateTime.UtcNow);
LibrarySavedDomainEvent domainEvent = _librarySavedDomainEventFixture.Create(library: library);
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.None));
@@ -223,7 +225,7 @@ public class LibrarySavedDomainEventHandlerTests
// Arrange
Guid libraryId = Guid.NewGuid();
Library library = _libraryFixture.Create(id: libraryId, coverImage: "C:/Users/user/cover.jpg");
LibrarySavedDomainEvent domainEvent = new(Guid.NewGuid(), library, DateTime.UtcNow);
LibrarySavedDomainEvent domainEvent = _librarySavedDomainEventFixture.Create(library: library);
Error error = Error.Failure(description: "Failed to copy cover file");
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
.Returns(error);
@@ -243,7 +245,7 @@ public class LibrarySavedDomainEventHandlerTests
// Arrange
Guid libraryId = Guid.NewGuid();
Library library = _libraryFixture.Create(id: libraryId, includeCoverImage: false);
LibrarySavedDomainEvent domainEvent = new(Guid.NewGuid(), library, DateTime.UtcNow);
LibrarySavedDomainEvent domainEvent = _librarySavedDomainEventFixture.Create(library: library);
Error error = Error.Failure(description: "Failed to combine path");
_mockPathService.CombinePath(Arg.Any<string>(), Arg.Any<string>()).Returns(error);
@@ -262,7 +264,7 @@ public class LibrarySavedDomainEventHandlerTests
// Arrange
Guid libraryId = Guid.NewGuid();
Library library = _libraryFixture.Create(id: libraryId, coverImage: "C:/Users/user/cover.jpg");
LibrarySavedDomainEvent domainEvent = new(Guid.NewGuid(), library, DateTime.UtcNow);
LibrarySavedDomainEvent domainEvent = _librarySavedDomainEventFixture.Create(library: library);
Error error = Error.Failure(description: "Failed to update library");
_mockLibraryRepository.UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>())
.Returns(error);
@@ -12,8 +12,7 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
using NSubstitute;
using System;
@@ -39,8 +38,7 @@ public class LibraryScanCancelledDomainEventHandlerTests
private readonly IMediaLibrariesScanCancellationTracker _mockMediaLibrariesScanCancellationTracker;
private readonly LibraryScanCancelledDomainEventHandler _sut;
private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new();
private readonly ScanIdFixture _scanIdFixture = new();
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly LibraryScanCancelledDomainEventFixture _libraryScanCancelledDomainEventFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="LibraryScanCancelledDomainEventHandlerTests"/> class.
@@ -68,8 +66,10 @@ public class LibraryScanCancelledDomainEventHandlerTests
public async Task HandleAsync_WhenScanExists_ShouldCancelScanAndCleanupResources()
{
// Arrange
LibraryScanEntity scan = _libraryScanEntityFixture.Create();
LibraryScanCancelledDomainEvent domainEvent = new(Guid.NewGuid(), _scanIdFixture.Create(value: scan.Id), _libraryIdFixture.Create(value: scan.LibraryId), DateTime.UtcNow);
LibraryScanCancelledDomainEvent domainEvent = _libraryScanCancelledDomainEventFixture.Create();
LibraryScanEntity scan = _libraryScanEntityFixture.Create(
id: domainEvent.ScanId.Value,
libraryId: domainEvent.LibraryId.Value);
_mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryScanEntity?>(scan));
@@ -87,7 +87,7 @@ public class LibraryScanCancelledDomainEventHandlerTests
public async Task HandleAsync_WhenGetByIdFails_ShouldThrowEventualConsistencyException()
{
// Arrange
LibraryScanCancelledDomainEvent domainEvent = new(Guid.NewGuid(), _scanIdFixture.Create(), _libraryIdFixture.Create(), DateTime.UtcNow);
LibraryScanCancelledDomainEvent domainEvent = _libraryScanCancelledDomainEventFixture.Create();
Error error = Error.Failure(description: "Failed to get library scan");
_mockLibraryScanRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(error);
@@ -105,7 +105,7 @@ public class LibraryScanCancelledDomainEventHandlerTests
public async Task HandleAsync_WhenScanDoesNotExist_ShouldThrowEventualConsistencyExceptionWithNotFoundError()
{
// Arrange
LibraryScanCancelledDomainEvent domainEvent = new(Guid.NewGuid(), _scanIdFixture.Create(), _libraryIdFixture.Create(), DateTime.UtcNow);
LibraryScanCancelledDomainEvent domainEvent = _libraryScanCancelledDomainEventFixture.Create();
_mockLibraryScanRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result<LibraryScanEntity?>.Success(null));
@@ -122,8 +122,10 @@ public class LibraryScanCancelledDomainEventHandlerTests
public async Task HandleAsync_WhenCancelScanFails_ShouldThrowEventualConsistencyException()
{
// Arrange
LibraryScanEntity scan = _libraryScanEntityFixture.Create();
LibraryScanCancelledDomainEvent domainEvent = new(Guid.NewGuid(), _scanIdFixture.Create(value: scan.Id), _libraryIdFixture.Create(value: scan.LibraryId), DateTime.UtcNow);
LibraryScanCancelledDomainEvent domainEvent = _libraryScanCancelledDomainEventFixture.Create();
LibraryScanEntity scan = _libraryScanEntityFixture.Create(
id: domainEvent.ScanId.Value,
libraryId: domainEvent.LibraryId.Value);
_mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryScanEntity?>(scan));
Error error = Error.Failure(description: "Failed to cancel scan");
@@ -143,8 +145,10 @@ public class LibraryScanCancelledDomainEventHandlerTests
public async Task HandleAsync_WhenClearForScanFails_ShouldThrowEventualConsistencyException()
{
// Arrange
LibraryScanEntity scan = _libraryScanEntityFixture.Create();
LibraryScanCancelledDomainEvent domainEvent = new(Guid.NewGuid(), _scanIdFixture.Create(value: scan.Id), _libraryIdFixture.Create(value: scan.LibraryId), DateTime.UtcNow);
LibraryScanCancelledDomainEvent domainEvent = _libraryScanCancelledDomainEventFixture.Create();
LibraryScanEntity scan = _libraryScanEntityFixture.Create(
id: domainEvent.ScanId.Value,
libraryId: domainEvent.LibraryId.Value);
_mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryScanEntity?>(scan));
Error error = Error.Failure(description: "Failed to clear staging results");
@@ -12,9 +12,7 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
using NSubstitute;
@@ -41,10 +39,7 @@ public class LibraryScanFailedDomainEventHandlerTests
private readonly IMediaLibraryScanProgressNotifier _mockDebouncedLibraryScanProgressNotifier;
private readonly LibraryScanFailedDomainEventHandler _sut;
private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new();
private readonly ScanIdFixture _scanIdFixture = new();
private readonly UserIdFixture _userIdFixture = new();
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new();
private readonly LibraryScanFailedDomainEventFixture _libraryScanFailedDomainEventFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="LibraryScanFailedDomainEventHandlerTests"/> class.
@@ -73,11 +68,11 @@ public class LibraryScanFailedDomainEventHandlerTests
public async Task HandleAsync_WhenScanIsRunning_ShouldFailScanAndCleanupResources()
{
// Arrange
LibraryScanEntity scan = _libraryScanEntityFixture.Create();
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(
scanId: _scanIdFixture.Create(value: scan.Id),
userId: _userIdFixture.Create(value: scan.UserId));
LibraryScanFailedDomainEvent domainEvent = new(Guid.NewGuid(), _libraryIdFixture.Create(value: scan.LibraryId), compositeId, DateTime.UtcNow);
LibraryScanFailedDomainEvent domainEvent = _libraryScanFailedDomainEventFixture.Create();
MediaLibraryScanCompositeId compositeId = domainEvent.MediaLibraryScanCompositeId;
LibraryScanEntity scan = _libraryScanEntityFixture.Create(
id: compositeId.ScanId.Value,
userId: compositeId.UserId.Value);
_mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryScanEntity?>(scan));
@@ -97,11 +92,12 @@ public class LibraryScanFailedDomainEventHandlerTests
public async Task HandleAsync_WhenScanIsNotRunning_ShouldSkipPersistenceButStillCleanupResources()
{
// Arrange
LibraryScanEntity scan = _libraryScanEntityFixture.Create(status: LibraryScanJobStatus.Failed);
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(
scanId: _scanIdFixture.Create(value: scan.Id),
userId: _userIdFixture.Create(value: scan.UserId));
LibraryScanFailedDomainEvent domainEvent = new(Guid.NewGuid(), _libraryIdFixture.Create(value: scan.LibraryId), compositeId, DateTime.UtcNow);
LibraryScanFailedDomainEvent domainEvent = _libraryScanFailedDomainEventFixture.Create();
MediaLibraryScanCompositeId compositeId = domainEvent.MediaLibraryScanCompositeId;
LibraryScanEntity scan = _libraryScanEntityFixture.Create(
id: compositeId.ScanId.Value,
userId: compositeId.UserId.Value,
status: LibraryScanJobStatus.Failed);
_mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryScanEntity?>(scan));
@@ -121,8 +117,7 @@ public class LibraryScanFailedDomainEventHandlerTests
public async Task HandleAsync_WhenGetByIdFails_ShouldThrowEventualConsistencyException()
{
// Arrange
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
LibraryScanFailedDomainEvent domainEvent = new(Guid.NewGuid(), _libraryIdFixture.Create(), compositeId, DateTime.UtcNow);
LibraryScanFailedDomainEvent domainEvent = _libraryScanFailedDomainEventFixture.Create();
Error error = Error.Failure(description: "Failed to get library scan");
_mockLibraryScanRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(error);
@@ -140,8 +135,7 @@ public class LibraryScanFailedDomainEventHandlerTests
public async Task HandleAsync_WhenScanDoesNotExist_ShouldThrowEventualConsistencyExceptionWithNotFoundError()
{
// Arrange
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
LibraryScanFailedDomainEvent domainEvent = new(Guid.NewGuid(), _libraryIdFixture.Create(), compositeId, DateTime.UtcNow);
LibraryScanFailedDomainEvent domainEvent = _libraryScanFailedDomainEventFixture.Create();
_mockLibraryScanRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result<LibraryScanEntity?>.Success(null));
@@ -158,11 +152,11 @@ public class LibraryScanFailedDomainEventHandlerTests
public async Task HandleAsync_WhenUpdateFails_ShouldThrowEventualConsistencyException()
{
// Arrange
LibraryScanEntity scan = _libraryScanEntityFixture.Create();
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(
scanId: _scanIdFixture.Create(value: scan.Id),
userId: _userIdFixture.Create(value: scan.UserId));
LibraryScanFailedDomainEvent domainEvent = new(Guid.NewGuid(), _libraryIdFixture.Create(value: scan.LibraryId), compositeId, DateTime.UtcNow);
LibraryScanFailedDomainEvent domainEvent = _libraryScanFailedDomainEventFixture.Create();
MediaLibraryScanCompositeId compositeId = domainEvent.MediaLibraryScanCompositeId;
LibraryScanEntity scan = _libraryScanEntityFixture.Create(
id: compositeId.ScanId.Value,
userId: compositeId.UserId.Value);
_mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryScanEntity?>(scan));
Error error = Error.Failure(description: "Failed to update library scan");
@@ -182,11 +176,11 @@ public class LibraryScanFailedDomainEventHandlerTests
public async Task HandleAsync_WhenClearForScanFails_ShouldThrowEventualConsistencyException()
{
// Arrange
LibraryScanEntity scan = _libraryScanEntityFixture.Create();
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(
scanId: _scanIdFixture.Create(value: scan.Id),
userId: _userIdFixture.Create(value: scan.UserId));
LibraryScanFailedDomainEvent domainEvent = new(Guid.NewGuid(), _libraryIdFixture.Create(value: scan.LibraryId), compositeId, DateTime.UtcNow);
LibraryScanFailedDomainEvent domainEvent = _libraryScanFailedDomainEventFixture.Create();
MediaLibraryScanCompositeId compositeId = domainEvent.MediaLibraryScanCompositeId;
LibraryScanEntity scan = _libraryScanEntityFixture.Create(
id: compositeId.ScanId.Value,
userId: compositeId.UserId.Value);
_mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryScanEntity?>(scan));
Error error = Error.Failure(description: "Failed to clear staging results");
@@ -8,14 +8,11 @@ using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Manage
using Lumina.Domain.Common.Exceptions;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
using NSubstitute;
@@ -41,10 +38,7 @@ public class LibraryScanFinishedDomainEventHandlerTests
private readonly IMediaLibraryScanProgressNotifier _mockDebouncedLibraryScanProgressNotifier;
private readonly LibraryScanFinishedDomainEventHandler _sut;
private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new();
private readonly ScanIdFixture _scanIdFixture = new();
private readonly UserIdFixture _userIdFixture = new();
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new();
private readonly LibraryScanFinishedDomainEventFixture _libraryScanFinishedDomainEventFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="LibraryScanFinishedDomainEventHandlerTests"/> class.
@@ -69,11 +63,11 @@ public class LibraryScanFinishedDomainEventHandlerTests
public async Task HandleAsync_WhenScanIsRunning_ShouldFinishScanAndNotifyClients()
{
// Arrange
LibraryScanEntity scan = _libraryScanEntityFixture.Create();
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(
scanId: _scanIdFixture.Create(value: scan.Id),
userId: _userIdFixture.Create(value: scan.UserId));
LibraryScanFinishedDomainEvent domainEvent = new(Guid.NewGuid(), compositeId, DateTime.UtcNow);
LibraryScanFinishedDomainEvent domainEvent = _libraryScanFinishedDomainEventFixture.Create();
MediaLibraryScanCompositeId compositeId = domainEvent.MediaLibraryScanCompositeId;
LibraryScanEntity scan = _libraryScanEntityFixture.Create(
id: compositeId.ScanId.Value,
userId: compositeId.UserId.Value);
_mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryScanEntity?>(scan));
_mockMediaLibrariesScanProgressTracker.UpdateScanProgress(Arg.Any<LibraryId>(), compositeId).Returns(Result.Updated);
@@ -93,8 +87,7 @@ public class LibraryScanFinishedDomainEventHandlerTests
public async Task HandleAsync_WhenGetByIdFails_ShouldThrowEventualConsistencyException()
{
// Arrange
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
LibraryScanFinishedDomainEvent domainEvent = new(Guid.NewGuid(), compositeId, DateTime.UtcNow);
LibraryScanFinishedDomainEvent domainEvent = _libraryScanFinishedDomainEventFixture.Create();
Error error = Error.Failure(description: "Failed to get library scan");
_mockLibraryScanRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(error);
@@ -112,8 +105,7 @@ public class LibraryScanFinishedDomainEventHandlerTests
public async Task HandleAsync_WhenScanDoesNotExist_ShouldThrowEventualConsistencyExceptionWithNotFoundError()
{
// Arrange
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
LibraryScanFinishedDomainEvent domainEvent = new(Guid.NewGuid(), compositeId, DateTime.UtcNow);
LibraryScanFinishedDomainEvent domainEvent = _libraryScanFinishedDomainEventFixture.Create();
_mockLibraryScanRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result<LibraryScanEntity?>.Success(null));
@@ -130,11 +122,12 @@ public class LibraryScanFinishedDomainEventHandlerTests
public async Task HandleAsync_WhenScanIsNotRunning_ShouldThrowEventualConsistencyException()
{
// Arrange
LibraryScanEntity scan = _libraryScanEntityFixture.Create(status: LibraryScanJobStatus.Pending);
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(
scanId: _scanIdFixture.Create(value: scan.Id),
userId: _userIdFixture.Create(value: scan.UserId));
LibraryScanFinishedDomainEvent domainEvent = new(Guid.NewGuid(), compositeId, DateTime.UtcNow);
LibraryScanFinishedDomainEvent domainEvent = _libraryScanFinishedDomainEventFixture.Create();
MediaLibraryScanCompositeId compositeId = domainEvent.MediaLibraryScanCompositeId;
LibraryScanEntity scan = _libraryScanEntityFixture.Create(
id: compositeId.ScanId.Value,
userId: compositeId.UserId.Value,
status: LibraryScanJobStatus.Pending);
_mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryScanEntity?>(scan));
@@ -152,11 +145,11 @@ public class LibraryScanFinishedDomainEventHandlerTests
public async Task HandleAsync_WhenUpdateFails_ShouldThrowEventualConsistencyException()
{
// Arrange
LibraryScanEntity scan = _libraryScanEntityFixture.Create();
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(
scanId: _scanIdFixture.Create(value: scan.Id),
userId: _userIdFixture.Create(value: scan.UserId));
LibraryScanFinishedDomainEvent domainEvent = new(Guid.NewGuid(), compositeId, DateTime.UtcNow);
LibraryScanFinishedDomainEvent domainEvent = _libraryScanFinishedDomainEventFixture.Create();
MediaLibraryScanCompositeId compositeId = domainEvent.MediaLibraryScanCompositeId;
LibraryScanEntity scan = _libraryScanEntityFixture.Create(
id: compositeId.ScanId.Value,
userId: compositeId.UserId.Value);
_mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryScanEntity?>(scan));
Error error = Error.Failure(description: "Failed to update library scan");
@@ -6,7 +6,7 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using NSubstitute;
using System;
@@ -26,9 +26,8 @@ public class LibraryScanJobProgressChangedDomainEventHandlerTests
private readonly IMediaLibrariesScanProgressTracker _mockMediaLibrariesScanProgressTracker;
private readonly IMediaLibraryScanProgressNotifier _mockDebouncedLibraryScanProgressNotifier;
private readonly LibraryScanJobProgressChangedDomainEventHandler _sut;
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new();
private readonly MediaLibraryScanJobProgressFixture _mediaLibraryScanJobProgressFixture = new();
private readonly LibraryScanJobProgressChangedDomainEventFixture _libraryScanJobProgressChangedDomainEventFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="LibraryScanJobProgressChangedDomainEventHandlerTests"/> class.
@@ -45,10 +44,10 @@ public class LibraryScanJobProgressChangedDomainEventHandlerTests
public async Task HandleAsync_WhenScanJobProgressChanges_ShouldUpdateTrackerAndNotifySignalRClients()
{
// Arrange
LibraryId libraryId = _libraryIdFixture.Create();
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
MediaLibraryScanJobProgress progress = _mediaLibraryScanJobProgressFixture.Create(completedItems: 5, totalItems: 10, currentOperation: "Hashing");
LibraryScanJobProgressChangedDomainEvent domainEvent = new(Guid.NewGuid(), libraryId, compositeId, progress, DateTime.UtcNow);
LibraryScanJobProgressChangedDomainEvent domainEvent = _libraryScanJobProgressChangedDomainEventFixture.Create(progress: progress);
LibraryId libraryId = domainEvent.LibraryId;
MediaLibraryScanCompositeId compositeId = domainEvent.MediaLibraryScanCompositeId;
_mockMediaLibrariesScanProgressTracker.UpdateScanJobProgress(libraryId, compositeId, progress).Returns(Result.Updated);
// Act
@@ -6,8 +6,7 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
@@ -26,8 +25,7 @@ public class LibraryScanProgressChangedDomainEventHandlerTests
private readonly IMediaLibrariesScanProgressTracker _mockMediaLibrariesScanProgressTracker;
private readonly IMediaLibraryScanProgressNotifier _mockDebouncedLibraryScanProgressNotifier;
private readonly LibraryScanProgressChangedDomainEventHandler _sut;
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new();
private readonly LibraryScanProgressChangedDomainEventFixture _libraryScanProgressChangedDomainEventFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="LibraryScanProgressChangedDomainEventHandlerTests"/> class.
@@ -44,9 +42,9 @@ public class LibraryScanProgressChangedDomainEventHandlerTests
public async Task HandleAsync_WhenScanProgressChanges_ShouldUpdateTrackerAndNotifySignalRClients()
{
// Arrange
LibraryId libraryId = _libraryIdFixture.Create();
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
LibraryScanProgressChangedDomainEvent domainEvent = new(Guid.NewGuid(), libraryId, compositeId, DateTime.UtcNow);
LibraryScanProgressChangedDomainEvent domainEvent = _libraryScanProgressChangedDomainEventFixture.Create();
LibraryId libraryId = domainEvent.LibraryId;
MediaLibraryScanCompositeId compositeId = domainEvent.MediaLibraryScanCompositeId;
_mockMediaLibrariesScanProgressTracker.UpdateScanProgress(libraryId, compositeId).Returns(Result.Updated);
// Act
@@ -11,8 +11,7 @@ using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using NSubstitute;
using System;
@@ -36,8 +35,7 @@ public class LibraryScanQueuedDomainEventHandlerTests
private readonly IDomainEventsQueue _mockDomainEventsQueue;
private readonly LibraryScanQueuedDomainEventHandler _sut;
private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new();
private readonly ScanIdFixture _scanIdFixture = new();
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly LibraryScanQueuedDomainEventFixture _libraryScanQueuedDomainEventFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="LibraryScanQueuedDomainEventHandlerTests"/> class.
@@ -61,8 +59,10 @@ public class LibraryScanQueuedDomainEventHandlerTests
public async Task HandleAsync_WhenScanExists_ShouldStartTheScan()
{
// Arrange
LibraryScanEntity scan = _libraryScanEntityFixture.Create();
LibraryScanQueuedDomainEvent domainEvent = new(Guid.NewGuid(), _scanIdFixture.Create(value: scan.Id), _libraryIdFixture.Create(value: scan.LibraryId), DateTime.UtcNow);
LibraryScanQueuedDomainEvent domainEvent = _libraryScanQueuedDomainEventFixture.Create();
LibraryScanEntity scan = _libraryScanEntityFixture.Create(
id: domainEvent.ScanId.Value,
libraryId: domainEvent.LibraryId.Value);
_mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryScanEntity?>(scan));
@@ -80,7 +80,7 @@ public class LibraryScanQueuedDomainEventHandlerTests
public async Task HandleAsync_WhenGetByIdFails_ShouldThrowEventualConsistencyException()
{
// Arrange
LibraryScanQueuedDomainEvent domainEvent = new(Guid.NewGuid(), _scanIdFixture.Create(), _libraryIdFixture.Create(), DateTime.UtcNow);
LibraryScanQueuedDomainEvent domainEvent = _libraryScanQueuedDomainEventFixture.Create();
Error error = Error.Failure(description: "Failed to get library scan");
_mockLibraryScanRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(error);
@@ -98,7 +98,7 @@ public class LibraryScanQueuedDomainEventHandlerTests
public async Task HandleAsync_WhenScanDoesNotExist_ShouldThrowEventualConsistencyExceptionWithNotFoundError()
{
// Arrange
LibraryScanQueuedDomainEvent domainEvent = new(Guid.NewGuid(), _scanIdFixture.Create(), _libraryIdFixture.Create(), DateTime.UtcNow);
LibraryScanQueuedDomainEvent domainEvent = _libraryScanQueuedDomainEventFixture.Create();
_mockLibraryScanRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result<LibraryScanEntity?>.Success(null));
@@ -115,8 +115,10 @@ public class LibraryScanQueuedDomainEventHandlerTests
public async Task HandleAsync_WhenStartScanFails_ShouldThrowEventualConsistencyException()
{
// Arrange
LibraryScanEntity scan = _libraryScanEntityFixture.Create();
LibraryScanQueuedDomainEvent domainEvent = new(Guid.NewGuid(), _scanIdFixture.Create(value: scan.Id), _libraryIdFixture.Create(value: scan.LibraryId), DateTime.UtcNow);
LibraryScanQueuedDomainEvent domainEvent = _libraryScanQueuedDomainEventFixture.Create();
LibraryScanEntity scan = _libraryScanEntityFixture.Create(
id: domainEvent.ScanId.Value,
libraryId: domainEvent.LibraryId.Value);
_mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryScanEntity?>(scan));
Error error = Error.Failure(description: "Failed to start scan");
@@ -5,9 +5,8 @@ using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Core.MediaLibrary.Management.Events;
using Lumina.Domain.Common.Exceptions;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using NSubstitute;
using System;
using System.Collections.Generic;
@@ -27,7 +26,7 @@ public class LibraryScanStartedDomainEventHandlerTests
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ILibraryScanRepository _mockLibraryScanRepository;
private readonly LibraryScanStartedDomainEventHandler _sut;
private readonly LibraryScanFixture _libraryScanFixture = new();
private readonly LibraryScanStartedDomainEventFixture _libraryScanStartedDomainEventFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="LibraryScanStartedDomainEventHandlerTests"/> class.
@@ -47,15 +46,14 @@ public class LibraryScanStartedDomainEventHandlerTests
public async Task HandleAsync_WhenScanStarts_ShouldUpdateScanStatusAndSaveChanges()
{
// Arrange
LibraryScan libraryScan = _libraryScanFixture.Create();
LibraryScanStartedDomainEvent domainEvent = new(Guid.NewGuid(), libraryScan, DateTime.UtcNow);
LibraryScanStartedDomainEvent domainEvent = _libraryScanStartedDomainEventFixture.Create();
// Act
await _sut.HandleAsync(domainEvent, CancellationToken.None);
// Assert
await _mockLibraryScanRepository.Received(1).UpdateAsync(
Arg.Is<LibraryScanEntity>(scan => scan.Id == libraryScan.Id.Value),
Arg.Is<LibraryScanEntity>(scan => scan.Id == domainEvent.LibraryScan.Id.Value),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -64,8 +62,7 @@ public class LibraryScanStartedDomainEventHandlerTests
public async Task HandleAsync_WhenUpdateFails_ShouldThrowEventualConsistencyException()
{
// Arrange
LibraryScan libraryScan = _libraryScanFixture.Create();
LibraryScanStartedDomainEvent domainEvent = new(Guid.NewGuid(), libraryScan, DateTime.UtcNow);
LibraryScanStartedDomainEvent domainEvent = _libraryScanStartedDomainEventFixture.Create();
Error error = Error.Failure(description: "Failed to update library scan");
_mockLibraryScanRepository.UpdateAsync(Arg.Any<LibraryScanEntity>(), Arg.Any<CancellationToken>())
.Returns(error);
@@ -0,0 +1,256 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DomainEvents;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.Scheduling.Commands.AddScheduledJob;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Fixtures.Core.Scheduling.Commands.AddScheduledJob;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Commands.AddScheduledJob;
/// <summary>
/// Contains unit tests for the <see cref="AddScheduledJobCommandHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddScheduledJobCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly IDomainEventsQueue _mockDomainEventsQueue;
private readonly IScheduledJobRepository _mockScheduledJobRepository;
private readonly IValidator<AddScheduledJobCommand> _mockValidator;
private readonly AddScheduledJobCommandHandler _sut;
private readonly AddScheduledJobCommandFixture _addScheduledJobCommandFixture = new();
private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new();
private readonly Guid _userId = Guid.NewGuid();
/// <summary>
/// Initializes a new instance of the <see cref="AddScheduledJobCommandHandlerTests"/> class.
/// </summary>
public AddScheduledJobCommandHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockDomainEventsQueue = Substitute.For<IDomainEventsQueue>();
_mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
_mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository);
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(true);
_mockValidator = Substitute.For<IValidator<AddScheduledJobCommand>>();
_mockValidator.Validate(Arg.Any<AddScheduledJobCommand>()).Returns([]);
_sut = new AddScheduledJobCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockDomainEventsQueue, _mockUnitOfWork, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenCommandIsValidWithIntervalSchedule_ShouldInsertScheduledJobAndReturnResponse()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(scheduleType: ScheduleType.WithIntervalInMinutes);
_mockScheduledJobRepository.InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>()).Returns(Result.Created);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(command.Name, result.Value.Name);
Assert.Equal(command.TaskType, result.Value.TaskType);
Assert.Equal(ScheduleType.WithIntervalInMinutes, result.Value.ScheduleType);
Assert.Equal(command.IntervalMinutes, result.Value.IntervalMinutes);
Assert.Equal(ScheduledJobStatus.Added, result.Value.Status);
await _mockScheduledJobRepository.Received(1).InsertAsync(
Arg.Is<ScheduledJobEntity>(scheduledJob =>
scheduledJob.Name == command.Name &&
scheduledJob.TaskType == command.TaskType &&
scheduledJob.ScheduleType == ScheduleType.WithIntervalInMinutes &&
scheduledJob.IntervalMinutes == command.IntervalMinutes &&
scheduledJob.OwnerUserId == _userId),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
_mockDomainEventsQueue.Received(1).Enqueue(Arg.Is<IDomainEvent>(domainEvent => domainEvent is ScheduledJobAddedDomainEvent));
}
[Fact]
public async Task HandleAsync_WhenCommandIsValidWithDailySchedule_ShouldInsertScheduledJobAndReturnResponse()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(scheduleType: ScheduleType.DailyAtHourAndMinute, hour: 6, minute: 30);
_mockScheduledJobRepository.InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>()).Returns(Result.Created);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(ScheduleType.DailyAtHourAndMinute, result.Value.ScheduleType);
Assert.Equal(6, result.Value.Hour);
Assert.Equal(30, result.Value.Minute);
Assert.Null(result.Value.IntervalMinutes);
await _mockScheduledJobRepository.Received(1).InsertAsync(
Arg.Is<ScheduledJobEntity>(scheduledJob =>
scheduledJob.ScheduleType == ScheduleType.DailyAtHourAndMinute &&
scheduledJob.Hour == 6 &&
scheduledJob.Minute == 30),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenValidatorReturnsError_ShouldReturnValidationErrorAndNotPersist()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create();
_mockValidator.Validate(Arg.Any<AddScheduledJobCommand>()).Returns([DomainErrors.Scheduling.ScheduledJobNameCannotBeEmpty]);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.ScheduledJobNameCannotBeEmpty, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
}
[Fact]
public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorizedAndNotPersist()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAdministrator_ShouldReturnNotAuthorizedAndNotPersist()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create();
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(false);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenIntervalScheduleHasNonPositiveInterval_ShouldReturnIntervalError()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(
scheduleType: ScheduleType.WithIntervalInMinutes,
intervalMinutes: 0);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.IntervalMinutesMustBePositive, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenDailyScheduleHasOutOfRangeHour_ShouldReturnHourError()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(
scheduleType: ScheduleType.DailyAtHourAndMinute,
hour: 24,
minute: 0);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.HourMustBeBetweenZeroAndTwentyThree, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenScheduleTypeIsUnsupported_ShouldReturnInvalidScheduleTypeError()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(scheduleType: (ScheduleType)999);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.InvalidScheduleType, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenScheduledJobNameIsEmpty_ShouldReturnNameErrorAndNotPersist()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(name: " ");
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Scheduling.ScheduledJobNameCannotBeEmpty, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenInsertFails_ShouldReturnErrorAndNotSaveChanges()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create();
_mockScheduledJobRepository.InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>())
.Returns(DomainErrors.Scheduling.ScheduledJobAlreadyExists);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.ScheduledJobAlreadyExists, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
}
}
@@ -0,0 +1,195 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Scheduling.Commands.AddScheduledJob;
using Lumina.Application.Fixtures.Core.Scheduling.Commands.AddScheduledJob;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Commands.AddScheduledJob;
/// <summary>
/// Contains unit tests for the <see cref="AddScheduledJobCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddScheduledJobCommandValidatorTests
{
private readonly AddScheduledJobCommandValidator _validator = new();
private readonly AddScheduledJobCommandFixture _addScheduledJobCommandFixture = new();
[Theory]
[InlineData(null)] // null name
[InlineData("")] // empty name
[InlineData(" ")] // whitespace name
public void Validate_WhenNameIsNullOrWhitespace_ShouldHaveValidationError(string? name)
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create() with { Name = name! };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Scheduling.ScheduledJobNameCannotBeEmpty);
}
[Fact]
public void Validate_WhenNameExceedsMaximumLength_ShouldHaveValidationError()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(name: new string('a', 81));
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Scheduling.ScheduledJobNameCannotBeEmpty);
}
[Fact]
public void Validate_WhenTaskTypeIsNotInEnum_ShouldHaveValidationError()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(taskType: (ScheduledTaskType)999);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Scheduling.InvalidScheduleType);
}
[Fact]
public void Validate_WhenScheduleTypeIsNotInEnum_ShouldHaveValidationError()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(scheduleType: (ScheduleType)999);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Scheduling.InvalidScheduleType);
}
[Fact]
public void Validate_WhenIntervalScheduleHasNullInterval_ShouldHaveValidationError()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(scheduleType: ScheduleType.WithIntervalInMinutes) with { IntervalMinutes = null };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Scheduling.IntervalMinutesMustBePositive);
}
[Theory]
[InlineData(0)] // interval of zero
[InlineData(-1)] // negative interval
public void Validate_WhenIntervalScheduleHasNonPositiveInterval_ShouldHaveValidationError(int intervalMinutes)
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(
scheduleType: ScheduleType.WithIntervalInMinutes,
intervalMinutes: intervalMinutes);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Scheduling.IntervalMinutesMustBePositive);
}
[Fact]
public void Validate_WhenDailyScheduleHasNullHour_ShouldHaveValidationError()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(scheduleType: ScheduleType.DailyAtHourAndMinute) with { Hour = null };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Scheduling.HourMustBeBetweenZeroAndTwentyThree);
}
[Fact]
public void Validate_WhenDailyScheduleHasNullMinute_ShouldHaveValidationError()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(scheduleType: ScheduleType.DailyAtHourAndMinute) with { Minute = null };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Scheduling.MinuteMustBeBetweenZeroAndFiftyNine);
}
[Theory]
[InlineData(-1)] // hour below the allowed range
[InlineData(24)] // hour above the allowed range
public void Validate_WhenDailyScheduleHasOutOfRangeHour_ShouldHaveValidationError(int hour)
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(
scheduleType: ScheduleType.DailyAtHourAndMinute,
hour: hour,
minute: 0);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Scheduling.HourMustBeBetweenZeroAndTwentyThree);
}
[Theory]
[InlineData(-1)] // minute below the allowed range
[InlineData(60)] // minute above the allowed range
public void Validate_WhenDailyScheduleHasOutOfRangeMinute_ShouldHaveValidationError(int minute)
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(
scheduleType: ScheduleType.DailyAtHourAndMinute,
hour: 12,
minute: minute);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Scheduling.MinuteMustBeBetweenZeroAndFiftyNine);
}
[Fact]
public void Validate_WhenCommandIsValidWithIntervalSchedule_ShouldNotHaveAnyValidationError()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(scheduleType: ScheduleType.WithIntervalInMinutes);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
[Fact]
public void Validate_WhenCommandIsValidWithDailySchedule_ShouldNotHaveAnyValidationError()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(scheduleType: ScheduleType.DailyAtHourAndMinute);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -0,0 +1,213 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DomainEvents;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.Scheduling.Commands.FireScheduledJob;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Fixtures.Core.Scheduling.Commands.FireScheduledJob;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Commands.FireScheduledJob;
/// <summary>
/// Contains unit tests for the <see cref="FireScheduledJobCommandHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class FireScheduledJobCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly IDomainEventsQueue _mockDomainEventsQueue;
private readonly IScheduledJobRepository _mockScheduledJobRepository;
private readonly IValidator<FireScheduledJobCommand> _mockValidator;
private readonly FireScheduledJobCommandHandler _sut;
private readonly FireScheduledJobCommandFixture _fireScheduledJobCommandFixture = new();
private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new();
private readonly Guid _userId = Guid.NewGuid();
/// <summary>
/// Initializes a new instance of the <see cref="FireScheduledJobCommandHandlerTests"/> class.
/// </summary>
public FireScheduledJobCommandHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockDomainEventsQueue = Substitute.For<IDomainEventsQueue>();
_mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
_mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository);
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(true);
_mockValidator = Substitute.For<IValidator<FireScheduledJobCommand>>();
_mockValidator.Validate(Arg.Any<FireScheduledJobCommand>()).Returns([]);
_sut = new FireScheduledJobCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockDomainEventsQueue, _mockUnitOfWork, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenScheduledJobIsAdded_ShouldEnqueueFiredEventAndReturnResponse()
{
// Arrange
FireScheduledJobCommand command = _fireScheduledJobCommandFixture.Create();
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(
id: command.ScheduledJobId,
scheduleType: ScheduleType.WithIntervalInMinutes,
status: ScheduledJobStatus.Active);
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(scheduledJob.Name, result.Value.Name);
_mockDomainEventsQueue.Received(1).Enqueue(Arg.Is<IDomainEvent>(domainEvent => domainEvent is ScheduledJobFiredDomainEvent));
await _mockScheduledJobRepository.DidNotReceive().UpdateAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenValidatorReturnsError_ShouldReturnValidationErrorAndNotQueueEvent()
{
// Arrange
FireScheduledJobCommand command = _fireScheduledJobCommandFixture.Create();
_mockValidator.Validate(Arg.Any<FireScheduledJobCommand>()).Returns([DomainErrors.Scheduling.ScheduledJobNotFound]);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
}
[Fact]
public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorized()
{
// Arrange
FireScheduledJobCommand command = _fireScheduledJobCommandFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAdministrator_ShouldReturnNotAuthorized()
{
// Arrange
FireScheduledJobCommand command = _fireScheduledJobCommandFixture.Create();
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(false);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetByIdReturnsError_ShouldReturnError()
{
// Arrange
FireScheduledJobCommand command = _fireScheduledJobCommandFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to get the scheduled job");
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>()).Returns(error);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
}
[Fact]
public async Task HandleAsync_WhenScheduledJobDoesNotExist_ShouldReturnNotFound()
{
// Arrange
FireScheduledJobCommand command = _fireScheduledJobCommandFixture.Create();
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(null));
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError);
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
}
[Fact]
public async Task HandleAsync_WhenToDomainEntityFails_ShouldReturnError()
{
// Arrange
FireScheduledJobCommand command = _fireScheduledJobCommandFixture.Create();
// A daily scheduled job with an out of range hour cannot convert to its domain aggregate.
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(
id: command.ScheduledJobId,
scheduleType: ScheduleType.DailyAtHourAndMinute,
hour: 99,
minute: 0);
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
}
[Fact]
public async Task HandleAsync_WhenScheduledJobIsRunning_ShouldReturnAlreadyRunningError()
{
// Arrange
FireScheduledJobCommand command = _fireScheduledJobCommandFixture.Create();
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(
id: command.ScheduledJobId,
scheduleType: ScheduleType.WithIntervalInMinutes,
status: ScheduledJobStatus.Running);
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.ScheduledJobAlreadyRunning, result.FirstError);
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
}
}
@@ -0,0 +1,48 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Scheduling.Commands.FireScheduledJob;
using Lumina.Application.Fixtures.Core.Scheduling.Commands.FireScheduledJob;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Commands.FireScheduledJob;
/// <summary>
/// Contains unit tests for the <see cref="FireScheduledJobCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class FireScheduledJobCommandValidatorTests
{
private readonly FireScheduledJobCommandValidator _validator = new();
private readonly FireScheduledJobCommandFixture _fireScheduledJobCommandFixture = new();
[Fact]
public void Validate_WhenScheduledJobIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
FireScheduledJobCommand command = _fireScheduledJobCommandFixture.Create() with { ScheduledJobId = Guid.Empty };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Scheduling.ScheduledJobNotFound);
}
[Fact]
public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationError()
{
// Arrange
FireScheduledJobCommand command = _fireScheduledJobCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -0,0 +1,219 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DomainEvents;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Scheduling;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.Scheduling.Commands.RemoveScheduledJob;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Fixtures.Core.Scheduling.Commands.RemoveScheduledJob;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
using ScheduledJobId = Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects.ScheduledJobId;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Commands.RemoveScheduledJob;
/// <summary>
/// Contains unit tests for the <see cref="RemoveScheduledJobCommandHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RemoveScheduledJobCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly IDomainEventsQueue _mockDomainEventsQueue;
private readonly IScheduledJobScheduler _mockScheduledJobScheduler;
private readonly IScheduledJobRepository _mockScheduledJobRepository;
private readonly IScheduledJobExecutionRepository _mockScheduledJobExecutionRepository;
private readonly IValidator<RemoveScheduledJobCommand> _mockValidator;
private readonly RemoveScheduledJobCommandHandler _sut;
private readonly RemoveScheduledJobCommandFixture _removeScheduledJobCommandFixture = new();
private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new();
private readonly Guid _userId = Guid.NewGuid();
/// <summary>
/// Initializes a new instance of the <see cref="RemoveScheduledJobCommandHandlerTests"/> class.
/// </summary>
public RemoveScheduledJobCommandHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockDomainEventsQueue = Substitute.For<IDomainEventsQueue>();
_mockScheduledJobScheduler = Substitute.For<IScheduledJobScheduler>();
_mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
_mockScheduledJobExecutionRepository = Substitute.For<IScheduledJobExecutionRepository>();
_mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository);
_mockUnitOfWork.ScheduledJobExecutionRepository.Returns(_mockScheduledJobExecutionRepository);
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(true);
_mockValidator = Substitute.For<IValidator<RemoveScheduledJobCommand>>();
_mockValidator.Validate(Arg.Any<RemoveScheduledJobCommand>()).Returns([]);
_sut = new RemoveScheduledJobCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockDomainEventsQueue, _mockScheduledJobScheduler, _mockUnitOfWork, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenScheduledJobExists_ShouldDeleteItAndEnqueueRemovedEvent()
{
// Arrange
RemoveScheduledJobCommand command = _removeScheduledJobCommandFixture.Create();
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(
id: command.ScheduledJobId,
scheduleType: ScheduleType.WithIntervalInMinutes,
status: ScheduledJobStatus.Active);
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
_mockScheduledJobExecutionRepository.DeleteByScheduledJobIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.Success);
_mockScheduledJobRepository.DeleteByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Success, result.Value);
await _mockScheduledJobScheduler.Received(1).StopCycleAsync(
Arg.Is<ScheduledJobId>(scheduledJobId => scheduledJobId.Value == command.ScheduledJobId),
Arg.Any<CancellationToken>());
await _mockScheduledJobExecutionRepository.Received(1).DeleteByScheduledJobIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>());
await _mockScheduledJobRepository.Received(1).DeleteByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
_mockDomainEventsQueue.Received(1).Enqueue(Arg.Is<IDomainEvent>(domainEvent => domainEvent is ScheduledJobRemovedDomainEvent));
}
[Fact]
public async Task HandleAsync_WhenValidatorReturnsError_ShouldReturnValidationErrorAndNotDelete()
{
// Arrange
RemoveScheduledJobCommand command = _removeScheduledJobCommandFixture.Create();
_mockValidator.Validate(Arg.Any<RemoveScheduledJobCommand>()).Returns([DomainErrors.Scheduling.ScheduledJobNotFound]);
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockScheduledJobRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorized()
{
// Arrange
RemoveScheduledJobCommand command = _removeScheduledJobCommandFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAdministrator_ShouldReturnNotAuthorized()
{
// Arrange
RemoveScheduledJobCommand command = _removeScheduledJobCommandFixture.Create();
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(false);
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenScheduledJobDoesNotExist_ShouldReturnNotFound()
{
// Arrange
RemoveScheduledJobCommand command = _removeScheduledJobCommandFixture.Create();
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(null));
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError);
await _mockScheduledJobScheduler.DidNotReceive().StopCycleAsync(Arg.Any<ScheduledJobId>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenDeleteExecutionsFails_ShouldReturnErrorAndNotDeleteScheduledJob()
{
// Arrange
RemoveScheduledJobCommand command = _removeScheduledJobCommandFixture.Create();
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(
id: command.ScheduledJobId,
scheduleType: ScheduleType.WithIntervalInMinutes,
status: ScheduledJobStatus.Active);
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
Error error = Error.Failure("Database.Error", "Failed to delete the executions");
_mockScheduledJobExecutionRepository.DeleteByScheduledJobIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenDeleteScheduledJobFails_ShouldReturnErrorAndNotSaveChanges()
{
// Arrange
RemoveScheduledJobCommand command = _removeScheduledJobCommandFixture.Create();
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(
id: command.ScheduledJobId,
scheduleType: ScheduleType.WithIntervalInMinutes,
status: ScheduledJobStatus.Active);
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
_mockScheduledJobExecutionRepository.DeleteByScheduledJobIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.Success);
_mockScheduledJobRepository.DeleteByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(DomainErrors.Scheduling.ScheduledJobNotFound);
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
}
}
@@ -0,0 +1,48 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Scheduling.Commands.RemoveScheduledJob;
using Lumina.Application.Fixtures.Core.Scheduling.Commands.RemoveScheduledJob;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Commands.RemoveScheduledJob;
/// <summary>
/// Contains unit tests for the <see cref="RemoveScheduledJobCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RemoveScheduledJobCommandValidatorTests
{
private readonly RemoveScheduledJobCommandValidator _validator = new();
private readonly RemoveScheduledJobCommandFixture _removeScheduledJobCommandFixture = new();
[Fact]
public void Validate_WhenScheduledJobIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
RemoveScheduledJobCommand command = _removeScheduledJobCommandFixture.Create() with { ScheduledJobId = Guid.Empty };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Scheduling.ScheduledJobNotFound);
}
[Fact]
public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationError()
{
// Arrange
RemoveScheduledJobCommand command = _removeScheduledJobCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -0,0 +1,203 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DomainEvents;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.Scheduling.Commands.StartScheduledJob;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Fixtures.Core.Scheduling.Commands.StartScheduledJob;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Commands.StartScheduledJob;
/// <summary>
/// Contains unit tests for the <see cref="StartScheduledJobCommandHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class StartScheduledJobCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly IDomainEventsQueue _mockDomainEventsQueue;
private readonly IScheduledJobRepository _mockScheduledJobRepository;
private readonly IValidator<StartScheduledJobCommand> _mockValidator;
private readonly StartScheduledJobCommandHandler _sut;
private readonly StartScheduledJobCommandFixture _startScheduledJobCommandFixture = new();
private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new();
private readonly Guid _userId = Guid.NewGuid();
/// <summary>
/// Initializes a new instance of the <see cref="StartScheduledJobCommandHandlerTests"/> class.
/// </summary>
public StartScheduledJobCommandHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockDomainEventsQueue = Substitute.For<IDomainEventsQueue>();
_mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
_mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository);
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(true);
_mockValidator = Substitute.For<IValidator<StartScheduledJobCommand>>();
_mockValidator.Validate(Arg.Any<StartScheduledJobCommand>()).Returns([]);
_sut = new StartScheduledJobCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockDomainEventsQueue, _mockUnitOfWork, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenScheduledJobIsAdded_ShouldUpdateToActiveAndEnqueueCycleStartedEvent()
{
// Arrange
StartScheduledJobCommand command = _startScheduledJobCommandFixture.Create();
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(
id: command.ScheduledJobId,
scheduleType: ScheduleType.WithIntervalInMinutes,
status: ScheduledJobStatus.Added);
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
_mockScheduledJobRepository.UpdateAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>()).Returns(Result.Updated);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(ScheduledJobStatus.Active, result.Value.Status);
await _mockScheduledJobRepository.Received(1).UpdateAsync(
Arg.Is<ScheduledJobEntity>(updatedScheduledJob => updatedScheduledJob.Status == ScheduledJobStatus.Active),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
_mockDomainEventsQueue.Received(1).Enqueue(Arg.Is<IDomainEvent>(domainEvent => domainEvent is ScheduledJobCycleStartedDomainEvent));
}
[Fact]
public async Task HandleAsync_WhenValidatorReturnsError_ShouldReturnValidationErrorAndNotPersist()
{
// Arrange
StartScheduledJobCommand command = _startScheduledJobCommandFixture.Create();
_mockValidator.Validate(Arg.Any<StartScheduledJobCommand>()).Returns([DomainErrors.Scheduling.ScheduledJobNotFound]);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorized()
{
// Arrange
StartScheduledJobCommand command = _startScheduledJobCommandFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAdministrator_ShouldReturnNotAuthorized()
{
// Arrange
StartScheduledJobCommand command = _startScheduledJobCommandFixture.Create();
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(false);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenScheduledJobDoesNotExist_ShouldReturnNotFound()
{
// Arrange
StartScheduledJobCommand command = _startScheduledJobCommandFixture.Create();
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(null));
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().UpdateAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenScheduledJobCycleAlreadyStarted_ShouldReturnCycleAlreadyStartedError()
{
// Arrange
StartScheduledJobCommand command = _startScheduledJobCommandFixture.Create();
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(
id: command.ScheduledJobId,
scheduleType: ScheduleType.WithIntervalInMinutes,
status: ScheduledJobStatus.Active);
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.ScheduledJobCycleAlreadyStarted, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().UpdateAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>());
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
}
[Fact]
public async Task HandleAsync_WhenUpdateFails_ShouldReturnErrorAndNotSaveChanges()
{
// Arrange
StartScheduledJobCommand command = _startScheduledJobCommandFixture.Create();
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(
id: command.ScheduledJobId,
scheduleType: ScheduleType.WithIntervalInMinutes,
status: ScheduledJobStatus.Added);
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
_mockScheduledJobRepository.UpdateAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>())
.Returns(DomainErrors.Scheduling.ScheduledJobNotFound);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
}
}
@@ -0,0 +1,48 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Scheduling.Commands.StartScheduledJob;
using Lumina.Application.Fixtures.Core.Scheduling.Commands.StartScheduledJob;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Commands.StartScheduledJob;
/// <summary>
/// Contains unit tests for the <see cref="StartScheduledJobCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class StartScheduledJobCommandValidatorTests
{
private readonly StartScheduledJobCommandValidator _validator = new();
private readonly StartScheduledJobCommandFixture _startScheduledJobCommandFixture = new();
[Fact]
public void Validate_WhenScheduledJobIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
StartScheduledJobCommand command = _startScheduledJobCommandFixture.Create() with { ScheduledJobId = Guid.Empty };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Scheduling.ScheduledJobNotFound);
}
[Fact]
public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationError()
{
// Arrange
StartScheduledJobCommand command = _startScheduledJobCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -0,0 +1,217 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DomainEvents;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Scheduling;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.Scheduling.Commands.StopScheduledJob;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Fixtures.Core.Scheduling.Commands.StopScheduledJob;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Commands.StopScheduledJob;
/// <summary>
/// Contains unit tests for the <see cref="StopScheduledJobCommandHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class StopScheduledJobCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly IDomainEventsQueue _mockDomainEventsQueue;
private readonly IScheduledJobScheduler _mockScheduledJobScheduler;
private readonly IScheduledJobRepository _mockScheduledJobRepository;
private readonly IValidator<StopScheduledJobCommand> _mockValidator;
private readonly StopScheduledJobCommandHandler _sut;
private readonly StopScheduledJobCommandFixture _stopScheduledJobCommandFixture = new();
private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new();
private readonly Guid _userId = Guid.NewGuid();
/// <summary>
/// Initializes a new instance of the <see cref="StopScheduledJobCommandHandlerTests"/> class.
/// </summary>
public StopScheduledJobCommandHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockDomainEventsQueue = Substitute.For<IDomainEventsQueue>();
_mockScheduledJobScheduler = Substitute.For<IScheduledJobScheduler>();
_mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
_mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository);
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(true);
_mockValidator = Substitute.For<IValidator<StopScheduledJobCommand>>();
_mockValidator.Validate(Arg.Any<StopScheduledJobCommand>()).Returns([]);
_sut = new StopScheduledJobCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockDomainEventsQueue, _mockScheduledJobScheduler, _mockUnitOfWork, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenScheduledJobIsActive_ShouldUpdateToAddedAndStopCycleInScheduler()
{
// Arrange
StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create();
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(
id: command.ScheduledJobId,
scheduleType: ScheduleType.WithIntervalInMinutes,
status: ScheduledJobStatus.Active);
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
_mockScheduledJobRepository.UpdateAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>()).Returns(Result.Updated);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(ScheduledJobStatus.Added, result.Value.Status);
await _mockScheduledJobRepository.Received(1).UpdateAsync(
Arg.Is<ScheduledJobEntity>(updatedScheduledJob => updatedScheduledJob.Status == ScheduledJobStatus.Added),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockScheduledJobScheduler.Received(1).StopCycleAsync(
Arg.Is<Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects.ScheduledJobId>(scheduledJobId => scheduledJobId.Value == command.ScheduledJobId),
Arg.Any<CancellationToken>());
_mockDomainEventsQueue.Received(1).Enqueue(Arg.Is<IDomainEvent>(domainEvent => domainEvent is ScheduledJobCycleStoppedDomainEvent));
}
[Fact]
public async Task HandleAsync_WhenScheduledJobIsRunning_ShouldEnqueueExecutionStoppedEvent()
{
// Arrange
StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create();
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(
id: command.ScheduledJobId,
scheduleType: ScheduleType.WithIntervalInMinutes,
status: ScheduledJobStatus.Running,
lastStartedOnUtc: DateTime.UtcNow.AddMinutes(-10));
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
_mockScheduledJobRepository.UpdateAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>()).Returns(Result.Updated);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(ScheduledJobStatus.Added, result.Value.Status);
_mockDomainEventsQueue.Received(1).Enqueue(Arg.Is<IDomainEvent>(domainEvent => domainEvent is ScheduledJobExecutionStoppedDomainEvent));
await _mockScheduledJobScheduler.Received(1).StopCycleAsync(Arg.Any<Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects.ScheduledJobId>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenValidatorReturnsError_ShouldReturnValidationErrorAndNotPersist()
{
// Arrange
StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create();
_mockValidator.Validate(Arg.Any<StopScheduledJobCommand>()).Returns([DomainErrors.Scheduling.ScheduledJobNotFound]);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockScheduledJobScheduler.DidNotReceive().StopCycleAsync(Arg.Any<Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects.ScheduledJobId>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorized()
{
// Arrange
StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenScheduledJobDoesNotExist_ShouldReturnNotFound()
{
// Arrange
StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create();
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(null));
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError);
await _mockScheduledJobScheduler.DidNotReceive().StopCycleAsync(Arg.Any<Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects.ScheduledJobId>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenScheduledJobCycleWasNeverStarted_ShouldReturnNotStartedError()
{
// Arrange
StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create();
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(
id: command.ScheduledJobId,
scheduleType: ScheduleType.WithIntervalInMinutes,
status: ScheduledJobStatus.Added);
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotStarted, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().UpdateAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>());
await _mockScheduledJobScheduler.DidNotReceive().StopCycleAsync(Arg.Any<Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects.ScheduledJobId>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUpdateFails_ShouldReturnErrorAndNotStopCycleInScheduler()
{
// Arrange
StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create();
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(
id: command.ScheduledJobId,
scheduleType: ScheduleType.WithIntervalInMinutes,
status: ScheduledJobStatus.Active);
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
_mockScheduledJobRepository.UpdateAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>())
.Returns(DomainErrors.Scheduling.ScheduledJobNotFound);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockScheduledJobScheduler.DidNotReceive().StopCycleAsync(Arg.Any<Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects.ScheduledJobId>(), Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,48 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Scheduling.Commands.StopScheduledJob;
using Lumina.Application.Fixtures.Core.Scheduling.Commands.StopScheduledJob;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Commands.StopScheduledJob;
/// <summary>
/// Contains unit tests for the <see cref="StopScheduledJobCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class StopScheduledJobCommandValidatorTests
{
private readonly StopScheduledJobCommandValidator _validator = new();
private readonly StopScheduledJobCommandFixture _stopScheduledJobCommandFixture = new();
[Fact]
public void Validate_WhenScheduledJobIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create() with { ScheduledJobId = Guid.Empty };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Scheduling.ScheduledJobNotFound);
}
[Fact]
public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationError()
{
// Arrange
StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -0,0 +1,152 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.Scheduling.Commands.UpdateSchedulerDisplayPreferences;
using Lumina.Application.Fixtures.Core.Scheduling.Commands.UpdateSchedulerDisplayPreferences;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Commands.UpdateSchedulerDisplayPreferences;
/// <summary>
/// Contains unit tests for the <see cref="UpdateSchedulerDisplayPreferencesCommandHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateSchedulerDisplayPreferencesCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ISchedulerDisplayPreferencesRepository _mockSchedulerDisplayPreferencesRepository;
private readonly IValidator<UpdateSchedulerDisplayPreferencesCommand> _mockValidator;
private readonly UpdateSchedulerDisplayPreferencesCommandHandler _sut;
private readonly UpdateSchedulerDisplayPreferencesCommandFixture _updateSchedulerDisplayPreferencesCommandFixture = new();
private readonly Guid _userId = Guid.NewGuid();
/// <summary>
/// Initializes a new instance of the <see cref="UpdateSchedulerDisplayPreferencesCommandHandlerTests"/> class.
/// </summary>
public UpdateSchedulerDisplayPreferencesCommandHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockSchedulerDisplayPreferencesRepository = Substitute.For<ISchedulerDisplayPreferencesRepository>();
_mockUnitOfWork.SchedulerDisplayPreferencesRepository.Returns(_mockSchedulerDisplayPreferencesRepository);
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(true);
_mockValidator = Substitute.For<IValidator<UpdateSchedulerDisplayPreferencesCommand>>();
_mockValidator.Validate(Arg.Any<UpdateSchedulerDisplayPreferencesCommand>()).Returns([]);
_sut = new UpdateSchedulerDisplayPreferencesCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenCommandIsValid_ShouldUpsertDisplayPreferencesAndReturnUpdated()
{
// Arrange
UpdateSchedulerDisplayPreferencesCommand command = _updateSchedulerDisplayPreferencesCommandFixture.Create(
jobTypeFilter: ScheduledTaskType.ScanMediaLibraries,
displayTimeSpan: 30,
displayTimeUnit: SchedulerDisplayTimeUnit.Minutes);
_mockSchedulerDisplayPreferencesRepository.UpsertAsync(Arg.Any<SchedulerDisplayPreferencesEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
await _mockSchedulerDisplayPreferencesRepository.Received(1).UpsertAsync(
Arg.Is<SchedulerDisplayPreferencesEntity>(preferences =>
preferences.UserId == _userId &&
preferences.JobTypeFilter == ScheduledTaskType.ScanMediaLibraries &&
preferences.DisplayTimeSpan == 30 &&
preferences.DisplayTimeUnit == SchedulerDisplayTimeUnit.Minutes),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenValidatorReturnsError_ShouldReturnValidationErrorAndNotPersist()
{
// Arrange
UpdateSchedulerDisplayPreferencesCommand command = _updateSchedulerDisplayPreferencesCommandFixture.Create(displayTimeSpan: 0);
_mockValidator.Validate(Arg.Any<UpdateSchedulerDisplayPreferencesCommand>())
.Returns([DomainErrors.Scheduling.SchedulerDisplayTimeSpanMustBePositive]);
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.SchedulerDisplayTimeSpanMustBePositive, result.FirstError);
await _mockSchedulerDisplayPreferencesRepository.DidNotReceive().UpsertAsync(Arg.Any<SchedulerDisplayPreferencesEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorized()
{
// Arrange
UpdateSchedulerDisplayPreferencesCommand command = _updateSchedulerDisplayPreferencesCommandFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockSchedulerDisplayPreferencesRepository.DidNotReceive().UpsertAsync(Arg.Any<SchedulerDisplayPreferencesEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAdministrator_ShouldReturnNotAuthorized()
{
// Arrange
UpdateSchedulerDisplayPreferencesCommand command = _updateSchedulerDisplayPreferencesCommandFixture.Create();
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(false);
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockSchedulerDisplayPreferencesRepository.DidNotReceive().UpsertAsync(Arg.Any<SchedulerDisplayPreferencesEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUpsertFails_ShouldReturnErrorAndNotSaveChanges()
{
// Arrange
UpdateSchedulerDisplayPreferencesCommand command = _updateSchedulerDisplayPreferencesCommandFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to upsert the display preferences");
_mockSchedulerDisplayPreferencesRepository.UpsertAsync(Arg.Any<SchedulerDisplayPreferencesEntity>(), Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,66 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Scheduling.Commands.UpdateSchedulerDisplayPreferences;
using Lumina.Application.Fixtures.Core.Scheduling.Commands.UpdateSchedulerDisplayPreferences;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Commands.UpdateSchedulerDisplayPreferences;
/// <summary>
/// Contains unit tests for the <see cref="UpdateSchedulerDisplayPreferencesCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateSchedulerDisplayPreferencesCommandValidatorTests
{
private readonly UpdateSchedulerDisplayPreferencesCommandValidator _validator = new();
private readonly UpdateSchedulerDisplayPreferencesCommandFixture _updateSchedulerDisplayPreferencesCommandFixture = new();
[Theory]
[InlineData(0)] // display time span of zero
[InlineData(-1)] // negative display time span
[InlineData(-100)] // negative display time span far from zero
public void Validate_WhenDisplayTimeSpanIsNotPositive_ShouldHaveValidationError(int displayTimeSpan)
{
// Arrange
UpdateSchedulerDisplayPreferencesCommand command = _updateSchedulerDisplayPreferencesCommandFixture.Create(displayTimeSpan: displayTimeSpan);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Scheduling.SchedulerDisplayTimeSpanMustBePositive);
}
[Theory]
[InlineData(1)] // minimal positive display time span
[InlineData(10)] // default display time span
[InlineData(1440)] // a day expressed in minutes
public void Validate_WhenDisplayTimeSpanIsPositive_ShouldNotHaveValidationError(int displayTimeSpan)
{
// Arrange
UpdateSchedulerDisplayPreferencesCommand command = _updateSchedulerDisplayPreferencesCommandFixture.Create(displayTimeSpan: displayTimeSpan);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Scheduling.SchedulerDisplayTimeSpanMustBePositive);
}
[Fact]
public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationError()
{
// Arrange
UpdateSchedulerDisplayPreferencesCommand command = _updateSchedulerDisplayPreferencesCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -0,0 +1,86 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Core.Scheduling.Events;
using Lumina.Application.Core.Scheduling.Notifications;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.Common.Exceptions;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Events;
/// <summary>
/// Contains unit tests for the <see cref="ScheduledJobAddedDomainEventHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScheduledJobAddedDomainEventHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IScheduledJobNotifier _mockScheduledJobNotifier;
private readonly IScheduledJobRepository _mockScheduledJobRepository;
private readonly ScheduledJobAddedDomainEventHandler _sut;
private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new();
private readonly ScheduledJobAddedDomainEventFixture _scheduledJobAddedDomainEventFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledJobAddedDomainEventHandlerTests"/> class.
/// </summary>
public ScheduledJobAddedDomainEventHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockScheduledJobNotifier = Substitute.For<IScheduledJobNotifier>();
_mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
_mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository);
_mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ScheduledJobEntity>>([]));
_sut = new ScheduledJobAddedDomainEventHandler(_mockScheduledJobNotifier, _mockUnitOfWork);
}
[Fact]
public async Task HandleAsync_WhenScheduledJobsAreLoaded_ShouldNotifyTheCurrentScheduledJobs()
{
// Arrange
ScheduledJobAddedDomainEvent domainEvent = _scheduledJobAddedDomainEventFixture.Create();
ScheduledJobEntity scheduledJob1 = _scheduledJobEntityFixture.Create(name: "Job 1");
ScheduledJobEntity scheduledJob2 = _scheduledJobEntityFixture.Create(name: "Job 2");
_mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ScheduledJobEntity>>([scheduledJob1, scheduledJob2]));
// Act
await _sut.HandleAsync(domainEvent, CancellationToken.None);
// Assert
await _mockScheduledJobNotifier.Received(1).SendScheduledJobsAsync(
Arg.Is<IReadOnlyList<ScheduledJobResponse>>(scheduledJobs => scheduledJobs.Count == 2),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetAllScheduledJobsFails_ShouldThrowEventualConsistencyException()
{
// Arrange
ScheduledJobAddedDomainEvent domainEvent = _scheduledJobAddedDomainEventFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to get the scheduled jobs");
_mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(error);
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
await _mockScheduledJobNotifier.DidNotReceive().SendScheduledJobsAsync(Arg.Any<IReadOnlyList<ScheduledJobResponse>>(), Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,82 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Scheduling;
using Lumina.Application.Core.Scheduling.Events;
using Lumina.Application.Core.Scheduling.Notifications;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.Common.Exceptions;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Events;
/// <summary>
/// Contains unit tests for the <see cref="ScheduledJobCycleStartedDomainEventHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScheduledJobCycleStartedDomainEventHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IScheduledJobNotifier _mockScheduledJobNotifier;
private readonly IScheduledJobScheduler _mockScheduledJobScheduler;
private readonly IScheduledJobRepository _mockScheduledJobRepository;
private readonly ScheduledJobCycleStartedDomainEventHandler _sut;
private readonly ScheduledJobCycleStartedDomainEventFixture _scheduledJobCycleStartedDomainEventFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledJobCycleStartedDomainEventHandlerTests"/> class.
/// </summary>
public ScheduledJobCycleStartedDomainEventHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockScheduledJobNotifier = Substitute.For<IScheduledJobNotifier>();
_mockScheduledJobScheduler = Substitute.For<IScheduledJobScheduler>();
_mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
_mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository);
_mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ScheduledJobEntity>>([]));
_sut = new ScheduledJobCycleStartedDomainEventHandler(_mockScheduledJobNotifier, _mockScheduledJobScheduler, _mockUnitOfWork);
}
[Fact]
public async Task HandleAsync_WhenScheduledJobsAreLoaded_ShouldStartTheCycleInTheSchedulerAndNotify()
{
// Arrange
ScheduledJobCycleStartedDomainEvent domainEvent = _scheduledJobCycleStartedDomainEventFixture.Create();
// Act
await _sut.HandleAsync(domainEvent, CancellationToken.None);
// Assert
await _mockScheduledJobScheduler.Received(1).StartCycleAsync(domainEvent.ScheduledJobId, Arg.Any<CancellationToken>());
await _mockScheduledJobNotifier.Received(1).SendScheduledJobsAsync(Arg.Any<IReadOnlyList<ScheduledJobResponse>>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetAllScheduledJobsFails_ShouldThrowEventualConsistencyException()
{
// Arrange
ScheduledJobCycleStartedDomainEvent domainEvent = _scheduledJobCycleStartedDomainEventFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to get the scheduled jobs");
_mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(error);
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
await _mockScheduledJobNotifier.DidNotReceive().SendScheduledJobsAsync(Arg.Any<IReadOnlyList<ScheduledJobResponse>>(), Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,84 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Core.Scheduling.Events;
using Lumina.Application.Core.Scheduling.Notifications;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.Common.Exceptions;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Events;
/// <summary>
/// Contains unit tests for the <see cref="ScheduledJobCycleStoppedDomainEventHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScheduledJobCycleStoppedDomainEventHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IScheduledJobNotifier _mockScheduledJobNotifier;
private readonly IScheduledJobRepository _mockScheduledJobRepository;
private readonly ScheduledJobCycleStoppedDomainEventHandler _sut;
private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new();
private readonly ScheduledJobCycleStoppedDomainEventFixture _scheduledJobCycleStoppedDomainEventFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledJobCycleStoppedDomainEventHandlerTests"/> class.
/// </summary>
public ScheduledJobCycleStoppedDomainEventHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockScheduledJobNotifier = Substitute.For<IScheduledJobNotifier>();
_mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
_mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository);
_mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ScheduledJobEntity>>([]));
_sut = new ScheduledJobCycleStoppedDomainEventHandler(_mockScheduledJobNotifier, _mockUnitOfWork);
}
[Fact]
public async Task HandleAsync_WhenScheduledJobsAreLoaded_ShouldNotifyTheCurrentScheduledJobs()
{
// 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<CancellationToken>()).Returns(Result.From<IEnumerable<ScheduledJobEntity>>([stoppedJob]));
// Act
await _sut.HandleAsync(domainEvent, CancellationToken.None);
// Assert
await _mockScheduledJobNotifier.Received(1).SendScheduledJobsAsync(
Arg.Is<IReadOnlyList<ScheduledJobResponse>>(scheduledJobs => scheduledJobs.Count == 1),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetAllScheduledJobsFails_ShouldThrowEventualConsistencyException()
{
// Arrange
ScheduledJobCycleStoppedDomainEvent domainEvent = _scheduledJobCycleStoppedDomainEventFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to get the scheduled jobs");
_mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(error);
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
await _mockScheduledJobNotifier.DidNotReceive().SendScheduledJobsAsync(Arg.Any<IReadOnlyList<ScheduledJobResponse>>(), Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,200 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Core.Scheduling.Events;
using Lumina.Application.Core.Scheduling.Notifications;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Exceptions;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Events;
/// <summary>
/// Contains unit tests for the <see cref="ScheduledJobExecutionCompletedDomainEventHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScheduledJobExecutionCompletedDomainEventHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IScheduledJobNotifier _mockScheduledJobNotifier;
private readonly IScheduledJobRepository _mockScheduledJobRepository;
private readonly IScheduledJobExecutionRepository _mockScheduledJobExecutionRepository;
private readonly ScheduledJobExecutionCompletedDomainEventHandler _sut;
private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new();
private readonly ScheduledJobExecutionEntityFixture _scheduledJobExecutionEntityFixture = new();
private readonly ScheduledJobExecutionCompletedDomainEventFixture _scheduledJobExecutionCompletedDomainEventFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledJobExecutionCompletedDomainEventHandlerTests"/> class.
/// </summary>
public ScheduledJobExecutionCompletedDomainEventHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockScheduledJobNotifier = Substitute.For<IScheduledJobNotifier>();
_mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
_mockScheduledJobExecutionRepository = Substitute.For<IScheduledJobExecutionRepository>();
_mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository);
_mockUnitOfWork.ScheduledJobExecutionRepository.Returns(_mockScheduledJobExecutionRepository);
_mockScheduledJobRepository.UpdateAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>()).Returns(Result.Updated);
_mockScheduledJobExecutionRepository.UpdateAsync(Arg.Any<ScheduledJobExecutionEntity>(), Arg.Any<CancellationToken>()).Returns(Result.Updated);
_mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ScheduledJobEntity>>([]));
_sut = new ScheduledJobExecutionCompletedDomainEventHandler(_mockScheduledJobNotifier, _mockUnitOfWork);
}
[Theory]
[InlineData(true, ScheduledJobStatus.Active)] // a cycle run returns the scheduled job to its active status
[InlineData(false, ScheduledJobStatus.Completed)] // a one time execution completes the scheduled job
public async Task HandleAsync_WhenScheduledJobAndExecutionExist_ShouldUpdateBothAndNotify(bool isCycleRun, ScheduledJobStatus expectedStatus)
{
// Arrange
DateTime completedOnUtc = DateTime.UtcNow;
ScheduledJobExecutionCompletedDomainEvent domainEvent = _scheduledJobExecutionCompletedDomainEventFixture.Create(isCycleRun: isCycleRun, completedOnUtc: completedOnUtc);
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(
id: domainEvent.ScheduledJobId.Value,
status: ScheduledJobStatus.Running,
lastStartedOnUtc: completedOnUtc.AddMinutes(-5));
_mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
ScheduledJobExecutionEntity execution = _scheduledJobExecutionEntityFixture.Create(
id: domainEvent.RunId,
scheduledJobId: scheduledJob.Id,
isCycleRun: isCycleRun,
completedOnUtc: null);
_mockScheduledJobExecutionRepository.GetByIdAsync(domainEvent.RunId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobExecutionEntity?>(execution));
// Act
await _sut.HandleAsync(domainEvent, CancellationToken.None);
// Assert
await _mockScheduledJobRepository.Received(1).UpdateAsync(
Arg.Is<ScheduledJobEntity>(updatedScheduledJob =>
updatedScheduledJob.Status == expectedStatus &&
updatedScheduledJob.LastCompletedOnUtc == completedOnUtc),
Arg.Any<CancellationToken>());
await _mockScheduledJobExecutionRepository.Received(1).UpdateAsync(
Arg.Is<ScheduledJobExecutionEntity>(updatedExecution => updatedExecution.CompletedOnUtc == completedOnUtc),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockScheduledJobNotifier.Received(1).SendScheduledJobsAsync(Arg.Any<IReadOnlyList<ScheduledJobResponse>>(), Arg.Any<CancellationToken>());
await _mockScheduledJobNotifier.Received(1).SendScheduledJobExecutionCompletedAsync(Arg.Any<ScheduledJobExecutionResponse>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenScheduledJobDoesNotExist_ShouldThrowEventualConsistencyException()
{
// Arrange
ScheduledJobExecutionCompletedDomainEvent domainEvent = _scheduledJobExecutionCompletedDomainEventFixture.Create(isCycleRun: true);
_mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(null));
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(Errors.Scheduling.ScheduledJobNotFound, exception.EventualConsistencyError);
await _mockScheduledJobExecutionRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUpdateScheduledJobFails_ShouldThrowEventualConsistencyException()
{
// 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<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
Error error = Error.Failure("Database.Error", "Failed to update the scheduled job");
_mockScheduledJobRepository.UpdateAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>()).Returns(error);
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
await _mockScheduledJobExecutionRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenExecutionDoesNotExist_ShouldThrowEventualConsistencyException()
{
// 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<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
_mockScheduledJobExecutionRepository.GetByIdAsync(domainEvent.RunId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobExecutionEntity?>(null));
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(Errors.Scheduling.ScheduledJobExecutionNotFound, exception.EventualConsistencyError);
await _mockScheduledJobExecutionRepository.DidNotReceive().UpdateAsync(Arg.Any<ScheduledJobExecutionEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUpdateExecutionFails_ShouldThrowEventualConsistencyException()
{
// 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<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
ScheduledJobExecutionEntity execution = _scheduledJobExecutionEntityFixture.Create(id: domainEvent.RunId);
_mockScheduledJobExecutionRepository.GetByIdAsync(domainEvent.RunId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobExecutionEntity?>(execution));
Error error = Error.Failure("Database.Error", "Failed to update the execution");
_mockScheduledJobExecutionRepository.UpdateAsync(Arg.Any<ScheduledJobExecutionEntity>(), Arg.Any<CancellationToken>()).Returns(error);
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetAllScheduledJobsFails_ShouldThrowEventualConsistencyException()
{
// 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<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
ScheduledJobExecutionEntity execution = _scheduledJobExecutionEntityFixture.Create(id: domainEvent.RunId);
_mockScheduledJobExecutionRepository.GetByIdAsync(domainEvent.RunId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobExecutionEntity?>(execution));
Error error = Error.Failure("Database.Error", "Failed to get the scheduled jobs");
_mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(error);
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
await _mockScheduledJobNotifier.DidNotReceive().SendScheduledJobExecutionCompletedAsync(Arg.Any<ScheduledJobExecutionResponse>(), Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,191 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Core.Scheduling.Events;
using Lumina.Application.Core.Scheduling.Notifications;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Exceptions;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Events;
/// <summary>
/// Contains unit tests for the <see cref="ScheduledJobExecutionStartedDomainEventHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScheduledJobExecutionStartedDomainEventHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IScheduledJobNotifier _mockScheduledJobNotifier;
private readonly IScheduledJobRepository _mockScheduledJobRepository;
private readonly IScheduledJobExecutionRepository _mockScheduledJobExecutionRepository;
private readonly ScheduledJobExecutionStartedDomainEventHandler _sut;
private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new();
private readonly ScheduledJobExecutionEntityFixture _scheduledJobExecutionEntityFixture = new();
private readonly ScheduledJobExecutionStartedDomainEventFixture _scheduledJobExecutionStartedDomainEventFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledJobExecutionStartedDomainEventHandlerTests"/> class.
/// </summary>
public ScheduledJobExecutionStartedDomainEventHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockScheduledJobNotifier = Substitute.For<IScheduledJobNotifier>();
_mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
_mockScheduledJobExecutionRepository = Substitute.For<IScheduledJobExecutionRepository>();
_mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository);
_mockUnitOfWork.ScheduledJobExecutionRepository.Returns(_mockScheduledJobExecutionRepository);
_mockScheduledJobRepository.UpdateAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>()).Returns(Result.Updated);
_mockScheduledJobExecutionRepository.InsertAsync(Arg.Any<ScheduledJobExecutionEntity>(), Arg.Any<CancellationToken>()).Returns(Result.Created);
_mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ScheduledJobEntity>>([]));
_sut = new ScheduledJobExecutionStartedDomainEventHandler(_mockScheduledJobNotifier, _mockUnitOfWork);
}
[Fact]
public async Task HandleAsync_WhenScheduledJobExists_ShouldUpdateItsStatusAndInsertTheExecution()
{
// Arrange
DateTime startedOnUtc = DateTime.UtcNow.AddMinutes(-1);
ScheduledJobExecutionStartedDomainEvent domainEvent = _scheduledJobExecutionStartedDomainEventFixture.Create(startedOnUtc: startedOnUtc);
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(
id: domainEvent.ScheduledJobId.Value,
taskType: domainEvent.TaskType,
scheduleType: ScheduleType.WithIntervalInMinutes,
status: ScheduledJobStatus.Active);
_mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
// Act
await _sut.HandleAsync(domainEvent, CancellationToken.None);
// Assert
await _mockScheduledJobRepository.Received(1).UpdateAsync(
Arg.Is<ScheduledJobEntity>(updatedScheduledJob =>
updatedScheduledJob.Status == ScheduledJobStatus.Running &&
updatedScheduledJob.LastStartedOnUtc == startedOnUtc),
Arg.Any<CancellationToken>());
await _mockScheduledJobExecutionRepository.Received(1).InsertAsync(
Arg.Is<ScheduledJobExecutionEntity>(execution =>
execution.Id == domainEvent.RunId &&
execution.ScheduledJobId == scheduledJob.Id &&
execution.TaskType == domainEvent.TaskType &&
execution.IsCycleRun == domainEvent.IsCycleRun &&
execution.StartedOnUtc == startedOnUtc &&
execution.CompletedOnUtc == null),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockScheduledJobNotifier.Received(1).SendScheduledJobsAsync(Arg.Any<IReadOnlyList<ScheduledJobResponse>>(), Arg.Any<CancellationToken>());
await _mockScheduledJobNotifier.Received(1).SendScheduledJobExecutionStartedAsync(Arg.Any<ScheduledJobExecutionResponse>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetByIdReturnsError_ShouldThrowEventualConsistencyException()
{
// Arrange
ScheduledJobExecutionStartedDomainEvent domainEvent = _scheduledJobExecutionStartedDomainEventFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to get the scheduled job");
_mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any<CancellationToken>()).Returns(error);
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
await _mockScheduledJobExecutionRepository.DidNotReceive().InsertAsync(Arg.Any<ScheduledJobExecutionEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenScheduledJobDoesNotExist_ShouldThrowEventualConsistencyException()
{
// Arrange
ScheduledJobExecutionStartedDomainEvent domainEvent = _scheduledJobExecutionStartedDomainEventFixture.Create();
_mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(null));
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(Errors.Scheduling.ScheduledJobNotFound, exception.EventualConsistencyError);
}
[Fact]
public async Task HandleAsync_WhenUpdateFails_ShouldThrowEventualConsistencyException()
{
// Arrange
ScheduledJobExecutionStartedDomainEvent domainEvent = _scheduledJobExecutionStartedDomainEventFixture.Create();
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(
id: domainEvent.ScheduledJobId.Value,
status: ScheduledJobStatus.Active);
_mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
Error error = Error.Failure("Database.Error", "Failed to update the scheduled job");
_mockScheduledJobRepository.UpdateAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>()).Returns(error);
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
await _mockScheduledJobExecutionRepository.DidNotReceive().InsertAsync(Arg.Any<ScheduledJobExecutionEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenInsertExecutionFails_ShouldThrowEventualConsistencyException()
{
// Arrange
ScheduledJobExecutionStartedDomainEvent domainEvent = _scheduledJobExecutionStartedDomainEventFixture.Create();
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(id: domainEvent.ScheduledJobId.Value);
_mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
Error error = Error.Failure("Database.Error", "Failed to insert the execution");
_mockScheduledJobExecutionRepository.InsertAsync(Arg.Any<ScheduledJobExecutionEntity>(), Arg.Any<CancellationToken>()).Returns(error);
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetAllScheduledJobsFails_ShouldThrowEventualConsistencyException()
{
// Arrange
ScheduledJobExecutionStartedDomainEvent domainEvent = _scheduledJobExecutionStartedDomainEventFixture.Create();
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(id: domainEvent.ScheduledJobId.Value);
_mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
Error error = Error.Failure("Database.Error", "Failed to get the scheduled jobs");
_mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(error);
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
await _mockScheduledJobNotifier.DidNotReceive().SendScheduledJobExecutionStartedAsync(Arg.Any<ScheduledJobExecutionResponse>(), Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,153 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Core.Scheduling.Events;
using Lumina.Application.Core.Scheduling.Notifications;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.Common.Exceptions;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Events;
/// <summary>
/// Contains unit tests for the <see cref="ScheduledJobExecutionStoppedDomainEventHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScheduledJobExecutionStoppedDomainEventHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IScheduledJobNotifier _mockScheduledJobNotifier;
private readonly IScheduledJobRepository _mockScheduledJobRepository;
private readonly IScheduledJobExecutionRepository _mockScheduledJobExecutionRepository;
private readonly ScheduledJobExecutionStoppedDomainEventHandler _sut;
private readonly ScheduledJobExecutionEntityFixture _scheduledJobExecutionEntityFixture = new();
private readonly ScheduledJobExecutionStoppedDomainEventFixture _scheduledJobExecutionStoppedDomainEventFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledJobExecutionStoppedDomainEventHandlerTests"/> class.
/// </summary>
public ScheduledJobExecutionStoppedDomainEventHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockScheduledJobNotifier = Substitute.For<IScheduledJobNotifier>();
_mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
_mockScheduledJobExecutionRepository = Substitute.For<IScheduledJobExecutionRepository>();
_mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository);
_mockUnitOfWork.ScheduledJobExecutionRepository.Returns(_mockScheduledJobExecutionRepository);
_mockScheduledJobExecutionRepository.UpdateAsync(Arg.Any<ScheduledJobExecutionEntity>(), Arg.Any<CancellationToken>()).Returns(Result.Updated);
_mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ScheduledJobEntity>>([]));
_sut = new ScheduledJobExecutionStoppedDomainEventHandler(_mockScheduledJobNotifier, _mockUnitOfWork);
}
[Fact]
public async Task HandleAsync_WhenOpenExecutionExists_ShouldCloseItAndNotifyScheduledJobs()
{
// Arrange
DateTime occurredOnUtc = DateTime.UtcNow;
ScheduledJobExecutionStoppedDomainEvent domainEvent = _scheduledJobExecutionStoppedDomainEventFixture.Create(occurredOnUtc: occurredOnUtc);
ScheduledJobExecutionEntity openExecution = _scheduledJobExecutionEntityFixture.Create(
scheduledJobId: domainEvent.ScheduledJobId.Value,
completedOnUtc: null);
_mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobExecutionEntity?>(openExecution));
// Act
await _sut.HandleAsync(domainEvent, CancellationToken.None);
// Assert
await _mockScheduledJobExecutionRepository.Received(1).UpdateAsync(
Arg.Is<ScheduledJobExecutionEntity>(updatedExecution => updatedExecution.CompletedOnUtc == occurredOnUtc),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockScheduledJobNotifier.Received(1).SendScheduledJobsAsync(Arg.Any<IReadOnlyList<ScheduledJobResponse>>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenNoOpenExecutionExists_ShouldOnlyNotifyScheduledJobs()
{
// Arrange
ScheduledJobExecutionStoppedDomainEvent domainEvent = _scheduledJobExecutionStoppedDomainEventFixture.Create();
_mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobExecutionEntity?>(null));
// Act
await _sut.HandleAsync(domainEvent, CancellationToken.None);
// Assert
await _mockScheduledJobExecutionRepository.DidNotReceive().UpdateAsync(Arg.Any<ScheduledJobExecutionEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockScheduledJobNotifier.Received(1).SendScheduledJobsAsync(Arg.Any<IReadOnlyList<ScheduledJobResponse>>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetOpenExecutionFails_ShouldThrowEventualConsistencyException()
{
// Arrange
ScheduledJobExecutionStoppedDomainEvent domainEvent = _scheduledJobExecutionStoppedDomainEventFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to get the open execution");
_mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any<CancellationToken>())
.Returns(error);
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
await _mockScheduledJobNotifier.DidNotReceive().SendScheduledJobsAsync(Arg.Any<IReadOnlyList<ScheduledJobResponse>>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUpdateExecutionFails_ShouldThrowEventualConsistencyException()
{
// Arrange
ScheduledJobExecutionStoppedDomainEvent domainEvent = _scheduledJobExecutionStoppedDomainEventFixture.Create();
ScheduledJobExecutionEntity openExecution = _scheduledJobExecutionEntityFixture.Create(
scheduledJobId: domainEvent.ScheduledJobId.Value,
completedOnUtc: null);
_mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobExecutionEntity?>(openExecution));
Error error = Error.Failure("Database.Error", "Failed to update the execution");
_mockScheduledJobExecutionRepository.UpdateAsync(Arg.Any<ScheduledJobExecutionEntity>(), Arg.Any<CancellationToken>()).Returns(error);
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
await _mockScheduledJobNotifier.DidNotReceive().SendScheduledJobsAsync(Arg.Any<IReadOnlyList<ScheduledJobResponse>>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetAllScheduledJobsFails_ShouldThrowEventualConsistencyException()
{
// Arrange
ScheduledJobExecutionStoppedDomainEvent domainEvent = _scheduledJobExecutionStoppedDomainEventFixture.Create();
_mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobExecutionEntity?>(null));
Error error = Error.Failure("Database.Error", "Failed to get the scheduled jobs");
_mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(error);
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
await _mockScheduledJobNotifier.DidNotReceive().SendScheduledJobsAsync(Arg.Any<IReadOnlyList<ScheduledJobResponse>>(), Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,46 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Scheduling;
using Lumina.Application.Core.Scheduling.Events;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Events;
/// <summary>
/// Contains unit tests for the <see cref="ScheduledJobFiredDomainEventHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScheduledJobFiredDomainEventHandlerTests
{
private readonly IScheduledJobScheduler _mockScheduledJobScheduler;
private readonly ScheduledJobFiredDomainEventHandler _sut;
private readonly ScheduledJobFiredDomainEventFixture _scheduledJobFiredDomainEventFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledJobFiredDomainEventHandlerTests"/> class.
/// </summary>
public ScheduledJobFiredDomainEventHandlerTests()
{
_mockScheduledJobScheduler = Substitute.For<IScheduledJobScheduler>();
_sut = new ScheduledJobFiredDomainEventHandler(_mockScheduledJobScheduler);
}
[Fact]
public async Task HandleAsync_WhenFiredEventIsHandled_ShouldRunTheTaskOnceInTheScheduler()
{
// Arrange
ScheduledJobFiredDomainEvent domainEvent = _scheduledJobFiredDomainEventFixture.Create();
// Act
await _sut.HandleAsync(domainEvent, CancellationToken.None);
// Assert
await _mockScheduledJobScheduler.Received(1).RunOnceAsync(domainEvent.ScheduledJobId, Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,84 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Core.Scheduling.Events;
using Lumina.Application.Core.Scheduling.Notifications;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.Common.Exceptions;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Events;
/// <summary>
/// Contains unit tests for the <see cref="ScheduledJobRemovedDomainEventHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScheduledJobRemovedDomainEventHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IScheduledJobNotifier _mockScheduledJobNotifier;
private readonly IScheduledJobRepository _mockScheduledJobRepository;
private readonly ScheduledJobRemovedDomainEventHandler _sut;
private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new();
private readonly ScheduledJobRemovedDomainEventFixture _scheduledJobRemovedDomainEventFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledJobRemovedDomainEventHandlerTests"/> class.
/// </summary>
public ScheduledJobRemovedDomainEventHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockScheduledJobNotifier = Substitute.For<IScheduledJobNotifier>();
_mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
_mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository);
_mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ScheduledJobEntity>>([]));
_sut = new ScheduledJobRemovedDomainEventHandler(_mockScheduledJobNotifier, _mockUnitOfWork);
}
[Fact]
public async Task HandleAsync_WhenScheduledJobsAreLoaded_ShouldNotifyTheCurrentScheduledJobs()
{
// Arrange
ScheduledJobRemovedDomainEvent domainEvent = _scheduledJobRemovedDomainEventFixture.Create();
ScheduledJobEntity remainingJob = _scheduledJobEntityFixture.Create(name: "Remaining job");
_mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ScheduledJobEntity>>([remainingJob]));
// Act
await _sut.HandleAsync(domainEvent, CancellationToken.None);
// Assert
await _mockScheduledJobNotifier.Received(1).SendScheduledJobsAsync(
Arg.Is<IReadOnlyList<ScheduledJobResponse>>(scheduledJobs => scheduledJobs.Count == 1),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetAllScheduledJobsFails_ShouldThrowEventualConsistencyException()
{
// Arrange
ScheduledJobRemovedDomainEvent domainEvent = _scheduledJobRemovedDomainEventFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to get the scheduled jobs");
_mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(error);
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
await _mockScheduledJobNotifier.DidNotReceive().SendScheduledJobsAsync(Arg.Any<IReadOnlyList<ScheduledJobResponse>>(), Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,161 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Core.Scheduling.Queries.GetScheduledJobHistory;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Fixtures.Core.Scheduling.Queries.GetScheduledJobHistory;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.Common.Primitives;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Queries.GetScheduledJobHistory;
/// <summary>
/// Contains unit tests for the <see cref="GetScheduledJobHistoryQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetScheduledJobHistoryQueryHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly IScheduledJobExecutionRepository _mockScheduledJobExecutionRepository;
private readonly GetScheduledJobHistoryQueryHandler _sut;
private readonly GetScheduledJobHistoryQueryFixture _getScheduledJobHistoryQueryFixture = new();
private readonly ScheduledJobExecutionEntityFixture _scheduledJobExecutionEntityFixture = new();
private readonly Guid _userId = Guid.NewGuid();
/// <summary>
/// Initializes a new instance of the <see cref="GetScheduledJobHistoryQueryHandlerTests"/> class.
/// </summary>
public GetScheduledJobHistoryQueryHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockScheduledJobExecutionRepository = Substitute.For<IScheduledJobExecutionRepository>();
_mockUnitOfWork.ScheduledJobExecutionRepository.Returns(_mockScheduledJobExecutionRepository);
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(true);
_sut = new GetScheduledJobHistoryQueryHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork);
}
[Fact]
public async Task HandleAsync_WhenExecutionsExistInTheRequestedRange_ShouldReturnThemAsResponses()
{
// Arrange
GetScheduledJobHistoryQuery query = _getScheduledJobHistoryQueryFixture.Create();
ScheduledJobExecutionEntity execution1 = _scheduledJobExecutionEntityFixture.Create(startedOnUtc: query.From);
ScheduledJobExecutionEntity execution2 = _scheduledJobExecutionEntityFixture.Create(startedOnUtc: query.From!.Value.AddMinutes(1));
_mockScheduledJobExecutionRepository.GetByTimeRangeAsync(query.From!.Value, query.To!.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IEnumerable<ScheduledJobExecutionEntity>>([execution1, execution2]));
// Act
Result<IEnumerable<ScheduledJobExecutionResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(2, result.Value.Count());
Assert.Contains(result.Value, execution => execution.Id == execution1.Id);
Assert.Contains(result.Value, execution => execution.Id == execution2.Id);
}
[Fact]
public async Task HandleAsync_WhenNoExecutionsExist_ShouldReturnEmptyCollection()
{
// Arrange
GetScheduledJobHistoryQuery query = _getScheduledJobHistoryQueryFixture.Create();
_mockScheduledJobExecutionRepository.GetByTimeRangeAsync(query.From!.Value, query.To!.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IEnumerable<ScheduledJobExecutionEntity>>([]));
// Act
Result<IEnumerable<ScheduledJobExecutionResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Empty(result.Value);
}
[Fact]
public async Task HandleAsync_WhenBoundsAreNotProvided_ShouldDefaultToThePastDay()
{
// Arrange
GetScheduledJobHistoryQuery query = _getScheduledJobHistoryQueryFixture.Create(includeFrom: false, includeTo: false);
DateTime beforeCall = DateTime.UtcNow;
_mockScheduledJobExecutionRepository.GetByTimeRangeAsync(Arg.Any<DateTime>(), Arg.Any<DateTime>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IEnumerable<ScheduledJobExecutionEntity>>([]));
// Act
Result<IEnumerable<ScheduledJobExecutionResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
DateTime afterCall = DateTime.UtcNow;
// Assert
Assert.False(result.IsFailure);
await _mockScheduledJobExecutionRepository.Received(1).GetByTimeRangeAsync(
Arg.Is<DateTime>(fromUtc => fromUtc <= afterCall && fromUtc >= beforeCall.AddDays(-1)),
Arg.Is<DateTime>(toUtc => toUtc >= beforeCall && toUtc <= afterCall),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorized()
{
// Arrange
GetScheduledJobHistoryQuery query = _getScheduledJobHistoryQueryFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<IEnumerable<ScheduledJobExecutionResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockScheduledJobExecutionRepository.DidNotReceive().GetByTimeRangeAsync(Arg.Any<DateTime>(), Arg.Any<DateTime>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAdministrator_ShouldReturnNotAuthorized()
{
// Arrange
GetScheduledJobHistoryQuery query = _getScheduledJobHistoryQueryFixture.Create();
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(false);
// Act
Result<IEnumerable<ScheduledJobExecutionResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockScheduledJobExecutionRepository.DidNotReceive().GetByTimeRangeAsync(Arg.Any<DateTime>(), Arg.Any<DateTime>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetByTimeRangeReturnsError_ShouldReturnError()
{
// Arrange
GetScheduledJobHistoryQuery query = _getScheduledJobHistoryQueryFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to get the execution history");
_mockScheduledJobExecutionRepository.GetByTimeRangeAsync(query.From!.Value, query.To!.Value, Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<IEnumerable<ScheduledJobExecutionResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
}
}
@@ -0,0 +1,132 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Core.Scheduling.Queries.GetScheduledJobs;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.Common.Primitives;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Queries.GetScheduledJobs;
/// <summary>
/// Contains unit tests for the <see cref="GetScheduledJobsQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetScheduledJobsQueryHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly IScheduledJobRepository _mockScheduledJobRepository;
private readonly GetScheduledJobsQueryHandler _sut;
private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new();
private readonly Guid _userId = Guid.NewGuid();
/// <summary>
/// Initializes a new instance of the <see cref="GetScheduledJobsQueryHandlerTests"/> class.
/// </summary>
public GetScheduledJobsQueryHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
_mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository);
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(true);
_sut = new GetScheduledJobsQueryHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork);
}
[Fact]
public async Task HandleAsync_WhenScheduledJobsExist_ShouldReturnAllOfThemAsResponses()
{
// Arrange
ScheduledJobEntity scheduledJob1 = _scheduledJobEntityFixture.Create(name: "Job 1");
ScheduledJobEntity scheduledJob2 = _scheduledJobEntityFixture.Create(name: "Job 2");
_mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(Result.From<IEnumerable<ScheduledJobEntity>>([scheduledJob1, scheduledJob2]));
// Act
Result<IEnumerable<ScheduledJobResponse>> result = await _sut.HandleAsync(new GetScheduledJobsQuery(), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(2, result.Value.Count());
Assert.Contains(result.Value, scheduledJob => scheduledJob.Id == scheduledJob1.Id && scheduledJob.Name == "Job 1");
Assert.Contains(result.Value, scheduledJob => scheduledJob.Id == scheduledJob2.Id && scheduledJob.Name == "Job 2");
}
[Fact]
public async Task HandleAsync_WhenNoScheduledJobsExist_ShouldReturnEmptyCollection()
{
// Arrange
_mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(Result.From<IEnumerable<ScheduledJobEntity>>([]));
// Act
Result<IEnumerable<ScheduledJobResponse>> result = await _sut.HandleAsync(new GetScheduledJobsQuery(), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Empty(result.Value);
}
[Fact]
public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorized()
{
// Arrange
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<IEnumerable<ScheduledJobResponse>> result = await _sut.HandleAsync(new GetScheduledJobsQuery(), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().GetAllAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAdministrator_ShouldReturnNotAuthorized()
{
// Arrange
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(false);
// Act
Result<IEnumerable<ScheduledJobResponse>> result = await _sut.HandleAsync(new GetScheduledJobsQuery(), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().GetAllAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetAllReturnsError_ShouldReturnError()
{
// Arrange
Error error = Error.Failure("Database.Error", "Failed to get the scheduled jobs");
_mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(error);
// Act
Result<IEnumerable<ScheduledJobResponse>> result = await _sut.HandleAsync(new GetScheduledJobsQuery(), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
}
}
@@ -0,0 +1,142 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Core.Scheduling.Queries.GetSchedulerDisplayPreferences;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Queries.GetSchedulerDisplayPreferences;
/// <summary>
/// Contains unit tests for the <see cref="GetSchedulerDisplayPreferencesQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetSchedulerDisplayPreferencesQueryHandlerTests
{
private const int DEFAULT_DISPLAY_TIME_SPAN = 10;
private const SchedulerDisplayTimeUnit DEFAULT_DISPLAY_TIME_UNIT = SchedulerDisplayTimeUnit.Minutes;
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ISchedulerDisplayPreferencesRepository _mockSchedulerDisplayPreferencesRepository;
private readonly GetSchedulerDisplayPreferencesQueryHandler _sut;
private readonly SchedulerDisplayPreferencesEntityFixture _schedulerDisplayPreferencesEntityFixture = new();
private readonly Guid _userId = Guid.NewGuid();
/// <summary>
/// Initializes a new instance of the <see cref="GetSchedulerDisplayPreferencesQueryHandlerTests"/> class.
/// </summary>
public GetSchedulerDisplayPreferencesQueryHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockSchedulerDisplayPreferencesRepository = Substitute.For<ISchedulerDisplayPreferencesRepository>();
_mockUnitOfWork.SchedulerDisplayPreferencesRepository.Returns(_mockSchedulerDisplayPreferencesRepository);
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(true);
_sut = new GetSchedulerDisplayPreferencesQueryHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork);
}
[Fact]
public async Task HandleAsync_WhenDisplayPreferencesExist_ShouldReturnThemAsResponse()
{
// Arrange
SchedulerDisplayPreferencesEntity displayPreferences = _schedulerDisplayPreferencesEntityFixture.Create(
userId: _userId,
jobTypeFilter: ScheduledTaskType.ScanMediaLibraries,
displayTimeSpan: 60,
displayTimeUnit: SchedulerDisplayTimeUnit.Hours);
_mockSchedulerDisplayPreferencesRepository.GetByUserIdAsync(_userId, Arg.Any<CancellationToken>())
.Returns(Result.From<SchedulerDisplayPreferencesEntity?>(displayPreferences));
// Act
Result<SchedulerDisplayPreferencesResponse> result = await _sut.HandleAsync(new GetSchedulerDisplayPreferencesQuery(), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(_userId, result.Value.UserId);
Assert.Equal(ScheduledTaskType.ScanMediaLibraries, result.Value.JobTypeFilter);
Assert.Equal(60, result.Value.DisplayTimeSpan);
Assert.Equal(SchedulerDisplayTimeUnit.Hours, result.Value.DisplayTimeUnit);
}
[Fact]
public async Task HandleAsync_WhenNoDisplayPreferencesExist_ShouldReturnDefaultResponse()
{
// Arrange
_mockSchedulerDisplayPreferencesRepository.GetByUserIdAsync(_userId, Arg.Any<CancellationToken>())
.Returns(Result.From<SchedulerDisplayPreferencesEntity?>(null));
// Act
Result<SchedulerDisplayPreferencesResponse> result = await _sut.HandleAsync(new GetSchedulerDisplayPreferencesQuery(), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(_userId, result.Value.UserId);
Assert.Null(result.Value.JobTypeFilter);
Assert.Equal(DEFAULT_DISPLAY_TIME_SPAN, result.Value.DisplayTimeSpan);
Assert.Equal(DEFAULT_DISPLAY_TIME_UNIT, result.Value.DisplayTimeUnit);
}
[Fact]
public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorized()
{
// Arrange
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<SchedulerDisplayPreferencesResponse> result = await _sut.HandleAsync(new GetSchedulerDisplayPreferencesQuery(), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockSchedulerDisplayPreferencesRepository.DidNotReceive().GetByUserIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAdministrator_ShouldReturnNotAuthorized()
{
// Arrange
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(false);
// Act
Result<SchedulerDisplayPreferencesResponse> result = await _sut.HandleAsync(new GetSchedulerDisplayPreferencesQuery(), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockSchedulerDisplayPreferencesRepository.DidNotReceive().GetByUserIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetByUserIdReturnsError_ShouldReturnError()
{
// Arrange
Error error = Error.Failure("Database.Error", "Failed to get the display preferences");
_mockSchedulerDisplayPreferencesRepository.GetByUserIdAsync(_userId, Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<SchedulerDisplayPreferencesResponse> result = await _sut.HandleAsync(new GetSchedulerDisplayPreferencesQuery(), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
}
}