mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-02 23:11:10 +00:00
Adds the scheduling module tests and centralizes domain event test fixtures
This commit is contained in:
1 parent
237be9e2c8
commit
99a6159f7f
135 files changed
+10203
-165
No files matched your search
+43
@@ -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);
|
||||
}
|
||||
}
|
||||
+34
@@ -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);
|
||||
}
|
||||
}
|
||||
+36
@@ -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);
|
||||
}
|
||||
}
|
||||
+34
@@ -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);
|
||||
}
|
||||
}
|
||||
+169
@@ -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);
|
||||
}
|
||||
}
|
||||
+62
@@ -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);
|
||||
}
|
||||
}
|
||||
+117
@@ -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);
|
||||
}
|
||||
}
|
||||
+59
@@ -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);
|
||||
}
|
||||
}
|
||||
+34
@@ -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);
|
||||
}
|
||||
}
|
||||
+34
@@ -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);
|
||||
}
|
||||
}
|
||||
+38
@@ -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);
|
||||
}
|
||||
}
|
||||
+5
-3
@@ -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);
|
||||
|
||||
|
||||
+7
-35
@@ -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>(
|
||||
|
||||
+13
-11
@@ -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);
|
||||
|
||||
+16
-12
@@ -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");
|
||||
|
||||
+25
-31
@@ -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");
|
||||
|
||||
+20
-27
@@ -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");
|
||||
|
||||
+5
-6
@@ -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
|
||||
|
||||
+5
-7
@@ -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
|
||||
|
||||
+12
-10
@@ -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
-8
@@ -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);
|
||||
|
||||
+256
@@ -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>());
|
||||
}
|
||||
}
|
||||
+195
@@ -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();
|
||||
}
|
||||
}
|
||||
+213
@@ -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>());
|
||||
}
|
||||
}
|
||||
+48
@@ -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();
|
||||
}
|
||||
}
|
||||
+219
@@ -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>());
|
||||
}
|
||||
}
|
||||
+48
@@ -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();
|
||||
}
|
||||
}
|
||||
+203
@@ -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>());
|
||||
}
|
||||
}
|
||||
+48
@@ -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();
|
||||
}
|
||||
}
|
||||
+217
@@ -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>());
|
||||
}
|
||||
}
|
||||
+48
@@ -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();
|
||||
}
|
||||
}
|
||||
+152
@@ -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>());
|
||||
}
|
||||
}
|
||||
+66
@@ -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();
|
||||
}
|
||||
}
|
||||
+86
@@ -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>());
|
||||
}
|
||||
}
|
||||
+82
@@ -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>());
|
||||
}
|
||||
}
|
||||
+84
@@ -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>());
|
||||
}
|
||||
}
|
||||
+200
@@ -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>());
|
||||
}
|
||||
}
|
||||
+191
@@ -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>());
|
||||
}
|
||||
}
|
||||
+153
@@ -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>());
|
||||
}
|
||||
}
|
||||
+46
@@ -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>());
|
||||
}
|
||||
}
|
||||
+84
@@ -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>());
|
||||
}
|
||||
}
|
||||
+161
@@ -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);
|
||||
}
|
||||
}
|
||||
+132
@@ -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);
|
||||
}
|
||||
}
|
||||
+142
@@ -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);
|
||||
}
|
||||
}
|
||||
+237
@@ -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);
|
||||
}
|
||||
}
|
||||
+211
@@ -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);
|
||||
}
|
||||
}
|
||||
+123
@@ -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
-1
@@ -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
-1
@@ -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);
|
||||
|
||||
+3
-1
@@ -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);
|
||||
|
||||
+3
-1
@@ -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);
|
||||
|
||||
+9
-6
@@ -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);
|
||||
|
||||
+3
-1
@@ -2,6 +2,7 @@
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.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;
|
||||
@@ -16,6 +17,7 @@ namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedC
|
||||
public class LibraryScanFinishedDomainEventTests
|
||||
{
|
||||
private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new();
|
||||
private readonly LibraryScanFinishedDomainEventFixture _libraryScanFinishedDomainEventFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenCalled_ShouldSetAllProperties()
|
||||
@@ -26,7 +28,7 @@ public class LibraryScanFinishedDomainEventTests
|
||||
DateTime occurredOnUtc = DateTime.UtcNow;
|
||||
|
||||
// Act
|
||||
LibraryScanFinishedDomainEvent domainEvent = new(id, compositeId, occurredOnUtc);
|
||||
LibraryScanFinishedDomainEvent domainEvent = _libraryScanFinishedDomainEventFixture.Create(id, compositeId, occurredOnUtc);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(id, domainEvent.Id);
|
||||
|
||||
+3
-1
@@ -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;
|
||||
@@ -20,6 +21,7 @@ public class LibraryScanJobProgressChangedDomainEventTests
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new();
|
||||
private readonly MediaLibraryScanJobProgressFixture _mediaLibraryScanJobProgressFixture = new();
|
||||
private readonly LibraryScanJobProgressChangedDomainEventFixture _libraryScanJobProgressChangedDomainEventFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenCalled_ShouldSetAllProperties()
|
||||
@@ -32,7 +34,7 @@ public class LibraryScanJobProgressChangedDomainEventTests
|
||||
DateTime occurredOnUtc = DateTime.UtcNow;
|
||||
|
||||
// Act
|
||||
LibraryScanJobProgressChangedDomainEvent domainEvent = new(id, libraryId, compositeId, progress, occurredOnUtc);
|
||||
LibraryScanJobProgressChangedDomainEvent domainEvent = _libraryScanJobProgressChangedDomainEventFixture.Create(id, libraryId, compositeId, progress, occurredOnUtc);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(id, domainEvent.Id);
|
||||
|
||||
+3
-1
@@ -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 LibraryScanProgressChangedDomainEventTests
|
||||
{
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new();
|
||||
private readonly LibraryScanProgressChangedDomainEventFixture _libraryScanProgressChangedDomainEventFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenCalled_ShouldSetAllProperties()
|
||||
@@ -30,7 +32,7 @@ public class LibraryScanProgressChangedDomainEventTests
|
||||
DateTime occurredOnUtc = DateTime.UtcNow;
|
||||
|
||||
// Act
|
||||
LibraryScanProgressChangedDomainEvent domainEvent = new(id, libraryId, compositeId, occurredOnUtc);
|
||||
LibraryScanProgressChangedDomainEvent domainEvent = _libraryScanProgressChangedDomainEventFixture.Create(id, libraryId, compositeId, occurredOnUtc);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(id, domainEvent.Id);
|
||||
|
||||
+3
-1
@@ -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 LibraryScanQueuedDomainEventTests
|
||||
{
|
||||
private readonly ScanIdFixture _scanIdFixture = new();
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly LibraryScanQueuedDomainEventFixture _libraryScanQueuedDomainEventFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenCalled_ShouldSetAllProperties()
|
||||
@@ -30,7 +32,7 @@ public class LibraryScanQueuedDomainEventTests
|
||||
DateTime occurredOnUtc = DateTime.UtcNow;
|
||||
|
||||
// Act
|
||||
LibraryScanQueuedDomainEvent domainEvent = new(id, scanId, libraryId, occurredOnUtc);
|
||||
LibraryScanQueuedDomainEvent domainEvent = _libraryScanQueuedDomainEventFixture.Create(id, scanId, libraryId, occurredOnUtc);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(id, domainEvent.Id);
|
||||
|
||||
+3
-1
@@ -3,6 +3,7 @@ using Lumina.Domain.Common.Events;
|
||||
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 System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
@@ -16,6 +17,7 @@ namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedC
|
||||
public class LibraryScanStartedDomainEventTests
|
||||
{
|
||||
private readonly LibraryScanFixture _libraryScanFixture = new();
|
||||
private readonly LibraryScanStartedDomainEventFixture _libraryScanStartedDomainEventFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenCalled_ShouldSetAllProperties()
|
||||
@@ -26,7 +28,7 @@ public class LibraryScanStartedDomainEventTests
|
||||
DateTime occurredOnUtc = DateTime.UtcNow;
|
||||
|
||||
// Act
|
||||
LibraryScanStartedDomainEvent domainEvent = new(id, scan, occurredOnUtc);
|
||||
LibraryScanStartedDomainEvent domainEvent = _libraryScanStartedDomainEventFixture.Create(id, scan, occurredOnUtc);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(id, domainEvent.Id);
|
||||
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.SchedulingBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="UserId"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UserIdTests
|
||||
{
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void CreateUnique_WhenCalled_ShouldReturnIdWithNonEmptyValue()
|
||||
{
|
||||
// Act
|
||||
UserId userId = UserId.CreateUnique();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(userId);
|
||||
Assert.NotEqual(default, userId.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithValue_ShouldReturnIdWithThatValue()
|
||||
{
|
||||
// Arrange
|
||||
Guid value = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
UserId userId = UserId.Create(value);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(value, userId.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithSameValue_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
Guid value = Guid.NewGuid();
|
||||
UserId firstId = _userIdFixture.Create(value);
|
||||
UserId secondId = _userIdFixture.Create(value);
|
||||
|
||||
// Act
|
||||
bool result = firstId.Equals(secondId);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentValue_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
UserId firstId = _userIdFixture.Create();
|
||||
UserId secondId = _userIdFixture.Create();
|
||||
|
||||
// Act
|
||||
bool result = firstId.Equals(secondId);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ScheduledJobAddedDomainEvent"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ScheduledJobAddedDomainEventTests
|
||||
{
|
||||
private readonly ScheduledJobIdFixture _scheduledJobIdFixture = new();
|
||||
private readonly ScheduledJobAddedDomainEventFixture _scheduledJobAddedDomainEventFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenCalled_ShouldSetAllProperties()
|
||||
{
|
||||
// Arrange
|
||||
Guid id = Guid.NewGuid();
|
||||
ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create();
|
||||
DateTime occurredOnUtc = DateTime.UtcNow;
|
||||
|
||||
// Act
|
||||
ScheduledJobAddedDomainEvent domainEvent = _scheduledJobAddedDomainEventFixture.Create(id, scheduledJobId, occurredOnUtc);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(id, domainEvent.Id);
|
||||
Assert.Equal(scheduledJobId, domainEvent.ScheduledJobId);
|
||||
Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc);
|
||||
Assert.IsType<IDomainEvent>(domainEvent, exactMatch: false);
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ScheduledJobCycleStartedDomainEvent"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ScheduledJobCycleStartedDomainEventTests
|
||||
{
|
||||
private readonly ScheduledJobIdFixture _scheduledJobIdFixture = new();
|
||||
private readonly ScheduledJobCycleStartedDomainEventFixture _scheduledJobCycleStartedDomainEventFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenCalled_ShouldSetAllProperties()
|
||||
{
|
||||
// Arrange
|
||||
Guid id = Guid.NewGuid();
|
||||
ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create();
|
||||
DateTime occurredOnUtc = DateTime.UtcNow;
|
||||
|
||||
// Act
|
||||
ScheduledJobCycleStartedDomainEvent domainEvent = _scheduledJobCycleStartedDomainEventFixture.Create(id, scheduledJobId, occurredOnUtc);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(id, domainEvent.Id);
|
||||
Assert.Equal(scheduledJobId, domainEvent.ScheduledJobId);
|
||||
Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc);
|
||||
Assert.IsType<IDomainEvent>(domainEvent, exactMatch: false);
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ScheduledJobCycleStoppedDomainEvent"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ScheduledJobCycleStoppedDomainEventTests
|
||||
{
|
||||
private readonly ScheduledJobIdFixture _scheduledJobIdFixture = new();
|
||||
private readonly ScheduledJobCycleStoppedDomainEventFixture _scheduledJobCycleStoppedDomainEventFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenCalled_ShouldSetAllProperties()
|
||||
{
|
||||
// Arrange
|
||||
Guid id = Guid.NewGuid();
|
||||
ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create();
|
||||
DateTime occurredOnUtc = DateTime.UtcNow;
|
||||
|
||||
// Act
|
||||
ScheduledJobCycleStoppedDomainEvent domainEvent = _scheduledJobCycleStoppedDomainEventFixture.Create(id, scheduledJobId, occurredOnUtc);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(id, domainEvent.Id);
|
||||
Assert.Equal(scheduledJobId, domainEvent.ScheduledJobId);
|
||||
Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc);
|
||||
Assert.IsType<IDomainEvent>(domainEvent, exactMatch: false);
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
|
||||
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.UnitTests.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ScheduledJobExecutionCompletedDomainEvent"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ScheduledJobExecutionCompletedDomainEventTests
|
||||
{
|
||||
private readonly ScheduledJobIdFixture _scheduledJobIdFixture = new();
|
||||
private readonly ScheduledJobExecutionCompletedDomainEventFixture _scheduledJobExecutionCompletedDomainEventFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenCalled_ShouldSetAllProperties()
|
||||
{
|
||||
// Arrange
|
||||
Guid id = Guid.NewGuid();
|
||||
ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create();
|
||||
Guid runId = Guid.NewGuid();
|
||||
ScheduledTaskType taskType = ScheduledTaskType.CleanTemporaryFiles;
|
||||
bool isCycleRun = false;
|
||||
DateTime completedOnUtc = DateTime.UtcNow;
|
||||
|
||||
// Act
|
||||
ScheduledJobExecutionCompletedDomainEvent domainEvent = _scheduledJobExecutionCompletedDomainEventFixture.Create(id, scheduledJobId, runId, taskType, isCycleRun, completedOnUtc);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(id, domainEvent.Id);
|
||||
Assert.Equal(scheduledJobId, domainEvent.ScheduledJobId);
|
||||
Assert.Equal(runId, domainEvent.RunId);
|
||||
Assert.Equal(taskType, domainEvent.TaskType);
|
||||
Assert.Equal(isCycleRun, domainEvent.IsCycleRun);
|
||||
Assert.Equal(completedOnUtc, domainEvent.CompletedOnUtc);
|
||||
Assert.Equal(completedOnUtc, domainEvent.OccurredOnUtc);
|
||||
Assert.IsType<IDomainEvent>(domainEvent, exactMatch: false);
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
|
||||
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.UnitTests.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ScheduledJobExecutionStartedDomainEvent"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ScheduledJobExecutionStartedDomainEventTests
|
||||
{
|
||||
private readonly ScheduledJobIdFixture _scheduledJobIdFixture = new();
|
||||
private readonly ScheduledJobExecutionStartedDomainEventFixture _scheduledJobExecutionStartedDomainEventFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenCalled_ShouldSetAllProperties()
|
||||
{
|
||||
// Arrange
|
||||
Guid id = Guid.NewGuid();
|
||||
ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create();
|
||||
Guid runId = Guid.NewGuid();
|
||||
ScheduledTaskType taskType = ScheduledTaskType.ScanMediaLibraries;
|
||||
bool isCycleRun = true;
|
||||
DateTime startedOnUtc = DateTime.UtcNow;
|
||||
|
||||
// Act
|
||||
ScheduledJobExecutionStartedDomainEvent domainEvent = _scheduledJobExecutionStartedDomainEventFixture.Create(id, scheduledJobId, runId, taskType, isCycleRun, startedOnUtc);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(id, domainEvent.Id);
|
||||
Assert.Equal(scheduledJobId, domainEvent.ScheduledJobId);
|
||||
Assert.Equal(runId, domainEvent.RunId);
|
||||
Assert.Equal(taskType, domainEvent.TaskType);
|
||||
Assert.Equal(isCycleRun, domainEvent.IsCycleRun);
|
||||
Assert.Equal(startedOnUtc, domainEvent.StartedOnUtc);
|
||||
Assert.Equal(startedOnUtc, domainEvent.OccurredOnUtc);
|
||||
Assert.IsType<IDomainEvent>(domainEvent, exactMatch: false);
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ScheduledJobExecutionStoppedDomainEvent"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ScheduledJobExecutionStoppedDomainEventTests
|
||||
{
|
||||
private readonly ScheduledJobIdFixture _scheduledJobIdFixture = new();
|
||||
private readonly ScheduledJobExecutionStoppedDomainEventFixture _scheduledJobExecutionStoppedDomainEventFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenCalled_ShouldSetAllProperties()
|
||||
{
|
||||
// Arrange
|
||||
Guid id = Guid.NewGuid();
|
||||
ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create();
|
||||
DateTime occurredOnUtc = DateTime.UtcNow;
|
||||
|
||||
// Act
|
||||
ScheduledJobExecutionStoppedDomainEvent domainEvent = _scheduledJobExecutionStoppedDomainEventFixture.Create(id, scheduledJobId, occurredOnUtc);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(id, domainEvent.Id);
|
||||
Assert.Equal(scheduledJobId, domainEvent.ScheduledJobId);
|
||||
Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc);
|
||||
Assert.IsType<IDomainEvent>(domainEvent, exactMatch: false);
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ScheduledJobFiredDomainEvent"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ScheduledJobFiredDomainEventTests
|
||||
{
|
||||
private readonly ScheduledJobIdFixture _scheduledJobIdFixture = new();
|
||||
private readonly ScheduledJobFiredDomainEventFixture _scheduledJobFiredDomainEventFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenCalled_ShouldSetAllProperties()
|
||||
{
|
||||
// Arrange
|
||||
Guid id = Guid.NewGuid();
|
||||
ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create();
|
||||
DateTime occurredOnUtc = DateTime.UtcNow;
|
||||
|
||||
// Act
|
||||
ScheduledJobFiredDomainEvent domainEvent = _scheduledJobFiredDomainEventFixture.Create(id, scheduledJobId, occurredOnUtc);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(id, domainEvent.Id);
|
||||
Assert.Equal(scheduledJobId, domainEvent.ScheduledJobId);
|
||||
Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc);
|
||||
Assert.IsType<IDomainEvent>(domainEvent, exactMatch: false);
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ScheduledJobRemovedDomainEvent"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ScheduledJobRemovedDomainEventTests
|
||||
{
|
||||
private readonly ScheduledJobIdFixture _scheduledJobIdFixture = new();
|
||||
private readonly ScheduledJobRemovedDomainEventFixture _scheduledJobRemovedDomainEventFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenCalled_ShouldSetAllProperties()
|
||||
{
|
||||
// Arrange
|
||||
Guid id = Guid.NewGuid();
|
||||
ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create();
|
||||
DateTime occurredOnUtc = DateTime.UtcNow;
|
||||
|
||||
// Act
|
||||
ScheduledJobRemovedDomainEvent domainEvent = _scheduledJobRemovedDomainEventFixture.Create(id, scheduledJobId, occurredOnUtc);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(id, domainEvent.Id);
|
||||
Assert.Equal(scheduledJobId, domainEvent.ScheduledJobId);
|
||||
Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc);
|
||||
Assert.IsType<IDomainEvent>(domainEvent, exactMatch: false);
|
||||
}
|
||||
}
|
||||
+406
@@ -0,0 +1,406 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Errors;
|
||||
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.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ScheduledJob"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ScheduledJobTests
|
||||
{
|
||||
private readonly ScheduledJobFixture _scheduledJobFixture = new();
|
||||
private readonly IntervalScheduleFixture _intervalScheduleFixture = new();
|
||||
private readonly DailyScheduleFixture _dailyScheduleFixture = new();
|
||||
private readonly ScheduledJobIdFixture _scheduledJobIdFixture = new();
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithValidData_ShouldCreateAddedScheduledJobWithAllPropertiesSet()
|
||||
{
|
||||
// Arrange
|
||||
string name = "Scan libraries every hour";
|
||||
ScheduledTaskType taskType = ScheduledTaskType.ScanMediaLibraries;
|
||||
IntervalSchedule schedule = _intervalScheduleFixture.Create(intervalMinutes: 60);
|
||||
UserId ownerUserId = _userIdFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<ScheduledJob> result = ScheduledJob.Create(name, taskType, schedule, ownerUserId);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(name, result.Value.Name);
|
||||
Assert.Equal(taskType, result.Value.TaskType);
|
||||
Assert.Equal(schedule, result.Value.Schedule);
|
||||
Assert.Equal(ownerUserId, result.Value.OwnerUserId);
|
||||
Assert.Equal(ScheduledJobStatus.Added, result.Value.Status);
|
||||
Assert.False(result.Value.LastStartedOnUtc.HasValue);
|
||||
Assert.False(result.Value.LastCompletedOnUtc.HasValue);
|
||||
Assert.Empty(result.Value.GetDomainEvents());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledTwice_ShouldGenerateDistinctIds()
|
||||
{
|
||||
// Act
|
||||
Result<ScheduledJob> firstResult = ScheduledJob.Create("Job 1", ScheduledTaskType.ScanMediaLibraries, _intervalScheduleFixture.Create(), _userIdFixture.Create());
|
||||
Result<ScheduledJob> secondResult = ScheduledJob.Create("Job 2", ScheduledTaskType.ScanMediaLibraries, _intervalScheduleFixture.Create(), _userIdFixture.Create());
|
||||
|
||||
// Assert
|
||||
Assert.False(firstResult.IsFailure);
|
||||
Assert.False(secondResult.IsFailure);
|
||||
Assert.NotEqual(firstResult.Value.Id.Value, secondResult.Value.Id.Value);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // null name
|
||||
[InlineData("")] // empty name
|
||||
[InlineData(" ")] // whitespace name
|
||||
public void Create_WhenNameIsEmptyOrWhitespace_ShouldReturnError(string? name)
|
||||
{
|
||||
// Act
|
||||
Result<ScheduledJob> result = ScheduledJob.Create(name!, ScheduledTaskType.ScanMediaLibraries, _intervalScheduleFixture.Create(), _userIdFixture.Create());
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Scheduling.ScheduledJobNameCannotBeEmpty, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithPreExistingIdAndData_ShouldCreateScheduledJobWithThatIdAndState()
|
||||
{
|
||||
// Arrange
|
||||
Guid id = Guid.NewGuid();
|
||||
DateTime lastStartedOnUtc = DateTime.UtcNow.AddHours(-1);
|
||||
DateTime lastCompletedOnUtc = DateTime.UtcNow.AddMinutes(-30);
|
||||
|
||||
// Act
|
||||
Result<ScheduledJob> result = ScheduledJob.Create(
|
||||
_scheduledJobIdFixture.Create(id),
|
||||
"Daily cleanup",
|
||||
ScheduledTaskType.CleanTemporaryFiles,
|
||||
_dailyScheduleFixture.Create(hour: 3, minute: 0),
|
||||
_userIdFixture.Create(),
|
||||
ScheduledJobStatus.Active,
|
||||
Optional<DateTime>.Some(lastStartedOnUtc),
|
||||
Optional<DateTime>.Some(lastCompletedOnUtc));
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(id, result.Value.Id.Value);
|
||||
Assert.Equal(ScheduledJobStatus.Active, result.Value.Status);
|
||||
Assert.Equal(lastStartedOnUtc, result.Value.LastStartedOnUtc.Value);
|
||||
Assert.Equal(lastCompletedOnUtc, result.Value.LastCompletedOnUtc.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Add_WhenStatusIsAdded_ShouldSucceedAndRaiseAddedEvent()
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJob scheduledJob = _scheduledJobFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Success> result = scheduledJob.Add();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Success, result.Value);
|
||||
Assert.Equal(ScheduledJobStatus.Added, scheduledJob.Status);
|
||||
ScheduledJobAddedDomainEvent addedEvent = Assert.IsType<ScheduledJobAddedDomainEvent>(Assert.Single(scheduledJob.GetDomainEvents()));
|
||||
Assert.Equal(scheduledJob.Id, addedEvent.ScheduledJobId);
|
||||
Assert.NotEqual(default, addedEvent.OccurredOnUtc);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(ScheduledJobStatus.Active)] // cannot add an already active scheduled job
|
||||
[InlineData(ScheduledJobStatus.Running)] // cannot add a running scheduled job
|
||||
[InlineData(ScheduledJobStatus.Completed)] // cannot add a completed scheduled job
|
||||
public void Add_WhenStatusIsNotAdded_ShouldReturnError(ScheduledJobStatus status)
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJob scheduledJob = _scheduledJobFixture.Create(status: status);
|
||||
|
||||
// Act
|
||||
Result<Success> result = scheduledJob.Add();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Scheduling.ScheduledJobCycleAlreadyStarted, result.FirstError);
|
||||
Assert.Empty(scheduledJob.GetDomainEvents());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void StartCycle_WhenStatusIsAdded_ShouldTransitionToActiveAndRaiseCycleStartedEvent()
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJob scheduledJob = _scheduledJobFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Success> result = scheduledJob.StartCycle();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Success, result.Value);
|
||||
Assert.Equal(ScheduledJobStatus.Active, scheduledJob.Status);
|
||||
ScheduledJobCycleStartedDomainEvent cycleStartedEvent = Assert.IsType<ScheduledJobCycleStartedDomainEvent>(Assert.Single(scheduledJob.GetDomainEvents()));
|
||||
Assert.Equal(scheduledJob.Id, cycleStartedEvent.ScheduledJobId);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(ScheduledJobStatus.Active)] // cannot start an already active execution cycle
|
||||
[InlineData(ScheduledJobStatus.Running)] // cannot start a running execution cycle
|
||||
public void StartCycle_WhenCycleAlreadyStarted_ShouldReturnError(ScheduledJobStatus status)
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJob scheduledJob = _scheduledJobFixture.Create(status: status);
|
||||
|
||||
// Act
|
||||
Result<Success> result = scheduledJob.StartCycle();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Scheduling.ScheduledJobCycleAlreadyStarted, result.FirstError);
|
||||
Assert.Equal(status, scheduledJob.Status);
|
||||
Assert.Empty(scheduledJob.GetDomainEvents());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void StopCycle_WhenStatusIsActive_ShouldTransitionToAddedAndRaiseCycleStoppedEvent()
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJob scheduledJob = _scheduledJobFixture.Create();
|
||||
scheduledJob.StartCycle();
|
||||
scheduledJob.GetDomainEvents();
|
||||
|
||||
// Act
|
||||
Result<Success> result = scheduledJob.StopCycle();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Success, result.Value);
|
||||
Assert.Equal(ScheduledJobStatus.Added, scheduledJob.Status);
|
||||
ScheduledJobCycleStoppedDomainEvent cycleStoppedEvent = Assert.IsType<ScheduledJobCycleStoppedDomainEvent>(Assert.Single(scheduledJob.GetDomainEvents()));
|
||||
Assert.Equal(scheduledJob.Id, cycleStoppedEvent.ScheduledJobId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void StopCycle_WhenStatusIsRunning_ShouldTransitionToAddedAndRaiseExecutionStoppedEvent()
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJob scheduledJob = _scheduledJobFixture.Create();
|
||||
scheduledJob.StartCycle();
|
||||
scheduledJob.MarkExecutionStarted(isCycleRun: true);
|
||||
scheduledJob.GetDomainEvents();
|
||||
|
||||
// Act
|
||||
Result<Success> result = scheduledJob.StopCycle();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Success, result.Value);
|
||||
Assert.Equal(ScheduledJobStatus.Added, scheduledJob.Status);
|
||||
Assert.True(scheduledJob.LastCompletedOnUtc.HasValue);
|
||||
ScheduledJobExecutionStoppedDomainEvent executionStoppedEvent = Assert.IsType<ScheduledJobExecutionStoppedDomainEvent>(Assert.Single(scheduledJob.GetDomainEvents()));
|
||||
Assert.Equal(scheduledJob.Id, executionStoppedEvent.ScheduledJobId);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(ScheduledJobStatus.Added)] // cannot stop a cycle that was never started
|
||||
[InlineData(ScheduledJobStatus.Completed)] // cannot stop a finished one time execution
|
||||
public void StopCycle_WhenCycleWasNeverStarted_ShouldReturnError(ScheduledJobStatus status)
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJob scheduledJob = _scheduledJobFixture.Create(status: status);
|
||||
|
||||
// Act
|
||||
Result<Success> result = scheduledJob.StopCycle();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Scheduling.ScheduledJobNotStarted, result.FirstError);
|
||||
Assert.Equal(status, scheduledJob.Status);
|
||||
Assert.Empty(scheduledJob.GetDomainEvents());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fire_WhenStatusIsNotRunning_ShouldSucceedAndRaiseFiredEvent()
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJob scheduledJob = _scheduledJobFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Success> result = scheduledJob.Fire();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Success, result.Value);
|
||||
ScheduledJobFiredDomainEvent firedEvent = Assert.IsType<ScheduledJobFiredDomainEvent>(Assert.Single(scheduledJob.GetDomainEvents()));
|
||||
Assert.Equal(scheduledJob.Id, firedEvent.ScheduledJobId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fire_WhenStatusIsRunning_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJob scheduledJob = _scheduledJobFixture.Create();
|
||||
scheduledJob.StartCycle();
|
||||
scheduledJob.MarkExecutionStarted(isCycleRun: true);
|
||||
scheduledJob.GetDomainEvents();
|
||||
|
||||
// Act
|
||||
Result<Success> result = scheduledJob.Fire();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Scheduling.ScheduledJobAlreadyRunning, result.FirstError);
|
||||
Assert.Empty(scheduledJob.GetDomainEvents());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Remove_WhenCalled_ShouldSucceedAndRaiseRemovedEvent()
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJob scheduledJob = _scheduledJobFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Success> result = scheduledJob.Remove();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Success, result.Value);
|
||||
ScheduledJobRemovedDomainEvent removedEvent = Assert.IsType<ScheduledJobRemovedDomainEvent>(Assert.Single(scheduledJob.GetDomainEvents()));
|
||||
Assert.Equal(scheduledJob.Id, removedEvent.ScheduledJobId);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(true)] // cycle run
|
||||
[InlineData(false)] // one time run
|
||||
public void MarkExecutionStarted_WhenStatusIsNotRunning_ShouldTransitionToRunningAndRaiseExecutionStartedEvent(bool isCycleRun)
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJob scheduledJob = _scheduledJobFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Success> result = scheduledJob.MarkExecutionStarted(isCycleRun);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Success, result.Value);
|
||||
Assert.Equal(ScheduledJobStatus.Running, scheduledJob.Status);
|
||||
Assert.True(scheduledJob.LastStartedOnUtc.HasValue);
|
||||
ScheduledJobExecutionStartedDomainEvent startedEvent = Assert.IsType<ScheduledJobExecutionStartedDomainEvent>(Assert.Single(scheduledJob.GetDomainEvents()));
|
||||
Assert.Equal(scheduledJob.Id, startedEvent.ScheduledJobId);
|
||||
Assert.Equal(scheduledJob.TaskType, startedEvent.TaskType);
|
||||
Assert.Equal(isCycleRun, startedEvent.IsCycleRun);
|
||||
Assert.NotEqual(Guid.Empty, startedEvent.RunId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MarkExecutionStarted_WhenStatusIsRunning_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJob scheduledJob = _scheduledJobFixture.Create();
|
||||
scheduledJob.StartCycle();
|
||||
scheduledJob.MarkExecutionStarted(isCycleRun: true);
|
||||
scheduledJob.GetDomainEvents();
|
||||
|
||||
// Act
|
||||
Result<Success> result = scheduledJob.MarkExecutionStarted(isCycleRun: true);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Scheduling.ScheduledJobAlreadyRunning, result.FirstError);
|
||||
Assert.Empty(scheduledJob.GetDomainEvents());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(true)] // a cycle run returns the scheduled job to its active status
|
||||
[InlineData(false)] // a one time execution completes the scheduled job
|
||||
public void MarkExecutionCompleted_WhenStatusIsRunning_ShouldTransitionStatusAndRaiseExecutionCompletedEvent(bool isCycleRun)
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJob scheduledJob = _scheduledJobFixture.Create();
|
||||
scheduledJob.StartCycle();
|
||||
scheduledJob.MarkExecutionStarted(isCycleRun);
|
||||
scheduledJob.GetDomainEvents();
|
||||
|
||||
// Act
|
||||
Result<Success> result = scheduledJob.MarkExecutionCompleted(isCycleRun);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Success, result.Value);
|
||||
Assert.Equal(isCycleRun ? ScheduledJobStatus.Active : ScheduledJobStatus.Completed, scheduledJob.Status);
|
||||
Assert.True(scheduledJob.LastCompletedOnUtc.HasValue);
|
||||
ScheduledJobExecutionCompletedDomainEvent completedEvent = Assert.IsType<ScheduledJobExecutionCompletedDomainEvent>(Assert.Single(scheduledJob.GetDomainEvents()));
|
||||
Assert.Equal(scheduledJob.Id, completedEvent.ScheduledJobId);
|
||||
Assert.Equal(scheduledJob.TaskType, completedEvent.TaskType);
|
||||
Assert.Equal(isCycleRun, completedEvent.IsCycleRun);
|
||||
Assert.NotEqual(Guid.Empty, completedEvent.RunId);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(ScheduledJobStatus.Added)] // cannot complete an execution that never started
|
||||
[InlineData(ScheduledJobStatus.Active)] // cannot complete an execution that never started
|
||||
[InlineData(ScheduledJobStatus.Completed)] // cannot complete an already completed execution
|
||||
public void MarkExecutionCompleted_WhenStatusIsNotRunning_ShouldReturnError(ScheduledJobStatus status)
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJob scheduledJob = _scheduledJobFixture.Create(status: status);
|
||||
|
||||
// Act
|
||||
Result<Success> result = scheduledJob.MarkExecutionCompleted(isCycleRun: true);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Scheduling.CanOnlyCompleteRunningScheduledJob, result.FirstError);
|
||||
Assert.Empty(scheduledJob.GetDomainEvents());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MarkExecutionCompleted_WhenLoadedFromStorageWithoutActiveRunId_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
// A scheduled job loaded from the storage medium with a running status has no active run id tracked by the aggregate.
|
||||
ScheduledJob scheduledJob = _scheduledJobFixture.Create(
|
||||
id: Guid.NewGuid(),
|
||||
status: ScheduledJobStatus.Running,
|
||||
lastStartedOnUtc: DateTime.UtcNow.AddMinutes(-5));
|
||||
|
||||
// Act
|
||||
Result<Success> result = scheduledJob.MarkExecutionCompleted(isCycleRun: true);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Scheduling.CanOnlyCompleteRunningScheduledJob, result.FirstError);
|
||||
Assert.Empty(scheduledJob.GetDomainEvents());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MarkExecutionCompleted_WhenCycleRunAfterExecutionStarted_ShouldAllowTheNextCycleRunToStart()
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJob scheduledJob = _scheduledJobFixture.Create();
|
||||
scheduledJob.StartCycle();
|
||||
scheduledJob.MarkExecutionStarted(isCycleRun: true);
|
||||
scheduledJob.MarkExecutionCompleted(isCycleRun: true);
|
||||
|
||||
// Act
|
||||
Result<Success> startNextExecutionResult = scheduledJob.MarkExecutionStarted(isCycleRun: true);
|
||||
// Assert
|
||||
Assert.False(startNextExecutionResult.IsFailure);
|
||||
Assert.Equal(ScheduledJobStatus.Running, scheduledJob.Status);
|
||||
}
|
||||
}
|
||||
+155
@@ -0,0 +1,155 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="DailySchedule"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DailyScheduleTests
|
||||
{
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithValidHourAndMinute_ShouldCreateDailyScheduleWithAllPropertiesSet()
|
||||
{
|
||||
// Act
|
||||
Result<DailySchedule> result = DailySchedule.Create(8, 30);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(8, result.Value.Hour);
|
||||
Assert.Equal(30, result.Value.Minute);
|
||||
Assert.Equal(ScheduleType.DailyAtHourAndMinute, result.Value.ScheduleType);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(-1)] // hour below the allowed range
|
||||
[InlineData(24)] // hour above the allowed range
|
||||
public void Create_WhenHourIsOutOfRange_ShouldReturnError(int hour)
|
||||
{
|
||||
// Act
|
||||
Result<DailySchedule> result = DailySchedule.Create(hour, 0);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Scheduling.HourMustBeBetweenZeroAndTwentyThree, result.FirstError);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(-1)] // minute below the allowed range
|
||||
[InlineData(60)] // minute above the allowed range
|
||||
public void Create_WhenMinuteIsOutOfRange_ShouldReturnError(int minute)
|
||||
{
|
||||
// Act
|
||||
Result<DailySchedule> result = DailySchedule.Create(8, minute);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Scheduling.MinuteMustBeBetweenZeroAndFiftyNine, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithLowerBoundaryValues_ShouldCreateDailySchedule()
|
||||
{
|
||||
// Act
|
||||
Result<DailySchedule> result = DailySchedule.Create(0, 0);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(0, result.Value.Hour);
|
||||
Assert.Equal(0, result.Value.Minute);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithUpperBoundaryValues_ShouldCreateDailySchedule()
|
||||
{
|
||||
// Act
|
||||
Result<DailySchedule> result = DailySchedule.Create(23, 59);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(23, result.Value.Hour);
|
||||
Assert.Equal(59, result.Value.Minute);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetDelayUntilNextExecution_WhenNextRunIsLaterToday_ShouldReturnDelayUntilNextRun()
|
||||
{
|
||||
// Arrange
|
||||
DailySchedule schedule = DailySchedule.Create(12, 30).Value;
|
||||
DateTime utcNow = new(2026, 1, 1, 10, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
// Act
|
||||
TimeSpan delay = schedule.GetDelayUntilNextExecution(utcNow, TimeZoneInfo.Utc);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(TimeSpan.FromHours(2.5), delay);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetDelayUntilNextExecution_WhenNextRunAlreadyPassedToday_ShouldReturnDelayUntilTomorrow()
|
||||
{
|
||||
// Arrange
|
||||
DailySchedule schedule = DailySchedule.Create(8, 0).Value;
|
||||
DateTime utcNow = new(2026, 1, 1, 10, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
// Act
|
||||
TimeSpan delay = schedule.GetDelayUntilNextExecution(utcNow, TimeZoneInfo.Utc);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(TimeSpan.FromHours(22), delay);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetDelayUntilNextExecution_WhenNextRunEqualsNow_ShouldReturnDelayUntilTomorrow()
|
||||
{
|
||||
// Arrange
|
||||
DailySchedule schedule = DailySchedule.Create(10, 0).Value;
|
||||
DateTime utcNow = new(2026, 1, 1, 10, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
// Act
|
||||
TimeSpan delay = schedule.GetDelayUntilNextExecution(utcNow, TimeZoneInfo.Utc);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(TimeSpan.FromDays(1), delay);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WhenHourAndMinuteAreEqual_ShouldReturnTrue()
|
||||
{
|
||||
// Act
|
||||
bool areEqual = DailySchedule.Create(8, 30).Value.Equals(DailySchedule.Create(8, 30).Value);
|
||||
|
||||
// Assert
|
||||
Assert.True(areEqual);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(9, 30)] // different hour
|
||||
[InlineData(8, 31)] // different minute
|
||||
public void Equals_WhenHourOrMinuteDiffer_ShouldReturnFalse(int hour, int minute)
|
||||
{
|
||||
// Act
|
||||
bool areEqual = DailySchedule.Create(8, 30).Value.Equals(DailySchedule.Create(hour, minute).Value);
|
||||
|
||||
// Assert
|
||||
Assert.False(areEqual);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetHashCode_WhenHourAndMinuteAreEqual_ShouldReturnEqualHashCodes()
|
||||
{
|
||||
// Act
|
||||
int firstHashCode = DailySchedule.Create(8, 30).Value.GetHashCode();
|
||||
int secondHashCode = DailySchedule.Create(8, 30).Value.GetHashCode();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(firstHashCode, secondHashCode);
|
||||
}
|
||||
}
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="IntervalSchedule"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class IntervalScheduleTests
|
||||
{
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithValidInterval_ShouldCreateIntervalScheduleWithAllPropertiesSet()
|
||||
{
|
||||
// Act
|
||||
Result<IntervalSchedule> result = IntervalSchedule.Create(60);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(60, result.Value.IntervalMinutes);
|
||||
Assert.Equal(ScheduleType.WithIntervalInMinutes, result.Value.ScheduleType);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0)] // interval of zero
|
||||
[InlineData(-1)] // negative interval
|
||||
[InlineData(-100)] // negative interval far from zero
|
||||
public void Create_WhenIntervalIsNotPositive_ShouldReturnError(int intervalMinutes)
|
||||
{
|
||||
// Act
|
||||
Result<IntervalSchedule> result = IntervalSchedule.Create(intervalMinutes);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Scheduling.IntervalMinutesMustBePositive, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithOneMinuteInterval_ShouldCreateIntervalSchedule()
|
||||
{
|
||||
// Act
|
||||
Result<IntervalSchedule> result = IntervalSchedule.Create(1);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(1, result.Value.IntervalMinutes);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetDelayUntilNextExecution_WhenCalled_ShouldReturnTheIntervalInMinutes()
|
||||
{
|
||||
// Arrange
|
||||
IntervalSchedule schedule = IntervalSchedule.Create(45).Value;
|
||||
DateTime utcNow = new(2026, 1, 1, 10, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
// Act
|
||||
TimeSpan delay = schedule.GetDelayUntilNextExecution(utcNow, TimeZoneInfo.Utc);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(TimeSpan.FromMinutes(45), delay);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WhenIntervalsAreEqual_ShouldReturnTrue()
|
||||
{
|
||||
// Act
|
||||
bool areEqual = IntervalSchedule.Create(60).Value.Equals(IntervalSchedule.Create(60).Value);
|
||||
|
||||
// Assert
|
||||
Assert.True(areEqual);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WhenIntervalsDiffer_ShouldReturnFalse()
|
||||
{
|
||||
// Act
|
||||
bool areEqual = IntervalSchedule.Create(60).Value.Equals(IntervalSchedule.Create(120).Value);
|
||||
|
||||
// Assert
|
||||
Assert.False(areEqual);
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
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.UnitTests.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ScheduledJobId"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ScheduledJobIdTests
|
||||
{
|
||||
private readonly ScheduledJobIdFixture _scheduledJobIdFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void CreateUnique_WhenCalled_ShouldReturnIdWithNonEmptyValue()
|
||||
{
|
||||
// Act
|
||||
ScheduledJobId scheduledJobId = ScheduledJobId.CreateUnique();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(scheduledJobId);
|
||||
Assert.NotEqual(default, scheduledJobId.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithValue_ShouldReturnIdWithThatValue()
|
||||
{
|
||||
// Arrange
|
||||
Guid value = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
ScheduledJobId scheduledJobId = ScheduledJobId.Create(value);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(value, scheduledJobId.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithSameValue_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
Guid value = Guid.NewGuid();
|
||||
ScheduledJobId firstId = _scheduledJobIdFixture.Create(value);
|
||||
ScheduledJobId secondId = _scheduledJobIdFixture.Create(value);
|
||||
|
||||
// Act
|
||||
bool result = firstId.Equals(secondId);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentValue_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJobId firstId = _scheduledJobIdFixture.Create();
|
||||
ScheduledJobId secondId = _scheduledJobIdFixture.Create();
|
||||
|
||||
// Act
|
||||
bool result = firstId.Equals(secondId);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
}
|
||||
+42
@@ -39,4 +39,46 @@ public class MediaLibraryScanProgressHubTests
|
||||
// Assert.
|
||||
await groupManager.Received(1).AddToGroupAsync("connection-1", $"{scanId}-{userId}", CancellationToken.None);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SubscribeToScan_WhenUserClaimIsMissing_ShouldNotAddTheConnectionToAnyGroup()
|
||||
{
|
||||
// Arrange.
|
||||
MediaLibraryScanProgressHub sut = new();
|
||||
HubCallerContext context = Substitute.For<HubCallerContext>();
|
||||
context.ConnectionId.Returns("connection-1");
|
||||
IGroupManager groupManager = Substitute.For<IGroupManager>();
|
||||
sut.Context = context;
|
||||
sut.Groups = groupManager;
|
||||
Guid scanId = Guid.NewGuid();
|
||||
ClaimsPrincipal user = new(new ClaimsIdentity());
|
||||
context.User.Returns(user);
|
||||
|
||||
// Act.
|
||||
await sut.SubscribeToScan(scanId);
|
||||
|
||||
// Assert.
|
||||
await groupManager.DidNotReceive().AddToGroupAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SubscribeToScan_WhenUserIdClaimIsNotAGuid_ShouldNotAddTheConnectionToAnyGroup()
|
||||
{
|
||||
// Arrange.
|
||||
MediaLibraryScanProgressHub sut = new();
|
||||
HubCallerContext context = Substitute.For<HubCallerContext>();
|
||||
context.ConnectionId.Returns("connection-1");
|
||||
IGroupManager groupManager = Substitute.For<IGroupManager>();
|
||||
sut.Context = context;
|
||||
sut.Groups = groupManager;
|
||||
Guid scanId = Guid.NewGuid();
|
||||
ClaimsPrincipal user = new(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, "not-a-guid")]));
|
||||
context.User.Returns(user);
|
||||
|
||||
// Act.
|
||||
await sut.SubscribeToScan(scanId);
|
||||
|
||||
// Assert.
|
||||
await groupManager.DidNotReceive().AddToGroupAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
|
||||
using Lumina.Infrastructure.Core.Scheduling.Execution;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.Scheduling.Execution;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ScheduledJobRuntimeRegistry"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ScheduledJobRuntimeRegistryTests
|
||||
{
|
||||
private readonly ScheduledJobRuntimeRegistry _sut = new();
|
||||
private readonly ScheduledJobIdFixture _scheduledJobIdFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void TryStartCycle_WhenNoCycleIsRunning_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create();
|
||||
using CancellationTokenSource cycleCancellationTokenSource = new();
|
||||
|
||||
// Act
|
||||
bool result = _sut.TryStartCycle(scheduledJobId, cycleCancellationTokenSource);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryStartCycle_WhenCycleIsAlreadyRunning_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create();
|
||||
using CancellationTokenSource firstCancellationTokenSource = new();
|
||||
using CancellationTokenSource secondCancellationTokenSource = new();
|
||||
_sut.TryStartCycle(scheduledJobId, firstCancellationTokenSource);
|
||||
|
||||
// Act
|
||||
bool result = _sut.TryStartCycle(scheduledJobId, secondCancellationTokenSource);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void StopCycle_WhenCycleIsRunning_ShouldCancelTheCycleAndAllowRestartingIt()
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create();
|
||||
using CancellationTokenSource cycleCancellationTokenSource = new();
|
||||
_sut.TryStartCycle(scheduledJobId, cycleCancellationTokenSource);
|
||||
|
||||
// Act
|
||||
_sut.StopCycle(scheduledJobId);
|
||||
|
||||
// Assert
|
||||
Assert.True(cycleCancellationTokenSource.IsCancellationRequested);
|
||||
using CancellationTokenSource restartedCycleCancellationTokenSource = new();
|
||||
Assert.True(_sut.TryStartCycle(scheduledJobId, restartedCycleCancellationTokenSource));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void StopCycle_WhenNoCycleIsRunning_ShouldNotThrow()
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create();
|
||||
|
||||
// Act
|
||||
_sut.StopCycle(scheduledJobId);
|
||||
|
||||
// Assert
|
||||
Assert.True(true);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryAcquireRunSlot_WhenNoExecutionIsRunning_ShouldReturnTrueAndThenFalseWhileHeld()
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create();
|
||||
|
||||
// Act
|
||||
bool firstAcquire = _sut.TryAcquireRunSlot(scheduledJobId);
|
||||
bool secondAcquire = _sut.TryAcquireRunSlot(scheduledJobId);
|
||||
|
||||
// Assert
|
||||
Assert.True(firstAcquire);
|
||||
Assert.False(secondAcquire);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReleaseRunSlot_WhenSlotWasAcquired_ShouldAllowAcquiringItAgain()
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create();
|
||||
_sut.TryAcquireRunSlot(scheduledJobId);
|
||||
|
||||
// Act
|
||||
_sut.ReleaseRunSlot(scheduledJobId);
|
||||
|
||||
// Assert
|
||||
Assert.True(_sut.TryAcquireRunSlot(scheduledJobId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryAcquireRunSlot_AfterReleasingTheSlot_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create();
|
||||
_sut.TryAcquireRunSlot(scheduledJobId);
|
||||
_sut.ReleaseRunSlot(scheduledJobId);
|
||||
|
||||
// Act
|
||||
bool result = _sut.TryAcquireRunSlot(scheduledJobId);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
}
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
|
||||
using Lumina.Infrastructure.Core.Scheduling.Execution;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.Scheduling.Execution;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ScheduledJobSchedulerJob"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ScheduledJobSchedulerJobTests
|
||||
{
|
||||
private readonly IServiceScopeFactory _mockServiceScopeFactory;
|
||||
private readonly IServiceScope _mockServiceScope;
|
||||
private readonly IServiceProvider _mockServiceProvider;
|
||||
private readonly ScheduledJobRuntimeRegistry _runtimeRegistry;
|
||||
private readonly ScheduledJobSchedulerJob _sut;
|
||||
private readonly ScheduledJobIdFixture _scheduledJobIdFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ScheduledJobSchedulerJobTests"/> class.
|
||||
/// </summary>
|
||||
public ScheduledJobSchedulerJobTests()
|
||||
{
|
||||
_mockServiceScopeFactory = Substitute.For<IServiceScopeFactory>();
|
||||
_mockServiceScope = Substitute.For<IServiceScope>();
|
||||
_mockServiceProvider = Substitute.For<IServiceProvider>();
|
||||
_mockServiceScope.ServiceProvider.Returns(_mockServiceProvider);
|
||||
_mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope);
|
||||
_mockServiceScopeFactory.CreateAsyncScope().Returns(new AsyncServiceScope(_mockServiceScope));
|
||||
|
||||
_runtimeRegistry = new ScheduledJobRuntimeRegistry();
|
||||
ILogger<ScheduledJobSchedulerJob> logger = Substitute.For<ILogger<ScheduledJobSchedulerJob>>();
|
||||
_sut = new ScheduledJobSchedulerJob(_runtimeRegistry, logger, _mockServiceScopeFactory);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StopCycleAsync_WhenCalled_ShouldStopTheRunningCycleInTheRegistry()
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create();
|
||||
using CancellationTokenSource cycleCancellationTokenSource = new();
|
||||
_runtimeRegistry.TryStartCycle(scheduledJobId, cycleCancellationTokenSource);
|
||||
|
||||
// Act
|
||||
await _sut.StopCycleAsync(scheduledJobId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(cycleCancellationTokenSource.IsCancellationRequested);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartCycleAsync_WhenCycleIsAlreadyRunning_ShouldNotStartAnotherCycle()
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create();
|
||||
using CancellationTokenSource firstCycleCancellationTokenSource = new();
|
||||
_runtimeRegistry.TryStartCycle(scheduledJobId, firstCycleCancellationTokenSource);
|
||||
|
||||
// Act
|
||||
await _sut.StartCycleAsync(scheduledJobId, CancellationToken.None);
|
||||
// Wait briefly so the fire-and-forget worker, if any, gets a chance to run.
|
||||
await Task.Delay(150);
|
||||
|
||||
// Assert
|
||||
using CancellationTokenSource secondCycleCancellationTokenSource = new();
|
||||
Assert.False(_runtimeRegistry.TryStartCycle(scheduledJobId, secondCycleCancellationTokenSource));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RunOnceAsync_WhenCalled_ShouldCompleteWithoutThrowing()
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create();
|
||||
|
||||
// Act
|
||||
await _sut.RunOnceAsync(scheduledJobId, CancellationToken.None);
|
||||
// Wait briefly so the fire-and-forget worker, if any, gets a chance to run.
|
||||
await Task.Delay(150);
|
||||
|
||||
// Assert
|
||||
Assert.True(true);
|
||||
}
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
|
||||
using Lumina.Infrastructure.Core.Scheduling.Execution;
|
||||
using Lumina.Infrastructure.Core.Scheduling.Execution.TaskExecutors;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.Scheduling.Execution;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ScheduledTaskExecutorFactory"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ScheduledTaskExecutorFactoryTests
|
||||
{
|
||||
private readonly IServiceProvider _mockServiceProvider;
|
||||
private readonly MediaLibraryScanTaskExecutor _mockMediaLibraryScanTaskExecutor;
|
||||
private readonly TemporaryFilesCleanupTaskExecutor _mockTemporaryFilesCleanupTaskExecutor;
|
||||
private readonly ScheduledTaskExecutorFactory _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ScheduledTaskExecutorFactoryTests"/> class.
|
||||
/// </summary>
|
||||
public ScheduledTaskExecutorFactoryTests()
|
||||
{
|
||||
_mockServiceProvider = Substitute.For<IServiceProvider>();
|
||||
_mockMediaLibraryScanTaskExecutor = Substitute.For<MediaLibraryScanTaskExecutor>(
|
||||
Substitute.For<IDomainEventPublisher>(),
|
||||
Substitute.For<ILogger<MediaLibraryScanTaskExecutor>>(),
|
||||
Substitute.For<IUnitOfWork>());
|
||||
_mockTemporaryFilesCleanupTaskExecutor = Substitute.For<TemporaryFilesCleanupTaskExecutor>(
|
||||
Substitute.For<ILogger<TemporaryFilesCleanupTaskExecutor>>());
|
||||
|
||||
_mockServiceProvider.GetService(typeof(MediaLibraryScanTaskExecutor)).Returns(_mockMediaLibraryScanTaskExecutor);
|
||||
_mockServiceProvider.GetService(typeof(TemporaryFilesCleanupTaskExecutor)).Returns(_mockTemporaryFilesCleanupTaskExecutor);
|
||||
|
||||
_sut = new ScheduledTaskExecutorFactory(_mockServiceProvider);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateExecutor_WhenTaskTypeIsScanMediaLibraries_ShouldReturnMediaLibraryScanTaskExecutor()
|
||||
{
|
||||
// Act
|
||||
IScheduledTaskExecutor result = _sut.CreateExecutor(ScheduledTaskType.ScanMediaLibraries);
|
||||
|
||||
// Assert
|
||||
Assert.Same(_mockMediaLibraryScanTaskExecutor, result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateExecutor_WhenTaskTypeIsCleanTemporaryFiles_ShouldReturnTemporaryFilesCleanupTaskExecutor()
|
||||
{
|
||||
// Act
|
||||
IScheduledTaskExecutor result = _sut.CreateExecutor(ScheduledTaskType.CleanTemporaryFiles);
|
||||
|
||||
// Assert
|
||||
Assert.Same(_mockTemporaryFilesCleanupTaskExecutor, result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateExecutor_WhenTaskTypeIsUnsupported_ShouldThrowArgumentException()
|
||||
{
|
||||
// Act
|
||||
ArgumentException exception = Assert.Throws<ArgumentException>(() => _sut.CreateExecutor((ScheduledTaskType)999));
|
||||
|
||||
// Assert
|
||||
Assert.Contains("Unsupported task type", exception.Message);
|
||||
Assert.Equal("taskType", exception.ParamName);
|
||||
}
|
||||
}
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
|
||||
using Lumina.Infrastructure.Core.Scheduling.Execution.TaskExecutors;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.Scheduling.Execution.TaskExecutors;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaLibraryScanTaskExecutor"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaLibraryScanTaskExecutorTests
|
||||
{
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly ILibraryRepository _mockLibraryRepository;
|
||||
private readonly IDomainEventPublisher _mockDomainEventPublisher;
|
||||
private readonly MediaLibraryScanTaskExecutor _sut;
|
||||
private readonly ScheduledJobFixture _scheduledJobFixture = new();
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaLibraryScanTaskExecutorTests"/> class.
|
||||
/// </summary>
|
||||
public MediaLibraryScanTaskExecutorTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
_mockLibraryRepository.GetAllEnabledAndUnlockedAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IEnumerable<LibraryEntity>>([]));
|
||||
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
|
||||
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
|
||||
_sut = new MediaLibraryScanTaskExecutor(_mockDomainEventPublisher, Substitute.For<ILogger<MediaLibraryScanTaskExecutor>>(), _mockUnitOfWork);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecutePayloadAsync_WhenNoLibrariesAreEnabled_ShouldReturnSuccessWithoutPublishingEvents()
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJob scheduledJob = _scheduledJobFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Success, result.Value);
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecutePayloadAsync_WhenGetAllEnabledAndUnlockedLibrariesFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJob scheduledJob = _scheduledJobFixture.Create();
|
||||
Error error = Error.Failure("Database.Error", "Failed to get the enabled libraries");
|
||||
_mockLibraryRepository.GetAllEnabledAndUnlockedAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(error);
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecutePayloadAsync_WhenGetPastMonthScansFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJob scheduledJob = _scheduledJobFixture.Create();
|
||||
LibraryEntity library = _libraryEntityFixture.Create();
|
||||
_mockLibraryRepository.GetAllEnabledAndUnlockedAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IEnumerable<LibraryEntity>>([library]));
|
||||
Error error = Error.Failure("Database.Error", "Failed to get the past month scans");
|
||||
_mockUnitOfWork.LibraryScanRepository.GetPastMonthScansByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(error);
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
}
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
|
||||
using Lumina.Infrastructure.Core.Scheduling.Execution.TaskExecutors;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.Scheduling.Execution.TaskExecutors;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="TemporaryFilesCleanupTaskExecutor"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class TemporaryFilesCleanupTaskExecutorTests
|
||||
{
|
||||
private readonly TemporaryFilesCleanupTaskExecutor _sut;
|
||||
private readonly ScheduledJobFixture _scheduledJobFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="TemporaryFilesCleanupTaskExecutorTests"/> class.
|
||||
/// </summary>
|
||||
public TemporaryFilesCleanupTaskExecutorTests()
|
||||
{
|
||||
ILogger<TemporaryFilesCleanupTaskExecutor> logger = Substitute.For<ILogger<TemporaryFilesCleanupTaskExecutor>>();
|
||||
_sut = new TemporaryFilesCleanupTaskExecutor(logger);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecutePayloadAsync_WhenTemporaryDirectoryExists_ShouldEmptyItAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJob scheduledJob = _scheduledJobFixture.Create();
|
||||
string temporaryDirectory = Path.Combine(AppContext.BaseDirectory, "reading-cache");
|
||||
Directory.CreateDirectory(Path.Combine(temporaryDirectory, "subdirectory"));
|
||||
File.WriteAllText(Path.Combine(temporaryDirectory, "subdirectory", "file.txt"), "content");
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Success, result.Value);
|
||||
Assert.True(Directory.Exists(temporaryDirectory));
|
||||
Assert.Empty(Directory.GetFileSystemEntries(temporaryDirectory));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecutePayloadAsync_WhenTemporaryDirectoryDoesNotExist_ShouldRecreateItAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJob scheduledJob = _scheduledJobFixture.Create();
|
||||
string temporaryDirectory = Path.Combine(AppContext.BaseDirectory, "reading-cache");
|
||||
if (Directory.Exists(temporaryDirectory))
|
||||
Directory.Delete(temporaryDirectory, recursive: true);
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Success, result.Value);
|
||||
Assert.True(Directory.Exists(temporaryDirectory));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecutePayloadAsync_WhenDeletingTheDirectoryFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJob scheduledJob = _scheduledJobFixture.Create();
|
||||
string temporaryDirectory = Path.Combine(AppContext.BaseDirectory, "reading-cache");
|
||||
Directory.CreateDirectory(temporaryDirectory);
|
||||
string lockedFile = Path.Combine(temporaryDirectory, "locked.txt");
|
||||
File.WriteAllText(lockedFile, "content");
|
||||
// Lock the file with an exclusive handle so the recursive delete fails.
|
||||
using FileStream lockStream = new(lockedFile, FileMode.Open, FileAccess.Read, FileShare.None);
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
}
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.Fixtures.Core.Responses.Scheduling;
|
||||
using Lumina.Contracts.Responses.Scheduling;
|
||||
using Lumina.Infrastructure.Core.Scheduling.Notifications;
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
using NSubstitute;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.Scheduling.Notifications;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ScheduledJobNotifier"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ScheduledJobNotifierTests
|
||||
{
|
||||
private readonly IHubContext<ScheduledJobsHub, IScheduledJobsClient> _mockHubContext;
|
||||
private readonly IHubClients<IScheduledJobsClient> _mockHubClients;
|
||||
private readonly IScheduledJobsClient _mockClient;
|
||||
private readonly ScheduledJobNotifier _sut;
|
||||
private readonly ScheduledJobResponseFixture _scheduledJobResponseFixture = new();
|
||||
private readonly ScheduledJobExecutionResponseFixture _scheduledJobExecutionResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ScheduledJobNotifierTests"/> class.
|
||||
/// </summary>
|
||||
public ScheduledJobNotifierTests()
|
||||
{
|
||||
_mockClient = Substitute.For<IScheduledJobsClient>();
|
||||
_mockHubClients = Substitute.For<IHubClients<IScheduledJobsClient>>();
|
||||
_mockHubClients.All.Returns(_mockClient);
|
||||
_mockHubContext = Substitute.For<IHubContext<ScheduledJobsHub, IScheduledJobsClient>>();
|
||||
_mockHubContext.Clients.Returns(_mockHubClients);
|
||||
_sut = new ScheduledJobNotifier(_mockHubContext);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendScheduledJobsAsync_WhenCalled_ShouldSendTheScheduledJobsToAllClients()
|
||||
{
|
||||
// Arrange
|
||||
IReadOnlyList<ScheduledJobResponse> scheduledJobs = _scheduledJobResponseFixture.CreateMany(2);
|
||||
|
||||
// Act
|
||||
await _sut.SendScheduledJobsAsync(scheduledJobs, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockClient.Received(1).ReceiveScheduledJobsAsync(scheduledJobs);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendScheduledJobExecutionStartedAsync_WhenCalled_ShouldSendTheExecutionToAllClients()
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJobExecutionResponse execution = _scheduledJobExecutionResponseFixture.Create();
|
||||
|
||||
// Act
|
||||
await _sut.SendScheduledJobExecutionStartedAsync(execution, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockClient.Received(1).ScheduledJobExecutionStartedAsync(execution);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendScheduledJobExecutionCompletedAsync_WhenCalled_ShouldSendTheExecutionToAllClients()
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJobExecutionResponse execution = _scheduledJobExecutionResponseFixture.Create();
|
||||
|
||||
// Act
|
||||
await _sut.SendScheduledJobExecutionCompletedAsync(execution, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockClient.Received(1).ScheduledJobExecutionCompletedAsync(execution);
|
||||
}
|
||||
}
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Infrastructure.Core.Scheduling.Notifications;
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Security.Claims;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.Scheduling.Notifications;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ScheduledJobsHub"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ScheduledJobsHubTests
|
||||
{
|
||||
private readonly IAuthorizationService _mockAuthorizationService;
|
||||
private readonly ScheduledJobsHub _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ScheduledJobsHubTests"/> class.
|
||||
/// </summary>
|
||||
public ScheduledJobsHubTests()
|
||||
{
|
||||
Microsoft.Extensions.DependencyInjection.IServiceScopeFactory mockScopeFactory = Substitute.For<Microsoft.Extensions.DependencyInjection.IServiceScopeFactory>();
|
||||
Microsoft.Extensions.DependencyInjection.IServiceScope mockScope = Substitute.For<Microsoft.Extensions.DependencyInjection.IServiceScope>();
|
||||
System.IServiceProvider mockServiceProvider = Substitute.For<System.IServiceProvider>();
|
||||
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
|
||||
|
||||
mockScope.ServiceProvider.Returns(mockServiceProvider);
|
||||
mockServiceProvider.GetService(typeof(IAuthorizationService)).Returns(_mockAuthorizationService);
|
||||
mockScopeFactory.CreateScope().Returns(mockScope);
|
||||
|
||||
_sut = new ScheduledJobsHub(mockScopeFactory);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task OnConnectedAsync_WhenUserClaimIsMissing_ShouldAbortTheConnection()
|
||||
{
|
||||
// Arrange
|
||||
HubCallerContext context = CreateHubCallerContext(new ClaimsPrincipal(new ClaimsIdentity()));
|
||||
_sut.Context = context;
|
||||
|
||||
// Act
|
||||
await _sut.OnConnectedAsync();
|
||||
|
||||
// Assert
|
||||
context.Received(1).Abort();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task OnConnectedAsync_WhenUserIdClaimIsNotAGuid_ShouldAbortTheConnection()
|
||||
{
|
||||
// Arrange
|
||||
ClaimsPrincipal user = new(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, "not-a-guid")]));
|
||||
HubCallerContext context = CreateHubCallerContext(user);
|
||||
_sut.Context = context;
|
||||
|
||||
// Act
|
||||
await _sut.OnConnectedAsync();
|
||||
|
||||
// Assert
|
||||
context.Received(1).Abort();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task OnConnectedAsync_WhenUserIsNotAdministrator_ShouldAbortTheConnection()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
ClaimsPrincipal user = new(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, userId.ToString())]));
|
||||
HubCallerContext context = CreateHubCallerContext(user);
|
||||
_sut.Context = context;
|
||||
_mockAuthorizationService.IsInRoleAsync(userId, "Admin", System.Threading.CancellationToken.None).Returns(false);
|
||||
|
||||
// Act
|
||||
await _sut.OnConnectedAsync();
|
||||
|
||||
// Assert
|
||||
context.Received(1).Abort();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task OnConnectedAsync_WhenUserIsAdministrator_ShouldNotAbortTheConnection()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
ClaimsPrincipal user = new(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, userId.ToString())]));
|
||||
HubCallerContext context = CreateHubCallerContext(user);
|
||||
_sut.Context = context;
|
||||
_mockAuthorizationService.IsInRoleAsync(userId, "Admin", System.Threading.CancellationToken.None).Returns(true);
|
||||
|
||||
// Act
|
||||
await _sut.OnConnectedAsync();
|
||||
|
||||
// Assert
|
||||
context.DidNotReceive().Abort();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a mocked hub caller context carrying the provided user.
|
||||
/// </summary>
|
||||
/// <param name="user">The user of the connection.</param>
|
||||
/// <returns>The created context.</returns>
|
||||
private static HubCallerContext CreateHubCallerContext(ClaimsPrincipal user)
|
||||
{
|
||||
HubCallerContext context = Substitute.For<HubCallerContext>();
|
||||
context.User.Returns(user);
|
||||
return context;
|
||||
}
|
||||
}
|
||||
+159
@@ -0,0 +1,159 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Application.Core.Scheduling.Commands.AddScheduledJob;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Scheduling;
|
||||
using Lumina.Contracts.Fixtures.Core.Responses.Scheduling;
|
||||
using Lumina.Contracts.Requests.Scheduling;
|
||||
using Lumina.Contracts.Responses.Scheduling;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Scheduling.AddScheduledJob;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Scheduling.AddScheduledJob;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="AddScheduledJobEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddScheduledJobEndpointTests
|
||||
{
|
||||
private readonly Application.Common.CQRS.ICommandHandler<AddScheduledJobCommand, Result<ScheduledJobResponse>> _mockHandler;
|
||||
private readonly AddScheduledJobEndpoint _sut;
|
||||
private readonly AddScheduledJobRequestFixture _addScheduledJobRequestFixture = new();
|
||||
private readonly ScheduledJobResponseFixture _scheduledJobResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddScheduledJobEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public AddScheduledJobEndpointTests()
|
||||
{
|
||||
_mockHandler = Substitute.For<Application.Common.CQRS.ICommandHandler<AddScheduledJobCommand, Result<ScheduledJobResponse>>>();
|
||||
_sut = Factory.Create<AddScheduledJobEndpoint>(_mockHandler);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithScheduledJobResponse()
|
||||
{
|
||||
// Arrange
|
||||
AddScheduledJobRequest request = _addScheduledJobRequestFixture.Create(name: "Scan job", scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60);
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
ScheduledJobResponse expectedResponse = _scheduledJobResponseFixture.Create(
|
||||
name: request.Name,
|
||||
taskType: request.TaskType,
|
||||
scheduleType: request.ScheduleType,
|
||||
intervalMinutes: request.IntervalMinutes,
|
||||
hour: request.Hour,
|
||||
minute: request.Minute,
|
||||
status: ScheduledJobStatus.Added);
|
||||
_mockHandler.HandleAsync(Arg.Any<AddScheduledJobCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(expectedResponse));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Ok<ScheduledJobResponse> okResult = Assert.IsType<Ok<ScheduledJobResponse>>(result);
|
||||
Assert.Equal(expectedResponse, okResult.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
AddScheduledJobRequest request = _addScheduledJobRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = Lumina.Domain.Common.Errors.Errors.Scheduling.ScheduledJobNameCannotBeEmpty;
|
||||
_mockHandler.HandleAsync(Arg.Any<AddScheduledJobCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemResult.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemResult.ContentType);
|
||||
Assert.NotNull(problemResult.ProblemDetails.Extensions["traceId"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendMappedCommandToHandler()
|
||||
{
|
||||
// Arrange
|
||||
AddScheduledJobRequest request = _addScheduledJobRequestFixture.Create(
|
||||
name: "Mapped job",
|
||||
taskType: ScheduledTaskType.CleanTemporaryFiles,
|
||||
scheduleType: ScheduleType.DailyAtHourAndMinute,
|
||||
hour: 2,
|
||||
minute: 15);
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
ScheduledJobResponse response = _scheduledJobResponseFixture.Create(
|
||||
name: request.Name,
|
||||
taskType: request.TaskType,
|
||||
scheduleType: request.ScheduleType,
|
||||
hour: request.Hour,
|
||||
minute: request.Minute,
|
||||
status: ScheduledJobStatus.Added);
|
||||
_mockHandler.HandleAsync(Arg.Any<AddScheduledJobCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(response));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<AddScheduledJobCommand>(command =>
|
||||
command.Name == request.Name &&
|
||||
command.TaskType == request.TaskType &&
|
||||
command.ScheduleType == request.ScheduleType &&
|
||||
command.IntervalMinutes == request.IntervalMinutes &&
|
||||
command.Hour == request.Hour &&
|
||||
command.Minute == request.Minute),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
AddScheduledJobRequest request = _addScheduledJobRequestFixture.Create();
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
ScheduledJobResponse response = _scheduledJobResponseFixture.Create(
|
||||
name: request.Name,
|
||||
taskType: request.TaskType,
|
||||
scheduleType: request.ScheduleType,
|
||||
intervalMinutes: request.IntervalMinutes,
|
||||
hour: request.Hour,
|
||||
minute: request.Minute,
|
||||
status: ScheduledJobStatus.Added);
|
||||
|
||||
_mockHandler.HandleAsync(Arg.Any<AddScheduledJobCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return Result.From(response);
|
||||
}, callInfo.Arg<CancellationToken>()));
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
+164
@@ -0,0 +1,164 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Application.Core.Scheduling.Commands.FireScheduledJob;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Scheduling;
|
||||
using Lumina.Contracts.Fixtures.Core.Responses.Scheduling;
|
||||
using Lumina.Contracts.Requests.Scheduling;
|
||||
using Lumina.Contracts.Responses.Scheduling;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Scheduling.FireScheduledJob;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
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.Presentation.Api.UnitTests.Core.Endpoints.Scheduling.FireScheduledJob;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="FireScheduledJobEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FireScheduledJobEndpointTests
|
||||
{
|
||||
private readonly Application.Common.CQRS.ICommandHandler<FireScheduledJobCommand, Result<ScheduledJobResponse>> _mockHandler;
|
||||
private readonly FireScheduledJobEndpoint _sut;
|
||||
private readonly FireScheduledJobRequestFixture _fireScheduledJobRequestFixture = new();
|
||||
private readonly ScheduledJobResponseFixture _scheduledJobResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="FireScheduledJobEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public FireScheduledJobEndpointTests()
|
||||
{
|
||||
_mockHandler = Substitute.For<Application.Common.CQRS.ICommandHandler<FireScheduledJobCommand, Result<ScheduledJobResponse>>>();
|
||||
_sut = Factory.Create<FireScheduledJobEndpoint>(_mockHandler);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithScheduledJobResponse()
|
||||
{
|
||||
// Arrange
|
||||
FireScheduledJobRequest request = _fireScheduledJobRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
ScheduledJobResponse expectedResponse = _scheduledJobResponseFixture.Create(
|
||||
id: request.ScheduledJobId,
|
||||
name: "Scan job",
|
||||
taskType: ScheduledTaskType.ScanMediaLibraries,
|
||||
scheduleType: ScheduleType.WithIntervalInMinutes,
|
||||
intervalMinutes: 60,
|
||||
status: ScheduledJobStatus.Active);
|
||||
_mockHandler.HandleAsync(Arg.Any<FireScheduledJobCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(expectedResponse));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Ok<ScheduledJobResponse> okResult = Assert.IsType<Ok<ScheduledJobResponse>>(result);
|
||||
Assert.Equal(expectedResponse, okResult.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
FireScheduledJobRequest request = _fireScheduledJobRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = Errors.Scheduling.ScheduledJobNotFound;
|
||||
_mockHandler.HandleAsync(Arg.Any<FireScheduledJobCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemResult.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemResult.ContentType);
|
||||
Assert.NotNull(problemResult.ProblemDetails.Extensions["traceId"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorized_ShouldReturnForbiddenProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
FireScheduledJobRequest request = _fireScheduledJobRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<FireScheduledJobCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ApplicationErrors.Authorization.NotAuthorized);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendMappedCommandToHandler()
|
||||
{
|
||||
// Arrange
|
||||
FireScheduledJobRequest request = _fireScheduledJobRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
ScheduledJobResponse response = _scheduledJobResponseFixture.Create(
|
||||
id: request.ScheduledJobId,
|
||||
name: "Scan job",
|
||||
taskType: ScheduledTaskType.ScanMediaLibraries,
|
||||
scheduleType: ScheduleType.WithIntervalInMinutes,
|
||||
intervalMinutes: 60,
|
||||
status: ScheduledJobStatus.Active);
|
||||
_mockHandler.HandleAsync(Arg.Any<FireScheduledJobCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(response));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<FireScheduledJobCommand>(command => command.ScheduledJobId == request.ScheduledJobId),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
FireScheduledJobRequest request = _fireScheduledJobRequestFixture.Create();
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
ScheduledJobResponse response = _scheduledJobResponseFixture.Create(
|
||||
id: request.ScheduledJobId,
|
||||
name: "Scan job",
|
||||
taskType: ScheduledTaskType.ScanMediaLibraries,
|
||||
scheduleType: ScheduleType.WithIntervalInMinutes,
|
||||
intervalMinutes: 60,
|
||||
status: ScheduledJobStatus.Active);
|
||||
|
||||
_mockHandler.HandleAsync(Arg.Any<FireScheduledJobCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return Result.From(response);
|
||||
}, callInfo.Arg<CancellationToken>()));
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Core.Scheduling.Queries.GetScheduledJobHistory;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Scheduling;
|
||||
using Lumina.Contracts.Fixtures.Core.Responses.Scheduling;
|
||||
using Lumina.Contracts.Requests.Scheduling;
|
||||
using Lumina.Contracts.Responses.Scheduling;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Scheduling.GetScheduledJobHistory;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
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.Presentation.Api.UnitTests.Core.Endpoints.Scheduling.GetScheduledJobHistory;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetScheduledJobHistoryEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetScheduledJobHistoryEndpointTests
|
||||
{
|
||||
private readonly IQueryHandler<GetScheduledJobHistoryQuery, Result<IEnumerable<ScheduledJobExecutionResponse>>> _mockHandler;
|
||||
private readonly GetScheduledJobHistoryEndpoint _sut;
|
||||
private readonly GetScheduledJobHistoryRequestFixture _getScheduledJobHistoryRequestFixture = new();
|
||||
private readonly ScheduledJobExecutionResponseFixture _scheduledJobExecutionResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetScheduledJobHistoryEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetScheduledJobHistoryEndpointTests()
|
||||
{
|
||||
_mockHandler = Substitute.For<IQueryHandler<GetScheduledJobHistoryQuery, Result<IEnumerable<ScheduledJobExecutionResponse>>>>();
|
||||
_sut = Factory.Create<GetScheduledJobHistoryEndpoint>(_mockHandler);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithExecutionResponses()
|
||||
{
|
||||
// Arrange
|
||||
GetScheduledJobHistoryRequest request = _getScheduledJobHistoryRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
List<ScheduledJobExecutionResponse> expectedResponses = _scheduledJobExecutionResponseFixture.CreateMany(2);
|
||||
_mockHandler.HandleAsync(Arg.Any<GetScheduledJobHistoryQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IEnumerable<ScheduledJobExecutionResponse>>(expectedResponses));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Ok<IEnumerable<ScheduledJobExecutionResponse>> okResult = Assert.IsType<Ok<IEnumerable<ScheduledJobExecutionResponse>>>(result);
|
||||
Assert.Equal(2, okResult.Value.Count());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
GetScheduledJobHistoryRequest request = _getScheduledJobHistoryRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetScheduledJobHistoryQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ApplicationErrors.Authorization.NotAuthorized);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendMappedQueryToHandler()
|
||||
{
|
||||
// Arrange
|
||||
GetScheduledJobHistoryRequest request = _getScheduledJobHistoryRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetScheduledJobHistoryQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IEnumerable<ScheduledJobExecutionResponse>>([]));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<GetScheduledJobHistoryQuery>(query => query.From == request.From && query.To == request.To),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Core.Scheduling.Queries.GetScheduledJobs;
|
||||
using Lumina.Contracts.Fixtures.Core.Responses.Scheduling;
|
||||
using Lumina.Contracts.Responses.Scheduling;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Scheduling.GetScheduledJobs;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using NSubstitute;
|
||||
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.Presentation.Api.UnitTests.Core.Endpoints.Scheduling.GetScheduledJobs;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetScheduledJobsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetScheduledJobsEndpointTests
|
||||
{
|
||||
private readonly IQueryHandler<GetScheduledJobsQuery, Result<IEnumerable<ScheduledJobResponse>>> _mockHandler;
|
||||
private readonly GetScheduledJobsEndpoint _sut;
|
||||
private readonly ScheduledJobResponseFixture _scheduledJobResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetScheduledJobsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetScheduledJobsEndpointTests()
|
||||
{
|
||||
_mockHandler = Substitute.For<IQueryHandler<GetScheduledJobsQuery, Result<IEnumerable<ScheduledJobResponse>>>>();
|
||||
_sut = Factory.Create<GetScheduledJobsEndpoint>(_mockHandler);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithScheduledJobResponses()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
List<ScheduledJobResponse> expectedResponses = _scheduledJobResponseFixture.CreateMany(2);
|
||||
_mockHandler.HandleAsync(Arg.Any<GetScheduledJobsQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IEnumerable<ScheduledJobResponse>>(expectedResponses));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Ok<IEnumerable<ScheduledJobResponse>> okResult = Assert.IsType<Ok<IEnumerable<ScheduledJobResponse>>>(result);
|
||||
Assert.Equal(2, okResult.Value.Count());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetScheduledJobsQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ApplicationErrors.Authorization.NotAuthorized);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendQueryToHandler()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetScheduledJobsQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IEnumerable<ScheduledJobResponse>>([]));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Any<GetScheduledJobsQuery>(),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
}
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Core.Scheduling.Queries.GetSchedulerDisplayPreferences;
|
||||
using Lumina.Contracts.Fixtures.Core.Responses.Scheduling;
|
||||
using Lumina.Contracts.Responses.Scheduling;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Scheduling.GetSchedulerDisplayPreferences;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using NSubstitute;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Scheduling.GetSchedulerDisplayPreferences;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetSchedulerDisplayPreferencesEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetSchedulerDisplayPreferencesEndpointTests
|
||||
{
|
||||
private readonly IQueryHandler<GetSchedulerDisplayPreferencesQuery, Result<SchedulerDisplayPreferencesResponse>> _mockHandler;
|
||||
private readonly GetSchedulerDisplayPreferencesEndpoint _sut;
|
||||
private readonly SchedulerDisplayPreferencesResponseFixture _schedulerDisplayPreferencesResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetSchedulerDisplayPreferencesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetSchedulerDisplayPreferencesEndpointTests()
|
||||
{
|
||||
_mockHandler = Substitute.For<IQueryHandler<GetSchedulerDisplayPreferencesQuery, Result<SchedulerDisplayPreferencesResponse>>>();
|
||||
_sut = Factory.Create<GetSchedulerDisplayPreferencesEndpoint>(_mockHandler);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithDisplayPreferencesResponse()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
SchedulerDisplayPreferencesResponse expectedResponse = _schedulerDisplayPreferencesResponseFixture.Create();
|
||||
_mockHandler.HandleAsync(Arg.Any<GetSchedulerDisplayPreferencesQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(expectedResponse));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Ok<SchedulerDisplayPreferencesResponse> okResult = Assert.IsType<Ok<SchedulerDisplayPreferencesResponse>>(result);
|
||||
Assert.Equal(expectedResponse, okResult.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetSchedulerDisplayPreferencesQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ApplicationErrors.Authorization.NotAuthorized);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendQueryToHandler()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetSchedulerDisplayPreferencesQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_schedulerDisplayPreferencesResponseFixture.Create()));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Any<GetSchedulerDisplayPreferencesQuery>(),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
}
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Core.Scheduling.Commands.RemoveScheduledJob;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Scheduling;
|
||||
using Lumina.Contracts.Requests.Scheduling;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Scheduling.RemoveScheduledJob;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
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.Presentation.Api.UnitTests.Core.Endpoints.Scheduling.RemoveScheduledJob;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="RemoveScheduledJobEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RemoveScheduledJobEndpointTests
|
||||
{
|
||||
private readonly Application.Common.CQRS.ICommandHandler<RemoveScheduledJobCommand, Result<Success>> _mockHandler;
|
||||
private readonly RemoveScheduledJobEndpoint _sut;
|
||||
private readonly RemoveScheduledJobRequestFixture _removeScheduledJobRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RemoveScheduledJobEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public RemoveScheduledJobEndpointTests()
|
||||
{
|
||||
_mockHandler = Substitute.For<Application.Common.CQRS.ICommandHandler<RemoveScheduledJobCommand, Result<Success>>>();
|
||||
_sut = Factory.Create<RemoveScheduledJobEndpoint>(_mockHandler);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResult()
|
||||
{
|
||||
// Arrange
|
||||
RemoveScheduledJobRequest request = _removeScheduledJobRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<RemoveScheduledJobCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Success);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
IStatusCodeHttpResult statusCodeResult = Assert.IsAssignableFrom<IStatusCodeHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status200OK, statusCodeResult.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
RemoveScheduledJobRequest request = _removeScheduledJobRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = Domain.Common.Errors.Errors.Scheduling.ScheduledJobNotFound;
|
||||
_mockHandler.HandleAsync(Arg.Any<RemoveScheduledJobCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemResult.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorized_ShouldReturnForbiddenProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
RemoveScheduledJobRequest request = _removeScheduledJobRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<RemoveScheduledJobCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ApplicationErrors.Authorization.NotAuthorized);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendMappedCommandToHandler()
|
||||
{
|
||||
// Arrange
|
||||
RemoveScheduledJobRequest request = _removeScheduledJobRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<RemoveScheduledJobCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Success);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<RemoveScheduledJobCommand>(command => command.ScheduledJobId == request.ScheduledJobId),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
}
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Application.Core.Scheduling.Commands.StartScheduledJob;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Scheduling;
|
||||
using Lumina.Contracts.Fixtures.Core.Responses.Scheduling;
|
||||
using Lumina.Contracts.Requests.Scheduling;
|
||||
using Lumina.Contracts.Responses.Scheduling;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Scheduling.StartScheduledJob;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using NSubstitute;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Scheduling.StartScheduledJob;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="StartScheduledJobEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class StartScheduledJobEndpointTests
|
||||
{
|
||||
private readonly Application.Common.CQRS.ICommandHandler<StartScheduledJobCommand, Result<ScheduledJobResponse>> _mockHandler;
|
||||
private readonly StartScheduledJobEndpoint _sut;
|
||||
private readonly StartScheduledJobRequestFixture _startScheduledJobRequestFixture = new();
|
||||
private readonly ScheduledJobResponseFixture _scheduledJobResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StartScheduledJobEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public StartScheduledJobEndpointTests()
|
||||
{
|
||||
_mockHandler = Substitute.For<Application.Common.CQRS.ICommandHandler<StartScheduledJobCommand, Result<ScheduledJobResponse>>>();
|
||||
_sut = Factory.Create<StartScheduledJobEndpoint>(_mockHandler);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithScheduledJobResponse()
|
||||
{
|
||||
// Arrange
|
||||
StartScheduledJobRequest request = _startScheduledJobRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
ScheduledJobResponse expectedResponse = _scheduledJobResponseFixture.Create(
|
||||
id: request.ScheduledJobId,
|
||||
status: ScheduledJobStatus.Active);
|
||||
_mockHandler.HandleAsync(Arg.Any<StartScheduledJobCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(expectedResponse));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Ok<ScheduledJobResponse> okResult = Assert.IsType<Ok<ScheduledJobResponse>>(result);
|
||||
Assert.Equal(expectedResponse, okResult.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
StartScheduledJobRequest request = _startScheduledJobRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = Errors.Scheduling.ScheduledJobNotFound;
|
||||
_mockHandler.HandleAsync(Arg.Any<StartScheduledJobCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemResult.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorized_ShouldReturnForbiddenProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
StartScheduledJobRequest request = _startScheduledJobRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<StartScheduledJobCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ApplicationErrors.Authorization.NotAuthorized);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendMappedCommandToHandler()
|
||||
{
|
||||
// Arrange
|
||||
StartScheduledJobRequest request = _startScheduledJobRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<StartScheduledJobCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_scheduledJobResponseFixture.Create(id: request.ScheduledJobId)));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<StartScheduledJobCommand>(command => command.ScheduledJobId == request.ScheduledJobId),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
}
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Application.Core.Scheduling.Commands.StopScheduledJob;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Scheduling;
|
||||
using Lumina.Contracts.Fixtures.Core.Responses.Scheduling;
|
||||
using Lumina.Contracts.Requests.Scheduling;
|
||||
using Lumina.Contracts.Responses.Scheduling;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Scheduling.StopScheduledJob;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using NSubstitute;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Scheduling.StopScheduledJob;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="StopScheduledJobEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class StopScheduledJobEndpointTests
|
||||
{
|
||||
private readonly Application.Common.CQRS.ICommandHandler<StopScheduledJobCommand, Result<ScheduledJobResponse>> _mockHandler;
|
||||
private readonly StopScheduledJobEndpoint _sut;
|
||||
private readonly StopScheduledJobRequestFixture _stopScheduledJobRequestFixture = new();
|
||||
private readonly ScheduledJobResponseFixture _scheduledJobResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StopScheduledJobEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public StopScheduledJobEndpointTests()
|
||||
{
|
||||
_mockHandler = Substitute.For<Application.Common.CQRS.ICommandHandler<StopScheduledJobCommand, Result<ScheduledJobResponse>>>();
|
||||
_sut = Factory.Create<StopScheduledJobEndpoint>(_mockHandler);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithScheduledJobResponse()
|
||||
{
|
||||
// Arrange
|
||||
StopScheduledJobRequest request = _stopScheduledJobRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
ScheduledJobResponse expectedResponse = _scheduledJobResponseFixture.Create(
|
||||
id: request.ScheduledJobId,
|
||||
status: ScheduledJobStatus.Added);
|
||||
_mockHandler.HandleAsync(Arg.Any<StopScheduledJobCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(expectedResponse));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Ok<ScheduledJobResponse> okResult = Assert.IsType<Ok<ScheduledJobResponse>>(result);
|
||||
Assert.Equal(expectedResponse, okResult.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
StopScheduledJobRequest request = _stopScheduledJobRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = Errors.Scheduling.ScheduledJobNotStarted;
|
||||
_mockHandler.HandleAsync(Arg.Any<StopScheduledJobCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorized_ShouldReturnForbiddenProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
StopScheduledJobRequest request = _stopScheduledJobRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<StopScheduledJobCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ApplicationErrors.Authorization.NotAuthorized);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendMappedCommandToHandler()
|
||||
{
|
||||
// Arrange
|
||||
StopScheduledJobRequest request = _stopScheduledJobRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<StopScheduledJobCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_scheduledJobResponseFixture.Create(id: request.ScheduledJobId)));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<StopScheduledJobCommand>(command => command.ScheduledJobId == request.ScheduledJobId),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
}
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Core.Scheduling.Commands.UpdateSchedulerDisplayPreferences;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Scheduling;
|
||||
using Lumina.Contracts.Requests.Scheduling;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Scheduling.UpdateSchedulerDisplayPreferences;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using NSubstitute;
|
||||
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.Presentation.Api.UnitTests.Core.Endpoints.Scheduling.UpdateSchedulerDisplayPreferences;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="UpdateSchedulerDisplayPreferencesEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateSchedulerDisplayPreferencesEndpointTests
|
||||
{
|
||||
private readonly Application.Common.CQRS.ICommandHandler<UpdateSchedulerDisplayPreferencesCommand, Result<Updated>> _mockHandler;
|
||||
private readonly UpdateSchedulerDisplayPreferencesEndpoint _sut;
|
||||
private readonly UpdateSchedulerDisplayPreferencesRequestFixture _updateSchedulerDisplayPreferencesRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateSchedulerDisplayPreferencesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public UpdateSchedulerDisplayPreferencesEndpointTests()
|
||||
{
|
||||
_mockHandler = Substitute.For<Application.Common.CQRS.ICommandHandler<UpdateSchedulerDisplayPreferencesCommand, Result<Updated>>>();
|
||||
_sut = Factory.Create<UpdateSchedulerDisplayPreferencesEndpoint>(_mockHandler);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithUpdated()
|
||||
{
|
||||
// Arrange
|
||||
UpdateSchedulerDisplayPreferencesRequest request = _updateSchedulerDisplayPreferencesRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateSchedulerDisplayPreferencesCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Updated);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Ok<Updated> okResult = Assert.IsType<Ok<Updated>>(result);
|
||||
Assert.Equal(Result.Updated, okResult.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
UpdateSchedulerDisplayPreferencesRequest request = _updateSchedulerDisplayPreferencesRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = DomainErrors.Scheduling.SchedulerDisplayTimeSpanMustBePositive;
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateSchedulerDisplayPreferencesCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemResult.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorized_ShouldReturnForbiddenProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
UpdateSchedulerDisplayPreferencesRequest request = _updateSchedulerDisplayPreferencesRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateSchedulerDisplayPreferencesCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ApplicationErrors.Authorization.NotAuthorized);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendMappedCommandToHandler()
|
||||
{
|
||||
// Arrange
|
||||
UpdateSchedulerDisplayPreferencesRequest request = _updateSchedulerDisplayPreferencesRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateSchedulerDisplayPreferencesCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Updated);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<UpdateSchedulerDisplayPreferencesCommand>(command =>
|
||||
command.JobTypeFilter == request.JobTypeFilter &&
|
||||
command.DisplayTimeSpan == request.DisplayTimeSpan &&
|
||||
command.DisplayTimeUnit == request.DisplayTimeUnit),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user