From 315aed90f02edd77e9e8739ae74b374161d035df Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Sat, 5 Sep 2026 01:40:15 -0700 Subject: [PATCH] Completes the scheduler module coverage with a startup theme bootstrap and a stubbed cycle ticker --- .../Execution/IScheduledJobCycleTicker.cs | 32 + .../PeriodicScheduledJobCycleTicker.cs | 53 + .../Execution/ScheduledJobSchedulerJob.cs | 76 +- .../DTO/Scheduling/ScheduledJobDtoFixture.cs | 71 ++ .../ScheduledJobExecutionDtoFixture.cs | 58 + .../SchedulerDisplayPreferencesDtoFixture.cs | 51 + .../AddScheduledJobRequestFixture.cs | 57 + .../FireScheduledJobRequestFixture.cs | 39 + .../GetScheduledJobHistoryRequestFixture.cs | 42 + .../RemoveScheduledJobRequestFixture.cs | 39 + .../StartScheduledJobRequestFixture.cs | 39 + .../StopScheduledJobRequestFixture.cs | 39 + ...hedulerDisplayPreferencesRequestFixture.cs | 47 + .../ScheduledJobExecutionRepositoryTests.cs | 76 ++ .../Core/UoW/LuminaDbContextTests.cs | 5 +- .../AddScheduledJobEndpointTests.cs | 66 ++ .../FireScheduledJobEndpointTests.cs | 65 + .../GetScheduledJobHistoryEndpointTests.cs | 58 + .../GetScheduledJobsEndpointTests.cs | 58 + ...chedulerDisplayPreferencesEndpointTests.cs | 58 + .../RemoveScheduledJobEndpointTests.cs | 64 + .../SchedulerIndexViewEndpointTests.cs | 64 + .../StartScheduledJobEndpointTests.cs | 64 + .../StopScheduledJobEndpointTests.cs | 64 + ...chedulerDisplayPreferencesEndpointTests.cs | 63 + .../AddScheduledJobEndpointTests.cs | 85 ++ .../FireScheduledJobEndpointTests.cs | 85 ++ .../GetScheduledJobHistoryEndpointTests.cs | 87 ++ .../GetScheduledJobsEndpointTests.cs | 87 ++ ...chedulerDisplayPreferencesEndpointTests.cs | 87 ++ .../RemoveScheduledJobEndpointTests.cs | 85 ++ .../SchedulerIndexViewEndpointTests.cs | 80 ++ .../StartScheduledJobEndpointTests.cs | 85 ++ .../StopScheduledJobEndpointTests.cs | 85 ++ ...chedulerDisplayPreferencesEndpointTests.cs | 85 ++ .../SetupApplicationCommandHandlerTests.cs | 57 +- .../AddScheduledJobCommandHandlerTests.cs | 26 + .../RemoveScheduledJobCommandHandlerTests.cs | 43 + .../StartScheduledJobCommandHandlerTests.cs | 42 + .../StopScheduledJobCommandHandlerTests.cs | 58 + .../Scheduling/ScheduledJobRepositoryTests.cs | 29 + .../Core/Seed/DataSeedServiceTests.cs | 50 +- .../ScheduledJobRuntimeRegistryTests.cs | 95 ++ .../ScheduledJobSchedulerJobTests.cs | 1043 ++++++++++++++++- .../ScheduledTaskExecutorFactoryTests.cs | 33 + ...ledJobExecutionHistoryTaskExecutorTests.cs | 78 ++ .../MediaLibraryScanTaskExecutorTests.cs | 69 ++ .../RepairThemesTaskExecutorTests.cs | 119 ++ .../Core/Themes/ThemeSynchronizerTests.cs | 498 ++++++++ .../AddScheduledJobEndpointTests.cs | 86 ++ .../FireScheduledJobEndpointTests.cs | 57 + .../GetScheduledJobHistoryEndpointTests.cs | 126 ++ .../GetScheduledJobsEndpointTests.cs | 73 ++ ...chedulerDisplayPreferencesEndpointTests.cs | 69 ++ .../RemoveScheduledJobEndpointTests.cs | 54 + .../SchedulerIndexViewEndpointTests.cs | 140 +++ .../StartScheduledJobEndpointTests.cs | 57 + .../StopScheduledJobEndpointTests.cs | 57 + ...chedulerDisplayPreferencesEndpointTests.cs | 59 + 59 files changed, 5152 insertions(+), 65 deletions(-) create mode 100644 src/Lumina.Infrastructure/Core/Scheduling/Execution/IScheduledJobCycleTicker.cs create mode 100644 src/Lumina.Infrastructure/Core/Scheduling/Execution/PeriodicScheduledJobCycleTicker.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Scheduling/ScheduledJobDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Scheduling/ScheduledJobExecutionDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Scheduling/SchedulerDisplayPreferencesDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/AddScheduledJobRequestFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/FireScheduledJobRequestFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/GetScheduledJobHistoryRequestFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/RemoveScheduledJobRequestFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/StartScheduledJobRequestFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/StopScheduledJobRequestFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/UpdateSchedulerDisplayPreferencesRequestFixture.cs create mode 100644 tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Scheduling/ScheduledJobExecutionRepositoryTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/AddScheduledJob/AddScheduledJobEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobHistory/GetScheduledJobHistoryEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobs/GetScheduledJobsEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/RemoveScheduledJob/RemoveScheduledJobEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/SchedulerIndexViewEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/AddScheduledJob/AddScheduledJobEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobHistory/GetScheduledJobHistoryEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobs/GetScheduledJobsEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/RemoveScheduledJob/RemoveScheduledJobEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/SchedulerIndexViewEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/CleanScheduledJobExecutionHistoryTaskExecutorTests.cs create mode 100644 tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/RepairThemesTaskExecutorTests.cs create mode 100644 tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeSynchronizerTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/AddScheduledJob/AddScheduledJobEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobHistory/GetScheduledJobHistoryEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobs/GetScheduledJobsEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/RemoveScheduledJob/RemoveScheduledJobEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/SchedulerIndexViewEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpointTests.cs diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Execution/IScheduledJobCycleTicker.cs b/src/Lumina.Infrastructure/Core/Scheduling/Execution/IScheduledJobCycleTicker.cs new file mode 100644 index 00000000..b25a91a3 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/Scheduling/Execution/IScheduledJobCycleTicker.cs @@ -0,0 +1,32 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.Scheduling.Execution; + +/// +/// Represents a cancellable periodic ticker that drives the cadence of an execution cycle of a scheduled job. +/// +/// +/// The interface is separated from the periodic timer it wraps so that the unit tests of the cycle worker can drive +/// the cadence with a stubbed ticker, instead of waiting on the real periodic timer, whose periods start at one minute. +/// +internal interface IScheduledJobCycleTicker : IDisposable +{ + /// + /// Sets the period between the ticks of the ticker. + /// + /// + /// The period of a daily schedule is recalculated after every run from the current time, so it is assigned after each tick. + /// + TimeSpan Period { set; } + + /// + /// Waits until the next tick of the ticker, or until the ticker is disposed or is cancelled. + /// + /// Cancellation token that can be used to stop the wait. + /// when a tick occurred; when the ticker was disposed before the next tick. + ValueTask WaitForNextTickAsync(CancellationToken cancellationToken); +} diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Execution/PeriodicScheduledJobCycleTicker.cs b/src/Lumina.Infrastructure/Core/Scheduling/Execution/PeriodicScheduledJobCycleTicker.cs new file mode 100644 index 00000000..b7c788ff --- /dev/null +++ b/src/Lumina.Infrastructure/Core/Scheduling/Execution/PeriodicScheduledJobCycleTicker.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.Scheduling.Execution; + +/// +/// Default implementation that ticks on a . +/// +internal sealed class PeriodicScheduledJobCycleTicker : IScheduledJobCycleTicker +{ + private readonly PeriodicTimer _periodicTimer; + + /// + /// Initializes a new instance of the class. + /// + /// The period between the ticks of the ticker. + public PeriodicScheduledJobCycleTicker(TimeSpan period) + { + _periodicTimer = new PeriodicTimer(period); + } + + /// + /// Sets the period between the ticks of the ticker. + /// + public TimeSpan Period + { + set + { + _periodicTimer.Period = value; + } + } + + /// + /// Waits until the next tick of the ticker, or until the ticker is disposed or is cancelled. + /// + /// Cancellation token that can be used to stop the wait. + /// when a tick occurred; when the ticker was disposed before the next tick. + public ValueTask WaitForNextTickAsync(CancellationToken cancellationToken) + { + return _periodicTimer.WaitForNextTickAsync(cancellationToken); + } + + /// + /// Disposes the periodic timer owned by the ticker. + /// + public void Dispose() + { + _periodicTimer.Dispose(); + } +} diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledJobSchedulerJob.cs b/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledJobSchedulerJob.cs index 604c5213..15511ac3 100644 --- a/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledJobSchedulerJob.cs +++ b/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledJobSchedulerJob.cs @@ -2,6 +2,7 @@ using Lumina.Application.Common.DataAccess.Entities.Scheduling; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Infrastructure.Scheduling; +using Lumina.Application.Common.Infrastructure.Themes; using Lumina.Application.Common.Infrastructure.Time; using Lumina.Application.Common.Mapping.Scheduling; using Lumina.Application.Common.Utilities; @@ -10,11 +11,13 @@ using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate; using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using Lumina.Infrastructure.Core.Themes; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; +using System.Linq; using System.Threading; using System.Threading.Tasks; #endregion @@ -29,6 +32,7 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS private readonly IServiceScopeFactory _serviceScopeFactory; private readonly IScheduledJobRuntimeRegistry _runtimeRegistry; private readonly ILogger _logger; + private readonly Func _cycleTickerFactory; /// /// Initializes a new instance of the class. @@ -37,10 +41,23 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS /// Injected service for logging. /// Injected factory used for creating scopes in which services are requested. public ScheduledJobSchedulerJob(IScheduledJobRuntimeRegistry runtimeRegistry, ILogger logger, IServiceScopeFactory serviceScopeFactory) + : this(runtimeRegistry, logger, serviceScopeFactory, period => new PeriodicScheduledJobCycleTicker(period)) + { + } + + /// + /// Initializes a new instance of the class with a custom cycle ticker factory. + /// + /// Injected registry that holds the live runtime state of the scheduled jobs. + /// Injected service for logging. + /// Injected factory used for creating scopes in which services are requested. + /// Factory that creates the ticker driving the cadence of an execution cycle, for which the unit tests substitute a stubbed ticker. + internal ScheduledJobSchedulerJob(IScheduledJobRuntimeRegistry runtimeRegistry, ILogger logger, IServiceScopeFactory serviceScopeFactory, Func cycleTickerFactory) { _serviceScopeFactory = serviceScopeFactory; _runtimeRegistry = runtimeRegistry; _logger = logger; + _cycleTickerFactory = cycleTickerFactory; } /// @@ -85,6 +102,7 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS /// Cancellation token that can be used to stop the execution. protected override async Task ExecuteAsync(CancellationToken stoppingToken) { + await SynchronizeBundledThemesIfNeededAsync(stoppingToken).ConfigureAwait(false); await ResumeActiveCyclesAsync(stoppingToken).ConfigureAwait(false); try { @@ -93,6 +111,43 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS catch (OperationCanceledException) { } } + /// + /// Installs and repairs the bundled themes at startup, but only when no active "Repair themes at startup" scheduled job will do it. + /// + /// Cancellation token that can be used to stop the execution. + /// + /// The default "Repair themes at startup" job is the single owner of the theme synchronization once the default jobs are + /// seeded during the application setup. Until then, for example on a fresh installation before the administrator account is + /// created, no scheduled job exists yet, so the themes are synchronized here, otherwise the pages of the setup flow would + /// have no theme to render and a hosted test host would have no bundled themes installed. + /// + private async Task SynchronizeBundledThemesIfNeededAsync(CancellationToken cancellationToken) + { + try + { + await using AsyncServiceScope scope = _serviceScopeFactory.CreateAsyncScope(); + IUnitOfWork unitOfWork = scope.ServiceProvider.GetRequiredService(); + Result> getScheduledJobsResult = await unitOfWork.ScheduledJobRepository.GetActiveOrRunningAsync(cancellationToken).ConfigureAwait(false); + if (getScheduledJobsResult.IsFailure) + { + _logger.LogWarning("Failed to read the scheduled jobs to decide whether the themes must be synchronized: {Error}", getScheduledJobsResult.FirstError.Description); + return; + } + // When an active "Repair themes at startup" job exists, its cycle is resumed below and it runs the synchronization. + if (getScheduledJobsResult.Value.Any(scheduledJob => scheduledJob.TaskType == ScheduledTaskType.RepairThemes)) + return; + + IThemeService themeService = scope.ServiceProvider.GetRequiredService(); + await ThemeSynchronizer.SynchronizeAsync(themeService, unitOfWork, _logger, cancellationToken).ConfigureAwait(false); + } + catch (OperationCanceledException) { } + catch (Exception exception) + { + // Synchronizing the themes at startup is best effort, so a failure here must never stop the scheduler. + _logger.LogWarning(exception, "Failed to synchronize the bundled themes at startup."); + } + } + /// /// Resumes the execution cycles of the scheduled jobs whose cycle was active when the application shut down. /// @@ -162,23 +217,24 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS return; TimeSpan delay = await CalculateDelayAsync(schedule).ConfigureAwait(false); - // The periodic timer owns the cadence of the cycle: an interval schedule ticks every interval, and a daily - // schedule ticks after the delay until the next daily hour and minute. - using PeriodicTimer timer = new(delay); - // Each iteration waits for the next tick, runs the task and loops; a cancelled token or a disposed timer makes WaitForNextTickAsync exit, - // which ends the cycle through the finally block below. - while (await timer.WaitForNextTickAsync(cycleToken).ConfigureAwait(false)) + // The ticker owns the cadence of the cycle: an interval schedule ticks every interval, and a daily schedule ticks + // after the delay until the next daily hour and minute. The default ticker wraps a periodic timer, which does not + // queue missed ticks, so a run that outlasts its period drops the missed ticks instead of piling them up. + using IScheduledJobCycleTicker cycleTicker = _cycleTickerFactory(delay); + // Each iteration waits for the next tick, runs the task and loops; a cancelled token or a disposed ticker makes + // WaitForNextTickAsync exit, which ends the cycle through the finally block below. + while (await cycleTicker.WaitForNextTickAsync(cycleToken).ConfigureAwait(false)) { if (cycleToken.IsCancellationRequested) return; - // The run is awaited inside the tick and the periodic timer does not queue missed ticks, so a task that - // outlasts its interval drops the missed ticks instead of piling them up; the run slot acquired inside - // RunScheduledJobAsync is the second guard against overlapping executions. + // The run is awaited inside the tick and missed ticks are not queued, so a task that outlasts its interval + // drops the missed ticks instead of piling them up; the run slot acquired inside RunScheduledJobAsync is the + // second guard against overlapping executions. await RunScheduledJobAsync(scheduledJobId, isCycleRun: true, cycleToken).ConfigureAwait(false); // A daily schedule needs its delay recalculated after every run from the current time, so the next run // happens at the next day's hour and minute, also across daylight saving time changes. if (schedule.ScheduleType == ScheduleType.DailyAtHourAndMinute) - timer.Period = await CalculateDelayAsync(schedule).ConfigureAwait(false); + cycleTicker.Period = await CalculateDelayAsync(schedule).ConfigureAwait(false); } } catch (OperationCanceledException) diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Scheduling/ScheduledJobDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Scheduling/ScheduledJobDtoFixture.cs new file mode 100644 index 00000000..a9b88f9f --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Scheduling/ScheduledJobDtoFixture.cs @@ -0,0 +1,71 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Scheduling; +using Lumina.Presentation.Web.Common.Enums.Scheduling; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Scheduling; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class ScheduledJobDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional unique identifier of the scheduled job. + /// Optional name of the scheduled job. + /// Optional type of the task executed by the scheduled job. + /// Optional type of the schedule of the scheduled job. + /// Optional interval in minutes of the schedule of the scheduled job. + /// Optional hour of the schedule of the scheduled job. + /// Optional minute of the schedule of the scheduled job. + /// Optional status of the scheduled job. + /// Optional date and time when the task of the scheduled job last started its execution. + /// Optional date and time when the task of the scheduled job last completed its execution. + /// A configured instance. + public ScheduledJobDto Create( + Guid? id = null, + string? name = null, + ScheduledTaskType? taskType = null, + ScheduleType? scheduleType = null, + int? intervalMinutes = null, + int? hour = null, + int? minute = null, + ScheduledJobStatus? status = null, + DateTime? lastStartedOnUtc = null, + DateTime? lastCompletedOnUtc = null) + { + ScheduleType resolvedScheduleType = scheduleType ?? _faker.PickRandom(); + DateTime? resolvedLastCompletedOnUtc = lastCompletedOnUtc ?? _faker.Date.Recent(10); + return new ScheduledJobDto( + Id: id ?? Guid.NewGuid(), + Name: name ?? _faker.Name.JobTitle(), + TaskType: taskType ?? _faker.PickRandom(), + ScheduleType: resolvedScheduleType, + IntervalMinutes: intervalMinutes ?? (resolvedScheduleType == ScheduleType.WithIntervalInMinutes ? _faker.Random.Int(1, 1440) : null), + Hour: hour ?? (resolvedScheduleType == ScheduleType.DailyAtHourAndMinute ? _faker.Random.Int(0, 23) : null), + Minute: minute ?? (resolvedScheduleType == ScheduleType.DailyAtHourAndMinute ? _faker.Random.Int(0, 59) : null), + Status: status ?? _faker.PickRandom(), + LastStartedOnUtc: lastStartedOnUtc ?? _faker.Date.Recent(10), + LastCompletedOnUtc: resolvedLastCompletedOnUtc); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Scheduling/ScheduledJobExecutionDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Scheduling/ScheduledJobExecutionDtoFixture.cs new file mode 100644 index 00000000..621619c2 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Scheduling/ScheduledJobExecutionDtoFixture.cs @@ -0,0 +1,58 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Scheduling; +using Lumina.Presentation.Web.Common.Enums.Scheduling; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Scheduling; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class ScheduledJobExecutionDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional unique identifier of the execution. + /// Optional unique identifier of the scheduled job whose task was executed. + /// Optional type of the task that was executed. + /// Optional value indicating whether the execution was triggered by the execution cycle of the scheduled job. + /// Optional date and time when the execution started. + /// Optional date and time when the execution completed. + /// A configured instance. + public ScheduledJobExecutionDto Create( + Guid? id = null, + Guid? scheduledJobId = null, + ScheduledTaskType? taskType = null, + bool? isCycleRun = null, + DateTime? startedOnUtc = null, + DateTime? completedOnUtc = null) + { + DateTime resolvedStartedOnUtc = startedOnUtc ?? _faker.Date.Recent(10); + return new ScheduledJobExecutionDto( + Id: id ?? Guid.NewGuid(), + ScheduledJobId: scheduledJobId ?? Guid.NewGuid(), + TaskType: taskType ?? _faker.PickRandom(), + IsCycleRun: isCycleRun ?? _faker.Random.Bool(), + StartedOnUtc: resolvedStartedOnUtc, + CompletedOnUtc: completedOnUtc ?? _faker.Date.Soon(1, resolvedStartedOnUtc)); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Scheduling/SchedulerDisplayPreferencesDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Scheduling/SchedulerDisplayPreferencesDtoFixture.cs new file mode 100644 index 00000000..103b48f2 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Scheduling/SchedulerDisplayPreferencesDtoFixture.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Scheduling; +using Lumina.Presentation.Web.Common.Enums.Scheduling; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Scheduling; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class SchedulerDisplayPreferencesDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional unique identifier of the user that owns the display preferences. + /// Optional type of the scheduled job tasks whose executions are shown on the scheduler page. + /// Optional time span, expressed in , that the scheduler page shows. + /// Optional unit in which the displayed time span of the scheduler page is expressed. + /// A configured instance. + public SchedulerDisplayPreferencesDto Create( + Guid? userId = null, + ScheduledTaskType? jobTypeFilter = null, + int? displayTimeSpan = null, + SchedulerDisplayTimeUnit? displayTimeUnit = null) + { + return new SchedulerDisplayPreferencesDto( + UserId: userId ?? Guid.NewGuid(), + JobTypeFilter: jobTypeFilter, + DisplayTimeSpan: displayTimeSpan ?? _faker.Random.Int(1, 30), + DisplayTimeUnit: displayTimeUnit ?? _faker.PickRandom()); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/AddScheduledJobRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/AddScheduledJobRequestFixture.cs new file mode 100644 index 00000000..19c3d29c --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/AddScheduledJobRequestFixture.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.Enums.Scheduling; +using Lumina.Presentation.Web.Common.Requests.Scheduling; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Scheduling; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class AddScheduledJobRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional name of the scheduled job. + /// Optional type of the task executed by the scheduled job. + /// Optional type of the schedule of the scheduled job. + /// Optional interval in minutes of the schedule, when the schedule type is . + /// Optional hour of the schedule, when the schedule type is . + /// Optional minute of the schedule, when the schedule type is . + /// A configured instance. + public AddScheduledJobRequest Create( + string? name = null, + ScheduledTaskType? taskType = null, + ScheduleType? scheduleType = null, + int? intervalMinutes = null, + int? hour = null, + int? minute = null) + { + ScheduleType resolvedScheduleType = scheduleType ?? _faker.PickRandom(); + return new AddScheduledJobRequest( + Name: name ?? _faker.Name.JobTitle(), + TaskType: taskType ?? _faker.PickRandom(), + ScheduleType: resolvedScheduleType, + IntervalMinutes: intervalMinutes ?? (resolvedScheduleType == ScheduleType.WithIntervalInMinutes ? _faker.Random.Int(1, 1440) : null), + Hour: hour ?? (resolvedScheduleType == ScheduleType.DailyAtHourAndMinute ? _faker.Random.Int(0, 23) : null), + Minute: minute ?? (resolvedScheduleType == ScheduleType.DailyAtHourAndMinute ? _faker.Random.Int(0, 59) : null)); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/FireScheduledJobRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/FireScheduledJobRequestFixture.cs new file mode 100644 index 00000000..04c48d00 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/FireScheduledJobRequestFixture.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Scheduling; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Scheduling; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class FireScheduledJobRequestFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional unique identifier of the scheduled job whose task is fired. + /// A configured instance. + public FireScheduledJobRequest Create( + Guid? scheduledJobId = null) + { + return new FireScheduledJobRequest( + ScheduledJobId: scheduledJobId ?? Guid.NewGuid() + ); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/GetScheduledJobHistoryRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/GetScheduledJobHistoryRequestFixture.cs new file mode 100644 index 00000000..aa730ea8 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/GetScheduledJobHistoryRequestFixture.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Scheduling; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Scheduling; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class GetScheduledJobHistoryRequestFixture +{ + /// + /// Creates a new instance. + /// + /// Optional inclusive lower bound of the interval for which the history is requested. + /// Optional inclusive upper bound of the interval for which the history is requested. + /// A configured instance. + public GetScheduledJobHistoryRequest Create( + DateTime? from = null, + DateTime? to = null) + { + return new GetScheduledJobHistoryRequest( + From: from, + To: to + ); + } + + /// + /// Creates multiple instances. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/RemoveScheduledJobRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/RemoveScheduledJobRequestFixture.cs new file mode 100644 index 00000000..08ce2872 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/RemoveScheduledJobRequestFixture.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Scheduling; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Scheduling; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class RemoveScheduledJobRequestFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional unique identifier of the scheduled job to remove. + /// A configured instance. + public RemoveScheduledJobRequest Create( + Guid? scheduledJobId = null) + { + return new RemoveScheduledJobRequest( + ScheduledJobId: scheduledJobId ?? Guid.NewGuid() + ); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/StartScheduledJobRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/StartScheduledJobRequestFixture.cs new file mode 100644 index 00000000..486a4903 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/StartScheduledJobRequestFixture.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Scheduling; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Scheduling; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class StartScheduledJobRequestFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional unique identifier of the scheduled job whose execution cycle is started. + /// A configured instance. + public StartScheduledJobRequest Create( + Guid? scheduledJobId = null) + { + return new StartScheduledJobRequest( + ScheduledJobId: scheduledJobId ?? Guid.NewGuid() + ); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/StopScheduledJobRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/StopScheduledJobRequestFixture.cs new file mode 100644 index 00000000..d61b4452 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/StopScheduledJobRequestFixture.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Scheduling; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Scheduling; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class StopScheduledJobRequestFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional unique identifier of the scheduled job whose execution cycle is stopped. + /// A configured instance. + public StopScheduledJobRequest Create( + Guid? scheduledJobId = null) + { + return new StopScheduledJobRequest( + ScheduledJobId: scheduledJobId ?? Guid.NewGuid() + ); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/UpdateSchedulerDisplayPreferencesRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/UpdateSchedulerDisplayPreferencesRequestFixture.cs new file mode 100644 index 00000000..1d162c96 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Scheduling/UpdateSchedulerDisplayPreferencesRequestFixture.cs @@ -0,0 +1,47 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.Enums.Scheduling; +using Lumina.Presentation.Web.Common.Requests.Scheduling; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Scheduling; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class UpdateSchedulerDisplayPreferencesRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional type of the scheduled job tasks whose executions are shown on the scheduler page. + /// Optional time span, expressed in , that the scheduler page shows. + /// Optional unit in which the displayed time span of the scheduler page is expressed. + /// A configured instance. + public UpdateSchedulerDisplayPreferencesRequest Create( + ScheduledTaskType? jobTypeFilter = null, + int? displayTimeSpan = null, + SchedulerDisplayTimeUnit? displayTimeUnit = null) + { + return new UpdateSchedulerDisplayPreferencesRequest( + JobTypeFilter: jobTypeFilter, + DisplayTimeSpan: displayTimeSpan ?? _faker.Random.Int(1, 30), + DisplayTimeUnit: displayTimeUnit ?? _faker.PickRandom()); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Scheduling/ScheduledJobExecutionRepositoryTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Scheduling/ScheduledJobExecutionRepositoryTests.cs new file mode 100644 index 00000000..d6fe1702 --- /dev/null +++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Scheduling/ScheduledJobExecutionRepositoryTests.cs @@ -0,0 +1,76 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling; +using Lumina.DataAccess.Core.Repositories.Scheduling; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Primitives; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.DataAccess.IntegrationTests.Core.Repositories.Scheduling; + +/// +/// Contains integration tests for the class, exercising it against a real SQLite database. +/// +[ExcludeFromCodeCoverage] +public class ScheduledJobExecutionRepositoryTests +{ + private readonly ScheduledJobExecutionEntityFixture _scheduledJobExecutionEntityFixture = new(); + + [Fact] + public async Task DeleteOlderThanAsync_WhenExecutionsStartedBeforeTheCutoff_ShouldDeleteOnlyThem() + { + // Arrange + // The deletion uses ExecuteDeleteAsync, which is not supported by the in-memory provider, so a real SQLite database is used. + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-scheduledjobexecutionrepo-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + ScheduledJobExecutionRepository sut = new(context); + + DateTime cutoffUtc = DateTime.UtcNow.AddMonths(-1); + ScheduledJobExecutionEntity olderExecution = _scheduledJobExecutionEntityFixture.Create(startedOnUtc: cutoffUtc.AddDays(-30)); + ScheduledJobExecutionEntity recentExecution = _scheduledJobExecutionEntityFixture.Create(startedOnUtc: cutoffUtc.AddDays(1)); + context.ScheduledJobExecutions.AddRange(olderExecution, recentExecution); + await context.SaveChangesAsync(); + + // Act + Result result = await sut.DeleteOlderThanAsync(cutoffUtc, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + int remainingCount = await context.ScheduledJobExecutions.CountAsync(); + Assert.Equal(1, remainingCount); + Assert.Null(await context.ScheduledJobExecutions.FirstOrDefaultAsync(execution => execution.Id == olderExecution.Id)); + Assert.NotNull(await context.ScheduledJobExecutions.FirstOrDefaultAsync(execution => execution.Id == recentExecution.Id)); + } + + [Fact] + public async Task DeleteOlderThanAsync_WhenNoExecutionStartedBeforeTheCutoff_ShouldNotDeleteAnything() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-scheduledjobexecutionrepo-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + ScheduledJobExecutionRepository sut = new(context); + + DateTime cutoffUtc = DateTime.UtcNow.AddMonths(-1); + ScheduledJobExecutionEntity recentExecution = _scheduledJobExecutionEntityFixture.Create(startedOnUtc: cutoffUtc.AddDays(1)); + context.ScheduledJobExecutions.Add(recentExecution); + await context.SaveChangesAsync(); + + // Act + Result result = await sut.DeleteOlderThanAsync(cutoffUtc, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(1, await context.ScheduledJobExecutions.CountAsync()); + } +} diff --git a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/UoW/LuminaDbContextTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/UoW/LuminaDbContextTests.cs index ffec9027..52e5e233 100644 --- a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/UoW/LuminaDbContextTests.cs +++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/UoW/LuminaDbContextTests.cs @@ -47,7 +47,7 @@ public class LuminaDbContextTests : IDisposable // Assert // The count assertion fails when a table is added or removed, reminding to update the assertions below. - Assert.Equal(29, tableNames.Length); + Assert.Equal(32, tableNames.Length); Assert.Contains("Books", tableNames); Assert.Contains("Users", tableNames); Assert.Contains("UserSettings", tableNames); @@ -77,6 +77,9 @@ public class LuminaDbContextTests : IDisposable Assert.Contains("MediaContributors", tableNames); Assert.Contains("BookContributors", tableNames); Assert.Contains("BookArtwork", tableNames); + Assert.Contains("ScheduledJobs", tableNames); + Assert.Contains("ScheduledJobExecutions", tableNames); + Assert.Contains("SchedulerDisplayPreferences", tableNames); } [Fact] diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/AddScheduledJob/AddScheduledJobEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/AddScheduledJob/AddScheduledJobEndpointTests.cs new file mode 100644 index 00000000..bef4e989 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/AddScheduledJob/AddScheduledJobEndpointTests.cs @@ -0,0 +1,66 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Scheduling; +using Lumina.Presentation.Web.Common.Requests.Scheduling; +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 Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Scheduler.AddScheduledJob; + +/// +/// Contains integration tests for the /{culture}/admin/api-scheduled-jobs/add route served by the class. +/// +[ExcludeFromCodeCoverage] +public class AddScheduledJobEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly AddScheduledJobRequestFixture _addScheduledJobRequestFixture = new(); + private readonly ScheduledJobDtoFixture _scheduledJobDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public AddScheduledJobEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task AddScheduledJob_WhenCalledByAuthenticatedAdminWithAntiforgeryToken_ShouldAddScheduledJobAndReturnSuccess() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AddScheduledJobRequest request = _addScheduledJobRequestFixture.Create(); + _apiFactory.ApiClientStub.RegisterPostResponse("scheduled-jobs", _scheduledJobDtoFixture.Create(name: request.Name)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage addRequest = new(HttpMethod.Post, "/en-us/admin/api-scheduled-jobs/add") + { + Content = JsonContent.Create(request) + }; + addRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + addRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + addRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(addRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Contains(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "scheduled-jobs"); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpointTests.cs new file mode 100644 index 00000000..5e47ba56 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpointTests.cs @@ -0,0 +1,65 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Scheduling; +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 Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Scheduler.FireScheduledJob; + +/// +/// Contains integration tests for the /{culture}/admin/api-scheduled-jobs/{scheduledJobId}/fire route served by the class. +/// +[ExcludeFromCodeCoverage] +public class FireScheduledJobEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly FireScheduledJobRequestFixture _fireScheduledJobRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public FireScheduledJobEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task FireScheduledJob_WhenCalledByAuthenticatedAdminWithAntiforgeryToken_ShouldFireScheduledJobAndReturnSuccess() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + FireScheduledJobRequest request = _fireScheduledJobRequestFixture.Create(); + string expectedEndpoint = $"scheduled-jobs/{request.ScheduledJobId}/fire"; + _apiFactory.ApiClientStub.RegisterPutResponseFactory(expectedEndpoint, _ => new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage fireRequest = new(HttpMethod.Put, $"/en-us/admin/api-scheduled-jobs/{request.ScheduledJobId}/fire") + { + Content = JsonContent.Create(new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()) + }; + fireRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + fireRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + fireRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(fireRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == expectedEndpoint); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobHistory/GetScheduledJobHistoryEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobHistory/GetScheduledJobHistoryEndpointTests.cs new file mode 100644 index 00000000..694a0d6b --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobHistory/GetScheduledJobHistoryEndpointTests.cs @@ -0,0 +1,58 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Scheduling; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.GetScheduledJobHistory; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Scheduling; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Scheduler.GetScheduledJobHistory; + +/// +/// Contains integration tests for the /{culture}/admin/api-scheduled-jobs/history route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetScheduledJobHistoryEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly ScheduledJobExecutionDtoFixture _scheduledJobExecutionDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetScheduledJobHistoryEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetScheduledJobHistory_WhenCalledByAuthenticatedAdmin_ShouldReturnExecutionHistoryFromApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + ScheduledJobExecutionDto[] expectedExecutions = [.. _scheduledJobExecutionDtoFixture.CreateMany(2)]; + _apiFactory.ApiClientStub.RegisterGetResponse("scheduled-jobs/history", expectedExecutions); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/admin/api-scheduled-jobs/history"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal(expectedExecutions.Length, json.RootElement.GetProperty("data").GetArrayLength()); + Assert.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == "scheduled-jobs/history"); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobs/GetScheduledJobsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobs/GetScheduledJobsEndpointTests.cs new file mode 100644 index 00000000..591527c7 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobs/GetScheduledJobsEndpointTests.cs @@ -0,0 +1,58 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Scheduling; +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 Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Scheduler.GetScheduledJobs; + +/// +/// Contains integration tests for the /{culture}/admin/api-scheduled-jobs route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetScheduledJobsEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly ScheduledJobDtoFixture _scheduledJobDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetScheduledJobsEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetScheduledJobs_WhenCalledByAuthenticatedAdmin_ShouldReturnScheduledJobsFromApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + ScheduledJobDto[] expectedJobs = [.. _scheduledJobDtoFixture.CreateMany(2)]; + _apiFactory.ApiClientStub.RegisterGetResponse("scheduled-jobs", expectedJobs); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/admin/api-scheduled-jobs"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal(expectedJobs.Length, json.RootElement.GetProperty("data").GetArrayLength()); + Assert.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == "scheduled-jobs"); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesEndpointTests.cs new file mode 100644 index 00000000..eff20ef2 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesEndpointTests.cs @@ -0,0 +1,58 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Scheduling; +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 Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Scheduler.GetSchedulerDisplayPreferences; + +/// +/// Contains integration tests for the /{culture}/admin/api-scheduled-jobs/display-preferences route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetSchedulerDisplayPreferencesEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly SchedulerDisplayPreferencesDtoFixture _schedulerDisplayPreferencesDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetSchedulerDisplayPreferencesEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetSchedulerDisplayPreferences_WhenCalledByAuthenticatedAdmin_ShouldReturnDisplayPreferencesFromApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + SchedulerDisplayPreferencesDto expectedPreferences = _schedulerDisplayPreferencesDtoFixture.Create(); + _apiFactory.ApiClientStub.RegisterGetResponse("scheduled-jobs/display-preferences", expectedPreferences); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/admin/api-scheduled-jobs/display-preferences"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal(expectedPreferences.UserId, json.RootElement.GetProperty("data").GetProperty("userId").GetGuid()); + Assert.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == "scheduled-jobs/display-preferences"); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/RemoveScheduledJob/RemoveScheduledJobEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/RemoveScheduledJob/RemoveScheduledJobEndpointTests.cs new file mode 100644 index 00000000..7a71b990 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/RemoveScheduledJob/RemoveScheduledJobEndpointTests.cs @@ -0,0 +1,64 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Scheduling; +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 Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Scheduler.RemoveScheduledJob; + +/// +/// Contains integration tests for the /{culture}/admin/api-scheduled-jobs/{scheduledJobId} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class RemoveScheduledJobEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly RemoveScheduledJobRequestFixture _removeScheduledJobRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public RemoveScheduledJobEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task RemoveScheduledJob_WhenCalledByAuthenticatedAdminWithAntiforgeryToken_ShouldRemoveScheduledJobAndReturnSuccess() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + RemoveScheduledJobRequest request = _removeScheduledJobRequestFixture.Create(); + string expectedEndpoint = $"scheduled-jobs/{request.ScheduledJobId}"; + _apiFactory.ApiClientStub.RegisterDeleteSuccess(expectedEndpoint); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage removeRequest = new(HttpMethod.Delete, $"/en-us/admin/api-scheduled-jobs/{request.ScheduledJobId}") + { + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + removeRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + removeRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + removeRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(removeRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Contains(_apiFactory.ApiClientStub.DeleteEndpointsCalled, endpoint => endpoint == expectedEndpoint); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/SchedulerIndexViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/SchedulerIndexViewEndpointTests.cs new file mode 100644 index 00000000..ce0d355c --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/SchedulerIndexViewEndpointTests.cs @@ -0,0 +1,64 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler; +using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Scheduler; + +/// +/// Contains integration tests for the /{culture}/admin/scheduled-jobs route served by the class. +/// +[ExcludeFromCodeCoverage] +public class SchedulerIndexViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public SchedulerIndexViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task SchedulerIndex_WhenCalledByAuthenticatedAdmin_ShouldRenderSchedulerPage() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/scheduled-jobs"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + } + + [Fact] + public async Task SchedulerIndex_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/scheduled-jobs"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpointTests.cs new file mode 100644 index 00000000..1d4da095 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpointTests.cs @@ -0,0 +1,64 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Scheduling; +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 Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Scheduler.StartScheduledJob; + +/// +/// Contains integration tests for the /{culture}/admin/api-scheduled-jobs/{scheduledJobId}/start route served by the class. +/// +[ExcludeFromCodeCoverage] +public class StartScheduledJobEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly StartScheduledJobRequestFixture _startScheduledJobRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public StartScheduledJobEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task StartScheduledJob_WhenCalledByAuthenticatedAdminWithAntiforgeryToken_ShouldStartScheduledJobAndReturnSuccess() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + StartScheduledJobRequest request = _startScheduledJobRequestFixture.Create(); + string expectedEndpoint = $"scheduled-jobs/{request.ScheduledJobId}/start"; + _apiFactory.ApiClientStub.RegisterPutResponseFactory(expectedEndpoint, _ => new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage startRequest = new(HttpMethod.Put, $"/en-us/admin/api-scheduled-jobs/{request.ScheduledJobId}/start") + { + Content = JsonContent.Create(new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()) + }; + startRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + startRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + startRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(startRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == expectedEndpoint); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpointTests.cs new file mode 100644 index 00000000..c8f04969 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpointTests.cs @@ -0,0 +1,64 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Scheduling; +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 Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Scheduler.StopScheduledJob; + +/// +/// Contains integration tests for the /{culture}/admin/api-scheduled-jobs/{scheduledJobId}/stop route served by the class. +/// +[ExcludeFromCodeCoverage] +public class StopScheduledJobEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly StopScheduledJobRequestFixture _stopScheduledJobRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public StopScheduledJobEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task StopScheduledJob_WhenCalledByAuthenticatedAdminWithAntiforgeryToken_ShouldStopScheduledJobAndReturnSuccess() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + StopScheduledJobRequest request = _stopScheduledJobRequestFixture.Create(); + string expectedEndpoint = $"scheduled-jobs/{request.ScheduledJobId}/stop"; + _apiFactory.ApiClientStub.RegisterPutResponseFactory(expectedEndpoint, _ => new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage stopRequest = new(HttpMethod.Put, $"/en-us/admin/api-scheduled-jobs/{request.ScheduledJobId}/stop") + { + Content = JsonContent.Create(new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()) + }; + stopRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + stopRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + stopRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(stopRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == expectedEndpoint); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpointTests.cs new file mode 100644 index 00000000..1e1d5757 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpointTests.cs @@ -0,0 +1,63 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Scheduling; +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 Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Scheduler.UpdateSchedulerDisplayPreferences; + +/// +/// Contains integration tests for the /{culture}/admin/api-scheduled-jobs/display-preferences route served by the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateSchedulerDisplayPreferencesEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly UpdateSchedulerDisplayPreferencesRequestFixture _updateSchedulerDisplayPreferencesRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public UpdateSchedulerDisplayPreferencesEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task UpdateSchedulerDisplayPreferences_WhenCalledByAuthenticatedAdminWithAntiforgeryToken_ShouldUpdateDisplayPreferencesAndReturnSuccess() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + UpdateSchedulerDisplayPreferencesRequest request = _updateSchedulerDisplayPreferencesRequestFixture.Create(); + _apiFactory.ApiClientStub.RegisterPutResponseFactory("scheduled-jobs/display-preferences", _ => new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/admin/api-scheduled-jobs/display-preferences") + { + Content = JsonContent.Create(request) + }; + updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + updateRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == "scheduled-jobs/display-preferences"); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/AddScheduledJob/AddScheduledJobEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/AddScheduledJob/AddScheduledJobEndpointTests.cs new file mode 100644 index 00000000..1cc4b2f0 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/AddScheduledJob/AddScheduledJobEndpointTests.cs @@ -0,0 +1,85 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Scheduler.AddScheduledJob; + +/// +/// Contains security tests for the /{culture}/admin/api-scheduled-jobs/add route served by the class. +/// +[ExcludeFromCodeCoverage] +public class AddScheduledJobEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public AddScheduledJobEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task AddScheduledJob_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + string url = "/en-us/admin/api-scheduled-jobs/add"; + HttpRequestMessage request = new(HttpMethod.Post, url) + { + Content = CreateJsonContent() + }; + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(request); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint.StartsWith("scheduled-jobs", StringComparison.Ordinal)); + } + + [Fact] + public async Task AddScheduledJob_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + string url = "/en-us/admin/api-scheduled-jobs/add"; + HttpRequestMessage request = new(HttpMethod.Post, url) + { + Content = CreateJsonContent() + }; + request.Headers.Add("RequestVerificationToken", antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(request); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint.StartsWith("scheduled-jobs", StringComparison.Ordinal)); + } + + /// + /// Creates the empty JSON body of the request; the content type is set without the charset suffix, because the antiforgery middleware matches the content type exactly. + /// + /// The created content. + private static StringContent CreateJsonContent() + { + StringContent content = new("{}", Encoding.UTF8, "application/json"); + content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + return content; + } +} \ No newline at end of file diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpointTests.cs new file mode 100644 index 00000000..9a81a979 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpointTests.cs @@ -0,0 +1,85 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Scheduler.FireScheduledJob; + +/// +/// Contains security tests for the /{culture}/admin/api-scheduled-jobs/{scheduledJobId}/fire route served by the class. +/// +[ExcludeFromCodeCoverage] +public class FireScheduledJobEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public FireScheduledJobEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task FireScheduledJob_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + string url = $"/en-us/admin/api-scheduled-jobs/{Guid.NewGuid()}/fire"; + HttpRequestMessage request = new(HttpMethod.Put, url) + { + Content = CreateJsonContent() + }; + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(request); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint.StartsWith("scheduled-jobs", StringComparison.Ordinal)); + } + + [Fact] + public async Task FireScheduledJob_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + string url = $"/en-us/admin/api-scheduled-jobs/{Guid.NewGuid()}/fire"; + HttpRequestMessage request = new(HttpMethod.Put, url) + { + Content = CreateJsonContent() + }; + request.Headers.Add("RequestVerificationToken", antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(request); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint.StartsWith("scheduled-jobs", StringComparison.Ordinal)); + } + + /// + /// Creates the empty JSON body of the request; the content type is set without the charset suffix, because the antiforgery middleware matches the content type exactly. + /// + /// The created content. + private static StringContent CreateJsonContent() + { + StringContent content = new("{}", Encoding.UTF8, "application/json"); + content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + return content; + } +} \ No newline at end of file diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobHistory/GetScheduledJobHistoryEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobHistory/GetScheduledJobHistoryEndpointTests.cs new file mode 100644 index 00000000..8c543f07 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobHistory/GetScheduledJobHistoryEndpointTests.cs @@ -0,0 +1,87 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Scheduling; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.GetScheduledJobHistory; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Scheduling; +using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Scheduler.GetScheduledJobHistory; + +/// +/// Contains security tests for the /{culture}/admin/api-scheduled-jobs/history route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetScheduledJobHistoryEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); + private readonly ScheduledJobExecutionDtoFixture _scheduledJobExecutionDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetScheduledJobHistoryEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetScheduledJobHistory_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/admin/api-scheduled-jobs/history"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("auth/login", response.Headers.Location!.ToString()); + } + + [Fact] + public async Task GetScheduledJobHistory_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/api-scheduled-jobs/history"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + } + + [Fact] + public async Task GetScheduledJobHistory_WhenCalledByAdminUser_ShouldReturnExecutionHistoryData() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + ScheduledJobExecutionDto[] expectedExecutions = [.. _scheduledJobExecutionDtoFixture.CreateMany(2)]; + _apiFactory.ApiClientStub.RegisterGetResponse("scheduled-jobs/history", expectedExecutions); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/admin/api-scheduled-jobs/history"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobs/GetScheduledJobsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobs/GetScheduledJobsEndpointTests.cs new file mode 100644 index 00000000..3dcb9a45 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobs/GetScheduledJobsEndpointTests.cs @@ -0,0 +1,87 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Scheduling; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.GetScheduledJobs; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Scheduling; +using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Scheduler.GetScheduledJobs; + +/// +/// Contains security tests for the /{culture}/admin/api-scheduled-jobs route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetScheduledJobsEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); + private readonly ScheduledJobDtoFixture _scheduledJobDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetScheduledJobsEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetScheduledJobs_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/admin/api-scheduled-jobs"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("auth/login", response.Headers.Location!.ToString()); + } + + [Fact] + public async Task GetScheduledJobs_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/api-scheduled-jobs"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + } + + [Fact] + public async Task GetScheduledJobs_WhenCalledByAdminUser_ShouldReturnScheduledJobsData() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + ScheduledJobDto[] expectedJobs = [.. _scheduledJobDtoFixture.CreateMany(2)]; + _apiFactory.ApiClientStub.RegisterGetResponse("scheduled-jobs", expectedJobs); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/admin/api-scheduled-jobs"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesEndpointTests.cs new file mode 100644 index 00000000..79a4fc7e --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesEndpointTests.cs @@ -0,0 +1,87 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Scheduling; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.GetSchedulerDisplayPreferences; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Scheduling; +using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Scheduler.GetSchedulerDisplayPreferences; + +/// +/// Contains security tests for the /{culture}/admin/api-scheduled-jobs/display-preferences route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetSchedulerDisplayPreferencesEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); + private readonly SchedulerDisplayPreferencesDtoFixture _schedulerDisplayPreferencesDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetSchedulerDisplayPreferencesEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetSchedulerDisplayPreferences_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/admin/api-scheduled-jobs/display-preferences"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("auth/login", response.Headers.Location!.ToString()); + } + + [Fact] + public async Task GetSchedulerDisplayPreferences_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/api-scheduled-jobs/display-preferences"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + } + + [Fact] + public async Task GetSchedulerDisplayPreferences_WhenCalledByAdminUser_ShouldReturnDisplayPreferencesData() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + SchedulerDisplayPreferencesDto expectedPreferences = _schedulerDisplayPreferencesDtoFixture.Create(); + _apiFactory.ApiClientStub.RegisterGetResponse("scheduled-jobs/display-preferences", expectedPreferences); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/admin/api-scheduled-jobs/display-preferences"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/RemoveScheduledJob/RemoveScheduledJobEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/RemoveScheduledJob/RemoveScheduledJobEndpointTests.cs new file mode 100644 index 00000000..576f7881 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/RemoveScheduledJob/RemoveScheduledJobEndpointTests.cs @@ -0,0 +1,85 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Scheduler.RemoveScheduledJob; + +/// +/// Contains security tests for the /{culture}/admin/api-scheduled-jobs/{scheduledJobId} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class RemoveScheduledJobEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public RemoveScheduledJobEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task RemoveScheduledJob_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + string url = $"/en-us/admin/api-scheduled-jobs/{Guid.NewGuid()}"; + HttpRequestMessage request = new(HttpMethod.Delete, url) + { + Content = CreateJsonContent() + }; + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(request); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.DeleteEndpointsCalled, endpoint => endpoint.StartsWith("scheduled-jobs", StringComparison.Ordinal)); + } + + [Fact] + public async Task RemoveScheduledJob_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + string url = $"/en-us/admin/api-scheduled-jobs/{Guid.NewGuid()}"; + HttpRequestMessage request = new(HttpMethod.Delete, url) + { + Content = CreateJsonContent() + }; + request.Headers.Add("RequestVerificationToken", antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(request); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.DeleteEndpointsCalled, endpoint => endpoint.StartsWith("scheduled-jobs", StringComparison.Ordinal)); + } + + /// + /// Creates the empty JSON body of the request; the content type is set without the charset suffix, because the antiforgery middleware matches the content type exactly. + /// + /// The created content. + private static StringContent CreateJsonContent() + { + StringContent content = new("{}", Encoding.UTF8, "application/json"); + content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + return content; + } +} \ No newline at end of file diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/SchedulerIndexViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/SchedulerIndexViewEndpointTests.cs new file mode 100644 index 00000000..be0107a6 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/SchedulerIndexViewEndpointTests.cs @@ -0,0 +1,80 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler; +using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Scheduler; + +/// +/// Contains security tests for the /{culture}/admin/scheduled-jobs route served by the class. +/// +[ExcludeFromCodeCoverage] +public class SchedulerIndexViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public SchedulerIndexViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task SchedulerIndex_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/admin/scheduled-jobs"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("auth/login", response.Headers.Location!.ToString()); + } + + [Fact] + public async Task SchedulerIndex_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/scheduled-jobs"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + } + + [Fact] + public async Task SchedulerIndex_WhenCalledByAdminUser_ShouldReturnSchedulerPage() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/scheduled-jobs"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpointTests.cs new file mode 100644 index 00000000..99bdf02f --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpointTests.cs @@ -0,0 +1,85 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Scheduler.StartScheduledJob; + +/// +/// Contains security tests for the /{culture}/admin/api-scheduled-jobs/{scheduledJobId}/start route served by the class. +/// +[ExcludeFromCodeCoverage] +public class StartScheduledJobEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public StartScheduledJobEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task StartScheduledJob_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + string url = $"/en-us/admin/api-scheduled-jobs/{Guid.NewGuid()}/start"; + HttpRequestMessage request = new(HttpMethod.Put, url) + { + Content = CreateJsonContent() + }; + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(request); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint.StartsWith("scheduled-jobs", StringComparison.Ordinal)); + } + + [Fact] + public async Task StartScheduledJob_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + string url = $"/en-us/admin/api-scheduled-jobs/{Guid.NewGuid()}/start"; + HttpRequestMessage request = new(HttpMethod.Put, url) + { + Content = CreateJsonContent() + }; + request.Headers.Add("RequestVerificationToken", antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(request); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint.StartsWith("scheduled-jobs", StringComparison.Ordinal)); + } + + /// + /// Creates the empty JSON body of the request; the content type is set without the charset suffix, because the antiforgery middleware matches the content type exactly. + /// + /// The created content. + private static StringContent CreateJsonContent() + { + StringContent content = new("{}", Encoding.UTF8, "application/json"); + content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + return content; + } +} \ No newline at end of file diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpointTests.cs new file mode 100644 index 00000000..1a26764f --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpointTests.cs @@ -0,0 +1,85 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Scheduler.StopScheduledJob; + +/// +/// Contains security tests for the /{culture}/admin/api-scheduled-jobs/{scheduledJobId}/stop route served by the class. +/// +[ExcludeFromCodeCoverage] +public class StopScheduledJobEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public StopScheduledJobEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task StopScheduledJob_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + string url = $"/en-us/admin/api-scheduled-jobs/{Guid.NewGuid()}/stop"; + HttpRequestMessage request = new(HttpMethod.Put, url) + { + Content = CreateJsonContent() + }; + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(request); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint.StartsWith("scheduled-jobs", StringComparison.Ordinal)); + } + + [Fact] + public async Task StopScheduledJob_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + string url = $"/en-us/admin/api-scheduled-jobs/{Guid.NewGuid()}/stop"; + HttpRequestMessage request = new(HttpMethod.Put, url) + { + Content = CreateJsonContent() + }; + request.Headers.Add("RequestVerificationToken", antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(request); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint.StartsWith("scheduled-jobs", StringComparison.Ordinal)); + } + + /// + /// Creates the empty JSON body of the request; the content type is set without the charset suffix, because the antiforgery middleware matches the content type exactly. + /// + /// The created content. + private static StringContent CreateJsonContent() + { + StringContent content = new("{}", Encoding.UTF8, "application/json"); + content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + return content; + } +} \ No newline at end of file diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpointTests.cs new file mode 100644 index 00000000..b8b8dfaa --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpointTests.cs @@ -0,0 +1,85 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Scheduler.UpdateSchedulerDisplayPreferences; + +/// +/// Contains security tests for the /{culture}/admin/api-scheduled-jobs/display-preferences route served by the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateSchedulerDisplayPreferencesEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public UpdateSchedulerDisplayPreferencesEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task UpdateSchedulerDisplayPreferences_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + string url = "/en-us/admin/api-scheduled-jobs/display-preferences"; + HttpRequestMessage request = new(HttpMethod.Put, url) + { + Content = CreateJsonContent() + }; + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(request); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint.StartsWith("scheduled-jobs", StringComparison.Ordinal)); + } + + [Fact] + public async Task UpdateSchedulerDisplayPreferences_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + string url = "/en-us/admin/api-scheduled-jobs/display-preferences"; + HttpRequestMessage request = new(HttpMethod.Put, url) + { + Content = CreateJsonContent() + }; + request.Headers.Add("RequestVerificationToken", antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(request); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint.StartsWith("scheduled-jobs", StringComparison.Ordinal)); + } + + /// + /// Creates the empty JSON body of the request; the content type is set without the charset suffix, because the antiforgery middleware matches the content type exactly. + /// + /// The created content. + private static StringContent CreateJsonContent() + { + StringContent content = new("{}", Encoding.UTF8, "application/json"); + content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + return content; + } +} \ No newline at end of file diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandlerTests.cs index 1068a8df..685422b6 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandlerTests.cs @@ -45,6 +45,7 @@ public class SetupApplicationCommandHandlerTests private readonly IDateTimeProvider _mockDateTimeProvider; private readonly IDataSeedService _mockDataSeedService; private readonly IDomainEventsQueue _mockDomainEventsQueue; + private readonly IValidator _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(); _mockDataSeedService = Substitute.For(); _mockDomainEventsQueue = Substitute.For(); - IValidator mockValidator = Substitute.For>(); - mockValidator.Validate(Arg.Any()) + _mockValidator = Substitute.For>(); + _mockValidator.Validate(Arg.Any()) .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(domainEvent => domainEvent.ScheduledJobId.Value == activeScheduledJob2.Id)); _mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Is(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()).Returns([validationError]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(validationError, result.FirstError); + await _mockUserRepository.DidNotReceive().GetAllAsync(Arg.Any()); + await _mockUserRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenReadingTheSeededScheduledJobsFails_ShouldReturnTheRepositoryError() + { + // Arrange + SetupApplicationCommand command = _setupApplicationCommandFixture.Create(); + _mockUserRepository.GetAllAsync(Arg.Any()) + .Returns(Result.From(Enumerable.Empty())); + _mockHashService.HashString(command.Password!) + .Returns("hashedPassword"); + _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + _mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + _mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + _mockDataSeedService.SetAdminRolePermissionsAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + _mockDataSeedService.SetAdminRoleToAdministratorAccount(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + Error expectedError = Error.Failure("ScheduledJobs.NotFound", "Failed to read the scheduled jobs"); + _mockScheduledJobRepository.GetAllAsync(Arg.Any()) + .Returns(expectedError); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(expectedError, result.FirstError); + _mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any()); + } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandHandlerTests.cs index b648344c..1ba576bb 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandHandlerTests.cs @@ -253,4 +253,30 @@ public class AddScheduledJobCommandHandlerTests await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); _mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any()); } + + [Fact] + public async Task HandleAsync_WhenCommandIsValidWithOnceAtStartupSchedule_ShouldInsertScheduledJobAndReturnResponse() + { + // Arrange + AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(scheduleType: ScheduleType.OnceAtStartup); + _mockScheduledJobRepository.InsertAsync(Arg.Any(), Arg.Any()).Returns(Result.Created); + + // Act + Result 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(scheduledJob => + scheduledJob.Name == command.Name && + scheduledJob.ScheduleType == ScheduleType.OnceAtStartup), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + _mockDomainEventsQueue.Received(1).Enqueue(Arg.Is(domainEvent => domainEvent is ScheduledJobAddedDomainEvent)); + } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommandHandlerTests.cs index f9c777c2..93a48823 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommandHandlerTests.cs @@ -216,4 +216,47 @@ public class RemoveScheduledJobCommandHandlerTests await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); _mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any()); } + + [Fact] + public async Task HandleAsync_WhenGettingTheScheduledJobFails_ShouldReturnTheRepositoryError() + { + // Arrange + RemoveScheduledJobCommand command = _removeScheduledJobCommandFixture.Create(); + Error repositoryError = DomainErrors.Scheduling.ScheduledJobNotFound; + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + .Returns(repositoryError); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(repositoryError, result.FirstError); + await _mockScheduledJobScheduler.DidNotReceive().StopCycleAsync(Arg.Any(), Arg.Any()); + await _mockScheduledJobExecutionRepository.DidNotReceive().DeleteByScheduledJobIdAsync(Arg.Any(), Arg.Any()); + } + + [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()) + .Returns(Result.From(invalidScheduledJob)); + + // Act + Result 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(), Arg.Any()); + await _mockScheduledJobExecutionRepository.DidNotReceive().DeleteByScheduledJobIdAsync(Arg.Any(), Arg.Any()); + } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommandHandlerTests.cs index c387134c..453cc88f 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommandHandlerTests.cs @@ -200,4 +200,46 @@ public class StartScheduledJobCommandHandlerTests await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); _mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any()); } + + [Fact] + public async Task HandleAsync_WhenGettingTheScheduledJobFails_ShouldReturnTheRepositoryError() + { + // Arrange + StartScheduledJobCommand command = _startScheduledJobCommandFixture.Create(); + Error repositoryError = DomainErrors.Scheduling.ScheduledJobNotFound; + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + .Returns(repositoryError); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(repositoryError, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [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()) + .Returns(Result.From(invalidScheduledJob)); + + // Act + Result 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()); + _mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any()); + } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommandHandlerTests.cs index 4d1efdd8..7c1d40e1 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommandHandlerTests.cs @@ -152,6 +152,22 @@ public class StopScheduledJobCommandHandlerTests await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); } + [Fact] + public async Task HandleAsync_WhenUserIsNotAdministrator_ShouldReturnNotAuthorized() + { + // Arrange + StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create(); + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(false); + + // Act + Result 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(), Arg.Any()); + } + [Fact] public async Task HandleAsync_WhenScheduledJobDoesNotExist_ShouldReturnNotFound() { @@ -214,4 +230,46 @@ public class StopScheduledJobCommandHandlerTests await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); await _mockScheduledJobScheduler.DidNotReceive().StopCycleAsync(Arg.Any(), Arg.Any()); } + + [Fact] + public async Task HandleAsync_WhenGettingTheScheduledJobFails_ShouldReturnTheRepositoryError() + { + // Arrange + StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create(); + Error repositoryError = DomainErrors.Scheduling.ScheduledJobNotFound; + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + .Returns(repositoryError); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(repositoryError, result.FirstError); + await _mockScheduledJobScheduler.DidNotReceive().StopCycleAsync(Arg.Any(), Arg.Any()); + } + + [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()) + .Returns(Result.From(invalidScheduledJob)); + + // Act + Result 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()); + await _mockScheduledJobScheduler.DidNotReceive().StopCycleAsync(Arg.Any(), Arg.Any()); + } } diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Scheduling/ScheduledJobRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Scheduling/ScheduledJobRepositoryTests.cs index a04d6802..b45c6ff8 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Scheduling/ScheduledJobRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Scheduling/ScheduledJobRepositoryTests.cs @@ -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 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 result = await _sut.GetByIdWithoutTrackingAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + [Fact] public async Task GetAllAsync_WhenScheduledJobsExist_ShouldReturnAllScheduledJobs() { diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Seed/DataSeedServiceTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Seed/DataSeedServiceTests.cs index c6bd2276..3ff2ee59 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Seed/DataSeedServiceTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Seed/DataSeedServiceTests.cs @@ -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(); /// /// Initializes a new instance of the 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(); _mockUnitOfWork.ScheduledJobRepository.Returns(mockScheduledJobRepository); - mockScheduledJobRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From(Enumerable.Empty())); List capturedScheduledJobs = []; mockScheduledJobRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.Created) @@ -583,48 +580,7 @@ public class DataSeedServiceTests await mockScheduledJobRepository.Received(5).InsertAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task SetDefaultScheduledJobsAsync_WhenScheduledJobsAlreadyExist_ShouldNotInsertAnyJob() - { - // Arrange - Guid adminUserId = Guid.NewGuid(); - IScheduledJobRepository mockScheduledJobRepository = Substitute.For(); - _mockUnitOfWork.ScheduledJobRepository.Returns(mockScheduledJobRepository); - ScheduledJobEntity existingScheduledJob = _scheduledJobEntityFixture.Create(scheduleType: ScheduleType.WithIntervalInMinutes); - mockScheduledJobRepository.GetAllAsync(Arg.Any()) - .Returns(new[] { existingScheduledJob }); - - // Act - Result result = await _sut.SetDefaultScheduledJobsAsync(adminUserId, CancellationToken.None); - - // Assert - Assert.False(result.IsFailure); - Assert.Equal(Result.Created, result.Value); - await mockScheduledJobRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task SetDefaultScheduledJobsAsync_WhenGetAllScheduledJobsFails_ShouldReturnError() - { - // Arrange - Guid adminUserId = Guid.NewGuid(); - IScheduledJobRepository mockScheduledJobRepository = Substitute.For(); - _mockUnitOfWork.ScheduledJobRepository.Returns(mockScheduledJobRepository); - Error expectedError = Error.Failure("ScheduledJobs.NotFound", "Failed to retrieve the scheduled jobs"); - mockScheduledJobRepository.GetAllAsync(Arg.Any()) - .Returns(expectedError); - - // Act - Result result = await _sut.SetDefaultScheduledJobsAsync(adminUserId, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(expectedError, result.FirstError); - await mockScheduledJobRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + await mockScheduledJobRepository.DidNotReceive().GetAllAsync(Arg.Any()); } [Fact] @@ -634,8 +590,6 @@ public class DataSeedServiceTests Guid adminUserId = Guid.NewGuid(); IScheduledJobRepository mockScheduledJobRepository = Substitute.For(); _mockUnitOfWork.ScheduledJobRepository.Returns(mockScheduledJobRepository); - mockScheduledJobRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From(Enumerable.Empty())); Error expectedError = Error.Failure("ScheduledJobs.InsertFailed", "Failed to insert the scheduled job"); mockScheduledJobRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.Created, expectedError); diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/ScheduledJobRuntimeRegistryTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/ScheduledJobRuntimeRegistryTests.cs index 0a40269e..55b6b16b 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/ScheduledJobRuntimeRegistryTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/ScheduledJobRuntimeRegistryTests.cs @@ -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)); + } } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/ScheduledJobSchedulerJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/ScheduledJobSchedulerJobTests.cs index fa348c40..63b116b2 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/ScheduledJobSchedulerJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/ScheduledJobSchedulerJobTests.cs @@ -1,14 +1,30 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Common.DataAccess.Entities.Themes; +using Lumina.Application.Common.DataAccess.Repositories.Scheduling; +using Lumina.Application.Common.DataAccess.Repositories.Themes; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Themes; +using Lumina.Application.Common.Infrastructure.Time; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling; using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate; using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; using Lumina.Infrastructure.Core.Scheduling.Execution; +using Lumina.Infrastructure.Core.Themes; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using NSubstitute; using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Reflection; using System.Threading; using System.Threading.Tasks; #endregion @@ -24,15 +40,27 @@ public class ScheduledJobSchedulerJobTests private readonly IServiceScopeFactory _mockServiceScopeFactory; private readonly IServiceScope _mockServiceScope; private readonly IServiceProvider _mockServiceProvider; + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IScheduledJobRepository _mockScheduledJobRepository; + private readonly IScheduledJobExecutionRepository _mockScheduledJobExecutionRepository; + private readonly IDomainEventPublisher _mockDomainEventPublisher; + private readonly IScheduledTaskExecutorFactory _mockTaskExecutorFactory; + private readonly IScheduledTaskExecutor _mockTaskExecutor; private readonly ScheduledJobRuntimeRegistry _runtimeRegistry; private readonly ScheduledJobSchedulerJob _sut; + private readonly Dictionary _services; private readonly ScheduledJobIdFixture _scheduledJobIdFixture = new(); + private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new(); + private readonly ScheduledJobExecutionEntityFixture _scheduledJobExecutionEntityFixture = new(); + private readonly ScheduledJobFixture _scheduledJobFixture = new(); + private readonly IntervalScheduleFixture _intervalScheduleFixture = new(); /// /// Initializes a new instance of the class. /// public ScheduledJobSchedulerJobTests() { + _services = []; _mockServiceScopeFactory = Substitute.For(); _mockServiceScope = Substitute.For(); _mockServiceProvider = Substitute.For(); @@ -40,6 +68,27 @@ public class ScheduledJobSchedulerJobTests _mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope); _mockServiceScopeFactory.CreateAsyncScope().Returns(new AsyncServiceScope(_mockServiceScope)); + _mockUnitOfWork = Substitute.For(); + _mockScheduledJobRepository = Substitute.For(); + _mockScheduledJobExecutionRepository = Substitute.For(); + _mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository); + _mockUnitOfWork.ScheduledJobExecutionRepository.Returns(_mockScheduledJobExecutionRepository); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockScheduledJobRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.Updated); + _mockScheduledJobExecutionRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.Updated); + + _mockDomainEventPublisher = Substitute.For(); + _mockTaskExecutorFactory = Substitute.For(); + _mockTaskExecutor = Substitute.For(); + _mockTaskExecutor.ExecutePayloadAsync(Arg.Any(), Arg.Any()).Returns(Result.Success); + _mockTaskExecutorFactory.CreateExecutor(Arg.Any()).Returns(_mockTaskExecutor); + + _services[typeof(IUnitOfWork)] = _mockUnitOfWork; + _services[typeof(IDomainEventPublisher)] = _mockDomainEventPublisher; + _services[typeof(IScheduledTaskExecutorFactory)] = _mockTaskExecutorFactory; + _mockServiceProvider.GetService(Arg.Any()) + .Returns(callInfo => _services.TryGetValue((Type)callInfo[0]!, out object? service) ? service : null); + _runtimeRegistry = new ScheduledJobRuntimeRegistry(); ILogger logger = Substitute.For>(); _sut = new ScheduledJobSchedulerJob(_runtimeRegistry, logger, _mockServiceScopeFactory); @@ -79,10 +128,12 @@ public class ScheduledJobSchedulerJobTests } [Fact] - public async Task RunOnceAsync_WhenCalled_ShouldCompleteWithoutThrowing() + public async Task RunOnceAsync_WhenTheJobCannotStart_ShouldNotExecuteThePayload() { // Arrange - ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(); + ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); // Act await _sut.RunOnceAsync(scheduledJobId, CancellationToken.None); @@ -90,6 +141,992 @@ public class ScheduledJobSchedulerJobTests await Task.Delay(150); // Assert - Assert.True(true); + await _mockTaskExecutor.DidNotReceive().ExecutePayloadAsync(Arg.Any(), Arg.Any()); + Assert.True(_runtimeRegistry.TryAcquireRunSlot(scheduledJobId)); + _runtimeRegistry.ReleaseRunSlot(scheduledJobId); + } + + [Fact] + public async Task ExecuteScheduledJobRunAsync_WhenFiredOnAJobWithoutAnActiveCycle_ShouldCompleteTheJobAsAOneTimeRun() + { + // Arrange + ScheduledJobEntity addedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(addedJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(addedJob); + _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(_scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60)); + + // Act + await InvokeAsync("ExecuteScheduledJobRunAsync", scheduledJobId, false, CancellationToken.None); + + // Assert + await _mockTaskExecutor.Received(1).ExecutePayloadAsync(Arg.Any(), Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => !domainEvent.IsCycleRun), Arg.Any()); + } + + [Fact] + public async Task ExecuteScheduledJobRunAsync_WhenFiredOnAJobWithAnActiveCycle_ShouldCompleteTheJobBackToItsActiveState() + { + // Arrange + ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(activeJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(activeJob); + _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(_scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60)); + using CancellationTokenSource cycleCancellationTokenSource = new(); + _runtimeRegistry.TryStartCycle(scheduledJobId, cycleCancellationTokenSource); + + // Act + await InvokeAsync("ExecuteScheduledJobRunAsync", scheduledJobId, false, CancellationToken.None); + + // Assert + await _mockTaskExecutor.Received(1).ExecutePayloadAsync(Arg.Any(), Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => domainEvent.IsCycleRun), Arg.Any()); + Assert.True(_runtimeRegistry.HasActiveCycle(scheduledJobId)); + } + + [Fact] + public async Task RunScheduledJobAsync_WhenTheStartedEventPublishingFails_ShouldReconcileTheInterruptedRunAndReleaseTheRunSlot() + { + // Arrange + ScheduledJobEntity addedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(addedJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(addedJob, runningJob); + ScheduledJobExecutionEntity openExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: runningJob.Id, isCycleRun: false, wasCycleActive: true, completedOnUtc: null); + _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(Arg.Any(), Arg.Any()).Returns(openExecution); + _mockDomainEventPublisher.When(publisher => publisher.PublishAsync(Arg.Is(_ => true), Arg.Any())) + .Do(_ => throw new InvalidOperationException("publish failed")); + + // Act + await InvokeAsync("RunScheduledJobAsync", scheduledJobId, false, CancellationToken.None); + + // Assert + await _mockScheduledJobRepository.Received(1).UpdateAsync(Arg.Is(entity => entity.Status == ScheduledJobStatus.Active), Arg.Any()); + await _mockScheduledJobExecutionRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + Assert.True(_runtimeRegistry.TryAcquireRunSlot(scheduledJobId)); + _runtimeRegistry.ReleaseRunSlot(scheduledJobId); + } + + [Fact] + public async Task ReconcileInterruptedRunAsync_WhenTheOpenExecutionHadAnActiveCycle_ShouldRestoreTheJobToItsActiveState() + { + // Arrange + ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + ScheduledJobExecutionEntity openExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: runningJob.Id, isCycleRun: false, wasCycleActive: true, completedOnUtc: null); + _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(Arg.Any(), Arg.Any()).Returns(openExecution); + + // Act + ScheduledJobStatus result = await InvokeAsync("ReconcileInterruptedRunAsync", scheduledJobId, CancellationToken.None); + + // Assert + Assert.Equal(ScheduledJobStatus.Active, result); + await _mockScheduledJobRepository.Received(1).UpdateAsync(Arg.Is(entity => entity.Status == ScheduledJobStatus.Active), Arg.Any()); + await _mockScheduledJobExecutionRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task ReconcileInterruptedRunAsync_WhenTheOpenExecutionHadNoActiveCycle_ShouldRestoreTheJobToItsAddedState() + { + // Arrange + ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + ScheduledJobExecutionEntity openExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: runningJob.Id, isCycleRun: false, wasCycleActive: false, completedOnUtc: null); + _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(Arg.Any(), Arg.Any()).Returns(openExecution); + + // Act + ScheduledJobStatus result = await InvokeAsync("ReconcileInterruptedRunAsync", scheduledJobId, CancellationToken.None); + + // Assert + Assert.Equal(ScheduledJobStatus.Added, result); + await _mockScheduledJobRepository.Received(1).UpdateAsync(Arg.Is(entity => entity.Status == ScheduledJobStatus.Added), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task ReconcileInterruptedRunAsync_WhenTheJobIsNotRunning_ShouldReturnItsCurrentStatusWithoutReconciling() + { + // Arrange + ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(activeJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(activeJob); + + // Act + ScheduledJobStatus result = await InvokeAsync("ReconcileInterruptedRunAsync", scheduledJobId, CancellationToken.None); + + // Assert + Assert.Equal(ScheduledJobStatus.Active, result); + await _mockScheduledJobRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task RunCycleWorkerAsync_WhenTheJobHasAOnceAtStartupSchedule_ShouldRunTheTaskOnceAndEndTheCycle() + { + // Arrange + ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.OnceAtStartup); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(activeJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(activeJob); + _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(_scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.OnceAtStartup)); + + // Act + await InvokeAsync("RunCycleWorkerAsync", scheduledJobId, true, CancellationToken.None); + + // Assert + await _mockTaskExecutor.Received(1).ExecutePayloadAsync(Arg.Any(), Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => domainEvent.IsCycleRun), Arg.Any()); + Assert.False(_runtimeRegistry.HasActiveCycle(scheduledJobId)); + } + + [Fact] + public async Task ResumeActiveCyclesAsync_WhenAnActiveOnceAtStartupJobExists_ShouldResumeItsCycleAndFireTheTask() + { + // Arrange + ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.OnceAtStartup); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(activeJob.Id); + _mockScheduledJobRepository.GetActiveOrRunningAsync(Arg.Any()).Returns(new[] { activeJob }); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(activeJob); + _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(_scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.OnceAtStartup)); + + // Act + await InvokeAsync("ResumeActiveCyclesAsync", CancellationToken.None); + await WaitUntilAsync(() => _mockTaskExecutor.ReceivedCalls().Count() > 0); + + // Assert + await _mockTaskExecutor.Received(1).ExecutePayloadAsync(Arg.Any(), Arg.Any()); + Assert.False(_runtimeRegistry.HasActiveCycle(scheduledJobId)); + } + + [Fact] + public async Task SynchronizeBundledThemesIfNeededAsync_WhenTheScheduledJobsCannotBeRead_ShouldNotSynchronizeTheThemes() + { + // Arrange + Error error = Error.Failure("ScheduledJobs.NotFound", "Failed to read the scheduled jobs"); + _mockScheduledJobRepository.GetActiveOrRunningAsync(Arg.Any()).Returns(error); + IThemeService mockThemeService = Substitute.For(); + _services[typeof(IThemeService)] = mockThemeService; + + // Act + await InvokeAsync("SynchronizeBundledThemesIfNeededAsync", CancellationToken.None); + + // Assert + mockThemeService.DidNotReceive().GetBundledThemeArchivePaths(); + } + + [Fact] + public async Task SynchronizeBundledThemesIfNeededAsync_WhenAnActiveRepairThemesJobExists_ShouldNotSynchronizeTheThemes() + { + // Arrange + ScheduledJobEntity repairThemesJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60, taskType: ScheduledTaskType.RepairThemes); + _mockScheduledJobRepository.GetActiveOrRunningAsync(Arg.Any()).Returns(new[] { repairThemesJob }); + IThemeService mockThemeService = Substitute.For(); + _services[typeof(IThemeService)] = mockThemeService; + + // Act + await InvokeAsync("SynchronizeBundledThemesIfNeededAsync", CancellationToken.None); + + // Assert + mockThemeService.DidNotReceive().GetBundledThemeArchivePaths(); + } + + [Fact] + public async Task SynchronizeBundledThemesIfNeededAsync_WhenNoRepairThemesJobExists_ShouldSynchronizeTheBundledThemes() + { + // Arrange + _mockScheduledJobRepository.GetActiveOrRunningAsync(Arg.Any()).Returns(Array.Empty()); + IThemeService mockThemeService = Substitute.For(); + mockThemeService.GetBundledThemeArchivePaths().Returns([]); + IThemeRepository mockThemeRepository = Substitute.For(); + mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From(Enumerable.Empty())); + _mockUnitOfWork.ThemeRepository.Returns(mockThemeRepository); + _services[typeof(IThemeService)] = mockThemeService; + + // Act + await InvokeAsync("SynchronizeBundledThemesIfNeededAsync", CancellationToken.None); + + // Assert + mockThemeService.Received(1).GetBundledThemeArchivePaths(); + await mockThemeRepository.Received(1).GetAllAsync(Arg.Any()); + } + + [Fact] + public async Task SynchronizeBundledThemesIfNeededAsync_WhenReadingTheScheduledJobsThrows_ShouldSwallowTheException() + { + // Arrange + Task>> faultedRead = Task.FromException>>(new InvalidOperationException("The database is unavailable.")); + _mockScheduledJobRepository.GetActiveOrRunningAsync(Arg.Any()).Returns(faultedRead); + IThemeService mockThemeService = Substitute.For(); + _services[typeof(IThemeService)] = mockThemeService; + + // Act + await InvokeAsync("SynchronizeBundledThemesIfNeededAsync", CancellationToken.None); + + // Assert + mockThemeService.DidNotReceive().GetBundledThemeArchivePaths(); + } + + [Fact] + public async Task SynchronizeBundledThemesIfNeededAsync_WhenTheThemeServiceCannotBeResolved_ShouldSwallowTheException() + { + // Arrange + _mockScheduledJobRepository.GetActiveOrRunningAsync(Arg.Any()).Returns(Array.Empty()); + // The theme service is intentionally not registered in the services of the scope. + + // Act + await InvokeAsync("SynchronizeBundledThemesIfNeededAsync", CancellationToken.None); + + // Assert + // The generic exception handler swallowed the resolution failure, so the scheduled jobs were still read. + await _mockScheduledJobRepository.Received(1).GetActiveOrRunningAsync(Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationIsRequested_ShouldSynchronizeThemesResumeCyclesAndStopTheBackgroundService() + { + // Arrange + _mockScheduledJobRepository.GetActiveOrRunningAsync(Arg.Any()).Returns(Array.Empty()); + IThemeService mockThemeService = Substitute.For(); + mockThemeService.GetBundledThemeArchivePaths().Returns([]); + IThemeRepository mockThemeRepository = Substitute.For(); + mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From(Enumerable.Empty())); + _mockUnitOfWork.ThemeRepository.Returns(mockThemeRepository); + _services[typeof(IThemeService)] = mockThemeService; + using CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + + // Act + await InvokeAsync("ExecuteAsync", cancellationTokenSource.Token); + + // Assert + mockThemeService.Received(1).GetBundledThemeArchivePaths(); + await _mockScheduledJobRepository.Received(2).GetActiveOrRunningAsync(Arg.Any()); + } + + [Fact] + public async Task RunCycleWorkerAsync_WhenTheScheduleCannotBeLoaded_ShouldEndTheCycle() + { + // Arrange + ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(activeJob.Id); + Error error = Error.Failure("ScheduledJobs.NotFound", "Failed to read the scheduled job"); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(error); + + // Act + await InvokeAsync("RunCycleWorkerAsync", scheduledJobId, false, CancellationToken.None); + + // Assert + await _mockTaskExecutor.DidNotReceive().ExecutePayloadAsync(Arg.Any(), Arg.Any()); + Assert.False(_runtimeRegistry.HasActiveCycle(scheduledJobId)); + } + + [Fact] + public async Task ExecuteScheduledJobRunAsync_WhenCancelledBeforeItStarts_ShouldNotRunTheTask() + { + // Arrange + ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(activeJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(activeJob); + using CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + + // Act + await InvokeAsync("ExecuteScheduledJobRunAsync", scheduledJobId, false, cancellationTokenSource.Token); + + // Assert + await _mockTaskExecutor.DidNotReceive().ExecutePayloadAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ExecuteScheduledJobRunAsync_WhenTheJobCannotBeRead_ShouldReturnWithoutRunningTheTask() + { + // Arrange + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(); + Error error = Error.Failure("ScheduledJobs.NotFound", "Failed to read the scheduled job"); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(error); + + // Act + await InvokeAsync("ExecuteScheduledJobRunAsync", scheduledJobId, false, CancellationToken.None); + + // Assert + await _mockTaskExecutor.DidNotReceive().ExecutePayloadAsync(Arg.Any(), Arg.Any()); + await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ExecuteScheduledJobRunAsync_WhenTheJobCannotBeConvertedToDomain_ShouldReturnWithoutRunningTheTask() + { + // Arrange + // An interval schedule whose interval is not positive cannot be converted to its domain object. + ScheduledJobEntity invalidJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 0); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(invalidJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(invalidJob); + + // Act + await InvokeAsync("ExecuteScheduledJobRunAsync", scheduledJobId, false, CancellationToken.None); + + // Assert + await _mockTaskExecutor.DidNotReceive().ExecutePayloadAsync(Arg.Any(), Arg.Any()); + await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ExecuteScheduledJobRunAsync_WhenTheTokenIsCancelledAfterTheExecutionStarted_ShouldNotRunTheTaskPayload() + { + // Arrange + ScheduledJobEntity addedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(addedJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(addedJob); + using CancellationTokenSource cancellationTokenSource = new(); + _mockDomainEventPublisher.When(publisher => publisher.PublishAsync(Arg.Any(), Arg.Any())) + .Do(_ => cancellationTokenSource.Cancel()); + + // Act + await InvokeAsync("ExecuteScheduledJobRunAsync", scheduledJobId, false, cancellationTokenSource.Token); + + // Assert + await _mockTaskExecutor.DidNotReceive().ExecutePayloadAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ExecuteScheduledJobRunAsync_WhenTheTaskPayloadFails_ShouldLogTheFailureAndStillCompleteTheExecution() + { + // Arrange + ScheduledJobEntity addedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(addedJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(addedJob); + _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(_scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60)); + _mockTaskExecutor.ExecutePayloadAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Task.Failed", "The task of the scheduled job failed.")); + + // Act + await InvokeAsync("ExecuteScheduledJobRunAsync", scheduledJobId, false, CancellationToken.None); + + // Assert + await _mockTaskExecutor.Received(1).ExecutePayloadAsync(Arg.Any(), Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => !domainEvent.IsCycleRun), Arg.Any()); + } + + [Fact] + public async Task ExecuteScheduledJobRunAsync_WhenTheTaskPayloadThrows_ShouldLogTheExceptionAndStillCompleteTheExecution() + { + // Arrange + ScheduledJobEntity addedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(addedJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(addedJob); + _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(_scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60)); + _mockTaskExecutor.ExecutePayloadAsync(Arg.Any(), Arg.Any()) + .Returns(Task.FromException>(new InvalidOperationException("The task threw."))); + + // Act + await InvokeAsync("ExecuteScheduledJobRunAsync", scheduledJobId, false, CancellationToken.None); + + // Assert + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => !domainEvent.IsCycleRun), Arg.Any()); + } + + [Fact] + public async Task ExecuteScheduledJobRunAsync_WhenTheTaskPayloadIsCancelled_ShouldReturnWithoutCompletingTheExecution() + { + // Arrange + ScheduledJobEntity addedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(addedJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(addedJob); + _mockTaskExecutor.ExecutePayloadAsync(Arg.Any(), Arg.Any()) + .Returns(Task.FromException>(new OperationCanceledException())); + + // Act + await InvokeAsync("ExecuteScheduledJobRunAsync", scheduledJobId, false, CancellationToken.None); + + // Assert + await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Is(_ => true), Arg.Any()); + } + + [Fact] + public async Task ExecuteScheduledJobRunAsync_WhenTheTokenIsCancelledAfterThePayloadRan_ShouldNotCompleteTheExecution() + { + // Arrange + ScheduledJobEntity addedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(addedJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(addedJob); + using CancellationTokenSource cancellationTokenSource = new(); + _mockTaskExecutor.When(executor => executor.ExecutePayloadAsync(Arg.Any(), Arg.Any())) + .Do(_ => cancellationTokenSource.Cancel()); + _mockTaskExecutor.ExecutePayloadAsync(Arg.Any(), Arg.Any()).Returns(Result.Success); + + // Act + await InvokeAsync("ExecuteScheduledJobRunAsync", scheduledJobId, false, cancellationTokenSource.Token); + + // Assert + await _mockTaskExecutor.Received(1).ExecutePayloadAsync(Arg.Any(), Arg.Any()); + await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Is(_ => true), Arg.Any()); + } + + [Fact] + public async Task RunScheduledJobAsync_WhenAnotherExecutionIsAlreadyRunning_ShouldSkipTheExecution() + { + // Arrange + ScheduledJobEntity addedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(addedJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(addedJob); + Assert.True(_runtimeRegistry.TryAcquireRunSlot(scheduledJobId)); + + // Act + await InvokeAsync("RunScheduledJobAsync", scheduledJobId, false, CancellationToken.None); + + // Assert + await _mockTaskExecutor.DidNotReceive().ExecutePayloadAsync(Arg.Any(), Arg.Any()); + Assert.False(_runtimeRegistry.TryAcquireRunSlot(scheduledJobId)); + _runtimeRegistry.ReleaseRunSlot(scheduledJobId); + } + + [Fact] + public async Task RunScheduledJobAsync_WhenTheStartedEventPublishingIsCancelled_ShouldReleaseTheRunSlot() + { + // Arrange + ScheduledJobEntity addedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(addedJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(addedJob, runningJob); + _mockDomainEventPublisher.When(publisher => publisher.PublishAsync(Arg.Any(), Arg.Any())) + .Do(_ => throw new OperationCanceledException()); + + // Act + await InvokeAsync("RunScheduledJobAsync", scheduledJobId, false, CancellationToken.None); + + // Assert + Assert.True(_runtimeRegistry.TryAcquireRunSlot(scheduledJobId)); + _runtimeRegistry.ReleaseRunSlot(scheduledJobId); + } + + [Fact] + public async Task CompleteExecutionAsync_WhenTheJobCannotBeReloaded_ShouldNotCompleteTheExecution() + { + // Arrange + ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); + _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(Error.Failure("ScheduledJobs.NotFound", "Failed to read the scheduled job")); + ScheduledJob scheduledJob = _scheduledJobFixture.Create(id: runningJob.Id, status: ScheduledJobStatus.Added); + scheduledJob.MarkExecutionStarted(isCycleRun: false); + + // Act + await InvokeAsync("CompleteExecutionAsync", scheduledJob, _mockUnitOfWork, _mockDomainEventPublisher, false, CancellationToken.None); + + // Assert + await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Is(_ => true), Arg.Any()); + } + + [Fact] + public async Task CompleteExecutionAsync_WhenTheJobIsNotRunningAnymore_ShouldNotCompleteTheExecution() + { + // Arrange + ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); + _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(activeJob); + ScheduledJob scheduledJob = _scheduledJobFixture.Create(id: runningJob.Id, status: ScheduledJobStatus.Added); + scheduledJob.MarkExecutionStarted(isCycleRun: false); + + // Act + await InvokeAsync("CompleteExecutionAsync", scheduledJob, _mockUnitOfWork, _mockDomainEventPublisher, false, CancellationToken.None); + + // Assert + await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Is(_ => true), Arg.Any()); + } + + [Fact] + public async Task CompleteExecutionAsync_WhenTheExecutionCannotBeMarkedCompleted_ShouldNotPublishTheCompletionEvent() + { + // Arrange + ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); + _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + // The domain scheduled job was never marked as started, so its execution cannot be marked as completed. + ScheduledJob scheduledJob = _scheduledJobFixture.Create(id: runningJob.Id, status: ScheduledJobStatus.Active); + + // Act + await InvokeAsync("CompleteExecutionAsync", scheduledJob, _mockUnitOfWork, _mockDomainEventPublisher, false, CancellationToken.None); + + // Assert + await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Is(_ => true), Arg.Any()); + } + + [Fact] + public async Task CompleteExecutionAsync_WhenPublishingTheCompletionEventFails_ShouldReconcileTheInterruptedRun() + { + // Arrange + ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + ScheduledJobExecutionEntity openExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: runningJob.Id, isCycleRun: false, wasCycleActive: true, completedOnUtc: null); + _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(Arg.Any(), Arg.Any()).Returns(openExecution); + _mockDomainEventPublisher.When(publisher => publisher.PublishAsync(Arg.Is(_ => true), Arg.Any())) + .Do(_ => throw new InvalidOperationException("publish failed")); + ScheduledJob scheduledJob = _scheduledJobFixture.Create(id: runningJob.Id, status: ScheduledJobStatus.Added); + scheduledJob.MarkExecutionStarted(isCycleRun: false); + + // Act + await InvokeAsync("CompleteExecutionAsync", scheduledJob, _mockUnitOfWork, _mockDomainEventPublisher, false, CancellationToken.None); + + // Assert + await _mockScheduledJobRepository.Received(1).UpdateAsync(Arg.Is(entity => entity.Status == ScheduledJobStatus.Active), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task ReconcileInterruptedRunAsync_WhenTheJobCannotBeRead_ShouldReturnAdded() + { + // Arrange + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure("ScheduledJobs.NotFound", "Failed to read the scheduled job")); + + // Act + ScheduledJobStatus result = await InvokeAsync("ReconcileInterruptedRunAsync", scheduledJobId, CancellationToken.None); + + // Assert + Assert.Equal(ScheduledJobStatus.Added, result); + } + + [Fact] + public async Task ReconcileInterruptedRunAsync_WhenTheOpenExecutionCannotBeRead_ShouldReturnAdded() + { + // Arrange + ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure("ScheduledJobExecutions.NotFound", "Failed to read the open execution")); + + // Act + ScheduledJobStatus result = await InvokeAsync("ReconcileInterruptedRunAsync", scheduledJobId, CancellationToken.None); + + // Assert + Assert.Equal(ScheduledJobStatus.Added, result); + await _mockScheduledJobRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task CompleteExecutionAsync_WhenPublishingTheCompletionEventIsCancelled_ShouldSwallowTheCancellation() + { + // Arrange + ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); + _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + _mockDomainEventPublisher.When(publisher => publisher.PublishAsync(Arg.Is(_ => true), Arg.Any())) + .Do(_ => throw new OperationCanceledException()); + ScheduledJob scheduledJob = _scheduledJobFixture.Create(id: runningJob.Id, status: ScheduledJobStatus.Added); + scheduledJob.MarkExecutionStarted(isCycleRun: false); + + // Act + await InvokeAsync("CompleteExecutionAsync", scheduledJob, _mockUnitOfWork, _mockDomainEventPublisher, false, CancellationToken.None); + + // Assert + // A cancelled completion is a normal shutdown outcome, so no reconciliation is started. + await _mockScheduledJobRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task ReconcileInterruptedRunAsync_WhenThereIsNoOpenExecution_ShouldRestoreTheJobToItsActiveState() + { + // Arrange + ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(null)); + + // Act + ScheduledJobStatus result = await InvokeAsync("ReconcileInterruptedRunAsync", scheduledJobId, CancellationToken.None); + + // Assert + Assert.Equal(ScheduledJobStatus.Active, result); + await _mockScheduledJobRepository.Received(1).UpdateAsync(Arg.Is(entity => entity.Status == ScheduledJobStatus.Active), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task ReconcileInterruptedRunAsync_WhenUpdatingTheScheduledJobFails_ShouldReturnAdded() + { + // Arrange + ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + ScheduledJobExecutionEntity openExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: runningJob.Id, isCycleRun: false, wasCycleActive: true, completedOnUtc: null); + _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(Arg.Any(), Arg.Any()).Returns(openExecution); + _mockScheduledJobRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure("ScheduledJobs.UpdateFailed", "Failed to update the scheduled job")); + + // Act + ScheduledJobStatus result = await InvokeAsync("ReconcileInterruptedRunAsync", scheduledJobId, CancellationToken.None); + + // Assert + Assert.Equal(ScheduledJobStatus.Added, result); + await _mockScheduledJobExecutionRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ReconcileInterruptedRunAsync_WhenClosingTheOpenExecutionFails_ShouldReturnAdded() + { + // Arrange + ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + ScheduledJobExecutionEntity openExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: runningJob.Id, isCycleRun: false, wasCycleActive: true, completedOnUtc: null); + _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(Arg.Any(), Arg.Any()).Returns(openExecution); + _mockScheduledJobExecutionRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure("ScheduledJobExecutions.UpdateFailed", "Failed to update the execution")); + + // Act + ScheduledJobStatus result = await InvokeAsync("ReconcileInterruptedRunAsync", scheduledJobId, CancellationToken.None); + + // Assert + Assert.Equal(ScheduledJobStatus.Added, result); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task ReconcileInterruptedRunAsync_WhenSavingTheReconciliationThrows_ShouldLogAndReturnAdded() + { + // Arrange + ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + ScheduledJobExecutionEntity openExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: runningJob.Id, isCycleRun: false, wasCycleActive: true, completedOnUtc: null); + _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(Arg.Any(), Arg.Any()).Returns(openExecution); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.FromException(new InvalidOperationException("Save failed"))); + + // Act + ScheduledJobStatus result = await InvokeAsync("ReconcileInterruptedRunAsync", scheduledJobId, CancellationToken.None); + + // Assert + Assert.Equal(ScheduledJobStatus.Added, result); + } + + [Fact] + public async Task ReconcileInterruptedRunAsync_WhenSavingTheReconciliationIsCancelled_ShouldReturnAdded() + { + // Arrange + ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + ScheduledJobExecutionEntity openExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: runningJob.Id, isCycleRun: false, wasCycleActive: true, completedOnUtc: null); + _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(Arg.Any(), Arg.Any()).Returns(openExecution); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.FromException(new OperationCanceledException())); + + // Act + ScheduledJobStatus result = await InvokeAsync("ReconcileInterruptedRunAsync", scheduledJobId, CancellationToken.None); + + // Assert + Assert.Equal(ScheduledJobStatus.Added, result); + } + + [Fact] + public async Task ResumeActiveCyclesAsync_WhenTheScheduledJobsCannotBeRead_ShouldNotResumeAnyCycle() + { + // Arrange + _mockScheduledJobRepository.GetActiveOrRunningAsync(Arg.Any()) + .Returns(Error.Failure("ScheduledJobs.NotFound", "Failed to read the scheduled jobs")); + + // Act + await InvokeAsync("ResumeActiveCyclesAsync", CancellationToken.None); + + // Assert + await _mockTaskExecutor.DidNotReceive().ExecutePayloadAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ResumeActiveCyclesAsync_WhenARunningJobWasReconciledToItsAddedState_ShouldSkipResumingItsCycle() + { + // Arrange + ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); + _mockScheduledJobRepository.GetActiveOrRunningAsync(Arg.Any()).Returns(new[] { runningJob }); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + ScheduledJobExecutionEntity openExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: runningJob.Id, isCycleRun: false, wasCycleActive: false, completedOnUtc: null); + _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(Arg.Any(), Arg.Any()).Returns(openExecution); + + // Act + await InvokeAsync("ResumeActiveCyclesAsync", CancellationToken.None); + await Task.Delay(100); + + // Assert + await _mockScheduledJobRepository.Received(1).UpdateAsync(Arg.Is(entity => entity.Status == ScheduledJobStatus.Added), Arg.Any()); + Assert.False(_runtimeRegistry.HasActiveCycle(scheduledJobId)); + } + + [Fact] + public async Task ResumeActiveCyclesAsync_WhenARunningJobWasReconciledToItsActiveState_ShouldResumeItsCycleAndFireTheTask() + { + // Arrange + ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.OnceAtStartup); + ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.OnceAtStartup); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); + _mockScheduledJobRepository.GetActiveOrRunningAsync(Arg.Any()).Returns(new[] { runningJob }); + // The first read reconciles the interrupted run while the job is still running; the reads made by the resumed cycle observe the reconciled active status. + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(runningJob, activeJob, activeJob); + _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(_scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.OnceAtStartup)); + ScheduledJobExecutionEntity openExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: runningJob.Id, isCycleRun: false, wasCycleActive: true, completedOnUtc: null); + _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(Arg.Any(), Arg.Any()).Returns(openExecution); + + // Act + await InvokeAsync("ResumeActiveCyclesAsync", CancellationToken.None); + await WaitUntilAsync(() => _mockTaskExecutor.ReceivedCalls().Count() > 0); + + // Assert + await _mockTaskExecutor.Received(1).ExecutePayloadAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ResumeActiveCyclesAsync_WhenAnActiveIntervalJobExists_ShouldResumeItsCycleWithoutFiringTheTask() + { + // Arrange + ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(activeJob.Id); + _mockScheduledJobRepository.GetActiveOrRunningAsync(Arg.Any()).Returns(new[] { activeJob }); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(activeJob); + + // Act + await InvokeAsync("ResumeActiveCyclesAsync", CancellationToken.None); + await WaitUntilAsync(() => _runtimeRegistry.HasActiveCycle(scheduledJobId)); + await _sut.StopCycleAsync(scheduledJobId, CancellationToken.None); + await Task.Delay(50); + + // Assert + await _mockTaskExecutor.DidNotReceive().ExecutePayloadAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task RunCycleWorkerAsync_WhenTheTimerTicks_ShouldRunTheTaskAfterEachTickAndEndTheCycle() + { + // Arrange + ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(activeJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(activeJob); + _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + RegisterDateTimeProvider(); + IScheduledJobCycleTicker mockCycleTicker = Substitute.For(); + mockCycleTicker.WaitForNextTickAsync(Arg.Any()) + .Returns(new ValueTask(true), new ValueTask(true), new ValueTask(false)); + ScheduledJobSchedulerJob schedulerJob = CreateScheduledJobSchedulerJob(_ => mockCycleTicker); + + // Act + await InvokeOnAsync(schedulerJob, "RunCycleWorkerAsync", scheduledJobId, false, CancellationToken.None); + + // Assert + await _mockTaskExecutor.Received(2).ExecutePayloadAsync(Arg.Any(), Arg.Any()); + await _mockDomainEventPublisher.Received(2).PublishAsync(Arg.Is(domainEvent => domainEvent.IsCycleRun), Arg.Any()); + Assert.False(_runtimeRegistry.HasActiveCycle(scheduledJobId)); + } + + [Fact] + public async Task RunCycleWorkerAsync_WhenTheTimerTicksForADailySchedule_ShouldRecalculateThePeriodAfterEveryRun() + { + // Arrange + ScheduledJobEntity dailyJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.DailyAtHourAndMinute, hour: 10, minute: 30); + ScheduledJobEntity runningDailyJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.DailyAtHourAndMinute, hour: 10, minute: 30); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(dailyJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(dailyJob); + _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(runningDailyJob); + RegisterDateTimeProvider(); + IScheduledJobCycleTicker mockCycleTicker = Substitute.For(); + mockCycleTicker.WaitForNextTickAsync(Arg.Any()) + .Returns(new ValueTask(true), new ValueTask(false)); + ScheduledJobSchedulerJob schedulerJob = CreateScheduledJobSchedulerJob(_ => mockCycleTicker); + + // Act + await InvokeOnAsync(schedulerJob, "RunCycleWorkerAsync", scheduledJobId, false, CancellationToken.None); + + // Assert + await _mockTaskExecutor.Received(1).ExecutePayloadAsync(Arg.Any(), Arg.Any()); + mockCycleTicker.Received(1).Period = Arg.Any(); + Assert.False(_runtimeRegistry.HasActiveCycle(scheduledJobId)); + } + + [Fact] + public async Task RunCycleWorkerAsync_WhenTheCycleIsStoppedDuringARun_ShouldEndTheCycleOnTheNextTick() + { + // Arrange + ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(activeJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(activeJob); + _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + RegisterDateTimeProvider(); + _mockTaskExecutor.ExecutePayloadAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Success) + .AndDoes(_ => _runtimeRegistry.StopCycle(scheduledJobId)); + IScheduledJobCycleTicker mockCycleTicker = Substitute.For(); + mockCycleTicker.WaitForNextTickAsync(Arg.Any()) + .Returns(new ValueTask(true), new ValueTask(true), new ValueTask(false)); + ScheduledJobSchedulerJob schedulerJob = CreateScheduledJobSchedulerJob(_ => mockCycleTicker); + + // Act + await InvokeOnAsync(schedulerJob, "RunCycleWorkerAsync", scheduledJobId, false, CancellationToken.None); + + // Assert + await _mockTaskExecutor.Received(1).ExecutePayloadAsync(Arg.Any(), Arg.Any()); + await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Is(_ => true), Arg.Any()); + Assert.False(_runtimeRegistry.HasActiveCycle(scheduledJobId)); + } + + [Fact] + public async Task RunCycleWorkerAsync_WhenTheCycleTokenIsCancelled_ShouldSwallowTheCancellationAndEndTheCycle() + { + // Arrange + ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(activeJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(activeJob); + RegisterDateTimeProvider(); + using CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + + // Act + await InvokeAsync("RunCycleWorkerAsync", scheduledJobId, false, cancellationTokenSource.Token); + + // Assert + await _mockTaskExecutor.DidNotReceive().ExecutePayloadAsync(Arg.Any(), Arg.Any()); + Assert.False(_runtimeRegistry.HasActiveCycle(scheduledJobId)); + } + + [Fact] + public async Task RunCycleWorkerAsync_WhenWaitingForTheNextTickThrows_ShouldLogTheErrorAndEndTheCycle() + { + // Arrange + ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(activeJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(activeJob); + RegisterDateTimeProvider(); + IScheduledJobCycleTicker mockCycleTicker = Substitute.For(); + mockCycleTicker.WaitForNextTickAsync(Arg.Any()) + .Returns(new ValueTask(Task.FromException(new InvalidOperationException("The ticker failed.")))); + ScheduledJobSchedulerJob schedulerJob = CreateScheduledJobSchedulerJob(_ => mockCycleTicker); + + // Act + await InvokeOnAsync(schedulerJob, "RunCycleWorkerAsync", scheduledJobId, false, CancellationToken.None); + + // Assert + await _mockTaskExecutor.DidNotReceive().ExecutePayloadAsync(Arg.Any(), Arg.Any()); + Assert.False(_runtimeRegistry.HasActiveCycle(scheduledJobId)); + } + + [Fact] + public async Task CalculateDelayAsync_WhenCalledWithAnIntervalSchedule_ShouldReturnTheIntervalDelay() + { + // Arrange + IntervalSchedule intervalSchedule = _intervalScheduleFixture.Create(intervalMinutes: 30); + IDateTimeProvider mockDateTimeProvider = Substitute.For(); + mockDateTimeProvider.UtcNow.Returns(new DateTime(2026, 1, 1, 12, 0, 0, DateTimeKind.Utc)); + _services[typeof(IDateTimeProvider)] = mockDateTimeProvider; + + // Act + TimeSpan result = await InvokeAsync("CalculateDelayAsync", intervalSchedule); + + // Assert + Assert.Equal(TimeSpan.FromMinutes(30), result); + } + + [Fact] + public async Task GetScheduleAsync_WhenTheScheduledJobCannotBeConvertedToDomain_ShouldReturnNull() + { + // Arrange + // An interval schedule whose interval is not positive cannot be converted to its domain object. + ScheduledJobEntity invalidJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 0); + ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(invalidJob.Id); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(invalidJob); + + // Act + Schedule? result = await InvokeAsync("GetScheduleAsync", scheduledJobId, CancellationToken.None); + + // Assert + Assert.Null(result); + } + + /// + /// Registers a date time provider that returns a fixed UTC time in the services of the mocked scope. + /// + private void RegisterDateTimeProvider() + { + IDateTimeProvider mockDateTimeProvider = Substitute.For(); + mockDateTimeProvider.UtcNow.Returns(new DateTime(2026, 1, 1, 12, 0, 0, DateTimeKind.Utc)); + _services[typeof(IDateTimeProvider)] = mockDateTimeProvider; + } + + /// + /// Creates a new instance of the class whose cycle cadence is driven by the tickers created by . + /// + /// The factory that creates the ticker driving the cadence of an execution cycle. + /// The created scheduled job scheduler. + private ScheduledJobSchedulerJob CreateScheduledJobSchedulerJob(Func cycleTickerFactory) + { + ILogger logger = Substitute.For>(); + return new ScheduledJobSchedulerJob(_runtimeRegistry, logger, _mockServiceScopeFactory, cycleTickerFactory); + } + + /// + /// Invokes the private method named on and awaits its returned task. + /// + /// The scheduled job scheduler on which the private method is invoked. + /// The name of the private method to invoke. + /// The arguments of the method. + private static async Task InvokeOnAsync(ScheduledJobSchedulerJob schedulerJob, string methodName, params object?[] args) + { + Task task = (Task)GetPrivateMethod(methodName).Invoke(schedulerJob, args)!; + await task.ConfigureAwait(false); + } + + /// + /// Invokes the private method named and awaits its returned task. + /// + /// The name of the private method to invoke. + /// The arguments of the method. + private async Task InvokeAsync(string methodName, params object?[] args) + { + Task task = (Task)GetPrivateMethod(methodName).Invoke(_sut, args)!; + await task.ConfigureAwait(false); + } + + /// + /// Invokes the private method named and awaits its returned task of type . + /// + /// The name of the private method to invoke. + /// The arguments of the method. + /// The type of the value the task returns. + /// The value returned by the method. + private async Task InvokeAsync(string methodName, params object?[] args) + { + Task task = (Task)GetPrivateMethod(methodName).Invoke(_sut, args)!; + return await task.ConfigureAwait(false); + } + + /// + /// Gets the private instance method named . + /// + /// The name of the method. + /// The reflected method. + private static MethodInfo GetPrivateMethod(string methodName) + { + return typeof(ScheduledJobSchedulerJob).GetMethod(methodName, BindingFlags.Instance | BindingFlags.NonPublic) + ?? throw new InvalidOperationException($"The method '{methodName}' was not found on the scheduled job scheduler."); + } + + /// + /// Waits until the provided condition is met, or the timeout elapses. + /// + /// The condition to wait for. + /// A task that represents the asynchronous operation. + private static async Task WaitUntilAsync(Func condition) + { + int remainingAttempts = 200; + while (!condition() && remainingAttempts > 0) + { + remainingAttempts--; + await Task.Delay(10); + } } } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/ScheduledTaskExecutorFactoryTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/ScheduledTaskExecutorFactoryTests.cs index fba50ab4..075bace8 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/ScheduledTaskExecutorFactoryTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/ScheduledTaskExecutorFactoryTests.cs @@ -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; /// @@ -35,9 +38,19 @@ public class ScheduledTaskExecutorFactoryTests Substitute.For()); _mockTemporaryFilesCleanupTaskExecutor = Substitute.For( Substitute.For>()); + _mockRepairThemesTaskExecutor = Substitute.For( + Substitute.For(), + Substitute.For>(), + Substitute.For()); + _mockCleanScheduledJobExecutionHistoryTaskExecutor = Substitute.For( + Substitute.For(), + Substitute.For>(), + Substitute.For()); _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() { diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/CleanScheduledJobExecutionHistoryTaskExecutorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/CleanScheduledJobExecutionHistoryTaskExecutorTests.cs new file mode 100644 index 00000000..0cbb40d1 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/CleanScheduledJobExecutionHistoryTaskExecutorTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[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; + + /// + /// Initializes a new instance of the class. + /// + public CleanScheduledJobExecutionHistoryTaskExecutorTests() + { + _mockDateTimeProvider = Substitute.For(); + _mockUnitOfWork = Substitute.For(); + _mockScheduledJobExecutionRepository = Substitute.For(); + _mockDateTimeProvider.UtcNow.Returns(_fixedUtcNow); + _mockUnitOfWork.ScheduledJobExecutionRepository.Returns(_mockScheduledJobExecutionRepository); + ILogger logger = Substitute.For>(); + _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(), Arg.Any()).Returns(Result.Success); + DateTime expectedCutoff = _fixedUtcNow.AddMonths(-1); + + // Act + Result result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockScheduledJobExecutionRepository.Received(1).DeleteOlderThanAsync(Arg.Is(cutoff => cutoff == expectedCutoff), Arg.Any()); + } + + [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(), Arg.Any()).Returns(expectedError); + + // Act + Result result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(expectedError, result.FirstError); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/MediaLibraryScanTaskExecutorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/MediaLibraryScanTaskExecutorTests.cs index 2db98614..ed5ca893 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/MediaLibraryScanTaskExecutorTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/MediaLibraryScanTaskExecutorTests.cs @@ -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(); /// /// Initializes a new instance of the 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()) + .Returns(Result.From>([library])); + LibraryScanEntity runningScan = _libraryScanEntityFixture.Create(libraryId: library.Id, status: LibraryScanJobStatus.Running); + _mockUnitOfWork.LibraryScanRepository.GetPastMonthScansByLibraryIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>([runningScan])); + + // Act + Result result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ExecutePayloadAsync_WhenAQueuedScanIsInserted_ShouldPublishItsDomainEvents() + { + // Arrange + ScheduledJob scheduledJob = _scheduledJobFixture.Create(); + LibraryEntity library = _libraryEntityFixture.Create(); + _mockLibraryRepository.GetAllEnabledAndUnlockedAsync(Arg.Any()) + .Returns(Result.From>([library])); + _mockUnitOfWork.LibraryScanRepository.GetPastMonthScansByLibraryIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>([])); + _mockUnitOfWork.LibraryScanRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + + // Act + Result result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockUnitOfWork.LibraryScanRepository.Received(1).InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ExecutePayloadAsync_WhenInsertingTheQueuedScanFails_ShouldReturnError() + { + // Arrange + ScheduledJob scheduledJob = _scheduledJobFixture.Create(); + LibraryEntity library = _libraryEntityFixture.Create(); + _mockLibraryRepository.GetAllEnabledAndUnlockedAsync(Arg.Any()) + .Returns(Result.From>([library])); + _mockUnitOfWork.LibraryScanRepository.GetPastMonthScansByLibraryIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>([])); + Error error = Error.Failure("Database.Error", "Failed to insert the scan"); + _mockUnitOfWork.LibraryScanRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Any(), Arg.Any()); + } } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/RepairThemesTaskExecutorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/RepairThemesTaskExecutorTests.cs new file mode 100644 index 00000000..fc7632b1 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/RepairThemesTaskExecutorTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[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(); + + /// + /// Initializes a new instance of the class. + /// + public RepairThemesTaskExecutorTests() + { + _mockThemeService = Substitute.For(); + _mockUnitOfWork = Substitute.For(); + _mockThemeRepository = Substitute.For(); + _mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + ILogger logger = Substitute.For>(); + _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()).Returns(Result.From(Enumerable.Empty())); + + // Act + Result result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockThemeRepository.Received(1).GetAllAsync(Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task ExecutePayloadAsync_WhenABundledThemeArchiveCannotBeRead_ShouldStillSucceed() + { + // Arrange + ScheduledJob scheduledJob = _scheduledJobFixture.Create(taskType: ScheduledTaskType.RepairThemes); + _mockThemeService.GetBundledThemeArchivePaths().Returns(["missing.zip"]); + _mockThemeService.ReadManifestFromArchiveAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Theme.Manifest", "Failed to read the theme manifest")); + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From(Enumerable.Empty())); + + // Act + Result result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockThemeRepository.Received(1).GetAllAsync(Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task ExecutePayloadAsync_WhenTheSynchronizationThrows_ShouldReturnFailure() + { + // Arrange + ScheduledJob scheduledJob = _scheduledJobFixture.Create(taskType: ScheduledTaskType.RepairThemes); + _mockThemeRepository.GetAllAsync(Arg.Any()) + .Returns(Task.FromException>>(new InvalidOperationException("The database is unavailable."))); + + // Act + Result 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()) + .Returns(Task.FromException>>(new OperationCanceledException())); + + // Act + async Task Act() + { + await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeSynchronizerTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeSynchronizerTests.cs new file mode 100644 index 00000000..af45a663 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeSynchronizerTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[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; + + /// + /// Initializes a new instance of the class. + /// + public ThemeSynchronizerTests() + { + _mockThemeService = Substitute.For(); + _mockUnitOfWork = Substitute.For(); + _mockThemeRepository = Substitute.For(); + _mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockLogger = Substitute.For(); + _mockThemeService.GetBundledThemeArchivePaths().Returns([]); + _mockThemeService.HasThemePack(Arg.Any()).Returns(true); + _mockThemeService.DefaultThemeId.Returns("lumina-default"); + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From(Enumerable.Empty())); + _mockThemeRepository.InsertAsync(Arg.Any(), Arg.Any()).Returns(Result.Created); + _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.Updated); + _mockThemeRepository.DeleteByIdAsync(Arg.Any(), Arg.Any()).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()) + .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(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task SynchronizeAsync_WhenABundledArchiveManifestCannotBeRead_ShouldSkipThatArchive() + { + // Arrange + _mockThemeService.GetBundledThemeArchivePaths().Returns(["missing.zip"]); + _mockThemeService.ReadManifestFromArchiveAsync("missing.zip", Arg.Any()) + .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(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [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()).Returns(new[] { installedTheme }); + _mockThemeService.GetBundledThemeArchivePaths().Returns(["bundled.zip"]); + _mockThemeService.ReadManifestFromArchiveAsync("bundled.zip", Arg.Any()).Returns(Result.From(manifest)); + + // Act + await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None); + + // Assert + await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any(), Arg.Any()); + await _mockThemeRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + } + + [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()).Returns(new[] { deletedTheme }); + _mockThemeService.GetBundledThemeArchivePaths().Returns(["bundled.zip"]); + _mockThemeService.ReadManifestFromArchiveAsync("bundled.zip", Arg.Any()).Returns(Result.From(manifest)); + + // Act + await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None); + + // Assert + await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any(), Arg.Any()); + await _mockThemeRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + } + + [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()).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()).Returns(Result.From(manifest)); + _mockThemeService.InstallAsync(Arg.Any(), Arg.Any()).Returns(Result.From(manifest)); + + // Act + await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None); + + // Assert + await _mockThemeService.Received(1).InstallAsync(Arg.Any(), Arg.Any()); + await _mockThemeRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + } + + [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()).Returns(new[] { damagedTheme }); + string archivePath = CreateArchiveFile(); + _mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]); + _mockThemeService.HasThemePack(damagedTheme.ThemeId).Returns(false, true); + _mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any()).Returns(Result.From(manifest)); + _mockThemeService.InstallAsync(Arg.Any(), Arg.Any()) + .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(), Arg.Any()); + await _mockThemeRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task SynchronizeAsync_WhenANewBundledThemeIsInstalled_ShouldInsertTheThemeRow() + { + // Arrange + ThemeManifestDto manifest = _themeManifestDtoFixture.Create(); + string archivePath = CreateArchiveFile(); + _mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]); + _mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any()).Returns(Result.From(manifest)); + _mockThemeService.InstallAsync(Arg.Any(), Arg.Any()).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(theme => theme.ThemeId == manifest.Id && theme.InstallSource == ThemeInstallSource.Bundled), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task SynchronizeAsync_WhenPersistingANewBundledThemeFails_ShouldLogAndContinue() + { + // Arrange + ThemeManifestDto manifest = _themeManifestDtoFixture.Create(); + string archivePath = CreateArchiveFile(); + _mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]); + _mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any()).Returns(Result.From(manifest)); + _mockThemeService.InstallAsync(Arg.Any(), Arg.Any()).Returns(Result.From(manifest)); + _mockThemeService.HasThemePack(manifest.Id).Returns(true); + _mockThemeRepository.InsertAsync(Arg.Any(), Arg.Any()) + .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(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [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()).Returns(Result.From(manifest)); + + // Act + await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None); + + // Assert + await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [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()).Returns(Result.From(manifest)); + + // Act + await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None); + + // Assert + await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [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()).Returns(new[] { healthyTheme }); + + // Act + await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None); + + // Assert + await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [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()).Returns(new[] { brokenTheme }); + _mockThemeService.HasThemePack(brokenTheme.ThemeId).Returns(false); + _mockThemeService.RestoreBundledThemeAsync(brokenTheme.ThemeId, Arg.Any()).Returns(Result.Success); + + // Act + await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None); + + // Assert + await _mockThemeService.Received(1).RestoreBundledThemeAsync(brokenTheme.ThemeId, Arg.Any()); + await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockThemeRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + } + + [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()).Returns(new[] { lastBundledTheme }); + _mockThemeService.HasThemePack(lastBundledTheme.ThemeId).Returns(false); + _mockThemeService.RestoreBundledThemeAsync(lastBundledTheme.ThemeId, Arg.Any()) + .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(), Arg.Any()); + } + + [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()).Returns(new[] { brokenBundledTheme, healthyBundledTheme }); + _mockThemeService.HasThemePack(brokenBundledTheme.ThemeId).Returns(false); + _mockThemeService.RestoreBundledThemeAsync(brokenBundledTheme.ThemeId, Arg.Any()) + .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(theme => theme.Id == brokenBundledTheme.Id), Arg.Any()); + await _mockThemeRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + } + + [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()).Returns(new[] { brokenBundledTheme, healthyBundledTheme }); + _mockThemeService.HasThemePack(brokenBundledTheme.ThemeId).Returns(false); + _mockThemeService.RestoreBundledThemeAsync(brokenBundledTheme.ThemeId, Arg.Any()) + .Returns(Error.Failure("Theme.Restore", "Failed to restore the theme")); + _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .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(theme => theme.Id == brokenBundledTheme.Id), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [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()).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()); + } + + [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()).Returns(new[] { brokenUserTheme }); + _mockThemeService.HasThemePack(brokenUserTheme.ThemeId).Returns(false); + _mockThemeRepository.DeleteByIdAsync(Arg.Any(), Arg.Any()) + .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()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [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()).Returns(new[] { throwingBundledTheme, healthyBundledTheme }); + _mockThemeService.HasThemePack(Arg.Any()).Returns(false); + _mockThemeService.RestoreBundledThemeAsync(throwingBundledTheme.ThemeId, Arg.Any()) + .Returns(Task.FromException>(new InvalidOperationException("Unexpected failure"))); + _mockThemeService.RestoreBundledThemeAsync(healthyBundledTheme.ThemeId, Arg.Any()) + .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(theme => theme.Id == healthyBundledTheme.Id), Arg.Any()); + } + + [Fact] + public async Task SynchronizeAsync_WhenRepairingABrokenThemeIsCancelled_ShouldRethrowTheCancellation() + { + // Arrange + ThemeEntity brokenBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false); + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(new[] { brokenBundledTheme }); + _mockThemeService.HasThemePack(brokenBundledTheme.ThemeId).Returns(false); + _mockThemeService.RestoreBundledThemeAsync(brokenBundledTheme.ThemeId, Arg.Any()) + .Returns(Task.FromException>(new OperationCanceledException())); + + // Act + async Task Act() + { + await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(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(), Arg.Any()); + } + + [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(), Arg.Any()); + } + + [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(theme => theme.Id == defaultTheme.Id), Arg.Any()); + } + + /// + /// Creates a real archive file on disk so that can open it. + /// + /// The path of the created archive file. + private string CreateArchiveFile() + { + string archivePath = Path.Combine(_temporaryDirectoryPath, $"theme-{Guid.NewGuid():N}.zip"); + File.WriteAllText(archivePath, "theme-pack"); + return archivePath; + } + + /// + /// Invokes the private EnsureCurrentThemeExistsAsync method of the synchronizer. + /// + /// The installed themes passed to the method. + /// A task that represents the asynchronous operation. + private async Task InvokeEnsureCurrentThemeExistsAsync(IReadOnlyList 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); + } + + /// + /// Removes the temporary files created by the tests. + /// + public void Dispose() + { + if (Directory.Exists(_temporaryDirectoryPath)) + Directory.Delete(_temporaryDirectoryPath, recursive: true); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/AddScheduledJob/AddScheduledJobEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/AddScheduledJob/AddScheduledJobEndpointTests.cs new file mode 100644 index 00000000..ffeedd01 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/AddScheduledJob/AddScheduledJobEndpointTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddScheduledJobEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly AddScheduledJobEndpoint _sut; + private readonly AddScheduledJobRequestFixture _addScheduledJobRequestFixture = new(); + private readonly ScheduledJobDtoFixture _scheduledJobDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public AddScheduledJobEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenApiReturnsCreatedJob_ShouldReturnSuccessJsonWithCreatedJob() + { + // Arrange + AddScheduledJobRequest request = _addScheduledJobRequestFixture.Create(); + ScheduledJobDto expectedJob = _scheduledJobDtoFixture.Create(name: request.Name); + _mockApiHttpClient.PostAsync(ApiRoutes.ScheduledJobs.ADD_SCHEDULED_JOB, Arg.Any(), Arg.Any()) + .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(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_scheduledJobDtoFixture.Create()); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + ApiRoutes.ScheduledJobs.ADD_SCHEDULED_JOB, + Arg.Is(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()); + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpointTests.cs new file mode 100644 index 00000000..b79ee921 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpointTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class FireScheduledJobEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly FireScheduledJobEndpoint _sut; + private readonly FireScheduledJobRequestFixture _fireScheduledJobRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public FireScheduledJobEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_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( + expectedEndpoint, + Arg.Any(), + Arg.Any()); + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobHistory/GetScheduledJobHistoryEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobHistory/GetScheduledJobHistoryEndpointTests.cs new file mode 100644 index 00000000..d9f26ac3 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobHistory/GetScheduledJobHistoryEndpointTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetScheduledJobHistoryEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly GetScheduledJobHistoryEndpoint _sut; + private readonly GetScheduledJobHistoryRequestFixture _getScheduledJobHistoryRequestFixture = new(); + private readonly ScheduledJobExecutionDtoFixture _scheduledJobExecutionDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetScheduledJobHistoryEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenApiReturnsExecutions_ShouldReturnSuccessJsonWithExecutions() + { + // Arrange + ScheduledJobExecutionDto[] expectedExecutions = [.. _scheduledJobExecutionDtoFixture.CreateMany(2)]; + _mockApiHttpClient.GetAsync(ApiRoutes.ScheduledJobs.GET_SCHEDULED_JOB_HISTORY, Arg.Any()) + .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(ApiRoutes.ScheduledJobs.GET_SCHEDULED_JOB_HISTORY, Arg.Any()) + .Returns([]); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync(ApiRoutes.ScheduledJobs.GET_SCHEDULED_JOB_HISTORY, Arg.Any()); + } + + [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(expectedEndpoint, Arg.Any()) + .Returns([]); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync(expectedEndpoint, Arg.Any()); + } + + [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(expectedEndpoint, Arg.Any()) + .Returns([]); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync(expectedEndpoint, Arg.Any()); + } + + [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(expectedEndpoint, Arg.Any()) + .Returns([]); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync(expectedEndpoint, Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobs/GetScheduledJobsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobs/GetScheduledJobsEndpointTests.cs new file mode 100644 index 00000000..7f7b8997 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/GetScheduledJobs/GetScheduledJobsEndpointTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetScheduledJobsEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly GetScheduledJobsEndpoint _sut; + private readonly ScheduledJobDtoFixture _scheduledJobDtoFixture = new(); + private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true }; + + /// + /// Initializes a new instance of the class. + /// + public GetScheduledJobsEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenApiReturnsJobs_ShouldReturnSuccessJsonWithScheduledJobs() + { + // Arrange + ScheduledJobDto[] expectedJobs = [.. _scheduledJobDtoFixture.CreateMany(2)]; + _mockApiHttpClient.GetAsync(ApiRoutes.ScheduledJobs.GET_SCHEDULED_JOBS, Arg.Any()) + .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(_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(ApiRoutes.ScheduledJobs.GET_SCHEDULED_JOBS, Arg.Any()) + .Returns([.. _scheduledJobDtoFixture.CreateMany()]); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync(ApiRoutes.ScheduledJobs.GET_SCHEDULED_JOBS, Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesEndpointTests.cs new file mode 100644 index 00000000..f264f66c --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesEndpointTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetSchedulerDisplayPreferencesEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly GetSchedulerDisplayPreferencesEndpoint _sut; + private readonly SchedulerDisplayPreferencesDtoFixture _schedulerDisplayPreferencesDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetSchedulerDisplayPreferencesEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenApiReturnsPreferences_ShouldReturnSuccessJsonWithDisplayPreferences() + { + // Arrange + SchedulerDisplayPreferencesDto expectedPreferences = _schedulerDisplayPreferencesDtoFixture.Create(displayTimeUnit: Lumina.Presentation.Web.Common.Enums.Scheduling.SchedulerDisplayTimeUnit.Minutes); + _mockApiHttpClient.GetAsync(ApiRoutes.ScheduledJobs.GET_DISPLAY_PREFERENCES, Arg.Any()) + .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(ApiRoutes.ScheduledJobs.GET_DISPLAY_PREFERENCES, Arg.Any()) + .Returns(_schedulerDisplayPreferencesDtoFixture.Create()); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync(ApiRoutes.ScheduledJobs.GET_DISPLAY_PREFERENCES, Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/RemoveScheduledJob/RemoveScheduledJobEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/RemoveScheduledJob/RemoveScheduledJobEndpointTests.cs new file mode 100644 index 00000000..4958c2a2 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/RemoveScheduledJob/RemoveScheduledJobEndpointTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RemoveScheduledJobEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly RemoveScheduledJobEndpoint _sut; + private readonly RemoveScheduledJobRequestFixture _removeScheduledJobRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public RemoveScheduledJobEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_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()); + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/SchedulerIndexViewEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/SchedulerIndexViewEndpointTests.cs new file mode 100644 index 00000000..3045a4cd --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/SchedulerIndexViewEndpointTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SchedulerIndexViewEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly IAntiforgery _mockAntiforgery; + private readonly IOptionsSnapshot _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(); + + /// + /// Initializes a new instance of the class. + /// + public SchedulerIndexViewEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _mockAntiforgery = Substitute.For(); + _mockAntiforgery.GetAndStoreTokens(Arg.Any()) + .Returns(new AntiforgeryTokenSet("test-request-token", "test-cookie-token", "__RequestVerificationToken", "RequestVerificationToken")); + _mockServerConfigurationOptions = Substitute.For>(); + _mockServerConfigurationOptions.Value.Returns(_serverConfigurationDtoFixture.Create(baseAddress: "http://localhost", port: 5214)); + _mockUrlService = Substitute.For(); + _mockThemePageRenderer = Substitute.For(new ThemeService(_mockApiHttpClient), new ThemeTemplateEngine()); + _mockStringLocalizer = Substitute.For(); + _mockStringLocalizer[Arg.Any()].Returns(callInfo => new LocalizedString(callInfo.Arg(), callInfo.Arg())); + _mockStringLocalizer.GetAllStrings(Arg.Any()).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(); + _mockStringLocalizerFactory.Create(Arg.Any(), Arg.Any()).Returns(_mockStringLocalizer); + _sut = Factory.Create(_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(), Arg.Any(), Arg.Any()) + .Returns(Result.From(_themePageRenderResultDtoFixture.Create(content: "
content
", script: ""))); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + Assert.IsType(result); + await _mockThemePageRenderer.Received(1).RenderAsync( + Arg.Is(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(requestedThemeId => requestedThemeId == null), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenThemeRenderingFails_ShouldFallBackToRazorView() + { + // Arrange + _mockThemePageRenderer.RenderAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.Failure(Error.Failure("Theme.Render", "The page could not be rendered."))); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + Assert.IsType(result); + await _mockThemePageRenderer.Received(1).RenderAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [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()).Returns("http://localhost/en-us/admin/api-scheduled-jobs/00000000-0000-0000-0000-000000000000/start"); + _mockThemePageRenderer.RenderAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .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(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(), + Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpointTests.cs new file mode 100644 index 00000000..0d2baa18 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpointTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class StartScheduledJobEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly StartScheduledJobEndpoint _sut; + private readonly StartScheduledJobRequestFixture _startScheduledJobRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public StartScheduledJobEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_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( + expectedEndpoint, + Arg.Any(), + Arg.Any()); + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpointTests.cs new file mode 100644 index 00000000..df66d913 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpointTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class StopScheduledJobEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly StopScheduledJobEndpoint _sut; + private readonly StopScheduledJobRequestFixture _stopScheduledJobRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public StopScheduledJobEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_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( + expectedEndpoint, + Arg.Any(), + Arg.Any()); + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpointTests.cs new file mode 100644 index 00000000..c956a614 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpointTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateSchedulerDisplayPreferencesEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly UpdateSchedulerDisplayPreferencesEndpoint _sut; + private readonly UpdateSchedulerDisplayPreferencesRequestFixture _updateSchedulerDisplayPreferencesRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public UpdateSchedulerDisplayPreferencesEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_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( + ApiRoutes.ScheduledJobs.UPDATE_DISPLAY_PREFERENCES, + Arg.Is(forwardedRequest => + forwardedRequest.JobTypeFilter == request.JobTypeFilter && + forwardedRequest.DisplayTimeSpan == request.DisplayTimeSpan && + forwardedRequest.DisplayTimeUnit == request.DisplayTimeUnit), + Arg.Any()); + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + } +}