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