Adds the scheduling module tests and centralizes domain event test fixtures

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

No files matched your search

@@ -0,0 +1,256 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DomainEvents;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.Scheduling.Commands.AddScheduledJob;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Fixtures.Core.Scheduling.Commands.AddScheduledJob;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Commands.AddScheduledJob;
/// <summary>
/// Contains unit tests for the <see cref="AddScheduledJobCommandHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddScheduledJobCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly IDomainEventsQueue _mockDomainEventsQueue;
private readonly IScheduledJobRepository _mockScheduledJobRepository;
private readonly IValidator<AddScheduledJobCommand> _mockValidator;
private readonly AddScheduledJobCommandHandler _sut;
private readonly AddScheduledJobCommandFixture _addScheduledJobCommandFixture = new();
private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new();
private readonly Guid _userId = Guid.NewGuid();
/// <summary>
/// Initializes a new instance of the <see cref="AddScheduledJobCommandHandlerTests"/> class.
/// </summary>
public AddScheduledJobCommandHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockDomainEventsQueue = Substitute.For<IDomainEventsQueue>();
_mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
_mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository);
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(true);
_mockValidator = Substitute.For<IValidator<AddScheduledJobCommand>>();
_mockValidator.Validate(Arg.Any<AddScheduledJobCommand>()).Returns([]);
_sut = new AddScheduledJobCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockDomainEventsQueue, _mockUnitOfWork, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenCommandIsValidWithIntervalSchedule_ShouldInsertScheduledJobAndReturnResponse()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(scheduleType: ScheduleType.WithIntervalInMinutes);
_mockScheduledJobRepository.InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>()).Returns(Result.Created);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(command.Name, result.Value.Name);
Assert.Equal(command.TaskType, result.Value.TaskType);
Assert.Equal(ScheduleType.WithIntervalInMinutes, result.Value.ScheduleType);
Assert.Equal(command.IntervalMinutes, result.Value.IntervalMinutes);
Assert.Equal(ScheduledJobStatus.Added, result.Value.Status);
await _mockScheduledJobRepository.Received(1).InsertAsync(
Arg.Is<ScheduledJobEntity>(scheduledJob =>
scheduledJob.Name == command.Name &&
scheduledJob.TaskType == command.TaskType &&
scheduledJob.ScheduleType == ScheduleType.WithIntervalInMinutes &&
scheduledJob.IntervalMinutes == command.IntervalMinutes &&
scheduledJob.OwnerUserId == _userId),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
_mockDomainEventsQueue.Received(1).Enqueue(Arg.Is<IDomainEvent>(domainEvent => domainEvent is ScheduledJobAddedDomainEvent));
}
[Fact]
public async Task HandleAsync_WhenCommandIsValidWithDailySchedule_ShouldInsertScheduledJobAndReturnResponse()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(scheduleType: ScheduleType.DailyAtHourAndMinute, hour: 6, minute: 30);
_mockScheduledJobRepository.InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>()).Returns(Result.Created);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(ScheduleType.DailyAtHourAndMinute, result.Value.ScheduleType);
Assert.Equal(6, result.Value.Hour);
Assert.Equal(30, result.Value.Minute);
Assert.Null(result.Value.IntervalMinutes);
await _mockScheduledJobRepository.Received(1).InsertAsync(
Arg.Is<ScheduledJobEntity>(scheduledJob =>
scheduledJob.ScheduleType == ScheduleType.DailyAtHourAndMinute &&
scheduledJob.Hour == 6 &&
scheduledJob.Minute == 30),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenValidatorReturnsError_ShouldReturnValidationErrorAndNotPersist()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create();
_mockValidator.Validate(Arg.Any<AddScheduledJobCommand>()).Returns([DomainErrors.Scheduling.ScheduledJobNameCannotBeEmpty]);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.ScheduledJobNameCannotBeEmpty, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
}
[Fact]
public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorizedAndNotPersist()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAdministrator_ShouldReturnNotAuthorizedAndNotPersist()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create();
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(false);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenIntervalScheduleHasNonPositiveInterval_ShouldReturnIntervalError()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(
scheduleType: ScheduleType.WithIntervalInMinutes,
intervalMinutes: 0);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.IntervalMinutesMustBePositive, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenDailyScheduleHasOutOfRangeHour_ShouldReturnHourError()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(
scheduleType: ScheduleType.DailyAtHourAndMinute,
hour: 24,
minute: 0);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.HourMustBeBetweenZeroAndTwentyThree, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenScheduleTypeIsUnsupported_ShouldReturnInvalidScheduleTypeError()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(scheduleType: (ScheduleType)999);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.InvalidScheduleType, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenScheduledJobNameIsEmpty_ShouldReturnNameErrorAndNotPersist()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(name: " ");
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Scheduling.ScheduledJobNameCannotBeEmpty, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenInsertFails_ShouldReturnErrorAndNotSaveChanges()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create();
_mockScheduledJobRepository.InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>())
.Returns(DomainErrors.Scheduling.ScheduledJobAlreadyExists);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.ScheduledJobAlreadyExists, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
}
}
@@ -0,0 +1,195 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Scheduling.Commands.AddScheduledJob;
using Lumina.Application.Fixtures.Core.Scheduling.Commands.AddScheduledJob;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Commands.AddScheduledJob;
/// <summary>
/// Contains unit tests for the <see cref="AddScheduledJobCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddScheduledJobCommandValidatorTests
{
private readonly AddScheduledJobCommandValidator _validator = new();
private readonly AddScheduledJobCommandFixture _addScheduledJobCommandFixture = new();
[Theory]
[InlineData(null)] // null name
[InlineData("")] // empty name
[InlineData(" ")] // whitespace name
public void Validate_WhenNameIsNullOrWhitespace_ShouldHaveValidationError(string? name)
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create() with { Name = name! };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Scheduling.ScheduledJobNameCannotBeEmpty);
}
[Fact]
public void Validate_WhenNameExceedsMaximumLength_ShouldHaveValidationError()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(name: new string('a', 81));
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Scheduling.ScheduledJobNameCannotBeEmpty);
}
[Fact]
public void Validate_WhenTaskTypeIsNotInEnum_ShouldHaveValidationError()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(taskType: (ScheduledTaskType)999);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Scheduling.InvalidScheduleType);
}
[Fact]
public void Validate_WhenScheduleTypeIsNotInEnum_ShouldHaveValidationError()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(scheduleType: (ScheduleType)999);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Scheduling.InvalidScheduleType);
}
[Fact]
public void Validate_WhenIntervalScheduleHasNullInterval_ShouldHaveValidationError()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(scheduleType: ScheduleType.WithIntervalInMinutes) with { IntervalMinutes = null };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Scheduling.IntervalMinutesMustBePositive);
}
[Theory]
[InlineData(0)] // interval of zero
[InlineData(-1)] // negative interval
public void Validate_WhenIntervalScheduleHasNonPositiveInterval_ShouldHaveValidationError(int intervalMinutes)
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(
scheduleType: ScheduleType.WithIntervalInMinutes,
intervalMinutes: intervalMinutes);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Scheduling.IntervalMinutesMustBePositive);
}
[Fact]
public void Validate_WhenDailyScheduleHasNullHour_ShouldHaveValidationError()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(scheduleType: ScheduleType.DailyAtHourAndMinute) with { Hour = null };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Scheduling.HourMustBeBetweenZeroAndTwentyThree);
}
[Fact]
public void Validate_WhenDailyScheduleHasNullMinute_ShouldHaveValidationError()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(scheduleType: ScheduleType.DailyAtHourAndMinute) with { Minute = null };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Scheduling.MinuteMustBeBetweenZeroAndFiftyNine);
}
[Theory]
[InlineData(-1)] // hour below the allowed range
[InlineData(24)] // hour above the allowed range
public void Validate_WhenDailyScheduleHasOutOfRangeHour_ShouldHaveValidationError(int hour)
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(
scheduleType: ScheduleType.DailyAtHourAndMinute,
hour: hour,
minute: 0);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Scheduling.HourMustBeBetweenZeroAndTwentyThree);
}
[Theory]
[InlineData(-1)] // minute below the allowed range
[InlineData(60)] // minute above the allowed range
public void Validate_WhenDailyScheduleHasOutOfRangeMinute_ShouldHaveValidationError(int minute)
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(
scheduleType: ScheduleType.DailyAtHourAndMinute,
hour: 12,
minute: minute);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Scheduling.MinuteMustBeBetweenZeroAndFiftyNine);
}
[Fact]
public void Validate_WhenCommandIsValidWithIntervalSchedule_ShouldNotHaveAnyValidationError()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(scheduleType: ScheduleType.WithIntervalInMinutes);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
[Fact]
public void Validate_WhenCommandIsValidWithDailySchedule_ShouldNotHaveAnyValidationError()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(scheduleType: ScheduleType.DailyAtHourAndMinute);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -0,0 +1,213 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DomainEvents;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.Scheduling.Commands.FireScheduledJob;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Fixtures.Core.Scheduling.Commands.FireScheduledJob;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Commands.FireScheduledJob;
/// <summary>
/// Contains unit tests for the <see cref="FireScheduledJobCommandHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class FireScheduledJobCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly IDomainEventsQueue _mockDomainEventsQueue;
private readonly IScheduledJobRepository _mockScheduledJobRepository;
private readonly IValidator<FireScheduledJobCommand> _mockValidator;
private readonly FireScheduledJobCommandHandler _sut;
private readonly FireScheduledJobCommandFixture _fireScheduledJobCommandFixture = new();
private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new();
private readonly Guid _userId = Guid.NewGuid();
/// <summary>
/// Initializes a new instance of the <see cref="FireScheduledJobCommandHandlerTests"/> class.
/// </summary>
public FireScheduledJobCommandHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockDomainEventsQueue = Substitute.For<IDomainEventsQueue>();
_mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
_mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository);
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(true);
_mockValidator = Substitute.For<IValidator<FireScheduledJobCommand>>();
_mockValidator.Validate(Arg.Any<FireScheduledJobCommand>()).Returns([]);
_sut = new FireScheduledJobCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockDomainEventsQueue, _mockUnitOfWork, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenScheduledJobIsAdded_ShouldEnqueueFiredEventAndReturnResponse()
{
// Arrange
FireScheduledJobCommand command = _fireScheduledJobCommandFixture.Create();
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(
id: command.ScheduledJobId,
scheduleType: ScheduleType.WithIntervalInMinutes,
status: ScheduledJobStatus.Active);
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(scheduledJob.Name, result.Value.Name);
_mockDomainEventsQueue.Received(1).Enqueue(Arg.Is<IDomainEvent>(domainEvent => domainEvent is ScheduledJobFiredDomainEvent));
await _mockScheduledJobRepository.DidNotReceive().UpdateAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenValidatorReturnsError_ShouldReturnValidationErrorAndNotQueueEvent()
{
// Arrange
FireScheduledJobCommand command = _fireScheduledJobCommandFixture.Create();
_mockValidator.Validate(Arg.Any<FireScheduledJobCommand>()).Returns([DomainErrors.Scheduling.ScheduledJobNotFound]);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
}
[Fact]
public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorized()
{
// Arrange
FireScheduledJobCommand command = _fireScheduledJobCommandFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAdministrator_ShouldReturnNotAuthorized()
{
// Arrange
FireScheduledJobCommand command = _fireScheduledJobCommandFixture.Create();
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(false);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetByIdReturnsError_ShouldReturnError()
{
// Arrange
FireScheduledJobCommand command = _fireScheduledJobCommandFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to get the scheduled job");
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>()).Returns(error);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
}
[Fact]
public async Task HandleAsync_WhenScheduledJobDoesNotExist_ShouldReturnNotFound()
{
// Arrange
FireScheduledJobCommand command = _fireScheduledJobCommandFixture.Create();
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(null));
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError);
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
}
[Fact]
public async Task HandleAsync_WhenToDomainEntityFails_ShouldReturnError()
{
// Arrange
FireScheduledJobCommand command = _fireScheduledJobCommandFixture.Create();
// A daily scheduled job with an out of range hour cannot convert to its domain aggregate.
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(
id: command.ScheduledJobId,
scheduleType: ScheduleType.DailyAtHourAndMinute,
hour: 99,
minute: 0);
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
}
[Fact]
public async Task HandleAsync_WhenScheduledJobIsRunning_ShouldReturnAlreadyRunningError()
{
// Arrange
FireScheduledJobCommand command = _fireScheduledJobCommandFixture.Create();
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(
id: command.ScheduledJobId,
scheduleType: ScheduleType.WithIntervalInMinutes,
status: ScheduledJobStatus.Running);
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.ScheduledJobAlreadyRunning, result.FirstError);
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
}
}
@@ -0,0 +1,48 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Scheduling.Commands.FireScheduledJob;
using Lumina.Application.Fixtures.Core.Scheduling.Commands.FireScheduledJob;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Commands.FireScheduledJob;
/// <summary>
/// Contains unit tests for the <see cref="FireScheduledJobCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class FireScheduledJobCommandValidatorTests
{
private readonly FireScheduledJobCommandValidator _validator = new();
private readonly FireScheduledJobCommandFixture _fireScheduledJobCommandFixture = new();
[Fact]
public void Validate_WhenScheduledJobIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
FireScheduledJobCommand command = _fireScheduledJobCommandFixture.Create() with { ScheduledJobId = Guid.Empty };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Scheduling.ScheduledJobNotFound);
}
[Fact]
public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationError()
{
// Arrange
FireScheduledJobCommand command = _fireScheduledJobCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -0,0 +1,219 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DomainEvents;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Scheduling;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.Scheduling.Commands.RemoveScheduledJob;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Fixtures.Core.Scheduling.Commands.RemoveScheduledJob;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
using ScheduledJobId = Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects.ScheduledJobId;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Commands.RemoveScheduledJob;
/// <summary>
/// Contains unit tests for the <see cref="RemoveScheduledJobCommandHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RemoveScheduledJobCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly IDomainEventsQueue _mockDomainEventsQueue;
private readonly IScheduledJobScheduler _mockScheduledJobScheduler;
private readonly IScheduledJobRepository _mockScheduledJobRepository;
private readonly IScheduledJobExecutionRepository _mockScheduledJobExecutionRepository;
private readonly IValidator<RemoveScheduledJobCommand> _mockValidator;
private readonly RemoveScheduledJobCommandHandler _sut;
private readonly RemoveScheduledJobCommandFixture _removeScheduledJobCommandFixture = new();
private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new();
private readonly Guid _userId = Guid.NewGuid();
/// <summary>
/// Initializes a new instance of the <see cref="RemoveScheduledJobCommandHandlerTests"/> class.
/// </summary>
public RemoveScheduledJobCommandHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockDomainEventsQueue = Substitute.For<IDomainEventsQueue>();
_mockScheduledJobScheduler = Substitute.For<IScheduledJobScheduler>();
_mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
_mockScheduledJobExecutionRepository = Substitute.For<IScheduledJobExecutionRepository>();
_mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository);
_mockUnitOfWork.ScheduledJobExecutionRepository.Returns(_mockScheduledJobExecutionRepository);
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(true);
_mockValidator = Substitute.For<IValidator<RemoveScheduledJobCommand>>();
_mockValidator.Validate(Arg.Any<RemoveScheduledJobCommand>()).Returns([]);
_sut = new RemoveScheduledJobCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockDomainEventsQueue, _mockScheduledJobScheduler, _mockUnitOfWork, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenScheduledJobExists_ShouldDeleteItAndEnqueueRemovedEvent()
{
// Arrange
RemoveScheduledJobCommand command = _removeScheduledJobCommandFixture.Create();
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(
id: command.ScheduledJobId,
scheduleType: ScheduleType.WithIntervalInMinutes,
status: ScheduledJobStatus.Active);
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
_mockScheduledJobExecutionRepository.DeleteByScheduledJobIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.Success);
_mockScheduledJobRepository.DeleteByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Success, result.Value);
await _mockScheduledJobScheduler.Received(1).StopCycleAsync(
Arg.Is<ScheduledJobId>(scheduledJobId => scheduledJobId.Value == command.ScheduledJobId),
Arg.Any<CancellationToken>());
await _mockScheduledJobExecutionRepository.Received(1).DeleteByScheduledJobIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>());
await _mockScheduledJobRepository.Received(1).DeleteByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
_mockDomainEventsQueue.Received(1).Enqueue(Arg.Is<IDomainEvent>(domainEvent => domainEvent is ScheduledJobRemovedDomainEvent));
}
[Fact]
public async Task HandleAsync_WhenValidatorReturnsError_ShouldReturnValidationErrorAndNotDelete()
{
// Arrange
RemoveScheduledJobCommand command = _removeScheduledJobCommandFixture.Create();
_mockValidator.Validate(Arg.Any<RemoveScheduledJobCommand>()).Returns([DomainErrors.Scheduling.ScheduledJobNotFound]);
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockScheduledJobRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorized()
{
// Arrange
RemoveScheduledJobCommand command = _removeScheduledJobCommandFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAdministrator_ShouldReturnNotAuthorized()
{
// Arrange
RemoveScheduledJobCommand command = _removeScheduledJobCommandFixture.Create();
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(false);
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenScheduledJobDoesNotExist_ShouldReturnNotFound()
{
// Arrange
RemoveScheduledJobCommand command = _removeScheduledJobCommandFixture.Create();
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(null));
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError);
await _mockScheduledJobScheduler.DidNotReceive().StopCycleAsync(Arg.Any<ScheduledJobId>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenDeleteExecutionsFails_ShouldReturnErrorAndNotDeleteScheduledJob()
{
// Arrange
RemoveScheduledJobCommand command = _removeScheduledJobCommandFixture.Create();
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(
id: command.ScheduledJobId,
scheduleType: ScheduleType.WithIntervalInMinutes,
status: ScheduledJobStatus.Active);
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
Error error = Error.Failure("Database.Error", "Failed to delete the executions");
_mockScheduledJobExecutionRepository.DeleteByScheduledJobIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenDeleteScheduledJobFails_ShouldReturnErrorAndNotSaveChanges()
{
// Arrange
RemoveScheduledJobCommand command = _removeScheduledJobCommandFixture.Create();
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(
id: command.ScheduledJobId,
scheduleType: ScheduleType.WithIntervalInMinutes,
status: ScheduledJobStatus.Active);
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
_mockScheduledJobExecutionRepository.DeleteByScheduledJobIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.Success);
_mockScheduledJobRepository.DeleteByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(DomainErrors.Scheduling.ScheduledJobNotFound);
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
}
}
@@ -0,0 +1,48 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Scheduling.Commands.RemoveScheduledJob;
using Lumina.Application.Fixtures.Core.Scheduling.Commands.RemoveScheduledJob;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Commands.RemoveScheduledJob;
/// <summary>
/// Contains unit tests for the <see cref="RemoveScheduledJobCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RemoveScheduledJobCommandValidatorTests
{
private readonly RemoveScheduledJobCommandValidator _validator = new();
private readonly RemoveScheduledJobCommandFixture _removeScheduledJobCommandFixture = new();
[Fact]
public void Validate_WhenScheduledJobIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
RemoveScheduledJobCommand command = _removeScheduledJobCommandFixture.Create() with { ScheduledJobId = Guid.Empty };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Scheduling.ScheduledJobNotFound);
}
[Fact]
public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationError()
{
// Arrange
RemoveScheduledJobCommand command = _removeScheduledJobCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -0,0 +1,203 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DomainEvents;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.Scheduling.Commands.StartScheduledJob;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Fixtures.Core.Scheduling.Commands.StartScheduledJob;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Commands.StartScheduledJob;
/// <summary>
/// Contains unit tests for the <see cref="StartScheduledJobCommandHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class StartScheduledJobCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly IDomainEventsQueue _mockDomainEventsQueue;
private readonly IScheduledJobRepository _mockScheduledJobRepository;
private readonly IValidator<StartScheduledJobCommand> _mockValidator;
private readonly StartScheduledJobCommandHandler _sut;
private readonly StartScheduledJobCommandFixture _startScheduledJobCommandFixture = new();
private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new();
private readonly Guid _userId = Guid.NewGuid();
/// <summary>
/// Initializes a new instance of the <see cref="StartScheduledJobCommandHandlerTests"/> class.
/// </summary>
public StartScheduledJobCommandHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockDomainEventsQueue = Substitute.For<IDomainEventsQueue>();
_mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
_mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository);
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(true);
_mockValidator = Substitute.For<IValidator<StartScheduledJobCommand>>();
_mockValidator.Validate(Arg.Any<StartScheduledJobCommand>()).Returns([]);
_sut = new StartScheduledJobCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockDomainEventsQueue, _mockUnitOfWork, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenScheduledJobIsAdded_ShouldUpdateToActiveAndEnqueueCycleStartedEvent()
{
// Arrange
StartScheduledJobCommand command = _startScheduledJobCommandFixture.Create();
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(
id: command.ScheduledJobId,
scheduleType: ScheduleType.WithIntervalInMinutes,
status: ScheduledJobStatus.Added);
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
_mockScheduledJobRepository.UpdateAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>()).Returns(Result.Updated);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(ScheduledJobStatus.Active, result.Value.Status);
await _mockScheduledJobRepository.Received(1).UpdateAsync(
Arg.Is<ScheduledJobEntity>(updatedScheduledJob => updatedScheduledJob.Status == ScheduledJobStatus.Active),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
_mockDomainEventsQueue.Received(1).Enqueue(Arg.Is<IDomainEvent>(domainEvent => domainEvent is ScheduledJobCycleStartedDomainEvent));
}
[Fact]
public async Task HandleAsync_WhenValidatorReturnsError_ShouldReturnValidationErrorAndNotPersist()
{
// Arrange
StartScheduledJobCommand command = _startScheduledJobCommandFixture.Create();
_mockValidator.Validate(Arg.Any<StartScheduledJobCommand>()).Returns([DomainErrors.Scheduling.ScheduledJobNotFound]);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorized()
{
// Arrange
StartScheduledJobCommand command = _startScheduledJobCommandFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAdministrator_ShouldReturnNotAuthorized()
{
// Arrange
StartScheduledJobCommand command = _startScheduledJobCommandFixture.Create();
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(false);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenScheduledJobDoesNotExist_ShouldReturnNotFound()
{
// Arrange
StartScheduledJobCommand command = _startScheduledJobCommandFixture.Create();
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(null));
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().UpdateAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenScheduledJobCycleAlreadyStarted_ShouldReturnCycleAlreadyStartedError()
{
// Arrange
StartScheduledJobCommand command = _startScheduledJobCommandFixture.Create();
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(
id: command.ScheduledJobId,
scheduleType: ScheduleType.WithIntervalInMinutes,
status: ScheduledJobStatus.Active);
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.ScheduledJobCycleAlreadyStarted, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().UpdateAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>());
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
}
[Fact]
public async Task HandleAsync_WhenUpdateFails_ShouldReturnErrorAndNotSaveChanges()
{
// Arrange
StartScheduledJobCommand command = _startScheduledJobCommandFixture.Create();
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(
id: command.ScheduledJobId,
scheduleType: ScheduleType.WithIntervalInMinutes,
status: ScheduledJobStatus.Added);
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
_mockScheduledJobRepository.UpdateAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>())
.Returns(DomainErrors.Scheduling.ScheduledJobNotFound);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
}
}
@@ -0,0 +1,48 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Scheduling.Commands.StartScheduledJob;
using Lumina.Application.Fixtures.Core.Scheduling.Commands.StartScheduledJob;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Commands.StartScheduledJob;
/// <summary>
/// Contains unit tests for the <see cref="StartScheduledJobCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class StartScheduledJobCommandValidatorTests
{
private readonly StartScheduledJobCommandValidator _validator = new();
private readonly StartScheduledJobCommandFixture _startScheduledJobCommandFixture = new();
[Fact]
public void Validate_WhenScheduledJobIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
StartScheduledJobCommand command = _startScheduledJobCommandFixture.Create() with { ScheduledJobId = Guid.Empty };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Scheduling.ScheduledJobNotFound);
}
[Fact]
public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationError()
{
// Arrange
StartScheduledJobCommand command = _startScheduledJobCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -0,0 +1,217 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DomainEvents;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Scheduling;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.Scheduling.Commands.StopScheduledJob;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Fixtures.Core.Scheduling.Commands.StopScheduledJob;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Commands.StopScheduledJob;
/// <summary>
/// Contains unit tests for the <see cref="StopScheduledJobCommandHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class StopScheduledJobCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly IDomainEventsQueue _mockDomainEventsQueue;
private readonly IScheduledJobScheduler _mockScheduledJobScheduler;
private readonly IScheduledJobRepository _mockScheduledJobRepository;
private readonly IValidator<StopScheduledJobCommand> _mockValidator;
private readonly StopScheduledJobCommandHandler _sut;
private readonly StopScheduledJobCommandFixture _stopScheduledJobCommandFixture = new();
private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new();
private readonly Guid _userId = Guid.NewGuid();
/// <summary>
/// Initializes a new instance of the <see cref="StopScheduledJobCommandHandlerTests"/> class.
/// </summary>
public StopScheduledJobCommandHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockDomainEventsQueue = Substitute.For<IDomainEventsQueue>();
_mockScheduledJobScheduler = Substitute.For<IScheduledJobScheduler>();
_mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
_mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository);
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(true);
_mockValidator = Substitute.For<IValidator<StopScheduledJobCommand>>();
_mockValidator.Validate(Arg.Any<StopScheduledJobCommand>()).Returns([]);
_sut = new StopScheduledJobCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockDomainEventsQueue, _mockScheduledJobScheduler, _mockUnitOfWork, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenScheduledJobIsActive_ShouldUpdateToAddedAndStopCycleInScheduler()
{
// Arrange
StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create();
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(
id: command.ScheduledJobId,
scheduleType: ScheduleType.WithIntervalInMinutes,
status: ScheduledJobStatus.Active);
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
_mockScheduledJobRepository.UpdateAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>()).Returns(Result.Updated);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(ScheduledJobStatus.Added, result.Value.Status);
await _mockScheduledJobRepository.Received(1).UpdateAsync(
Arg.Is<ScheduledJobEntity>(updatedScheduledJob => updatedScheduledJob.Status == ScheduledJobStatus.Added),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockScheduledJobScheduler.Received(1).StopCycleAsync(
Arg.Is<Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects.ScheduledJobId>(scheduledJobId => scheduledJobId.Value == command.ScheduledJobId),
Arg.Any<CancellationToken>());
_mockDomainEventsQueue.Received(1).Enqueue(Arg.Is<IDomainEvent>(domainEvent => domainEvent is ScheduledJobCycleStoppedDomainEvent));
}
[Fact]
public async Task HandleAsync_WhenScheduledJobIsRunning_ShouldEnqueueExecutionStoppedEvent()
{
// Arrange
StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create();
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(
id: command.ScheduledJobId,
scheduleType: ScheduleType.WithIntervalInMinutes,
status: ScheduledJobStatus.Running,
lastStartedOnUtc: DateTime.UtcNow.AddMinutes(-10));
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
_mockScheduledJobRepository.UpdateAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>()).Returns(Result.Updated);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(ScheduledJobStatus.Added, result.Value.Status);
_mockDomainEventsQueue.Received(1).Enqueue(Arg.Is<IDomainEvent>(domainEvent => domainEvent is ScheduledJobExecutionStoppedDomainEvent));
await _mockScheduledJobScheduler.Received(1).StopCycleAsync(Arg.Any<Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects.ScheduledJobId>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenValidatorReturnsError_ShouldReturnValidationErrorAndNotPersist()
{
// Arrange
StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create();
_mockValidator.Validate(Arg.Any<StopScheduledJobCommand>()).Returns([DomainErrors.Scheduling.ScheduledJobNotFound]);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockScheduledJobScheduler.DidNotReceive().StopCycleAsync(Arg.Any<Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects.ScheduledJobId>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorized()
{
// Arrange
StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenScheduledJobDoesNotExist_ShouldReturnNotFound()
{
// Arrange
StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create();
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(null));
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError);
await _mockScheduledJobScheduler.DidNotReceive().StopCycleAsync(Arg.Any<Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects.ScheduledJobId>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenScheduledJobCycleWasNeverStarted_ShouldReturnNotStartedError()
{
// Arrange
StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create();
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(
id: command.ScheduledJobId,
scheduleType: ScheduleType.WithIntervalInMinutes,
status: ScheduledJobStatus.Added);
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotStarted, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().UpdateAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>());
await _mockScheduledJobScheduler.DidNotReceive().StopCycleAsync(Arg.Any<Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects.ScheduledJobId>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUpdateFails_ShouldReturnErrorAndNotStopCycleInScheduler()
{
// Arrange
StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create();
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(
id: command.ScheduledJobId,
scheduleType: ScheduleType.WithIntervalInMinutes,
status: ScheduledJobStatus.Active);
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
_mockScheduledJobRepository.UpdateAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>())
.Returns(DomainErrors.Scheduling.ScheduledJobNotFound);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockScheduledJobScheduler.DidNotReceive().StopCycleAsync(Arg.Any<Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects.ScheduledJobId>(), Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,48 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Scheduling.Commands.StopScheduledJob;
using Lumina.Application.Fixtures.Core.Scheduling.Commands.StopScheduledJob;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Commands.StopScheduledJob;
/// <summary>
/// Contains unit tests for the <see cref="StopScheduledJobCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class StopScheduledJobCommandValidatorTests
{
private readonly StopScheduledJobCommandValidator _validator = new();
private readonly StopScheduledJobCommandFixture _stopScheduledJobCommandFixture = new();
[Fact]
public void Validate_WhenScheduledJobIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create() with { ScheduledJobId = Guid.Empty };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Scheduling.ScheduledJobNotFound);
}
[Fact]
public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationError()
{
// Arrange
StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -0,0 +1,152 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.Scheduling.Commands.UpdateSchedulerDisplayPreferences;
using Lumina.Application.Fixtures.Core.Scheduling.Commands.UpdateSchedulerDisplayPreferences;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Commands.UpdateSchedulerDisplayPreferences;
/// <summary>
/// Contains unit tests for the <see cref="UpdateSchedulerDisplayPreferencesCommandHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateSchedulerDisplayPreferencesCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ISchedulerDisplayPreferencesRepository _mockSchedulerDisplayPreferencesRepository;
private readonly IValidator<UpdateSchedulerDisplayPreferencesCommand> _mockValidator;
private readonly UpdateSchedulerDisplayPreferencesCommandHandler _sut;
private readonly UpdateSchedulerDisplayPreferencesCommandFixture _updateSchedulerDisplayPreferencesCommandFixture = new();
private readonly Guid _userId = Guid.NewGuid();
/// <summary>
/// Initializes a new instance of the <see cref="UpdateSchedulerDisplayPreferencesCommandHandlerTests"/> class.
/// </summary>
public UpdateSchedulerDisplayPreferencesCommandHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockSchedulerDisplayPreferencesRepository = Substitute.For<ISchedulerDisplayPreferencesRepository>();
_mockUnitOfWork.SchedulerDisplayPreferencesRepository.Returns(_mockSchedulerDisplayPreferencesRepository);
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(true);
_mockValidator = Substitute.For<IValidator<UpdateSchedulerDisplayPreferencesCommand>>();
_mockValidator.Validate(Arg.Any<UpdateSchedulerDisplayPreferencesCommand>()).Returns([]);
_sut = new UpdateSchedulerDisplayPreferencesCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenCommandIsValid_ShouldUpsertDisplayPreferencesAndReturnUpdated()
{
// Arrange
UpdateSchedulerDisplayPreferencesCommand command = _updateSchedulerDisplayPreferencesCommandFixture.Create(
jobTypeFilter: ScheduledTaskType.ScanMediaLibraries,
displayTimeSpan: 30,
displayTimeUnit: SchedulerDisplayTimeUnit.Minutes);
_mockSchedulerDisplayPreferencesRepository.UpsertAsync(Arg.Any<SchedulerDisplayPreferencesEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
await _mockSchedulerDisplayPreferencesRepository.Received(1).UpsertAsync(
Arg.Is<SchedulerDisplayPreferencesEntity>(preferences =>
preferences.UserId == _userId &&
preferences.JobTypeFilter == ScheduledTaskType.ScanMediaLibraries &&
preferences.DisplayTimeSpan == 30 &&
preferences.DisplayTimeUnit == SchedulerDisplayTimeUnit.Minutes),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenValidatorReturnsError_ShouldReturnValidationErrorAndNotPersist()
{
// Arrange
UpdateSchedulerDisplayPreferencesCommand command = _updateSchedulerDisplayPreferencesCommandFixture.Create(displayTimeSpan: 0);
_mockValidator.Validate(Arg.Any<UpdateSchedulerDisplayPreferencesCommand>())
.Returns([DomainErrors.Scheduling.SchedulerDisplayTimeSpanMustBePositive]);
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.SchedulerDisplayTimeSpanMustBePositive, result.FirstError);
await _mockSchedulerDisplayPreferencesRepository.DidNotReceive().UpsertAsync(Arg.Any<SchedulerDisplayPreferencesEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorized()
{
// Arrange
UpdateSchedulerDisplayPreferencesCommand command = _updateSchedulerDisplayPreferencesCommandFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockSchedulerDisplayPreferencesRepository.DidNotReceive().UpsertAsync(Arg.Any<SchedulerDisplayPreferencesEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAdministrator_ShouldReturnNotAuthorized()
{
// Arrange
UpdateSchedulerDisplayPreferencesCommand command = _updateSchedulerDisplayPreferencesCommandFixture.Create();
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(false);
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockSchedulerDisplayPreferencesRepository.DidNotReceive().UpsertAsync(Arg.Any<SchedulerDisplayPreferencesEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUpsertFails_ShouldReturnErrorAndNotSaveChanges()
{
// Arrange
UpdateSchedulerDisplayPreferencesCommand command = _updateSchedulerDisplayPreferencesCommandFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to upsert the display preferences");
_mockSchedulerDisplayPreferencesRepository.UpsertAsync(Arg.Any<SchedulerDisplayPreferencesEntity>(), Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,66 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Scheduling.Commands.UpdateSchedulerDisplayPreferences;
using Lumina.Application.Fixtures.Core.Scheduling.Commands.UpdateSchedulerDisplayPreferences;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Commands.UpdateSchedulerDisplayPreferences;
/// <summary>
/// Contains unit tests for the <see cref="UpdateSchedulerDisplayPreferencesCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateSchedulerDisplayPreferencesCommandValidatorTests
{
private readonly UpdateSchedulerDisplayPreferencesCommandValidator _validator = new();
private readonly UpdateSchedulerDisplayPreferencesCommandFixture _updateSchedulerDisplayPreferencesCommandFixture = new();
[Theory]
[InlineData(0)] // display time span of zero
[InlineData(-1)] // negative display time span
[InlineData(-100)] // negative display time span far from zero
public void Validate_WhenDisplayTimeSpanIsNotPositive_ShouldHaveValidationError(int displayTimeSpan)
{
// Arrange
UpdateSchedulerDisplayPreferencesCommand command = _updateSchedulerDisplayPreferencesCommandFixture.Create(displayTimeSpan: displayTimeSpan);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Scheduling.SchedulerDisplayTimeSpanMustBePositive);
}
[Theory]
[InlineData(1)] // minimal positive display time span
[InlineData(10)] // default display time span
[InlineData(1440)] // a day expressed in minutes
public void Validate_WhenDisplayTimeSpanIsPositive_ShouldNotHaveValidationError(int displayTimeSpan)
{
// Arrange
UpdateSchedulerDisplayPreferencesCommand command = _updateSchedulerDisplayPreferencesCommandFixture.Create(displayTimeSpan: displayTimeSpan);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Scheduling.SchedulerDisplayTimeSpanMustBePositive);
}
[Fact]
public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationError()
{
// Arrange
UpdateSchedulerDisplayPreferencesCommand command = _updateSchedulerDisplayPreferencesCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}