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

@@ -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);
}
}