Adds the scheduling module tests and centralizes domain event test fixtures

This commit is contained in:
BinaryAlley committed 2026-09-04 00:16:41 -07:00
1 parent 237be9e2c8
commit 99a6159f7f
135 files changed
+10203 -165

No files matched your search

@@ -0,0 +1,103 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
/// <summary>
/// Fixture class for the <see cref="ScheduledJobEntity"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScheduledJobEntityFixture
{
/// <summary>
/// Creates a random valid <see cref="ScheduledJobEntity"/>.
/// </summary>
/// <param name="id">Optional. The Id of the scheduled job.</param>
/// <param name="name">Optional. The name of the scheduled job.</param>
/// <param name="taskType">Optional. The type of the task executed by the scheduled job.</param>
/// <param name="scheduleType">Optional. The type of the schedule of the scheduled job.</param>
/// <param name="intervalMinutes">Optional. The interval in minutes of the schedule.</param>
/// <param name="hour">Optional. The hour of the schedule.</param>
/// <param name="minute">Optional. The minute of the schedule.</param>
/// <param name="status">Optional. The status of the scheduled job.</param>
/// <param name="ownerUserId">Optional. The Id of the user that owns the scheduled job.</param>
/// <param name="lastStartedOnUtc">Optional. The last start time of the scheduled job.</param>
/// <param name="lastCompletedOnUtc">Optional. The last completion time of the scheduled job.</param>
/// <returns>The created <see cref="ScheduledJobEntity"/>.</returns>
public ScheduledJobEntity 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,
Guid? ownerUserId = null,
DateTime? lastStartedOnUtc = null,
DateTime? lastCompletedOnUtc = null)
{
return new Faker<ScheduledJobEntity>()
.CustomInstantiator(f =>
{
ScheduleType resolvedScheduleType = scheduleType ?? f.PickRandom<ScheduleType>();
if (resolvedScheduleType == ScheduleType.WithIntervalInMinutes)
{
return new ScheduledJobEntity
{
Id = id ?? Guid.NewGuid(),
Name = name ?? f.Commerce.ProductName(),
TaskType = taskType ?? f.PickRandom<ScheduledTaskType>(),
ScheduleType = resolvedScheduleType,
IntervalMinutes = intervalMinutes ?? f.Random.Int(1, 1440),
Hour = null,
Minute = null,
Status = status ?? f.PickRandom<ScheduledJobStatus>(),
OwnerUserId = ownerUserId ?? Guid.NewGuid(),
LastStartedOnUtc = lastStartedOnUtc,
LastCompletedOnUtc = lastCompletedOnUtc,
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = Guid.NewGuid(),
UpdatedOnUtc = null,
UpdatedBy = null
};
}
return new ScheduledJobEntity
{
Id = id ?? Guid.NewGuid(),
Name = name ?? f.Commerce.ProductName(),
TaskType = taskType ?? f.PickRandom<ScheduledTaskType>(),
ScheduleType = resolvedScheduleType,
IntervalMinutes = null,
Hour = hour ?? f.Random.Int(0, 23),
Minute = minute ?? f.Random.Int(0, 59),
Status = status ?? f.PickRandom<ScheduledJobStatus>(),
OwnerUserId = ownerUserId ?? Guid.NewGuid(),
LastStartedOnUtc = lastStartedOnUtc,
LastCompletedOnUtc = lastCompletedOnUtc,
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = Guid.NewGuid(),
UpdatedOnUtc = null,
UpdatedBy = null
};
})
.Generate();
}
/// <summary>
/// Creates a list of <see cref="ScheduledJobEntity"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="ScheduledJobEntity"/> instances.</returns>
public List<ScheduledJobEntity> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,63 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
/// <summary>
/// Fixture class for the <see cref="ScheduledJobExecutionEntity"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScheduledJobExecutionEntityFixture
{
/// <summary>
/// Creates a random valid <see cref="ScheduledJobExecutionEntity"/>.
/// </summary>
/// <param name="id">Optional. The Id of the execution.</param>
/// <param name="scheduledJobId">Optional. The Id of the scheduled job whose task was executed.</param>
/// <param name="taskType">Optional. The type of the task that was executed.</param>
/// <param name="isCycleRun">Optional. Whether the execution was a cycle run.</param>
/// <param name="startedOnUtc">Optional. The start time of the execution.</param>
/// <param name="completedOnUtc">Optional. The completion time of the execution.</param>
/// <returns>The created <see cref="ScheduledJobExecutionEntity"/>.</returns>
public ScheduledJobExecutionEntity Create(
Guid? id = null,
Guid? scheduledJobId = null,
ScheduledTaskType? taskType = null,
bool? isCycleRun = null,
DateTime? startedOnUtc = null,
DateTime? completedOnUtc = null)
{
return new Faker<ScheduledJobExecutionEntity>()
.CustomInstantiator(f => new ScheduledJobExecutionEntity
{
Id = id ?? Guid.NewGuid(),
ScheduledJobId = scheduledJobId ?? Guid.NewGuid(),
TaskType = taskType ?? f.PickRandom<ScheduledTaskType>(),
IsCycleRun = isCycleRun ?? f.Random.Bool(),
StartedOnUtc = startedOnUtc ?? DateTime.UtcNow,
CompletedOnUtc = completedOnUtc,
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = Guid.NewGuid(),
UpdatedOnUtc = null,
UpdatedBy = null
})
.Generate();
}
/// <summary>
/// Creates a list of <see cref="ScheduledJobExecutionEntity"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="ScheduledJobExecutionEntity"/> instances.</returns>
public List<ScheduledJobExecutionEntity> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,60 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
/// <summary>
/// Fixture class for the <see cref="SchedulerDisplayPreferencesEntity"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SchedulerDisplayPreferencesEntityFixture
{
/// <summary>
/// Creates a random valid <see cref="SchedulerDisplayPreferencesEntity"/>.
/// </summary>
/// <param name="id">Optional. The Id of the display preferences.</param>
/// <param name="userId">Optional. The Id of the user that owns the display preferences.</param>
/// <param name="jobTypeFilter">Optional. The type of the scheduled job tasks whose executions are shown.</param>
/// <param name="displayTimeSpan">Optional. The displayed time span.</param>
/// <param name="displayTimeUnit">Optional. The unit of the displayed time span.</param>
/// <returns>The created <see cref="SchedulerDisplayPreferencesEntity"/>.</returns>
public SchedulerDisplayPreferencesEntity Create(
Guid? id = null,
Guid? userId = null,
ScheduledTaskType? jobTypeFilter = null,
int? displayTimeSpan = null,
SchedulerDisplayTimeUnit? displayTimeUnit = null)
{
return new Faker<SchedulerDisplayPreferencesEntity>()
.CustomInstantiator(f => new SchedulerDisplayPreferencesEntity
{
Id = id ?? Guid.NewGuid(),
UserId = userId ?? Guid.NewGuid(),
JobTypeFilter = jobTypeFilter ?? (f.Random.Bool() ? f.PickRandom<ScheduledTaskType>() : null),
DisplayTimeSpan = displayTimeSpan ?? f.Random.Int(1, 24 * 60),
DisplayTimeUnit = displayTimeUnit ?? f.PickRandom<SchedulerDisplayTimeUnit>(),
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = Guid.NewGuid(),
UpdatedOnUtc = null,
UpdatedBy = null
})
.Generate();
}
/// <summary>
/// Creates a list of <see cref="SchedulerDisplayPreferencesEntity"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="SchedulerDisplayPreferencesEntity"/> instances.</returns>
public List<SchedulerDisplayPreferencesEntity> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,70 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.Scheduling.Commands.AddScheduledJob;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Core.Scheduling.Commands.AddScheduledJob;
/// <summary>
/// Fixture class for the <see cref="AddScheduledJobCommand"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddScheduledJobCommandFixture
{
/// <summary>
/// Creates a random valid command to add a scheduled job.
/// </summary>
/// <param name="name">Optional. The name of the scheduled job.</param>
/// <param name="taskType">Optional. The type of the task executed by the scheduled job.</param>
/// <param name="scheduleType">Optional. The type of the schedule of the scheduled job.</param>
/// <param name="intervalMinutes">Optional. The interval in minutes of the schedule.</param>
/// <param name="hour">Optional. The hour of the schedule.</param>
/// <param name="minute">Optional. The minute of the schedule.</param>
/// <returns>The created command.</returns>
public AddScheduledJobCommand Create(
string? name = null,
ScheduledTaskType? taskType = null,
ScheduleType? scheduleType = null,
int? intervalMinutes = null,
int? hour = null,
int? minute = null)
{
return new Faker<AddScheduledJobCommand>()
.CustomInstantiator(f =>
{
ScheduleType resolvedScheduleType = scheduleType ?? f.PickRandom<ScheduleType>();
if (resolvedScheduleType == ScheduleType.WithIntervalInMinutes)
{
return new AddScheduledJobCommand(
name ?? f.Commerce.ProductName(),
taskType ?? f.PickRandom<ScheduledTaskType>(),
resolvedScheduleType,
intervalMinutes ?? f.Random.Int(1, 1440),
null,
null);
}
return new AddScheduledJobCommand(
name ?? f.Commerce.ProductName(),
taskType ?? f.PickRandom<ScheduledTaskType>(),
resolvedScheduleType,
null,
hour ?? f.Random.Int(0, 23),
minute ?? f.Random.Int(0, 59));
})
.Generate();
}
/// <summary>
/// Creates a list of <see cref="AddScheduledJobCommand"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<AddScheduledJobCommand> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,40 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.Scheduling.Commands.FireScheduledJob;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Core.Scheduling.Commands.FireScheduledJob;
/// <summary>
/// Fixture class for the <see cref="FireScheduledJobCommand"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class FireScheduledJobCommandFixture
{
/// <summary>
/// Creates a random valid command to fire the task of a scheduled job once.
/// </summary>
/// <param name="scheduledJobId">Optional. The Id of the scheduled job whose task is fired.</param>
/// <returns>The created command.</returns>
public FireScheduledJobCommand Create(
Guid? scheduledJobId = null)
{
return new Faker<FireScheduledJobCommand>()
.CustomInstantiator(f => new FireScheduledJobCommand(scheduledJobId ?? Guid.NewGuid()))
.Generate();
}
/// <summary>
/// Creates a list of <see cref="FireScheduledJobCommand"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<FireScheduledJobCommand> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,40 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.Scheduling.Commands.RemoveScheduledJob;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Core.Scheduling.Commands.RemoveScheduledJob;
/// <summary>
/// Fixture class for the <see cref="RemoveScheduledJobCommand"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RemoveScheduledJobCommandFixture
{
/// <summary>
/// Creates a random valid command to remove a scheduled job.
/// </summary>
/// <param name="scheduledJobId">Optional. The Id of the scheduled job to remove.</param>
/// <returns>The created command.</returns>
public RemoveScheduledJobCommand Create(
Guid? scheduledJobId = null)
{
return new Faker<RemoveScheduledJobCommand>()
.CustomInstantiator(f => new RemoveScheduledJobCommand(scheduledJobId ?? Guid.NewGuid()))
.Generate();
}
/// <summary>
/// Creates a list of <see cref="RemoveScheduledJobCommand"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<RemoveScheduledJobCommand> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,40 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.Scheduling.Commands.StartScheduledJob;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Core.Scheduling.Commands.StartScheduledJob;
/// <summary>
/// Fixture class for the <see cref="StartScheduledJobCommand"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class StartScheduledJobCommandFixture
{
/// <summary>
/// Creates a random valid command to start the execution cycle of a scheduled job.
/// </summary>
/// <param name="scheduledJobId">Optional. The Id of the scheduled job whose execution cycle is started.</param>
/// <returns>The created command.</returns>
public StartScheduledJobCommand Create(
Guid? scheduledJobId = null)
{
return new Faker<StartScheduledJobCommand>()
.CustomInstantiator(f => new StartScheduledJobCommand(scheduledJobId ?? Guid.NewGuid()))
.Generate();
}
/// <summary>
/// Creates a list of <see cref="StartScheduledJobCommand"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<StartScheduledJobCommand> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,40 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.Scheduling.Commands.StopScheduledJob;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Core.Scheduling.Commands.StopScheduledJob;
/// <summary>
/// Fixture class for the <see cref="StopScheduledJobCommand"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class StopScheduledJobCommandFixture
{
/// <summary>
/// Creates a random valid command to stop the execution cycle of a scheduled job.
/// </summary>
/// <param name="scheduledJobId">Optional. The Id of the scheduled job whose execution cycle is stopped.</param>
/// <returns>The created command.</returns>
public StopScheduledJobCommand Create(
Guid? scheduledJobId = null)
{
return new Faker<StopScheduledJobCommand>()
.CustomInstantiator(f => new StopScheduledJobCommand(scheduledJobId ?? Guid.NewGuid()))
.Generate();
}
/// <summary>
/// Creates a list of <see cref="StopScheduledJobCommand"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<StopScheduledJobCommand> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,47 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.Scheduling.Commands.UpdateSchedulerDisplayPreferences;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Core.Scheduling.Commands.UpdateSchedulerDisplayPreferences;
/// <summary>
/// Fixture class for the <see cref="UpdateSchedulerDisplayPreferencesCommand"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateSchedulerDisplayPreferencesCommandFixture
{
/// <summary>
/// Creates a random valid command to update the display preferences of the scheduler page of the current user.
/// </summary>
/// <param name="jobTypeFilter">Optional. The type of the scheduled job tasks whose executions are shown.</param>
/// <param name="displayTimeSpan">Optional. The displayed time span.</param>
/// <param name="displayTimeUnit">Optional. The unit of the displayed time span.</param>
/// <returns>The created command.</returns>
public UpdateSchedulerDisplayPreferencesCommand Create(
ScheduledTaskType? jobTypeFilter = null,
int? displayTimeSpan = null,
SchedulerDisplayTimeUnit? displayTimeUnit = null)
{
return new Faker<UpdateSchedulerDisplayPreferencesCommand>()
.CustomInstantiator(f => new UpdateSchedulerDisplayPreferencesCommand(
jobTypeFilter ?? (f.Random.Bool() ? f.PickRandom<ScheduledTaskType>() : null),
displayTimeSpan ?? f.Random.Int(1, 24 * 60),
displayTimeUnit ?? f.PickRandom<SchedulerDisplayTimeUnit>()))
.Generate();
}
/// <summary>
/// Creates a list of <see cref="UpdateSchedulerDisplayPreferencesCommand"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<UpdateSchedulerDisplayPreferencesCommand> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,53 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.Scheduling.Queries.GetScheduledJobHistory;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Core.Scheduling.Queries.GetScheduledJobHistory;
/// <summary>
/// Fixture class for the <see cref="GetScheduledJobHistoryQuery"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetScheduledJobHistoryQueryFixture
{
/// <summary>
/// Creates a random valid query to get the history of the executions of the tasks of scheduled jobs.
/// </summary>
/// <param name="from">Optional. The inclusive lower bound of the requested interval.</param>
/// <param name="to">Optional. The inclusive upper bound of the requested interval.</param>
/// <param name="includeFrom">Whether to include the lower bound in the query. When false, the lower bound is left unset.</param>
/// <param name="includeTo">Whether to include the upper bound in the query. When false, the upper bound is left unset.</param>
/// <returns>The created query.</returns>
public GetScheduledJobHistoryQuery Create(
DateTime? from = null,
DateTime? to = null,
bool includeFrom = true,
bool includeTo = true)
{
return new Faker<GetScheduledJobHistoryQuery>()
.CustomInstantiator(f =>
{
DateTime generatedFrom = f.Date.Recent(30);
DateTime? resolvedFrom = includeFrom ? (from ?? generatedFrom) : null;
DateTime resolvedToBase = resolvedFrom ?? generatedFrom;
DateTime? resolvedTo = includeTo ? (to ?? f.Date.Soon(1, resolvedToBase)) : null;
return new GetScheduledJobHistoryQuery(resolvedFrom, resolvedTo);
})
.Generate();
}
/// <summary>
/// Creates a list of <see cref="GetScheduledJobHistoryQuery"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<GetScheduledJobHistoryQuery> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,70 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.Requests.Scheduling;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Contracts.Fixtures.Core.Requests.Scheduling;
/// <summary>
/// Fixture class for the <see cref="AddScheduledJobRequest"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddScheduledJobRequestFixture
{
/// <summary>
/// Creates a random valid request to add a scheduled job.
/// </summary>
/// <param name="name">Optional. The name of the scheduled job.</param>
/// <param name="taskType">Optional. The type of the task executed by the scheduled job.</param>
/// <param name="scheduleType">Optional. The type of the schedule of the scheduled job.</param>
/// <param name="intervalMinutes">Optional. The interval in minutes of the schedule.</param>
/// <param name="hour">Optional. The hour of the schedule.</param>
/// <param name="minute">Optional. The minute of the schedule.</param>
/// <returns>The created request.</returns>
public AddScheduledJobRequest Create(
string? name = null,
ScheduledTaskType? taskType = null,
ScheduleType? scheduleType = null,
int? intervalMinutes = null,
int? hour = null,
int? minute = null)
{
return new Faker<AddScheduledJobRequest>()
.CustomInstantiator(f =>
{
ScheduleType resolvedScheduleType = scheduleType ?? f.PickRandom<ScheduleType>();
if (resolvedScheduleType == ScheduleType.WithIntervalInMinutes)
{
return new AddScheduledJobRequest(
name ?? f.Commerce.ProductName(),
taskType ?? f.PickRandom<ScheduledTaskType>(),
resolvedScheduleType,
intervalMinutes ?? f.Random.Int(1, 1440),
null,
null);
}
return new AddScheduledJobRequest(
name ?? f.Commerce.ProductName(),
taskType ?? f.PickRandom<ScheduledTaskType>(),
resolvedScheduleType,
null,
hour ?? f.Random.Int(0, 23),
minute ?? f.Random.Int(0, 59));
})
.Generate();
}
/// <summary>
/// Creates a list of <see cref="AddScheduledJobRequest"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<AddScheduledJobRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,40 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.Requests.Scheduling;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Contracts.Fixtures.Core.Requests.Scheduling;
/// <summary>
/// Fixture class for the <see cref="FireScheduledJobRequest"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class FireScheduledJobRequestFixture
{
/// <summary>
/// Creates a random valid request to fire the task of a scheduled job once.
/// </summary>
/// <param name="scheduledJobId">Optional. The Id of the scheduled job whose task is fired.</param>
/// <returns>The created request.</returns>
public FireScheduledJobRequest Create(
Guid? scheduledJobId = null)
{
return new Faker<FireScheduledJobRequest>()
.CustomInstantiator(f => new FireScheduledJobRequest(scheduledJobId ?? Guid.NewGuid()))
.Generate();
}
/// <summary>
/// Creates a list of <see cref="FireScheduledJobRequest"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<FireScheduledJobRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,47 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.Requests.Scheduling;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Contracts.Fixtures.Core.Requests.Scheduling;
/// <summary>
/// Fixture class for the <see cref="GetScheduledJobHistoryRequest"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetScheduledJobHistoryRequestFixture
{
/// <summary>
/// Creates a random valid request to get the history of the executions of the tasks of scheduled jobs.
/// </summary>
/// <param name="from">Optional. The inclusive lower bound of the requested interval.</param>
/// <param name="to">Optional. The inclusive upper bound of the requested interval.</param>
/// <returns>The created request.</returns>
public GetScheduledJobHistoryRequest Create(
DateTime? from = null,
DateTime? to = null)
{
return new Faker<GetScheduledJobHistoryRequest>()
.CustomInstantiator(f =>
{
DateTime resolvedFrom = from ?? f.Date.Recent(30);
DateTime resolvedTo = to ?? f.Date.Soon(1, resolvedFrom);
return new GetScheduledJobHistoryRequest(resolvedFrom, resolvedTo);
})
.Generate();
}
/// <summary>
/// Creates a list of <see cref="GetScheduledJobHistoryRequest"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<GetScheduledJobHistoryRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,40 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.Requests.Scheduling;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Contracts.Fixtures.Core.Requests.Scheduling;
/// <summary>
/// Fixture class for the <see cref="RemoveScheduledJobRequest"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RemoveScheduledJobRequestFixture
{
/// <summary>
/// Creates a random valid request to remove a scheduled job.
/// </summary>
/// <param name="scheduledJobId">Optional. The Id of the scheduled job to remove.</param>
/// <returns>The created request.</returns>
public RemoveScheduledJobRequest Create(
Guid? scheduledJobId = null)
{
return new Faker<RemoveScheduledJobRequest>()
.CustomInstantiator(f => new RemoveScheduledJobRequest(scheduledJobId ?? Guid.NewGuid()))
.Generate();
}
/// <summary>
/// Creates a list of <see cref="RemoveScheduledJobRequest"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<RemoveScheduledJobRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,40 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.Requests.Scheduling;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Contracts.Fixtures.Core.Requests.Scheduling;
/// <summary>
/// Fixture class for the <see cref="StartScheduledJobRequest"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class StartScheduledJobRequestFixture
{
/// <summary>
/// Creates a random valid request to start the execution cycle of a scheduled job.
/// </summary>
/// <param name="scheduledJobId">Optional. The Id of the scheduled job whose execution cycle is started.</param>
/// <returns>The created request.</returns>
public StartScheduledJobRequest Create(
Guid? scheduledJobId = null)
{
return new Faker<StartScheduledJobRequest>()
.CustomInstantiator(f => new StartScheduledJobRequest(scheduledJobId ?? Guid.NewGuid()))
.Generate();
}
/// <summary>
/// Creates a list of <see cref="StartScheduledJobRequest"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<StartScheduledJobRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,40 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.Requests.Scheduling;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Contracts.Fixtures.Core.Requests.Scheduling;
/// <summary>
/// Fixture class for the <see cref="StopScheduledJobRequest"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class StopScheduledJobRequestFixture
{
/// <summary>
/// Creates a random valid request to stop the execution cycle of a scheduled job.
/// </summary>
/// <param name="scheduledJobId">Optional. The Id of the scheduled job whose execution cycle is stopped.</param>
/// <returns>The created request.</returns>
public StopScheduledJobRequest Create(
Guid? scheduledJobId = null)
{
return new Faker<StopScheduledJobRequest>()
.CustomInstantiator(f => new StopScheduledJobRequest(scheduledJobId ?? Guid.NewGuid()))
.Generate();
}
/// <summary>
/// Creates a list of <see cref="StopScheduledJobRequest"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</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.Contracts.Requests.Scheduling;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Contracts.Fixtures.Core.Requests.Scheduling;
/// <summary>
/// Fixture class for the <see cref="UpdateSchedulerDisplayPreferencesRequest"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateSchedulerDisplayPreferencesRequestFixture
{
/// <summary>
/// Creates a random valid request to update the display preferences of the scheduler page of the current user.
/// </summary>
/// <param name="jobTypeFilter">Optional. The type of the scheduled job tasks whose executions are shown.</param>
/// <param name="displayTimeSpan">Optional. The displayed time span.</param>
/// <param name="displayTimeUnit">Optional. The unit of the displayed time span.</param>
/// <returns>The created request.</returns>
public UpdateSchedulerDisplayPreferencesRequest Create(
ScheduledTaskType? jobTypeFilter = null,
int? displayTimeSpan = null,
SchedulerDisplayTimeUnit? displayTimeUnit = null)
{
return new Faker<UpdateSchedulerDisplayPreferencesRequest>()
.CustomInstantiator(f => new UpdateSchedulerDisplayPreferencesRequest(
jobTypeFilter ?? (f.Random.Bool() ? f.PickRandom<ScheduledTaskType>() : null),
displayTimeSpan ?? f.Random.Int(1, 24 * 60),
displayTimeUnit ?? f.PickRandom<SchedulerDisplayTimeUnit>()))
.Generate();
}
/// <summary>
/// Creates a list of <see cref="UpdateSchedulerDisplayPreferencesRequest"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<UpdateSchedulerDisplayPreferencesRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,57 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Contracts.Fixtures.Core.Responses.Scheduling;
/// <summary>
/// Fixture class for the <see cref="ScheduledJobExecutionResponse"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScheduledJobExecutionResponseFixture
{
/// <summary>
/// Creates a random valid <see cref="ScheduledJobExecutionResponse"/>.
/// </summary>
/// <param name="id">Optional. The Id of the execution.</param>
/// <param name="scheduledJobId">Optional. The Id of the scheduled job whose task was executed.</param>
/// <param name="taskType">Optional. The type of the task that was executed.</param>
/// <param name="isCycleRun">Optional. Whether the execution was a cycle run.</param>
/// <param name="startedOnUtc">Optional. The start time of the execution.</param>
/// <param name="completedOnUtc">Optional. The completion time of the execution.</param>
/// <returns>The created <see cref="ScheduledJobExecutionResponse"/>.</returns>
public ScheduledJobExecutionResponse Create(
Guid? id = null,
Guid? scheduledJobId = null,
ScheduledTaskType? taskType = null,
bool? isCycleRun = null,
DateTime? startedOnUtc = null,
DateTime? completedOnUtc = null)
{
return new Faker<ScheduledJobExecutionResponse>()
.CustomInstantiator(f => new ScheduledJobExecutionResponse(
id ?? Guid.NewGuid(),
scheduledJobId ?? Guid.NewGuid(),
taskType ?? f.PickRandom<ScheduledTaskType>(),
isCycleRun ?? f.Random.Bool(),
startedOnUtc ?? DateTime.UtcNow,
completedOnUtc))
.Generate();
}
/// <summary>
/// Creates a list of <see cref="ScheduledJobExecutionResponse"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="ScheduledJobExecutionResponse"/> instances.</returns>
public List<ScheduledJobExecutionResponse> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,87 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Contracts.Fixtures.Core.Responses.Scheduling;
/// <summary>
/// Fixture class for the <see cref="ScheduledJobResponse"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScheduledJobResponseFixture
{
/// <summary>
/// Creates a random valid <see cref="ScheduledJobResponse"/>.
/// </summary>
/// <param name="id">Optional. The Id of the scheduled job.</param>
/// <param name="name">Optional. The name of the scheduled job.</param>
/// <param name="taskType">Optional. The type of the task executed by the scheduled job.</param>
/// <param name="scheduleType">Optional. The type of the schedule of the scheduled job.</param>
/// <param name="intervalMinutes">Optional. The interval in minutes of the schedule.</param>
/// <param name="hour">Optional. The hour of the schedule.</param>
/// <param name="minute">Optional. The minute of the schedule.</param>
/// <param name="status">Optional. The status of the scheduled job.</param>
/// <param name="lastStartedOnUtc">Optional. The last start time of the scheduled job.</param>
/// <param name="lastCompletedOnUtc">Optional. The last completion time of the scheduled job.</param>
/// <returns>The created <see cref="ScheduledJobResponse"/>.</returns>
public ScheduledJobResponse 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)
{
return new Faker<ScheduledJobResponse>()
.CustomInstantiator(f =>
{
ScheduleType resolvedScheduleType = scheduleType ?? f.PickRandom<ScheduleType>();
if (resolvedScheduleType == ScheduleType.WithIntervalInMinutes)
{
return new ScheduledJobResponse(
id ?? Guid.NewGuid(),
name ?? f.Commerce.ProductName(),
taskType ?? f.PickRandom<ScheduledTaskType>(),
resolvedScheduleType,
intervalMinutes ?? f.Random.Int(1, 1440),
null,
null,
status ?? f.PickRandom<ScheduledJobStatus>(),
lastStartedOnUtc,
lastCompletedOnUtc);
}
return new ScheduledJobResponse(
id ?? Guid.NewGuid(),
name ?? f.Commerce.ProductName(),
taskType ?? f.PickRandom<ScheduledTaskType>(),
resolvedScheduleType,
null,
hour ?? f.Random.Int(0, 23),
minute ?? f.Random.Int(0, 59),
status ?? f.PickRandom<ScheduledJobStatus>(),
lastStartedOnUtc,
lastCompletedOnUtc);
})
.Generate();
}
/// <summary>
/// Creates a list of <see cref="ScheduledJobResponse"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="ScheduledJobResponse"/> instances.</returns>
public List<ScheduledJobResponse> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,51 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Contracts.Fixtures.Core.Responses.Scheduling;
/// <summary>
/// Fixture class for the <see cref="SchedulerDisplayPreferencesResponse"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SchedulerDisplayPreferencesResponseFixture
{
/// <summary>
/// Creates a random valid <see cref="SchedulerDisplayPreferencesResponse"/>.
/// </summary>
/// <param name="userId">Optional. The Id of the user that owns the display preferences.</param>
/// <param name="jobTypeFilter">Optional. The type of the scheduled job tasks whose executions are shown.</param>
/// <param name="displayTimeSpan">Optional. The displayed time span.</param>
/// <param name="displayTimeUnit">Optional. The unit of the displayed time span.</param>
/// <returns>The created <see cref="SchedulerDisplayPreferencesResponse"/>.</returns>
public SchedulerDisplayPreferencesResponse Create(
Guid? userId = null,
ScheduledTaskType? jobTypeFilter = null,
int? displayTimeSpan = null,
SchedulerDisplayTimeUnit? displayTimeUnit = null)
{
return new Faker<SchedulerDisplayPreferencesResponse>()
.CustomInstantiator(f => new SchedulerDisplayPreferencesResponse(
userId ?? Guid.NewGuid(),
jobTypeFilter ?? (f.Random.Bool() ? f.PickRandom<ScheduledTaskType>() : null),
displayTimeSpan ?? f.Random.Int(1, 24 * 60),
displayTimeUnit ?? f.PickRandom<SchedulerDisplayTimeUnit>()))
.Generate();
}
/// <summary>
/// Creates a list of <see cref="SchedulerDisplayPreferencesResponse"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="SchedulerDisplayPreferencesResponse"/> instances.</returns>
public List<SchedulerDisplayPreferencesResponse> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,33 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events;
/// <summary>
/// Fixture class for the <see cref="LibraryDeletedDomainEvent"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryDeletedDomainEventFixture
{
private readonly LibraryFixture _libraryFixture = new();
/// <summary>
/// Creates a random valid <see cref="LibraryDeletedDomainEvent"/>.
/// </summary>
/// <param name="id">Optional. The Id of the domain event.</param>
/// <param name="library">Optional. The library that was deleted.</param>
/// <param name="occurredOnUtc">Optional. The date and time when the domain event occurred.</param>
/// <returns>The created <see cref="LibraryDeletedDomainEvent"/>.</returns>
public LibraryDeletedDomainEvent Create(Guid? id = null, Library? library = null, DateTime? occurredOnUtc = null)
{
return new LibraryDeletedDomainEvent(
id ?? Guid.NewGuid(),
library ?? _libraryFixture.Create(),
occurredOnUtc ?? DateTime.UtcNow);
}
}
@@ -0,0 +1,47 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
/// <summary>
/// Fixture class for the <see cref="LibraryMediaItemDeletedDomainEvent"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryMediaItemDeletedDomainEventFixture
{
private readonly Faker _faker = new();
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new();
/// <summary>
/// Creates a random valid <see cref="LibraryMediaItemDeletedDomainEvent"/>.
/// </summary>
/// <param name="id">Optional. The Id of the domain event.</param>
/// <param name="libraryId">Optional. The unique identifier of the library to which the deleted media library item belonged.</param>
/// <param name="mediaLibraryScanCompositeId">Optional. The composite identifier of the media library scan during which the item deletion was detected.</param>
/// <param name="path">Optional. The path of the media library item that was deleted.</param>
/// <param name="occurredOnUtc">Optional. The date and time when the domain event occurred.</param>
/// <returns>The created <see cref="LibraryMediaItemDeletedDomainEvent"/>.</returns>
public LibraryMediaItemDeletedDomainEvent Create(
Guid? id = null,
LibraryId? libraryId = null,
MediaLibraryScanCompositeId? mediaLibraryScanCompositeId = null,
string? path = null,
DateTime? occurredOnUtc = null)
{
return new LibraryMediaItemDeletedDomainEvent(
id ?? Guid.NewGuid(),
libraryId ?? _libraryIdFixture.Create(),
mediaLibraryScanCompositeId ?? _mediaLibraryScanCompositeIdFixture.Create(),
path ?? _faker.System.FilePath(),
occurredOnUtc ?? DateTime.UtcNow);
}
}
@@ -0,0 +1,42 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
/// <summary>
/// Fixture class for the <see cref="LibraryScanCancelledDomainEvent"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryScanCancelledDomainEventFixture
{
private readonly ScanIdFixture _scanIdFixture = new();
private readonly LibraryIdFixture _libraryIdFixture = new();
/// <summary>
/// Creates a random valid <see cref="LibraryScanCancelledDomainEvent"/>.
/// </summary>
/// <param name="id">Optional. The Id of the domain event.</param>
/// <param name="scanId">Optional. The unique identifier of the cancelled media library scan.</param>
/// <param name="libraryId">Optional. The unique identifier of the library whose scan was cancelled.</param>
/// <param name="occurredOnUtc">Optional. The date and time when the domain event occurred.</param>
/// <returns>The created <see cref="LibraryScanCancelledDomainEvent"/>.</returns>
public LibraryScanCancelledDomainEvent Create(
Guid? id = null,
ScanId? scanId = null,
LibraryId? libraryId = null,
DateTime? occurredOnUtc = null)
{
return new LibraryScanCancelledDomainEvent(
id ?? Guid.NewGuid(),
scanId ?? _scanIdFixture.Create(),
libraryId ?? _libraryIdFixture.Create(),
occurredOnUtc ?? DateTime.UtcNow);
}
}
@@ -0,0 +1,49 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
/// <summary>
/// Fixture class for the <see cref="LibraryScanFailedDomainEvent"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryScanFailedDomainEventFixture
{
private readonly Faker _faker = new();
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new();
/// <summary>
/// Creates a random valid <see cref="LibraryScanFailedDomainEvent"/>.
/// </summary>
/// <param name="id">Optional. The Id of the domain event.</param>
/// <param name="libraryId">Optional. The unique identifier of the library whose scan has failed.</param>
/// <param name="mediaLibraryScanCompositeId">Optional. The composite identifier of the media library scan that has failed.</param>
/// <param name="occurredOnUtc">Optional. The date and time when the domain event occurred.</param>
/// <param name="errorMessage">Optional. The descriptive message of the failure.</param>
/// <param name="includeErrorMessage">Whether to include an error message in the domain event. When false, the error message is left unset.</param>
/// <returns>The created <see cref="LibraryScanFailedDomainEvent"/>.</returns>
public LibraryScanFailedDomainEvent Create(
Guid? id = null,
LibraryId? libraryId = null,
MediaLibraryScanCompositeId? mediaLibraryScanCompositeId = null,
DateTime? occurredOnUtc = null,
string? errorMessage = null,
bool includeErrorMessage = true)
{
return new LibraryScanFailedDomainEvent(
id ?? Guid.NewGuid(),
libraryId ?? _libraryIdFixture.Create(),
mediaLibraryScanCompositeId ?? _mediaLibraryScanCompositeIdFixture.Create(),
occurredOnUtc ?? DateTime.UtcNow,
includeErrorMessage ? (errorMessage ?? _faker.Random.Words()) : null);
}
}
@@ -0,0 +1,36 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
/// <summary>
/// Fixture class for the <see cref="LibraryScanFinishedDomainEvent"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryScanFinishedDomainEventFixture
{
private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new();
/// <summary>
/// Creates a random valid <see cref="LibraryScanFinishedDomainEvent"/>.
/// </summary>
/// <param name="id">Optional. The Id of the domain event.</param>
/// <param name="mediaLibraryScanCompositeId">Optional. The composite identifier of the media library scan that was finished.</param>
/// <param name="occurredOnUtc">Optional. The date and time when the domain event occurred.</param>
/// <returns>The created <see cref="LibraryScanFinishedDomainEvent"/>.</returns>
public LibraryScanFinishedDomainEvent Create(
Guid? id = null,
MediaLibraryScanCompositeId? mediaLibraryScanCompositeId = null,
DateTime? occurredOnUtc = null)
{
return new LibraryScanFinishedDomainEvent(
id ?? Guid.NewGuid(),
mediaLibraryScanCompositeId ?? _mediaLibraryScanCompositeIdFixture.Create(),
occurredOnUtc ?? DateTime.UtcNow);
}
}
@@ -0,0 +1,46 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
/// <summary>
/// Fixture class for the <see cref="LibraryScanJobProgressChangedDomainEvent"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryScanJobProgressChangedDomainEventFixture
{
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new();
private readonly MediaLibraryScanJobProgressFixture _mediaLibraryScanJobProgressFixture = new();
/// <summary>
/// Creates a random valid <see cref="LibraryScanJobProgressChangedDomainEvent"/>.
/// </summary>
/// <param name="id">Optional. The Id of the domain event.</param>
/// <param name="libraryId">Optional. The unique identifier of the library being scanned.</param>
/// <param name="mediaLibraryScanCompositeId">Optional. The composite identifier of the media library scan whose job progress changed.</param>
/// <param name="progress">Optional. The new media library scan job progress.</param>
/// <param name="occurredOnUtc">Optional. The date and time when the domain event occurred.</param>
/// <returns>The created <see cref="LibraryScanJobProgressChangedDomainEvent"/>.</returns>
public LibraryScanJobProgressChangedDomainEvent Create(
Guid? id = null,
LibraryId? libraryId = null,
MediaLibraryScanCompositeId? mediaLibraryScanCompositeId = null,
MediaLibraryScanJobProgress? progress = null,
DateTime? occurredOnUtc = null)
{
return new LibraryScanJobProgressChangedDomainEvent(
id ?? Guid.NewGuid(),
libraryId ?? _libraryIdFixture.Create(),
mediaLibraryScanCompositeId ?? _mediaLibraryScanCompositeIdFixture.Create(),
progress ?? _mediaLibraryScanJobProgressFixture.Create(),
occurredOnUtc ?? DateTime.UtcNow);
}
}
@@ -0,0 +1,42 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
/// <summary>
/// Fixture class for the <see cref="LibraryScanProgressChangedDomainEvent"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryScanProgressChangedDomainEventFixture
{
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new();
/// <summary>
/// Creates a random valid <see cref="LibraryScanProgressChangedDomainEvent"/>.
/// </summary>
/// <param name="id">Optional. The Id of the domain event.</param>
/// <param name="libraryId">Optional. The unique identifier of the library being scanned.</param>
/// <param name="mediaLibraryScanCompositeId">Optional. The composite identifier of the media library scan whose progress changed.</param>
/// <param name="occurredOnUtc">Optional. The date and time when the domain event occurred.</param>
/// <returns>The created <see cref="LibraryScanProgressChangedDomainEvent"/>.</returns>
public LibraryScanProgressChangedDomainEvent Create(
Guid? id = null,
LibraryId? libraryId = null,
MediaLibraryScanCompositeId? mediaLibraryScanCompositeId = null,
DateTime? occurredOnUtc = null)
{
return new LibraryScanProgressChangedDomainEvent(
id ?? Guid.NewGuid(),
libraryId ?? _libraryIdFixture.Create(),
mediaLibraryScanCompositeId ?? _mediaLibraryScanCompositeIdFixture.Create(),
occurredOnUtc ?? DateTime.UtcNow);
}
}
@@ -0,0 +1,42 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
/// <summary>
/// Fixture class for the <see cref="LibraryScanQueuedDomainEvent"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryScanQueuedDomainEventFixture
{
private readonly ScanIdFixture _scanIdFixture = new();
private readonly LibraryIdFixture _libraryIdFixture = new();
/// <summary>
/// Creates a random valid <see cref="LibraryScanQueuedDomainEvent"/>.
/// </summary>
/// <param name="id">Optional. The Id of the domain event.</param>
/// <param name="scanId">Optional. The unique identifier of the queued media library scan.</param>
/// <param name="libraryId">Optional. The unique identifier of the library whose scan was queued.</param>
/// <param name="occurredOnUtc">Optional. The date and time when the domain event occurred.</param>
/// <returns>The created <see cref="LibraryScanQueuedDomainEvent"/>.</returns>
public LibraryScanQueuedDomainEvent Create(
Guid? id = null,
ScanId? scanId = null,
LibraryId? libraryId = null,
DateTime? occurredOnUtc = null)
{
return new LibraryScanQueuedDomainEvent(
id ?? Guid.NewGuid(),
scanId ?? _scanIdFixture.Create(),
libraryId ?? _libraryIdFixture.Create(),
occurredOnUtc ?? DateTime.UtcNow);
}
}
@@ -0,0 +1,33 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
/// <summary>
/// Fixture class for the <see cref="LibraryScanStartedDomainEvent"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryScanStartedDomainEventFixture
{
private readonly LibraryScanFixture _libraryScanFixture = new();
/// <summary>
/// Creates a random valid <see cref="LibraryScanStartedDomainEvent"/>.
/// </summary>
/// <param name="id">Optional. The Id of the domain event.</param>
/// <param name="libraryScan">Optional. The library scan that was started.</param>
/// <param name="occurredOnUtc">Optional. The date and time when the domain event occurred.</param>
/// <returns>The created <see cref="LibraryScanStartedDomainEvent"/>.</returns>
public LibraryScanStartedDomainEvent Create(Guid? id = null, LibraryScan? libraryScan = null, DateTime? occurredOnUtc = null)
{
return new LibraryScanStartedDomainEvent(
id ?? Guid.NewGuid(),
libraryScan ?? _libraryScanFixture.Create(),
occurredOnUtc ?? DateTime.UtcNow);
}
}
@@ -0,0 +1,37 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
/// <summary>
/// Fixture class for the <see cref="UserId"/> value object.
/// </summary>
[ExcludeFromCodeCoverage]
public class UserIdFixture
{
/// <summary>
/// Creates a random valid <see cref="UserId"/>.
/// </summary>
/// <param name="value">Optional. The raw value of the user Id.</param>
/// <returns>The created <see cref="UserId"/>.</returns>
public UserId Create(
Guid? value = null)
{
return UserId.Create(value ?? Guid.NewGuid());
}
/// <summary>
/// Creates a list of <see cref="UserId"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="UserId"/> instances.</returns>
public List<UserId> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,36 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
/// <summary>
/// Fixture class for the <see cref="ScheduledJobAddedDomainEvent"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScheduledJobAddedDomainEventFixture
{
private readonly ScheduledJobIdFixture _scheduledJobIdFixture = new();
/// <summary>
/// Creates a random valid <see cref="ScheduledJobAddedDomainEvent"/>.
/// </summary>
/// <param name="id">Optional. The Id of the domain event.</param>
/// <param name="scheduledJobId">Optional. The unique identifier of the scheduled job that was added.</param>
/// <param name="occurredOnUtc">Optional. The date and time when the domain event occurred.</param>
/// <returns>The created <see cref="ScheduledJobAddedDomainEvent"/>.</returns>
public ScheduledJobAddedDomainEvent Create(
Guid? id = null,
ScheduledJobId? scheduledJobId = null,
DateTime? occurredOnUtc = null)
{
return new ScheduledJobAddedDomainEvent(
id ?? Guid.NewGuid(),
scheduledJobId ?? _scheduledJobIdFixture.Create(),
occurredOnUtc ?? DateTime.UtcNow);
}
}
@@ -0,0 +1,36 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
/// <summary>
/// Fixture class for the <see cref="ScheduledJobCycleStartedDomainEvent"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScheduledJobCycleStartedDomainEventFixture
{
private readonly ScheduledJobIdFixture _scheduledJobIdFixture = new();
/// <summary>
/// Creates a random valid <see cref="ScheduledJobCycleStartedDomainEvent"/>.
/// </summary>
/// <param name="id">Optional. The Id of the domain event.</param>
/// <param name="scheduledJobId">Optional. The unique identifier of the scheduled job whose execution cycle was started.</param>
/// <param name="occurredOnUtc">Optional. The date and time when the domain event occurred.</param>
/// <returns>The created <see cref="ScheduledJobCycleStartedDomainEvent"/>.</returns>
public ScheduledJobCycleStartedDomainEvent Create(
Guid? id = null,
ScheduledJobId? scheduledJobId = null,
DateTime? occurredOnUtc = null)
{
return new ScheduledJobCycleStartedDomainEvent(
id ?? Guid.NewGuid(),
scheduledJobId ?? _scheduledJobIdFixture.Create(),
occurredOnUtc ?? DateTime.UtcNow);
}
}
@@ -0,0 +1,36 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
/// <summary>
/// Fixture class for the <see cref="ScheduledJobCycleStoppedDomainEvent"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScheduledJobCycleStoppedDomainEventFixture
{
private readonly ScheduledJobIdFixture _scheduledJobIdFixture = new();
/// <summary>
/// Creates a random valid <see cref="ScheduledJobCycleStoppedDomainEvent"/>.
/// </summary>
/// <param name="id">Optional. The Id of the domain event.</param>
/// <param name="scheduledJobId">Optional. The unique identifier of the scheduled job whose execution cycle was stopped.</param>
/// <param name="occurredOnUtc">Optional. The date and time when the domain event occurred.</param>
/// <returns>The created <see cref="ScheduledJobCycleStoppedDomainEvent"/>.</returns>
public ScheduledJobCycleStoppedDomainEvent Create(
Guid? id = null,
ScheduledJobId? scheduledJobId = null,
DateTime? occurredOnUtc = null)
{
return new ScheduledJobCycleStoppedDomainEvent(
id ?? Guid.NewGuid(),
scheduledJobId ?? _scheduledJobIdFixture.Create(),
occurredOnUtc ?? DateTime.UtcNow);
}
}
@@ -0,0 +1,46 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
/// <summary>
/// Fixture class for the <see cref="ScheduledJobExecutionCompletedDomainEvent"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScheduledJobExecutionCompletedDomainEventFixture
{
private readonly ScheduledJobIdFixture _scheduledJobIdFixture = new();
/// <summary>
/// Creates a random valid <see cref="ScheduledJobExecutionCompletedDomainEvent"/>.
/// </summary>
/// <param name="id">Optional. The Id of the domain event.</param>
/// <param name="scheduledJobId">Optional. The unique identifier of the scheduled job whose task completed its execution.</param>
/// <param name="runId">Optional. The unique identifier of the current execution of the task of the scheduled job.</param>
/// <param name="taskType">The type of the task that completed its execution.</param>
/// <param name="isCycleRun">Whether the execution was triggered by the execution cycle of the scheduled job.</param>
/// <param name="completedOnUtc">Optional. The date and time when the execution completed.</param>
/// <returns>The created <see cref="ScheduledJobExecutionCompletedDomainEvent"/>.</returns>
public ScheduledJobExecutionCompletedDomainEvent Create(
Guid? id = null,
ScheduledJobId? scheduledJobId = null,
Guid? runId = null,
ScheduledTaskType taskType = ScheduledTaskType.ScanMediaLibraries,
bool isCycleRun = false,
DateTime? completedOnUtc = null)
{
return new ScheduledJobExecutionCompletedDomainEvent(
id ?? Guid.NewGuid(),
scheduledJobId ?? _scheduledJobIdFixture.Create(),
runId ?? Guid.NewGuid(),
taskType,
isCycleRun,
completedOnUtc ?? DateTime.UtcNow);
}
}
@@ -0,0 +1,46 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
/// <summary>
/// Fixture class for the <see cref="ScheduledJobExecutionStartedDomainEvent"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScheduledJobExecutionStartedDomainEventFixture
{
private readonly ScheduledJobIdFixture _scheduledJobIdFixture = new();
/// <summary>
/// Creates a random valid <see cref="ScheduledJobExecutionStartedDomainEvent"/>.
/// </summary>
/// <param name="id">Optional. The Id of the domain event.</param>
/// <param name="scheduledJobId">Optional. The unique identifier of the scheduled job whose task started executing.</param>
/// <param name="runId">Optional. The unique identifier of the current execution of the task of the scheduled job.</param>
/// <param name="taskType">The type of the task that started executing.</param>
/// <param name="isCycleRun">Whether the execution was triggered by the execution cycle of the scheduled job.</param>
/// <param name="startedOnUtc">Optional. The date and time when the execution started.</param>
/// <returns>The created <see cref="ScheduledJobExecutionStartedDomainEvent"/>.</returns>
public ScheduledJobExecutionStartedDomainEvent Create(
Guid? id = null,
ScheduledJobId? scheduledJobId = null,
Guid? runId = null,
ScheduledTaskType taskType = ScheduledTaskType.ScanMediaLibraries,
bool isCycleRun = false,
DateTime? startedOnUtc = null)
{
return new ScheduledJobExecutionStartedDomainEvent(
id ?? Guid.NewGuid(),
scheduledJobId ?? _scheduledJobIdFixture.Create(),
runId ?? Guid.NewGuid(),
taskType,
isCycleRun,
startedOnUtc ?? DateTime.UtcNow);
}
}
@@ -0,0 +1,36 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
/// <summary>
/// Fixture class for the <see cref="ScheduledJobExecutionStoppedDomainEvent"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScheduledJobExecutionStoppedDomainEventFixture
{
private readonly ScheduledJobIdFixture _scheduledJobIdFixture = new();
/// <summary>
/// Creates a random valid <see cref="ScheduledJobExecutionStoppedDomainEvent"/>.
/// </summary>
/// <param name="id">Optional. The Id of the domain event.</param>
/// <param name="scheduledJobId">Optional. The unique identifier of the scheduled job whose running execution was stopped.</param>
/// <param name="occurredOnUtc">Optional. The date and time when the domain event occurred.</param>
/// <returns>The created <see cref="ScheduledJobExecutionStoppedDomainEvent"/>.</returns>
public ScheduledJobExecutionStoppedDomainEvent Create(
Guid? id = null,
ScheduledJobId? scheduledJobId = null,
DateTime? occurredOnUtc = null)
{
return new ScheduledJobExecutionStoppedDomainEvent(
id ?? Guid.NewGuid(),
scheduledJobId ?? _scheduledJobIdFixture.Create(),
occurredOnUtc ?? DateTime.UtcNow);
}
}
@@ -0,0 +1,36 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
/// <summary>
/// Fixture class for the <see cref="ScheduledJobFiredDomainEvent"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScheduledJobFiredDomainEventFixture
{
private readonly ScheduledJobIdFixture _scheduledJobIdFixture = new();
/// <summary>
/// Creates a random valid <see cref="ScheduledJobFiredDomainEvent"/>.
/// </summary>
/// <param name="id">Optional. The Id of the domain event.</param>
/// <param name="scheduledJobId">Optional. The unique identifier of the scheduled job whose task was fired.</param>
/// <param name="occurredOnUtc">Optional. The date and time when the domain event occurred.</param>
/// <returns>The created <see cref="ScheduledJobFiredDomainEvent"/>.</returns>
public ScheduledJobFiredDomainEvent Create(
Guid? id = null,
ScheduledJobId? scheduledJobId = null,
DateTime? occurredOnUtc = null)
{
return new ScheduledJobFiredDomainEvent(
id ?? Guid.NewGuid(),
scheduledJobId ?? _scheduledJobIdFixture.Create(),
occurredOnUtc ?? DateTime.UtcNow);
}
}
@@ -0,0 +1,36 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
/// <summary>
/// Fixture class for the <see cref="ScheduledJobRemovedDomainEvent"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScheduledJobRemovedDomainEventFixture
{
private readonly ScheduledJobIdFixture _scheduledJobIdFixture = new();
/// <summary>
/// Creates a random valid <see cref="ScheduledJobRemovedDomainEvent"/>.
/// </summary>
/// <param name="id">Optional. The Id of the domain event.</param>
/// <param name="scheduledJobId">Optional. The unique identifier of the scheduled job that was removed.</param>
/// <param name="occurredOnUtc">Optional. The date and time when the domain event occurred.</param>
/// <returns>The created <see cref="ScheduledJobRemovedDomainEvent"/>.</returns>
public ScheduledJobRemovedDomainEvent Create(
Guid? id = null,
ScheduledJobId? scheduledJobId = null,
DateTime? occurredOnUtc = null)
{
return new ScheduledJobRemovedDomainEvent(
id ?? Guid.NewGuid(),
scheduledJobId ?? _scheduledJobIdFixture.Create(),
occurredOnUtc ?? DateTime.UtcNow);
}
}
@@ -0,0 +1,83 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
/// <summary>
/// Fixture class for the <see cref="ScheduledJob"/> domain aggregate.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScheduledJobFixture
{
private readonly IntervalScheduleFixture _intervalScheduleFixture = new();
/// <summary>
/// Creates a random valid <see cref="ScheduledJob"/> domain aggregate.
/// </summary>
/// <param name="id">Optional. The Id of the scheduled job. When provided, the aggregate is created with pre-existing data.</param>
/// <param name="name">Optional. The name of the scheduled job.</param>
/// <param name="taskType">Optional. The type of the task executed by the scheduled job.</param>
/// <param name="schedule">Optional. The schedule of the scheduled job. Defaults to an interval schedule of 60 minutes.</param>
/// <param name="ownerUserId">Optional. The Id of the user that owns the scheduled job.</param>
/// <param name="status">Optional. The status of the scheduled job. Only applied when <paramref name="id"/> is provided.</param>
/// <param name="lastStartedOnUtc">Optional. The last start time of the scheduled job. Only applied when <paramref name="id"/> is provided.</param>
/// <param name="lastCompletedOnUtc">Optional. The last completion time of the scheduled job. Only applied when <paramref name="id"/> is provided.</param>
/// <returns>The created <see cref="ScheduledJob"/>.</returns>
public ScheduledJob Create(
Guid? id = null,
string? name = null,
ScheduledTaskType? taskType = null,
Schedule? schedule = null,
Guid? ownerUserId = null,
ScheduledJobStatus? status = null,
DateTime? lastStartedOnUtc = null,
DateTime? lastCompletedOnUtc = null)
{
Faker faker = new();
ScheduledJobStatus resolvedStatus = status ?? ScheduledJobStatus.Added;
string resolvedName = name ?? faker.Commerce.ProductName();
ScheduledTaskType resolvedTaskType = taskType ?? faker.PickRandom<ScheduledTaskType>();
UserId resolvedOwnerUserId = UserId.Create(ownerUserId ?? Guid.NewGuid());
Schedule resolvedSchedule = schedule ?? _intervalScheduleFixture.Create(faker.Random.Int(5, 1440));
// When no pre-existing state is requested, create a fresh scheduled job with the default Added status.
if (id is null && status is null)
{
Result<ScheduledJob> createResult = ScheduledJob.Create(resolvedName, resolvedTaskType, resolvedSchedule, resolvedOwnerUserId);
return createResult.Value;
}
// When a pre-existing Id or an explicit status is requested, create the scheduled job with that pre-existing state.
Result<ScheduledJob> createWithIdResult = ScheduledJob.Create(
ScheduledJobId.Create(id ?? Guid.NewGuid()),
resolvedName,
resolvedTaskType,
resolvedSchedule,
resolvedOwnerUserId,
resolvedStatus,
Optional<DateTime>.FromNullable(lastStartedOnUtc),
Optional<DateTime>.FromNullable(lastCompletedOnUtc));
return createWithIdResult.Value;
}
/// <summary>
/// Creates multiple <see cref="ScheduledJob"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="ScheduledJob"/> instances.</returns>
public List<ScheduledJob> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,41 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
/// <summary>
/// Fixture class for the <see cref="DailySchedule"/> value object.
/// </summary>
[ExcludeFromCodeCoverage]
public class DailyScheduleFixture
{
/// <summary>
/// Creates a random valid <see cref="DailySchedule"/>.
/// </summary>
/// <param name="hour">Optional. The hour of the day at which the task runs.</param>
/// <param name="minute">Optional. The minute of the hour at which the task runs.</param>
/// <returns>The created <see cref="DailySchedule"/>.</returns>
public DailySchedule Create(int? hour = null, int? minute = null)
{
Faker faker = new();
return DailySchedule.Create(
hour ?? faker.Random.Int(0, 23),
minute ?? faker.Random.Int(0, 59)).Value;
}
/// <summary>
/// Creates a list of <see cref="DailySchedule"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="DailySchedule"/> instances.</returns>
public List<DailySchedule> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,38 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
/// <summary>
/// Fixture class for the <see cref="IntervalSchedule"/> value object.
/// </summary>
[ExcludeFromCodeCoverage]
public class IntervalScheduleFixture
{
/// <summary>
/// Creates a random valid <see cref="IntervalSchedule"/>.
/// </summary>
/// <param name="intervalMinutes">Optional. The number of minutes between each execution.</param>
/// <returns>The created <see cref="IntervalSchedule"/>.</returns>
public IntervalSchedule Create(int? intervalMinutes = null)
{
Faker faker = new();
return IntervalSchedule.Create(intervalMinutes ?? faker.Random.Int(1, 1440)).Value;
}
/// <summary>
/// Creates a list of <see cref="IntervalSchedule"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="IntervalSchedule"/> instances.</returns>
public List<IntervalSchedule> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,37 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
/// <summary>
/// Fixture class for the <see cref="ScheduledJobId"/> value object.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScheduledJobIdFixture
{
/// <summary>
/// Creates a random valid <see cref="ScheduledJobId"/>.
/// </summary>
/// <param name="value">Optional. The raw value of the scheduled job Id.</param>
/// <returns>The created <see cref="ScheduledJobId"/>.</returns>
public ScheduledJobId Create(
Guid? value = null)
{
return ScheduledJobId.Create(value ?? Guid.NewGuid());
}
/// <summary>
/// Creates a list of <see cref="ScheduledJobId"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="ScheduledJobId"/> instances.</returns>
public List<ScheduledJobId> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,183 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Fixtures.Core.Requests.Scheduling;
using Lumina.Contracts.Requests.Scheduling;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Scheduling.AddScheduledJob;
/// <summary>
/// Contains integration tests for the <see cref="AddScheduledJobEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddScheduledJobEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
private readonly AddScheduledJobRequestFixture _addScheduledJobRequestFixture = new();
private readonly List<Guid> _createdScheduledJobIds = [];
private HttpClient _client;
/// <summary>
/// Initializes a new instance of the <see cref="AddScheduledJobEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public AddScheduledJobEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes an authenticated admin API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedAdminClientAsync();
}
[Fact]
public async Task AddScheduledJob_WhenCalledWithValidIntervalRequest_ShouldCreateScheduledJob()
{
// Arrange
AddScheduledJobRequest request = _addScheduledJobRequestFixture.Create(
name: $"Scan job {Guid.NewGuid()}",
taskType: ScheduledTaskType.ScanMediaLibraries,
scheduleType: ScheduleType.WithIntervalInMinutes,
intervalMinutes: 60);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/scheduled-jobs", request);
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
ScheduledJobResponse? result = JsonSerializer.Deserialize<ScheduledJobResponse>(content, _jsonOptions);
Assert.NotNull(result);
Assert.Equal(request.Name, result!.Name);
Assert.Equal(request.TaskType, result.TaskType);
Assert.Equal(ScheduleType.WithIntervalInMinutes, result.ScheduleType);
Assert.Equal(60, result.IntervalMinutes);
Assert.Equal(ScheduledJobStatus.Added, result.Status);
_createdScheduledJobIds.Add(result.Id);
}
[Fact]
public async Task AddScheduledJob_WhenCalledWithValidDailyRequest_ShouldCreateScheduledJob()
{
// Arrange
AddScheduledJobRequest request = _addScheduledJobRequestFixture.Create(
name: $"Daily job {Guid.NewGuid()}",
taskType: ScheduledTaskType.CleanTemporaryFiles,
scheduleType: ScheduleType.DailyAtHourAndMinute,
hour: 6,
minute: 30);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/scheduled-jobs", request);
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
ScheduledJobResponse? result = JsonSerializer.Deserialize<ScheduledJobResponse>(content, _jsonOptions);
Assert.NotNull(result);
Assert.Equal(ScheduleType.DailyAtHourAndMinute, result!.ScheduleType);
Assert.Equal(6, result.Hour);
Assert.Equal(30, result.Minute);
Assert.Null(result.IntervalMinutes);
_createdScheduledJobIds.Add(result.Id);
}
[Fact]
public async Task AddScheduledJob_WhenCalledWithInvalidName_ShouldReturnValidationProblem()
{
// Arrange
AddScheduledJobRequest request = _addScheduledJobRequestFixture.Create(
name: " ",
scheduleType: ScheduleType.WithIntervalInMinutes,
intervalMinutes: 60);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/scheduled-jobs", request);
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
}
[Fact]
public async Task AddScheduledJob_WhenCalledWithNonAdminAccount_ShouldReturnForbiddenResult()
{
// Arrange
_client = await _apiFactory.CreateAuthenticatedClientAsync();
AddScheduledJobRequest request = _addScheduledJobRequestFixture.Create(scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/scheduled-jobs", request);
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
// Wipe the tables touched by the tests, because the in-memory database of the class factory is shared between the tests of the class.
await dbContext.Set<RolePermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserPermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<ScheduledJobExecutionEntity>().ExecuteDeleteAsync();
await dbContext.Set<ScheduledJobEntity>().ExecuteDeleteAsync();
await dbContext.Set<SchedulerDisplayPreferencesEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserRoleEntity>().ExecuteDeleteAsync();
await dbContext.Set<RoleEntity>().ExecuteDeleteAsync();
await dbContext.Set<PermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
await dbContext.SaveChangesAsync();
}
}
@@ -0,0 +1,129 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Fixtures.Core.Requests.Scheduling;
using Lumina.Contracts.Requests.Scheduling;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Scheduling.GetScheduledJobs;
/// <summary>
/// Contains integration tests for the <see cref="GetScheduledJobsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetScheduledJobsEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
private readonly AddScheduledJobRequestFixture _addScheduledJobRequestFixture = new();
private readonly List<Guid> _createdScheduledJobIds = [];
private HttpClient _client;
/// <summary>
/// Initializes a new instance of the <see cref="GetScheduledJobsEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetScheduledJobsEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes an authenticated admin API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedAdminClientAsync();
}
[Fact]
public async Task GetScheduledJobs_WhenScheduledJobsExist_ShouldReturnTheListOfScheduledJobs()
{
// Arrange
AddScheduledJobRequest addRequest = _addScheduledJobRequestFixture.Create(
name: $"Listed job {Guid.NewGuid()}",
scheduleType: ScheduleType.WithIntervalInMinutes,
intervalMinutes: 30);
HttpResponseMessage addResponse = await _client.PostAsJsonAsync("/api/v1/scheduled-jobs", addRequest);
string addContent = await addResponse.Content.ReadAsStringAsync();
ScheduledJobResponse? createdJob = JsonSerializer.Deserialize<ScheduledJobResponse>(addContent, _jsonOptions);
Assert.NotNull(createdJob);
_createdScheduledJobIds.Add(createdJob!.Id);
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1/scheduled-jobs");
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
List<ScheduledJobResponse>? result = JsonSerializer.Deserialize<List<ScheduledJobResponse>>(content, _jsonOptions);
Assert.NotNull(result);
Assert.Contains(result!, scheduledJob => scheduledJob.Id == createdJob.Id && scheduledJob.Name == addRequest.Name);
}
[Fact]
public async Task GetScheduledJobs_WhenCalledWithNonAdminAccount_ShouldReturnForbiddenResult()
{
// Arrange
_client = await _apiFactory.CreateAuthenticatedClientAsync();
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1/scheduled-jobs");
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
// Wipe the tables touched by the tests, because the in-memory database of the class factory is shared between the tests of the class.
await dbContext.Set<RolePermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserPermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<ScheduledJobExecutionEntity>().ExecuteDeleteAsync();
await dbContext.Set<ScheduledJobEntity>().ExecuteDeleteAsync();
await dbContext.Set<SchedulerDisplayPreferencesEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserRoleEntity>().ExecuteDeleteAsync();
await dbContext.Set<RoleEntity>().ExecuteDeleteAsync();
await dbContext.Set<PermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
await dbContext.SaveChangesAsync();
}
}
@@ -0,0 +1,110 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Scheduling.GetSchedulerDisplayPreferences;
/// <summary>
/// Contains integration tests for the <see cref="GetSchedulerDisplayPreferencesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetSchedulerDisplayPreferencesEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
private HttpClient _client;
/// <summary>
/// Initializes a new instance of the <see cref="GetSchedulerDisplayPreferencesEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetSchedulerDisplayPreferencesEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes an authenticated admin API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedAdminClientAsync();
}
[Fact]
public async Task GetSchedulerDisplayPreferences_WhenNoPreferencesStored_ShouldReturnTheDefaultPreferences()
{
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1/scheduled-jobs/display-preferences");
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
SchedulerDisplayPreferencesResponse? result = JsonSerializer.Deserialize<SchedulerDisplayPreferencesResponse>(content, _jsonOptions);
Assert.NotNull(result);
Assert.Null(result!.JobTypeFilter);
Assert.Equal(10, result.DisplayTimeSpan);
Assert.Equal(SchedulerDisplayTimeUnit.Minutes, result.DisplayTimeUnit);
}
[Fact]
public async Task GetSchedulerDisplayPreferences_WhenCalledWithNonAdminAccount_ShouldReturnForbiddenResult()
{
// Arrange
_client = await _apiFactory.CreateAuthenticatedClientAsync();
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1/scheduled-jobs/display-preferences");
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
// Wipe the tables touched by the tests, because the in-memory database of the class factory is shared between the tests of the class.
await dbContext.Set<RolePermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserPermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<ScheduledJobExecutionEntity>().ExecuteDeleteAsync();
await dbContext.Set<ScheduledJobEntity>().ExecuteDeleteAsync();
await dbContext.Set<SchedulerDisplayPreferencesEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserRoleEntity>().ExecuteDeleteAsync();
await dbContext.Set<RoleEntity>().ExecuteDeleteAsync();
await dbContext.Set<PermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
await dbContext.SaveChangesAsync();
}
}
@@ -0,0 +1,152 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Fixtures.Core.Requests.Scheduling;
using Lumina.Contracts.Requests.Scheduling;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Scheduling.RemoveScheduledJob;
/// <summary>
/// Contains integration tests for the <see cref="RemoveScheduledJobEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RemoveScheduledJobEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
private readonly AddScheduledJobRequestFixture _addScheduledJobRequestFixture = new();
private readonly List<Guid> _createdScheduledJobIds = [];
private HttpClient _client;
/// <summary>
/// Initializes a new instance of the <see cref="RemoveScheduledJobEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public RemoveScheduledJobEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes an authenticated admin API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedAdminClientAsync();
}
[Fact]
public async Task RemoveScheduledJob_WhenScheduledJobExists_ShouldRemoveIt()
{
// Arrange
ScheduledJobResponse createdJob = await CreateScheduledJobAsync();
// Act
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/scheduled-jobs/{createdJob.Id}");
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.Null(await dbContext.ScheduledJobs.FirstOrDefaultAsync(scheduledJob => scheduledJob.Id == createdJob.Id));
}
[Fact]
public async Task RemoveScheduledJob_WhenScheduledJobDoesNotExist_ShouldReturnNotFound()
{
// Arrange
Guid missingScheduledJobId = Guid.NewGuid();
// Act
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/scheduled-jobs/{missingScheduledJobId}");
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32());
Assert.Equal("ScheduledJobNotFound", problemDetails["detail"].GetString());
}
[Fact]
public async Task RemoveScheduledJob_WhenCalledWithNonAdminAccount_ShouldReturnForbiddenResult()
{
// Arrange
_client = await _apiFactory.CreateAuthenticatedClientAsync();
Guid scheduledJobId = Guid.NewGuid();
// Act
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/scheduled-jobs/{scheduledJobId}");
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
}
/// <summary>
/// Creates a scheduled job through the API and returns its response.
/// </summary>
/// <returns>The created scheduled job response.</returns>
private async Task<ScheduledJobResponse> CreateScheduledJobAsync()
{
AddScheduledJobRequest addRequest = _addScheduledJobRequestFixture.Create(
name: $"Removable job {Guid.NewGuid()}",
scheduleType: ScheduleType.WithIntervalInMinutes,
intervalMinutes: 60);
HttpResponseMessage addResponse = await _client.PostAsJsonAsync("/api/v1/scheduled-jobs", addRequest);
string addContent = await addResponse.Content.ReadAsStringAsync();
ScheduledJobResponse? createdJob = JsonSerializer.Deserialize<ScheduledJobResponse>(addContent, _jsonOptions);
Assert.NotNull(createdJob);
_createdScheduledJobIds.Add(createdJob!.Id);
return createdJob;
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
// Wipe the tables touched by the tests, because the in-memory database of the class factory is shared between the tests of the class.
await dbContext.Set<RolePermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserPermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<ScheduledJobExecutionEntity>().ExecuteDeleteAsync();
await dbContext.Set<ScheduledJobEntity>().ExecuteDeleteAsync();
await dbContext.Set<SchedulerDisplayPreferencesEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserRoleEntity>().ExecuteDeleteAsync();
await dbContext.Set<RoleEntity>().ExecuteDeleteAsync();
await dbContext.Set<PermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
await dbContext.SaveChangesAsync();
}
}
@@ -0,0 +1,142 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Fixtures.Core.Requests.Scheduling;
using Lumina.Contracts.Requests.Scheduling;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Scheduling.UpdateSchedulerDisplayPreferences;
/// <summary>
/// Contains integration tests for the <see cref="UpdateSchedulerDisplayPreferencesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateSchedulerDisplayPreferencesEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
private readonly UpdateSchedulerDisplayPreferencesRequestFixture _updateSchedulerDisplayPreferencesRequestFixture = new();
private Guid? _createdPreferencesUserId;
private HttpClient _client;
/// <summary>
/// Initializes a new instance of the <see cref="UpdateSchedulerDisplayPreferencesEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public UpdateSchedulerDisplayPreferencesEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes an authenticated admin API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedAdminClientAsync();
}
[Fact]
public async Task UpdateSchedulerDisplayPreferences_WhenCalledWithValidRequest_ShouldPersistThePreferences()
{
// Arrange
UpdateSchedulerDisplayPreferencesRequest request = _updateSchedulerDisplayPreferencesRequestFixture.Create(
jobTypeFilter: ScheduledTaskType.ScanMediaLibraries,
displayTimeSpan: 30,
displayTimeUnit: SchedulerDisplayTimeUnit.Minutes);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/scheduled-jobs/display-preferences", request);
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
HttpResponseMessage getResponse = await _client.GetAsync("/api/v1/scheduled-jobs/display-preferences");
string content = await getResponse.Content.ReadAsStringAsync();
SchedulerDisplayPreferencesResponse? result = JsonSerializer.Deserialize<SchedulerDisplayPreferencesResponse>(content, _jsonOptions);
Assert.NotNull(result);
Assert.Equal(ScheduledTaskType.ScanMediaLibraries, result!.JobTypeFilter);
Assert.Equal(30, result.DisplayTimeSpan);
Assert.Equal(SchedulerDisplayTimeUnit.Minutes, result.DisplayTimeUnit);
_createdPreferencesUserId = result.UserId;
}
[Fact]
public async Task UpdateSchedulerDisplayPreferences_WhenCalledWithNonPositiveTimeSpan_ShouldReturnValidationProblem()
{
// Arrange
UpdateSchedulerDisplayPreferencesRequest request = _updateSchedulerDisplayPreferencesRequestFixture.Create(displayTimeSpan: 0);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/scheduled-jobs/display-preferences", request);
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
}
[Fact]
public async Task UpdateSchedulerDisplayPreferences_WhenCalledWithNonAdminAccount_ShouldReturnForbiddenResult()
{
// Arrange
_client = await _apiFactory.CreateAuthenticatedClientAsync();
UpdateSchedulerDisplayPreferencesRequest request = _updateSchedulerDisplayPreferencesRequestFixture.Create();
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/scheduled-jobs/display-preferences", request);
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
// Wipe the tables touched by the tests, because the in-memory database of the class factory is shared between the tests of the class.
await dbContext.Set<RolePermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserPermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<ScheduledJobExecutionEntity>().ExecuteDeleteAsync();
await dbContext.Set<ScheduledJobEntity>().ExecuteDeleteAsync();
await dbContext.Set<SchedulerDisplayPreferencesEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserRoleEntity>().ExecuteDeleteAsync();
await dbContext.Set<RoleEntity>().ExecuteDeleteAsync();
await dbContext.Set<PermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
await dbContext.SaveChangesAsync();
}
}
@@ -0,0 +1,157 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Scheduling.AddScheduledJob;
/// <summary>
/// Contains security tests for the <c>/api/v1/scheduled-jobs</c> route.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddScheduledJobEndpointTests : IClassFixture<LuminaApiFactory>, IAsyncDisposable
{
private readonly HttpClient _client;
private readonly LuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
private Guid _adminUserId;
/// <summary>
/// Initializes a new instance of the <see cref="AddScheduledJobEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public AddScheduledJobEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
}
[Fact]
public async Task AddScheduledJob_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
object requestBody = new
{
Name = "Unauthorized job",
TaskType = ScheduledTaskType.ScanMediaLibraries,
ScheduleType = ScheduleType.WithIntervalInMinutes,
IntervalMinutes = 60
};
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/scheduled-jobs", requestBody);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
}
[Fact]
public async Task AddScheduledJob_WhenCalledWithNonAdminAccount_ShouldReturnForbiddenResult()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
await _apiFactory.CreateAndAuthenticateUserAsync(client);
object requestBody = new
{
Name = "Non admin job",
TaskType = ScheduledTaskType.ScanMediaLibraries,
ScheduleType = ScheduleType.WithIntervalInMinutes,
IntervalMinutes = 60
};
// Act
HttpResponseMessage response = await client.PostAsJsonAsync("/api/v1/scheduled-jobs", requestBody);
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
}
[Theory]
[InlineData("'; DROP TABLE ScheduledJobs--")] // destructive injection
[InlineData("' OR '1'='1")] // boolean-based injection
[InlineData("<script>alert('xss')</script>")] // script injection
public async Task AddScheduledJob_WithMaliciousName_ShouldNotLeakDataOrExecuteInjection(string maliciousName)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
_adminUserId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
object requestBody = new
{
Name = maliciousName,
TaskType = ScheduledTaskType.ScanMediaLibraries,
ScheduleType = ScheduleType.WithIntervalInMinutes,
IntervalMinutes = 60
};
// Act
HttpResponseMessage response = await client.PostAsJsonAsync("/api/v1/scheduled-jobs", requestBody);
// Assert
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
// The malicious name either reaches the parameterized insert verbatim or is rejected by validation; it never corrupts the storage medium.
Assert.True(response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.UnprocessableEntity);
if (response.StatusCode == HttpStatusCode.OK)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.NotNull(await dbContext.ScheduledJobs.FirstOrDefaultAsync(scheduledJob => scheduledJob.Name == maliciousName));
}
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async ValueTask DisposeAsync()
{
if (_adminUserId != Guid.Empty)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
ScheduledJobEntity[] scheduledJobs = await dbContext.ScheduledJobs
.Where(scheduledJob => scheduledJob.OwnerUserId == _adminUserId)
.ToArrayAsync();
foreach (ScheduledJobEntity scheduledJob in scheduledJobs)
{
dbContext.ScheduledJobExecutions.RemoveRange(dbContext.ScheduledJobExecutions.Where(execution => execution.ScheduledJobId == scheduledJob.Id));
dbContext.ScheduledJobs.Remove(scheduledJob);
}
await dbContext.SaveChangesAsync();
await _apiFactory.RemoveAdminUserAsync(_adminUserId);
}
}
}
@@ -0,0 +1,43 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.Scheduling;
using Lumina.Application.Core.Scheduling.Commands.AddScheduledJob;
using Lumina.Contracts.Fixtures.Core.Requests.Scheduling;
using Lumina.Contracts.Requests.Scheduling;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.Scheduling;
/// <summary>
/// Contains unit tests for the <see cref="AddScheduledJobRequestMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddScheduledJobRequestMappingTests
{
private readonly AddScheduledJobRequestFixture _requestFixture = new();
[Fact]
public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly()
{
// Arrange
AddScheduledJobRequest request = _requestFixture.Create(
name: "Scan at 6am",
taskType: ScheduledTaskType.ScanMediaLibraries,
scheduleType: ScheduleType.DailyAtHourAndMinute,
hour: 6,
minute: 0);
// Act
AddScheduledJobCommand result = request.ToCommand();
// Assert
Assert.NotNull(result);
Assert.Equal(request.Name, result.Name);
Assert.Equal(request.TaskType, result.TaskType);
Assert.Equal(request.ScheduleType, result.ScheduleType);
Assert.Equal(request.IntervalMinutes, result.IntervalMinutes);
Assert.Equal(request.Hour, result.Hour);
Assert.Equal(request.Minute, result.Minute);
}
}
@@ -0,0 +1,34 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.Scheduling;
using Lumina.Application.Core.Scheduling.Commands.FireScheduledJob;
using Lumina.Contracts.Fixtures.Core.Requests.Scheduling;
using Lumina.Contracts.Requests.Scheduling;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.Scheduling;
/// <summary>
/// Contains unit tests for the <see cref="FireScheduledJobRequestMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class FireScheduledJobRequestMappingTests
{
private readonly FireScheduledJobRequestFixture _requestFixture = new();
[Fact]
public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly()
{
// Arrange
Guid scheduledJobId = Guid.NewGuid();
FireScheduledJobRequest request = _requestFixture.Create(scheduledJobId);
// Act
FireScheduledJobCommand result = request.ToCommand();
// Assert
Assert.NotNull(result);
Assert.Equal(request.ScheduledJobId, result.ScheduledJobId);
}
}
@@ -0,0 +1,36 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.Scheduling;
using Lumina.Application.Core.Scheduling.Queries.GetScheduledJobHistory;
using Lumina.Contracts.Fixtures.Core.Requests.Scheduling;
using Lumina.Contracts.Requests.Scheduling;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.Scheduling;
/// <summary>
/// Contains unit tests for the <see cref="GetScheduledJobHistoryRequestMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetScheduledJobHistoryRequestMappingTests
{
private readonly GetScheduledJobHistoryRequestFixture _requestFixture = new();
[Fact]
public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly()
{
// Arrange
DateTime from = new(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc);
DateTime to = new(2026, 1, 2, 0, 0, 0, DateTimeKind.Utc);
GetScheduledJobHistoryRequest request = _requestFixture.Create(from, to);
// Act
GetScheduledJobHistoryQuery result = request.ToQuery();
// Assert
Assert.NotNull(result);
Assert.Equal(request.From, result.From);
Assert.Equal(request.To, result.To);
}
}
@@ -0,0 +1,34 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.Scheduling;
using Lumina.Application.Core.Scheduling.Commands.RemoveScheduledJob;
using Lumina.Contracts.Fixtures.Core.Requests.Scheduling;
using Lumina.Contracts.Requests.Scheduling;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.Scheduling;
/// <summary>
/// Contains unit tests for the <see cref="RemoveScheduledJobRequestMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RemoveScheduledJobRequestMappingTests
{
private readonly RemoveScheduledJobRequestFixture _requestFixture = new();
[Fact]
public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly()
{
// Arrange
Guid scheduledJobId = Guid.NewGuid();
RemoveScheduledJobRequest request = _requestFixture.Create(scheduledJobId);
// Act
RemoveScheduledJobCommand result = request.ToCommand();
// Assert
Assert.NotNull(result);
Assert.Equal(request.ScheduledJobId, result.ScheduledJobId);
}
}
@@ -0,0 +1,169 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.Mapping.Scheduling;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
using Lumina.Contracts.Responses.Scheduling;
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 System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.Scheduling;
/// <summary>
/// Contains unit tests for the <see cref="ScheduledJobEntityMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScheduledJobEntityMappingTests
{
private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new();
[Fact]
public void ToDomainEntity_WhenRepositoryEntityHasIntervalSchedule_ShouldMapToIntervalScheduledJob()
{
// Arrange
ScheduledJobEntity repositoryEntity = _scheduledJobEntityFixture.Create(
scheduleType: ScheduleType.WithIntervalInMinutes,
status: ScheduledJobStatus.Active);
// Act
Result<ScheduledJob> result = repositoryEntity.ToDomainEntity();
// Assert
Assert.False(result.IsFailure);
Assert.Equal(repositoryEntity.Id, result.Value.Id.Value);
Assert.Equal(repositoryEntity.Name, result.Value.Name);
Assert.Equal(repositoryEntity.TaskType, result.Value.TaskType);
Assert.Equal(repositoryEntity.Status, result.Value.Status);
Assert.Equal(repositoryEntity.OwnerUserId, result.Value.OwnerUserId.Value);
IntervalSchedule intervalSchedule = Assert.IsType<IntervalSchedule>(result.Value.Schedule);
Assert.Equal(repositoryEntity.IntervalMinutes, intervalSchedule.IntervalMinutes);
if (repositoryEntity.LastStartedOnUtc is not null)
Assert.Equal(repositoryEntity.LastStartedOnUtc.Value, result.Value.LastStartedOnUtc.Value);
if (repositoryEntity.LastCompletedOnUtc is not null)
Assert.Equal(repositoryEntity.LastCompletedOnUtc.Value, result.Value.LastCompletedOnUtc.Value);
}
[Fact]
public void ToDomainEntity_WhenRepositoryEntityHasDailySchedule_ShouldMapToDailyScheduledJob()
{
// Arrange
ScheduledJobEntity repositoryEntity = _scheduledJobEntityFixture.Create(
scheduleType: ScheduleType.DailyAtHourAndMinute,
hour: 7,
minute: 15);
// Act
Result<ScheduledJob> result = repositoryEntity.ToDomainEntity();
// Assert
Assert.False(result.IsFailure);
DailySchedule dailySchedule = Assert.IsType<DailySchedule>(result.Value.Schedule);
Assert.Equal(7, dailySchedule.Hour);
Assert.Equal(15, dailySchedule.Minute);
}
[Fact]
public void ToDomainEntity_WhenIntervalScheduleHasNonPositiveInterval_ShouldReturnError()
{
// Arrange
ScheduledJobEntity repositoryEntity = _scheduledJobEntityFixture.Create(
scheduleType: ScheduleType.WithIntervalInMinutes,
intervalMinutes: 0);
// Act
Result<ScheduledJob> result = repositoryEntity.ToDomainEntity();
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Lumina.Domain.Common.Errors.Errors.Scheduling.IntervalMinutesMustBePositive, result.FirstError);
}
[Fact]
public void ToDomainEntity_WhenDailyScheduleHasOutOfRangeHour_ShouldReturnError()
{
// Arrange
ScheduledJobEntity repositoryEntity = _scheduledJobEntityFixture.Create(
scheduleType: ScheduleType.DailyAtHourAndMinute,
hour: 30,
minute: 0);
// Act
Result<ScheduledJob> result = repositoryEntity.ToDomainEntity();
// Assert
Assert.True(result.IsFailure);
}
[Fact]
public void ToDomainEntities_WhenCalledWithCollection_ShouldMapEveryRepositoryEntity()
{
// Arrange
List<ScheduledJobEntity> repositoryEntities =
[
_scheduledJobEntityFixture.Create(scheduleType: ScheduleType.WithIntervalInMinutes),
_scheduledJobEntityFixture.Create(scheduleType: ScheduleType.DailyAtHourAndMinute)
];
// Act
List<Result<ScheduledJob>> results = repositoryEntities.ToDomainEntities().ToList();
// Assert
Assert.Equal(2, results.Count);
Assert.All(results, result => Assert.False(result.IsFailure));
}
[Fact]
public void ToResponse_WhenRepositoryEntityHasIntervalSchedule_ShouldMapToResponse()
{
// Arrange
ScheduledJobEntity repositoryEntity = _scheduledJobEntityFixture.Create(
id: Guid.NewGuid(),
scheduleType: ScheduleType.WithIntervalInMinutes,
intervalMinutes: 45,
status: ScheduledJobStatus.Active);
// Act
ScheduledJobResponse result = repositoryEntity.ToResponse();
// Assert
Assert.NotNull(result);
Assert.Equal(repositoryEntity.Id, result.Id);
Assert.Equal(repositoryEntity.Name, result.Name);
Assert.Equal(repositoryEntity.TaskType, result.TaskType);
Assert.Equal(ScheduleType.WithIntervalInMinutes, result.ScheduleType);
Assert.Equal(45, result.IntervalMinutes);
Assert.Null(result.Hour);
Assert.Null(result.Minute);
Assert.Equal(ScheduledJobStatus.Active, result.Status);
Assert.Equal(repositoryEntity.LastStartedOnUtc, result.LastStartedOnUtc);
Assert.Equal(repositoryEntity.LastCompletedOnUtc, result.LastCompletedOnUtc);
}
[Fact]
public void ToResponse_WhenRepositoryEntityHasDailySchedule_ShouldMapToResponse()
{
// Arrange
ScheduledJobEntity repositoryEntity = _scheduledJobEntityFixture.Create(
id: Guid.NewGuid(),
scheduleType: ScheduleType.DailyAtHourAndMinute,
hour: 6,
minute: 30,
status: ScheduledJobStatus.Added);
// Act
ScheduledJobResponse result = repositoryEntity.ToResponse();
// Assert
Assert.NotNull(result);
Assert.Equal(ScheduleType.DailyAtHourAndMinute, result.ScheduleType);
Assert.Null(result.IntervalMinutes);
Assert.Equal(6, result.Hour);
Assert.Equal(30, result.Minute);
}
}
@@ -0,0 +1,62 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.Mapping.Scheduling;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
using Lumina.Contracts.Responses.Scheduling;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.Scheduling;
/// <summary>
/// Contains unit tests for the <see cref="ScheduledJobExecutionEntityMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScheduledJobExecutionEntityMappingTests
{
private readonly ScheduledJobExecutionEntityFixture _scheduledJobExecutionEntityFixture = new();
[Fact]
public void ToResponse_WhenRepositoryEntityIsCompleted_ShouldMapToResponse()
{
// Arrange
DateTime startedOnUtc = DateTime.UtcNow.AddMinutes(-10);
DateTime completedOnUtc = DateTime.UtcNow;
ScheduledJobExecutionEntity repositoryEntity = _scheduledJobExecutionEntityFixture.Create(
scheduledJobId: Guid.NewGuid(),
isCycleRun: true,
startedOnUtc: startedOnUtc,
completedOnUtc: completedOnUtc);
// Act
ScheduledJobExecutionResponse result = repositoryEntity.ToResponse();
// Assert
Assert.NotNull(result);
Assert.Equal(repositoryEntity.Id, result.Id);
Assert.Equal(repositoryEntity.ScheduledJobId, result.ScheduledJobId);
Assert.Equal(repositoryEntity.TaskType, result.TaskType);
Assert.True(result.IsCycleRun);
Assert.Equal(startedOnUtc, result.StartedOnUtc);
Assert.Equal(completedOnUtc, result.CompletedOnUtc);
}
[Fact]
public void ToResponse_WhenRepositoryEntityIsStillRunning_ShouldMapToResponseWithNullCompletionTime()
{
// Arrange
ScheduledJobExecutionEntity repositoryEntity = _scheduledJobExecutionEntityFixture.Create(
isCycleRun: false,
completedOnUtc: null);
// Act
ScheduledJobExecutionResponse result = repositoryEntity.ToResponse();
// Assert
Assert.NotNull(result);
Assert.Equal(repositoryEntity.Id, result.Id);
Assert.False(result.IsCycleRun);
Assert.Null(result.CompletedOnUtc);
}
}
@@ -0,0 +1,117 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.Mapping.Scheduling;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.Scheduling;
/// <summary>
/// Contains unit tests for the <see cref="ScheduledJobMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScheduledJobMappingTests
{
private readonly ScheduledJobFixture _scheduledJobFixture = new();
[Fact]
public void ToRepositoryEntity_WhenDomainEntityHasIntervalSchedule_ShouldMapToRepositoryEntity()
{
// Arrange
Guid ownerUserId = Guid.NewGuid();
Result<IntervalSchedule> intervalScheduleResult = IntervalSchedule.Create(30);
ScheduledJob domainEntity = _scheduledJobFixture.Create(
name: "Interval job",
taskType: ScheduledTaskType.ScanMediaLibraries,
schedule: intervalScheduleResult.Value,
ownerUserId: ownerUserId);
// Act
ScheduledJobEntity result = domainEntity.ToRepositoryEntity();
// Assert
Assert.NotNull(result);
Assert.Equal(domainEntity.Id.Value, result.Id);
Assert.Equal(domainEntity.Name, result.Name);
Assert.Equal(domainEntity.TaskType, result.TaskType);
Assert.Equal(ScheduleType.WithIntervalInMinutes, result.ScheduleType);
Assert.Equal(30, result.IntervalMinutes);
Assert.Null(result.Hour);
Assert.Null(result.Minute);
Assert.Equal(domainEntity.Status, result.Status);
Assert.Equal(ownerUserId, result.OwnerUserId);
Assert.False(result.LastStartedOnUtc.HasValue);
Assert.False(result.LastCompletedOnUtc.HasValue);
}
[Fact]
public void ToRepositoryEntity_WhenDomainEntityHasDailySchedule_ShouldMapToRepositoryEntity()
{
// Arrange
Result<DailySchedule> dailyScheduleResult = DailySchedule.Create(9, 45);
ScheduledJob domainEntity = _scheduledJobFixture.Create(
name: "Daily job",
taskType: ScheduledTaskType.CleanTemporaryFiles,
schedule: dailyScheduleResult.Value);
// Act
ScheduledJobEntity result = domainEntity.ToRepositoryEntity();
// Assert
Assert.NotNull(result);
Assert.Equal(ScheduleType.DailyAtHourAndMinute, result.ScheduleType);
Assert.Null(result.IntervalMinutes);
Assert.Equal(9, result.Hour);
Assert.Equal(45, result.Minute);
}
[Fact]
public void ToResponse_WhenDomainEntityHasIntervalSchedule_ShouldMapToResponse()
{
// Arrange
Result<IntervalSchedule> intervalScheduleResult = IntervalSchedule.Create(120);
ScheduledJob domainEntity = _scheduledJobFixture.Create(
name: "Interval job",
schedule: intervalScheduleResult.Value);
// Act
ScheduledJobResponse result = domainEntity.ToResponse();
// Assert
Assert.NotNull(result);
Assert.Equal(domainEntity.Id.Value, result.Id);
Assert.Equal(domainEntity.Name, result.Name);
Assert.Equal(ScheduleType.WithIntervalInMinutes, result.ScheduleType);
Assert.Equal(120, result.IntervalMinutes);
Assert.Null(result.Hour);
Assert.Null(result.Minute);
Assert.Equal(domainEntity.Status, result.Status);
}
[Fact]
public void ToResponse_WhenDomainEntityHasDailySchedule_ShouldMapToResponse()
{
// Arrange
Result<DailySchedule> dailyScheduleResult = DailySchedule.Create(5, 0);
ScheduledJob domainEntity = _scheduledJobFixture.Create(
name: "Daily job",
schedule: dailyScheduleResult.Value);
// Act
ScheduledJobResponse result = domainEntity.ToResponse();
// Assert
Assert.NotNull(result);
Assert.Equal(ScheduleType.DailyAtHourAndMinute, result.ScheduleType);
Assert.Null(result.IntervalMinutes);
Assert.Equal(5, result.Hour);
Assert.Equal(0, result.Minute);
}
}
@@ -0,0 +1,59 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.Mapping.Scheduling;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.Scheduling;
/// <summary>
/// Contains unit tests for the <see cref="SchedulerDisplayPreferencesEntityMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SchedulerDisplayPreferencesEntityMappingTests
{
private readonly SchedulerDisplayPreferencesEntityFixture _schedulerDisplayPreferencesEntityFixture = new();
[Fact]
public void ToResponse_WhenRepositoryEntityExists_ShouldMapToResponse()
{
// Arrange
Guid userId = Guid.NewGuid();
SchedulerDisplayPreferencesEntity repositoryEntity = _schedulerDisplayPreferencesEntityFixture.Create(
userId: userId,
jobTypeFilter: ScheduledTaskType.CleanTemporaryFiles,
displayTimeSpan: 30,
displayTimeUnit: SchedulerDisplayTimeUnit.Minutes);
// Act
SchedulerDisplayPreferencesResponse result = repositoryEntity.ToResponse();
// Assert
Assert.NotNull(result);
Assert.Equal(userId, result.UserId);
Assert.Equal(ScheduledTaskType.CleanTemporaryFiles, result.JobTypeFilter);
Assert.Equal(30, result.DisplayTimeSpan);
Assert.Equal(SchedulerDisplayTimeUnit.Minutes, result.DisplayTimeUnit);
}
[Fact]
public void ToDefaultResponse_WhenRepositoryEntityIsNull_ShouldReturnDefaultResponseForTheUser()
{
// Arrange
Guid userId = Guid.NewGuid();
// Act
SchedulerDisplayPreferencesResponse result = ((SchedulerDisplayPreferencesEntity?)null).ToDefaultResponse(userId);
// Assert
Assert.NotNull(result);
Assert.Equal(userId, result.UserId);
Assert.Null(result.JobTypeFilter);
Assert.Equal(10, result.DisplayTimeSpan);
Assert.Equal(SchedulerDisplayTimeUnit.Minutes, result.DisplayTimeUnit);
}
}
@@ -0,0 +1,34 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.Scheduling;
using Lumina.Application.Core.Scheduling.Commands.StartScheduledJob;
using Lumina.Contracts.Fixtures.Core.Requests.Scheduling;
using Lumina.Contracts.Requests.Scheduling;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.Scheduling;
/// <summary>
/// Contains unit tests for the <see cref="StartScheduledJobRequestMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class StartScheduledJobRequestMappingTests
{
private readonly StartScheduledJobRequestFixture _requestFixture = new();
[Fact]
public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly()
{
// Arrange
Guid scheduledJobId = Guid.NewGuid();
StartScheduledJobRequest request = _requestFixture.Create(scheduledJobId);
// Act
StartScheduledJobCommand result = request.ToCommand();
// Assert
Assert.NotNull(result);
Assert.Equal(request.ScheduledJobId, result.ScheduledJobId);
}
}
@@ -0,0 +1,34 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.Scheduling;
using Lumina.Application.Core.Scheduling.Commands.StopScheduledJob;
using Lumina.Contracts.Fixtures.Core.Requests.Scheduling;
using Lumina.Contracts.Requests.Scheduling;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.Scheduling;
/// <summary>
/// Contains unit tests for the <see cref="StopScheduledJobRequestMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class StopScheduledJobRequestMappingTests
{
private readonly StopScheduledJobRequestFixture _requestFixture = new();
[Fact]
public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly()
{
// Arrange
Guid scheduledJobId = Guid.NewGuid();
StopScheduledJobRequest request = _requestFixture.Create(scheduledJobId);
// Act
StopScheduledJobCommand result = request.ToCommand();
// Assert
Assert.NotNull(result);
Assert.Equal(request.ScheduledJobId, result.ScheduledJobId);
}
}
@@ -0,0 +1,38 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.Scheduling;
using Lumina.Application.Core.Scheduling.Commands.UpdateSchedulerDisplayPreferences;
using Lumina.Contracts.Fixtures.Core.Requests.Scheduling;
using Lumina.Contracts.Requests.Scheduling;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.Scheduling;
/// <summary>
/// Contains unit tests for the <see cref="UpdateSchedulerDisplayPreferencesRequestMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateSchedulerDisplayPreferencesRequestMappingTests
{
private readonly UpdateSchedulerDisplayPreferencesRequestFixture _requestFixture = new();
[Fact]
public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly()
{
// Arrange
UpdateSchedulerDisplayPreferencesRequest request = _requestFixture.Create(
jobTypeFilter: ScheduledTaskType.CleanTemporaryFiles,
displayTimeSpan: 15,
displayTimeUnit: SchedulerDisplayTimeUnit.Hours);
// Act
UpdateSchedulerDisplayPreferencesCommand result = request.ToCommand();
// Assert
Assert.NotNull(result);
Assert.Equal(request.JobTypeFilter, result.JobTypeFilter);
Assert.Equal(request.DisplayTimeSpan, result.DisplayTimeSpan);
Assert.Equal(request.DisplayTimeUnit, result.DisplayTimeUnit);
}
}
@@ -10,6 +10,7 @@ using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.File
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events;
using Microsoft.Extensions.Options;
using NSubstitute;
using System;
@@ -31,6 +32,7 @@ public class LibraryDeletedDomainEventHandlerTests
private readonly IPathService _mockPathService;
private readonly LibraryDeletedDomainEventHandler _sut;
private readonly LibraryFixture _libraryFixture = new();
private readonly LibraryDeletedDomainEventFixture _libraryDeletedDomainEventFixture = new();
private readonly MediaSettingsDtoFixture _mediaSettingsDtoFixture = new();
/// <summary>
@@ -64,7 +66,7 @@ public class LibraryDeletedDomainEventHandlerTests
// Arrange
Guid libraryId = Guid.NewGuid();
Library library = _libraryFixture.Create(id: libraryId);
LibraryDeletedDomainEvent domainEvent = new(Guid.NewGuid(), library, DateTime.UtcNow);
LibraryDeletedDomainEvent domainEvent = _libraryDeletedDomainEventFixture.Create(library: library);
// Act
await _sut.HandleAsync(domainEvent, CancellationToken.None);
@@ -80,7 +82,7 @@ public class LibraryDeletedDomainEventHandlerTests
// Arrange
Guid libraryId = Guid.NewGuid();
Library library = _libraryFixture.Create(id: libraryId);
LibraryDeletedDomainEvent domainEvent = new(Guid.NewGuid(), library, DateTime.UtcNow);
LibraryDeletedDomainEvent domainEvent = _libraryDeletedDomainEventFixture.Create(library: library);
Error error = Error.Failure(description: "Failed to delete library directory");
_mockDirectoryProviderService.DeleteDirectory(Arg.Any<FileSystemPathId>()).Returns(error);
@@ -98,7 +100,7 @@ public class LibraryDeletedDomainEventHandlerTests
// Arrange
Guid libraryId = Guid.NewGuid();
Library library = _libraryFixture.Create(id: libraryId);
LibraryDeletedDomainEvent domainEvent = new(Guid.NewGuid(), library, DateTime.UtcNow);
LibraryDeletedDomainEvent domainEvent = _libraryDeletedDomainEventFixture.Create(library: library);
Error error = Error.Failure(description: "Failed to combine path");
_mockPathService.CombinePath(Arg.Any<string>(), Arg.Any<string>()).Returns(error);
@@ -12,10 +12,8 @@ using Lumina.Domain.Common.Exceptions;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Microsoft.Extensions.Logging;
using NSubstitute;
using System;
@@ -40,10 +38,9 @@ public class LibraryMediaItemDeletedDomainEventHandlerTests
private readonly ILogger<LibraryMediaItemDeletedDomainEventHandler> _mockLogger;
private readonly LibraryMediaItemDeletedDomainEventHandler _sut;
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly ScanIdFixture _scanIdFixture = new();
private readonly UserIdFixture _userIdFixture = new();
private readonly BookEntityFixture _bookEntityFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly LibraryMediaItemDeletedDomainEventFixture _libraryMediaItemDeletedDomainEventFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="LibraryMediaItemDeletedDomainEventHandlerTests"/> class.
@@ -81,12 +78,7 @@ public class LibraryMediaItemDeletedDomainEventHandlerTests
.Returns(Result.Deleted);
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
LibraryMediaItemDeletedDomainEvent domainEvent = new(
Guid.NewGuid(),
libraryId,
MediaLibraryScanCompositeId.Create(_scanIdFixture.Create(), _userIdFixture.Create()),
book.Path,
DateTime.UtcNow);
LibraryMediaItemDeletedDomainEvent domainEvent = _libraryMediaItemDeletedDomainEventFixture.Create(libraryId: libraryId, path: book.Path);
// Act
await _sut.HandleAsync(domainEvent, CancellationToken.None);
@@ -105,12 +97,7 @@ public class LibraryMediaItemDeletedDomainEventHandlerTests
_mockBookRepository.GetByPathAsync(libraryId.Value, "/books/deleted.epub", Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(null));
LibraryMediaItemDeletedDomainEvent domainEvent = new(
Guid.NewGuid(),
libraryId,
MediaLibraryScanCompositeId.Create(_scanIdFixture.Create(), _userIdFixture.Create()),
"/books/deleted.epub",
DateTime.UtcNow);
LibraryMediaItemDeletedDomainEvent domainEvent = _libraryMediaItemDeletedDomainEventFixture.Create(libraryId: libraryId, path: "/books/deleted.epub");
// Act
await _sut.HandleAsync(domainEvent, CancellationToken.None);
@@ -140,12 +127,7 @@ public class LibraryMediaItemDeletedDomainEventHandlerTests
.Returns(Result.From(Result.Deleted));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
LibraryMediaItemDeletedDomainEvent domainEvent = new(
Guid.NewGuid(),
libraryId,
MediaLibraryScanCompositeId.Create(_scanIdFixture.Create(), _userIdFixture.Create()),
book.Path,
DateTime.UtcNow);
LibraryMediaItemDeletedDomainEvent domainEvent = _libraryMediaItemDeletedDomainEventFixture.Create(libraryId: libraryId, path: book.Path);
// Act
await _sut.HandleAsync(domainEvent, CancellationToken.None);
@@ -165,12 +147,7 @@ public class LibraryMediaItemDeletedDomainEventHandlerTests
_mockBookRepository.GetByPathAsync(libraryId.Value, "/books/deleted.epub", Arg.Any<CancellationToken>())
.Returns(error);
LibraryMediaItemDeletedDomainEvent domainEvent = new(
Guid.NewGuid(),
libraryId,
MediaLibraryScanCompositeId.Create(_scanIdFixture.Create(), _userIdFixture.Create()),
"/books/deleted.epub",
DateTime.UtcNow);
LibraryMediaItemDeletedDomainEvent domainEvent = _libraryMediaItemDeletedDomainEventFixture.Create(libraryId: libraryId, path: "/books/deleted.epub");
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
@@ -200,12 +177,7 @@ public class LibraryMediaItemDeletedDomainEventHandlerTests
_mockBookRepository.DeleteAsync(book.Id, Arg.Any<CancellationToken>())
.Returns(error);
LibraryMediaItemDeletedDomainEvent domainEvent = new(
Guid.NewGuid(),
libraryId,
MediaLibraryScanCompositeId.Create(_scanIdFixture.Create(), _userIdFixture.Create()),
book.Path,
DateTime.UtcNow);
LibraryMediaItemDeletedDomainEvent domainEvent = _libraryMediaItemDeletedDomainEventFixture.Create(libraryId: libraryId, path: book.Path);
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
@@ -15,6 +15,7 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events;
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events;
using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary;
using Microsoft.Extensions.Options;
using NSubstitute;
@@ -43,6 +44,7 @@ public class LibrarySavedDomainEventHandlerTests
private readonly IPathService _mockPathService;
private readonly LibrarySavedDomainEventHandler _sut;
private readonly LibraryFixture _libraryFixture = new();
private readonly LibrarySavedDomainEventFixture _librarySavedDomainEventFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new();
private readonly MediaSettingsDtoFixture _mediaSettingsDtoFixture = new();
@@ -97,14 +99,14 @@ public class LibrarySavedDomainEventHandlerTests
// Arrange
Guid libraryId = Guid.NewGuid();
Library library = _libraryFixture.Create(id: libraryId, coverImage: "C:/Users/user/cover.jpg");
LibrarySavedDomainEvent domainEvent = new(Guid.NewGuid(), library, DateTime.UtcNow);
LibrarySavedDomainEvent domainEvent = _librarySavedDomainEventFixture.Create(library: library);
LibraryEntity updatedLibrary = _libraryEntityFixture.Create(id: libraryId);
// Act
await _sut.HandleAsync(domainEvent, CancellationToken.None);
// Assert
Assert.NotNull(library.CoverImage);
Assert.NotNull(domainEvent.Library.CoverImage);
await _mockLibraryRepository.Received(1).UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -115,7 +117,7 @@ public class LibrarySavedDomainEventHandlerTests
// Arrange
Guid libraryId = Guid.NewGuid();
Library library = _libraryFixture.Create(id: libraryId, coverImage: "C:/Users/user/cover.jpg");
LibrarySavedDomainEvent domainEvent = new(Guid.NewGuid(), library, DateTime.UtcNow);
LibrarySavedDomainEvent domainEvent = _librarySavedDomainEventFixture.Create(library: library);
_mockDirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockFileProviderService.GetFilePaths(Arg.Any<FileSystemPathId>(), true)
.Returns(Result.From<IEnumerable<FileSystemPathId>>(
@@ -140,7 +142,7 @@ public class LibrarySavedDomainEventHandlerTests
// Arrange
Guid libraryId = Guid.NewGuid();
Library library = _libraryFixture.Create(id: libraryId, includeCoverImage: false);
LibrarySavedDomainEvent domainEvent = new(Guid.NewGuid(), library, DateTime.UtcNow);
LibrarySavedDomainEvent domainEvent = _librarySavedDomainEventFixture.Create(library: library);
_mockFileProviderService.GetFilePaths(Arg.Any<FileSystemPathId>(), true)
.Returns(Result.From<IEnumerable<FileSystemPathId>>(
[
@@ -162,7 +164,7 @@ public class LibrarySavedDomainEventHandlerTests
// Arrange
Guid libraryId = Guid.NewGuid();
Library library = _libraryFixture.Create(id: libraryId, coverImage: "/Media/Libraries/guid/cover.png");
LibrarySavedDomainEvent domainEvent = new(Guid.NewGuid(), library, DateTime.UtcNow);
LibrarySavedDomainEvent domainEvent = _librarySavedDomainEventFixture.Create(library: library);
// mirror the real CombinePath behavior, which treats the combined name as a directory segment and appends a trailing
// separator; the internal cover path resolution must still yield the file path without that trailing separator
_mockPathService.CombinePath(Arg.Any<string>(), Arg.Any<string>())
@@ -175,7 +177,7 @@ public class LibrarySavedDomainEventHandlerTests
await _sut.HandleAsync(domainEvent, CancellationToken.None);
// Assert
Assert.Equal("/Media/Libraries/guid/cover.png", library.CoverImage);
Assert.Equal("/Media/Libraries/guid/cover.png", domainEvent.Library.CoverImage);
_mockFileProviderService.DidNotReceive().CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), Arg.Any<bool>());
await _mockLibraryRepository.Received(1).UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
}
@@ -186,7 +188,7 @@ public class LibrarySavedDomainEventHandlerTests
// Arrange
Guid libraryId = Guid.NewGuid();
Library library = _libraryFixture.Create(id: libraryId, coverImage: "C:/Users/user/cover.jpg");
LibrarySavedDomainEvent domainEvent = new(Guid.NewGuid(), library, DateTime.UtcNow);
LibrarySavedDomainEvent domainEvent = _librarySavedDomainEventFixture.Create(library: library);
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(false));
// Act
@@ -204,7 +206,7 @@ public class LibrarySavedDomainEventHandlerTests
// Arrange
Guid libraryId = Guid.NewGuid();
Library library = _libraryFixture.Create(id: libraryId, coverImage: "C:/Users/user/cover.jpg");
LibrarySavedDomainEvent domainEvent = new(Guid.NewGuid(), library, DateTime.UtcNow);
LibrarySavedDomainEvent domainEvent = _librarySavedDomainEventFixture.Create(library: library);
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.None));
@@ -223,7 +225,7 @@ public class LibrarySavedDomainEventHandlerTests
// Arrange
Guid libraryId = Guid.NewGuid();
Library library = _libraryFixture.Create(id: libraryId, coverImage: "C:/Users/user/cover.jpg");
LibrarySavedDomainEvent domainEvent = new(Guid.NewGuid(), library, DateTime.UtcNow);
LibrarySavedDomainEvent domainEvent = _librarySavedDomainEventFixture.Create(library: library);
Error error = Error.Failure(description: "Failed to copy cover file");
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
.Returns(error);
@@ -243,7 +245,7 @@ public class LibrarySavedDomainEventHandlerTests
// Arrange
Guid libraryId = Guid.NewGuid();
Library library = _libraryFixture.Create(id: libraryId, includeCoverImage: false);
LibrarySavedDomainEvent domainEvent = new(Guid.NewGuid(), library, DateTime.UtcNow);
LibrarySavedDomainEvent domainEvent = _librarySavedDomainEventFixture.Create(library: library);
Error error = Error.Failure(description: "Failed to combine path");
_mockPathService.CombinePath(Arg.Any<string>(), Arg.Any<string>()).Returns(error);
@@ -262,7 +264,7 @@ public class LibrarySavedDomainEventHandlerTests
// Arrange
Guid libraryId = Guid.NewGuid();
Library library = _libraryFixture.Create(id: libraryId, coverImage: "C:/Users/user/cover.jpg");
LibrarySavedDomainEvent domainEvent = new(Guid.NewGuid(), library, DateTime.UtcNow);
LibrarySavedDomainEvent domainEvent = _librarySavedDomainEventFixture.Create(library: library);
Error error = Error.Failure(description: "Failed to update library");
_mockLibraryRepository.UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>())
.Returns(error);
@@ -12,8 +12,7 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
using NSubstitute;
using System;
@@ -39,8 +38,7 @@ public class LibraryScanCancelledDomainEventHandlerTests
private readonly IMediaLibrariesScanCancellationTracker _mockMediaLibrariesScanCancellationTracker;
private readonly LibraryScanCancelledDomainEventHandler _sut;
private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new();
private readonly ScanIdFixture _scanIdFixture = new();
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly LibraryScanCancelledDomainEventFixture _libraryScanCancelledDomainEventFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="LibraryScanCancelledDomainEventHandlerTests"/> class.
@@ -68,8 +66,10 @@ public class LibraryScanCancelledDomainEventHandlerTests
public async Task HandleAsync_WhenScanExists_ShouldCancelScanAndCleanupResources()
{
// Arrange
LibraryScanEntity scan = _libraryScanEntityFixture.Create();
LibraryScanCancelledDomainEvent domainEvent = new(Guid.NewGuid(), _scanIdFixture.Create(value: scan.Id), _libraryIdFixture.Create(value: scan.LibraryId), DateTime.UtcNow);
LibraryScanCancelledDomainEvent domainEvent = _libraryScanCancelledDomainEventFixture.Create();
LibraryScanEntity scan = _libraryScanEntityFixture.Create(
id: domainEvent.ScanId.Value,
libraryId: domainEvent.LibraryId.Value);
_mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryScanEntity?>(scan));
@@ -87,7 +87,7 @@ public class LibraryScanCancelledDomainEventHandlerTests
public async Task HandleAsync_WhenGetByIdFails_ShouldThrowEventualConsistencyException()
{
// Arrange
LibraryScanCancelledDomainEvent domainEvent = new(Guid.NewGuid(), _scanIdFixture.Create(), _libraryIdFixture.Create(), DateTime.UtcNow);
LibraryScanCancelledDomainEvent domainEvent = _libraryScanCancelledDomainEventFixture.Create();
Error error = Error.Failure(description: "Failed to get library scan");
_mockLibraryScanRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(error);
@@ -105,7 +105,7 @@ public class LibraryScanCancelledDomainEventHandlerTests
public async Task HandleAsync_WhenScanDoesNotExist_ShouldThrowEventualConsistencyExceptionWithNotFoundError()
{
// Arrange
LibraryScanCancelledDomainEvent domainEvent = new(Guid.NewGuid(), _scanIdFixture.Create(), _libraryIdFixture.Create(), DateTime.UtcNow);
LibraryScanCancelledDomainEvent domainEvent = _libraryScanCancelledDomainEventFixture.Create();
_mockLibraryScanRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result<LibraryScanEntity?>.Success(null));
@@ -122,8 +122,10 @@ public class LibraryScanCancelledDomainEventHandlerTests
public async Task HandleAsync_WhenCancelScanFails_ShouldThrowEventualConsistencyException()
{
// Arrange
LibraryScanEntity scan = _libraryScanEntityFixture.Create();
LibraryScanCancelledDomainEvent domainEvent = new(Guid.NewGuid(), _scanIdFixture.Create(value: scan.Id), _libraryIdFixture.Create(value: scan.LibraryId), DateTime.UtcNow);
LibraryScanCancelledDomainEvent domainEvent = _libraryScanCancelledDomainEventFixture.Create();
LibraryScanEntity scan = _libraryScanEntityFixture.Create(
id: domainEvent.ScanId.Value,
libraryId: domainEvent.LibraryId.Value);
_mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryScanEntity?>(scan));
Error error = Error.Failure(description: "Failed to cancel scan");
@@ -143,8 +145,10 @@ public class LibraryScanCancelledDomainEventHandlerTests
public async Task HandleAsync_WhenClearForScanFails_ShouldThrowEventualConsistencyException()
{
// Arrange
LibraryScanEntity scan = _libraryScanEntityFixture.Create();
LibraryScanCancelledDomainEvent domainEvent = new(Guid.NewGuid(), _scanIdFixture.Create(value: scan.Id), _libraryIdFixture.Create(value: scan.LibraryId), DateTime.UtcNow);
LibraryScanCancelledDomainEvent domainEvent = _libraryScanCancelledDomainEventFixture.Create();
LibraryScanEntity scan = _libraryScanEntityFixture.Create(
id: domainEvent.ScanId.Value,
libraryId: domainEvent.LibraryId.Value);
_mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryScanEntity?>(scan));
Error error = Error.Failure(description: "Failed to clear staging results");
@@ -12,9 +12,7 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
using NSubstitute;
@@ -41,10 +39,7 @@ public class LibraryScanFailedDomainEventHandlerTests
private readonly IMediaLibraryScanProgressNotifier _mockDebouncedLibraryScanProgressNotifier;
private readonly LibraryScanFailedDomainEventHandler _sut;
private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new();
private readonly ScanIdFixture _scanIdFixture = new();
private readonly UserIdFixture _userIdFixture = new();
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new();
private readonly LibraryScanFailedDomainEventFixture _libraryScanFailedDomainEventFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="LibraryScanFailedDomainEventHandlerTests"/> class.
@@ -73,11 +68,11 @@ public class LibraryScanFailedDomainEventHandlerTests
public async Task HandleAsync_WhenScanIsRunning_ShouldFailScanAndCleanupResources()
{
// Arrange
LibraryScanEntity scan = _libraryScanEntityFixture.Create();
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(
scanId: _scanIdFixture.Create(value: scan.Id),
userId: _userIdFixture.Create(value: scan.UserId));
LibraryScanFailedDomainEvent domainEvent = new(Guid.NewGuid(), _libraryIdFixture.Create(value: scan.LibraryId), compositeId, DateTime.UtcNow);
LibraryScanFailedDomainEvent domainEvent = _libraryScanFailedDomainEventFixture.Create();
MediaLibraryScanCompositeId compositeId = domainEvent.MediaLibraryScanCompositeId;
LibraryScanEntity scan = _libraryScanEntityFixture.Create(
id: compositeId.ScanId.Value,
userId: compositeId.UserId.Value);
_mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryScanEntity?>(scan));
@@ -97,11 +92,12 @@ public class LibraryScanFailedDomainEventHandlerTests
public async Task HandleAsync_WhenScanIsNotRunning_ShouldSkipPersistenceButStillCleanupResources()
{
// Arrange
LibraryScanEntity scan = _libraryScanEntityFixture.Create(status: LibraryScanJobStatus.Failed);
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(
scanId: _scanIdFixture.Create(value: scan.Id),
userId: _userIdFixture.Create(value: scan.UserId));
LibraryScanFailedDomainEvent domainEvent = new(Guid.NewGuid(), _libraryIdFixture.Create(value: scan.LibraryId), compositeId, DateTime.UtcNow);
LibraryScanFailedDomainEvent domainEvent = _libraryScanFailedDomainEventFixture.Create();
MediaLibraryScanCompositeId compositeId = domainEvent.MediaLibraryScanCompositeId;
LibraryScanEntity scan = _libraryScanEntityFixture.Create(
id: compositeId.ScanId.Value,
userId: compositeId.UserId.Value,
status: LibraryScanJobStatus.Failed);
_mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryScanEntity?>(scan));
@@ -121,8 +117,7 @@ public class LibraryScanFailedDomainEventHandlerTests
public async Task HandleAsync_WhenGetByIdFails_ShouldThrowEventualConsistencyException()
{
// Arrange
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
LibraryScanFailedDomainEvent domainEvent = new(Guid.NewGuid(), _libraryIdFixture.Create(), compositeId, DateTime.UtcNow);
LibraryScanFailedDomainEvent domainEvent = _libraryScanFailedDomainEventFixture.Create();
Error error = Error.Failure(description: "Failed to get library scan");
_mockLibraryScanRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(error);
@@ -140,8 +135,7 @@ public class LibraryScanFailedDomainEventHandlerTests
public async Task HandleAsync_WhenScanDoesNotExist_ShouldThrowEventualConsistencyExceptionWithNotFoundError()
{
// Arrange
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
LibraryScanFailedDomainEvent domainEvent = new(Guid.NewGuid(), _libraryIdFixture.Create(), compositeId, DateTime.UtcNow);
LibraryScanFailedDomainEvent domainEvent = _libraryScanFailedDomainEventFixture.Create();
_mockLibraryScanRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result<LibraryScanEntity?>.Success(null));
@@ -158,11 +152,11 @@ public class LibraryScanFailedDomainEventHandlerTests
public async Task HandleAsync_WhenUpdateFails_ShouldThrowEventualConsistencyException()
{
// Arrange
LibraryScanEntity scan = _libraryScanEntityFixture.Create();
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(
scanId: _scanIdFixture.Create(value: scan.Id),
userId: _userIdFixture.Create(value: scan.UserId));
LibraryScanFailedDomainEvent domainEvent = new(Guid.NewGuid(), _libraryIdFixture.Create(value: scan.LibraryId), compositeId, DateTime.UtcNow);
LibraryScanFailedDomainEvent domainEvent = _libraryScanFailedDomainEventFixture.Create();
MediaLibraryScanCompositeId compositeId = domainEvent.MediaLibraryScanCompositeId;
LibraryScanEntity scan = _libraryScanEntityFixture.Create(
id: compositeId.ScanId.Value,
userId: compositeId.UserId.Value);
_mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryScanEntity?>(scan));
Error error = Error.Failure(description: "Failed to update library scan");
@@ -182,11 +176,11 @@ public class LibraryScanFailedDomainEventHandlerTests
public async Task HandleAsync_WhenClearForScanFails_ShouldThrowEventualConsistencyException()
{
// Arrange
LibraryScanEntity scan = _libraryScanEntityFixture.Create();
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(
scanId: _scanIdFixture.Create(value: scan.Id),
userId: _userIdFixture.Create(value: scan.UserId));
LibraryScanFailedDomainEvent domainEvent = new(Guid.NewGuid(), _libraryIdFixture.Create(value: scan.LibraryId), compositeId, DateTime.UtcNow);
LibraryScanFailedDomainEvent domainEvent = _libraryScanFailedDomainEventFixture.Create();
MediaLibraryScanCompositeId compositeId = domainEvent.MediaLibraryScanCompositeId;
LibraryScanEntity scan = _libraryScanEntityFixture.Create(
id: compositeId.ScanId.Value,
userId: compositeId.UserId.Value);
_mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryScanEntity?>(scan));
Error error = Error.Failure(description: "Failed to clear staging results");
@@ -8,14 +8,11 @@ using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Manage
using Lumina.Domain.Common.Exceptions;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
using NSubstitute;
@@ -41,10 +38,7 @@ public class LibraryScanFinishedDomainEventHandlerTests
private readonly IMediaLibraryScanProgressNotifier _mockDebouncedLibraryScanProgressNotifier;
private readonly LibraryScanFinishedDomainEventHandler _sut;
private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new();
private readonly ScanIdFixture _scanIdFixture = new();
private readonly UserIdFixture _userIdFixture = new();
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new();
private readonly LibraryScanFinishedDomainEventFixture _libraryScanFinishedDomainEventFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="LibraryScanFinishedDomainEventHandlerTests"/> class.
@@ -69,11 +63,11 @@ public class LibraryScanFinishedDomainEventHandlerTests
public async Task HandleAsync_WhenScanIsRunning_ShouldFinishScanAndNotifyClients()
{
// Arrange
LibraryScanEntity scan = _libraryScanEntityFixture.Create();
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(
scanId: _scanIdFixture.Create(value: scan.Id),
userId: _userIdFixture.Create(value: scan.UserId));
LibraryScanFinishedDomainEvent domainEvent = new(Guid.NewGuid(), compositeId, DateTime.UtcNow);
LibraryScanFinishedDomainEvent domainEvent = _libraryScanFinishedDomainEventFixture.Create();
MediaLibraryScanCompositeId compositeId = domainEvent.MediaLibraryScanCompositeId;
LibraryScanEntity scan = _libraryScanEntityFixture.Create(
id: compositeId.ScanId.Value,
userId: compositeId.UserId.Value);
_mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryScanEntity?>(scan));
_mockMediaLibrariesScanProgressTracker.UpdateScanProgress(Arg.Any<LibraryId>(), compositeId).Returns(Result.Updated);
@@ -93,8 +87,7 @@ public class LibraryScanFinishedDomainEventHandlerTests
public async Task HandleAsync_WhenGetByIdFails_ShouldThrowEventualConsistencyException()
{
// Arrange
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
LibraryScanFinishedDomainEvent domainEvent = new(Guid.NewGuid(), compositeId, DateTime.UtcNow);
LibraryScanFinishedDomainEvent domainEvent = _libraryScanFinishedDomainEventFixture.Create();
Error error = Error.Failure(description: "Failed to get library scan");
_mockLibraryScanRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(error);
@@ -112,8 +105,7 @@ public class LibraryScanFinishedDomainEventHandlerTests
public async Task HandleAsync_WhenScanDoesNotExist_ShouldThrowEventualConsistencyExceptionWithNotFoundError()
{
// Arrange
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
LibraryScanFinishedDomainEvent domainEvent = new(Guid.NewGuid(), compositeId, DateTime.UtcNow);
LibraryScanFinishedDomainEvent domainEvent = _libraryScanFinishedDomainEventFixture.Create();
_mockLibraryScanRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result<LibraryScanEntity?>.Success(null));
@@ -130,11 +122,12 @@ public class LibraryScanFinishedDomainEventHandlerTests
public async Task HandleAsync_WhenScanIsNotRunning_ShouldThrowEventualConsistencyException()
{
// Arrange
LibraryScanEntity scan = _libraryScanEntityFixture.Create(status: LibraryScanJobStatus.Pending);
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(
scanId: _scanIdFixture.Create(value: scan.Id),
userId: _userIdFixture.Create(value: scan.UserId));
LibraryScanFinishedDomainEvent domainEvent = new(Guid.NewGuid(), compositeId, DateTime.UtcNow);
LibraryScanFinishedDomainEvent domainEvent = _libraryScanFinishedDomainEventFixture.Create();
MediaLibraryScanCompositeId compositeId = domainEvent.MediaLibraryScanCompositeId;
LibraryScanEntity scan = _libraryScanEntityFixture.Create(
id: compositeId.ScanId.Value,
userId: compositeId.UserId.Value,
status: LibraryScanJobStatus.Pending);
_mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryScanEntity?>(scan));
@@ -152,11 +145,11 @@ public class LibraryScanFinishedDomainEventHandlerTests
public async Task HandleAsync_WhenUpdateFails_ShouldThrowEventualConsistencyException()
{
// Arrange
LibraryScanEntity scan = _libraryScanEntityFixture.Create();
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(
scanId: _scanIdFixture.Create(value: scan.Id),
userId: _userIdFixture.Create(value: scan.UserId));
LibraryScanFinishedDomainEvent domainEvent = new(Guid.NewGuid(), compositeId, DateTime.UtcNow);
LibraryScanFinishedDomainEvent domainEvent = _libraryScanFinishedDomainEventFixture.Create();
MediaLibraryScanCompositeId compositeId = domainEvent.MediaLibraryScanCompositeId;
LibraryScanEntity scan = _libraryScanEntityFixture.Create(
id: compositeId.ScanId.Value,
userId: compositeId.UserId.Value);
_mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryScanEntity?>(scan));
Error error = Error.Failure(description: "Failed to update library scan");
@@ -6,7 +6,7 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using NSubstitute;
using System;
@@ -26,9 +26,8 @@ public class LibraryScanJobProgressChangedDomainEventHandlerTests
private readonly IMediaLibrariesScanProgressTracker _mockMediaLibrariesScanProgressTracker;
private readonly IMediaLibraryScanProgressNotifier _mockDebouncedLibraryScanProgressNotifier;
private readonly LibraryScanJobProgressChangedDomainEventHandler _sut;
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new();
private readonly MediaLibraryScanJobProgressFixture _mediaLibraryScanJobProgressFixture = new();
private readonly LibraryScanJobProgressChangedDomainEventFixture _libraryScanJobProgressChangedDomainEventFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="LibraryScanJobProgressChangedDomainEventHandlerTests"/> class.
@@ -45,10 +44,10 @@ public class LibraryScanJobProgressChangedDomainEventHandlerTests
public async Task HandleAsync_WhenScanJobProgressChanges_ShouldUpdateTrackerAndNotifySignalRClients()
{
// Arrange
LibraryId libraryId = _libraryIdFixture.Create();
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
MediaLibraryScanJobProgress progress = _mediaLibraryScanJobProgressFixture.Create(completedItems: 5, totalItems: 10, currentOperation: "Hashing");
LibraryScanJobProgressChangedDomainEvent domainEvent = new(Guid.NewGuid(), libraryId, compositeId, progress, DateTime.UtcNow);
LibraryScanJobProgressChangedDomainEvent domainEvent = _libraryScanJobProgressChangedDomainEventFixture.Create(progress: progress);
LibraryId libraryId = domainEvent.LibraryId;
MediaLibraryScanCompositeId compositeId = domainEvent.MediaLibraryScanCompositeId;
_mockMediaLibrariesScanProgressTracker.UpdateScanJobProgress(libraryId, compositeId, progress).Returns(Result.Updated);
// Act
@@ -6,8 +6,7 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
@@ -26,8 +25,7 @@ public class LibraryScanProgressChangedDomainEventHandlerTests
private readonly IMediaLibrariesScanProgressTracker _mockMediaLibrariesScanProgressTracker;
private readonly IMediaLibraryScanProgressNotifier _mockDebouncedLibraryScanProgressNotifier;
private readonly LibraryScanProgressChangedDomainEventHandler _sut;
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new();
private readonly LibraryScanProgressChangedDomainEventFixture _libraryScanProgressChangedDomainEventFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="LibraryScanProgressChangedDomainEventHandlerTests"/> class.
@@ -44,9 +42,9 @@ public class LibraryScanProgressChangedDomainEventHandlerTests
public async Task HandleAsync_WhenScanProgressChanges_ShouldUpdateTrackerAndNotifySignalRClients()
{
// Arrange
LibraryId libraryId = _libraryIdFixture.Create();
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
LibraryScanProgressChangedDomainEvent domainEvent = new(Guid.NewGuid(), libraryId, compositeId, DateTime.UtcNow);
LibraryScanProgressChangedDomainEvent domainEvent = _libraryScanProgressChangedDomainEventFixture.Create();
LibraryId libraryId = domainEvent.LibraryId;
MediaLibraryScanCompositeId compositeId = domainEvent.MediaLibraryScanCompositeId;
_mockMediaLibrariesScanProgressTracker.UpdateScanProgress(libraryId, compositeId).Returns(Result.Updated);
// Act
@@ -11,8 +11,7 @@ using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using NSubstitute;
using System;
@@ -36,8 +35,7 @@ public class LibraryScanQueuedDomainEventHandlerTests
private readonly IDomainEventsQueue _mockDomainEventsQueue;
private readonly LibraryScanQueuedDomainEventHandler _sut;
private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new();
private readonly ScanIdFixture _scanIdFixture = new();
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly LibraryScanQueuedDomainEventFixture _libraryScanQueuedDomainEventFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="LibraryScanQueuedDomainEventHandlerTests"/> class.
@@ -61,8 +59,10 @@ public class LibraryScanQueuedDomainEventHandlerTests
public async Task HandleAsync_WhenScanExists_ShouldStartTheScan()
{
// Arrange
LibraryScanEntity scan = _libraryScanEntityFixture.Create();
LibraryScanQueuedDomainEvent domainEvent = new(Guid.NewGuid(), _scanIdFixture.Create(value: scan.Id), _libraryIdFixture.Create(value: scan.LibraryId), DateTime.UtcNow);
LibraryScanQueuedDomainEvent domainEvent = _libraryScanQueuedDomainEventFixture.Create();
LibraryScanEntity scan = _libraryScanEntityFixture.Create(
id: domainEvent.ScanId.Value,
libraryId: domainEvent.LibraryId.Value);
_mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryScanEntity?>(scan));
@@ -80,7 +80,7 @@ public class LibraryScanQueuedDomainEventHandlerTests
public async Task HandleAsync_WhenGetByIdFails_ShouldThrowEventualConsistencyException()
{
// Arrange
LibraryScanQueuedDomainEvent domainEvent = new(Guid.NewGuid(), _scanIdFixture.Create(), _libraryIdFixture.Create(), DateTime.UtcNow);
LibraryScanQueuedDomainEvent domainEvent = _libraryScanQueuedDomainEventFixture.Create();
Error error = Error.Failure(description: "Failed to get library scan");
_mockLibraryScanRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(error);
@@ -98,7 +98,7 @@ public class LibraryScanQueuedDomainEventHandlerTests
public async Task HandleAsync_WhenScanDoesNotExist_ShouldThrowEventualConsistencyExceptionWithNotFoundError()
{
// Arrange
LibraryScanQueuedDomainEvent domainEvent = new(Guid.NewGuid(), _scanIdFixture.Create(), _libraryIdFixture.Create(), DateTime.UtcNow);
LibraryScanQueuedDomainEvent domainEvent = _libraryScanQueuedDomainEventFixture.Create();
_mockLibraryScanRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result<LibraryScanEntity?>.Success(null));
@@ -115,8 +115,10 @@ public class LibraryScanQueuedDomainEventHandlerTests
public async Task HandleAsync_WhenStartScanFails_ShouldThrowEventualConsistencyException()
{
// Arrange
LibraryScanEntity scan = _libraryScanEntityFixture.Create();
LibraryScanQueuedDomainEvent domainEvent = new(Guid.NewGuid(), _scanIdFixture.Create(value: scan.Id), _libraryIdFixture.Create(value: scan.LibraryId), DateTime.UtcNow);
LibraryScanQueuedDomainEvent domainEvent = _libraryScanQueuedDomainEventFixture.Create();
LibraryScanEntity scan = _libraryScanEntityFixture.Create(
id: domainEvent.ScanId.Value,
libraryId: domainEvent.LibraryId.Value);
_mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryScanEntity?>(scan));
Error error = Error.Failure(description: "Failed to start scan");
@@ -5,9 +5,8 @@ using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Core.MediaLibrary.Management.Events;
using Lumina.Domain.Common.Exceptions;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using NSubstitute;
using System;
using System.Collections.Generic;
@@ -27,7 +26,7 @@ public class LibraryScanStartedDomainEventHandlerTests
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ILibraryScanRepository _mockLibraryScanRepository;
private readonly LibraryScanStartedDomainEventHandler _sut;
private readonly LibraryScanFixture _libraryScanFixture = new();
private readonly LibraryScanStartedDomainEventFixture _libraryScanStartedDomainEventFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="LibraryScanStartedDomainEventHandlerTests"/> class.
@@ -47,15 +46,14 @@ public class LibraryScanStartedDomainEventHandlerTests
public async Task HandleAsync_WhenScanStarts_ShouldUpdateScanStatusAndSaveChanges()
{
// Arrange
LibraryScan libraryScan = _libraryScanFixture.Create();
LibraryScanStartedDomainEvent domainEvent = new(Guid.NewGuid(), libraryScan, DateTime.UtcNow);
LibraryScanStartedDomainEvent domainEvent = _libraryScanStartedDomainEventFixture.Create();
// Act
await _sut.HandleAsync(domainEvent, CancellationToken.None);
// Assert
await _mockLibraryScanRepository.Received(1).UpdateAsync(
Arg.Is<LibraryScanEntity>(scan => scan.Id == libraryScan.Id.Value),
Arg.Is<LibraryScanEntity>(scan => scan.Id == domainEvent.LibraryScan.Id.Value),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -64,8 +62,7 @@ public class LibraryScanStartedDomainEventHandlerTests
public async Task HandleAsync_WhenUpdateFails_ShouldThrowEventualConsistencyException()
{
// Arrange
LibraryScan libraryScan = _libraryScanFixture.Create();
LibraryScanStartedDomainEvent domainEvent = new(Guid.NewGuid(), libraryScan, DateTime.UtcNow);
LibraryScanStartedDomainEvent domainEvent = _libraryScanStartedDomainEventFixture.Create();
Error error = Error.Failure(description: "Failed to update library scan");
_mockLibraryScanRepository.UpdateAsync(Arg.Any<LibraryScanEntity>(), Arg.Any<CancellationToken>())
.Returns(error);
@@ -0,0 +1,256 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DomainEvents;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.Scheduling.Commands.AddScheduledJob;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Fixtures.Core.Scheduling.Commands.AddScheduledJob;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Commands.AddScheduledJob;
/// <summary>
/// Contains unit tests for the <see cref="AddScheduledJobCommandHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddScheduledJobCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly IDomainEventsQueue _mockDomainEventsQueue;
private readonly IScheduledJobRepository _mockScheduledJobRepository;
private readonly IValidator<AddScheduledJobCommand> _mockValidator;
private readonly AddScheduledJobCommandHandler _sut;
private readonly AddScheduledJobCommandFixture _addScheduledJobCommandFixture = new();
private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new();
private readonly Guid _userId = Guid.NewGuid();
/// <summary>
/// Initializes a new instance of the <see cref="AddScheduledJobCommandHandlerTests"/> class.
/// </summary>
public AddScheduledJobCommandHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockDomainEventsQueue = Substitute.For<IDomainEventsQueue>();
_mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
_mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository);
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(true);
_mockValidator = Substitute.For<IValidator<AddScheduledJobCommand>>();
_mockValidator.Validate(Arg.Any<AddScheduledJobCommand>()).Returns([]);
_sut = new AddScheduledJobCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockDomainEventsQueue, _mockUnitOfWork, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenCommandIsValidWithIntervalSchedule_ShouldInsertScheduledJobAndReturnResponse()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(scheduleType: ScheduleType.WithIntervalInMinutes);
_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(command.TaskType, result.Value.TaskType);
Assert.Equal(ScheduleType.WithIntervalInMinutes, result.Value.ScheduleType);
Assert.Equal(command.IntervalMinutes, result.Value.IntervalMinutes);
Assert.Equal(ScheduledJobStatus.Added, result.Value.Status);
await _mockScheduledJobRepository.Received(1).InsertAsync(
Arg.Is<ScheduledJobEntity>(scheduledJob =>
scheduledJob.Name == command.Name &&
scheduledJob.TaskType == command.TaskType &&
scheduledJob.ScheduleType == ScheduleType.WithIntervalInMinutes &&
scheduledJob.IntervalMinutes == command.IntervalMinutes &&
scheduledJob.OwnerUserId == _userId),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
_mockDomainEventsQueue.Received(1).Enqueue(Arg.Is<IDomainEvent>(domainEvent => domainEvent is ScheduledJobAddedDomainEvent));
}
[Fact]
public async Task HandleAsync_WhenCommandIsValidWithDailySchedule_ShouldInsertScheduledJobAndReturnResponse()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(scheduleType: ScheduleType.DailyAtHourAndMinute, hour: 6, minute: 30);
_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(ScheduleType.DailyAtHourAndMinute, result.Value.ScheduleType);
Assert.Equal(6, result.Value.Hour);
Assert.Equal(30, result.Value.Minute);
Assert.Null(result.Value.IntervalMinutes);
await _mockScheduledJobRepository.Received(1).InsertAsync(
Arg.Is<ScheduledJobEntity>(scheduledJob =>
scheduledJob.ScheduleType == ScheduleType.DailyAtHourAndMinute &&
scheduledJob.Hour == 6 &&
scheduledJob.Minute == 30),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenValidatorReturnsError_ShouldReturnValidationErrorAndNotPersist()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create();
_mockValidator.Validate(Arg.Any<AddScheduledJobCommand>()).Returns([DomainErrors.Scheduling.ScheduledJobNameCannotBeEmpty]);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.ScheduledJobNameCannotBeEmpty, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
}
[Fact]
public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorizedAndNotPersist()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// 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().InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAdministrator_ShouldReturnNotAuthorizedAndNotPersist()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.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().InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenIntervalScheduleHasNonPositiveInterval_ShouldReturnIntervalError()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(
scheduleType: ScheduleType.WithIntervalInMinutes,
intervalMinutes: 0);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.IntervalMinutesMustBePositive, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenDailyScheduleHasOutOfRangeHour_ShouldReturnHourError()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(
scheduleType: ScheduleType.DailyAtHourAndMinute,
hour: 24,
minute: 0);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.HourMustBeBetweenZeroAndTwentyThree, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenScheduleTypeIsUnsupported_ShouldReturnInvalidScheduleTypeError()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(scheduleType: (ScheduleType)999);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.InvalidScheduleType, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenScheduledJobNameIsEmpty_ShouldReturnNameErrorAndNotPersist()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(name: " ");
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Scheduling.ScheduledJobNameCannotBeEmpty, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenInsertFails_ShouldReturnErrorAndNotSaveChanges()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create();
_mockScheduledJobRepository.InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>())
.Returns(DomainErrors.Scheduling.ScheduledJobAlreadyExists);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.ScheduledJobAlreadyExists, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
}
}
@@ -0,0 +1,195 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Scheduling.Commands.AddScheduledJob;
using Lumina.Application.Fixtures.Core.Scheduling.Commands.AddScheduledJob;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Commands.AddScheduledJob;
/// <summary>
/// Contains unit tests for the <see cref="AddScheduledJobCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddScheduledJobCommandValidatorTests
{
private readonly AddScheduledJobCommandValidator _validator = new();
private readonly AddScheduledJobCommandFixture _addScheduledJobCommandFixture = new();
[Theory]
[InlineData(null)] // null name
[InlineData("")] // empty name
[InlineData(" ")] // whitespace name
public void Validate_WhenNameIsNullOrWhitespace_ShouldHaveValidationError(string? name)
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create() with { Name = name! };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Scheduling.ScheduledJobNameCannotBeEmpty);
}
[Fact]
public void Validate_WhenNameExceedsMaximumLength_ShouldHaveValidationError()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(name: new string('a', 81));
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Scheduling.ScheduledJobNameCannotBeEmpty);
}
[Fact]
public void Validate_WhenTaskTypeIsNotInEnum_ShouldHaveValidationError()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(taskType: (ScheduledTaskType)999);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Scheduling.InvalidScheduleType);
}
[Fact]
public void Validate_WhenScheduleTypeIsNotInEnum_ShouldHaveValidationError()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(scheduleType: (ScheduleType)999);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Scheduling.InvalidScheduleType);
}
[Fact]
public void Validate_WhenIntervalScheduleHasNullInterval_ShouldHaveValidationError()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(scheduleType: ScheduleType.WithIntervalInMinutes) with { IntervalMinutes = null };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Scheduling.IntervalMinutesMustBePositive);
}
[Theory]
[InlineData(0)] // interval of zero
[InlineData(-1)] // negative interval
public void Validate_WhenIntervalScheduleHasNonPositiveInterval_ShouldHaveValidationError(int intervalMinutes)
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(
scheduleType: ScheduleType.WithIntervalInMinutes,
intervalMinutes: intervalMinutes);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Scheduling.IntervalMinutesMustBePositive);
}
[Fact]
public void Validate_WhenDailyScheduleHasNullHour_ShouldHaveValidationError()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(scheduleType: ScheduleType.DailyAtHourAndMinute) with { Hour = null };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Scheduling.HourMustBeBetweenZeroAndTwentyThree);
}
[Fact]
public void Validate_WhenDailyScheduleHasNullMinute_ShouldHaveValidationError()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(scheduleType: ScheduleType.DailyAtHourAndMinute) with { Minute = null };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Scheduling.MinuteMustBeBetweenZeroAndFiftyNine);
}
[Theory]
[InlineData(-1)] // hour below the allowed range
[InlineData(24)] // hour above the allowed range
public void Validate_WhenDailyScheduleHasOutOfRangeHour_ShouldHaveValidationError(int hour)
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(
scheduleType: ScheduleType.DailyAtHourAndMinute,
hour: hour,
minute: 0);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Scheduling.HourMustBeBetweenZeroAndTwentyThree);
}
[Theory]
[InlineData(-1)] // minute below the allowed range
[InlineData(60)] // minute above the allowed range
public void Validate_WhenDailyScheduleHasOutOfRangeMinute_ShouldHaveValidationError(int minute)
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(
scheduleType: ScheduleType.DailyAtHourAndMinute,
hour: 12,
minute: minute);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Scheduling.MinuteMustBeBetweenZeroAndFiftyNine);
}
[Fact]
public void Validate_WhenCommandIsValidWithIntervalSchedule_ShouldNotHaveAnyValidationError()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(scheduleType: ScheduleType.WithIntervalInMinutes);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
[Fact]
public void Validate_WhenCommandIsValidWithDailySchedule_ShouldNotHaveAnyValidationError()
{
// Arrange
AddScheduledJobCommand command = _addScheduledJobCommandFixture.Create(scheduleType: ScheduleType.DailyAtHourAndMinute);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -0,0 +1,213 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DomainEvents;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.Scheduling.Commands.FireScheduledJob;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Fixtures.Core.Scheduling.Commands.FireScheduledJob;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Commands.FireScheduledJob;
/// <summary>
/// Contains unit tests for the <see cref="FireScheduledJobCommandHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class FireScheduledJobCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly IDomainEventsQueue _mockDomainEventsQueue;
private readonly IScheduledJobRepository _mockScheduledJobRepository;
private readonly IValidator<FireScheduledJobCommand> _mockValidator;
private readonly FireScheduledJobCommandHandler _sut;
private readonly FireScheduledJobCommandFixture _fireScheduledJobCommandFixture = new();
private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new();
private readonly Guid _userId = Guid.NewGuid();
/// <summary>
/// Initializes a new instance of the <see cref="FireScheduledJobCommandHandlerTests"/> class.
/// </summary>
public FireScheduledJobCommandHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockDomainEventsQueue = Substitute.For<IDomainEventsQueue>();
_mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
_mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository);
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(true);
_mockValidator = Substitute.For<IValidator<FireScheduledJobCommand>>();
_mockValidator.Validate(Arg.Any<FireScheduledJobCommand>()).Returns([]);
_sut = new FireScheduledJobCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockDomainEventsQueue, _mockUnitOfWork, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenScheduledJobIsAdded_ShouldEnqueueFiredEventAndReturnResponse()
{
// Arrange
FireScheduledJobCommand command = _fireScheduledJobCommandFixture.Create();
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(
id: command.ScheduledJobId,
scheduleType: ScheduleType.WithIntervalInMinutes,
status: ScheduledJobStatus.Active);
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(scheduledJob.Name, result.Value.Name);
_mockDomainEventsQueue.Received(1).Enqueue(Arg.Is<IDomainEvent>(domainEvent => domainEvent is ScheduledJobFiredDomainEvent));
await _mockScheduledJobRepository.DidNotReceive().UpdateAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenValidatorReturnsError_ShouldReturnValidationErrorAndNotQueueEvent()
{
// Arrange
FireScheduledJobCommand command = _fireScheduledJobCommandFixture.Create();
_mockValidator.Validate(Arg.Any<FireScheduledJobCommand>()).Returns([DomainErrors.Scheduling.ScheduledJobNotFound]);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
}
[Fact]
public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorized()
{
// Arrange
FireScheduledJobCommand command = _fireScheduledJobCommandFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// 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_WhenUserIsNotAdministrator_ShouldReturnNotAuthorized()
{
// Arrange
FireScheduledJobCommand command = _fireScheduledJobCommandFixture.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_WhenGetByIdReturnsError_ShouldReturnError()
{
// Arrange
FireScheduledJobCommand command = _fireScheduledJobCommandFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to get the scheduled job");
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>()).Returns(error);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
}
[Fact]
public async Task HandleAsync_WhenScheduledJobDoesNotExist_ShouldReturnNotFound()
{
// Arrange
FireScheduledJobCommand command = _fireScheduledJobCommandFixture.Create();
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(null));
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError);
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
}
[Fact]
public async Task HandleAsync_WhenToDomainEntityFails_ShouldReturnError()
{
// Arrange
FireScheduledJobCommand command = _fireScheduledJobCommandFixture.Create();
// A daily scheduled job with an out of range hour cannot convert to its domain aggregate.
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(
id: command.ScheduledJobId,
scheduleType: ScheduleType.DailyAtHourAndMinute,
hour: 99,
minute: 0);
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
}
[Fact]
public async Task HandleAsync_WhenScheduledJobIsRunning_ShouldReturnAlreadyRunningError()
{
// Arrange
FireScheduledJobCommand command = _fireScheduledJobCommandFixture.Create();
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(
id: command.ScheduledJobId,
scheduleType: ScheduleType.WithIntervalInMinutes,
status: ScheduledJobStatus.Running);
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.ScheduledJobAlreadyRunning, result.FirstError);
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
}
}
@@ -0,0 +1,48 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Scheduling.Commands.FireScheduledJob;
using Lumina.Application.Fixtures.Core.Scheduling.Commands.FireScheduledJob;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Commands.FireScheduledJob;
/// <summary>
/// Contains unit tests for the <see cref="FireScheduledJobCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class FireScheduledJobCommandValidatorTests
{
private readonly FireScheduledJobCommandValidator _validator = new();
private readonly FireScheduledJobCommandFixture _fireScheduledJobCommandFixture = new();
[Fact]
public void Validate_WhenScheduledJobIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
FireScheduledJobCommand command = _fireScheduledJobCommandFixture.Create() with { ScheduledJobId = Guid.Empty };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Scheduling.ScheduledJobNotFound);
}
[Fact]
public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationError()
{
// Arrange
FireScheduledJobCommand command = _fireScheduledJobCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -0,0 +1,219 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DomainEvents;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Scheduling;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.Scheduling.Commands.RemoveScheduledJob;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Fixtures.Core.Scheduling.Commands.RemoveScheduledJob;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
using ScheduledJobId = Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects.ScheduledJobId;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Commands.RemoveScheduledJob;
/// <summary>
/// Contains unit tests for the <see cref="RemoveScheduledJobCommandHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RemoveScheduledJobCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly IDomainEventsQueue _mockDomainEventsQueue;
private readonly IScheduledJobScheduler _mockScheduledJobScheduler;
private readonly IScheduledJobRepository _mockScheduledJobRepository;
private readonly IScheduledJobExecutionRepository _mockScheduledJobExecutionRepository;
private readonly IValidator<RemoveScheduledJobCommand> _mockValidator;
private readonly RemoveScheduledJobCommandHandler _sut;
private readonly RemoveScheduledJobCommandFixture _removeScheduledJobCommandFixture = new();
private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new();
private readonly Guid _userId = Guid.NewGuid();
/// <summary>
/// Initializes a new instance of the <see cref="RemoveScheduledJobCommandHandlerTests"/> class.
/// </summary>
public RemoveScheduledJobCommandHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockDomainEventsQueue = Substitute.For<IDomainEventsQueue>();
_mockScheduledJobScheduler = Substitute.For<IScheduledJobScheduler>();
_mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
_mockScheduledJobExecutionRepository = Substitute.For<IScheduledJobExecutionRepository>();
_mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository);
_mockUnitOfWork.ScheduledJobExecutionRepository.Returns(_mockScheduledJobExecutionRepository);
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(true);
_mockValidator = Substitute.For<IValidator<RemoveScheduledJobCommand>>();
_mockValidator.Validate(Arg.Any<RemoveScheduledJobCommand>()).Returns([]);
_sut = new RemoveScheduledJobCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockDomainEventsQueue, _mockScheduledJobScheduler, _mockUnitOfWork, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenScheduledJobExists_ShouldDeleteItAndEnqueueRemovedEvent()
{
// Arrange
RemoveScheduledJobCommand command = _removeScheduledJobCommandFixture.Create();
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(
id: command.ScheduledJobId,
scheduleType: ScheduleType.WithIntervalInMinutes,
status: ScheduledJobStatus.Active);
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
_mockScheduledJobExecutionRepository.DeleteByScheduledJobIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.Success);
_mockScheduledJobRepository.DeleteByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Success, result.Value);
await _mockScheduledJobScheduler.Received(1).StopCycleAsync(
Arg.Is<ScheduledJobId>(scheduledJobId => scheduledJobId.Value == command.ScheduledJobId),
Arg.Any<CancellationToken>());
await _mockScheduledJobExecutionRepository.Received(1).DeleteByScheduledJobIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>());
await _mockScheduledJobRepository.Received(1).DeleteByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
_mockDomainEventsQueue.Received(1).Enqueue(Arg.Is<IDomainEvent>(domainEvent => domainEvent is ScheduledJobRemovedDomainEvent));
}
[Fact]
public async Task HandleAsync_WhenValidatorReturnsError_ShouldReturnValidationErrorAndNotDelete()
{
// Arrange
RemoveScheduledJobCommand command = _removeScheduledJobCommandFixture.Create();
_mockValidator.Validate(Arg.Any<RemoveScheduledJobCommand>()).Returns([DomainErrors.Scheduling.ScheduledJobNotFound]);
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockScheduledJobRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorized()
{
// Arrange
RemoveScheduledJobCommand command = _removeScheduledJobCommandFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<Success> 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_WhenUserIsNotAdministrator_ShouldReturnNotAuthorized()
{
// Arrange
RemoveScheduledJobCommand command = _removeScheduledJobCommandFixture.Create();
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(false);
// Act
Result<Success> 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()
{
// Arrange
RemoveScheduledJobCommand command = _removeScheduledJobCommandFixture.Create();
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(null));
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError);
await _mockScheduledJobScheduler.DidNotReceive().StopCycleAsync(Arg.Any<ScheduledJobId>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenDeleteExecutionsFails_ShouldReturnErrorAndNotDeleteScheduledJob()
{
// Arrange
RemoveScheduledJobCommand command = _removeScheduledJobCommandFixture.Create();
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(
id: command.ScheduledJobId,
scheduleType: ScheduleType.WithIntervalInMinutes,
status: ScheduledJobStatus.Active);
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
Error error = Error.Failure("Database.Error", "Failed to delete the executions");
_mockScheduledJobExecutionRepository.DeleteByScheduledJobIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenDeleteScheduledJobFails_ShouldReturnErrorAndNotSaveChanges()
{
// Arrange
RemoveScheduledJobCommand command = _removeScheduledJobCommandFixture.Create();
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(
id: command.ScheduledJobId,
scheduleType: ScheduleType.WithIntervalInMinutes,
status: ScheduledJobStatus.Active);
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
_mockScheduledJobExecutionRepository.DeleteByScheduledJobIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.Success);
_mockScheduledJobRepository.DeleteByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(DomainErrors.Scheduling.ScheduledJobNotFound);
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
}
}
@@ -0,0 +1,48 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Scheduling.Commands.RemoveScheduledJob;
using Lumina.Application.Fixtures.Core.Scheduling.Commands.RemoveScheduledJob;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Commands.RemoveScheduledJob;
/// <summary>
/// Contains unit tests for the <see cref="RemoveScheduledJobCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RemoveScheduledJobCommandValidatorTests
{
private readonly RemoveScheduledJobCommandValidator _validator = new();
private readonly RemoveScheduledJobCommandFixture _removeScheduledJobCommandFixture = new();
[Fact]
public void Validate_WhenScheduledJobIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
RemoveScheduledJobCommand command = _removeScheduledJobCommandFixture.Create() with { ScheduledJobId = Guid.Empty };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Scheduling.ScheduledJobNotFound);
}
[Fact]
public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationError()
{
// Arrange
RemoveScheduledJobCommand command = _removeScheduledJobCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -0,0 +1,203 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DomainEvents;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.Scheduling.Commands.StartScheduledJob;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Fixtures.Core.Scheduling.Commands.StartScheduledJob;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Commands.StartScheduledJob;
/// <summary>
/// Contains unit tests for the <see cref="StartScheduledJobCommandHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class StartScheduledJobCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly IDomainEventsQueue _mockDomainEventsQueue;
private readonly IScheduledJobRepository _mockScheduledJobRepository;
private readonly IValidator<StartScheduledJobCommand> _mockValidator;
private readonly StartScheduledJobCommandHandler _sut;
private readonly StartScheduledJobCommandFixture _startScheduledJobCommandFixture = new();
private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new();
private readonly Guid _userId = Guid.NewGuid();
/// <summary>
/// Initializes a new instance of the <see cref="StartScheduledJobCommandHandlerTests"/> class.
/// </summary>
public StartScheduledJobCommandHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockDomainEventsQueue = Substitute.For<IDomainEventsQueue>();
_mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
_mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository);
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(true);
_mockValidator = Substitute.For<IValidator<StartScheduledJobCommand>>();
_mockValidator.Validate(Arg.Any<StartScheduledJobCommand>()).Returns([]);
_sut = new StartScheduledJobCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockDomainEventsQueue, _mockUnitOfWork, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenScheduledJobIsAdded_ShouldUpdateToActiveAndEnqueueCycleStartedEvent()
{
// Arrange
StartScheduledJobCommand command = _startScheduledJobCommandFixture.Create();
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(
id: command.ScheduledJobId,
scheduleType: ScheduleType.WithIntervalInMinutes,
status: ScheduledJobStatus.Added);
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
_mockScheduledJobRepository.UpdateAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>()).Returns(Result.Updated);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(ScheduledJobStatus.Active, result.Value.Status);
await _mockScheduledJobRepository.Received(1).UpdateAsync(
Arg.Is<ScheduledJobEntity>(updatedScheduledJob => updatedScheduledJob.Status == ScheduledJobStatus.Active),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
_mockDomainEventsQueue.Received(1).Enqueue(Arg.Is<IDomainEvent>(domainEvent => domainEvent is ScheduledJobCycleStartedDomainEvent));
}
[Fact]
public async Task HandleAsync_WhenValidatorReturnsError_ShouldReturnValidationErrorAndNotPersist()
{
// Arrange
StartScheduledJobCommand command = _startScheduledJobCommandFixture.Create();
_mockValidator.Validate(Arg.Any<StartScheduledJobCommand>()).Returns([DomainErrors.Scheduling.ScheduledJobNotFound]);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorized()
{
// Arrange
StartScheduledJobCommand command = _startScheduledJobCommandFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// 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_WhenUserIsNotAdministrator_ShouldReturnNotAuthorized()
{
// Arrange
StartScheduledJobCommand command = _startScheduledJobCommandFixture.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()
{
// Arrange
StartScheduledJobCommand command = _startScheduledJobCommandFixture.Create();
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(null));
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().UpdateAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenScheduledJobCycleAlreadyStarted_ShouldReturnCycleAlreadyStartedError()
{
// Arrange
StartScheduledJobCommand command = _startScheduledJobCommandFixture.Create();
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(
id: command.ScheduledJobId,
scheduleType: ScheduleType.WithIntervalInMinutes,
status: ScheduledJobStatus.Active);
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.ScheduledJobCycleAlreadyStarted, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().UpdateAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>());
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
}
[Fact]
public async Task HandleAsync_WhenUpdateFails_ShouldReturnErrorAndNotSaveChanges()
{
// Arrange
StartScheduledJobCommand command = _startScheduledJobCommandFixture.Create();
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(
id: command.ScheduledJobId,
scheduleType: ScheduleType.WithIntervalInMinutes,
status: ScheduledJobStatus.Added);
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
_mockScheduledJobRepository.UpdateAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>())
.Returns(DomainErrors.Scheduling.ScheduledJobNotFound);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
}
}
@@ -0,0 +1,48 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Scheduling.Commands.StartScheduledJob;
using Lumina.Application.Fixtures.Core.Scheduling.Commands.StartScheduledJob;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Commands.StartScheduledJob;
/// <summary>
/// Contains unit tests for the <see cref="StartScheduledJobCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class StartScheduledJobCommandValidatorTests
{
private readonly StartScheduledJobCommandValidator _validator = new();
private readonly StartScheduledJobCommandFixture _startScheduledJobCommandFixture = new();
[Fact]
public void Validate_WhenScheduledJobIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
StartScheduledJobCommand command = _startScheduledJobCommandFixture.Create() with { ScheduledJobId = Guid.Empty };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Scheduling.ScheduledJobNotFound);
}
[Fact]
public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationError()
{
// Arrange
StartScheduledJobCommand command = _startScheduledJobCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -0,0 +1,217 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DomainEvents;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Scheduling;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.Scheduling.Commands.StopScheduledJob;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Fixtures.Core.Scheduling.Commands.StopScheduledJob;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Commands.StopScheduledJob;
/// <summary>
/// Contains unit tests for the <see cref="StopScheduledJobCommandHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class StopScheduledJobCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly IDomainEventsQueue _mockDomainEventsQueue;
private readonly IScheduledJobScheduler _mockScheduledJobScheduler;
private readonly IScheduledJobRepository _mockScheduledJobRepository;
private readonly IValidator<StopScheduledJobCommand> _mockValidator;
private readonly StopScheduledJobCommandHandler _sut;
private readonly StopScheduledJobCommandFixture _stopScheduledJobCommandFixture = new();
private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new();
private readonly Guid _userId = Guid.NewGuid();
/// <summary>
/// Initializes a new instance of the <see cref="StopScheduledJobCommandHandlerTests"/> class.
/// </summary>
public StopScheduledJobCommandHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockDomainEventsQueue = Substitute.For<IDomainEventsQueue>();
_mockScheduledJobScheduler = Substitute.For<IScheduledJobScheduler>();
_mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
_mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository);
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(true);
_mockValidator = Substitute.For<IValidator<StopScheduledJobCommand>>();
_mockValidator.Validate(Arg.Any<StopScheduledJobCommand>()).Returns([]);
_sut = new StopScheduledJobCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockDomainEventsQueue, _mockScheduledJobScheduler, _mockUnitOfWork, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenScheduledJobIsActive_ShouldUpdateToAddedAndStopCycleInScheduler()
{
// Arrange
StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create();
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(
id: command.ScheduledJobId,
scheduleType: ScheduleType.WithIntervalInMinutes,
status: ScheduledJobStatus.Active);
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
_mockScheduledJobRepository.UpdateAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>()).Returns(Result.Updated);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(ScheduledJobStatus.Added, result.Value.Status);
await _mockScheduledJobRepository.Received(1).UpdateAsync(
Arg.Is<ScheduledJobEntity>(updatedScheduledJob => updatedScheduledJob.Status == ScheduledJobStatus.Added),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockScheduledJobScheduler.Received(1).StopCycleAsync(
Arg.Is<Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects.ScheduledJobId>(scheduledJobId => scheduledJobId.Value == command.ScheduledJobId),
Arg.Any<CancellationToken>());
_mockDomainEventsQueue.Received(1).Enqueue(Arg.Is<IDomainEvent>(domainEvent => domainEvent is ScheduledJobCycleStoppedDomainEvent));
}
[Fact]
public async Task HandleAsync_WhenScheduledJobIsRunning_ShouldEnqueueExecutionStoppedEvent()
{
// Arrange
StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create();
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(
id: command.ScheduledJobId,
scheduleType: ScheduleType.WithIntervalInMinutes,
status: ScheduledJobStatus.Running,
lastStartedOnUtc: DateTime.UtcNow.AddMinutes(-10));
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
_mockScheduledJobRepository.UpdateAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>()).Returns(Result.Updated);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(ScheduledJobStatus.Added, result.Value.Status);
_mockDomainEventsQueue.Received(1).Enqueue(Arg.Is<IDomainEvent>(domainEvent => domainEvent is ScheduledJobExecutionStoppedDomainEvent));
await _mockScheduledJobScheduler.Received(1).StopCycleAsync(Arg.Any<Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects.ScheduledJobId>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenValidatorReturnsError_ShouldReturnValidationErrorAndNotPersist()
{
// Arrange
StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create();
_mockValidator.Validate(Arg.Any<StopScheduledJobCommand>()).Returns([DomainErrors.Scheduling.ScheduledJobNotFound]);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), 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_WhenCurrentUserIsNull_ShouldReturnNotAuthorized()
{
// Arrange
StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// 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()
{
// Arrange
StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create();
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(null));
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError);
await _mockScheduledJobScheduler.DidNotReceive().StopCycleAsync(Arg.Any<Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects.ScheduledJobId>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenScheduledJobCycleWasNeverStarted_ShouldReturnNotStartedError()
{
// Arrange
StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create();
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(
id: command.ScheduledJobId,
scheduleType: ScheduleType.WithIntervalInMinutes,
status: ScheduledJobStatus.Added);
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotStarted, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().UpdateAsync(Arg.Any<ScheduledJobEntity>(), 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_WhenUpdateFails_ShouldReturnErrorAndNotStopCycleInScheduler()
{
// Arrange
StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create();
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(
id: command.ScheduledJobId,
scheduleType: ScheduleType.WithIntervalInMinutes,
status: ScheduledJobStatus.Active);
_mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
_mockScheduledJobRepository.UpdateAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>())
.Returns(DomainErrors.Scheduling.ScheduledJobNotFound);
// Act
Result<ScheduledJobResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, 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>());
}
}
@@ -0,0 +1,48 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Scheduling.Commands.StopScheduledJob;
using Lumina.Application.Fixtures.Core.Scheduling.Commands.StopScheduledJob;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Commands.StopScheduledJob;
/// <summary>
/// Contains unit tests for the <see cref="StopScheduledJobCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class StopScheduledJobCommandValidatorTests
{
private readonly StopScheduledJobCommandValidator _validator = new();
private readonly StopScheduledJobCommandFixture _stopScheduledJobCommandFixture = new();
[Fact]
public void Validate_WhenScheduledJobIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create() with { ScheduledJobId = Guid.Empty };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Scheduling.ScheduledJobNotFound);
}
[Fact]
public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationError()
{
// Arrange
StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -0,0 +1,152 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.Scheduling.Commands.UpdateSchedulerDisplayPreferences;
using Lumina.Application.Fixtures.Core.Scheduling.Commands.UpdateSchedulerDisplayPreferences;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Commands.UpdateSchedulerDisplayPreferences;
/// <summary>
/// Contains unit tests for the <see cref="UpdateSchedulerDisplayPreferencesCommandHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateSchedulerDisplayPreferencesCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ISchedulerDisplayPreferencesRepository _mockSchedulerDisplayPreferencesRepository;
private readonly IValidator<UpdateSchedulerDisplayPreferencesCommand> _mockValidator;
private readonly UpdateSchedulerDisplayPreferencesCommandHandler _sut;
private readonly UpdateSchedulerDisplayPreferencesCommandFixture _updateSchedulerDisplayPreferencesCommandFixture = new();
private readonly Guid _userId = Guid.NewGuid();
/// <summary>
/// Initializes a new instance of the <see cref="UpdateSchedulerDisplayPreferencesCommandHandlerTests"/> class.
/// </summary>
public UpdateSchedulerDisplayPreferencesCommandHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockSchedulerDisplayPreferencesRepository = Substitute.For<ISchedulerDisplayPreferencesRepository>();
_mockUnitOfWork.SchedulerDisplayPreferencesRepository.Returns(_mockSchedulerDisplayPreferencesRepository);
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(true);
_mockValidator = Substitute.For<IValidator<UpdateSchedulerDisplayPreferencesCommand>>();
_mockValidator.Validate(Arg.Any<UpdateSchedulerDisplayPreferencesCommand>()).Returns([]);
_sut = new UpdateSchedulerDisplayPreferencesCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenCommandIsValid_ShouldUpsertDisplayPreferencesAndReturnUpdated()
{
// Arrange
UpdateSchedulerDisplayPreferencesCommand command = _updateSchedulerDisplayPreferencesCommandFixture.Create(
jobTypeFilter: ScheduledTaskType.ScanMediaLibraries,
displayTimeSpan: 30,
displayTimeUnit: SchedulerDisplayTimeUnit.Minutes);
_mockSchedulerDisplayPreferencesRepository.UpsertAsync(Arg.Any<SchedulerDisplayPreferencesEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
await _mockSchedulerDisplayPreferencesRepository.Received(1).UpsertAsync(
Arg.Is<SchedulerDisplayPreferencesEntity>(preferences =>
preferences.UserId == _userId &&
preferences.JobTypeFilter == ScheduledTaskType.ScanMediaLibraries &&
preferences.DisplayTimeSpan == 30 &&
preferences.DisplayTimeUnit == SchedulerDisplayTimeUnit.Minutes),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenValidatorReturnsError_ShouldReturnValidationErrorAndNotPersist()
{
// Arrange
UpdateSchedulerDisplayPreferencesCommand command = _updateSchedulerDisplayPreferencesCommandFixture.Create(displayTimeSpan: 0);
_mockValidator.Validate(Arg.Any<UpdateSchedulerDisplayPreferencesCommand>())
.Returns([DomainErrors.Scheduling.SchedulerDisplayTimeSpanMustBePositive]);
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Scheduling.SchedulerDisplayTimeSpanMustBePositive, result.FirstError);
await _mockSchedulerDisplayPreferencesRepository.DidNotReceive().UpsertAsync(Arg.Any<SchedulerDisplayPreferencesEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorized()
{
// Arrange
UpdateSchedulerDisplayPreferencesCommand command = _updateSchedulerDisplayPreferencesCommandFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockSchedulerDisplayPreferencesRepository.DidNotReceive().UpsertAsync(Arg.Any<SchedulerDisplayPreferencesEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAdministrator_ShouldReturnNotAuthorized()
{
// Arrange
UpdateSchedulerDisplayPreferencesCommand command = _updateSchedulerDisplayPreferencesCommandFixture.Create();
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(false);
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockSchedulerDisplayPreferencesRepository.DidNotReceive().UpsertAsync(Arg.Any<SchedulerDisplayPreferencesEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUpsertFails_ShouldReturnErrorAndNotSaveChanges()
{
// Arrange
UpdateSchedulerDisplayPreferencesCommand command = _updateSchedulerDisplayPreferencesCommandFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to upsert the display preferences");
_mockSchedulerDisplayPreferencesRepository.UpsertAsync(Arg.Any<SchedulerDisplayPreferencesEntity>(), Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,66 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Scheduling.Commands.UpdateSchedulerDisplayPreferences;
using Lumina.Application.Fixtures.Core.Scheduling.Commands.UpdateSchedulerDisplayPreferences;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Commands.UpdateSchedulerDisplayPreferences;
/// <summary>
/// Contains unit tests for the <see cref="UpdateSchedulerDisplayPreferencesCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateSchedulerDisplayPreferencesCommandValidatorTests
{
private readonly UpdateSchedulerDisplayPreferencesCommandValidator _validator = new();
private readonly UpdateSchedulerDisplayPreferencesCommandFixture _updateSchedulerDisplayPreferencesCommandFixture = new();
[Theory]
[InlineData(0)] // display time span of zero
[InlineData(-1)] // negative display time span
[InlineData(-100)] // negative display time span far from zero
public void Validate_WhenDisplayTimeSpanIsNotPositive_ShouldHaveValidationError(int displayTimeSpan)
{
// Arrange
UpdateSchedulerDisplayPreferencesCommand command = _updateSchedulerDisplayPreferencesCommandFixture.Create(displayTimeSpan: displayTimeSpan);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Scheduling.SchedulerDisplayTimeSpanMustBePositive);
}
[Theory]
[InlineData(1)] // minimal positive display time span
[InlineData(10)] // default display time span
[InlineData(1440)] // a day expressed in minutes
public void Validate_WhenDisplayTimeSpanIsPositive_ShouldNotHaveValidationError(int displayTimeSpan)
{
// Arrange
UpdateSchedulerDisplayPreferencesCommand command = _updateSchedulerDisplayPreferencesCommandFixture.Create(displayTimeSpan: displayTimeSpan);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Scheduling.SchedulerDisplayTimeSpanMustBePositive);
}
[Fact]
public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationError()
{
// Arrange
UpdateSchedulerDisplayPreferencesCommand command = _updateSchedulerDisplayPreferencesCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -0,0 +1,86 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Core.Scheduling.Events;
using Lumina.Application.Core.Scheduling.Notifications;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.Common.Exceptions;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
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.Application.UnitTests.Core.Scheduling.Events;
/// <summary>
/// Contains unit tests for the <see cref="ScheduledJobAddedDomainEventHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScheduledJobAddedDomainEventHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IScheduledJobNotifier _mockScheduledJobNotifier;
private readonly IScheduledJobRepository _mockScheduledJobRepository;
private readonly ScheduledJobAddedDomainEventHandler _sut;
private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new();
private readonly ScheduledJobAddedDomainEventFixture _scheduledJobAddedDomainEventFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledJobAddedDomainEventHandlerTests"/> class.
/// </summary>
public ScheduledJobAddedDomainEventHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockScheduledJobNotifier = Substitute.For<IScheduledJobNotifier>();
_mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
_mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository);
_mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ScheduledJobEntity>>([]));
_sut = new ScheduledJobAddedDomainEventHandler(_mockScheduledJobNotifier, _mockUnitOfWork);
}
[Fact]
public async Task HandleAsync_WhenScheduledJobsAreLoaded_ShouldNotifyTheCurrentScheduledJobs()
{
// Arrange
ScheduledJobAddedDomainEvent domainEvent = _scheduledJobAddedDomainEventFixture.Create();
ScheduledJobEntity scheduledJob1 = _scheduledJobEntityFixture.Create(name: "Job 1");
ScheduledJobEntity scheduledJob2 = _scheduledJobEntityFixture.Create(name: "Job 2");
_mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ScheduledJobEntity>>([scheduledJob1, scheduledJob2]));
// Act
await _sut.HandleAsync(domainEvent, CancellationToken.None);
// Assert
await _mockScheduledJobNotifier.Received(1).SendScheduledJobsAsync(
Arg.Is<IReadOnlyList<ScheduledJobResponse>>(scheduledJobs => scheduledJobs.Count == 2),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetAllScheduledJobsFails_ShouldThrowEventualConsistencyException()
{
// Arrange
ScheduledJobAddedDomainEvent domainEvent = _scheduledJobAddedDomainEventFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to get the scheduled jobs");
_mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(error);
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
await _mockScheduledJobNotifier.DidNotReceive().SendScheduledJobsAsync(Arg.Any<IReadOnlyList<ScheduledJobResponse>>(), Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,82 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Scheduling;
using Lumina.Application.Core.Scheduling.Events;
using Lumina.Application.Core.Scheduling.Notifications;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.Common.Exceptions;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Events;
/// <summary>
/// Contains unit tests for the <see cref="ScheduledJobCycleStartedDomainEventHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScheduledJobCycleStartedDomainEventHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IScheduledJobNotifier _mockScheduledJobNotifier;
private readonly IScheduledJobScheduler _mockScheduledJobScheduler;
private readonly IScheduledJobRepository _mockScheduledJobRepository;
private readonly ScheduledJobCycleStartedDomainEventHandler _sut;
private readonly ScheduledJobCycleStartedDomainEventFixture _scheduledJobCycleStartedDomainEventFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledJobCycleStartedDomainEventHandlerTests"/> class.
/// </summary>
public ScheduledJobCycleStartedDomainEventHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockScheduledJobNotifier = Substitute.For<IScheduledJobNotifier>();
_mockScheduledJobScheduler = Substitute.For<IScheduledJobScheduler>();
_mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
_mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository);
_mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ScheduledJobEntity>>([]));
_sut = new ScheduledJobCycleStartedDomainEventHandler(_mockScheduledJobNotifier, _mockScheduledJobScheduler, _mockUnitOfWork);
}
[Fact]
public async Task HandleAsync_WhenScheduledJobsAreLoaded_ShouldStartTheCycleInTheSchedulerAndNotify()
{
// Arrange
ScheduledJobCycleStartedDomainEvent domainEvent = _scheduledJobCycleStartedDomainEventFixture.Create();
// Act
await _sut.HandleAsync(domainEvent, CancellationToken.None);
// Assert
await _mockScheduledJobScheduler.Received(1).StartCycleAsync(domainEvent.ScheduledJobId, Arg.Any<CancellationToken>());
await _mockScheduledJobNotifier.Received(1).SendScheduledJobsAsync(Arg.Any<IReadOnlyList<ScheduledJobResponse>>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetAllScheduledJobsFails_ShouldThrowEventualConsistencyException()
{
// Arrange
ScheduledJobCycleStartedDomainEvent domainEvent = _scheduledJobCycleStartedDomainEventFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to get the scheduled jobs");
_mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(error);
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
await _mockScheduledJobNotifier.DidNotReceive().SendScheduledJobsAsync(Arg.Any<IReadOnlyList<ScheduledJobResponse>>(), Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,84 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Core.Scheduling.Events;
using Lumina.Application.Core.Scheduling.Notifications;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.Common.Exceptions;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Events;
/// <summary>
/// Contains unit tests for the <see cref="ScheduledJobCycleStoppedDomainEventHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScheduledJobCycleStoppedDomainEventHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IScheduledJobNotifier _mockScheduledJobNotifier;
private readonly IScheduledJobRepository _mockScheduledJobRepository;
private readonly ScheduledJobCycleStoppedDomainEventHandler _sut;
private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new();
private readonly ScheduledJobCycleStoppedDomainEventFixture _scheduledJobCycleStoppedDomainEventFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledJobCycleStoppedDomainEventHandlerTests"/> class.
/// </summary>
public ScheduledJobCycleStoppedDomainEventHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockScheduledJobNotifier = Substitute.For<IScheduledJobNotifier>();
_mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
_mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository);
_mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ScheduledJobEntity>>([]));
_sut = new ScheduledJobCycleStoppedDomainEventHandler(_mockScheduledJobNotifier, _mockUnitOfWork);
}
[Fact]
public async Task HandleAsync_WhenScheduledJobsAreLoaded_ShouldNotifyTheCurrentScheduledJobs()
{
// Arrange
ScheduledJobCycleStoppedDomainEvent domainEvent = _scheduledJobCycleStoppedDomainEventFixture.Create();
ScheduledJobEntity stoppedJob = _scheduledJobEntityFixture.Create(name: "Stopped job", status: Lumina.Domain.SharedKernel.Common.Enums.Scheduling.ScheduledJobStatus.Added);
_mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ScheduledJobEntity>>([stoppedJob]));
// Act
await _sut.HandleAsync(domainEvent, CancellationToken.None);
// Assert
await _mockScheduledJobNotifier.Received(1).SendScheduledJobsAsync(
Arg.Is<IReadOnlyList<ScheduledJobResponse>>(scheduledJobs => scheduledJobs.Count == 1),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetAllScheduledJobsFails_ShouldThrowEventualConsistencyException()
{
// Arrange
ScheduledJobCycleStoppedDomainEvent domainEvent = _scheduledJobCycleStoppedDomainEventFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to get the scheduled jobs");
_mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(error);
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
await _mockScheduledJobNotifier.DidNotReceive().SendScheduledJobsAsync(Arg.Any<IReadOnlyList<ScheduledJobResponse>>(), Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,200 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Core.Scheduling.Events;
using Lumina.Application.Core.Scheduling.Notifications;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Exceptions;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Events;
/// <summary>
/// Contains unit tests for the <see cref="ScheduledJobExecutionCompletedDomainEventHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScheduledJobExecutionCompletedDomainEventHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IScheduledJobNotifier _mockScheduledJobNotifier;
private readonly IScheduledJobRepository _mockScheduledJobRepository;
private readonly IScheduledJobExecutionRepository _mockScheduledJobExecutionRepository;
private readonly ScheduledJobExecutionCompletedDomainEventHandler _sut;
private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new();
private readonly ScheduledJobExecutionEntityFixture _scheduledJobExecutionEntityFixture = new();
private readonly ScheduledJobExecutionCompletedDomainEventFixture _scheduledJobExecutionCompletedDomainEventFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledJobExecutionCompletedDomainEventHandlerTests"/> class.
/// </summary>
public ScheduledJobExecutionCompletedDomainEventHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockScheduledJobNotifier = Substitute.For<IScheduledJobNotifier>();
_mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
_mockScheduledJobExecutionRepository = Substitute.For<IScheduledJobExecutionRepository>();
_mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository);
_mockUnitOfWork.ScheduledJobExecutionRepository.Returns(_mockScheduledJobExecutionRepository);
_mockScheduledJobRepository.UpdateAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>()).Returns(Result.Updated);
_mockScheduledJobExecutionRepository.UpdateAsync(Arg.Any<ScheduledJobExecutionEntity>(), Arg.Any<CancellationToken>()).Returns(Result.Updated);
_mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ScheduledJobEntity>>([]));
_sut = new ScheduledJobExecutionCompletedDomainEventHandler(_mockScheduledJobNotifier, _mockUnitOfWork);
}
[Theory]
[InlineData(true, ScheduledJobStatus.Active)] // a cycle run returns the scheduled job to its active status
[InlineData(false, ScheduledJobStatus.Completed)] // a one time execution completes the scheduled job
public async Task HandleAsync_WhenScheduledJobAndExecutionExist_ShouldUpdateBothAndNotify(bool isCycleRun, ScheduledJobStatus expectedStatus)
{
// Arrange
DateTime completedOnUtc = DateTime.UtcNow;
ScheduledJobExecutionCompletedDomainEvent domainEvent = _scheduledJobExecutionCompletedDomainEventFixture.Create(isCycleRun: isCycleRun, completedOnUtc: completedOnUtc);
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(
id: domainEvent.ScheduledJobId.Value,
status: ScheduledJobStatus.Running,
lastStartedOnUtc: completedOnUtc.AddMinutes(-5));
_mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
ScheduledJobExecutionEntity execution = _scheduledJobExecutionEntityFixture.Create(
id: domainEvent.RunId,
scheduledJobId: scheduledJob.Id,
isCycleRun: isCycleRun,
completedOnUtc: null);
_mockScheduledJobExecutionRepository.GetByIdAsync(domainEvent.RunId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobExecutionEntity?>(execution));
// Act
await _sut.HandleAsync(domainEvent, CancellationToken.None);
// Assert
await _mockScheduledJobRepository.Received(1).UpdateAsync(
Arg.Is<ScheduledJobEntity>(updatedScheduledJob =>
updatedScheduledJob.Status == expectedStatus &&
updatedScheduledJob.LastCompletedOnUtc == completedOnUtc),
Arg.Any<CancellationToken>());
await _mockScheduledJobExecutionRepository.Received(1).UpdateAsync(
Arg.Is<ScheduledJobExecutionEntity>(updatedExecution => updatedExecution.CompletedOnUtc == completedOnUtc),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockScheduledJobNotifier.Received(1).SendScheduledJobsAsync(Arg.Any<IReadOnlyList<ScheduledJobResponse>>(), Arg.Any<CancellationToken>());
await _mockScheduledJobNotifier.Received(1).SendScheduledJobExecutionCompletedAsync(Arg.Any<ScheduledJobExecutionResponse>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenScheduledJobDoesNotExist_ShouldThrowEventualConsistencyException()
{
// Arrange
ScheduledJobExecutionCompletedDomainEvent domainEvent = _scheduledJobExecutionCompletedDomainEventFixture.Create(isCycleRun: true);
_mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(null));
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(Errors.Scheduling.ScheduledJobNotFound, exception.EventualConsistencyError);
await _mockScheduledJobExecutionRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUpdateScheduledJobFails_ShouldThrowEventualConsistencyException()
{
// Arrange
ScheduledJobExecutionCompletedDomainEvent domainEvent = _scheduledJobExecutionCompletedDomainEventFixture.Create(isCycleRun: true);
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(id: domainEvent.ScheduledJobId.Value, status: ScheduledJobStatus.Running);
_mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
Error error = Error.Failure("Database.Error", "Failed to update the scheduled job");
_mockScheduledJobRepository.UpdateAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>()).Returns(error);
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
await _mockScheduledJobExecutionRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenExecutionDoesNotExist_ShouldThrowEventualConsistencyException()
{
// Arrange
ScheduledJobExecutionCompletedDomainEvent domainEvent = _scheduledJobExecutionCompletedDomainEventFixture.Create(isCycleRun: true);
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(id: domainEvent.ScheduledJobId.Value, status: ScheduledJobStatus.Running);
_mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
_mockScheduledJobExecutionRepository.GetByIdAsync(domainEvent.RunId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobExecutionEntity?>(null));
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(Errors.Scheduling.ScheduledJobExecutionNotFound, exception.EventualConsistencyError);
await _mockScheduledJobExecutionRepository.DidNotReceive().UpdateAsync(Arg.Any<ScheduledJobExecutionEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUpdateExecutionFails_ShouldThrowEventualConsistencyException()
{
// Arrange
ScheduledJobExecutionCompletedDomainEvent domainEvent = _scheduledJobExecutionCompletedDomainEventFixture.Create(isCycleRun: true);
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(id: domainEvent.ScheduledJobId.Value, status: ScheduledJobStatus.Running);
_mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
ScheduledJobExecutionEntity execution = _scheduledJobExecutionEntityFixture.Create(id: domainEvent.RunId);
_mockScheduledJobExecutionRepository.GetByIdAsync(domainEvent.RunId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobExecutionEntity?>(execution));
Error error = Error.Failure("Database.Error", "Failed to update the execution");
_mockScheduledJobExecutionRepository.UpdateAsync(Arg.Any<ScheduledJobExecutionEntity>(), Arg.Any<CancellationToken>()).Returns(error);
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetAllScheduledJobsFails_ShouldThrowEventualConsistencyException()
{
// Arrange
ScheduledJobExecutionCompletedDomainEvent domainEvent = _scheduledJobExecutionCompletedDomainEventFixture.Create(isCycleRun: true);
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(id: domainEvent.ScheduledJobId.Value, status: ScheduledJobStatus.Running);
_mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
ScheduledJobExecutionEntity execution = _scheduledJobExecutionEntityFixture.Create(id: domainEvent.RunId);
_mockScheduledJobExecutionRepository.GetByIdAsync(domainEvent.RunId, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobExecutionEntity?>(execution));
Error error = Error.Failure("Database.Error", "Failed to get the scheduled jobs");
_mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(error);
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
await _mockScheduledJobNotifier.DidNotReceive().SendScheduledJobExecutionCompletedAsync(Arg.Any<ScheduledJobExecutionResponse>(), Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,191 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Core.Scheduling.Events;
using Lumina.Application.Core.Scheduling.Notifications;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Exceptions;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
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.Application.UnitTests.Core.Scheduling.Events;
/// <summary>
/// Contains unit tests for the <see cref="ScheduledJobExecutionStartedDomainEventHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScheduledJobExecutionStartedDomainEventHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IScheduledJobNotifier _mockScheduledJobNotifier;
private readonly IScheduledJobRepository _mockScheduledJobRepository;
private readonly IScheduledJobExecutionRepository _mockScheduledJobExecutionRepository;
private readonly ScheduledJobExecutionStartedDomainEventHandler _sut;
private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new();
private readonly ScheduledJobExecutionEntityFixture _scheduledJobExecutionEntityFixture = new();
private readonly ScheduledJobExecutionStartedDomainEventFixture _scheduledJobExecutionStartedDomainEventFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledJobExecutionStartedDomainEventHandlerTests"/> class.
/// </summary>
public ScheduledJobExecutionStartedDomainEventHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockScheduledJobNotifier = Substitute.For<IScheduledJobNotifier>();
_mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
_mockScheduledJobExecutionRepository = Substitute.For<IScheduledJobExecutionRepository>();
_mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository);
_mockUnitOfWork.ScheduledJobExecutionRepository.Returns(_mockScheduledJobExecutionRepository);
_mockScheduledJobRepository.UpdateAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>()).Returns(Result.Updated);
_mockScheduledJobExecutionRepository.InsertAsync(Arg.Any<ScheduledJobExecutionEntity>(), Arg.Any<CancellationToken>()).Returns(Result.Created);
_mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ScheduledJobEntity>>([]));
_sut = new ScheduledJobExecutionStartedDomainEventHandler(_mockScheduledJobNotifier, _mockUnitOfWork);
}
[Fact]
public async Task HandleAsync_WhenScheduledJobExists_ShouldUpdateItsStatusAndInsertTheExecution()
{
// Arrange
DateTime startedOnUtc = DateTime.UtcNow.AddMinutes(-1);
ScheduledJobExecutionStartedDomainEvent domainEvent = _scheduledJobExecutionStartedDomainEventFixture.Create(startedOnUtc: startedOnUtc);
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(
id: domainEvent.ScheduledJobId.Value,
taskType: domainEvent.TaskType,
scheduleType: ScheduleType.WithIntervalInMinutes,
status: ScheduledJobStatus.Active);
_mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
// Act
await _sut.HandleAsync(domainEvent, CancellationToken.None);
// Assert
await _mockScheduledJobRepository.Received(1).UpdateAsync(
Arg.Is<ScheduledJobEntity>(updatedScheduledJob =>
updatedScheduledJob.Status == ScheduledJobStatus.Running &&
updatedScheduledJob.LastStartedOnUtc == startedOnUtc),
Arg.Any<CancellationToken>());
await _mockScheduledJobExecutionRepository.Received(1).InsertAsync(
Arg.Is<ScheduledJobExecutionEntity>(execution =>
execution.Id == domainEvent.RunId &&
execution.ScheduledJobId == scheduledJob.Id &&
execution.TaskType == domainEvent.TaskType &&
execution.IsCycleRun == domainEvent.IsCycleRun &&
execution.StartedOnUtc == startedOnUtc &&
execution.CompletedOnUtc == null),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockScheduledJobNotifier.Received(1).SendScheduledJobsAsync(Arg.Any<IReadOnlyList<ScheduledJobResponse>>(), Arg.Any<CancellationToken>());
await _mockScheduledJobNotifier.Received(1).SendScheduledJobExecutionStartedAsync(Arg.Any<ScheduledJobExecutionResponse>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetByIdReturnsError_ShouldThrowEventualConsistencyException()
{
// Arrange
ScheduledJobExecutionStartedDomainEvent domainEvent = _scheduledJobExecutionStartedDomainEventFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to get the scheduled job");
_mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any<CancellationToken>()).Returns(error);
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
await _mockScheduledJobExecutionRepository.DidNotReceive().InsertAsync(Arg.Any<ScheduledJobExecutionEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenScheduledJobDoesNotExist_ShouldThrowEventualConsistencyException()
{
// Arrange
ScheduledJobExecutionStartedDomainEvent domainEvent = _scheduledJobExecutionStartedDomainEventFixture.Create();
_mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(null));
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(Errors.Scheduling.ScheduledJobNotFound, exception.EventualConsistencyError);
}
[Fact]
public async Task HandleAsync_WhenUpdateFails_ShouldThrowEventualConsistencyException()
{
// Arrange
ScheduledJobExecutionStartedDomainEvent domainEvent = _scheduledJobExecutionStartedDomainEventFixture.Create();
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(
id: domainEvent.ScheduledJobId.Value,
status: ScheduledJobStatus.Active);
_mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
Error error = Error.Failure("Database.Error", "Failed to update the scheduled job");
_mockScheduledJobRepository.UpdateAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>()).Returns(error);
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
await _mockScheduledJobExecutionRepository.DidNotReceive().InsertAsync(Arg.Any<ScheduledJobExecutionEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenInsertExecutionFails_ShouldThrowEventualConsistencyException()
{
// Arrange
ScheduledJobExecutionStartedDomainEvent domainEvent = _scheduledJobExecutionStartedDomainEventFixture.Create();
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(id: domainEvent.ScheduledJobId.Value);
_mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
Error error = Error.Failure("Database.Error", "Failed to insert the execution");
_mockScheduledJobExecutionRepository.InsertAsync(Arg.Any<ScheduledJobExecutionEntity>(), Arg.Any<CancellationToken>()).Returns(error);
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetAllScheduledJobsFails_ShouldThrowEventualConsistencyException()
{
// Arrange
ScheduledJobExecutionStartedDomainEvent domainEvent = _scheduledJobExecutionStartedDomainEventFixture.Create();
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(id: domainEvent.ScheduledJobId.Value);
_mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobEntity?>(scheduledJob));
Error error = Error.Failure("Database.Error", "Failed to get the scheduled jobs");
_mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(error);
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
await _mockScheduledJobNotifier.DidNotReceive().SendScheduledJobExecutionStartedAsync(Arg.Any<ScheduledJobExecutionResponse>(), Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,153 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Core.Scheduling.Events;
using Lumina.Application.Core.Scheduling.Notifications;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.Common.Exceptions;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Events;
/// <summary>
/// Contains unit tests for the <see cref="ScheduledJobExecutionStoppedDomainEventHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScheduledJobExecutionStoppedDomainEventHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IScheduledJobNotifier _mockScheduledJobNotifier;
private readonly IScheduledJobRepository _mockScheduledJobRepository;
private readonly IScheduledJobExecutionRepository _mockScheduledJobExecutionRepository;
private readonly ScheduledJobExecutionStoppedDomainEventHandler _sut;
private readonly ScheduledJobExecutionEntityFixture _scheduledJobExecutionEntityFixture = new();
private readonly ScheduledJobExecutionStoppedDomainEventFixture _scheduledJobExecutionStoppedDomainEventFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledJobExecutionStoppedDomainEventHandlerTests"/> class.
/// </summary>
public ScheduledJobExecutionStoppedDomainEventHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockScheduledJobNotifier = Substitute.For<IScheduledJobNotifier>();
_mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
_mockScheduledJobExecutionRepository = Substitute.For<IScheduledJobExecutionRepository>();
_mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository);
_mockUnitOfWork.ScheduledJobExecutionRepository.Returns(_mockScheduledJobExecutionRepository);
_mockScheduledJobExecutionRepository.UpdateAsync(Arg.Any<ScheduledJobExecutionEntity>(), Arg.Any<CancellationToken>()).Returns(Result.Updated);
_mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ScheduledJobEntity>>([]));
_sut = new ScheduledJobExecutionStoppedDomainEventHandler(_mockScheduledJobNotifier, _mockUnitOfWork);
}
[Fact]
public async Task HandleAsync_WhenOpenExecutionExists_ShouldCloseItAndNotifyScheduledJobs()
{
// Arrange
DateTime occurredOnUtc = DateTime.UtcNow;
ScheduledJobExecutionStoppedDomainEvent domainEvent = _scheduledJobExecutionStoppedDomainEventFixture.Create(occurredOnUtc: occurredOnUtc);
ScheduledJobExecutionEntity openExecution = _scheduledJobExecutionEntityFixture.Create(
scheduledJobId: domainEvent.ScheduledJobId.Value,
completedOnUtc: null);
_mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobExecutionEntity?>(openExecution));
// Act
await _sut.HandleAsync(domainEvent, CancellationToken.None);
// Assert
await _mockScheduledJobExecutionRepository.Received(1).UpdateAsync(
Arg.Is<ScheduledJobExecutionEntity>(updatedExecution => updatedExecution.CompletedOnUtc == occurredOnUtc),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockScheduledJobNotifier.Received(1).SendScheduledJobsAsync(Arg.Any<IReadOnlyList<ScheduledJobResponse>>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenNoOpenExecutionExists_ShouldOnlyNotifyScheduledJobs()
{
// Arrange
ScheduledJobExecutionStoppedDomainEvent domainEvent = _scheduledJobExecutionStoppedDomainEventFixture.Create();
_mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobExecutionEntity?>(null));
// Act
await _sut.HandleAsync(domainEvent, CancellationToken.None);
// Assert
await _mockScheduledJobExecutionRepository.DidNotReceive().UpdateAsync(Arg.Any<ScheduledJobExecutionEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockScheduledJobNotifier.Received(1).SendScheduledJobsAsync(Arg.Any<IReadOnlyList<ScheduledJobResponse>>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetOpenExecutionFails_ShouldThrowEventualConsistencyException()
{
// Arrange
ScheduledJobExecutionStoppedDomainEvent domainEvent = _scheduledJobExecutionStoppedDomainEventFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to get the open execution");
_mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any<CancellationToken>())
.Returns(error);
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
await _mockScheduledJobNotifier.DidNotReceive().SendScheduledJobsAsync(Arg.Any<IReadOnlyList<ScheduledJobResponse>>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUpdateExecutionFails_ShouldThrowEventualConsistencyException()
{
// Arrange
ScheduledJobExecutionStoppedDomainEvent domainEvent = _scheduledJobExecutionStoppedDomainEventFixture.Create();
ScheduledJobExecutionEntity openExecution = _scheduledJobExecutionEntityFixture.Create(
scheduledJobId: domainEvent.ScheduledJobId.Value,
completedOnUtc: null);
_mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobExecutionEntity?>(openExecution));
Error error = Error.Failure("Database.Error", "Failed to update the execution");
_mockScheduledJobExecutionRepository.UpdateAsync(Arg.Any<ScheduledJobExecutionEntity>(), Arg.Any<CancellationToken>()).Returns(error);
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
await _mockScheduledJobNotifier.DidNotReceive().SendScheduledJobsAsync(Arg.Any<IReadOnlyList<ScheduledJobResponse>>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetAllScheduledJobsFails_ShouldThrowEventualConsistencyException()
{
// Arrange
ScheduledJobExecutionStoppedDomainEvent domainEvent = _scheduledJobExecutionStoppedDomainEventFixture.Create();
_mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<ScheduledJobExecutionEntity?>(null));
Error error = Error.Failure("Database.Error", "Failed to get the scheduled jobs");
_mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(error);
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
await _mockScheduledJobNotifier.DidNotReceive().SendScheduledJobsAsync(Arg.Any<IReadOnlyList<ScheduledJobResponse>>(), Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,46 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Scheduling;
using Lumina.Application.Core.Scheduling.Events;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Events;
/// <summary>
/// Contains unit tests for the <see cref="ScheduledJobFiredDomainEventHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScheduledJobFiredDomainEventHandlerTests
{
private readonly IScheduledJobScheduler _mockScheduledJobScheduler;
private readonly ScheduledJobFiredDomainEventHandler _sut;
private readonly ScheduledJobFiredDomainEventFixture _scheduledJobFiredDomainEventFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledJobFiredDomainEventHandlerTests"/> class.
/// </summary>
public ScheduledJobFiredDomainEventHandlerTests()
{
_mockScheduledJobScheduler = Substitute.For<IScheduledJobScheduler>();
_sut = new ScheduledJobFiredDomainEventHandler(_mockScheduledJobScheduler);
}
[Fact]
public async Task HandleAsync_WhenFiredEventIsHandled_ShouldRunTheTaskOnceInTheScheduler()
{
// Arrange
ScheduledJobFiredDomainEvent domainEvent = _scheduledJobFiredDomainEventFixture.Create();
// Act
await _sut.HandleAsync(domainEvent, CancellationToken.None);
// Assert
await _mockScheduledJobScheduler.Received(1).RunOnceAsync(domainEvent.ScheduledJobId, Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,84 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Core.Scheduling.Events;
using Lumina.Application.Core.Scheduling.Notifications;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.Common.Exceptions;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Events;
/// <summary>
/// Contains unit tests for the <see cref="ScheduledJobRemovedDomainEventHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScheduledJobRemovedDomainEventHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IScheduledJobNotifier _mockScheduledJobNotifier;
private readonly IScheduledJobRepository _mockScheduledJobRepository;
private readonly ScheduledJobRemovedDomainEventHandler _sut;
private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new();
private readonly ScheduledJobRemovedDomainEventFixture _scheduledJobRemovedDomainEventFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledJobRemovedDomainEventHandlerTests"/> class.
/// </summary>
public ScheduledJobRemovedDomainEventHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockScheduledJobNotifier = Substitute.For<IScheduledJobNotifier>();
_mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
_mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository);
_mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ScheduledJobEntity>>([]));
_sut = new ScheduledJobRemovedDomainEventHandler(_mockScheduledJobNotifier, _mockUnitOfWork);
}
[Fact]
public async Task HandleAsync_WhenScheduledJobsAreLoaded_ShouldNotifyTheCurrentScheduledJobs()
{
// Arrange
ScheduledJobRemovedDomainEvent domainEvent = _scheduledJobRemovedDomainEventFixture.Create();
ScheduledJobEntity remainingJob = _scheduledJobEntityFixture.Create(name: "Remaining job");
_mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ScheduledJobEntity>>([remainingJob]));
// Act
await _sut.HandleAsync(domainEvent, CancellationToken.None);
// Assert
await _mockScheduledJobNotifier.Received(1).SendScheduledJobsAsync(
Arg.Is<IReadOnlyList<ScheduledJobResponse>>(scheduledJobs => scheduledJobs.Count == 1),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetAllScheduledJobsFails_ShouldThrowEventualConsistencyException()
{
// Arrange
ScheduledJobRemovedDomainEvent domainEvent = _scheduledJobRemovedDomainEventFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to get the scheduled jobs");
_mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(error);
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
await _mockScheduledJobNotifier.DidNotReceive().SendScheduledJobsAsync(Arg.Any<IReadOnlyList<ScheduledJobResponse>>(), Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,161 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Core.Scheduling.Queries.GetScheduledJobHistory;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Fixtures.Core.Scheduling.Queries.GetScheduledJobHistory;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.Common.Primitives;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Queries.GetScheduledJobHistory;
/// <summary>
/// Contains unit tests for the <see cref="GetScheduledJobHistoryQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetScheduledJobHistoryQueryHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly IScheduledJobExecutionRepository _mockScheduledJobExecutionRepository;
private readonly GetScheduledJobHistoryQueryHandler _sut;
private readonly GetScheduledJobHistoryQueryFixture _getScheduledJobHistoryQueryFixture = new();
private readonly ScheduledJobExecutionEntityFixture _scheduledJobExecutionEntityFixture = new();
private readonly Guid _userId = Guid.NewGuid();
/// <summary>
/// Initializes a new instance of the <see cref="GetScheduledJobHistoryQueryHandlerTests"/> class.
/// </summary>
public GetScheduledJobHistoryQueryHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockScheduledJobExecutionRepository = Substitute.For<IScheduledJobExecutionRepository>();
_mockUnitOfWork.ScheduledJobExecutionRepository.Returns(_mockScheduledJobExecutionRepository);
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(true);
_sut = new GetScheduledJobHistoryQueryHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork);
}
[Fact]
public async Task HandleAsync_WhenExecutionsExistInTheRequestedRange_ShouldReturnThemAsResponses()
{
// Arrange
GetScheduledJobHistoryQuery query = _getScheduledJobHistoryQueryFixture.Create();
ScheduledJobExecutionEntity execution1 = _scheduledJobExecutionEntityFixture.Create(startedOnUtc: query.From);
ScheduledJobExecutionEntity execution2 = _scheduledJobExecutionEntityFixture.Create(startedOnUtc: query.From!.Value.AddMinutes(1));
_mockScheduledJobExecutionRepository.GetByTimeRangeAsync(query.From!.Value, query.To!.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IEnumerable<ScheduledJobExecutionEntity>>([execution1, execution2]));
// Act
Result<IEnumerable<ScheduledJobExecutionResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(2, result.Value.Count());
Assert.Contains(result.Value, execution => execution.Id == execution1.Id);
Assert.Contains(result.Value, execution => execution.Id == execution2.Id);
}
[Fact]
public async Task HandleAsync_WhenNoExecutionsExist_ShouldReturnEmptyCollection()
{
// Arrange
GetScheduledJobHistoryQuery query = _getScheduledJobHistoryQueryFixture.Create();
_mockScheduledJobExecutionRepository.GetByTimeRangeAsync(query.From!.Value, query.To!.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IEnumerable<ScheduledJobExecutionEntity>>([]));
// Act
Result<IEnumerable<ScheduledJobExecutionResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Empty(result.Value);
}
[Fact]
public async Task HandleAsync_WhenBoundsAreNotProvided_ShouldDefaultToThePastDay()
{
// Arrange
GetScheduledJobHistoryQuery query = _getScheduledJobHistoryQueryFixture.Create(includeFrom: false, includeTo: false);
DateTime beforeCall = DateTime.UtcNow;
_mockScheduledJobExecutionRepository.GetByTimeRangeAsync(Arg.Any<DateTime>(), Arg.Any<DateTime>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IEnumerable<ScheduledJobExecutionEntity>>([]));
// Act
Result<IEnumerable<ScheduledJobExecutionResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
DateTime afterCall = DateTime.UtcNow;
// Assert
Assert.False(result.IsFailure);
await _mockScheduledJobExecutionRepository.Received(1).GetByTimeRangeAsync(
Arg.Is<DateTime>(fromUtc => fromUtc <= afterCall && fromUtc >= beforeCall.AddDays(-1)),
Arg.Is<DateTime>(toUtc => toUtc >= beforeCall && toUtc <= afterCall),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorized()
{
// Arrange
GetScheduledJobHistoryQuery query = _getScheduledJobHistoryQueryFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<IEnumerable<ScheduledJobExecutionResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockScheduledJobExecutionRepository.DidNotReceive().GetByTimeRangeAsync(Arg.Any<DateTime>(), Arg.Any<DateTime>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAdministrator_ShouldReturnNotAuthorized()
{
// Arrange
GetScheduledJobHistoryQuery query = _getScheduledJobHistoryQueryFixture.Create();
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(false);
// Act
Result<IEnumerable<ScheduledJobExecutionResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockScheduledJobExecutionRepository.DidNotReceive().GetByTimeRangeAsync(Arg.Any<DateTime>(), Arg.Any<DateTime>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetByTimeRangeReturnsError_ShouldReturnError()
{
// Arrange
GetScheduledJobHistoryQuery query = _getScheduledJobHistoryQueryFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to get the execution history");
_mockScheduledJobExecutionRepository.GetByTimeRangeAsync(query.From!.Value, query.To!.Value, Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<IEnumerable<ScheduledJobExecutionResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
}
}
@@ -0,0 +1,132 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Core.Scheduling.Queries.GetScheduledJobs;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.Common.Primitives;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Queries.GetScheduledJobs;
/// <summary>
/// Contains unit tests for the <see cref="GetScheduledJobsQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetScheduledJobsQueryHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly IScheduledJobRepository _mockScheduledJobRepository;
private readonly GetScheduledJobsQueryHandler _sut;
private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new();
private readonly Guid _userId = Guid.NewGuid();
/// <summary>
/// Initializes a new instance of the <see cref="GetScheduledJobsQueryHandlerTests"/> class.
/// </summary>
public GetScheduledJobsQueryHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
_mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository);
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(true);
_sut = new GetScheduledJobsQueryHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork);
}
[Fact]
public async Task HandleAsync_WhenScheduledJobsExist_ShouldReturnAllOfThemAsResponses()
{
// Arrange
ScheduledJobEntity scheduledJob1 = _scheduledJobEntityFixture.Create(name: "Job 1");
ScheduledJobEntity scheduledJob2 = _scheduledJobEntityFixture.Create(name: "Job 2");
_mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(Result.From<IEnumerable<ScheduledJobEntity>>([scheduledJob1, scheduledJob2]));
// Act
Result<IEnumerable<ScheduledJobResponse>> result = await _sut.HandleAsync(new GetScheduledJobsQuery(), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(2, result.Value.Count());
Assert.Contains(result.Value, scheduledJob => scheduledJob.Id == scheduledJob1.Id && scheduledJob.Name == "Job 1");
Assert.Contains(result.Value, scheduledJob => scheduledJob.Id == scheduledJob2.Id && scheduledJob.Name == "Job 2");
}
[Fact]
public async Task HandleAsync_WhenNoScheduledJobsExist_ShouldReturnEmptyCollection()
{
// Arrange
_mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(Result.From<IEnumerable<ScheduledJobEntity>>([]));
// Act
Result<IEnumerable<ScheduledJobResponse>> result = await _sut.HandleAsync(new GetScheduledJobsQuery(), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Empty(result.Value);
}
[Fact]
public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorized()
{
// Arrange
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<IEnumerable<ScheduledJobResponse>> result = await _sut.HandleAsync(new GetScheduledJobsQuery(), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().GetAllAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAdministrator_ShouldReturnNotAuthorized()
{
// Arrange
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(false);
// Act
Result<IEnumerable<ScheduledJobResponse>> result = await _sut.HandleAsync(new GetScheduledJobsQuery(), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockScheduledJobRepository.DidNotReceive().GetAllAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetAllReturnsError_ShouldReturnError()
{
// Arrange
Error error = Error.Failure("Database.Error", "Failed to get the scheduled jobs");
_mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(error);
// Act
Result<IEnumerable<ScheduledJobResponse>> result = await _sut.HandleAsync(new GetScheduledJobsQuery(), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
}
}
@@ -0,0 +1,142 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Core.Scheduling.Queries.GetSchedulerDisplayPreferences;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.Scheduling.Queries.GetSchedulerDisplayPreferences;
/// <summary>
/// Contains unit tests for the <see cref="GetSchedulerDisplayPreferencesQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetSchedulerDisplayPreferencesQueryHandlerTests
{
private const int DEFAULT_DISPLAY_TIME_SPAN = 10;
private const SchedulerDisplayTimeUnit DEFAULT_DISPLAY_TIME_UNIT = SchedulerDisplayTimeUnit.Minutes;
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ISchedulerDisplayPreferencesRepository _mockSchedulerDisplayPreferencesRepository;
private readonly GetSchedulerDisplayPreferencesQueryHandler _sut;
private readonly SchedulerDisplayPreferencesEntityFixture _schedulerDisplayPreferencesEntityFixture = new();
private readonly Guid _userId = Guid.NewGuid();
/// <summary>
/// Initializes a new instance of the <see cref="GetSchedulerDisplayPreferencesQueryHandlerTests"/> class.
/// </summary>
public GetSchedulerDisplayPreferencesQueryHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockSchedulerDisplayPreferencesRepository = Substitute.For<ISchedulerDisplayPreferencesRepository>();
_mockUnitOfWork.SchedulerDisplayPreferencesRepository.Returns(_mockSchedulerDisplayPreferencesRepository);
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(true);
_sut = new GetSchedulerDisplayPreferencesQueryHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork);
}
[Fact]
public async Task HandleAsync_WhenDisplayPreferencesExist_ShouldReturnThemAsResponse()
{
// Arrange
SchedulerDisplayPreferencesEntity displayPreferences = _schedulerDisplayPreferencesEntityFixture.Create(
userId: _userId,
jobTypeFilter: ScheduledTaskType.ScanMediaLibraries,
displayTimeSpan: 60,
displayTimeUnit: SchedulerDisplayTimeUnit.Hours);
_mockSchedulerDisplayPreferencesRepository.GetByUserIdAsync(_userId, Arg.Any<CancellationToken>())
.Returns(Result.From<SchedulerDisplayPreferencesEntity?>(displayPreferences));
// Act
Result<SchedulerDisplayPreferencesResponse> result = await _sut.HandleAsync(new GetSchedulerDisplayPreferencesQuery(), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(_userId, result.Value.UserId);
Assert.Equal(ScheduledTaskType.ScanMediaLibraries, result.Value.JobTypeFilter);
Assert.Equal(60, result.Value.DisplayTimeSpan);
Assert.Equal(SchedulerDisplayTimeUnit.Hours, result.Value.DisplayTimeUnit);
}
[Fact]
public async Task HandleAsync_WhenNoDisplayPreferencesExist_ShouldReturnDefaultResponse()
{
// Arrange
_mockSchedulerDisplayPreferencesRepository.GetByUserIdAsync(_userId, Arg.Any<CancellationToken>())
.Returns(Result.From<SchedulerDisplayPreferencesEntity?>(null));
// Act
Result<SchedulerDisplayPreferencesResponse> result = await _sut.HandleAsync(new GetSchedulerDisplayPreferencesQuery(), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(_userId, result.Value.UserId);
Assert.Null(result.Value.JobTypeFilter);
Assert.Equal(DEFAULT_DISPLAY_TIME_SPAN, result.Value.DisplayTimeSpan);
Assert.Equal(DEFAULT_DISPLAY_TIME_UNIT, result.Value.DisplayTimeUnit);
}
[Fact]
public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorized()
{
// Arrange
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<SchedulerDisplayPreferencesResponse> result = await _sut.HandleAsync(new GetSchedulerDisplayPreferencesQuery(), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockSchedulerDisplayPreferencesRepository.DidNotReceive().GetByUserIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAdministrator_ShouldReturnNotAuthorized()
{
// Arrange
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(false);
// Act
Result<SchedulerDisplayPreferencesResponse> result = await _sut.HandleAsync(new GetSchedulerDisplayPreferencesQuery(), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockSchedulerDisplayPreferencesRepository.DidNotReceive().GetByUserIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetByUserIdReturnsError_ShouldReturnError()
{
// Arrange
Error error = Error.Failure("Database.Error", "Failed to get the display preferences");
_mockSchedulerDisplayPreferencesRepository.GetByUserIdAsync(_userId, Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<SchedulerDisplayPreferencesResponse> result = await _sut.HandleAsync(new GetSchedulerDisplayPreferencesQuery(), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
}
}
@@ -0,0 +1,237 @@
#region ========================================================================= USING =====================================================================================
using EntityFrameworkCore.Testing.NSubstitute;
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.Errors;
using Lumina.Domain.Common.Primitives;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.UnitTests.Core.Repositories.Scheduling;
/// <summary>
/// Contains unit tests for the <see cref="ScheduledJobExecutionRepository"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScheduledJobExecutionRepositoryTests
{
private readonly LuminaDbContext _mockContext;
private readonly ScheduledJobExecutionRepository _sut;
private readonly ScheduledJobExecutionEntityFixture _scheduledJobExecutionEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledJobExecutionRepositoryTests"/> class.
/// </summary>
public ScheduledJobExecutionRepositoryTests()
{
_mockContext = Create.MockedDbContextFor<LuminaDbContext>();
_sut = new ScheduledJobExecutionRepository(_mockContext);
}
[Fact]
public async Task GetByIdAsync_WhenExecutionExists_ShouldReturnExecution()
{
// Arrange
ScheduledJobExecutionEntity execution = _scheduledJobExecutionEntityFixture.Create();
_mockContext.ScheduledJobExecutions.Add(execution);
await _mockContext.SaveChangesAsync();
// Act
Result<ScheduledJobExecutionEntity?> result = await _sut.GetByIdAsync(execution.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.NotNull(result.Value);
Assert.Equal(execution.Id, result.Value!.Id);
Assert.Equal(execution.ScheduledJobId, result.Value.ScheduledJobId);
}
[Fact]
public async Task GetByIdAsync_WhenExecutionDoesNotExist_ShouldReturnNull()
{
// Act
Result<ScheduledJobExecutionEntity?> result = await _sut.GetByIdAsync(Guid.NewGuid(), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public async Task InsertAsync_WhenExecutionDoesNotExist_ShouldAddExecutionToContextAndReturnCreated()
{
// Arrange
ScheduledJobExecutionEntity execution = _scheduledJobExecutionEntityFixture.Create();
// Act
Result<Created> result = await _sut.InsertAsync(execution, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Created, result.Value);
EntityEntry<ScheduledJobExecutionEntity>? addedExecution = _mockContext.ChangeTracker.Entries<ScheduledJobExecutionEntity>()
.FirstOrDefault(entry => entry.State == EntityState.Added && entry.Entity.Id == execution.Id);
Assert.NotNull(addedExecution);
}
[Fact]
public async Task InsertAsync_WhenExecutionAlreadyExists_ShouldReturnError()
{
// Arrange
ScheduledJobExecutionEntity execution = _scheduledJobExecutionEntityFixture.Create();
_mockContext.ScheduledJobExecutions.Add(execution);
await _mockContext.SaveChangesAsync();
// Act
Result<Created> result = await _sut.InsertAsync(execution, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Scheduling.ScheduledJobExecutionAlreadyExists, result.FirstError);
}
[Fact]
public async Task UpdateAsync_WhenExecutionExists_ShouldUpdateItsPropertiesAndReturnUpdated()
{
// Arrange
DateTime completedOnUtc = DateTime.UtcNow;
ScheduledJobExecutionEntity existingExecution = _scheduledJobExecutionEntityFixture.Create(completedOnUtc: null);
_mockContext.ScheduledJobExecutions.Add(existingExecution);
await _mockContext.SaveChangesAsync();
ScheduledJobExecutionEntity updatedExecution = _scheduledJobExecutionEntityFixture.Create(
id: existingExecution.Id,
scheduledJobId: existingExecution.ScheduledJobId,
isCycleRun: existingExecution.IsCycleRun,
startedOnUtc: existingExecution.StartedOnUtc,
completedOnUtc: completedOnUtc);
// Act
Result<Updated> result = await _sut.UpdateAsync(updatedExecution, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
ScheduledJobExecutionEntity? modifiedExecution = await _mockContext.ScheduledJobExecutions.FirstOrDefaultAsync(execution => execution.Id == existingExecution.Id);
Assert.NotNull(modifiedExecution);
Assert.Equal(completedOnUtc, modifiedExecution!.CompletedOnUtc);
}
[Fact]
public async Task UpdateAsync_WhenExecutionDoesNotExist_ShouldReturnError()
{
// Arrange
ScheduledJobExecutionEntity execution = _scheduledJobExecutionEntityFixture.Create();
// Act
Result<Updated> result = await _sut.UpdateAsync(execution, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Scheduling.ScheduledJobExecutionNotFound, result.FirstError);
}
[Fact]
public async Task GetOpenByScheduledJobIdAsync_WhenAnOpenExecutionExists_ShouldReturnTheMostRecentOne()
{
// Arrange
Guid scheduledJobId = Guid.NewGuid();
DateTime mostRecentStart = DateTime.UtcNow.AddMinutes(-1);
ScheduledJobExecutionEntity openExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: scheduledJobId, startedOnUtc: mostRecentStart, completedOnUtc: null);
ScheduledJobExecutionEntity olderOpenExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: scheduledJobId, startedOnUtc: mostRecentStart.AddMinutes(-10), completedOnUtc: null);
ScheduledJobExecutionEntity closedExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: scheduledJobId, startedOnUtc: mostRecentStart.AddMinutes(-5), completedOnUtc: DateTime.UtcNow);
_mockContext.ScheduledJobExecutions.AddRange(openExecution, olderOpenExecution, closedExecution);
await _mockContext.SaveChangesAsync();
// Act
Result<ScheduledJobExecutionEntity?> result = await _sut.GetOpenByScheduledJobIdAsync(scheduledJobId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.NotNull(result.Value);
Assert.Equal(openExecution.Id, result.Value!.Id);
}
[Fact]
public async Task GetOpenByScheduledJobIdAsync_WhenNoOpenExecutionExists_ShouldReturnNull()
{
// Arrange
Guid scheduledJobId = Guid.NewGuid();
ScheduledJobExecutionEntity closedExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: scheduledJobId, completedOnUtc: DateTime.UtcNow);
_mockContext.ScheduledJobExecutions.Add(closedExecution);
await _mockContext.SaveChangesAsync();
// Act
Result<ScheduledJobExecutionEntity?> result = await _sut.GetOpenByScheduledJobIdAsync(scheduledJobId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public async Task GetByTimeRangeAsync_WhenExecutionsStartedInTheRange_ShouldReturnThemOrderedByStartTime()
{
// Arrange
DateTime fromUtc = DateTime.UtcNow.AddHours(-2);
DateTime toUtc = DateTime.UtcNow;
ScheduledJobExecutionEntity inRange1 = _scheduledJobExecutionEntityFixture.Create(startedOnUtc: fromUtc.AddMinutes(1));
ScheduledJobExecutionEntity inRange2 = _scheduledJobExecutionEntityFixture.Create(startedOnUtc: fromUtc.AddMinutes(30));
ScheduledJobExecutionEntity beforeRange = _scheduledJobExecutionEntityFixture.Create(startedOnUtc: fromUtc.AddMinutes(-10));
ScheduledJobExecutionEntity afterRange = _scheduledJobExecutionEntityFixture.Create(startedOnUtc: toUtc.AddMinutes(10));
_mockContext.ScheduledJobExecutions.AddRange(inRange1, inRange2, beforeRange, afterRange);
await _mockContext.SaveChangesAsync();
// Act
Result<IEnumerable<ScheduledJobExecutionEntity>> result = await _sut.GetByTimeRangeAsync(fromUtc, toUtc, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
List<ScheduledJobExecutionEntity> executions = [.. result.Value];
Assert.Equal(2, executions.Count);
Assert.Equal(inRange1.Id, executions[0].Id);
Assert.Equal(inRange2.Id, executions[1].Id);
}
[Fact]
public async Task DeleteByScheduledJobIdAsync_WhenExecutionsExist_ShouldRemoveThemAllAndReturnSuccess()
{
// Arrange
Guid scheduledJobId = Guid.NewGuid();
ScheduledJobExecutionEntity execution1 = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: scheduledJobId);
ScheduledJobExecutionEntity execution2 = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: scheduledJobId);
ScheduledJobExecutionEntity otherExecution = _scheduledJobExecutionEntityFixture.Create();
_mockContext.ScheduledJobExecutions.AddRange(execution1, execution2, otherExecution);
await _mockContext.SaveChangesAsync();
// Act
Result<Success> result = await _sut.DeleteByScheduledJobIdAsync(scheduledJobId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Success, result.Value);
Assert.Equal(2, _mockContext.ChangeTracker.Entries<ScheduledJobExecutionEntity>().Count(entry => entry.State == EntityState.Deleted));
Assert.Contains(_mockContext.ChangeTracker.Entries<ScheduledJobExecutionEntity>(), entry => entry.State == EntityState.Deleted && entry.Entity.Id == execution1.Id);
Assert.Contains(_mockContext.ChangeTracker.Entries<ScheduledJobExecutionEntity>(), entry => entry.State == EntityState.Deleted && entry.Entity.Id == execution2.Id);
}
[Fact]
public async Task DeleteByScheduledJobIdAsync_WhenNoExecutionsExist_ShouldReturnSuccess()
{
// Act
Result<Success> result = await _sut.DeleteByScheduledJobIdAsync(Guid.NewGuid(), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Success, result.Value);
}
}
@@ -0,0 +1,211 @@
#region ========================================================================= USING =====================================================================================
using EntityFrameworkCore.Testing.NSubstitute;
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.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.UnitTests.Core.Repositories.Scheduling;
/// <summary>
/// Contains unit tests for the <see cref="ScheduledJobRepository"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScheduledJobRepositoryTests
{
private readonly LuminaDbContext _mockContext;
private readonly ScheduledJobRepository _sut;
private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledJobRepositoryTests"/> class.
/// </summary>
public ScheduledJobRepositoryTests()
{
_mockContext = Create.MockedDbContextFor<LuminaDbContext>();
_sut = new ScheduledJobRepository(_mockContext);
}
[Fact]
public async Task GetByIdAsync_WhenScheduledJobExists_ShouldReturnScheduledJob()
{
// Arrange
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create();
_mockContext.ScheduledJobs.Add(scheduledJob);
await _mockContext.SaveChangesAsync();
// Act
Result<ScheduledJobEntity?> result = await _sut.GetByIdAsync(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 GetByIdAsync_WhenScheduledJobDoesNotExist_ShouldReturnNull()
{
// Act
Result<ScheduledJobEntity?> result = await _sut.GetByIdAsync(Guid.NewGuid(), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public async Task GetAllAsync_WhenScheduledJobsExist_ShouldReturnAllScheduledJobs()
{
// Arrange
ScheduledJobEntity scheduledJob1 = _scheduledJobEntityFixture.Create();
ScheduledJobEntity scheduledJob2 = _scheduledJobEntityFixture.Create();
_mockContext.ScheduledJobs.AddRange(scheduledJob1, scheduledJob2);
await _mockContext.SaveChangesAsync();
// Act
Result<IEnumerable<ScheduledJobEntity>> result = await _sut.GetAllAsync(CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(2, result.Value.Count());
}
[Fact]
public async Task GetActiveOrRunningAsync_WhenScheduledJobsAreActiveOrRunning_ShouldReturnOnlyThem()
{
// Arrange
ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active);
ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running);
ScheduledJobEntity addedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added);
ScheduledJobEntity completedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Completed);
_mockContext.ScheduledJobs.AddRange(activeJob, runningJob, addedJob, completedJob);
await _mockContext.SaveChangesAsync();
// Act
Result<IEnumerable<ScheduledJobEntity>> result = await _sut.GetActiveOrRunningAsync(CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
List<ScheduledJobEntity> scheduledJobs = result.Value.ToList();
Assert.Equal(2, scheduledJobs.Count);
Assert.Contains(scheduledJobs, scheduledJob => scheduledJob.Id == activeJob.Id);
Assert.Contains(scheduledJobs, scheduledJob => scheduledJob.Id == runningJob.Id);
}
[Fact]
public async Task InsertAsync_WhenScheduledJobDoesNotExist_ShouldAddScheduledJobToContextAndReturnCreated()
{
// Arrange
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create();
// Act
Result<Created> result = await _sut.InsertAsync(scheduledJob, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Created, result.Value);
EntityEntry<ScheduledJobEntity>? addedScheduledJob = _mockContext.ChangeTracker.Entries<ScheduledJobEntity>()
.FirstOrDefault(entry => entry.State == EntityState.Added && entry.Entity.Id == scheduledJob.Id);
Assert.NotNull(addedScheduledJob);
Assert.Equal(scheduledJob.Name, addedScheduledJob!.Entity.Name);
}
[Fact]
public async Task InsertAsync_WhenScheduledJobAlreadyExists_ShouldReturnError()
{
// Arrange
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create();
_mockContext.ScheduledJobs.Add(scheduledJob);
await _mockContext.SaveChangesAsync();
// Act
Result<Created> result = await _sut.InsertAsync(scheduledJob, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Scheduling.ScheduledJobAlreadyExists, result.FirstError);
}
[Fact]
public async Task UpdateAsync_WhenScheduledJobExists_ShouldUpdateItsPropertiesAndReturnUpdated()
{
// Arrange
ScheduledJobEntity existingScheduledJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added);
_mockContext.ScheduledJobs.Add(existingScheduledJob);
await _mockContext.SaveChangesAsync();
ScheduledJobEntity updatedScheduledJob = _scheduledJobEntityFixture.Create(
id: existingScheduledJob.Id,
name: "Updated name",
status: ScheduledJobStatus.Active);
// Act
Result<Updated> result = await _sut.UpdateAsync(updatedScheduledJob, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
ScheduledJobEntity? modifiedScheduledJob = await _mockContext.ScheduledJobs.FirstOrDefaultAsync(scheduledJob => scheduledJob.Id == existingScheduledJob.Id);
Assert.NotNull(modifiedScheduledJob);
Assert.Equal("Updated name", modifiedScheduledJob!.Name);
Assert.Equal(ScheduledJobStatus.Active, modifiedScheduledJob.Status);
}
[Fact]
public async Task UpdateAsync_WhenScheduledJobDoesNotExist_ShouldReturnError()
{
// Arrange
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create();
// Act
Result<Updated> result = await _sut.UpdateAsync(scheduledJob, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Scheduling.ScheduledJobNotFound, result.FirstError);
}
[Fact]
public async Task DeleteByIdAsync_WhenScheduledJobExists_ShouldRemoveItAndReturnDeleted()
{
// Arrange
ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create();
_mockContext.ScheduledJobs.Add(scheduledJob);
await _mockContext.SaveChangesAsync();
// Act
Result<Deleted> result = await _sut.DeleteByIdAsync(scheduledJob.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Deleted, result.Value);
EntityEntry<ScheduledJobEntity>? deletedScheduledJob = _mockContext.ChangeTracker.Entries<ScheduledJobEntity>()
.FirstOrDefault(entry => entry.State == EntityState.Deleted && entry.Entity.Id == scheduledJob.Id);
Assert.NotNull(deletedScheduledJob);
}
[Fact]
public async Task DeleteByIdAsync_WhenScheduledJobDoesNotExist_ShouldReturnError()
{
// Act
Result<Deleted> result = await _sut.DeleteByIdAsync(Guid.NewGuid(), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Scheduling.ScheduledJobNotFound, result.FirstError);
}
}
@@ -0,0 +1,123 @@
#region ========================================================================= USING =====================================================================================
using EntityFrameworkCore.Testing.NSubstitute;
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 Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.UnitTests.Core.Repositories.Scheduling;
/// <summary>
/// Contains unit tests for the <see cref="SchedulerDisplayPreferencesRepository"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SchedulerDisplayPreferencesRepositoryTests
{
private readonly LuminaDbContext _mockContext;
private readonly SchedulerDisplayPreferencesRepository _sut;
private readonly SchedulerDisplayPreferencesEntityFixture _schedulerDisplayPreferencesEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="SchedulerDisplayPreferencesRepositoryTests"/> class.
/// </summary>
public SchedulerDisplayPreferencesRepositoryTests()
{
_mockContext = Create.MockedDbContextFor<LuminaDbContext>();
_sut = new SchedulerDisplayPreferencesRepository(_mockContext);
}
[Fact]
public async Task GetByUserIdAsync_WhenDisplayPreferencesExist_ShouldReturnThem()
{
// Arrange
SchedulerDisplayPreferencesEntity displayPreferences = _schedulerDisplayPreferencesEntityFixture.Create();
_mockContext.SchedulerDisplayPreferences.Add(displayPreferences);
await _mockContext.SaveChangesAsync();
// Act
Result<SchedulerDisplayPreferencesEntity?> result = await _sut.GetByUserIdAsync(displayPreferences.UserId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.NotNull(result.Value);
Assert.Equal(displayPreferences.Id, result.Value!.Id);
Assert.Equal(displayPreferences.UserId, result.Value.UserId);
Assert.Equal(displayPreferences.DisplayTimeSpan, result.Value.DisplayTimeSpan);
}
[Fact]
public async Task GetByUserIdAsync_WhenDisplayPreferencesDoNotExist_ShouldReturnNull()
{
// Act
Result<SchedulerDisplayPreferencesEntity?> result = await _sut.GetByUserIdAsync(Guid.NewGuid(), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public async Task UpsertAsync_WhenDisplayPreferencesDoNotExist_ShouldAddThemToContextAndReturnUpdated()
{
// Arrange
SchedulerDisplayPreferencesEntity displayPreferences = _schedulerDisplayPreferencesEntityFixture.Create(
displayTimeSpan: 30,
displayTimeUnit: SchedulerDisplayTimeUnit.Minutes);
// Act
Result<Updated> result = await _sut.UpsertAsync(displayPreferences, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
EntityEntry<SchedulerDisplayPreferencesEntity>? addedPreferences = _mockContext.ChangeTracker.Entries<SchedulerDisplayPreferencesEntity>()
.FirstOrDefault(entry => entry.State == EntityState.Added && entry.Entity.UserId == displayPreferences.UserId);
Assert.NotNull(addedPreferences);
}
[Fact]
public async Task UpsertAsync_WhenDisplayPreferencesAlreadyExist_ShouldUpdateTheMutableFieldsAndReturnUpdated()
{
// Arrange
Guid userId = Guid.NewGuid();
SchedulerDisplayPreferencesEntity existingPreferences = _schedulerDisplayPreferencesEntityFixture.Create(
userId: userId,
jobTypeFilter: ScheduledTaskType.ScanMediaLibraries,
displayTimeSpan: 10,
displayTimeUnit: SchedulerDisplayTimeUnit.Hours);
_mockContext.SchedulerDisplayPreferences.Add(existingPreferences);
await _mockContext.SaveChangesAsync();
SchedulerDisplayPreferencesEntity updatedPreferences = _schedulerDisplayPreferencesEntityFixture.Create(
userId: userId,
jobTypeFilter: ScheduledTaskType.CleanTemporaryFiles,
displayTimeSpan: 60,
displayTimeUnit: SchedulerDisplayTimeUnit.Days);
// Act
Result<Updated> result = await _sut.UpsertAsync(updatedPreferences, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
SchedulerDisplayPreferencesEntity? modifiedPreferences = await _mockContext.SchedulerDisplayPreferences
.FirstOrDefaultAsync(preferences => preferences.UserId == userId);
Assert.NotNull(modifiedPreferences);
// The Id and the ownership of the existing preferences are preserved.
Assert.Equal(existingPreferences.Id, modifiedPreferences!.Id);
Assert.Equal(ScheduledTaskType.CleanTemporaryFiles, modifiedPreferences.JobTypeFilter);
Assert.Equal(60, modifiedPreferences.DisplayTimeSpan);
Assert.Equal(SchedulerDisplayTimeUnit.Days, modifiedPreferences.DisplayTimeUnit);
Assert.Single(_mockContext.ChangeTracker.Entries<SchedulerDisplayPreferencesEntity>());
}
}
@@ -3,6 +3,7 @@ using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
@@ -16,6 +17,7 @@ namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedC
public class LibraryDeletedDomainEventTests
{
private readonly LibraryFixture _libraryFixture = new();
private readonly LibraryDeletedDomainEventFixture _libraryDeletedDomainEventFixture = new();
[Fact]
public void Constructor_WhenCalled_ShouldSetAllProperties()
@@ -26,7 +28,7 @@ public class LibraryDeletedDomainEventTests
DateTime occurredOnUtc = DateTime.UtcNow;
// Act
LibraryDeletedDomainEvent domainEvent = new(id, library, occurredOnUtc);
LibraryDeletedDomainEvent domainEvent = _libraryDeletedDomainEventFixture.Create(id, library, occurredOnUtc);
// Assert
Assert.Equal(id, domainEvent.Id);
@@ -3,6 +3,7 @@ using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
@@ -16,6 +17,7 @@ namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedC
public class LibrarySavedDomainEventTests
{
private readonly LibraryFixture _libraryFixture = new();
private readonly LibrarySavedDomainEventFixture _librarySavedDomainEventFixture = new();
[Fact]
public void Constructor_WhenCalled_ShouldSetAllProperties()
@@ -26,7 +28,7 @@ public class LibrarySavedDomainEventTests
DateTime occurredOnUtc = DateTime.UtcNow;
// Act
LibrarySavedDomainEvent domainEvent = new(id, library, occurredOnUtc);
LibrarySavedDomainEvent domainEvent = _librarySavedDomainEventFixture.Create(id, library, occurredOnUtc);
// Assert
Assert.Equal(id, domainEvent.Id);
@@ -4,6 +4,7 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using System;
using System.Diagnostics.CodeAnalysis;
@@ -19,6 +20,7 @@ public class LibraryMediaItemDeletedDomainEventTests
{
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new();
private readonly LibraryMediaItemDeletedDomainEventFixture _libraryMediaItemDeletedDomainEventFixture = new();
[Fact]
public void Constructor_WhenCalled_ShouldSetAllProperties()
@@ -31,7 +33,7 @@ public class LibraryMediaItemDeletedDomainEventTests
DateTime occurredOnUtc = DateTime.UtcNow;
// Act
LibraryMediaItemDeletedDomainEvent domainEvent = new(id, libraryId, compositeId, path, occurredOnUtc);
LibraryMediaItemDeletedDomainEvent domainEvent = _libraryMediaItemDeletedDomainEventFixture.Create(id, libraryId, compositeId, path, occurredOnUtc);
// Assert
Assert.Equal(id, domainEvent.Id);
@@ -4,6 +4,7 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using System;
using System.Diagnostics.CodeAnalysis;
@@ -19,6 +20,7 @@ public class LibraryScanCancelledDomainEventTests
{
private readonly ScanIdFixture _scanIdFixture = new();
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly LibraryScanCancelledDomainEventFixture _libraryScanCancelledDomainEventFixture = new();
[Fact]
public void Constructor_WhenCalled_ShouldSetAllProperties()
@@ -30,7 +32,7 @@ public class LibraryScanCancelledDomainEventTests
DateTime occurredOnUtc = DateTime.UtcNow;
// Act
LibraryScanCancelledDomainEvent domainEvent = new(id, scanId, libraryId, occurredOnUtc);
LibraryScanCancelledDomainEvent domainEvent = _libraryScanCancelledDomainEventFixture.Create(id, scanId, libraryId, occurredOnUtc);
// Assert
Assert.Equal(id, domainEvent.Id);
@@ -4,6 +4,7 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using System;
using System.Diagnostics.CodeAnalysis;
@@ -19,6 +20,7 @@ public class LibraryScanFailedDomainEventTests
{
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new();
private readonly LibraryScanFailedDomainEventFixture _libraryScanFailedDomainEventFixture = new();
[Fact]
public void Constructor_WhenCalledWithErrorMessage_ShouldSetAllProperties()
@@ -31,7 +33,12 @@ public class LibraryScanFailedDomainEventTests
string errorMessage = "Scan failed unexpectedly.";
// Act
LibraryScanFailedDomainEvent domainEvent = new(id, libraryId, compositeId, occurredOnUtc, errorMessage);
LibraryScanFailedDomainEvent domainEvent = _libraryScanFailedDomainEventFixture.Create(
id: id,
libraryId: libraryId,
mediaLibraryScanCompositeId: compositeId,
occurredOnUtc: occurredOnUtc,
errorMessage: errorMessage);
// Assert
Assert.Equal(id, domainEvent.Id);
@@ -46,11 +53,7 @@ public class LibraryScanFailedDomainEventTests
public void Constructor_WhenCalledWithoutErrorMessage_ShouldDefaultErrorMessageToNull()
{
// Act
LibraryScanFailedDomainEvent domainEvent = new(
Guid.NewGuid(),
_libraryIdFixture.Create(),
_mediaLibraryScanCompositeIdFixture.Create(),
DateTime.UtcNow);
LibraryScanFailedDomainEvent domainEvent = _libraryScanFailedDomainEventFixture.Create(includeErrorMessage: false);
// Assert
Assert.Null(domainEvent.ErrorMessage);
Loaded 100 of 135 files, more files were not shown because too many files have changed in this diff. Show more