mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-02 20:11:10 +00:00
Renames project paths from Lumina to Nemera
This commit is contained in:
1 parent
ce6fddb4c9
commit
0f659a4877
6450 files changed
No files matched your search
+283
@@ -0,0 +1,283 @@
|
||||
#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>();
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_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>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenCommandIsValidWithOnceAtStartupSchedule_ShouldInsertScheduledJobAndReturnResponse()
|
||||
{
|
||||
// Arrange
|
||||
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(scheduleType: ScheduleType.OnceAtStartup);
|
||||
_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(ScheduleType.OnceAtStartup, result.Value.ScheduleType);
|
||||
Assert.Null(result.Value.IntervalMinutes);
|
||||
Assert.Null(result.Value.Hour);
|
||||
Assert.Null(result.Value.Minute);
|
||||
await _mockScheduledJobRepository.Received(1).InsertAsync(
|
||||
Arg.Is<ScheduledJobEntity>(scheduledJob =>
|
||||
scheduledJob.Name == command.Name &&
|
||||
scheduledJob.ScheduleType == ScheduleType.OnceAtStartup),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
_mockDomainEventsQueue.Received(1).Enqueue(Arg.Is<IDomainEvent>(domainEvent => domainEvent is ScheduledJobAddedDomainEvent));
|
||||
}
|
||||
}
|
||||
+195
@@ -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();
|
||||
}
|
||||
}
|
||||
+214
@@ -0,0 +1,214 @@
|
||||
#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>();
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_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, cancellationToken: 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>(), cancellationToken: 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>(), cancellationToken: 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>(), cancellationToken: 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, cancellationToken: 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, cancellationToken: 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, cancellationToken: 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, cancellationToken: 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>());
|
||||
}
|
||||
}
|
||||
+48
@@ -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();
|
||||
}
|
||||
}
|
||||
+263
@@ -0,0 +1,263 @@
|
||||
#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>();
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_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, cancellationToken: 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>(), cancellationToken: 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>(), cancellationToken: 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>(), cancellationToken: Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenScheduledJobDoesNotExist_ShouldReturnNotFound()
|
||||
{
|
||||
// Arrange
|
||||
RemoveScheduledJobCommand command = _removeScheduledJobCommandFixture.Create();
|
||||
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: 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, cancellationToken: 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, cancellationToken: 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>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenGettingTheScheduledJobFails_ShouldReturnTheRepositoryError()
|
||||
{
|
||||
// Arrange
|
||||
RemoveScheduledJobCommand command = _removeScheduledJobCommandFixture.Create();
|
||||
Error repositoryError = DomainErrors.Scheduling.ScheduledJobNotFound;
|
||||
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(repositoryError);
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(repositoryError, result.FirstError);
|
||||
await _mockScheduledJobScheduler.DidNotReceive().StopCycleAsync(Arg.Any<ScheduledJobId>(), Arg.Any<CancellationToken>());
|
||||
await _mockScheduledJobExecutionRepository.DidNotReceive().DeleteByScheduledJobIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTheScheduledJobCannotBeConvertedToDomain_ShouldReturnTheMappingError()
|
||||
{
|
||||
// Arrange
|
||||
RemoveScheduledJobCommand command = _removeScheduledJobCommandFixture.Create();
|
||||
// An interval schedule whose interval is not positive cannot be converted to its domain object.
|
||||
ScheduledJobEntity invalidScheduledJob = _scheduledJobEntityFixture.Create(
|
||||
id: command.ScheduledJobId,
|
||||
scheduleType: ScheduleType.WithIntervalInMinutes,
|
||||
intervalMinutes: 0,
|
||||
status: ScheduledJobStatus.Active);
|
||||
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<ScheduledJobEntity?>(invalidScheduledJob));
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(DomainErrors.Scheduling.IntervalMinutesMustBePositive, result.FirstError);
|
||||
await _mockScheduledJobScheduler.DidNotReceive().StopCycleAsync(Arg.Any<ScheduledJobId>(), Arg.Any<CancellationToken>());
|
||||
await _mockScheduledJobExecutionRepository.DidNotReceive().DeleteByScheduledJobIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+48
@@ -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();
|
||||
}
|
||||
}
|
||||
+246
@@ -0,0 +1,246 @@
|
||||
#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>();
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_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, cancellationToken: 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>(), cancellationToken: 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>(), cancellationToken: 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>(), cancellationToken: Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenScheduledJobDoesNotExist_ShouldReturnNotFound()
|
||||
{
|
||||
// Arrange
|
||||
StartScheduledJobCommand command = _startScheduledJobCommandFixture.Create();
|
||||
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: 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, cancellationToken: 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, cancellationToken: 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>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenGettingTheScheduledJobFails_ShouldReturnTheRepositoryError()
|
||||
{
|
||||
// Arrange
|
||||
StartScheduledJobCommand command = _startScheduledJobCommandFixture.Create();
|
||||
Error repositoryError = DomainErrors.Scheduling.ScheduledJobNotFound;
|
||||
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(repositoryError);
|
||||
|
||||
// Act
|
||||
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(repositoryError, result.FirstError);
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTheScheduledJobCannotBeConvertedToDomain_ShouldReturnTheMappingError()
|
||||
{
|
||||
// Arrange
|
||||
StartScheduledJobCommand command = _startScheduledJobCommandFixture.Create();
|
||||
// An interval schedule whose interval is not positive cannot be converted to its domain object.
|
||||
ScheduledJobEntity invalidScheduledJob = _scheduledJobEntityFixture.Create(
|
||||
id: command.ScheduledJobId,
|
||||
scheduleType: ScheduleType.WithIntervalInMinutes,
|
||||
intervalMinutes: 0,
|
||||
status: ScheduledJobStatus.Added);
|
||||
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<ScheduledJobEntity?>(invalidScheduledJob));
|
||||
|
||||
// Act
|
||||
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(DomainErrors.Scheduling.IntervalMinutesMustBePositive, result.FirstError);
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
|
||||
}
|
||||
}
|
||||
+48
@@ -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();
|
||||
}
|
||||
}
|
||||
+276
@@ -0,0 +1,276 @@
|
||||
#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>();
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_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, cancellationToken: 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, cancellationToken: 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>(), cancellationToken: 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>(), cancellationToken: Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenUserIsNotAdministrator_ShouldReturnNotAuthorized()
|
||||
{
|
||||
// Arrange
|
||||
StopScheduledJobCommand command = _stopScheduledJobCommandFixture.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>(), cancellationToken: Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenScheduledJobDoesNotExist_ShouldReturnNotFound()
|
||||
{
|
||||
// Arrange
|
||||
StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create();
|
||||
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: 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, cancellationToken: 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, cancellationToken: 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>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenGettingTheScheduledJobFails_ShouldReturnTheRepositoryError()
|
||||
{
|
||||
// Arrange
|
||||
StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create();
|
||||
Error repositoryError = DomainErrors.Scheduling.ScheduledJobNotFound;
|
||||
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(repositoryError);
|
||||
|
||||
// Act
|
||||
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(repositoryError, result.FirstError);
|
||||
await _mockScheduledJobScheduler.DidNotReceive().StopCycleAsync(Arg.Any<Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects.ScheduledJobId>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTheScheduledJobCannotBeConvertedToDomain_ShouldReturnTheMappingError()
|
||||
{
|
||||
// Arrange
|
||||
StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create();
|
||||
// An interval schedule whose interval is not positive cannot be converted to its domain object.
|
||||
ScheduledJobEntity invalidScheduledJob = _scheduledJobEntityFixture.Create(
|
||||
id: command.ScheduledJobId,
|
||||
scheduleType: ScheduleType.WithIntervalInMinutes,
|
||||
intervalMinutes: 0,
|
||||
status: ScheduledJobStatus.Active);
|
||||
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<ScheduledJobEntity?>(invalidScheduledJob));
|
||||
|
||||
// Act
|
||||
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(DomainErrors.Scheduling.IntervalMinutesMustBePositive, 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>());
|
||||
}
|
||||
}
|
||||
+48
@@ -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();
|
||||
}
|
||||
}
|
||||
+152
@@ -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;
|
||||
#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>();
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_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([ApplicationErrors.Scheduling.SchedulerDisplayTimeSpanMustBePositive]);
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.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>());
|
||||
}
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.Scheduling.Commands.UpdateSchedulerDisplayPreferences;
|
||||
using Lumina.Application.Fixtures.Core.Scheduling.Commands.UpdateSchedulerDisplayPreferences;
|
||||
using Lumina.Application.Common.Errors;
|
||||
using Lumina.Application.UnitTests.Common.Setup;
|
||||
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();
|
||||
}
|
||||
}
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
#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.DTO.Filtering;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Core.Scheduling.Events;
|
||||
using Lumina.Application.Core.Scheduling.Notifications;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
|
||||
using Lumina.Application.Fixtures.Common.DTO.Pagination;
|
||||
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();
|
||||
private readonly PaginatedResultDtoFixture<ScheduledJobEntity> _paginatedResultDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ScheduledJobAddedDomainEventHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public ScheduledJobAddedDomainEventHandlerTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_mockScheduledJobNotifier = Substitute.For<IScheduledJobNotifier>();
|
||||
_mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
|
||||
|
||||
_mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository);
|
||||
_mockScheduledJobRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1)));
|
||||
|
||||
_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<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [scheduledJob1, scheduledJob2], currentPage: 1, perPage: 2, count: 2, numberOfPages: 1)));
|
||||
|
||||
// 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<BaseFilterDto>(cancellationToken: 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>());
|
||||
}
|
||||
}
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
#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.DTO.Filtering;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Common.Infrastructure.Scheduling;
|
||||
using Lumina.Application.Core.Scheduling.Events;
|
||||
using Lumina.Application.Core.Scheduling.Notifications;
|
||||
using Lumina.Application.Fixtures.Common.DTO.Pagination;
|
||||
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();
|
||||
private readonly PaginatedResultDtoFixture<ScheduledJobEntity> _paginatedResultDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ScheduledJobCycleStartedDomainEventHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public ScheduledJobCycleStartedDomainEventHandlerTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_mockScheduledJobNotifier = Substitute.For<IScheduledJobNotifier>();
|
||||
_mockScheduledJobScheduler = Substitute.For<IScheduledJobScheduler>();
|
||||
_mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
|
||||
|
||||
_mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository);
|
||||
_mockScheduledJobRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1)));
|
||||
|
||||
_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<BaseFilterDto>(cancellationToken: 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>());
|
||||
}
|
||||
}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
#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.DTO.Filtering;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Core.Scheduling.Events;
|
||||
using Lumina.Application.Core.Scheduling.Notifications;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
|
||||
using Lumina.Application.Fixtures.Common.DTO.Pagination;
|
||||
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();
|
||||
private readonly PaginatedResultDtoFixture<ScheduledJobEntity> _paginatedResultDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ScheduledJobCycleStoppedDomainEventHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public ScheduledJobCycleStoppedDomainEventHandlerTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_mockScheduledJobNotifier = Substitute.For<IScheduledJobNotifier>();
|
||||
_mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
|
||||
|
||||
_mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository);
|
||||
_mockScheduledJobRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1)));
|
||||
|
||||
_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<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [stoppedJob], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
|
||||
|
||||
// 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<BaseFilterDto>(cancellationToken: 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>());
|
||||
}
|
||||
}
|
||||
+205
@@ -0,0 +1,205 @@
|
||||
#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.DTO.Filtering;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Core.Scheduling.Events;
|
||||
using Lumina.Application.Core.Scheduling.Notifications;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
|
||||
using Lumina.Application.Fixtures.Common.DTO.Pagination;
|
||||
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();
|
||||
private readonly PaginatedResultDtoFixture<ScheduledJobEntity> _paginatedResultDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ScheduledJobExecutionCompletedDomainEventHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public ScheduledJobExecutionCompletedDomainEventHandlerTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_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<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1)));
|
||||
|
||||
_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, cancellationToken: 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, cancellationToken: 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, cancellationToken: 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>(), cancellationToken: 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, cancellationToken: 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>(), cancellationToken: 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, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
|
||||
_mockScheduledJobExecutionRepository.GetByIdAsync(domainEvent.RunId, cancellationToken: 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, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
|
||||
ScheduledJobExecutionEntity execution = _scheduledJobExecutionEntityFixture.Create(id: domainEvent.RunId);
|
||||
_mockScheduledJobExecutionRepository.GetByIdAsync(domainEvent.RunId, cancellationToken: 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, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
|
||||
ScheduledJobExecutionEntity execution = _scheduledJobExecutionEntityFixture.Create(id: domainEvent.RunId);
|
||||
_mockScheduledJobExecutionRepository.GetByIdAsync(domainEvent.RunId, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<ScheduledJobExecutionEntity?>(execution));
|
||||
Error error = Error.Failure("Database.Error", "Failed to get the scheduled jobs");
|
||||
_mockScheduledJobRepository.GetAllAsync<BaseFilterDto>(cancellationToken: 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>());
|
||||
}
|
||||
}
|
||||
+196
@@ -0,0 +1,196 @@
|
||||
#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.DTO.Filtering;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Core.Scheduling.Events;
|
||||
using Lumina.Application.Core.Scheduling.Notifications;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
|
||||
using Lumina.Application.Fixtures.Common.DTO.Pagination;
|
||||
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();
|
||||
private readonly PaginatedResultDtoFixture<ScheduledJobEntity> _paginatedResultDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ScheduledJobExecutionStartedDomainEventHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public ScheduledJobExecutionStartedDomainEventHandlerTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_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<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1)));
|
||||
|
||||
_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, cancellationToken: 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, cancellationToken: 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, cancellationToken: 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, cancellationToken: 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, cancellationToken: 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, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
|
||||
Error error = Error.Failure("Database.Error", "Failed to get the scheduled jobs");
|
||||
_mockScheduledJobRepository.GetAllAsync<BaseFilterDto>(cancellationToken: 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>());
|
||||
}
|
||||
}
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
#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.DTO.Filtering;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Core.Scheduling.Events;
|
||||
using Lumina.Application.Core.Scheduling.Notifications;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
|
||||
using Lumina.Application.Fixtures.Common.DTO.Pagination;
|
||||
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();
|
||||
private readonly PaginatedResultDtoFixture<ScheduledJobEntity> _paginatedResultDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ScheduledJobExecutionStoppedDomainEventHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public ScheduledJobExecutionStoppedDomainEventHandlerTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_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<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1)));
|
||||
|
||||
_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<BaseFilterDto>(cancellationToken: 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>());
|
||||
}
|
||||
}
|
||||
+46
@@ -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>());
|
||||
}
|
||||
}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
#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.DTO.Filtering;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Core.Scheduling.Events;
|
||||
using Lumina.Application.Core.Scheduling.Notifications;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
|
||||
using Lumina.Application.Fixtures.Common.DTO.Pagination;
|
||||
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();
|
||||
private readonly PaginatedResultDtoFixture<ScheduledJobEntity> _paginatedResultDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ScheduledJobRemovedDomainEventHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public ScheduledJobRemovedDomainEventHandlerTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_mockScheduledJobNotifier = Substitute.For<IScheduledJobNotifier>();
|
||||
_mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
|
||||
|
||||
_mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository);
|
||||
_mockScheduledJobRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1)));
|
||||
|
||||
_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<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [remainingJob], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
|
||||
|
||||
// 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<BaseFilterDto>(cancellationToken: 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>());
|
||||
}
|
||||
}
|
||||
+162
@@ -0,0 +1,162 @@
|
||||
#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>();
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_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);
|
||||
}
|
||||
}
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
#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.DTO.Filtering;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Core.Scheduling.Queries.GetScheduledJobs;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
|
||||
using Lumina.Application.Fixtures.Common.DTO.Pagination;
|
||||
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 PaginatedResultDtoFixture<ScheduledJobEntity> _paginatedResultDtoFixture = 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>();
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_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<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_paginatedResultDtoFixture.Create(data: [scheduledJob1, scheduledJob2], currentPage: 1, perPage: 2, count: 2, numberOfPages: 1)));
|
||||
|
||||
// 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<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1)));
|
||||
|
||||
// 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<BaseFilterDto>(cancellationToken: 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<BaseFilterDto>(cancellationToken: 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<BaseFilterDto>(cancellationToken: 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);
|
||||
}
|
||||
}
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
#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>();
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user