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

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

No files matched your search

@@ -0,0 +1,32 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.Core.Scheduling.Execution;
/// <summary>
/// Represents a cancellable periodic ticker that drives the cadence of an execution cycle of a scheduled job.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
internal interface IScheduledJobCycleTicker : IDisposable
{
/// <summary>
/// Sets the period between the ticks of the ticker.
/// </summary>
/// <remarks>
/// The period of a daily schedule is recalculated after every run from the current time, so it is assigned after each tick.
/// </remarks>
TimeSpan Period { set; }
/// <summary>
/// Waits until the next tick of the ticker, or until the ticker is disposed or <paramref name="cancellationToken"/> is cancelled.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the wait.</param>
/// <returns><see langword="true"/> when a tick occurred; <see langword="false"/> when the ticker was disposed before the next tick.</returns>
ValueTask<bool> WaitForNextTickAsync(CancellationToken cancellationToken);
}
@@ -0,0 +1,53 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.Core.Scheduling.Execution;
/// <summary>
/// Default <see cref="IScheduledJobCycleTicker"/> implementation that ticks on a <see cref="PeriodicTimer"/>.
/// </summary>
internal sealed class PeriodicScheduledJobCycleTicker : IScheduledJobCycleTicker
{
private readonly PeriodicTimer _periodicTimer;
/// <summary>
/// Initializes a new instance of the <see cref="PeriodicScheduledJobCycleTicker"/> class.
/// </summary>
/// <param name="period">The period between the ticks of the ticker.</param>
public PeriodicScheduledJobCycleTicker(TimeSpan period)
{
_periodicTimer = new PeriodicTimer(period);
}
/// <summary>
/// Sets the period between the ticks of the ticker.
/// </summary>
public TimeSpan Period
{
set
{
_periodicTimer.Period = value;
}
}
/// <summary>
/// Waits until the next tick of the ticker, or until the ticker is disposed or <paramref name="cancellationToken"/> is cancelled.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the wait.</param>
/// <returns><see langword="true"/> when a tick occurred; <see langword="false"/> when the ticker was disposed before the next tick.</returns>
public ValueTask<bool> WaitForNextTickAsync(CancellationToken cancellationToken)
{
return _periodicTimer.WaitForNextTickAsync(cancellationToken);
}
/// <summary>
/// Disposes the periodic timer owned by the ticker.
/// </summary>
public void Dispose()
{
_periodicTimer.Dispose();
}
}
@@ -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<ScheduledJobSchedulerJob> _logger;
private readonly Func<TimeSpan, IScheduledJobCycleTicker> _cycleTickerFactory;
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledJobSchedulerJob"/> class.
@@ -37,10 +41,23 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
/// <param name="logger">Injected service for logging.</param>
/// <param name="serviceScopeFactory">Injected factory used for creating scopes in which services are requested.</param>
public ScheduledJobSchedulerJob(IScheduledJobRuntimeRegistry runtimeRegistry, ILogger<ScheduledJobSchedulerJob> logger, IServiceScopeFactory serviceScopeFactory)
: this(runtimeRegistry, logger, serviceScopeFactory, period => new PeriodicScheduledJobCycleTicker(period))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledJobSchedulerJob"/> class with a custom cycle ticker factory.
/// </summary>
/// <param name="runtimeRegistry">Injected registry that holds the live runtime state of the scheduled jobs.</param>
/// <param name="logger">Injected service for logging.</param>
/// <param name="serviceScopeFactory">Injected factory used for creating scopes in which services are requested.</param>
/// <param name="cycleTickerFactory">Factory that creates the ticker driving the cadence of an execution cycle, for which the unit tests substitute a stubbed ticker.</param>
internal ScheduledJobSchedulerJob(IScheduledJobRuntimeRegistry runtimeRegistry, ILogger<ScheduledJobSchedulerJob> logger, IServiceScopeFactory serviceScopeFactory, Func<TimeSpan, IScheduledJobCycleTicker> cycleTickerFactory)
{
_serviceScopeFactory = serviceScopeFactory;
_runtimeRegistry = runtimeRegistry;
_logger = logger;
_cycleTickerFactory = cycleTickerFactory;
}
/// <summary>
@@ -85,6 +102,7 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
/// <param name="stoppingToken">Cancellation token that can be used to stop the execution.</param>
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) { }
}
/// <summary>
/// Installs and repairs the bundled themes at startup, but only when no active "Repair themes at startup" scheduled job will do it.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <remarks>
/// 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.
/// </remarks>
private async Task SynchronizeBundledThemesIfNeededAsync(CancellationToken cancellationToken)
{
try
{
await using AsyncServiceScope scope = _serviceScopeFactory.CreateAsyncScope();
IUnitOfWork unitOfWork = scope.ServiceProvider.GetRequiredService<IUnitOfWork>();
Result<IEnumerable<ScheduledJobEntity>> 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<IThemeService>();
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.");
}
}
/// <summary>
/// Resumes the execution cycles of the scheduled jobs whose cycle was active when the application shut down.
/// </summary>
@@ -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)
@@ -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;
/// <summary>
/// Fixture class for generating <see cref="ScheduledJobDto"/> test data.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScheduledJobDtoFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a new <see cref="ScheduledJobDto"/> instance with randomized test data.
/// </summary>
/// <param name="id">Optional unique identifier of the scheduled job.</param>
/// <param name="name">Optional name of the scheduled job.</param>
/// <param name="taskType">Optional type of the task executed by the scheduled job.</param>
/// <param name="scheduleType">Optional type of the schedule of the scheduled job.</param>
/// <param name="intervalMinutes">Optional interval in minutes of the schedule of the scheduled job.</param>
/// <param name="hour">Optional hour of the schedule of the scheduled job.</param>
/// <param name="minute">Optional minute of the schedule of the scheduled job.</param>
/// <param name="status">Optional status of the scheduled job.</param>
/// <param name="lastStartedOnUtc">Optional date and time when the task of the scheduled job last started its execution.</param>
/// <param name="lastCompletedOnUtc">Optional date and time when the task of the scheduled job last completed its execution.</param>
/// <returns>A configured <see cref="ScheduledJobDto"/> instance.</returns>
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<ScheduleType>();
DateTime? resolvedLastCompletedOnUtc = lastCompletedOnUtc ?? _faker.Date.Recent(10);
return new ScheduledJobDto(
Id: id ?? Guid.NewGuid(),
Name: name ?? _faker.Name.JobTitle(),
TaskType: taskType ?? _faker.PickRandom<ScheduledTaskType>(),
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<ScheduledJobStatus>(),
LastStartedOnUtc: lastStartedOnUtc ?? _faker.Date.Recent(10),
LastCompletedOnUtc: resolvedLastCompletedOnUtc);
}
/// <summary>
/// Creates multiple <see cref="ScheduledJobDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="ScheduledJobDto"/> instances.</returns>
public List<ScheduledJobDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for generating <see cref="ScheduledJobExecutionDto"/> test data.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScheduledJobExecutionDtoFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a new <see cref="ScheduledJobExecutionDto"/> instance with randomized test data.
/// </summary>
/// <param name="id">Optional unique identifier of the execution.</param>
/// <param name="scheduledJobId">Optional unique identifier of the scheduled job whose task was executed.</param>
/// <param name="taskType">Optional type of the task that was executed.</param>
/// <param name="isCycleRun">Optional value indicating whether the execution was triggered by the execution cycle of the scheduled job.</param>
/// <param name="startedOnUtc">Optional date and time when the execution started.</param>
/// <param name="completedOnUtc">Optional date and time when the execution completed.</param>
/// <returns>A configured <see cref="ScheduledJobExecutionDto"/> instance.</returns>
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<ScheduledTaskType>(),
IsCycleRun: isCycleRun ?? _faker.Random.Bool(),
StartedOnUtc: resolvedStartedOnUtc,
CompletedOnUtc: completedOnUtc ?? _faker.Date.Soon(1, resolvedStartedOnUtc));
}
/// <summary>
/// Creates multiple <see cref="ScheduledJobExecutionDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="ScheduledJobExecutionDto"/> instances.</returns>
public List<ScheduledJobExecutionDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for generating <see cref="SchedulerDisplayPreferencesDto"/> test data.
/// </summary>
[ExcludeFromCodeCoverage]
public class SchedulerDisplayPreferencesDtoFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a new <see cref="SchedulerDisplayPreferencesDto"/> instance with randomized test data.
/// </summary>
/// <param name="userId">Optional unique identifier of the user that owns the display preferences.</param>
/// <param name="jobTypeFilter">Optional type of the scheduled job tasks whose executions are shown on the scheduler page.</param>
/// <param name="displayTimeSpan">Optional time span, expressed in <paramref name="displayTimeUnit"/>, that the scheduler page shows.</param>
/// <param name="displayTimeUnit">Optional unit in which the displayed time span of the scheduler page is expressed.</param>
/// <returns>A configured <see cref="SchedulerDisplayPreferencesDto"/> instance.</returns>
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<SchedulerDisplayTimeUnit>());
}
/// <summary>
/// Creates multiple <see cref="SchedulerDisplayPreferencesDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="SchedulerDisplayPreferencesDto"/> instances.</returns>
public List<SchedulerDisplayPreferencesDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for generating <see cref="AddScheduledJobRequest"/> test data.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddScheduledJobRequestFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a new <see cref="AddScheduledJobRequest"/> instance with randomized test data.
/// </summary>
/// <param name="name">Optional name of the scheduled job.</param>
/// <param name="taskType">Optional type of the task executed by the scheduled job.</param>
/// <param name="scheduleType">Optional type of the schedule of the scheduled job.</param>
/// <param name="intervalMinutes">Optional interval in minutes of the schedule, when the schedule type is <see cref="ScheduleType.WithIntervalInMinutes"/>.</param>
/// <param name="hour">Optional hour of the schedule, when the schedule type is <see cref="ScheduleType.DailyAtHourAndMinute"/>.</param>
/// <param name="minute">Optional minute of the schedule, when the schedule type is <see cref="ScheduleType.DailyAtHourAndMinute"/>.</param>
/// <returns>A configured <see cref="AddScheduledJobRequest"/> instance.</returns>
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<ScheduleType>();
return new AddScheduledJobRequest(
Name: name ?? _faker.Name.JobTitle(),
TaskType: taskType ?? _faker.PickRandom<ScheduledTaskType>(),
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));
}
/// <summary>
/// Creates multiple <see cref="AddScheduledJobRequest"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="AddScheduledJobRequest"/> instances.</returns>
public List<AddScheduledJobRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for generating <see cref="FireScheduledJobRequest"/> test data.
/// </summary>
[ExcludeFromCodeCoverage]
public class FireScheduledJobRequestFixture
{
/// <summary>
/// Creates a new <see cref="FireScheduledJobRequest"/> instance with randomized test data.
/// </summary>
/// <param name="scheduledJobId">Optional unique identifier of the scheduled job whose task is fired.</param>
/// <returns>A configured <see cref="FireScheduledJobRequest"/> instance.</returns>
public FireScheduledJobRequest Create(
Guid? scheduledJobId = null)
{
return new FireScheduledJobRequest(
ScheduledJobId: scheduledJobId ?? Guid.NewGuid()
);
}
/// <summary>
/// Creates multiple <see cref="FireScheduledJobRequest"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="FireScheduledJobRequest"/> instances.</returns>
public List<FireScheduledJobRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for generating <see cref="GetScheduledJobHistoryRequest"/> test data.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetScheduledJobHistoryRequestFixture
{
/// <summary>
/// Creates a new <see cref="GetScheduledJobHistoryRequest"/> instance.
/// </summary>
/// <param name="from">Optional inclusive lower bound of the interval for which the history is requested.</param>
/// <param name="to">Optional inclusive upper bound of the interval for which the history is requested.</param>
/// <returns>A configured <see cref="GetScheduledJobHistoryRequest"/> instance.</returns>
public GetScheduledJobHistoryRequest Create(
DateTime? from = null,
DateTime? to = null)
{
return new GetScheduledJobHistoryRequest(
From: from,
To: to
);
}
/// <summary>
/// Creates multiple <see cref="GetScheduledJobHistoryRequest"/> instances.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="GetScheduledJobHistoryRequest"/> instances.</returns>
public List<GetScheduledJobHistoryRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for generating <see cref="RemoveScheduledJobRequest"/> test data.
/// </summary>
[ExcludeFromCodeCoverage]
public class RemoveScheduledJobRequestFixture
{
/// <summary>
/// Creates a new <see cref="RemoveScheduledJobRequest"/> instance with randomized test data.
/// </summary>
/// <param name="scheduledJobId">Optional unique identifier of the scheduled job to remove.</param>
/// <returns>A configured <see cref="RemoveScheduledJobRequest"/> instance.</returns>
public RemoveScheduledJobRequest Create(
Guid? scheduledJobId = null)
{
return new RemoveScheduledJobRequest(
ScheduledJobId: scheduledJobId ?? Guid.NewGuid()
);
}
/// <summary>
/// Creates multiple <see cref="RemoveScheduledJobRequest"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="RemoveScheduledJobRequest"/> instances.</returns>
public List<RemoveScheduledJobRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for generating <see cref="StartScheduledJobRequest"/> test data.
/// </summary>
[ExcludeFromCodeCoverage]
public class StartScheduledJobRequestFixture
{
/// <summary>
/// Creates a new <see cref="StartScheduledJobRequest"/> instance with randomized test data.
/// </summary>
/// <param name="scheduledJobId">Optional unique identifier of the scheduled job whose execution cycle is started.</param>
/// <returns>A configured <see cref="StartScheduledJobRequest"/> instance.</returns>
public StartScheduledJobRequest Create(
Guid? scheduledJobId = null)
{
return new StartScheduledJobRequest(
ScheduledJobId: scheduledJobId ?? Guid.NewGuid()
);
}
/// <summary>
/// Creates multiple <see cref="StartScheduledJobRequest"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="StartScheduledJobRequest"/> instances.</returns>
public List<StartScheduledJobRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for generating <see cref="StopScheduledJobRequest"/> test data.
/// </summary>
[ExcludeFromCodeCoverage]
public class StopScheduledJobRequestFixture
{
/// <summary>
/// Creates a new <see cref="StopScheduledJobRequest"/> instance with randomized test data.
/// </summary>
/// <param name="scheduledJobId">Optional unique identifier of the scheduled job whose execution cycle is stopped.</param>
/// <returns>A configured <see cref="StopScheduledJobRequest"/> instance.</returns>
public StopScheduledJobRequest Create(
Guid? scheduledJobId = null)
{
return new StopScheduledJobRequest(
ScheduledJobId: scheduledJobId ?? Guid.NewGuid()
);
}
/// <summary>
/// Creates multiple <see cref="StopScheduledJobRequest"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="StopScheduledJobRequest"/> instances.</returns>
public List<StopScheduledJobRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for generating <see cref="UpdateSchedulerDisplayPreferencesRequest"/> test data.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateSchedulerDisplayPreferencesRequestFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a new <see cref="UpdateSchedulerDisplayPreferencesRequest"/> instance with randomized test data.
/// </summary>
/// <param name="jobTypeFilter">Optional type of the scheduled job tasks whose executions are shown on the scheduler page.</param>
/// <param name="displayTimeSpan">Optional time span, expressed in <paramref name="displayTimeUnit"/>, that the scheduler page shows.</param>
/// <param name="displayTimeUnit">Optional unit in which the displayed time span of the scheduler page is expressed.</param>
/// <returns>A configured <see cref="UpdateSchedulerDisplayPreferencesRequest"/> instance.</returns>
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<SchedulerDisplayTimeUnit>());
}
/// <summary>
/// Creates multiple <see cref="UpdateSchedulerDisplayPreferencesRequest"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="UpdateSchedulerDisplayPreferencesRequest"/> instances.</returns>
public List<UpdateSchedulerDisplayPreferencesRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="ScheduledJobExecutionRepository"/> class, exercising it against a real SQLite database.
/// </summary>
[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<LuminaDbContext>().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<Success> 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<LuminaDbContext>().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<Success> result = await sut.DeleteOlderThanAsync(cutoffUtc, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(1, await context.ScheduledJobExecutions.CountAsync());
}
}
@@ -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]
@@ -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;
/// <summary>
/// Contains integration tests for the <c>/{culture}/admin/api-scheduled-jobs/add</c> route served by the <see cref="AddScheduledJobEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddScheduledJobEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
private readonly AddScheduledJobRequestFixture _addScheduledJobRequestFixture = new();
private readonly ScheduledJobDtoFixture _scheduledJobDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="AddScheduledJobEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
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");
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <c>/{culture}/admin/api-scheduled-jobs/{scheduledJobId}/fire</c> route served by the <see cref="FireScheduledJobEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class FireScheduledJobEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
private readonly FireScheduledJobRequestFixture _fireScheduledJobRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="FireScheduledJobEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
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);
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <c>/{culture}/admin/api-scheduled-jobs/history</c> route served by the <see cref="GetScheduledJobHistoryEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetScheduledJobHistoryEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
private readonly ScheduledJobExecutionDtoFixture _scheduledJobExecutionDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetScheduledJobHistoryEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
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");
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <c>/{culture}/admin/api-scheduled-jobs</c> route served by the <see cref="GetScheduledJobsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetScheduledJobsEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
private readonly ScheduledJobDtoFixture _scheduledJobDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetScheduledJobsEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
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");
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <c>/{culture}/admin/api-scheduled-jobs/display-preferences</c> route served by the <see cref="GetSchedulerDisplayPreferencesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetSchedulerDisplayPreferencesEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
private readonly SchedulerDisplayPreferencesDtoFixture _schedulerDisplayPreferencesDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetSchedulerDisplayPreferencesEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
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");
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <c>/{culture}/admin/api-scheduled-jobs/{scheduledJobId}</c> route served by the <see cref="RemoveScheduledJobEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RemoveScheduledJobEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
private readonly RemoveScheduledJobRequestFixture _removeScheduledJobRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="RemoveScheduledJobEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
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);
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <c>/{culture}/admin/scheduled-jobs</c> route served by the <see cref="SchedulerIndexViewEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SchedulerIndexViewEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="SchedulerIndexViewEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
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());
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <c>/{culture}/admin/api-scheduled-jobs/{scheduledJobId}/start</c> route served by the <see cref="StartScheduledJobEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class StartScheduledJobEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
private readonly StartScheduledJobRequestFixture _startScheduledJobRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="StartScheduledJobEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
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);
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <c>/{culture}/admin/api-scheduled-jobs/{scheduledJobId}/stop</c> route served by the <see cref="StopScheduledJobEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class StopScheduledJobEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
private readonly StopScheduledJobRequestFixture _stopScheduledJobRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="StopScheduledJobEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
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);
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <c>/{culture}/admin/api-scheduled-jobs/display-preferences</c> route served by the <see cref="UpdateSchedulerDisplayPreferencesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateSchedulerDisplayPreferencesEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
private readonly UpdateSchedulerDisplayPreferencesRequestFixture _updateSchedulerDisplayPreferencesRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="UpdateSchedulerDisplayPreferencesEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
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");
}
}
@@ -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;
/// <summary>
/// Contains security tests for the <c>/{culture}/admin/api-scheduled-jobs/add</c> route served by the <see cref="AddScheduledJobEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddScheduledJobEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
/// <summary>
/// Initializes a new instance of the <see cref="AddScheduledJobEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
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));
}
/// <summary>
/// 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.
/// </summary>
/// <returns>The created content.</returns>
private static StringContent CreateJsonContent()
{
StringContent content = new("{}", Encoding.UTF8, "application/json");
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
return content;
}
}
@@ -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;
/// <summary>
/// Contains security tests for the <c>/{culture}/admin/api-scheduled-jobs/{scheduledJobId}/fire</c> route served by the <see cref="FireScheduledJobEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class FireScheduledJobEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
/// <summary>
/// Initializes a new instance of the <see cref="FireScheduledJobEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
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));
}
/// <summary>
/// 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.
/// </summary>
/// <returns>The created content.</returns>
private static StringContent CreateJsonContent()
{
StringContent content = new("{}", Encoding.UTF8, "application/json");
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
return content;
}
}
@@ -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;
/// <summary>
/// Contains security tests for the <c>/{culture}/admin/api-scheduled-jobs/history</c> route served by the <see cref="GetScheduledJobHistoryEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetScheduledJobHistoryEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new();
private readonly ScheduledJobExecutionDtoFixture _scheduledJobExecutionDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetScheduledJobHistoryEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
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);
}
}
@@ -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;
/// <summary>
/// Contains security tests for the <c>/{culture}/admin/api-scheduled-jobs</c> route served by the <see cref="GetScheduledJobsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetScheduledJobsEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new();
private readonly ScheduledJobDtoFixture _scheduledJobDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetScheduledJobsEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
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);
}
}
@@ -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;
/// <summary>
/// Contains security tests for the <c>/{culture}/admin/api-scheduled-jobs/display-preferences</c> route served by the <see cref="GetSchedulerDisplayPreferencesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetSchedulerDisplayPreferencesEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new();
private readonly SchedulerDisplayPreferencesDtoFixture _schedulerDisplayPreferencesDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetSchedulerDisplayPreferencesEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
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);
}
}
@@ -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;
/// <summary>
/// Contains security tests for the <c>/{culture}/admin/api-scheduled-jobs/{scheduledJobId}</c> route served by the <see cref="RemoveScheduledJobEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RemoveScheduledJobEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
/// <summary>
/// Initializes a new instance of the <see cref="RemoveScheduledJobEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
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));
}
/// <summary>
/// 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.
/// </summary>
/// <returns>The created content.</returns>
private static StringContent CreateJsonContent()
{
StringContent content = new("{}", Encoding.UTF8, "application/json");
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
return content;
}
}
@@ -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;
/// <summary>
/// Contains security tests for the <c>/{culture}/admin/scheduled-jobs</c> route served by the <see cref="SchedulerIndexViewEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SchedulerIndexViewEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="SchedulerIndexViewEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
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);
}
}
@@ -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;
/// <summary>
/// Contains security tests for the <c>/{culture}/admin/api-scheduled-jobs/{scheduledJobId}/start</c> route served by the <see cref="StartScheduledJobEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class StartScheduledJobEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
/// <summary>
/// Initializes a new instance of the <see cref="StartScheduledJobEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
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));
}
/// <summary>
/// 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.
/// </summary>
/// <returns>The created content.</returns>
private static StringContent CreateJsonContent()
{
StringContent content = new("{}", Encoding.UTF8, "application/json");
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
return content;
}
}
@@ -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;
/// <summary>
/// Contains security tests for the <c>/{culture}/admin/api-scheduled-jobs/{scheduledJobId}/stop</c> route served by the <see cref="StopScheduledJobEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class StopScheduledJobEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
/// <summary>
/// Initializes a new instance of the <see cref="StopScheduledJobEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
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));
}
/// <summary>
/// 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.
/// </summary>
/// <returns>The created content.</returns>
private static StringContent CreateJsonContent()
{
StringContent content = new("{}", Encoding.UTF8, "application/json");
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
return content;
}
}
@@ -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;
/// <summary>
/// Contains security tests for the <c>/{culture}/admin/api-scheduled-jobs/display-preferences</c> route served by the <see cref="UpdateSchedulerDisplayPreferencesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateSchedulerDisplayPreferencesEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
/// <summary>
/// Initializes a new instance of the <see cref="UpdateSchedulerDisplayPreferencesEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
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));
}
/// <summary>
/// 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.
/// </summary>
/// <returns>The created content.</returns>
private static StringContent CreateJsonContent()
{
StringContent content = new("{}", Encoding.UTF8, "application/json");
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
return content;
}
}
@@ -45,6 +45,7 @@ public class SetupApplicationCommandHandlerTests
private readonly IDateTimeProvider _mockDateTimeProvider;
private readonly IDataSeedService _mockDataSeedService;
private readonly IDomainEventsQueue _mockDomainEventsQueue;
private readonly IValidator<SetupApplicationCommand> _mockValidator;
private readonly SetupApplicationCommandHandler _sut;
private readonly UserEntityFixture _userEntityFixture = new();
private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new();
@@ -65,8 +66,8 @@ public class SetupApplicationCommandHandlerTests
_mockDateTimeProvider = Substitute.For<IDateTimeProvider>();
_mockDataSeedService = Substitute.For<IDataSeedService>();
_mockDomainEventsQueue = Substitute.For<IDomainEventsQueue>();
IValidator<SetupApplicationCommand> mockValidator = Substitute.For<IValidator<SetupApplicationCommand>>();
mockValidator.Validate(Arg.Any<SetupApplicationCommand>())
_mockValidator = Substitute.For<IValidator<SetupApplicationCommand>>();
_mockValidator.Validate(Arg.Any<SetupApplicationCommand>())
.Returns([]);
_mockUnitOfWork.UserRepository.Returns(_mockUserRepository);
@@ -86,7 +87,7 @@ public class SetupApplicationCommandHandlerTests
_mockDateTimeProvider,
_mockDataSeedService,
_mockDomainEventsQueue,
mockValidator);
_mockValidator);
}
[Fact]
@@ -456,4 +457,54 @@ public class SetupApplicationCommandHandlerTests
_mockDomainEventsQueue.Received(1).Enqueue(Arg.Is<ScheduledJobCycleStartedDomainEvent>(domainEvent => domainEvent.ScheduledJobId.Value == activeScheduledJob2.Id));
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Is<ScheduledJobCycleStartedDomainEvent>(domainEvent => domainEvent.ScheduledJobId.Value == addedScheduledJob.Id));
}
[Fact]
public async Task HandleAsync_WhenValidatorReturnsError_ShouldReturnValidationErrorAndNotCreateAnyUser()
{
// Arrange
SetupApplicationCommand command = _setupApplicationCommandFixture.Create();
Error validationError = Error.Validation("Setup.Validation", "The setup command is invalid.");
_mockValidator.Validate(Arg.Any<SetupApplicationCommand>()).Returns([validationError]);
// Act
Result<RegistrationResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(validationError, result.FirstError);
await _mockUserRepository.DidNotReceive().GetAllAsync(Arg.Any<CancellationToken>());
await _mockUserRepository.DidNotReceive().InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenReadingTheSeededScheduledJobsFails_ShouldReturnTheRepositoryError()
{
// Arrange
SetupApplicationCommand command = _setupApplicationCommandFixture.Create();
_mockUserRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(Result.From(Enumerable.Empty<UserEntity>()));
_mockHashService.HashString(command.Password!)
.Returns("hashedPassword");
_mockUserRepository.InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Created);
_mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Created);
_mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Created);
_mockDataSeedService.SetAdminRolePermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Created);
_mockDataSeedService.SetAdminRoleToAdministratorAccount(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Created);
Error expectedError = Error.Failure("ScheduledJobs.NotFound", "Failed to read the scheduled jobs");
_mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
Result<RegistrationResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(expectedError, result.FirstError);
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<ScheduledJobCycleStartedDomainEvent>());
}
}
@@ -253,4 +253,30 @@ public class AddScheduledJobCommandHandlerTests
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
}
[Fact]
public async Task HandleAsync_WhenCommandIsValidWithOnceAtStartupSchedule_ShouldInsertScheduledJobAndReturnResponse()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(scheduleType: ScheduleType.OnceAtStartup);
_mockScheduledJobRepository.InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>()).Returns(Result.Created);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(command.Name, result.Value.Name);
Assert.Equal(ScheduleType.OnceAtStartup, result.Value.ScheduleType);
Assert.Null(result.Value.IntervalMinutes);
Assert.Null(result.Value.Hour);
Assert.Null(result.Value.Minute);
await _mockScheduledJobRepository.Received(1).InsertAsync(
Arg.Is<ScheduledJobEntity>(scheduledJob =>
scheduledJob.Name == command.Name &&
scheduledJob.ScheduleType == ScheduleType.OnceAtStartup),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
_mockDomainEventsQueue.Received(1).Enqueue(Arg.Is<IDomainEvent>(domainEvent => domainEvent is ScheduledJobAddedDomainEvent));
}
}
@@ -216,4 +216,47 @@ public class RemoveScheduledJobCommandHandlerTests
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
}
[Fact]
public async Task HandleAsync_WhenGettingTheScheduledJobFails_ShouldReturnTheRepositoryError()
{
// Arrange
RemoveScheduledJobCommand command = _removeScheduledJobCommandFixture.Create();
Error repositoryError = DomainErrors.Scheduling.ScheduledJobNotFound;
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(repositoryError);
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(repositoryError, result.FirstError);
await _mockScheduledJobScheduler.DidNotReceive().StopCycleAsync(Arg.Any<ScheduledJobId>(), Arg.Any<CancellationToken>());
await _mockScheduledJobExecutionRepository.DidNotReceive().DeleteByScheduledJobIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenTheScheduledJobCannotBeConvertedToDomain_ShouldReturnTheMappingError()
{
// Arrange
RemoveScheduledJobCommand command = _removeScheduledJobCommandFixture.Create();
// An interval schedule whose interval is not positive cannot be converted to its domain object.
ScheduledJobEntity invalidScheduledJob = _scheduledJobEntityFixture.Create(
id: command.ScheduledJobId,
scheduleType: ScheduleType.WithIntervalInMinutes,
intervalMinutes: 0,
status: ScheduledJobStatus.Active);
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(invalidScheduledJob));
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.IntervalMinutesMustBePositive, result.FirstError);
await _mockScheduledJobScheduler.DidNotReceive().StopCycleAsync(Arg.Any<ScheduledJobId>(), Arg.Any<CancellationToken>());
await _mockScheduledJobExecutionRepository.DidNotReceive().DeleteByScheduledJobIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
}
@@ -200,4 +200,46 @@ public class StartScheduledJobCommandHandlerTests
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
}
[Fact]
public async Task HandleAsync_WhenGettingTheScheduledJobFails_ShouldReturnTheRepositoryError()
{
// Arrange
StartScheduledJobCommand command = _startScheduledJobCommandFixture.Create();
Error repositoryError = DomainErrors.Scheduling.ScheduledJobNotFound;
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(repositoryError);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(repositoryError, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenTheScheduledJobCannotBeConvertedToDomain_ShouldReturnTheMappingError()
{
// Arrange
StartScheduledJobCommand command = _startScheduledJobCommandFixture.Create();
// An interval schedule whose interval is not positive cannot be converted to its domain object.
ScheduledJobEntity invalidScheduledJob = _scheduledJobEntityFixture.Create(
id: command.ScheduledJobId,
scheduleType: ScheduleType.WithIntervalInMinutes,
intervalMinutes: 0,
status: ScheduledJobStatus.Added);
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(invalidScheduledJob));
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.IntervalMinutesMustBePositive, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
}
}
@@ -152,6 +152,22 @@ public class StopScheduledJobCommandHandlerTests
await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAdministrator_ShouldReturnNotAuthorized()
{
// Arrange
StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create();
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(false);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenScheduledJobDoesNotExist_ShouldReturnNotFound()
{
@@ -214,4 +230,46 @@ public class StopScheduledJobCommandHandlerTests
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockScheduledJobScheduler.DidNotReceive().StopCycleAsync(Arg.Any<Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects.ScheduledJobId>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGettingTheScheduledJobFails_ShouldReturnTheRepositoryError()
{
// Arrange
StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create();
Error repositoryError = DomainErrors.Scheduling.ScheduledJobNotFound;
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(repositoryError);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(repositoryError, result.FirstError);
await _mockScheduledJobScheduler.DidNotReceive().StopCycleAsync(Arg.Any<Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects.ScheduledJobId>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenTheScheduledJobCannotBeConvertedToDomain_ShouldReturnTheMappingError()
{
// Arrange
StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create();
// An interval schedule whose interval is not positive cannot be converted to its domain object.
ScheduledJobEntity invalidScheduledJob = _scheduledJobEntityFixture.Create(
id: command.ScheduledJobId,
scheduleType: ScheduleType.WithIntervalInMinutes,
intervalMinutes: 0,
status: ScheduledJobStatus.Active);
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(invalidScheduledJob));
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.IntervalMinutesMustBePositive, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockScheduledJobScheduler.DidNotReceive().StopCycleAsync(Arg.Any<Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects.ScheduledJobId>(), Arg.Any<CancellationToken>());
}
}
@@ -67,6 +67,35 @@ public class ScheduledJobRepositoryTests
Assert.Null(result.Value);
}
[Fact]
public async Task GetByIdWithoutTrackingAsync_WhenScheduledJobExists_ShouldReturnScheduledJob()
{
// Arrange
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create();
_mockContext.ScheduledJobs.Add(scheduledJob);
await _mockContext.SaveChangesAsync();
// Act
Result<ScheduledJobEntity?> result = await _sut.GetByIdWithoutTrackingAsync(scheduledJob.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.NotNull(result.Value);
Assert.Equal(scheduledJob.Id, result.Value!.Id);
Assert.Equal(scheduledJob.Name, result.Value.Name);
}
[Fact]
public async Task GetByIdWithoutTrackingAsync_WhenScheduledJobDoesNotExist_ShouldReturnNull()
{
// Act
Result<ScheduledJobEntity?> result = await _sut.GetByIdWithoutTrackingAsync(Guid.NewGuid(), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public async Task GetAllAsync_WhenScheduledJobsExist_ShouldReturnAllScheduledJobs()
{
@@ -40,7 +40,6 @@ public class DataSeedServiceTests
private readonly UserEntityFixture _userEntityFixture = new();
private readonly RoleEntityFixture _roleEntityFixture = new();
private readonly PermissionEntityFixture _permissionEntityFixture = new();
private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="DataSeedServiceTests"/> class.
@@ -551,14 +550,12 @@ public class DataSeedServiceTests
}
[Fact]
public async Task SetDefaultScheduledJobsAsync_WhenNoScheduledJobsExist_ShouldInsertTheFiveDefaultJobsAndReturnCreated()
public async Task SetDefaultScheduledJobsAsync_WhenCalled_ShouldInsertTheFiveDefaultJobsAndReturnCreated()
{
// Arrange
Guid adminUserId = Guid.NewGuid();
IScheduledJobRepository mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
_mockUnitOfWork.ScheduledJobRepository.Returns(mockScheduledJobRepository);
mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(Result.From(Enumerable.Empty<ScheduledJobEntity>()));
List<ScheduledJobEntity> capturedScheduledJobs = [];
mockScheduledJobRepository.InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Created)
@@ -583,48 +580,7 @@ public class DataSeedServiceTests
await mockScheduledJobRepository.Received(5).InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task SetDefaultScheduledJobsAsync_WhenScheduledJobsAlreadyExist_ShouldNotInsertAnyJob()
{
// Arrange
Guid adminUserId = Guid.NewGuid();
IScheduledJobRepository mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
_mockUnitOfWork.ScheduledJobRepository.Returns(mockScheduledJobRepository);
ScheduledJobEntity existingScheduledJob = _scheduledJobEntityFixture.Create(scheduleType: ScheduleType.WithIntervalInMinutes);
mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(new[] { existingScheduledJob });
// Act
Result<Created> result = await _sut.SetDefaultScheduledJobsAsync(adminUserId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Created, result.Value);
await mockScheduledJobRepository.DidNotReceive().InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task SetDefaultScheduledJobsAsync_WhenGetAllScheduledJobsFails_ShouldReturnError()
{
// Arrange
Guid adminUserId = Guid.NewGuid();
IScheduledJobRepository mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
_mockUnitOfWork.ScheduledJobRepository.Returns(mockScheduledJobRepository);
Error expectedError = Error.Failure("ScheduledJobs.NotFound", "Failed to retrieve the scheduled jobs");
mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
Result<Created> result = await _sut.SetDefaultScheduledJobsAsync(adminUserId, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(expectedError, result.FirstError);
await mockScheduledJobRepository.DidNotReceive().InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
await mockScheduledJobRepository.DidNotReceive().GetAllAsync(Arg.Any<CancellationToken>());
}
[Fact]
@@ -634,8 +590,6 @@ public class DataSeedServiceTests
Guid adminUserId = Guid.NewGuid();
IScheduledJobRepository mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
_mockUnitOfWork.ScheduledJobRepository.Returns(mockScheduledJobRepository);
mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(Result.From(Enumerable.Empty<ScheduledJobEntity>()));
Error expectedError = Error.Failure("ScheduledJobs.InsertFailed", "Failed to insert the scheduled job");
mockScheduledJobRepository.InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Created, expectedError);
@@ -120,4 +120,99 @@ public class ScheduledJobRuntimeRegistryTests
// Assert
Assert.True(result);
}
[Fact]
public void HasActiveCycle_WhenCycleIsRunning_ShouldReturnTrue()
{
// Arrange
ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create();
using CancellationTokenSource cycleCancellationTokenSource = new();
_sut.TryStartCycle(scheduledJobId, cycleCancellationTokenSource);
// Act
bool result = _sut.HasActiveCycle(scheduledJobId);
// Assert
Assert.True(result);
}
[Fact]
public void HasActiveCycle_WhenNoCycleIsRunning_ShouldReturnFalse()
{
// Arrange
ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create();
// Act
bool result = _sut.HasActiveCycle(scheduledJobId);
// Assert
Assert.False(result);
}
[Fact]
public void HasActiveCycle_AfterTheCycleWasStopped_ShouldReturnFalse()
{
// Arrange
ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create();
using CancellationTokenSource cycleCancellationTokenSource = new();
_sut.TryStartCycle(scheduledJobId, cycleCancellationTokenSource);
_sut.StopCycle(scheduledJobId);
// Act
bool result = _sut.HasActiveCycle(scheduledJobId);
// Assert
Assert.False(result);
}
[Fact]
public void EndCycle_WhenCalledWithTheOwnedTokenSource_ShouldCancelItAndClearTheCycle()
{
// Arrange
ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create();
using CancellationTokenSource cycleCancellationTokenSource = new();
_sut.TryStartCycle(scheduledJobId, cycleCancellationTokenSource);
// Act
_sut.EndCycle(scheduledJobId, cycleCancellationTokenSource);
// Assert
Assert.True(cycleCancellationTokenSource.IsCancellationRequested);
Assert.False(_sut.HasActiveCycle(scheduledJobId));
}
[Fact]
public void EndCycle_WhenTheCycleWasReplacedByANewerOne_ShouldNotCancelTheNewerCycle()
{
// Arrange
ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create();
using CancellationTokenSource oldCycleCancellationTokenSource = new();
using CancellationTokenSource newCycleCancellationTokenSource = new();
_sut.TryStartCycle(scheduledJobId, oldCycleCancellationTokenSource);
_sut.StopCycle(scheduledJobId);
_sut.TryStartCycle(scheduledJobId, newCycleCancellationTokenSource);
// Act
_sut.EndCycle(scheduledJobId, oldCycleCancellationTokenSource);
// Assert
Assert.True(oldCycleCancellationTokenSource.IsCancellationRequested);
Assert.False(newCycleCancellationTokenSource.IsCancellationRequested);
Assert.True(_sut.HasActiveCycle(scheduledJobId));
}
[Fact]
public void EndCycle_WhenNoCycleIsRegistered_ShouldStillCancelTheOwnedTokenSource()
{
// Arrange
ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create();
using CancellationTokenSource cycleCancellationTokenSource = new();
// Act
_sut.EndCycle(scheduledJobId, cycleCancellationTokenSource);
// Assert
Assert.True(cycleCancellationTokenSource.IsCancellationRequested);
Assert.False(_sut.HasActiveCycle(scheduledJobId));
}
}
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Domain.Common.Events;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using Lumina.Infrastructure.Core.Scheduling.Execution;
@@ -21,6 +22,8 @@ public class ScheduledTaskExecutorFactoryTests
private readonly IServiceProvider _mockServiceProvider;
private readonly MediaLibraryScanTaskExecutor _mockMediaLibraryScanTaskExecutor;
private readonly TemporaryFilesCleanupTaskExecutor _mockTemporaryFilesCleanupTaskExecutor;
private readonly RepairThemesTaskExecutor _mockRepairThemesTaskExecutor;
private readonly CleanScheduledJobExecutionHistoryTaskExecutor _mockCleanScheduledJobExecutionHistoryTaskExecutor;
private readonly ScheduledTaskExecutorFactory _sut;
/// <summary>
@@ -35,9 +38,19 @@ public class ScheduledTaskExecutorFactoryTests
Substitute.For<IUnitOfWork>());
_mockTemporaryFilesCleanupTaskExecutor = Substitute.For<TemporaryFilesCleanupTaskExecutor>(
Substitute.For<ILogger<TemporaryFilesCleanupTaskExecutor>>());
_mockRepairThemesTaskExecutor = Substitute.For<RepairThemesTaskExecutor>(
Substitute.For<Lumina.Application.Common.Infrastructure.Themes.IThemeService>(),
Substitute.For<ILogger<RepairThemesTaskExecutor>>(),
Substitute.For<IUnitOfWork>());
_mockCleanScheduledJobExecutionHistoryTaskExecutor = Substitute.For<CleanScheduledJobExecutionHistoryTaskExecutor>(
Substitute.For<IDateTimeProvider>(),
Substitute.For<ILogger<CleanScheduledJobExecutionHistoryTaskExecutor>>(),
Substitute.For<IUnitOfWork>());
_mockServiceProvider.GetService(typeof(MediaLibraryScanTaskExecutor)).Returns(_mockMediaLibraryScanTaskExecutor);
_mockServiceProvider.GetService(typeof(TemporaryFilesCleanupTaskExecutor)).Returns(_mockTemporaryFilesCleanupTaskExecutor);
_mockServiceProvider.GetService(typeof(RepairThemesTaskExecutor)).Returns(_mockRepairThemesTaskExecutor);
_mockServiceProvider.GetService(typeof(CleanScheduledJobExecutionHistoryTaskExecutor)).Returns(_mockCleanScheduledJobExecutionHistoryTaskExecutor);
_sut = new ScheduledTaskExecutorFactory(_mockServiceProvider);
}
@@ -62,6 +75,26 @@ public class ScheduledTaskExecutorFactoryTests
Assert.Same(_mockTemporaryFilesCleanupTaskExecutor, result);
}
[Fact]
public void CreateExecutor_WhenTaskTypeIsRepairThemes_ShouldReturnRepairThemesTaskExecutor()
{
// Act
IScheduledTaskExecutor result = _sut.CreateExecutor(ScheduledTaskType.RepairThemes);
// Assert
Assert.Same(_mockRepairThemesTaskExecutor, result);
}
[Fact]
public void CreateExecutor_WhenTaskTypeIsCleanScheduledJobExecutionHistory_ShouldReturnCleanScheduledJobExecutionHistoryTaskExecutor()
{
// Act
IScheduledTaskExecutor result = _sut.CreateExecutor(ScheduledTaskType.CleanScheduledJobExecutionHistory);
// Assert
Assert.Same(_mockCleanScheduledJobExecutionHistoryTaskExecutor, result);
}
[Fact]
public void CreateExecutor_WhenTaskTypeIsUnsupported_ShouldThrowArgumentException()
{
@@ -0,0 +1,78 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using Lumina.Infrastructure.Core.Scheduling.Execution.TaskExecutors;
using Microsoft.Extensions.Logging;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.Scheduling.Execution.TaskExecutors;
/// <summary>
/// Contains unit tests for the <see cref="CleanScheduledJobExecutionHistoryTaskExecutor"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class CleanScheduledJobExecutionHistoryTaskExecutorTests
{
private readonly IDateTimeProvider _mockDateTimeProvider;
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IScheduledJobExecutionRepository _mockScheduledJobExecutionRepository;
private readonly CleanScheduledJobExecutionHistoryTaskExecutor _sut;
private readonly ScheduledJobFixture _scheduledJobFixture = new();
private readonly DateTime _fixedUtcNow = DateTime.UtcNow;
/// <summary>
/// Initializes a new instance of the <see cref="CleanScheduledJobExecutionHistoryTaskExecutorTests"/> class.
/// </summary>
public CleanScheduledJobExecutionHistoryTaskExecutorTests()
{
_mockDateTimeProvider = Substitute.For<IDateTimeProvider>();
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockScheduledJobExecutionRepository = Substitute.For<IScheduledJobExecutionRepository>();
_mockDateTimeProvider.UtcNow.Returns(_fixedUtcNow);
_mockUnitOfWork.ScheduledJobExecutionRepository.Returns(_mockScheduledJobExecutionRepository);
ILogger<CleanScheduledJobExecutionHistoryTaskExecutor> logger = Substitute.For<ILogger<CleanScheduledJobExecutionHistoryTaskExecutor>>();
_sut = new CleanScheduledJobExecutionHistoryTaskExecutor(_mockDateTimeProvider, logger, _mockUnitOfWork);
}
[Fact]
public async Task ExecutePayloadAsync_WhenCalled_ShouldDeleteTheExecutionsOlderThanAMonth()
{
// Arrange
ScheduledJob scheduledJob = _scheduledJobFixture.Create(taskType: ScheduledTaskType.CleanScheduledJobExecutionHistory);
_mockScheduledJobExecutionRepository.DeleteOlderThanAsync(Arg.Any<DateTime>(), Arg.Any<CancellationToken>()).Returns(Result.Success);
DateTime expectedCutoff = _fixedUtcNow.AddMonths(-1);
// Act
Result<Success> result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockScheduledJobExecutionRepository.Received(1).DeleteOlderThanAsync(Arg.Is<DateTime>(cutoff => cutoff == expectedCutoff), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecutePayloadAsync_WhenTheDeletionFails_ShouldReturnTheError()
{
// Arrange
ScheduledJob scheduledJob = _scheduledJobFixture.Create(taskType: ScheduledTaskType.CleanScheduledJobExecutionHistory);
Error expectedError = Error.Failure("Database.Error", "Failed to delete the old executions");
_mockScheduledJobExecutionRepository.DeleteOlderThanAsync(Arg.Any<DateTime>(), Arg.Any<CancellationToken>()).Returns(expectedError);
// Act
Result<Success> result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(expectedError, result.FirstError);
}
}
@@ -7,6 +7,7 @@ using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Infrastructure.Core.Scheduling.Execution.TaskExecutors;
using Microsoft.Extensions.Logging;
using NSubstitute;
@@ -31,6 +32,7 @@ public class MediaLibraryScanTaskExecutorTests
private readonly MediaLibraryScanTaskExecutor _sut;
private readonly ScheduledJobFixture _scheduledJobFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="MediaLibraryScanTaskExecutorTests"/> class.
@@ -100,4 +102,71 @@ public class MediaLibraryScanTaskExecutorTests
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
}
[Fact]
public async Task ExecutePayloadAsync_WhenALibraryIsAlreadyBeingScanned_ShouldSkipThatLibrary()
{
// Arrange
ScheduledJob scheduledJob = _scheduledJobFixture.Create();
LibraryEntity library = _libraryEntityFixture.Create();
_mockLibraryRepository.GetAllEnabledAndUnlockedAsync(Arg.Any<CancellationToken>())
.Returns(Result.From<IEnumerable<LibraryEntity>>([library]));
LibraryScanEntity runningScan = _libraryScanEntityFixture.Create(libraryId: library.Id, status: LibraryScanJobStatus.Running);
_mockUnitOfWork.LibraryScanRepository.GetPastMonthScansByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IEnumerable<LibraryScanEntity>>([runningScan]));
// Act
Result<Success> result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecutePayloadAsync_WhenAQueuedScanIsInserted_ShouldPublishItsDomainEvents()
{
// Arrange
ScheduledJob scheduledJob = _scheduledJobFixture.Create();
LibraryEntity library = _libraryEntityFixture.Create();
_mockLibraryRepository.GetAllEnabledAndUnlockedAsync(Arg.Any<CancellationToken>())
.Returns(Result.From<IEnumerable<LibraryEntity>>([library]));
_mockUnitOfWork.LibraryScanRepository.GetPastMonthScansByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IEnumerable<LibraryScanEntity>>([]));
_mockUnitOfWork.LibraryScanRepository.InsertAsync(Arg.Any<LibraryScanEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Created);
// Act
Result<Success> result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockUnitOfWork.LibraryScanRepository.Received(1).InsertAsync(Arg.Any<LibraryScanEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecutePayloadAsync_WhenInsertingTheQueuedScanFails_ShouldReturnError()
{
// Arrange
ScheduledJob scheduledJob = _scheduledJobFixture.Create();
LibraryEntity library = _libraryEntityFixture.Create();
_mockLibraryRepository.GetAllEnabledAndUnlockedAsync(Arg.Any<CancellationToken>())
.Returns(Result.From<IEnumerable<LibraryEntity>>([library]));
_mockUnitOfWork.LibraryScanRepository.GetPastMonthScansByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IEnumerable<LibraryScanEntity>>([]));
Error error = Error.Failure("Database.Error", "Failed to insert the scan");
_mockUnitOfWork.LibraryScanRepository.InsertAsync(Arg.Any<LibraryScanEntity>(), Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<Success> result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,119 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Themes;
using Lumina.Application.Common.DataAccess.Repositories.Themes;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Models.DTO.Themes;
using Lumina.Application.Common.Infrastructure.Themes;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using Lumina.Infrastructure.Core.Scheduling.Execution.TaskExecutors;
using Microsoft.Extensions.Logging;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.Scheduling.Execution.TaskExecutors;
/// <summary>
/// Contains unit tests for the <see cref="RepairThemesTaskExecutor"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RepairThemesTaskExecutorTests
{
private readonly IThemeService _mockThemeService;
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IThemeRepository _mockThemeRepository;
private readonly RepairThemesTaskExecutor _sut;
private readonly ScheduledJobFixture _scheduledJobFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="RepairThemesTaskExecutorTests"/> class.
/// </summary>
public RepairThemesTaskExecutorTests()
{
_mockThemeService = Substitute.For<IThemeService>();
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockThemeRepository = Substitute.For<IThemeRepository>();
_mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository);
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
ILogger<RepairThemesTaskExecutor> logger = Substitute.For<ILogger<RepairThemesTaskExecutor>>();
_sut = new RepairThemesTaskExecutor(_mockThemeService, logger, _mockUnitOfWork);
}
[Fact]
public async Task ExecutePayloadAsync_WhenCalled_ShouldSynchronizeTheThemes()
{
// Arrange
ScheduledJob scheduledJob = _scheduledJobFixture.Create(taskType: ScheduledTaskType.RepairThemes);
_mockThemeService.GetBundledThemeArchivePaths().Returns([]);
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From(Enumerable.Empty<ThemeEntity>()));
// Act
Result<Success> result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockThemeRepository.Received(1).GetAllAsync(Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecutePayloadAsync_WhenABundledThemeArchiveCannotBeRead_ShouldStillSucceed()
{
// Arrange
ScheduledJob scheduledJob = _scheduledJobFixture.Create(taskType: ScheduledTaskType.RepairThemes);
_mockThemeService.GetBundledThemeArchivePaths().Returns(["missing.zip"]);
_mockThemeService.ReadManifestFromArchiveAsync(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Theme.Manifest", "Failed to read the theme manifest"));
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From(Enumerable.Empty<ThemeEntity>()));
// Act
Result<Success> result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockThemeRepository.Received(1).GetAllAsync(Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecutePayloadAsync_WhenTheSynchronizationThrows_ShouldReturnFailure()
{
// Arrange
ScheduledJob scheduledJob = _scheduledJobFixture.Create(taskType: ScheduledTaskType.RepairThemes);
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(Task.FromException<Result<IEnumerable<ThemeEntity>>>(new InvalidOperationException("The database is unavailable.")));
// Act
Result<Success> result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(nameof(RepairThemesTaskExecutor), result.FirstError.Description);
}
[Fact]
public async Task ExecutePayloadAsync_WhenTheSynchronizationIsCancelled_ShouldRethrowTheCancellation()
{
// Arrange
ScheduledJob scheduledJob = _scheduledJobFixture.Create(taskType: ScheduledTaskType.RepairThemes);
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(Task.FromException<Result<IEnumerable<ThemeEntity>>>(new OperationCanceledException()));
// Act
async Task Act()
{
await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None);
}
// Assert
await Assert.ThrowsAsync<OperationCanceledException>(Act);
}
}
@@ -0,0 +1,498 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Themes;
using Lumina.Application.Common.DataAccess.Repositories.Themes;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Models.DTO.Themes;
using Lumina.Application.Common.Infrastructure.Themes;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes;
using Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.Themes;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Themes;
using Lumina.Infrastructure.Core.Themes;
using Microsoft.Extensions.Logging;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.Themes;
/// <summary>
/// Contains unit tests for the <see cref="ThemeSynchronizer"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ThemeSynchronizerTests : IDisposable
{
private readonly IThemeService _mockThemeService;
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IThemeRepository _mockThemeRepository;
private readonly ILogger _mockLogger;
private readonly ThemeEntityFixture _themeEntityFixture = new();
private readonly ThemeManifestDtoFixture _themeManifestDtoFixture = new();
private readonly string _temporaryDirectoryPath;
/// <summary>
/// Initializes a new instance of the <see cref="ThemeSynchronizerTests"/> class.
/// </summary>
public ThemeSynchronizerTests()
{
_mockThemeService = Substitute.For<IThemeService>();
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockThemeRepository = Substitute.For<IThemeRepository>();
_mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository);
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
_mockLogger = Substitute.For<ILogger>();
_mockThemeService.GetBundledThemeArchivePaths().Returns([]);
_mockThemeService.HasThemePack(Arg.Any<string>()).Returns(true);
_mockThemeService.DefaultThemeId.Returns("lumina-default");
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From(Enumerable.Empty<ThemeEntity>()));
_mockThemeRepository.InsertAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>()).Returns(Result.Created);
_mockThemeRepository.UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>()).Returns(Result.Updated);
_mockThemeRepository.DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(Result.Deleted);
_temporaryDirectoryPath = Path.Combine(Path.GetTempPath(), $"lumina-theme-sync-{Guid.NewGuid():N}");
Directory.CreateDirectory(_temporaryDirectoryPath);
}
[Fact]
public async Task SynchronizeAsync_WhenTheInstalledThemesCannotBeRead_ShouldLogAndReturn()
{
// Arrange
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(Error.Failure("Themes.NotFound", "Failed to read the installed themes"));
_mockThemeService.GetBundledThemeArchivePaths().Returns(["bundled.zip"]);
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockThemeService.DidNotReceive().ReadManifestFromArchiveAsync(Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenABundledArchiveManifestCannotBeRead_ShouldSkipThatArchive()
{
// Arrange
_mockThemeService.GetBundledThemeArchivePaths().Returns(["missing.zip"]);
_mockThemeService.ReadManifestFromArchiveAsync("missing.zip", Arg.Any<CancellationToken>())
.Returns(Error.Failure("Theme.Manifest", "Failed to read the theme manifest"));
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenTheBundledThemeIsAlreadyInstalled_ShouldNotReinstallIt()
{
// Arrange
ThemeManifestDto manifest = _themeManifestDtoFixture.Create();
ThemeEntity installedTheme = _themeEntityFixture.Create(themeId: manifest.Id, installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true);
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(new[] { installedTheme });
_mockThemeService.GetBundledThemeArchivePaths().Returns(["bundled.zip"]);
_mockThemeService.ReadManifestFromArchiveAsync("bundled.zip", Arg.Any<CancellationToken>()).Returns(Result.From(manifest));
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>());
await _mockThemeRepository.DidNotReceive().InsertAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenTheBundledThemeWasSoftDeletedByTheUser_ShouldNotReinstallIt()
{
// Arrange
ThemeManifestDto manifest = _themeManifestDtoFixture.Create();
ThemeEntity deletedTheme = _themeEntityFixture.Create(themeId: manifest.Id, installSource: ThemeInstallSource.Bundled, isDeleted: true);
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(new[] { deletedTheme });
_mockThemeService.GetBundledThemeArchivePaths().Returns(["bundled.zip"]);
_mockThemeService.ReadManifestFromArchiveAsync("bundled.zip", Arg.Any<CancellationToken>()).Returns(Result.From(manifest));
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>());
await _mockThemeRepository.DidNotReceive().InsertAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenABundledThemeIsMissingItsFiles_ShouldReinstallThemWithoutAddingANewRow()
{
// Arrange
ThemeManifestDto manifest = _themeManifestDtoFixture.Create();
ThemeEntity damagedTheme = _themeEntityFixture.Create(themeId: manifest.Id, installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true);
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(new[] { damagedTheme });
string archivePath = CreateArchiveFile();
_mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]);
// The first pack check happens before the repair and reports the files as missing; the later checks report the files as present.
_mockThemeService.HasThemePack(damagedTheme.ThemeId).Returns(false, true);
_mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any<CancellationToken>()).Returns(Result.From(manifest));
_mockThemeService.InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>()).Returns(Result.From(manifest));
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockThemeService.Received(1).InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>());
await _mockThemeRepository.DidNotReceive().InsertAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenTheReinstallationFails_ShouldLogAndKeepTheExistingTheme()
{
// Arrange
ThemeManifestDto manifest = _themeManifestDtoFixture.Create();
ThemeEntity damagedTheme = _themeEntityFixture.Create(themeId: manifest.Id, installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true);
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(new[] { damagedTheme });
string archivePath = CreateArchiveFile();
_mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]);
_mockThemeService.HasThemePack(damagedTheme.ThemeId).Returns(false, true);
_mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any<CancellationToken>()).Returns(Result.From(manifest));
_mockThemeService.InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Theme.Install", "Failed to install the theme"));
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockThemeService.Received(1).InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>());
await _mockThemeRepository.DidNotReceive().InsertAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenANewBundledThemeIsInstalled_ShouldInsertTheThemeRow()
{
// Arrange
ThemeManifestDto manifest = _themeManifestDtoFixture.Create();
string archivePath = CreateArchiveFile();
_mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]);
_mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any<CancellationToken>()).Returns(Result.From(manifest));
_mockThemeService.InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>()).Returns(Result.From(manifest));
_mockThemeService.HasThemePack(manifest.Id).Returns(true);
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockThemeRepository.Received(1).InsertAsync(Arg.Is<ThemeEntity>(theme => theme.ThemeId == manifest.Id && theme.InstallSource == ThemeInstallSource.Bundled), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenPersistingANewBundledThemeFails_ShouldLogAndContinue()
{
// Arrange
ThemeManifestDto manifest = _themeManifestDtoFixture.Create();
string archivePath = CreateArchiveFile();
_mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]);
_mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any<CancellationToken>()).Returns(Result.From(manifest));
_mockThemeService.InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>()).Returns(Result.From(manifest));
_mockThemeService.HasThemePack(manifest.Id).Returns(true);
_mockThemeRepository.InsertAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Themes.InsertFailed", "Failed to insert the theme"));
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockThemeRepository.Received(1).InsertAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenTheArchiveFileCannotBeRead_ShouldLogAndContinue()
{
// Arrange
ThemeManifestDto manifest = _themeManifestDtoFixture.Create();
string missingArchivePath = Path.Combine(_temporaryDirectoryPath, "missing.zip");
_mockThemeService.GetBundledThemeArchivePaths().Returns([missingArchivePath]);
_mockThemeService.ReadManifestFromArchiveAsync(missingArchivePath, Arg.Any<CancellationToken>()).Returns(Result.From(manifest));
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenAccessToTheArchiveFileIsDenied_ShouldLogAndContinue()
{
// On non Windows platforms opening a directory behaves differently, so the test only asserts the denied access path on Windows.
if (!OperatingSystem.IsWindows())
return;
// Arrange
ThemeManifestDto manifest = _themeManifestDtoFixture.Create();
string deniedArchivePath = _temporaryDirectoryPath;
_mockThemeService.GetBundledThemeArchivePaths().Returns([deniedArchivePath]);
_mockThemeService.ReadManifestFromArchiveAsync(deniedArchivePath, Arg.Any<CancellationToken>()).Returns(Result.From(manifest));
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenAllThemesAreHealthyAndNoArchiveIsBundled_ShouldOnlyPersistTheChanges()
{
// Arrange
ThemeEntity healthyTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true);
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(new[] { healthyTheme });
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenABundledThemeIsBroken_ShouldRestoreItsFiles()
{
// Arrange
ThemeEntity brokenTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true);
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(new[] { brokenTheme });
_mockThemeService.HasThemePack(brokenTheme.ThemeId).Returns(false);
_mockThemeService.RestoreBundledThemeAsync(brokenTheme.ThemeId, Arg.Any<CancellationToken>()).Returns(Result.Success);
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockThemeService.Received(1).RestoreBundledThemeAsync(brokenTheme.ThemeId, Arg.Any<CancellationToken>());
await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
await _mockThemeRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenTheLastBundledThemeCannotBeRestored_ShouldKeepIt()
{
// Arrange
ThemeEntity lastBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true);
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(new[] { lastBundledTheme });
_mockThemeService.HasThemePack(lastBundledTheme.ThemeId).Returns(false);
_mockThemeService.RestoreBundledThemeAsync(lastBundledTheme.ThemeId, Arg.Any<CancellationToken>())
.Returns(Error.Failure("Theme.Restore", "Failed to restore the theme"));
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
Assert.False(lastBundledTheme.IsDeleted);
await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenABundledThemeCannotBeRestored_ShouldSoftDeleteIt()
{
// Arrange
ThemeEntity brokenBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false);
ThemeEntity healthyBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true);
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(new[] { brokenBundledTheme, healthyBundledTheme });
_mockThemeService.HasThemePack(brokenBundledTheme.ThemeId).Returns(false);
_mockThemeService.RestoreBundledThemeAsync(brokenBundledTheme.ThemeId, Arg.Any<CancellationToken>())
.Returns(Error.Failure("Theme.Restore", "Failed to restore the theme"));
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
Assert.True(brokenBundledTheme.IsDeleted);
await _mockThemeRepository.Received(1).UpdateAsync(Arg.Is<ThemeEntity>(theme => theme.Id == brokenBundledTheme.Id), Arg.Any<CancellationToken>());
await _mockThemeRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenSoftDeletingABrokenBundledThemeFails_ShouldLogAndContinue()
{
// Arrange
ThemeEntity brokenBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false);
ThemeEntity healthyBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true);
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(new[] { brokenBundledTheme, healthyBundledTheme });
_mockThemeService.HasThemePack(brokenBundledTheme.ThemeId).Returns(false);
_mockThemeService.RestoreBundledThemeAsync(brokenBundledTheme.ThemeId, Arg.Any<CancellationToken>())
.Returns(Error.Failure("Theme.Restore", "Failed to restore the theme"));
_mockThemeRepository.UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Themes.UpdateFailed", "Failed to update the theme"));
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockThemeRepository.Received(1).UpdateAsync(Arg.Is<ThemeEntity>(theme => theme.Id == brokenBundledTheme.Id), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenAUserThemeIsBroken_ShouldDeleteIt()
{
// Arrange
ThemeEntity brokenUserTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Uploaded, isDeleted: false, includeIsCurrent: true, isCurrent: true);
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(new[] { brokenUserTheme });
_mockThemeService.HasThemePack(brokenUserTheme.ThemeId).Returns(false);
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockThemeRepository.Received(1).DeleteByIdAsync(brokenUserTheme.Id, Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenDeletingABrokenUserThemeFails_ShouldLogAndContinue()
{
// Arrange
ThemeEntity brokenUserTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Uploaded, isDeleted: false, includeIsCurrent: true, isCurrent: true);
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(new[] { brokenUserTheme });
_mockThemeService.HasThemePack(brokenUserTheme.ThemeId).Returns(false);
_mockThemeRepository.DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Themes.DeleteFailed", "Failed to delete the theme"));
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockThemeRepository.Received(1).DeleteByIdAsync(brokenUserTheme.Id, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenRepairingOneBrokenThemeThrows_ShouldContinueWithTheRemainingBrokenThemes()
{
// Arrange
ThemeEntity throwingBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false);
ThemeEntity healthyBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true);
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(new[] { throwingBundledTheme, healthyBundledTheme });
_mockThemeService.HasThemePack(Arg.Any<string>()).Returns(false);
_mockThemeService.RestoreBundledThemeAsync(throwingBundledTheme.ThemeId, Arg.Any<CancellationToken>())
.Returns(Task.FromException<Result<Success>>(new InvalidOperationException("Unexpected failure")));
_mockThemeService.RestoreBundledThemeAsync(healthyBundledTheme.ThemeId, Arg.Any<CancellationToken>())
.Returns(Error.Failure("Theme.Restore", "Failed to restore the theme"));
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
// The second broken bundled theme is still soft deleted even though the first one threw.
Assert.True(healthyBundledTheme.IsDeleted);
await _mockThemeRepository.Received(1).UpdateAsync(Arg.Is<ThemeEntity>(theme => theme.Id == healthyBundledTheme.Id), Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenRepairingABrokenThemeIsCancelled_ShouldRethrowTheCancellation()
{
// Arrange
ThemeEntity brokenBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false);
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(new[] { brokenBundledTheme });
_mockThemeService.HasThemePack(brokenBundledTheme.ThemeId).Returns(false);
_mockThemeService.RestoreBundledThemeAsync(brokenBundledTheme.ThemeId, Arg.Any<CancellationToken>())
.Returns(Task.FromException<Result<Success>>(new OperationCanceledException()));
// Act
async Task Act()
{
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
}
// Assert
await Assert.ThrowsAsync<OperationCanceledException>(Act);
}
[Fact]
public async Task EnsureCurrentThemeExistsAsync_WhenANonDeletedThemeIsCurrent_ShouldNotSelectAnotherTheme()
{
// Arrange
ThemeEntity currentTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true);
ThemeEntity otherTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Uploaded, isDeleted: false);
// Act
await InvokeEnsureCurrentThemeExistsAsync([currentTheme, otherTheme]);
// Assert
Assert.True(currentTheme.IsCurrent);
Assert.NotEqual(true, otherTheme.IsCurrent);
await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task EnsureCurrentThemeExistsAsync_WhenNoThemeCanBeSelected_ShouldNotSelectAnyTheme()
{
// Arrange
ThemeEntity deletedTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: true);
// Act
await InvokeEnsureCurrentThemeExistsAsync([deletedTheme]);
// Assert
Assert.NotEqual(true, deletedTheme.IsCurrent);
await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task EnsureCurrentThemeExistsAsync_WhenNoThemeIsCurrent_ShouldActivateTheDefaultTheme()
{
// Arrange
ThemeEntity defaultTheme = _themeEntityFixture.Create(themeId: "lumina-default", installSource: ThemeInstallSource.Bundled, isDeleted: false);
ThemeEntity userTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Uploaded, isDeleted: false);
_mockThemeService.HasThemePack(defaultTheme.ThemeId).Returns(true);
_mockThemeService.HasThemePack(userTheme.ThemeId).Returns(false);
// Act
await InvokeEnsureCurrentThemeExistsAsync([userTheme, defaultTheme]);
// Assert
Assert.True(defaultTheme.IsCurrent);
await _mockThemeRepository.Received(1).UpdateAsync(Arg.Is<ThemeEntity>(theme => theme.Id == defaultTheme.Id), Arg.Any<CancellationToken>());
}
/// <summary>
/// Creates a real archive file on disk so that <see cref="ThemeSynchronizer"/> can open it.
/// </summary>
/// <returns>The path of the created archive file.</returns>
private string CreateArchiveFile()
{
string archivePath = Path.Combine(_temporaryDirectoryPath, $"theme-{Guid.NewGuid():N}.zip");
File.WriteAllText(archivePath, "theme-pack");
return archivePath;
}
/// <summary>
/// Invokes the private <c>EnsureCurrentThemeExistsAsync</c> method of the synchronizer.
/// </summary>
/// <param name="themes">The installed themes passed to the method.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
private async Task InvokeEnsureCurrentThemeExistsAsync(IReadOnlyList<ThemeEntity> themes)
{
MethodInfo method = typeof(ThemeSynchronizer).GetMethod("EnsureCurrentThemeExistsAsync", BindingFlags.Static | BindingFlags.NonPublic)
?? throw new InvalidOperationException("The method 'EnsureCurrentThemeExistsAsync' was not found on the theme synchronizer.");
Task task = (Task)method.Invoke(null, [_mockThemeService, _mockUnitOfWork, themes, CancellationToken.None])!;
await task.ConfigureAwait(false);
}
/// <summary>
/// Removes the temporary files created by the tests.
/// </summary>
public void Dispose()
{
if (Directory.Exists(_temporaryDirectoryPath))
Directory.Delete(_temporaryDirectoryPath, recursive: true);
}
}
@@ -0,0 +1,86 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.Scheduling;
using Lumina.Presentation.Web.Common.Requests.Scheduling;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.AddScheduledJob;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Scheduling;
using Lumina.Presentation.Web.Fixtures.Common.Requests.Scheduling;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Microsoft.AspNetCore.Http;
using NSubstitute;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Scheduler.AddScheduledJob;
/// <summary>
/// Contains unit tests for the <see cref="AddScheduledJobEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddScheduledJobEndpointTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly AddScheduledJobEndpoint _sut;
private readonly AddScheduledJobRequestFixture _addScheduledJobRequestFixture = new();
private readonly ScheduledJobDtoFixture _scheduledJobDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="AddScheduledJobEndpointTests"/> class.
/// </summary>
public AddScheduledJobEndpointTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
_sut = Factory.Create<AddScheduledJobEndpoint>(_mockApiHttpClient);
}
[Fact]
public async Task ExecuteAsync_WhenApiReturnsCreatedJob_ShouldReturnSuccessJsonWithCreatedJob()
{
// Arrange
AddScheduledJobRequest request = _addScheduledJobRequestFixture.Create();
ScheduledJobDto expectedJob = _scheduledJobDtoFixture.Create(name: request.Name);
_mockApiHttpClient.PostAsync<ScheduledJobDto, AddScheduledJobRequest>(ApiRoutes.ScheduledJobs.ADD_SCHEDULED_JOB, Arg.Any<AddScheduledJobRequest>(), Arg.Any<CancellationToken>())
.Returns(expectedJob);
// Act
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
// Assert
using JsonDocument jsonDocument = JsonDocument.Parse(body);
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
Assert.Equal(expectedJob.Name, jsonDocument.RootElement.GetProperty("data").GetProperty("name").GetString());
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldForwardRequestToApiAndReturnSuccess()
{
// Arrange
AddScheduledJobRequest request = _addScheduledJobRequestFixture.Create();
_mockApiHttpClient.PostAsync<ScheduledJobDto, AddScheduledJobRequest>(Arg.Any<string>(), Arg.Any<AddScheduledJobRequest>(), Arg.Any<CancellationToken>())
.Returns(_scheduledJobDtoFixture.Create());
// Act
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
// Assert
await _mockApiHttpClient.Received(1).PostAsync<ScheduledJobDto, AddScheduledJobRequest>(
ApiRoutes.ScheduledJobs.ADD_SCHEDULED_JOB,
Arg.Is<AddScheduledJobRequest>(forwardedRequest =>
forwardedRequest.Name == request.Name &&
forwardedRequest.TaskType == request.TaskType &&
forwardedRequest.ScheduleType == request.ScheduleType &&
forwardedRequest.IntervalMinutes == request.IntervalMinutes &&
forwardedRequest.Hour == request.Hour &&
forwardedRequest.Minute == request.Minute),
Arg.Any<CancellationToken>());
using JsonDocument jsonDocument = JsonDocument.Parse(body);
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
}
}
@@ -0,0 +1,57 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Requests.Scheduling;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.FireScheduledJob;
using Lumina.Presentation.Web.Fixtures.Common.Requests.Scheduling;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Microsoft.AspNetCore.Http;
using NSubstitute;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Scheduler.FireScheduledJob;
/// <summary>
/// Contains unit tests for the <see cref="FireScheduledJobEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class FireScheduledJobEndpointTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly FireScheduledJobEndpoint _sut;
private readonly FireScheduledJobRequestFixture _fireScheduledJobRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="FireScheduledJobEndpointTests"/> class.
/// </summary>
public FireScheduledJobEndpointTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
_sut = Factory.Create<FireScheduledJobEndpoint>(_mockApiHttpClient);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldFireScheduledJobViaApiAndReturnSuccess()
{
// Arrange
FireScheduledJobRequest request = _fireScheduledJobRequestFixture.Create();
// Act
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
// Assert
string expectedEndpoint = ApiRoutes.ScheduledJobs.FIRE_SCHEDULED_JOB.Replace("{scheduledJobId}", request.ScheduledJobId.ToString());
await _mockApiHttpClient.Received(1).PutAsync<Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest, Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest>(
expectedEndpoint,
Arg.Any<Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
using JsonDocument jsonDocument = JsonDocument.Parse(body);
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
}
}
@@ -0,0 +1,126 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.Scheduling;
using Lumina.Presentation.Web.Common.Requests.Scheduling;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.GetScheduledJobHistory;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Scheduling;
using Lumina.Presentation.Web.Fixtures.Common.Requests.Scheduling;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Microsoft.AspNetCore.Http;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Scheduler.GetScheduledJobHistory;
/// <summary>
/// Contains unit tests for the <see cref="GetScheduledJobHistoryEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetScheduledJobHistoryEndpointTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly GetScheduledJobHistoryEndpoint _sut;
private readonly GetScheduledJobHistoryRequestFixture _getScheduledJobHistoryRequestFixture = new();
private readonly ScheduledJobExecutionDtoFixture _scheduledJobExecutionDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetScheduledJobHistoryEndpointTests"/> class.
/// </summary>
public GetScheduledJobHistoryEndpointTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
_sut = Factory.Create<GetScheduledJobHistoryEndpoint>(_mockApiHttpClient);
}
[Fact]
public async Task ExecuteAsync_WhenApiReturnsExecutions_ShouldReturnSuccessJsonWithExecutions()
{
// Arrange
ScheduledJobExecutionDto[] expectedExecutions = [.. _scheduledJobExecutionDtoFixture.CreateMany(2)];
_mockApiHttpClient.GetAsync<ScheduledJobExecutionDto[]>(ApiRoutes.ScheduledJobs.GET_SCHEDULED_JOB_HISTORY, Arg.Any<CancellationToken>())
.Returns(expectedExecutions);
// Act
IResult result = await _sut.ExecuteAsync(_getScheduledJobHistoryRequestFixture.Create(), CancellationToken.None);
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
// Assert
using JsonDocument jsonDocument = JsonDocument.Parse(body);
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
Assert.Equal(expectedExecutions.Length, jsonDocument.RootElement.GetProperty("data").GetArrayLength());
}
[Fact]
public async Task ExecuteAsync_WhenFromAndToAreNull_ShouldRequestHistoryWithoutQueryString()
{
// Arrange
GetScheduledJobHistoryRequest request = _getScheduledJobHistoryRequestFixture.Create();
_mockApiHttpClient.GetAsync<ScheduledJobExecutionDto[]>(ApiRoutes.ScheduledJobs.GET_SCHEDULED_JOB_HISTORY, Arg.Any<CancellationToken>())
.Returns([]);
// Act
await _sut.ExecuteAsync(request, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).GetAsync<ScheduledJobExecutionDto[]>(ApiRoutes.ScheduledJobs.GET_SCHEDULED_JOB_HISTORY, Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenOnlyFromIsProvided_ShouldRequestHistoryWithFromQueryString()
{
// Arrange
DateTime from = new(2026, 1, 5, 4, 3, 2, DateTimeKind.Utc);
GetScheduledJobHistoryRequest request = _getScheduledJobHistoryRequestFixture.Create(from: from);
string expectedEndpoint = $"{ApiRoutes.ScheduledJobs.GET_SCHEDULED_JOB_HISTORY}?from={Uri.EscapeDataString(from.ToString("o"))}";
_mockApiHttpClient.GetAsync<ScheduledJobExecutionDto[]>(expectedEndpoint, Arg.Any<CancellationToken>())
.Returns([]);
// Act
await _sut.ExecuteAsync(request, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).GetAsync<ScheduledJobExecutionDto[]>(expectedEndpoint, Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenOnlyToIsProvided_ShouldRequestHistoryWithToQueryString()
{
// Arrange
DateTime to = new(2026, 1, 5, 4, 3, 2, DateTimeKind.Utc);
GetScheduledJobHistoryRequest request = _getScheduledJobHistoryRequestFixture.Create(to: to);
string expectedEndpoint = $"{ApiRoutes.ScheduledJobs.GET_SCHEDULED_JOB_HISTORY}?to={Uri.EscapeDataString(to.ToString("o"))}";
_mockApiHttpClient.GetAsync<ScheduledJobExecutionDto[]>(expectedEndpoint, Arg.Any<CancellationToken>())
.Returns([]);
// Act
await _sut.ExecuteAsync(request, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).GetAsync<ScheduledJobExecutionDto[]>(expectedEndpoint, Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenFromAndToAreProvided_ShouldRequestHistoryWithBothQueryStrings()
{
// Arrange
DateTime from = new(2026, 1, 5, 4, 3, 2, DateTimeKind.Utc);
DateTime to = new(2026, 1, 6, 4, 3, 2, DateTimeKind.Utc);
GetScheduledJobHistoryRequest request = _getScheduledJobHistoryRequestFixture.Create(from: from, to: to);
string expectedEndpoint = $"{ApiRoutes.ScheduledJobs.GET_SCHEDULED_JOB_HISTORY}?from={Uri.EscapeDataString(from.ToString("o"))}&to={Uri.EscapeDataString(to.ToString("o"))}";
_mockApiHttpClient.GetAsync<ScheduledJobExecutionDto[]>(expectedEndpoint, Arg.Any<CancellationToken>())
.Returns([]);
// Act
await _sut.ExecuteAsync(request, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).GetAsync<ScheduledJobExecutionDto[]>(expectedEndpoint, Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,73 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.Scheduling;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.GetScheduledJobs;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Scheduling;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Microsoft.AspNetCore.Http;
using NSubstitute;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Scheduler.GetScheduledJobs;
/// <summary>
/// Contains unit tests for the <see cref="GetScheduledJobsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetScheduledJobsEndpointTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly GetScheduledJobsEndpoint _sut;
private readonly ScheduledJobDtoFixture _scheduledJobDtoFixture = new();
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
/// <summary>
/// Initializes a new instance of the <see cref="GetScheduledJobsEndpointTests"/> class.
/// </summary>
public GetScheduledJobsEndpointTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
_sut = Factory.Create<GetScheduledJobsEndpoint>(_mockApiHttpClient);
}
[Fact]
public async Task ExecuteAsync_WhenApiReturnsJobs_ShouldReturnSuccessJsonWithScheduledJobs()
{
// Arrange
ScheduledJobDto[] expectedJobs = [.. _scheduledJobDtoFixture.CreateMany(2)];
_mockApiHttpClient.GetAsync<ScheduledJobDto[]>(ApiRoutes.ScheduledJobs.GET_SCHEDULED_JOBS, Arg.Any<CancellationToken>())
.Returns(expectedJobs);
// Act
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
// Assert
using JsonDocument jsonDocument = JsonDocument.Parse(body);
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
ScheduledJobDto[]? returnedJobs = jsonDocument.RootElement.GetProperty("data").Deserialize<ScheduledJobDto[]>(_jsonOptions);
Assert.Equal(expectedJobs.Length, returnedJobs!.Length);
Assert.Equal(expectedJobs.Select(job => job.Name), returnedJobs.Select(job => job.Name));
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldRequestScheduledJobsFromApi()
{
// Arrange
_mockApiHttpClient.GetAsync<ScheduledJobDto[]>(ApiRoutes.ScheduledJobs.GET_SCHEDULED_JOBS, Arg.Any<CancellationToken>())
.Returns([.. _scheduledJobDtoFixture.CreateMany()]);
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).GetAsync<ScheduledJobDto[]>(ApiRoutes.ScheduledJobs.GET_SCHEDULED_JOBS, Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,69 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.Scheduling;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.GetSchedulerDisplayPreferences;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Scheduling;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Microsoft.AspNetCore.Http;
using NSubstitute;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Scheduler.GetSchedulerDisplayPreferences;
/// <summary>
/// Contains unit tests for the <see cref="GetSchedulerDisplayPreferencesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetSchedulerDisplayPreferencesEndpointTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly GetSchedulerDisplayPreferencesEndpoint _sut;
private readonly SchedulerDisplayPreferencesDtoFixture _schedulerDisplayPreferencesDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetSchedulerDisplayPreferencesEndpointTests"/> class.
/// </summary>
public GetSchedulerDisplayPreferencesEndpointTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
_sut = Factory.Create<GetSchedulerDisplayPreferencesEndpoint>(_mockApiHttpClient);
}
[Fact]
public async Task ExecuteAsync_WhenApiReturnsPreferences_ShouldReturnSuccessJsonWithDisplayPreferences()
{
// Arrange
SchedulerDisplayPreferencesDto expectedPreferences = _schedulerDisplayPreferencesDtoFixture.Create(displayTimeUnit: Lumina.Presentation.Web.Common.Enums.Scheduling.SchedulerDisplayTimeUnit.Minutes);
_mockApiHttpClient.GetAsync<SchedulerDisplayPreferencesDto>(ApiRoutes.ScheduledJobs.GET_DISPLAY_PREFERENCES, Arg.Any<CancellationToken>())
.Returns(expectedPreferences);
// Act
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
// Assert
using JsonDocument jsonDocument = JsonDocument.Parse(body);
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
Assert.Equal(expectedPreferences.UserId, jsonDocument.RootElement.GetProperty("data").GetProperty("userId").GetGuid());
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldRequestDisplayPreferencesFromApi()
{
// Arrange
_mockApiHttpClient.GetAsync<SchedulerDisplayPreferencesDto>(ApiRoutes.ScheduledJobs.GET_DISPLAY_PREFERENCES, Arg.Any<CancellationToken>())
.Returns(_schedulerDisplayPreferencesDtoFixture.Create());
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).GetAsync<SchedulerDisplayPreferencesDto>(ApiRoutes.ScheduledJobs.GET_DISPLAY_PREFERENCES, Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,54 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Requests.Scheduling;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.RemoveScheduledJob;
using Lumina.Presentation.Web.Fixtures.Common.Requests.Scheduling;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Microsoft.AspNetCore.Http;
using NSubstitute;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Scheduler.RemoveScheduledJob;
/// <summary>
/// Contains unit tests for the <see cref="RemoveScheduledJobEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RemoveScheduledJobEndpointTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly RemoveScheduledJobEndpoint _sut;
private readonly RemoveScheduledJobRequestFixture _removeScheduledJobRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="RemoveScheduledJobEndpointTests"/> class.
/// </summary>
public RemoveScheduledJobEndpointTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
_sut = Factory.Create<RemoveScheduledJobEndpoint>(_mockApiHttpClient);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldRemoveScheduledJobViaApiAndReturnSuccess()
{
// Arrange
RemoveScheduledJobRequest request = _removeScheduledJobRequestFixture.Create();
// Act
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
// Assert
string expectedEndpoint = ApiRoutes.ScheduledJobs.REMOVE_SCHEDULED_JOB.Replace("{scheduledJobId}", request.ScheduledJobId.ToString());
await _mockApiHttpClient.Received(1).DeleteAsync(expectedEndpoint, Arg.Any<CancellationToken>());
using JsonDocument jsonDocument = JsonDocument.Parse(body);
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
}
}
@@ -0,0 +1,140 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.Configuration;
using Lumina.Presentation.Web.Common.DTO.Themes;
using Lumina.Presentation.Web.Common.Http;
using Lumina.Presentation.Web.Common.Primitives;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Common.Services;
using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler;
using Lumina.Presentation.Web.Core.Themes;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Configuration;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Options;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Scheduler;
/// <summary>
/// Contains unit tests for the <see cref="SchedulerIndexViewEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SchedulerIndexViewEndpointTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly IAntiforgery _mockAntiforgery;
private readonly IOptionsSnapshot<ServerConfigurationDto> _mockServerConfigurationOptions;
private readonly IUrlService _mockUrlService;
private readonly ThemePageRenderer _mockThemePageRenderer;
private readonly IStringLocalizerFactory _mockStringLocalizerFactory;
private readonly IStringLocalizer _mockStringLocalizer;
private readonly SchedulerIndexViewEndpoint _sut;
private readonly ServerConfigurationDtoFixture _serverConfigurationDtoFixture = new();
private readonly ThemePageRenderResultDtoFixture _themePageRenderResultDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="SchedulerIndexViewEndpointTests"/> class.
/// </summary>
public SchedulerIndexViewEndpointTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
_mockAntiforgery = Substitute.For<IAntiforgery>();
_mockAntiforgery.GetAndStoreTokens(Arg.Any<HttpContext>())
.Returns(new AntiforgeryTokenSet("test-request-token", "test-cookie-token", "__RequestVerificationToken", "RequestVerificationToken"));
_mockServerConfigurationOptions = Substitute.For<IOptionsSnapshot<ServerConfigurationDto>>();
_mockServerConfigurationOptions.Value.Returns(_serverConfigurationDtoFixture.Create(baseAddress: "http://localhost", port: 5214));
_mockUrlService = Substitute.For<IUrlService>();
_mockThemePageRenderer = Substitute.For<ThemePageRenderer>(new ThemeService(_mockApiHttpClient), new ThemeTemplateEngine());
_mockStringLocalizer = Substitute.For<IStringLocalizer>();
_mockStringLocalizer[Arg.Any<string>()].Returns(callInfo => new LocalizedString(callInfo.Arg<string>(), callInfo.Arg<string>()));
_mockStringLocalizer.GetAllStrings(Arg.Any<bool>()).Returns(
[
new LocalizedString("ScheduledJobs", "Scheduled Jobs"),
new LocalizedString("TaskType.ScanMediaLibraries", "Scan media libraries"),
new LocalizedString("TaskType.CleanTemporaryFiles", "Clean temporary files"),
new LocalizedString("TaskType.RepairThemes", "Repair themes"),
new LocalizedString("TaskType.CleanScheduledJobExecutionHistory", "Clean execution history"),
new LocalizedString("Status.Added", "Added"),
new LocalizedString("Status.Active", "Active"),
new LocalizedString("Status.Running", "Running"),
new LocalizedString("Status.Completed", "Completed")
]);
_mockStringLocalizerFactory = Substitute.For<IStringLocalizerFactory>();
_mockStringLocalizerFactory.Create(Arg.Any<string>(), Arg.Any<string>()).Returns(_mockStringLocalizer);
_sut = Factory.Create<SchedulerIndexViewEndpoint>(_mockAntiforgery, _mockServerConfigurationOptions, _mockUrlService, _mockThemePageRenderer, _mockStringLocalizerFactory);
TestHttpContextFactory.ConfigureSession(_sut.HttpContext, TestHttpContextFactory.CreateSession());
_sut.HttpContext.Request.Path = "/en-us/admin/scheduled-jobs";
}
[Fact]
public async Task ExecuteAsync_WhenThemeRenderingSucceeds_ShouldRenderThemedPageThroughTheSharedView()
{
// Arrange
_mockUrlService.GetAbsoluteUrl(WebRoutes.Scheduler.GET_SCHEDULED_JOBS).Returns("http://localhost/en-us/admin/api-scheduled-jobs");
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_themePageRenderResultDtoFixture.Create(content: "<section>content</section>", script: "<script>script</script>")));
// Act
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
Assert.IsType<RazorViewResult>(result);
await _mockThemePageRenderer.Received(1).RenderAsync(
Arg.Is<ThemePageDto>(page =>
page.PageKey == "admin/scheduler" &&
page.Title == "ScheduledJobs" &&
string.Equals(page.PageData["scheduledJobsHubUrl"] as string, "http://localhost:5214/scheduledJobsHub", StringComparison.Ordinal) &&
string.Equals(page.PageData["jobsListUrl"] as string, "http://localhost/en-us/admin/api-scheduled-jobs", StringComparison.Ordinal) &&
string.Equals(page.PageData["antiforgeryToken"] as string, "test-request-token", StringComparison.Ordinal) &&
page.PageData.ContainsKey("strings")),
Arg.Is<string?>(requestedThemeId => requestedThemeId == null),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenThemeRenderingFails_ShouldFallBackToRazorView()
{
// Arrange
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(Result<ThemePageRenderResultDto>.Failure(Error.Failure("Theme.Render", "The page could not be rendered.")));
// Act
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
Assert.IsType<RazorViewResult>(result);
await _mockThemePageRenderer.Received(1).RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldStoreAntiforgeryTokenAndRequestSchedulerUrls()
{
// Arrange
_mockUrlService.GetAbsoluteUrl(WebRoutes.Scheduler.GET_DISPLAY_PREFERENCES).Returns("http://localhost/en-us/admin/api-scheduled-jobs/display-preferences");
_mockUrlService.GetAbsoluteUrl(WebRoutes.Scheduler.START_SCHEDULED_JOB, Arg.Any<object>()).Returns("http://localhost/en-us/admin/api-scheduled-jobs/00000000-0000-0000-0000-000000000000/start");
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_themePageRenderResultDtoFixture.Create()));
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
_mockAntiforgery.Received(1).GetAndStoreTokens(_sut.HttpContext);
await _mockThemePageRenderer.Received(1).RenderAsync(
Arg.Is<ThemePageDto>(page =>
string.Equals(page.PageData["getDisplayPreferencesUrl"] as string, "http://localhost/en-us/admin/api-scheduled-jobs/display-preferences", StringComparison.Ordinal) &&
string.Equals(page.PageData["startJobUrlTemplate"] as string, "http://localhost/en-us/admin/api-scheduled-jobs/00000000-0000-0000-0000-000000000000/start", StringComparison.Ordinal)),
Arg.Any<string?>(),
Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,57 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Requests.Scheduling;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.StartScheduledJob;
using Lumina.Presentation.Web.Fixtures.Common.Requests.Scheduling;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Microsoft.AspNetCore.Http;
using NSubstitute;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Scheduler.StartScheduledJob;
/// <summary>
/// Contains unit tests for the <see cref="StartScheduledJobEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class StartScheduledJobEndpointTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly StartScheduledJobEndpoint _sut;
private readonly StartScheduledJobRequestFixture _startScheduledJobRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="StartScheduledJobEndpointTests"/> class.
/// </summary>
public StartScheduledJobEndpointTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
_sut = Factory.Create<StartScheduledJobEndpoint>(_mockApiHttpClient);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldStartScheduledJobViaApiAndReturnSuccess()
{
// Arrange
StartScheduledJobRequest request = _startScheduledJobRequestFixture.Create();
// Act
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
// Assert
string expectedEndpoint = ApiRoutes.ScheduledJobs.START_SCHEDULED_JOB.Replace("{scheduledJobId}", request.ScheduledJobId.ToString());
await _mockApiHttpClient.Received(1).PutAsync<Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest, Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest>(
expectedEndpoint,
Arg.Any<Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
using JsonDocument jsonDocument = JsonDocument.Parse(body);
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
}
}
@@ -0,0 +1,57 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Requests.Scheduling;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.StopScheduledJob;
using Lumina.Presentation.Web.Fixtures.Common.Requests.Scheduling;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Microsoft.AspNetCore.Http;
using NSubstitute;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Scheduler.StopScheduledJob;
/// <summary>
/// Contains unit tests for the <see cref="StopScheduledJobEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class StopScheduledJobEndpointTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly StopScheduledJobEndpoint _sut;
private readonly StopScheduledJobRequestFixture _stopScheduledJobRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="StopScheduledJobEndpointTests"/> class.
/// </summary>
public StopScheduledJobEndpointTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
_sut = Factory.Create<StopScheduledJobEndpoint>(_mockApiHttpClient);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldStopScheduledJobViaApiAndReturnSuccess()
{
// Arrange
StopScheduledJobRequest request = _stopScheduledJobRequestFixture.Create();
// Act
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
// Assert
string expectedEndpoint = ApiRoutes.ScheduledJobs.STOP_SCHEDULED_JOB.Replace("{scheduledJobId}", request.ScheduledJobId.ToString());
await _mockApiHttpClient.Received(1).PutAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
expectedEndpoint,
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
using JsonDocument jsonDocument = JsonDocument.Parse(body);
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
}
}
@@ -0,0 +1,59 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Requests.Scheduling;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.UpdateSchedulerDisplayPreferences;
using Lumina.Presentation.Web.Fixtures.Common.Requests.Scheduling;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Microsoft.AspNetCore.Http;
using NSubstitute;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Scheduler.UpdateSchedulerDisplayPreferences;
/// <summary>
/// Contains unit tests for the <see cref="UpdateSchedulerDisplayPreferencesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateSchedulerDisplayPreferencesEndpointTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly UpdateSchedulerDisplayPreferencesEndpoint _sut;
private readonly UpdateSchedulerDisplayPreferencesRequestFixture _updateSchedulerDisplayPreferencesRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="UpdateSchedulerDisplayPreferencesEndpointTests"/> class.
/// </summary>
public UpdateSchedulerDisplayPreferencesEndpointTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
_sut = Factory.Create<UpdateSchedulerDisplayPreferencesEndpoint>(_mockApiHttpClient);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldUpdateDisplayPreferencesViaApiAndReturnSuccess()
{
// Arrange
UpdateSchedulerDisplayPreferencesRequest request = _updateSchedulerDisplayPreferencesRequestFixture.Create();
// Act
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
// Assert
await _mockApiHttpClient.Received(1).PutAsync<Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest, UpdateSchedulerDisplayPreferencesRequest>(
ApiRoutes.ScheduledJobs.UPDATE_DISPLAY_PREFERENCES,
Arg.Is<UpdateSchedulerDisplayPreferencesRequest>(forwardedRequest =>
forwardedRequest.JobTypeFilter == request.JobTypeFilter &&
forwardedRequest.DisplayTimeSpan == request.DisplayTimeSpan &&
forwardedRequest.DisplayTimeUnit == request.DisplayTimeUnit),
Arg.Any<CancellationToken>());
using JsonDocument jsonDocument = JsonDocument.Parse(body);
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
}
}