Adds the scheduling module tests and centralizes domain event test fixtures

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

No files matched your search

@@ -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>());
}
}
@@ -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);
}
}
@@ -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);
}
}
@@ -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);
}
}
@@ -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);
}
}
@@ -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);
}
}
@@ -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);
}
}
@@ -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;
}
}