Completes the scheduler module coverage with a startup theme bootstrap and a stubbed cycle ticker

This commit is contained in:
BinaryAlley committed 2026-09-05 01:40:15 -07:00
1 parent 4b7cfbbe11
commit 315aed90f0
59 files changed
+5152 -65

No files matched your search

@@ -45,6 +45,7 @@ public class SetupApplicationCommandHandlerTests
private readonly IDateTimeProvider _mockDateTimeProvider;
private readonly IDataSeedService _mockDataSeedService;
private readonly IDomainEventsQueue _mockDomainEventsQueue;
private readonly IValidator<SetupApplicationCommand> _mockValidator;
private readonly SetupApplicationCommandHandler _sut;
private readonly UserEntityFixture _userEntityFixture = new();
private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new();
@@ -65,8 +66,8 @@ public class SetupApplicationCommandHandlerTests
_mockDateTimeProvider = Substitute.For<IDateTimeProvider>();
_mockDataSeedService = Substitute.For<IDataSeedService>();
_mockDomainEventsQueue = Substitute.For<IDomainEventsQueue>();
IValidator<SetupApplicationCommand> mockValidator = Substitute.For<IValidator<SetupApplicationCommand>>();
mockValidator.Validate(Arg.Any<SetupApplicationCommand>())
_mockValidator = Substitute.For<IValidator<SetupApplicationCommand>>();
_mockValidator.Validate(Arg.Any<SetupApplicationCommand>())
.Returns([]);
_mockUnitOfWork.UserRepository.Returns(_mockUserRepository);
@@ -86,7 +87,7 @@ public class SetupApplicationCommandHandlerTests
_mockDateTimeProvider,
_mockDataSeedService,
_mockDomainEventsQueue,
mockValidator);
_mockValidator);
}
[Fact]
@@ -456,4 +457,54 @@ public class SetupApplicationCommandHandlerTests
_mockDomainEventsQueue.Received(1).Enqueue(Arg.Is<ScheduledJobCycleStartedDomainEvent>(domainEvent => domainEvent.ScheduledJobId.Value == activeScheduledJob2.Id));
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Is<ScheduledJobCycleStartedDomainEvent>(domainEvent => domainEvent.ScheduledJobId.Value == addedScheduledJob.Id));
}
[Fact]
public async Task HandleAsync_WhenValidatorReturnsError_ShouldReturnValidationErrorAndNotCreateAnyUser()
{
// Arrange
SetupApplicationCommand command = _setupApplicationCommandFixture.Create();
Error validationError = Error.Validation("Setup.Validation", "The setup command is invalid.");
_mockValidator.Validate(Arg.Any<SetupApplicationCommand>()).Returns([validationError]);
// Act
Result<RegistrationResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(validationError, result.FirstError);
await _mockUserRepository.DidNotReceive().GetAllAsync(Arg.Any<CancellationToken>());
await _mockUserRepository.DidNotReceive().InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenReadingTheSeededScheduledJobsFails_ShouldReturnTheRepositoryError()
{
// Arrange
SetupApplicationCommand command = _setupApplicationCommandFixture.Create();
_mockUserRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(Result.From(Enumerable.Empty<UserEntity>()));
_mockHashService.HashString(command.Password!)
.Returns("hashedPassword");
_mockUserRepository.InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Created);
_mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Created);
_mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Created);
_mockDataSeedService.SetAdminRolePermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Created);
_mockDataSeedService.SetAdminRoleToAdministratorAccount(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Created);
Error expectedError = Error.Failure("ScheduledJobs.NotFound", "Failed to read the scheduled jobs");
_mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
Result<RegistrationResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(expectedError, result.FirstError);
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<ScheduledJobCycleStartedDomainEvent>());
}
}
@@ -253,4 +253,30 @@ public class AddScheduledJobCommandHandlerTests
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));
}
}
@@ -216,4 +216,47 @@ public class RemoveScheduledJobCommandHandlerTests
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, 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, 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>());
}
}
@@ -200,4 +200,46 @@ public class StartScheduledJobCommandHandlerTests
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, 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, 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>());
}
}
@@ -152,6 +152,22 @@ public class StopScheduledJobCommandHandlerTests
await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), 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>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenScheduledJobDoesNotExist_ShouldReturnNotFound()
{
@@ -214,4 +230,46 @@ public class StopScheduledJobCommandHandlerTests
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, 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, 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>());
}
}
@@ -67,6 +67,35 @@ public class ScheduledJobRepositoryTests
Assert.Null(result.Value);
}
[Fact]
public async Task GetByIdWithoutTrackingAsync_WhenScheduledJobExists_ShouldReturnScheduledJob()
{
// Arrange
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create();
_mockContext.ScheduledJobs.Add(scheduledJob);
await _mockContext.SaveChangesAsync();
// Act
Result<ScheduledJobEntity?> result = await _sut.GetByIdWithoutTrackingAsync(scheduledJob.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.NotNull(result.Value);
Assert.Equal(scheduledJob.Id, result.Value!.Id);
Assert.Equal(scheduledJob.Name, result.Value.Name);
}
[Fact]
public async Task GetByIdWithoutTrackingAsync_WhenScheduledJobDoesNotExist_ShouldReturnNull()
{
// Act
Result<ScheduledJobEntity?> result = await _sut.GetByIdWithoutTrackingAsync(Guid.NewGuid(), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public async Task GetAllAsync_WhenScheduledJobsExist_ShouldReturnAllScheduledJobs()
{
@@ -40,7 +40,6 @@ public class DataSeedServiceTests
private readonly UserEntityFixture _userEntityFixture = new();
private readonly RoleEntityFixture _roleEntityFixture = new();
private readonly PermissionEntityFixture _permissionEntityFixture = new();
private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="DataSeedServiceTests"/> class.
@@ -551,14 +550,12 @@ public class DataSeedServiceTests
}
[Fact]
public async Task SetDefaultScheduledJobsAsync_WhenNoScheduledJobsExist_ShouldInsertTheFiveDefaultJobsAndReturnCreated()
public async Task SetDefaultScheduledJobsAsync_WhenCalled_ShouldInsertTheFiveDefaultJobsAndReturnCreated()
{
// Arrange
Guid adminUserId = Guid.NewGuid();
IScheduledJobRepository mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
_mockUnitOfWork.ScheduledJobRepository.Returns(mockScheduledJobRepository);
mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(Result.From(Enumerable.Empty<ScheduledJobEntity>()));
List<ScheduledJobEntity> capturedScheduledJobs = [];
mockScheduledJobRepository.InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Created)
@@ -583,48 +580,7 @@ public class DataSeedServiceTests
await mockScheduledJobRepository.Received(5).InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task SetDefaultScheduledJobsAsync_WhenScheduledJobsAlreadyExist_ShouldNotInsertAnyJob()
{
// Arrange
Guid adminUserId = Guid.NewGuid();
IScheduledJobRepository mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
_mockUnitOfWork.ScheduledJobRepository.Returns(mockScheduledJobRepository);
ScheduledJobEntity existingScheduledJob = _scheduledJobEntityFixture.Create(scheduleType: ScheduleType.WithIntervalInMinutes);
mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(new[] { existingScheduledJob });
// Act
Result<Created> result = await _sut.SetDefaultScheduledJobsAsync(adminUserId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Created, result.Value);
await mockScheduledJobRepository.DidNotReceive().InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task SetDefaultScheduledJobsAsync_WhenGetAllScheduledJobsFails_ShouldReturnError()
{
// Arrange
Guid adminUserId = Guid.NewGuid();
IScheduledJobRepository mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
_mockUnitOfWork.ScheduledJobRepository.Returns(mockScheduledJobRepository);
Error expectedError = Error.Failure("ScheduledJobs.NotFound", "Failed to retrieve the scheduled jobs");
mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
Result<Created> result = await _sut.SetDefaultScheduledJobsAsync(adminUserId, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(expectedError, result.FirstError);
await mockScheduledJobRepository.DidNotReceive().InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
await mockScheduledJobRepository.DidNotReceive().GetAllAsync(Arg.Any<CancellationToken>());
}
[Fact]
@@ -634,8 +590,6 @@ public class DataSeedServiceTests
Guid adminUserId = Guid.NewGuid();
IScheduledJobRepository mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
_mockUnitOfWork.ScheduledJobRepository.Returns(mockScheduledJobRepository);
mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(Result.From(Enumerable.Empty<ScheduledJobEntity>()));
Error expectedError = Error.Failure("ScheduledJobs.InsertFailed", "Failed to insert the scheduled job");
mockScheduledJobRepository.InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Created, expectedError);
@@ -120,4 +120,99 @@ public class ScheduledJobRuntimeRegistryTests
// Assert
Assert.True(result);
}
[Fact]
public void HasActiveCycle_WhenCycleIsRunning_ShouldReturnTrue()
{
// Arrange
ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create();
using CancellationTokenSource cycleCancellationTokenSource = new();
_sut.TryStartCycle(scheduledJobId, cycleCancellationTokenSource);
// Act
bool result = _sut.HasActiveCycle(scheduledJobId);
// Assert
Assert.True(result);
}
[Fact]
public void HasActiveCycle_WhenNoCycleIsRunning_ShouldReturnFalse()
{
// Arrange
ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create();
// Act
bool result = _sut.HasActiveCycle(scheduledJobId);
// Assert
Assert.False(result);
}
[Fact]
public void HasActiveCycle_AfterTheCycleWasStopped_ShouldReturnFalse()
{
// Arrange
ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create();
using CancellationTokenSource cycleCancellationTokenSource = new();
_sut.TryStartCycle(scheduledJobId, cycleCancellationTokenSource);
_sut.StopCycle(scheduledJobId);
// Act
bool result = _sut.HasActiveCycle(scheduledJobId);
// Assert
Assert.False(result);
}
[Fact]
public void EndCycle_WhenCalledWithTheOwnedTokenSource_ShouldCancelItAndClearTheCycle()
{
// Arrange
ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create();
using CancellationTokenSource cycleCancellationTokenSource = new();
_sut.TryStartCycle(scheduledJobId, cycleCancellationTokenSource);
// Act
_sut.EndCycle(scheduledJobId, cycleCancellationTokenSource);
// Assert
Assert.True(cycleCancellationTokenSource.IsCancellationRequested);
Assert.False(_sut.HasActiveCycle(scheduledJobId));
}
[Fact]
public void EndCycle_WhenTheCycleWasReplacedByANewerOne_ShouldNotCancelTheNewerCycle()
{
// Arrange
ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create();
using CancellationTokenSource oldCycleCancellationTokenSource = new();
using CancellationTokenSource newCycleCancellationTokenSource = new();
_sut.TryStartCycle(scheduledJobId, oldCycleCancellationTokenSource);
_sut.StopCycle(scheduledJobId);
_sut.TryStartCycle(scheduledJobId, newCycleCancellationTokenSource);
// Act
_sut.EndCycle(scheduledJobId, oldCycleCancellationTokenSource);
// Assert
Assert.True(oldCycleCancellationTokenSource.IsCancellationRequested);
Assert.False(newCycleCancellationTokenSource.IsCancellationRequested);
Assert.True(_sut.HasActiveCycle(scheduledJobId));
}
[Fact]
public void EndCycle_WhenNoCycleIsRegistered_ShouldStillCancelTheOwnedTokenSource()
{
// Arrange
ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create();
using CancellationTokenSource cycleCancellationTokenSource = new();
// Act
_sut.EndCycle(scheduledJobId, cycleCancellationTokenSource);
// Assert
Assert.True(cycleCancellationTokenSource.IsCancellationRequested);
Assert.False(_sut.HasActiveCycle(scheduledJobId));
}
}
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Domain.Common.Events;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using Lumina.Infrastructure.Core.Scheduling.Execution;
@@ -21,6 +22,8 @@ public class ScheduledTaskExecutorFactoryTests
private readonly IServiceProvider _mockServiceProvider;
private readonly MediaLibraryScanTaskExecutor _mockMediaLibraryScanTaskExecutor;
private readonly TemporaryFilesCleanupTaskExecutor _mockTemporaryFilesCleanupTaskExecutor;
private readonly RepairThemesTaskExecutor _mockRepairThemesTaskExecutor;
private readonly CleanScheduledJobExecutionHistoryTaskExecutor _mockCleanScheduledJobExecutionHistoryTaskExecutor;
private readonly ScheduledTaskExecutorFactory _sut;
/// <summary>
@@ -35,9 +38,19 @@ public class ScheduledTaskExecutorFactoryTests
Substitute.For<IUnitOfWork>());
_mockTemporaryFilesCleanupTaskExecutor = Substitute.For<TemporaryFilesCleanupTaskExecutor>(
Substitute.For<ILogger<TemporaryFilesCleanupTaskExecutor>>());
_mockRepairThemesTaskExecutor = Substitute.For<RepairThemesTaskExecutor>(
Substitute.For<Lumina.Application.Common.Infrastructure.Themes.IThemeService>(),
Substitute.For<ILogger<RepairThemesTaskExecutor>>(),
Substitute.For<IUnitOfWork>());
_mockCleanScheduledJobExecutionHistoryTaskExecutor = Substitute.For<CleanScheduledJobExecutionHistoryTaskExecutor>(
Substitute.For<IDateTimeProvider>(),
Substitute.For<ILogger<CleanScheduledJobExecutionHistoryTaskExecutor>>(),
Substitute.For<IUnitOfWork>());
_mockServiceProvider.GetService(typeof(MediaLibraryScanTaskExecutor)).Returns(_mockMediaLibraryScanTaskExecutor);
_mockServiceProvider.GetService(typeof(TemporaryFilesCleanupTaskExecutor)).Returns(_mockTemporaryFilesCleanupTaskExecutor);
_mockServiceProvider.GetService(typeof(RepairThemesTaskExecutor)).Returns(_mockRepairThemesTaskExecutor);
_mockServiceProvider.GetService(typeof(CleanScheduledJobExecutionHistoryTaskExecutor)).Returns(_mockCleanScheduledJobExecutionHistoryTaskExecutor);
_sut = new ScheduledTaskExecutorFactory(_mockServiceProvider);
}
@@ -62,6 +75,26 @@ public class ScheduledTaskExecutorFactoryTests
Assert.Same(_mockTemporaryFilesCleanupTaskExecutor, result);
}
[Fact]
public void CreateExecutor_WhenTaskTypeIsRepairThemes_ShouldReturnRepairThemesTaskExecutor()
{
// Act
IScheduledTaskExecutor result = _sut.CreateExecutor(ScheduledTaskType.RepairThemes);
// Assert
Assert.Same(_mockRepairThemesTaskExecutor, result);
}
[Fact]
public void CreateExecutor_WhenTaskTypeIsCleanScheduledJobExecutionHistory_ShouldReturnCleanScheduledJobExecutionHistoryTaskExecutor()
{
// Act
IScheduledTaskExecutor result = _sut.CreateExecutor(ScheduledTaskType.CleanScheduledJobExecutionHistory);
// Assert
Assert.Same(_mockCleanScheduledJobExecutionHistoryTaskExecutor, result);
}
[Fact]
public void CreateExecutor_WhenTaskTypeIsUnsupported_ShouldThrowArgumentException()
{
@@ -0,0 +1,78 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using Lumina.Infrastructure.Core.Scheduling.Execution.TaskExecutors;
using Microsoft.Extensions.Logging;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.Scheduling.Execution.TaskExecutors;
/// <summary>
/// Contains unit tests for the <see cref="CleanScheduledJobExecutionHistoryTaskExecutor"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class CleanScheduledJobExecutionHistoryTaskExecutorTests
{
private readonly IDateTimeProvider _mockDateTimeProvider;
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IScheduledJobExecutionRepository _mockScheduledJobExecutionRepository;
private readonly CleanScheduledJobExecutionHistoryTaskExecutor _sut;
private readonly ScheduledJobFixture _scheduledJobFixture = new();
private readonly DateTime _fixedUtcNow = DateTime.UtcNow;
/// <summary>
/// Initializes a new instance of the <see cref="CleanScheduledJobExecutionHistoryTaskExecutorTests"/> class.
/// </summary>
public CleanScheduledJobExecutionHistoryTaskExecutorTests()
{
_mockDateTimeProvider = Substitute.For<IDateTimeProvider>();
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockScheduledJobExecutionRepository = Substitute.For<IScheduledJobExecutionRepository>();
_mockDateTimeProvider.UtcNow.Returns(_fixedUtcNow);
_mockUnitOfWork.ScheduledJobExecutionRepository.Returns(_mockScheduledJobExecutionRepository);
ILogger<CleanScheduledJobExecutionHistoryTaskExecutor> logger = Substitute.For<ILogger<CleanScheduledJobExecutionHistoryTaskExecutor>>();
_sut = new CleanScheduledJobExecutionHistoryTaskExecutor(_mockDateTimeProvider, logger, _mockUnitOfWork);
}
[Fact]
public async Task ExecutePayloadAsync_WhenCalled_ShouldDeleteTheExecutionsOlderThanAMonth()
{
// Arrange
ScheduledJob scheduledJob = _scheduledJobFixture.Create(taskType: ScheduledTaskType.CleanScheduledJobExecutionHistory);
_mockScheduledJobExecutionRepository.DeleteOlderThanAsync(Arg.Any<DateTime>(), Arg.Any<CancellationToken>()).Returns(Result.Success);
DateTime expectedCutoff = _fixedUtcNow.AddMonths(-1);
// Act
Result<Success> result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockScheduledJobExecutionRepository.Received(1).DeleteOlderThanAsync(Arg.Is<DateTime>(cutoff => cutoff == expectedCutoff), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecutePayloadAsync_WhenTheDeletionFails_ShouldReturnTheError()
{
// Arrange
ScheduledJob scheduledJob = _scheduledJobFixture.Create(taskType: ScheduledTaskType.CleanScheduledJobExecutionHistory);
Error expectedError = Error.Failure("Database.Error", "Failed to delete the old executions");
_mockScheduledJobExecutionRepository.DeleteOlderThanAsync(Arg.Any<DateTime>(), Arg.Any<CancellationToken>()).Returns(expectedError);
// Act
Result<Success> result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(expectedError, result.FirstError);
}
}
@@ -7,6 +7,7 @@ using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Infrastructure.Core.Scheduling.Execution.TaskExecutors;
using Microsoft.Extensions.Logging;
using NSubstitute;
@@ -31,6 +32,7 @@ public class MediaLibraryScanTaskExecutorTests
private readonly MediaLibraryScanTaskExecutor _sut;
private readonly ScheduledJobFixture _scheduledJobFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="MediaLibraryScanTaskExecutorTests"/> class.
@@ -100,4 +102,71 @@ public class MediaLibraryScanTaskExecutorTests
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
}
[Fact]
public async Task ExecutePayloadAsync_WhenALibraryIsAlreadyBeingScanned_ShouldSkipThatLibrary()
{
// Arrange
ScheduledJob scheduledJob = _scheduledJobFixture.Create();
LibraryEntity library = _libraryEntityFixture.Create();
_mockLibraryRepository.GetAllEnabledAndUnlockedAsync(Arg.Any<CancellationToken>())
.Returns(Result.From<IEnumerable<LibraryEntity>>([library]));
LibraryScanEntity runningScan = _libraryScanEntityFixture.Create(libraryId: library.Id, status: LibraryScanJobStatus.Running);
_mockUnitOfWork.LibraryScanRepository.GetPastMonthScansByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IEnumerable<LibraryScanEntity>>([runningScan]));
// Act
Result<Success> result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecutePayloadAsync_WhenAQueuedScanIsInserted_ShouldPublishItsDomainEvents()
{
// Arrange
ScheduledJob scheduledJob = _scheduledJobFixture.Create();
LibraryEntity library = _libraryEntityFixture.Create();
_mockLibraryRepository.GetAllEnabledAndUnlockedAsync(Arg.Any<CancellationToken>())
.Returns(Result.From<IEnumerable<LibraryEntity>>([library]));
_mockUnitOfWork.LibraryScanRepository.GetPastMonthScansByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IEnumerable<LibraryScanEntity>>([]));
_mockUnitOfWork.LibraryScanRepository.InsertAsync(Arg.Any<LibraryScanEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Created);
// Act
Result<Success> result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockUnitOfWork.LibraryScanRepository.Received(1).InsertAsync(Arg.Any<LibraryScanEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecutePayloadAsync_WhenInsertingTheQueuedScanFails_ShouldReturnError()
{
// Arrange
ScheduledJob scheduledJob = _scheduledJobFixture.Create();
LibraryEntity library = _libraryEntityFixture.Create();
_mockLibraryRepository.GetAllEnabledAndUnlockedAsync(Arg.Any<CancellationToken>())
.Returns(Result.From<IEnumerable<LibraryEntity>>([library]));
_mockUnitOfWork.LibraryScanRepository.GetPastMonthScansByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IEnumerable<LibraryScanEntity>>([]));
Error error = Error.Failure("Database.Error", "Failed to insert the scan");
_mockUnitOfWork.LibraryScanRepository.InsertAsync(Arg.Any<LibraryScanEntity>(), Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<Success> result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,119 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Themes;
using Lumina.Application.Common.DataAccess.Repositories.Themes;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Models.DTO.Themes;
using Lumina.Application.Common.Infrastructure.Themes;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using Lumina.Infrastructure.Core.Scheduling.Execution.TaskExecutors;
using Microsoft.Extensions.Logging;
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.Infrastructure.UnitTests.Core.Scheduling.Execution.TaskExecutors;
/// <summary>
/// Contains unit tests for the <see cref="RepairThemesTaskExecutor"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RepairThemesTaskExecutorTests
{
private readonly IThemeService _mockThemeService;
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IThemeRepository _mockThemeRepository;
private readonly RepairThemesTaskExecutor _sut;
private readonly ScheduledJobFixture _scheduledJobFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="RepairThemesTaskExecutorTests"/> class.
/// </summary>
public RepairThemesTaskExecutorTests()
{
_mockThemeService = Substitute.For<IThemeService>();
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockThemeRepository = Substitute.For<IThemeRepository>();
_mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository);
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
ILogger<RepairThemesTaskExecutor> logger = Substitute.For<ILogger<RepairThemesTaskExecutor>>();
_sut = new RepairThemesTaskExecutor(_mockThemeService, logger, _mockUnitOfWork);
}
[Fact]
public async Task ExecutePayloadAsync_WhenCalled_ShouldSynchronizeTheThemes()
{
// Arrange
ScheduledJob scheduledJob = _scheduledJobFixture.Create(taskType: ScheduledTaskType.RepairThemes);
_mockThemeService.GetBundledThemeArchivePaths().Returns([]);
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From(Enumerable.Empty<ThemeEntity>()));
// Act
Result<Success> result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockThemeRepository.Received(1).GetAllAsync(Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecutePayloadAsync_WhenABundledThemeArchiveCannotBeRead_ShouldStillSucceed()
{
// Arrange
ScheduledJob scheduledJob = _scheduledJobFixture.Create(taskType: ScheduledTaskType.RepairThemes);
_mockThemeService.GetBundledThemeArchivePaths().Returns(["missing.zip"]);
_mockThemeService.ReadManifestFromArchiveAsync(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Theme.Manifest", "Failed to read the theme manifest"));
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From(Enumerable.Empty<ThemeEntity>()));
// Act
Result<Success> result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockThemeRepository.Received(1).GetAllAsync(Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecutePayloadAsync_WhenTheSynchronizationThrows_ShouldReturnFailure()
{
// Arrange
ScheduledJob scheduledJob = _scheduledJobFixture.Create(taskType: ScheduledTaskType.RepairThemes);
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(Task.FromException<Result<IEnumerable<ThemeEntity>>>(new InvalidOperationException("The database is unavailable.")));
// Act
Result<Success> result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(nameof(RepairThemesTaskExecutor), result.FirstError.Description);
}
[Fact]
public async Task ExecutePayloadAsync_WhenTheSynchronizationIsCancelled_ShouldRethrowTheCancellation()
{
// Arrange
ScheduledJob scheduledJob = _scheduledJobFixture.Create(taskType: ScheduledTaskType.RepairThemes);
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(Task.FromException<Result<IEnumerable<ThemeEntity>>>(new OperationCanceledException()));
// Act
async Task Act()
{
await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None);
}
// Assert
await Assert.ThrowsAsync<OperationCanceledException>(Act);
}
}
@@ -0,0 +1,498 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Themes;
using Lumina.Application.Common.DataAccess.Repositories.Themes;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Models.DTO.Themes;
using Lumina.Application.Common.Infrastructure.Themes;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes;
using Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.Themes;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Themes;
using Lumina.Infrastructure.Core.Themes;
using Microsoft.Extensions.Logging;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.Themes;
/// <summary>
/// Contains unit tests for the <see cref="ThemeSynchronizer"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ThemeSynchronizerTests : IDisposable
{
private readonly IThemeService _mockThemeService;
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IThemeRepository _mockThemeRepository;
private readonly ILogger _mockLogger;
private readonly ThemeEntityFixture _themeEntityFixture = new();
private readonly ThemeManifestDtoFixture _themeManifestDtoFixture = new();
private readonly string _temporaryDirectoryPath;
/// <summary>
/// Initializes a new instance of the <see cref="ThemeSynchronizerTests"/> class.
/// </summary>
public ThemeSynchronizerTests()
{
_mockThemeService = Substitute.For<IThemeService>();
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockThemeRepository = Substitute.For<IThemeRepository>();
_mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository);
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
_mockLogger = Substitute.For<ILogger>();
_mockThemeService.GetBundledThemeArchivePaths().Returns([]);
_mockThemeService.HasThemePack(Arg.Any<string>()).Returns(true);
_mockThemeService.DefaultThemeId.Returns("lumina-default");
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From(Enumerable.Empty<ThemeEntity>()));
_mockThemeRepository.InsertAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>()).Returns(Result.Created);
_mockThemeRepository.UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>()).Returns(Result.Updated);
_mockThemeRepository.DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(Result.Deleted);
_temporaryDirectoryPath = Path.Combine(Path.GetTempPath(), $"lumina-theme-sync-{Guid.NewGuid():N}");
Directory.CreateDirectory(_temporaryDirectoryPath);
}
[Fact]
public async Task SynchronizeAsync_WhenTheInstalledThemesCannotBeRead_ShouldLogAndReturn()
{
// Arrange
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(Error.Failure("Themes.NotFound", "Failed to read the installed themes"));
_mockThemeService.GetBundledThemeArchivePaths().Returns(["bundled.zip"]);
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockThemeService.DidNotReceive().ReadManifestFromArchiveAsync(Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenABundledArchiveManifestCannotBeRead_ShouldSkipThatArchive()
{
// Arrange
_mockThemeService.GetBundledThemeArchivePaths().Returns(["missing.zip"]);
_mockThemeService.ReadManifestFromArchiveAsync("missing.zip", Arg.Any<CancellationToken>())
.Returns(Error.Failure("Theme.Manifest", "Failed to read the theme manifest"));
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenTheBundledThemeIsAlreadyInstalled_ShouldNotReinstallIt()
{
// Arrange
ThemeManifestDto manifest = _themeManifestDtoFixture.Create();
ThemeEntity installedTheme = _themeEntityFixture.Create(themeId: manifest.Id, installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true);
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(new[] { installedTheme });
_mockThemeService.GetBundledThemeArchivePaths().Returns(["bundled.zip"]);
_mockThemeService.ReadManifestFromArchiveAsync("bundled.zip", Arg.Any<CancellationToken>()).Returns(Result.From(manifest));
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>());
await _mockThemeRepository.DidNotReceive().InsertAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenTheBundledThemeWasSoftDeletedByTheUser_ShouldNotReinstallIt()
{
// Arrange
ThemeManifestDto manifest = _themeManifestDtoFixture.Create();
ThemeEntity deletedTheme = _themeEntityFixture.Create(themeId: manifest.Id, installSource: ThemeInstallSource.Bundled, isDeleted: true);
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(new[] { deletedTheme });
_mockThemeService.GetBundledThemeArchivePaths().Returns(["bundled.zip"]);
_mockThemeService.ReadManifestFromArchiveAsync("bundled.zip", Arg.Any<CancellationToken>()).Returns(Result.From(manifest));
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>());
await _mockThemeRepository.DidNotReceive().InsertAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenABundledThemeIsMissingItsFiles_ShouldReinstallThemWithoutAddingANewRow()
{
// Arrange
ThemeManifestDto manifest = _themeManifestDtoFixture.Create();
ThemeEntity damagedTheme = _themeEntityFixture.Create(themeId: manifest.Id, installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true);
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(new[] { damagedTheme });
string archivePath = CreateArchiveFile();
_mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]);
// The first pack check happens before the repair and reports the files as missing; the later checks report the files as present.
_mockThemeService.HasThemePack(damagedTheme.ThemeId).Returns(false, true);
_mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any<CancellationToken>()).Returns(Result.From(manifest));
_mockThemeService.InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>()).Returns(Result.From(manifest));
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockThemeService.Received(1).InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>());
await _mockThemeRepository.DidNotReceive().InsertAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenTheReinstallationFails_ShouldLogAndKeepTheExistingTheme()
{
// Arrange
ThemeManifestDto manifest = _themeManifestDtoFixture.Create();
ThemeEntity damagedTheme = _themeEntityFixture.Create(themeId: manifest.Id, installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true);
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(new[] { damagedTheme });
string archivePath = CreateArchiveFile();
_mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]);
_mockThemeService.HasThemePack(damagedTheme.ThemeId).Returns(false, true);
_mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any<CancellationToken>()).Returns(Result.From(manifest));
_mockThemeService.InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Theme.Install", "Failed to install the theme"));
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockThemeService.Received(1).InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>());
await _mockThemeRepository.DidNotReceive().InsertAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenANewBundledThemeIsInstalled_ShouldInsertTheThemeRow()
{
// Arrange
ThemeManifestDto manifest = _themeManifestDtoFixture.Create();
string archivePath = CreateArchiveFile();
_mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]);
_mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any<CancellationToken>()).Returns(Result.From(manifest));
_mockThemeService.InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>()).Returns(Result.From(manifest));
_mockThemeService.HasThemePack(manifest.Id).Returns(true);
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockThemeRepository.Received(1).InsertAsync(Arg.Is<ThemeEntity>(theme => theme.ThemeId == manifest.Id && theme.InstallSource == ThemeInstallSource.Bundled), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenPersistingANewBundledThemeFails_ShouldLogAndContinue()
{
// Arrange
ThemeManifestDto manifest = _themeManifestDtoFixture.Create();
string archivePath = CreateArchiveFile();
_mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]);
_mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any<CancellationToken>()).Returns(Result.From(manifest));
_mockThemeService.InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>()).Returns(Result.From(manifest));
_mockThemeService.HasThemePack(manifest.Id).Returns(true);
_mockThemeRepository.InsertAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Themes.InsertFailed", "Failed to insert the theme"));
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockThemeRepository.Received(1).InsertAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenTheArchiveFileCannotBeRead_ShouldLogAndContinue()
{
// Arrange
ThemeManifestDto manifest = _themeManifestDtoFixture.Create();
string missingArchivePath = Path.Combine(_temporaryDirectoryPath, "missing.zip");
_mockThemeService.GetBundledThemeArchivePaths().Returns([missingArchivePath]);
_mockThemeService.ReadManifestFromArchiveAsync(missingArchivePath, Arg.Any<CancellationToken>()).Returns(Result.From(manifest));
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenAccessToTheArchiveFileIsDenied_ShouldLogAndContinue()
{
// On non Windows platforms opening a directory behaves differently, so the test only asserts the denied access path on Windows.
if (!OperatingSystem.IsWindows())
return;
// Arrange
ThemeManifestDto manifest = _themeManifestDtoFixture.Create();
string deniedArchivePath = _temporaryDirectoryPath;
_mockThemeService.GetBundledThemeArchivePaths().Returns([deniedArchivePath]);
_mockThemeService.ReadManifestFromArchiveAsync(deniedArchivePath, Arg.Any<CancellationToken>()).Returns(Result.From(manifest));
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenAllThemesAreHealthyAndNoArchiveIsBundled_ShouldOnlyPersistTheChanges()
{
// Arrange
ThemeEntity healthyTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true);
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(new[] { healthyTheme });
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenABundledThemeIsBroken_ShouldRestoreItsFiles()
{
// Arrange
ThemeEntity brokenTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true);
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(new[] { brokenTheme });
_mockThemeService.HasThemePack(brokenTheme.ThemeId).Returns(false);
_mockThemeService.RestoreBundledThemeAsync(brokenTheme.ThemeId, Arg.Any<CancellationToken>()).Returns(Result.Success);
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockThemeService.Received(1).RestoreBundledThemeAsync(brokenTheme.ThemeId, Arg.Any<CancellationToken>());
await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
await _mockThemeRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenTheLastBundledThemeCannotBeRestored_ShouldKeepIt()
{
// Arrange
ThemeEntity lastBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true);
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(new[] { lastBundledTheme });
_mockThemeService.HasThemePack(lastBundledTheme.ThemeId).Returns(false);
_mockThemeService.RestoreBundledThemeAsync(lastBundledTheme.ThemeId, Arg.Any<CancellationToken>())
.Returns(Error.Failure("Theme.Restore", "Failed to restore the theme"));
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
Assert.False(lastBundledTheme.IsDeleted);
await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenABundledThemeCannotBeRestored_ShouldSoftDeleteIt()
{
// Arrange
ThemeEntity brokenBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false);
ThemeEntity healthyBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true);
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(new[] { brokenBundledTheme, healthyBundledTheme });
_mockThemeService.HasThemePack(brokenBundledTheme.ThemeId).Returns(false);
_mockThemeService.RestoreBundledThemeAsync(brokenBundledTheme.ThemeId, Arg.Any<CancellationToken>())
.Returns(Error.Failure("Theme.Restore", "Failed to restore the theme"));
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
Assert.True(brokenBundledTheme.IsDeleted);
await _mockThemeRepository.Received(1).UpdateAsync(Arg.Is<ThemeEntity>(theme => theme.Id == brokenBundledTheme.Id), Arg.Any<CancellationToken>());
await _mockThemeRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenSoftDeletingABrokenBundledThemeFails_ShouldLogAndContinue()
{
// Arrange
ThemeEntity brokenBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false);
ThemeEntity healthyBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true);
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(new[] { brokenBundledTheme, healthyBundledTheme });
_mockThemeService.HasThemePack(brokenBundledTheme.ThemeId).Returns(false);
_mockThemeService.RestoreBundledThemeAsync(brokenBundledTheme.ThemeId, Arg.Any<CancellationToken>())
.Returns(Error.Failure("Theme.Restore", "Failed to restore the theme"));
_mockThemeRepository.UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Themes.UpdateFailed", "Failed to update the theme"));
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockThemeRepository.Received(1).UpdateAsync(Arg.Is<ThemeEntity>(theme => theme.Id == brokenBundledTheme.Id), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenAUserThemeIsBroken_ShouldDeleteIt()
{
// Arrange
ThemeEntity brokenUserTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Uploaded, isDeleted: false, includeIsCurrent: true, isCurrent: true);
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(new[] { brokenUserTheme });
_mockThemeService.HasThemePack(brokenUserTheme.ThemeId).Returns(false);
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockThemeRepository.Received(1).DeleteByIdAsync(brokenUserTheme.Id, Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenDeletingABrokenUserThemeFails_ShouldLogAndContinue()
{
// Arrange
ThemeEntity brokenUserTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Uploaded, isDeleted: false, includeIsCurrent: true, isCurrent: true);
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(new[] { brokenUserTheme });
_mockThemeService.HasThemePack(brokenUserTheme.ThemeId).Returns(false);
_mockThemeRepository.DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Themes.DeleteFailed", "Failed to delete the theme"));
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockThemeRepository.Received(1).DeleteByIdAsync(brokenUserTheme.Id, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenRepairingOneBrokenThemeThrows_ShouldContinueWithTheRemainingBrokenThemes()
{
// Arrange
ThemeEntity throwingBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false);
ThemeEntity healthyBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true);
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(new[] { throwingBundledTheme, healthyBundledTheme });
_mockThemeService.HasThemePack(Arg.Any<string>()).Returns(false);
_mockThemeService.RestoreBundledThemeAsync(throwingBundledTheme.ThemeId, Arg.Any<CancellationToken>())
.Returns(Task.FromException<Result<Success>>(new InvalidOperationException("Unexpected failure")));
_mockThemeService.RestoreBundledThemeAsync(healthyBundledTheme.ThemeId, Arg.Any<CancellationToken>())
.Returns(Error.Failure("Theme.Restore", "Failed to restore the theme"));
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
// The second broken bundled theme is still soft deleted even though the first one threw.
Assert.True(healthyBundledTheme.IsDeleted);
await _mockThemeRepository.Received(1).UpdateAsync(Arg.Is<ThemeEntity>(theme => theme.Id == healthyBundledTheme.Id), Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenRepairingABrokenThemeIsCancelled_ShouldRethrowTheCancellation()
{
// Arrange
ThemeEntity brokenBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false);
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(new[] { brokenBundledTheme });
_mockThemeService.HasThemePack(brokenBundledTheme.ThemeId).Returns(false);
_mockThemeService.RestoreBundledThemeAsync(brokenBundledTheme.ThemeId, Arg.Any<CancellationToken>())
.Returns(Task.FromException<Result<Success>>(new OperationCanceledException()));
// Act
async Task Act()
{
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
}
// Assert
await Assert.ThrowsAsync<OperationCanceledException>(Act);
}
[Fact]
public async Task EnsureCurrentThemeExistsAsync_WhenANonDeletedThemeIsCurrent_ShouldNotSelectAnotherTheme()
{
// Arrange
ThemeEntity currentTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true);
ThemeEntity otherTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Uploaded, isDeleted: false);
// Act
await InvokeEnsureCurrentThemeExistsAsync([currentTheme, otherTheme]);
// Assert
Assert.True(currentTheme.IsCurrent);
Assert.NotEqual(true, otherTheme.IsCurrent);
await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task EnsureCurrentThemeExistsAsync_WhenNoThemeCanBeSelected_ShouldNotSelectAnyTheme()
{
// Arrange
ThemeEntity deletedTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: true);
// Act
await InvokeEnsureCurrentThemeExistsAsync([deletedTheme]);
// Assert
Assert.NotEqual(true, deletedTheme.IsCurrent);
await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task EnsureCurrentThemeExistsAsync_WhenNoThemeIsCurrent_ShouldActivateTheDefaultTheme()
{
// Arrange
ThemeEntity defaultTheme = _themeEntityFixture.Create(themeId: "lumina-default", installSource: ThemeInstallSource.Bundled, isDeleted: false);
ThemeEntity userTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Uploaded, isDeleted: false);
_mockThemeService.HasThemePack(defaultTheme.ThemeId).Returns(true);
_mockThemeService.HasThemePack(userTheme.ThemeId).Returns(false);
// Act
await InvokeEnsureCurrentThemeExistsAsync([userTheme, defaultTheme]);
// Assert
Assert.True(defaultTheme.IsCurrent);
await _mockThemeRepository.Received(1).UpdateAsync(Arg.Is<ThemeEntity>(theme => theme.Id == defaultTheme.Id), Arg.Any<CancellationToken>());
}
/// <summary>
/// Creates a real archive file on disk so that <see cref="ThemeSynchronizer"/> can open it.
/// </summary>
/// <returns>The path of the created archive file.</returns>
private string CreateArchiveFile()
{
string archivePath = Path.Combine(_temporaryDirectoryPath, $"theme-{Guid.NewGuid():N}.zip");
File.WriteAllText(archivePath, "theme-pack");
return archivePath;
}
/// <summary>
/// Invokes the private <c>EnsureCurrentThemeExistsAsync</c> method of the synchronizer.
/// </summary>
/// <param name="themes">The installed themes passed to the method.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
private async Task InvokeEnsureCurrentThemeExistsAsync(IReadOnlyList<ThemeEntity> themes)
{
MethodInfo method = typeof(ThemeSynchronizer).GetMethod("EnsureCurrentThemeExistsAsync", BindingFlags.Static | BindingFlags.NonPublic)
?? throw new InvalidOperationException("The method 'EnsureCurrentThemeExistsAsync' was not found on the theme synchronizer.");
Task task = (Task)method.Invoke(null, [_mockThemeService, _mockUnitOfWork, themes, CancellationToken.None])!;
await task.ConfigureAwait(false);
}
/// <summary>
/// Removes the temporary files created by the tests.
/// </summary>
public void Dispose()
{
if (Directory.Exists(_temporaryDirectoryPath))
Directory.Delete(_temporaryDirectoryPath, recursive: true);
}
}
@@ -0,0 +1,86 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.Scheduling;
using Lumina.Presentation.Web.Common.Requests.Scheduling;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.AddScheduledJob;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Scheduling;
using Lumina.Presentation.Web.Fixtures.Common.Requests.Scheduling;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Microsoft.AspNetCore.Http;
using NSubstitute;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Scheduler.AddScheduledJob;
/// <summary>
/// Contains unit tests for the <see cref="AddScheduledJobEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddScheduledJobEndpointTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly AddScheduledJobEndpoint _sut;
private readonly AddScheduledJobRequestFixture _addScheduledJobRequestFixture = new();
private readonly ScheduledJobDtoFixture _scheduledJobDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="AddScheduledJobEndpointTests"/> class.
/// </summary>
public AddScheduledJobEndpointTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
_sut = Factory.Create<AddScheduledJobEndpoint>(_mockApiHttpClient);
}
[Fact]
public async Task ExecuteAsync_WhenApiReturnsCreatedJob_ShouldReturnSuccessJsonWithCreatedJob()
{
// Arrange
AddScheduledJobRequest request = _addScheduledJobRequestFixture.Create();
ScheduledJobDto expectedJob = _scheduledJobDtoFixture.Create(name: request.Name);
_mockApiHttpClient.PostAsync<ScheduledJobDto, AddScheduledJobRequest>(ApiRoutes.ScheduledJobs.ADD_SCHEDULED_JOB, Arg.Any<AddScheduledJobRequest>(), Arg.Any<CancellationToken>())
.Returns(expectedJob);
// Act
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
// Assert
using JsonDocument jsonDocument = JsonDocument.Parse(body);
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
Assert.Equal(expectedJob.Name, jsonDocument.RootElement.GetProperty("data").GetProperty("name").GetString());
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldForwardRequestToApiAndReturnSuccess()
{
// Arrange
AddScheduledJobRequest request = _addScheduledJobRequestFixture.Create();
_mockApiHttpClient.PostAsync<ScheduledJobDto, AddScheduledJobRequest>(Arg.Any<string>(), Arg.Any<AddScheduledJobRequest>(), Arg.Any<CancellationToken>())
.Returns(_scheduledJobDtoFixture.Create());
// Act
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
// Assert
await _mockApiHttpClient.Received(1).PostAsync<ScheduledJobDto, AddScheduledJobRequest>(
ApiRoutes.ScheduledJobs.ADD_SCHEDULED_JOB,
Arg.Is<AddScheduledJobRequest>(forwardedRequest =>
forwardedRequest.Name == request.Name &&
forwardedRequest.TaskType == request.TaskType &&
forwardedRequest.ScheduleType == request.ScheduleType &&
forwardedRequest.IntervalMinutes == request.IntervalMinutes &&
forwardedRequest.Hour == request.Hour &&
forwardedRequest.Minute == request.Minute),
Arg.Any<CancellationToken>());
using JsonDocument jsonDocument = JsonDocument.Parse(body);
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
}
}
@@ -0,0 +1,57 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Requests.Scheduling;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.FireScheduledJob;
using Lumina.Presentation.Web.Fixtures.Common.Requests.Scheduling;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Microsoft.AspNetCore.Http;
using NSubstitute;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Scheduler.FireScheduledJob;
/// <summary>
/// Contains unit tests for the <see cref="FireScheduledJobEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class FireScheduledJobEndpointTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly FireScheduledJobEndpoint _sut;
private readonly FireScheduledJobRequestFixture _fireScheduledJobRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="FireScheduledJobEndpointTests"/> class.
/// </summary>
public FireScheduledJobEndpointTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
_sut = Factory.Create<FireScheduledJobEndpoint>(_mockApiHttpClient);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldFireScheduledJobViaApiAndReturnSuccess()
{
// Arrange
FireScheduledJobRequest request = _fireScheduledJobRequestFixture.Create();
// Act
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
// Assert
string expectedEndpoint = ApiRoutes.ScheduledJobs.FIRE_SCHEDULED_JOB.Replace("{scheduledJobId}", request.ScheduledJobId.ToString());
await _mockApiHttpClient.Received(1).PutAsync<Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest, Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest>(
expectedEndpoint,
Arg.Any<Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
using JsonDocument jsonDocument = JsonDocument.Parse(body);
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
}
}
@@ -0,0 +1,126 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.Scheduling;
using Lumina.Presentation.Web.Common.Requests.Scheduling;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.GetScheduledJobHistory;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Scheduling;
using Lumina.Presentation.Web.Fixtures.Common.Requests.Scheduling;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Microsoft.AspNetCore.Http;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Scheduler.GetScheduledJobHistory;
/// <summary>
/// Contains unit tests for the <see cref="GetScheduledJobHistoryEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetScheduledJobHistoryEndpointTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly GetScheduledJobHistoryEndpoint _sut;
private readonly GetScheduledJobHistoryRequestFixture _getScheduledJobHistoryRequestFixture = new();
private readonly ScheduledJobExecutionDtoFixture _scheduledJobExecutionDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetScheduledJobHistoryEndpointTests"/> class.
/// </summary>
public GetScheduledJobHistoryEndpointTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
_sut = Factory.Create<GetScheduledJobHistoryEndpoint>(_mockApiHttpClient);
}
[Fact]
public async Task ExecuteAsync_WhenApiReturnsExecutions_ShouldReturnSuccessJsonWithExecutions()
{
// Arrange
ScheduledJobExecutionDto[] expectedExecutions = [.. _scheduledJobExecutionDtoFixture.CreateMany(2)];
_mockApiHttpClient.GetAsync<ScheduledJobExecutionDto[]>(ApiRoutes.ScheduledJobs.GET_SCHEDULED_JOB_HISTORY, Arg.Any<CancellationToken>())
.Returns(expectedExecutions);
// Act
IResult result = await _sut.ExecuteAsync(_getScheduledJobHistoryRequestFixture.Create(), CancellationToken.None);
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
// Assert
using JsonDocument jsonDocument = JsonDocument.Parse(body);
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
Assert.Equal(expectedExecutions.Length, jsonDocument.RootElement.GetProperty("data").GetArrayLength());
}
[Fact]
public async Task ExecuteAsync_WhenFromAndToAreNull_ShouldRequestHistoryWithoutQueryString()
{
// Arrange
GetScheduledJobHistoryRequest request = _getScheduledJobHistoryRequestFixture.Create();
_mockApiHttpClient.GetAsync<ScheduledJobExecutionDto[]>(ApiRoutes.ScheduledJobs.GET_SCHEDULED_JOB_HISTORY, Arg.Any<CancellationToken>())
.Returns([]);
// Act
await _sut.ExecuteAsync(request, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).GetAsync<ScheduledJobExecutionDto[]>(ApiRoutes.ScheduledJobs.GET_SCHEDULED_JOB_HISTORY, Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenOnlyFromIsProvided_ShouldRequestHistoryWithFromQueryString()
{
// Arrange
DateTime from = new(2026, 1, 5, 4, 3, 2, DateTimeKind.Utc);
GetScheduledJobHistoryRequest request = _getScheduledJobHistoryRequestFixture.Create(from: from);
string expectedEndpoint = $"{ApiRoutes.ScheduledJobs.GET_SCHEDULED_JOB_HISTORY}?from={Uri.EscapeDataString(from.ToString("o"))}";
_mockApiHttpClient.GetAsync<ScheduledJobExecutionDto[]>(expectedEndpoint, Arg.Any<CancellationToken>())
.Returns([]);
// Act
await _sut.ExecuteAsync(request, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).GetAsync<ScheduledJobExecutionDto[]>(expectedEndpoint, Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenOnlyToIsProvided_ShouldRequestHistoryWithToQueryString()
{
// Arrange
DateTime to = new(2026, 1, 5, 4, 3, 2, DateTimeKind.Utc);
GetScheduledJobHistoryRequest request = _getScheduledJobHistoryRequestFixture.Create(to: to);
string expectedEndpoint = $"{ApiRoutes.ScheduledJobs.GET_SCHEDULED_JOB_HISTORY}?to={Uri.EscapeDataString(to.ToString("o"))}";
_mockApiHttpClient.GetAsync<ScheduledJobExecutionDto[]>(expectedEndpoint, Arg.Any<CancellationToken>())
.Returns([]);
// Act
await _sut.ExecuteAsync(request, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).GetAsync<ScheduledJobExecutionDto[]>(expectedEndpoint, Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenFromAndToAreProvided_ShouldRequestHistoryWithBothQueryStrings()
{
// Arrange
DateTime from = new(2026, 1, 5, 4, 3, 2, DateTimeKind.Utc);
DateTime to = new(2026, 1, 6, 4, 3, 2, DateTimeKind.Utc);
GetScheduledJobHistoryRequest request = _getScheduledJobHistoryRequestFixture.Create(from: from, to: to);
string expectedEndpoint = $"{ApiRoutes.ScheduledJobs.GET_SCHEDULED_JOB_HISTORY}?from={Uri.EscapeDataString(from.ToString("o"))}&to={Uri.EscapeDataString(to.ToString("o"))}";
_mockApiHttpClient.GetAsync<ScheduledJobExecutionDto[]>(expectedEndpoint, Arg.Any<CancellationToken>())
.Returns([]);
// Act
await _sut.ExecuteAsync(request, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).GetAsync<ScheduledJobExecutionDto[]>(expectedEndpoint, Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,73 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.Scheduling;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.GetScheduledJobs;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Scheduling;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Microsoft.AspNetCore.Http;
using NSubstitute;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Scheduler.GetScheduledJobs;
/// <summary>
/// Contains unit tests for the <see cref="GetScheduledJobsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetScheduledJobsEndpointTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly GetScheduledJobsEndpoint _sut;
private readonly ScheduledJobDtoFixture _scheduledJobDtoFixture = new();
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
/// <summary>
/// Initializes a new instance of the <see cref="GetScheduledJobsEndpointTests"/> class.
/// </summary>
public GetScheduledJobsEndpointTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
_sut = Factory.Create<GetScheduledJobsEndpoint>(_mockApiHttpClient);
}
[Fact]
public async Task ExecuteAsync_WhenApiReturnsJobs_ShouldReturnSuccessJsonWithScheduledJobs()
{
// Arrange
ScheduledJobDto[] expectedJobs = [.. _scheduledJobDtoFixture.CreateMany(2)];
_mockApiHttpClient.GetAsync<ScheduledJobDto[]>(ApiRoutes.ScheduledJobs.GET_SCHEDULED_JOBS, Arg.Any<CancellationToken>())
.Returns(expectedJobs);
// Act
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
// Assert
using JsonDocument jsonDocument = JsonDocument.Parse(body);
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
ScheduledJobDto[]? returnedJobs = jsonDocument.RootElement.GetProperty("data").Deserialize<ScheduledJobDto[]>(_jsonOptions);
Assert.Equal(expectedJobs.Length, returnedJobs!.Length);
Assert.Equal(expectedJobs.Select(job => job.Name), returnedJobs.Select(job => job.Name));
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldRequestScheduledJobsFromApi()
{
// Arrange
_mockApiHttpClient.GetAsync<ScheduledJobDto[]>(ApiRoutes.ScheduledJobs.GET_SCHEDULED_JOBS, Arg.Any<CancellationToken>())
.Returns([.. _scheduledJobDtoFixture.CreateMany()]);
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).GetAsync<ScheduledJobDto[]>(ApiRoutes.ScheduledJobs.GET_SCHEDULED_JOBS, Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,69 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.Scheduling;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.GetSchedulerDisplayPreferences;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Scheduling;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Microsoft.AspNetCore.Http;
using NSubstitute;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Scheduler.GetSchedulerDisplayPreferences;
/// <summary>
/// Contains unit tests for the <see cref="GetSchedulerDisplayPreferencesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetSchedulerDisplayPreferencesEndpointTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly GetSchedulerDisplayPreferencesEndpoint _sut;
private readonly SchedulerDisplayPreferencesDtoFixture _schedulerDisplayPreferencesDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetSchedulerDisplayPreferencesEndpointTests"/> class.
/// </summary>
public GetSchedulerDisplayPreferencesEndpointTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
_sut = Factory.Create<GetSchedulerDisplayPreferencesEndpoint>(_mockApiHttpClient);
}
[Fact]
public async Task ExecuteAsync_WhenApiReturnsPreferences_ShouldReturnSuccessJsonWithDisplayPreferences()
{
// Arrange
SchedulerDisplayPreferencesDto expectedPreferences = _schedulerDisplayPreferencesDtoFixture.Create(displayTimeUnit: Lumina.Presentation.Web.Common.Enums.Scheduling.SchedulerDisplayTimeUnit.Minutes);
_mockApiHttpClient.GetAsync<SchedulerDisplayPreferencesDto>(ApiRoutes.ScheduledJobs.GET_DISPLAY_PREFERENCES, Arg.Any<CancellationToken>())
.Returns(expectedPreferences);
// Act
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
// Assert
using JsonDocument jsonDocument = JsonDocument.Parse(body);
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
Assert.Equal(expectedPreferences.UserId, jsonDocument.RootElement.GetProperty("data").GetProperty("userId").GetGuid());
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldRequestDisplayPreferencesFromApi()
{
// Arrange
_mockApiHttpClient.GetAsync<SchedulerDisplayPreferencesDto>(ApiRoutes.ScheduledJobs.GET_DISPLAY_PREFERENCES, Arg.Any<CancellationToken>())
.Returns(_schedulerDisplayPreferencesDtoFixture.Create());
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).GetAsync<SchedulerDisplayPreferencesDto>(ApiRoutes.ScheduledJobs.GET_DISPLAY_PREFERENCES, Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,54 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Requests.Scheduling;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.RemoveScheduledJob;
using Lumina.Presentation.Web.Fixtures.Common.Requests.Scheduling;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Microsoft.AspNetCore.Http;
using NSubstitute;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Scheduler.RemoveScheduledJob;
/// <summary>
/// Contains unit tests for the <see cref="RemoveScheduledJobEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RemoveScheduledJobEndpointTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly RemoveScheduledJobEndpoint _sut;
private readonly RemoveScheduledJobRequestFixture _removeScheduledJobRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="RemoveScheduledJobEndpointTests"/> class.
/// </summary>
public RemoveScheduledJobEndpointTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
_sut = Factory.Create<RemoveScheduledJobEndpoint>(_mockApiHttpClient);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldRemoveScheduledJobViaApiAndReturnSuccess()
{
// Arrange
RemoveScheduledJobRequest request = _removeScheduledJobRequestFixture.Create();
// Act
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
// Assert
string expectedEndpoint = ApiRoutes.ScheduledJobs.REMOVE_SCHEDULED_JOB.Replace("{scheduledJobId}", request.ScheduledJobId.ToString());
await _mockApiHttpClient.Received(1).DeleteAsync(expectedEndpoint, Arg.Any<CancellationToken>());
using JsonDocument jsonDocument = JsonDocument.Parse(body);
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
}
}
@@ -0,0 +1,140 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.Configuration;
using Lumina.Presentation.Web.Common.DTO.Themes;
using Lumina.Presentation.Web.Common.Http;
using Lumina.Presentation.Web.Common.Primitives;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Common.Services;
using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler;
using Lumina.Presentation.Web.Core.Themes;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Configuration;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Options;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Scheduler;
/// <summary>
/// Contains unit tests for the <see cref="SchedulerIndexViewEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SchedulerIndexViewEndpointTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly IAntiforgery _mockAntiforgery;
private readonly IOptionsSnapshot<ServerConfigurationDto> _mockServerConfigurationOptions;
private readonly IUrlService _mockUrlService;
private readonly ThemePageRenderer _mockThemePageRenderer;
private readonly IStringLocalizerFactory _mockStringLocalizerFactory;
private readonly IStringLocalizer _mockStringLocalizer;
private readonly SchedulerIndexViewEndpoint _sut;
private readonly ServerConfigurationDtoFixture _serverConfigurationDtoFixture = new();
private readonly ThemePageRenderResultDtoFixture _themePageRenderResultDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="SchedulerIndexViewEndpointTests"/> class.
/// </summary>
public SchedulerIndexViewEndpointTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
_mockAntiforgery = Substitute.For<IAntiforgery>();
_mockAntiforgery.GetAndStoreTokens(Arg.Any<HttpContext>())
.Returns(new AntiforgeryTokenSet("test-request-token", "test-cookie-token", "__RequestVerificationToken", "RequestVerificationToken"));
_mockServerConfigurationOptions = Substitute.For<IOptionsSnapshot<ServerConfigurationDto>>();
_mockServerConfigurationOptions.Value.Returns(_serverConfigurationDtoFixture.Create(baseAddress: "http://localhost", port: 5214));
_mockUrlService = Substitute.For<IUrlService>();
_mockThemePageRenderer = Substitute.For<ThemePageRenderer>(new ThemeService(_mockApiHttpClient), new ThemeTemplateEngine());
_mockStringLocalizer = Substitute.For<IStringLocalizer>();
_mockStringLocalizer[Arg.Any<string>()].Returns(callInfo => new LocalizedString(callInfo.Arg<string>(), callInfo.Arg<string>()));
_mockStringLocalizer.GetAllStrings(Arg.Any<bool>()).Returns(
[
new LocalizedString("ScheduledJobs", "Scheduled Jobs"),
new LocalizedString("TaskType.ScanMediaLibraries", "Scan media libraries"),
new LocalizedString("TaskType.CleanTemporaryFiles", "Clean temporary files"),
new LocalizedString("TaskType.RepairThemes", "Repair themes"),
new LocalizedString("TaskType.CleanScheduledJobExecutionHistory", "Clean execution history"),
new LocalizedString("Status.Added", "Added"),
new LocalizedString("Status.Active", "Active"),
new LocalizedString("Status.Running", "Running"),
new LocalizedString("Status.Completed", "Completed")
]);
_mockStringLocalizerFactory = Substitute.For<IStringLocalizerFactory>();
_mockStringLocalizerFactory.Create(Arg.Any<string>(), Arg.Any<string>()).Returns(_mockStringLocalizer);
_sut = Factory.Create<SchedulerIndexViewEndpoint>(_mockAntiforgery, _mockServerConfigurationOptions, _mockUrlService, _mockThemePageRenderer, _mockStringLocalizerFactory);
TestHttpContextFactory.ConfigureSession(_sut.HttpContext, TestHttpContextFactory.CreateSession());
_sut.HttpContext.Request.Path = "/en-us/admin/scheduled-jobs";
}
[Fact]
public async Task ExecuteAsync_WhenThemeRenderingSucceeds_ShouldRenderThemedPageThroughTheSharedView()
{
// Arrange
_mockUrlService.GetAbsoluteUrl(WebRoutes.Scheduler.GET_SCHEDULED_JOBS).Returns("http://localhost/en-us/admin/api-scheduled-jobs");
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_themePageRenderResultDtoFixture.Create(content: "<section>content</section>", script: "<script>script</script>")));
// Act
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
Assert.IsType<RazorViewResult>(result);
await _mockThemePageRenderer.Received(1).RenderAsync(
Arg.Is<ThemePageDto>(page =>
page.PageKey == "admin/scheduler" &&
page.Title == "ScheduledJobs" &&
string.Equals(page.PageData["scheduledJobsHubUrl"] as string, "http://localhost:5214/scheduledJobsHub", StringComparison.Ordinal) &&
string.Equals(page.PageData["jobsListUrl"] as string, "http://localhost/en-us/admin/api-scheduled-jobs", StringComparison.Ordinal) &&
string.Equals(page.PageData["antiforgeryToken"] as string, "test-request-token", StringComparison.Ordinal) &&
page.PageData.ContainsKey("strings")),
Arg.Is<string?>(requestedThemeId => requestedThemeId == null),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenThemeRenderingFails_ShouldFallBackToRazorView()
{
// Arrange
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(Result<ThemePageRenderResultDto>.Failure(Error.Failure("Theme.Render", "The page could not be rendered.")));
// Act
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
Assert.IsType<RazorViewResult>(result);
await _mockThemePageRenderer.Received(1).RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldStoreAntiforgeryTokenAndRequestSchedulerUrls()
{
// Arrange
_mockUrlService.GetAbsoluteUrl(WebRoutes.Scheduler.GET_DISPLAY_PREFERENCES).Returns("http://localhost/en-us/admin/api-scheduled-jobs/display-preferences");
_mockUrlService.GetAbsoluteUrl(WebRoutes.Scheduler.START_SCHEDULED_JOB, Arg.Any<object>()).Returns("http://localhost/en-us/admin/api-scheduled-jobs/00000000-0000-0000-0000-000000000000/start");
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_themePageRenderResultDtoFixture.Create()));
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
_mockAntiforgery.Received(1).GetAndStoreTokens(_sut.HttpContext);
await _mockThemePageRenderer.Received(1).RenderAsync(
Arg.Is<ThemePageDto>(page =>
string.Equals(page.PageData["getDisplayPreferencesUrl"] as string, "http://localhost/en-us/admin/api-scheduled-jobs/display-preferences", StringComparison.Ordinal) &&
string.Equals(page.PageData["startJobUrlTemplate"] as string, "http://localhost/en-us/admin/api-scheduled-jobs/00000000-0000-0000-0000-000000000000/start", StringComparison.Ordinal)),
Arg.Any<string?>(),
Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,57 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Requests.Scheduling;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.StartScheduledJob;
using Lumina.Presentation.Web.Fixtures.Common.Requests.Scheduling;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Microsoft.AspNetCore.Http;
using NSubstitute;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Scheduler.StartScheduledJob;
/// <summary>
/// Contains unit tests for the <see cref="StartScheduledJobEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class StartScheduledJobEndpointTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly StartScheduledJobEndpoint _sut;
private readonly StartScheduledJobRequestFixture _startScheduledJobRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="StartScheduledJobEndpointTests"/> class.
/// </summary>
public StartScheduledJobEndpointTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
_sut = Factory.Create<StartScheduledJobEndpoint>(_mockApiHttpClient);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldStartScheduledJobViaApiAndReturnSuccess()
{
// Arrange
StartScheduledJobRequest request = _startScheduledJobRequestFixture.Create();
// Act
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
// Assert
string expectedEndpoint = ApiRoutes.ScheduledJobs.START_SCHEDULED_JOB.Replace("{scheduledJobId}", request.ScheduledJobId.ToString());
await _mockApiHttpClient.Received(1).PutAsync<Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest, Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest>(
expectedEndpoint,
Arg.Any<Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
using JsonDocument jsonDocument = JsonDocument.Parse(body);
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
}
}
@@ -0,0 +1,57 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Requests.Scheduling;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.StopScheduledJob;
using Lumina.Presentation.Web.Fixtures.Common.Requests.Scheduling;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Microsoft.AspNetCore.Http;
using NSubstitute;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Scheduler.StopScheduledJob;
/// <summary>
/// Contains unit tests for the <see cref="StopScheduledJobEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class StopScheduledJobEndpointTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly StopScheduledJobEndpoint _sut;
private readonly StopScheduledJobRequestFixture _stopScheduledJobRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="StopScheduledJobEndpointTests"/> class.
/// </summary>
public StopScheduledJobEndpointTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
_sut = Factory.Create<StopScheduledJobEndpoint>(_mockApiHttpClient);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldStopScheduledJobViaApiAndReturnSuccess()
{
// Arrange
StopScheduledJobRequest request = _stopScheduledJobRequestFixture.Create();
// Act
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
// Assert
string expectedEndpoint = ApiRoutes.ScheduledJobs.STOP_SCHEDULED_JOB.Replace("{scheduledJobId}", request.ScheduledJobId.ToString());
await _mockApiHttpClient.Received(1).PutAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
expectedEndpoint,
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
using JsonDocument jsonDocument = JsonDocument.Parse(body);
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
}
}
@@ -0,0 +1,59 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Requests.Scheduling;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.UpdateSchedulerDisplayPreferences;
using Lumina.Presentation.Web.Fixtures.Common.Requests.Scheduling;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Microsoft.AspNetCore.Http;
using NSubstitute;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Scheduler.UpdateSchedulerDisplayPreferences;
/// <summary>
/// Contains unit tests for the <see cref="UpdateSchedulerDisplayPreferencesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateSchedulerDisplayPreferencesEndpointTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly UpdateSchedulerDisplayPreferencesEndpoint _sut;
private readonly UpdateSchedulerDisplayPreferencesRequestFixture _updateSchedulerDisplayPreferencesRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="UpdateSchedulerDisplayPreferencesEndpointTests"/> class.
/// </summary>
public UpdateSchedulerDisplayPreferencesEndpointTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
_sut = Factory.Create<UpdateSchedulerDisplayPreferencesEndpoint>(_mockApiHttpClient);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldUpdateDisplayPreferencesViaApiAndReturnSuccess()
{
// Arrange
UpdateSchedulerDisplayPreferencesRequest request = _updateSchedulerDisplayPreferencesRequestFixture.Create();
// Act
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
// Assert
await _mockApiHttpClient.Received(1).PutAsync<Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest, UpdateSchedulerDisplayPreferencesRequest>(
ApiRoutes.ScheduledJobs.UPDATE_DISPLAY_PREFERENCES,
Arg.Is<UpdateSchedulerDisplayPreferencesRequest>(forwardedRequest =>
forwardedRequest.JobTypeFilter == request.JobTypeFilter &&
forwardedRequest.DisplayTimeSpan == request.DisplayTimeSpan &&
forwardedRequest.DisplayTimeUnit == request.DisplayTimeUnit),
Arg.Any<CancellationToken>());
using JsonDocument jsonDocument = JsonDocument.Parse(body);
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
}
}