mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 03:11:10 +00:00
Completes the scheduled jobs module with default jobs, a themed scheduler page and aligned recovery semantics
This commit is contained in:
1 parent
99a6159f7f
commit
4b7cfbbe11
67 files changed
+3324
-745
No files matched your search
+23
-8
@@ -146,24 +146,39 @@ public class ScheduledJobEntityMappingTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenRepositoryEntityHasDailySchedule_ShouldMapToResponse()
|
||||
public void ToDomainEntity_WhenRepositoryEntityHasOnceAtStartupSchedule_ShouldMapToOnceAtStartupScheduledJob()
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJobEntity repositoryEntity = _scheduledJobEntityFixture.Create(
|
||||
scheduleType: ScheduleType.OnceAtStartup,
|
||||
status: ScheduledJobStatus.Active);
|
||||
|
||||
// Act
|
||||
Result<ScheduledJob> result = repositoryEntity.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
OnceAtStartupSchedule onceAtStartupSchedule = Assert.IsType<OnceAtStartupSchedule>(result.Value.Schedule);
|
||||
Assert.Equal(ScheduleType.OnceAtStartup, onceAtStartupSchedule.ScheduleType);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenRepositoryEntityHasOnceAtStartupSchedule_ShouldMapToResponse()
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJobEntity repositoryEntity = _scheduledJobEntityFixture.Create(
|
||||
id: Guid.NewGuid(),
|
||||
scheduleType: ScheduleType.DailyAtHourAndMinute,
|
||||
hour: 6,
|
||||
minute: 30,
|
||||
status: ScheduledJobStatus.Added);
|
||||
scheduleType: ScheduleType.OnceAtStartup,
|
||||
status: ScheduledJobStatus.Active);
|
||||
|
||||
// Act
|
||||
ScheduledJobResponse result = repositoryEntity.ToResponse();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(ScheduleType.DailyAtHourAndMinute, result.ScheduleType);
|
||||
Assert.Equal(ScheduleType.OnceAtStartup, result.ScheduleType);
|
||||
Assert.Null(result.IntervalMinutes);
|
||||
Assert.Equal(6, result.Hour);
|
||||
Assert.Equal(30, result.Minute);
|
||||
Assert.Null(result.Hour);
|
||||
Assert.Null(result.Minute);
|
||||
}
|
||||
}
|
||||
+86
@@ -1,18 +1,24 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Users;
|
||||
using Lumina.Application.Common.DataAccess.Seed;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.DomainEvents;
|
||||
using Lumina.Application.Common.Errors;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Security;
|
||||
using Lumina.Application.Common.Infrastructure.Time;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Core.Maintenance.ApplicationSetup.Commands.SetupApplication;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Core.Maintenance.ApplicationSetup.Commands.SetupApplication;
|
||||
using Lumina.Contracts.Responses.Authentication;
|
||||
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;
|
||||
@@ -35,10 +41,13 @@ public class SetupApplicationCommandHandlerTests
|
||||
private readonly ITotpTokenGenerator _mockTotpTokenGenerator;
|
||||
private readonly IQRCodeGenerator _mockQRCodeGenerator;
|
||||
private readonly IUserRepository _mockUserRepository;
|
||||
private readonly IScheduledJobRepository _mockScheduledJobRepository;
|
||||
private readonly IDateTimeProvider _mockDateTimeProvider;
|
||||
private readonly IDataSeedService _mockDataSeedService;
|
||||
private readonly IDomainEventsQueue _mockDomainEventsQueue;
|
||||
private readonly SetupApplicationCommandHandler _sut;
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new();
|
||||
private readonly SetupApplicationCommandFixture _setupApplicationCommandFixture = new();
|
||||
|
||||
/// <summary>
|
||||
@@ -52,14 +61,21 @@ public class SetupApplicationCommandHandlerTests
|
||||
_mockTotpTokenGenerator = Substitute.For<ITotpTokenGenerator>();
|
||||
_mockQRCodeGenerator = Substitute.For<IQRCodeGenerator>();
|
||||
_mockUserRepository = Substitute.For<IUserRepository>();
|
||||
_mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
|
||||
_mockDateTimeProvider = Substitute.For<IDateTimeProvider>();
|
||||
_mockDataSeedService = Substitute.For<IDataSeedService>();
|
||||
_mockDomainEventsQueue = Substitute.For<IDomainEventsQueue>();
|
||||
IValidator<SetupApplicationCommand> mockValidator = Substitute.For<IValidator<SetupApplicationCommand>>();
|
||||
mockValidator.Validate(Arg.Any<SetupApplicationCommand>())
|
||||
.Returns([]);
|
||||
|
||||
_mockUnitOfWork.UserRepository.Returns(_mockUserRepository);
|
||||
_mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository);
|
||||
_mockDateTimeProvider.UtcNow.Returns(DateTime.UtcNow);
|
||||
_mockDataSeedService.SetDefaultScheduledJobsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
_mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Enumerable.Empty<ScheduledJobEntity>()));
|
||||
|
||||
_sut = new SetupApplicationCommandHandler(
|
||||
_mockUnitOfWork,
|
||||
@@ -69,6 +85,7 @@ public class SetupApplicationCommandHandlerTests
|
||||
_mockQRCodeGenerator,
|
||||
_mockDateTimeProvider,
|
||||
_mockDataSeedService,
|
||||
_mockDomainEventsQueue,
|
||||
mockValidator);
|
||||
}
|
||||
|
||||
@@ -336,6 +353,40 @@ public class SetupApplicationCommandHandlerTests
|
||||
await _mockDataSeedService.Received(1).SetDefaultAuthorizationRolesAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockDataSeedService.Received(1).SetAdminRolePermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockDataSeedService.Received(1).SetAdminRoleToAdministratorAccount(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockDataSeedService.DidNotReceive().SetDefaultScheduledJobsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenSeedingDefaultScheduledJobsFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
SetupApplicationCommand command = _setupApplicationCommandFixture.Create();
|
||||
Error error = Error.Failure("Database.Error", "Failed to seed default scheduled jobs");
|
||||
|
||||
_mockUserRepository.GetAllAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Enumerable.Empty<UserEntity>()));
|
||||
_mockUserRepository.InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
_mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
_mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
_mockDataSeedService.SetAdminRolePermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
_mockDataSeedService.SetAdminRoleToAdministratorAccount(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
_mockDataSeedService.SetDefaultScheduledJobsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(error);
|
||||
|
||||
// Act
|
||||
Result<RegistrationResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
|
||||
await _mockDataSeedService.Received(1).SetAdminRoleToAdministratorAccount(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockDataSeedService.Received(1).SetDefaultScheduledJobsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -369,5 +420,40 @@ public class SetupApplicationCommandHandlerTests
|
||||
await _mockDataSeedService.Received(1).SetDefaultAuthorizationRolesAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockDataSeedService.Received(1).SetAdminRolePermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockDataSeedService.Received(1).SetAdminRoleToAdministratorAccount(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockDataSeedService.Received(1).SetDefaultScheduledJobsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenDefaultScheduledJobsAreSeeded_ShouldQueueACycleStartedEventForEachActiveJob()
|
||||
{
|
||||
// Arrange
|
||||
SetupApplicationCommand command = _setupApplicationCommandFixture.Create();
|
||||
ScheduledJobEntity activeScheduledJob1 = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active);
|
||||
ScheduledJobEntity activeScheduledJob2 = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active);
|
||||
ScheduledJobEntity addedScheduledJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added);
|
||||
|
||||
_mockUserRepository.GetAllAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Enumerable.Empty<UserEntity>()));
|
||||
_mockUserRepository.InsertAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
_mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
_mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
_mockDataSeedService.SetAdminRolePermissionsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
_mockDataSeedService.SetAdminRoleToAdministratorAccount(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
_mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(new[] { activeScheduledJob1, activeScheduledJob2, addedScheduledJob });
|
||||
|
||||
// Act
|
||||
Result<RegistrationResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
_mockDomainEventsQueue.Received(1).Enqueue(Arg.Is<ScheduledJobCycleStartedDomainEvent>(domainEvent => domainEvent.ScheduledJobId.Value == activeScheduledJob1.Id));
|
||||
_mockDomainEventsQueue.Received(1).Enqueue(Arg.Is<ScheduledJobCycleStartedDomainEvent>(domainEvent => domainEvent.ScheduledJobId.Value == activeScheduledJob2.Id));
|
||||
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Is<ScheduledJobCycleStartedDomainEvent>(domainEvent => domainEvent.ScheduledJobId.Value == addedScheduledJob.Id));
|
||||
}
|
||||
}
|
||||
@@ -1,20 +1,25 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Users;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Errors;
|
||||
using Lumina.Application.Common.Infrastructure.Time;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.DataAccess.Core.Seed;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
|
||||
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
|
||||
@@ -35,6 +40,7 @@ public class DataSeedServiceTests
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly RoleEntityFixture _roleEntityFixture = new();
|
||||
private readonly PermissionEntityFixture _permissionEntityFixture = new();
|
||||
private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DataSeedServiceTests"/> class.
|
||||
@@ -543,4 +549,103 @@ public class DataSeedServiceTests
|
||||
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetDefaultScheduledJobsAsync_WhenNoScheduledJobsExist_ShouldInsertTheFiveDefaultJobsAndReturnCreated()
|
||||
{
|
||||
// Arrange
|
||||
Guid adminUserId = Guid.NewGuid();
|
||||
IScheduledJobRepository mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
|
||||
_mockUnitOfWork.ScheduledJobRepository.Returns(mockScheduledJobRepository);
|
||||
mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Enumerable.Empty<ScheduledJobEntity>()));
|
||||
List<ScheduledJobEntity> capturedScheduledJobs = [];
|
||||
mockScheduledJobRepository.InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created)
|
||||
.AndDoes(info => capturedScheduledJobs.Add(info.Arg<ScheduledJobEntity>()));
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.SetDefaultScheduledJobsAsync(adminUserId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Created, result.Value);
|
||||
Assert.Equal(5, capturedScheduledJobs.Count);
|
||||
Assert.All(capturedScheduledJobs, scheduledJob => Assert.Equal(ScheduledJobStatus.Active, scheduledJob.Status));
|
||||
Assert.All(capturedScheduledJobs, scheduledJob => Assert.Equal(adminUserId, scheduledJob.OwnerUserId));
|
||||
Assert.All(capturedScheduledJobs, scheduledJob => Assert.Equal(adminUserId, scheduledJob.CreatedBy));
|
||||
Assert.All(capturedScheduledJobs, scheduledJob => Assert.Equal(_fixedUtcNow, scheduledJob.CreatedOnUtc));
|
||||
Assert.Contains(capturedScheduledJobs, scheduledJob => scheduledJob.TaskType == ScheduledTaskType.ScanMediaLibraries && scheduledJob.ScheduleType == ScheduleType.DailyAtHourAndMinute && scheduledJob.Hour == 0 && scheduledJob.Minute == 0);
|
||||
Assert.Contains(capturedScheduledJobs, scheduledJob => scheduledJob.TaskType == ScheduledTaskType.CleanTemporaryFiles && scheduledJob.ScheduleType == ScheduleType.OnceAtStartup);
|
||||
Assert.Contains(capturedScheduledJobs, scheduledJob => scheduledJob.TaskType == ScheduledTaskType.CleanTemporaryFiles && scheduledJob.ScheduleType == ScheduleType.WithIntervalInMinutes && scheduledJob.IntervalMinutes == 720);
|
||||
Assert.Contains(capturedScheduledJobs, scheduledJob => scheduledJob.TaskType == ScheduledTaskType.RepairThemes && scheduledJob.ScheduleType == ScheduleType.OnceAtStartup);
|
||||
Assert.Contains(capturedScheduledJobs, scheduledJob => scheduledJob.TaskType == ScheduledTaskType.CleanScheduledJobExecutionHistory && scheduledJob.ScheduleType == ScheduleType.OnceAtStartup);
|
||||
|
||||
await mockScheduledJobRepository.Received(5).InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetDefaultScheduledJobsAsync_WhenScheduledJobsAlreadyExist_ShouldNotInsertAnyJob()
|
||||
{
|
||||
// Arrange
|
||||
Guid adminUserId = Guid.NewGuid();
|
||||
IScheduledJobRepository mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
|
||||
_mockUnitOfWork.ScheduledJobRepository.Returns(mockScheduledJobRepository);
|
||||
ScheduledJobEntity existingScheduledJob = _scheduledJobEntityFixture.Create(scheduleType: ScheduleType.WithIntervalInMinutes);
|
||||
mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(new[] { existingScheduledJob });
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.SetDefaultScheduledJobsAsync(adminUserId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Created, result.Value);
|
||||
await mockScheduledJobRepository.DidNotReceive().InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetDefaultScheduledJobsAsync_WhenGetAllScheduledJobsFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
Guid adminUserId = Guid.NewGuid();
|
||||
IScheduledJobRepository mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
|
||||
_mockUnitOfWork.ScheduledJobRepository.Returns(mockScheduledJobRepository);
|
||||
Error expectedError = Error.Failure("ScheduledJobs.NotFound", "Failed to retrieve the scheduled jobs");
|
||||
mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.SetDefaultScheduledJobsAsync(adminUserId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(expectedError, result.FirstError);
|
||||
await mockScheduledJobRepository.DidNotReceive().InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetDefaultScheduledJobsAsync_WhenInsertScheduledJobFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
Guid adminUserId = Guid.NewGuid();
|
||||
IScheduledJobRepository mockScheduledJobRepository = Substitute.For<IScheduledJobRepository>();
|
||||
_mockUnitOfWork.ScheduledJobRepository.Returns(mockScheduledJobRepository);
|
||||
mockScheduledJobRepository.GetAllAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Enumerable.Empty<ScheduledJobEntity>()));
|
||||
Error expectedError = Error.Failure("ScheduledJobs.InsertFailed", "Failed to insert the scheduled job");
|
||||
mockScheduledJobRepository.InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created, expectedError);
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.SetDefaultScheduledJobsAsync(adminUserId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(expectedError, result.FirstError);
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="OnceAtStartupSchedule"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class OnceAtStartupScheduleTests
|
||||
{
|
||||
private readonly OnceAtStartupScheduleFixture _onceAtStartupScheduleFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalled_ShouldCreateOnceAtStartupSchedule()
|
||||
{
|
||||
// Act
|
||||
OnceAtStartupSchedule schedule = _onceAtStartupScheduleFixture.Create();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(ScheduleType.OnceAtStartup, schedule.ScheduleType);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetDelayUntilNextExecution_WhenCalled_ShouldReturnTheMaximumDelay()
|
||||
{
|
||||
// Arrange
|
||||
OnceAtStartupSchedule schedule = _onceAtStartupScheduleFixture.Create();
|
||||
DateTime utcNow = new(2026, 1, 1, 10, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
// Act
|
||||
TimeSpan delay = schedule.GetDelayUntilNextExecution(utcNow, TimeZoneInfo.Utc);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(TimeSpan.MaxValue, delay);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WhenBothAreOnceAtStartupSchedules_ShouldReturnTrue()
|
||||
{
|
||||
// Act
|
||||
bool areEqual = _onceAtStartupScheduleFixture.Create().Equals(_onceAtStartupScheduleFixture.Create());
|
||||
|
||||
// Assert
|
||||
Assert.True(areEqual);
|
||||
}
|
||||
}
|
||||
+7
-4
@@ -32,14 +32,14 @@ public class ScheduledJobNotifierTests
|
||||
{
|
||||
_mockClient = Substitute.For<IScheduledJobsClient>();
|
||||
_mockHubClients = Substitute.For<IHubClients<IScheduledJobsClient>>();
|
||||
_mockHubClients.All.Returns(_mockClient);
|
||||
_mockHubClients.Group(ScheduledJobsHub.ADMINISTRATORS_GROUP).Returns(_mockClient);
|
||||
_mockHubContext = Substitute.For<IHubContext<ScheduledJobsHub, IScheduledJobsClient>>();
|
||||
_mockHubContext.Clients.Returns(_mockHubClients);
|
||||
_sut = new ScheduledJobNotifier(_mockHubContext);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendScheduledJobsAsync_WhenCalled_ShouldSendTheScheduledJobsToAllClients()
|
||||
public async Task SendScheduledJobsAsync_WhenCalled_ShouldSendTheScheduledJobsToTheAdministratorGroup()
|
||||
{
|
||||
// Arrange
|
||||
IReadOnlyList<ScheduledJobResponse> scheduledJobs = _scheduledJobResponseFixture.CreateMany(2);
|
||||
@@ -49,10 +49,11 @@ public class ScheduledJobNotifierTests
|
||||
|
||||
// Assert
|
||||
await _mockClient.Received(1).ReceiveScheduledJobsAsync(scheduledJobs);
|
||||
_mockHubClients.Received(1).Group(ScheduledJobsHub.ADMINISTRATORS_GROUP);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendScheduledJobExecutionStartedAsync_WhenCalled_ShouldSendTheExecutionToAllClients()
|
||||
public async Task SendScheduledJobExecutionStartedAsync_WhenCalled_ShouldSendTheExecutionToTheAdministratorGroup()
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJobExecutionResponse execution = _scheduledJobExecutionResponseFixture.Create();
|
||||
@@ -62,10 +63,11 @@ public class ScheduledJobNotifierTests
|
||||
|
||||
// Assert
|
||||
await _mockClient.Received(1).ScheduledJobExecutionStartedAsync(execution);
|
||||
_mockHubClients.Received(1).Group(ScheduledJobsHub.ADMINISTRATORS_GROUP);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendScheduledJobExecutionCompletedAsync_WhenCalled_ShouldSendTheExecutionToAllClients()
|
||||
public async Task SendScheduledJobExecutionCompletedAsync_WhenCalled_ShouldSendTheExecutionToTheAdministratorGroup()
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJobExecutionResponse execution = _scheduledJobExecutionResponseFixture.Create();
|
||||
@@ -75,5 +77,6 @@ public class ScheduledJobNotifierTests
|
||||
|
||||
// Assert
|
||||
await _mockClient.Received(1).ScheduledJobExecutionCompletedAsync(execution);
|
||||
_mockHubClients.Received(1).Group(ScheduledJobsHub.ADMINISTRATORS_GROUP);
|
||||
}
|
||||
}
|
||||
+5
-1
@@ -84,13 +84,16 @@ public class ScheduledJobsHubTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task OnConnectedAsync_WhenUserIsAdministrator_ShouldNotAbortTheConnection()
|
||||
public async Task OnConnectedAsync_WhenUserIsAdministrator_ShouldAddTheConnectionToTheAdministratorGroup()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
ClaimsPrincipal user = new(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, userId.ToString())]));
|
||||
HubCallerContext context = CreateHubCallerContext(user);
|
||||
context.ConnectionId.Returns("connection-1");
|
||||
_sut.Context = context;
|
||||
IGroupManager mockGroupManager = Substitute.For<IGroupManager>();
|
||||
_sut.Groups = mockGroupManager;
|
||||
_mockAuthorizationService.IsInRoleAsync(userId, "Admin", System.Threading.CancellationToken.None).Returns(true);
|
||||
|
||||
// Act
|
||||
@@ -98,6 +101,7 @@ public class ScheduledJobsHubTests
|
||||
|
||||
// Assert
|
||||
context.DidNotReceive().Abort();
|
||||
await mockGroupManager.Received(1).AddToGroupAsync("connection-1", ScheduledJobsHub.ADMINISTRATORS_GROUP, System.Threading.CancellationToken.None);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
-550
@@ -1,550 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Themes;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Themes;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Models.DTO.Themes;
|
||||
using Lumina.Application.Common.Infrastructure.Themes;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes;
|
||||
using Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.Themes;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Themes;
|
||||
using Lumina.Infrastructure.Core.Themes;
|
||||
using Lumina.Infrastructure.Fixtures.Core.Themes;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.Themes;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ThemeDetectionSyncJob"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ThemeDetectionSyncJobTests : IDisposable
|
||||
{
|
||||
private readonly IServiceScopeFactory _mockServiceScopeFactory;
|
||||
private readonly IServiceScope _mockServiceScope;
|
||||
private readonly IServiceProvider _mockServiceProvider;
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly IThemeRepository _mockThemeRepository;
|
||||
private readonly IThemeService _mockThemeService;
|
||||
private readonly ILogger<ThemeDetectionSyncJob> _mockLogger;
|
||||
private readonly ThemePackFixture _themePackFixture = new();
|
||||
private readonly ThemeEntityFixture _themeEntityFixture = new();
|
||||
private readonly ThemeManifestDtoFixture _themeManifestDtoFixture = new();
|
||||
private readonly string _testRootPath;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ThemeDetectionSyncJobTests"/> class.
|
||||
/// </summary>
|
||||
public ThemeDetectionSyncJobTests()
|
||||
{
|
||||
_testRootPath = Path.Combine(Path.GetTempPath(), $"lumina-theme-job-{Guid.NewGuid():N}");
|
||||
Directory.CreateDirectory(_testRootPath);
|
||||
_mockServiceScopeFactory = Substitute.For<IServiceScopeFactory>();
|
||||
_mockServiceScope = Substitute.For<IServiceScope>();
|
||||
_mockServiceProvider = Substitute.For<IServiceProvider>();
|
||||
_mockServiceScopeFactory.CreateAsyncScope().Returns(new AsyncServiceScope(_mockServiceScope));
|
||||
_mockServiceScope.ServiceProvider.Returns(_mockServiceProvider);
|
||||
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockThemeRepository = Substitute.For<IThemeRepository>();
|
||||
_mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository);
|
||||
_mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork);
|
||||
|
||||
_mockThemeService = Substitute.For<IThemeService>();
|
||||
_mockThemeService.HasThemePack(Arg.Any<string>()).Returns(true);
|
||||
_mockLogger = Substitute.For<ILogger<ThemeDetectionSyncJob>>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Cleans up the temporary storage used by the tests.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(_testRootPath))
|
||||
Directory.Delete(_testRootPath, recursive: true);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
// best effort cleanup of the per-test temp directory
|
||||
}
|
||||
catch (UnauthorizedAccessException)
|
||||
{
|
||||
// best effort cleanup of the per-test temp directory
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartAsync_WhenThereAreNoBundledThemesAndNoInstalledThemes_ShouldOnlySaveChanges()
|
||||
{
|
||||
// Arrange
|
||||
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ThemeEntity>>([]));
|
||||
_mockThemeService.GetBundledThemeArchivePaths().Returns([]);
|
||||
|
||||
// Act
|
||||
await StartAndWaitForExecutionAsync(CreateSut());
|
||||
|
||||
// Assert
|
||||
await _mockThemeRepository.DidNotReceiveWithAnyArgs().InsertAsync(default!, Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartAsync_WhenBundledThemeIsNotYetInstalled_ShouldInstallAndPersistTheTheme()
|
||||
{
|
||||
// Arrange
|
||||
string archivePath = CreateBundledArchiveFile("bundled-theme");
|
||||
ThemeManifestDto manifest = _themeManifestDtoFixture.Create(id: "bundled-theme");
|
||||
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ThemeEntity>>([]));
|
||||
_mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]);
|
||||
_mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any<CancellationToken>()).Returns(manifest);
|
||||
_mockThemeService.InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>()).Returns(manifest);
|
||||
_mockThemeRepository.InsertAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>()).Returns(Result.From(Result.Created));
|
||||
|
||||
// Act
|
||||
await StartAndWaitForExecutionAsync(CreateSut());
|
||||
|
||||
// Assert
|
||||
await _mockThemeService.Received(1).InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>());
|
||||
await _mockThemeRepository.Received(1).InsertAsync(
|
||||
Arg.Is<ThemeEntity>(theme => theme.ThemeId == "bundled-theme"
|
||||
&& theme.Name == manifest.Name
|
||||
&& theme.Description == manifest.Description
|
||||
&& theme.Version == manifest.Version
|
||||
&& theme.InstallSource == ThemeInstallSource.Bundled),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartAsync_WhenBundledThemeIsAlreadyInstalled_ShouldSkipInstallingIt()
|
||||
{
|
||||
// Arrange
|
||||
ThemeEntity existingTheme = _themeEntityFixture.Create(themeId: "bundled-theme", isCurrent: true, includeIsCurrent: true, installSource: ThemeInstallSource.Bundled, isDeleted: false);
|
||||
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ThemeEntity>>([existingTheme]));
|
||||
_mockThemeService.GetBundledThemeArchivePaths().Returns(["C:\\bundled\\bundled-theme.zip"]);
|
||||
_mockThemeService.ReadManifestFromArchiveAsync("C:\\bundled\\bundled-theme.zip", Arg.Any<CancellationToken>()).Returns(_themeManifestDtoFixture.Create(id: "bundled-theme"));
|
||||
|
||||
// Act
|
||||
await StartAndWaitForExecutionAsync(CreateSut());
|
||||
|
||||
// Assert
|
||||
await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>());
|
||||
await _mockThemeRepository.DidNotReceiveWithAnyArgs().InsertAsync(default!, Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartAsync_WhenBundledThemeWasSoftDeletedByTheUser_ShouldNotReinstallIt()
|
||||
{
|
||||
// Arrange
|
||||
ThemeEntity deletedTheme = _themeEntityFixture.Create(themeId: "bundled-theme", isDeleted: true, installSource: ThemeInstallSource.Bundled);
|
||||
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ThemeEntity>>([deletedTheme]));
|
||||
_mockThemeService.GetBundledThemeArchivePaths().Returns(["C:\\bundled\\bundled-theme.zip"]);
|
||||
_mockThemeService.ReadManifestFromArchiveAsync("C:\\bundled\\bundled-theme.zip", Arg.Any<CancellationToken>()).Returns(_themeManifestDtoFixture.Create(id: "bundled-theme"));
|
||||
|
||||
// Act
|
||||
await StartAndWaitForExecutionAsync(CreateSut());
|
||||
|
||||
// Assert
|
||||
await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>());
|
||||
await _mockThemeRepository.DidNotReceiveWithAnyArgs().InsertAsync(default!, Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartAsync_WhenInstalledBundledThemePackIsMissingAndNotDeleted_ShouldReinstallTheFilesWithoutInsertingANewRow()
|
||||
{
|
||||
// Arrange
|
||||
ThemeEntity existingTheme = _themeEntityFixture.Create(themeId: "bundled-theme", isCurrent: true, includeIsCurrent: true, installSource: ThemeInstallSource.Bundled, isDeleted: false);
|
||||
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ThemeEntity>>([existingTheme]));
|
||||
_mockThemeService.HasThemePack("bundled-theme").Returns(false);
|
||||
string archivePath = CreateBundledArchiveFile("bundled-theme");
|
||||
ThemeManifestDto manifest = _themeManifestDtoFixture.Create(id: "bundled-theme");
|
||||
_mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]);
|
||||
_mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any<CancellationToken>()).Returns(manifest);
|
||||
_mockThemeService.InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>()).Returns(manifest);
|
||||
_mockThemeService.RestoreBundledThemeAsync("bundled-theme", Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
|
||||
// Act
|
||||
await StartAndWaitForExecutionAsync(CreateSut());
|
||||
|
||||
// Assert
|
||||
await _mockThemeService.Received(1).InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>());
|
||||
await _mockThemeRepository.DidNotReceiveWithAnyArgs().InsertAsync(default!, Arg.Any<CancellationToken>());
|
||||
await _mockThemeRepository.DidNotReceiveWithAnyArgs().UpdateAsync(default!, Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartAsync_WhenBundledArchiveManifestCannotBeRead_ShouldSkipTheArchive()
|
||||
{
|
||||
// Arrange
|
||||
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ThemeEntity>>([]));
|
||||
_mockThemeService.GetBundledThemeArchivePaths().Returns(["C:\\bundled\\broken.zip"]);
|
||||
_mockThemeService.ReadManifestFromArchiveAsync("C:\\bundled\\broken.zip", Arg.Any<CancellationToken>()).Returns(Error.Failure("Theme.Files", "unreadable"));
|
||||
|
||||
// Act
|
||||
await StartAndWaitForExecutionAsync(CreateSut());
|
||||
|
||||
// Assert
|
||||
await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>());
|
||||
await _mockThemeRepository.DidNotReceiveWithAnyArgs().InsertAsync(default!, Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartAsync_WhenBundledThemeInstallFails_ShouldNotPersistTheTheme()
|
||||
{
|
||||
// Arrange
|
||||
string archivePath = CreateBundledArchiveFile("bundled-theme");
|
||||
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ThemeEntity>>([]));
|
||||
_mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]);
|
||||
_mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any<CancellationToken>()).Returns(_themeManifestDtoFixture.Create(id: "bundled-theme"));
|
||||
_mockThemeService.InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>()).Returns(Error.Failure("Theme.Install", "install failed"));
|
||||
|
||||
// Act
|
||||
await StartAndWaitForExecutionAsync(CreateSut());
|
||||
|
||||
// Assert
|
||||
await _mockThemeRepository.DidNotReceiveWithAnyArgs().InsertAsync(default!, Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartAsync_WhenPersistingDetectedThemeFails_ShouldLogWarningAndContinue()
|
||||
{
|
||||
// Arrange
|
||||
string archivePath = CreateBundledArchiveFile("bundled-theme");
|
||||
ThemeManifestDto manifest = _themeManifestDtoFixture.Create(id: "bundled-theme");
|
||||
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ThemeEntity>>([]));
|
||||
_mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]);
|
||||
_mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any<CancellationToken>()).Returns(manifest);
|
||||
_mockThemeService.InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>()).Returns(manifest);
|
||||
_mockThemeRepository.InsertAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>()).Returns(Error.Failure("Database.Error", "failed to persist"));
|
||||
|
||||
// Act
|
||||
await StartAndWaitForExecutionAsync(CreateSut());
|
||||
|
||||
// Assert
|
||||
await _mockThemeRepository.Received(1).InsertAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartAsync_WhenReadingInstalledThemesFails_ShouldReturnWithoutPersistingChanges()
|
||||
{
|
||||
// Arrange
|
||||
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Error.Failure("Database.Error", "failed to read themes"));
|
||||
|
||||
// Act
|
||||
await StartAndWaitForExecutionAsync(CreateSut());
|
||||
|
||||
// Assert
|
||||
_mockThemeService.DidNotReceive().GetBundledThemeArchivePaths();
|
||||
await _mockUnitOfWork.DidNotReceiveWithAnyArgs().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartAsync_WhenMissingBundledThemePackCanBeRestored_ShouldRestoreTheFiles()
|
||||
{
|
||||
// Arrange
|
||||
ThemeEntity brokenTheme = _themeEntityFixture.Create(themeId: "bundled-theme", isCurrent: true, includeIsCurrent: true, installSource: ThemeInstallSource.Bundled, isDeleted: false);
|
||||
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ThemeEntity>>([brokenTheme]));
|
||||
_mockThemeService.HasThemePack("bundled-theme").Returns(false);
|
||||
_mockThemeService.GetBundledThemeArchivePaths().Returns([]);
|
||||
_mockThemeService.RestoreBundledThemeAsync("bundled-theme", Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
|
||||
// Act
|
||||
await StartAndWaitForExecutionAsync(CreateSut());
|
||||
|
||||
// Assert
|
||||
await _mockThemeService.Received(1).RestoreBundledThemeAsync("bundled-theme", Arg.Any<CancellationToken>());
|
||||
await _mockThemeRepository.DidNotReceiveWithAnyArgs().UpdateAsync(default!, Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartAsync_WhenRestoringBundledThemeThrows_ShouldNotCrashTheJob()
|
||||
{
|
||||
// Arrange
|
||||
ThemeEntity brokenTheme = _themeEntityFixture.Create(themeId: "bundled-theme", installSource: ThemeInstallSource.Bundled, isDeleted: false);
|
||||
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ThemeEntity>>([brokenTheme]));
|
||||
_mockThemeService.HasThemePack("bundled-theme").Returns(false);
|
||||
_mockThemeService.GetBundledThemeArchivePaths().Returns([]);
|
||||
_mockThemeService.RestoreBundledThemeAsync("bundled-theme", Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromException<Result<Success>>(new IOException("The theme storage is locked.")));
|
||||
_mockThemeRepository.UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>()).Returns(Result.From(Result.Updated));
|
||||
|
||||
// Act
|
||||
await StartAndWaitForExecutionAsync(CreateSut());
|
||||
|
||||
// Assert
|
||||
await _mockThemeService.Received(1).RestoreBundledThemeAsync("bundled-theme", Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartAsync_WhenLastBundledThemePackCannotBeRestored_ShouldKeepAndActivateTheTheme()
|
||||
{
|
||||
// Arrange
|
||||
ThemeEntity brokenTheme = _themeEntityFixture.Create(themeId: "bundled-theme", installSource: ThemeInstallSource.Bundled, isDeleted: false);
|
||||
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ThemeEntity>>([brokenTheme]));
|
||||
_mockThemeService.HasThemePack("bundled-theme").Returns(false);
|
||||
_mockThemeService.GetBundledThemeArchivePaths().Returns([]);
|
||||
_mockThemeService.RestoreBundledThemeAsync("bundled-theme", Arg.Any<CancellationToken>()).Returns(Error.Failure("Theme.Files", "restore failed"));
|
||||
_mockThemeRepository.UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>()).Returns(Result.From(Result.Updated));
|
||||
|
||||
// Act
|
||||
await StartAndWaitForExecutionAsync(CreateSut());
|
||||
|
||||
// Assert
|
||||
await _mockThemeRepository.Received(1).UpdateAsync(
|
||||
Arg.Is<ThemeEntity>(theme => theme.ThemeId == "bundled-theme" && theme.IsCurrent == true && !theme.IsDeleted),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockThemeService.Received(1).RestoreBundledThemeAsync("bundled-theme", Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartAsync_WhenMissingBundledThemePackCannotBeRestoredAndAnotherBundledThemeRemains_ShouldSoftDeleteTheTheme()
|
||||
{
|
||||
// Arrange
|
||||
ThemeEntity brokenTheme = _themeEntityFixture.Create(themeId: "broken-theme", installSource: ThemeInstallSource.Bundled, isDeleted: false);
|
||||
ThemeEntity healthyTheme = _themeEntityFixture.Create(themeId: "healthy-theme", installSource: ThemeInstallSource.Bundled, isDeleted: false);
|
||||
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ThemeEntity>>([brokenTheme, healthyTheme]));
|
||||
_mockThemeService.HasThemePack("broken-theme").Returns(false);
|
||||
_mockThemeService.GetBundledThemeArchivePaths().Returns([]);
|
||||
_mockThemeService.RestoreBundledThemeAsync("broken-theme", Arg.Any<CancellationToken>()).Returns(Error.Failure("Theme.Files", "restore failed"));
|
||||
_mockThemeRepository.UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>()).Returns(Result.From(Result.Updated));
|
||||
|
||||
// Act
|
||||
await StartAndWaitForExecutionAsync(CreateSut());
|
||||
|
||||
// Assert
|
||||
await _mockThemeRepository.Received(1).UpdateAsync(
|
||||
Arg.Is<ThemeEntity>(theme => theme.ThemeId == "broken-theme" && theme.IsDeleted && theme.IsCurrent == null),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockThemeRepository.Received(1).UpdateAsync(
|
||||
Arg.Is<ThemeEntity>(theme => theme.ThemeId == "healthy-theme" && theme.IsCurrent == true),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartAsync_WhenMissingUserThemePackExists_ShouldDeleteTheTheme()
|
||||
{
|
||||
// Arrange
|
||||
ThemeEntity brokenTheme = _themeEntityFixture.Create(themeId: "user-theme", installSource: ThemeInstallSource.Uploaded, isDeleted: false);
|
||||
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ThemeEntity>>([brokenTheme]));
|
||||
_mockThemeService.HasThemePack("user-theme").Returns(false);
|
||||
_mockThemeService.GetBundledThemeArchivePaths().Returns([]);
|
||||
_mockThemeRepository.DeleteByIdAsync(brokenTheme.Id, Arg.Any<CancellationToken>()).Returns(Result.From(Result.Deleted));
|
||||
|
||||
// Act
|
||||
await StartAndWaitForExecutionAsync(CreateSut());
|
||||
|
||||
// Assert
|
||||
await _mockThemeRepository.Received(1).DeleteByIdAsync(brokenTheme.Id, Arg.Any<CancellationToken>());
|
||||
await _mockThemeService.DidNotReceive().RestoreBundledThemeAsync(Arg.Any<string>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartAsync_WhenDeletingMissingUserThemeFails_ShouldLogWarningAndContinue()
|
||||
{
|
||||
// Arrange
|
||||
ThemeEntity brokenTheme = _themeEntityFixture.Create(themeId: "user-theme", installSource: ThemeInstallSource.Uploaded, isDeleted: false);
|
||||
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ThemeEntity>>([brokenTheme]));
|
||||
_mockThemeService.HasThemePack("user-theme").Returns(false);
|
||||
_mockThemeService.GetBundledThemeArchivePaths().Returns([]);
|
||||
_mockThemeRepository.DeleteByIdAsync(brokenTheme.Id, Arg.Any<CancellationToken>()).Returns(Error.Failure("Database.Error", "delete failed"));
|
||||
|
||||
// Act
|
||||
await StartAndWaitForExecutionAsync(CreateSut());
|
||||
|
||||
// Assert
|
||||
await _mockThemeRepository.Received(1).DeleteByIdAsync(brokenTheme.Id, Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartAsync_WhenNoThemeIsCurrent_ShouldActivateTheDefaultTheme()
|
||||
{
|
||||
// Arrange
|
||||
ThemeEntity theme = _themeEntityFixture.Create(themeId: "default-theme", installSource: ThemeInstallSource.Bundled, isDeleted: false);
|
||||
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ThemeEntity>>([theme]));
|
||||
_mockThemeService.DefaultThemeId.Returns("default-theme");
|
||||
_mockThemeService.GetBundledThemeArchivePaths().Returns([]);
|
||||
_mockThemeRepository.UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>()).Returns(Result.From(Result.Updated));
|
||||
|
||||
// Act
|
||||
await StartAndWaitForExecutionAsync(CreateSut());
|
||||
|
||||
// Assert
|
||||
await _mockThemeRepository.Received(1).UpdateAsync(
|
||||
Arg.Is<ThemeEntity>(candidate => candidate.ThemeId == "default-theme" && candidate.IsCurrent == true),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartAsync_WhenNoThemeIsCurrent_ShouldPreferTheConfiguredDefaultTheme()
|
||||
{
|
||||
// Arrange
|
||||
ThemeEntity firstTheme = _themeEntityFixture.Create(themeId: "alpha-theme", installSource: ThemeInstallSource.Bundled, isDeleted: false);
|
||||
ThemeEntity defaultTheme = _themeEntityFixture.Create(themeId: "default-theme", installSource: ThemeInstallSource.Bundled, isDeleted: false);
|
||||
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ThemeEntity>>([firstTheme, defaultTheme]));
|
||||
_mockThemeService.DefaultThemeId.Returns("default-theme");
|
||||
_mockThemeService.GetBundledThemeArchivePaths().Returns([]);
|
||||
_mockThemeRepository.UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>()).Returns(Result.From(Result.Updated));
|
||||
|
||||
// Act
|
||||
await StartAndWaitForExecutionAsync(CreateSut());
|
||||
|
||||
// Assert
|
||||
await _mockThemeRepository.Received(1).UpdateAsync(
|
||||
Arg.Is<ThemeEntity>(candidate => candidate.ThemeId == "default-theme" && candidate.IsCurrent == true),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartAsync_WhenAThemeIsAlreadyCurrent_ShouldNotChangeActivation()
|
||||
{
|
||||
// Arrange
|
||||
ThemeEntity theme = _themeEntityFixture.Create(themeId: "current-theme", isCurrent: true, includeIsCurrent: true, installSource: ThemeInstallSource.Bundled, isDeleted: false);
|
||||
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ThemeEntity>>([theme]));
|
||||
_mockThemeService.GetBundledThemeArchivePaths().Returns([]);
|
||||
|
||||
// Act
|
||||
await StartAndWaitForExecutionAsync(CreateSut());
|
||||
|
||||
// Assert
|
||||
await _mockThemeRepository.DidNotReceiveWithAnyArgs().UpdateAsync(default!, Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartAsync_WhenBundledThemeArchiveFileCannotBeOpened_ShouldLogWarningAndContinue()
|
||||
{
|
||||
// Arrange
|
||||
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ThemeEntity>>([]));
|
||||
string missingArchivePath = Path.Combine(_testRootPath, "bundled", "missing.zip");
|
||||
_mockThemeService.GetBundledThemeArchivePaths().Returns([missingArchivePath]);
|
||||
_mockThemeService.ReadManifestFromArchiveAsync(missingArchivePath, Arg.Any<CancellationToken>()).Returns(_themeManifestDtoFixture.Create(id: "bundled-theme"));
|
||||
|
||||
// Act
|
||||
await StartAndWaitForExecutionAsync(CreateSut());
|
||||
|
||||
// Assert
|
||||
await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>());
|
||||
await _mockThemeRepository.DidNotReceiveWithAnyArgs().InsertAsync(default!, Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartAsync_WhenBundledThemeArchivePathIsADirectory_ShouldLogWarningAndContinue()
|
||||
{
|
||||
// Arrange
|
||||
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ThemeEntity>>([]));
|
||||
string directoryPath = Path.Combine(_testRootPath, "not-an-archive");
|
||||
Directory.CreateDirectory(directoryPath);
|
||||
_mockThemeService.GetBundledThemeArchivePaths().Returns([directoryPath]);
|
||||
_mockThemeService.ReadManifestFromArchiveAsync(directoryPath, Arg.Any<CancellationToken>()).Returns(_themeManifestDtoFixture.Create(id: "bundled-theme"));
|
||||
|
||||
// Act
|
||||
await StartAndWaitForExecutionAsync(CreateSut());
|
||||
|
||||
// Assert
|
||||
await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>());
|
||||
await _mockThemeRepository.DidNotReceiveWithAnyArgs().InsertAsync(default!, Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartAsync_WhenSoftDeletingUnrestorableBundledThemeFails_ShouldLogWarningAndContinue()
|
||||
{
|
||||
// Arrange
|
||||
ThemeEntity brokenTheme = _themeEntityFixture.Create(themeId: "broken-theme", installSource: ThemeInstallSource.Bundled, isDeleted: false);
|
||||
ThemeEntity healthyTheme = _themeEntityFixture.Create(themeId: "healthy-theme", isCurrent: true, includeIsCurrent: true, installSource: ThemeInstallSource.Bundled, isDeleted: false);
|
||||
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ThemeEntity>>([brokenTheme, healthyTheme]));
|
||||
_mockThemeService.HasThemePack("broken-theme").Returns(false);
|
||||
_mockThemeService.GetBundledThemeArchivePaths().Returns([]);
|
||||
_mockThemeService.RestoreBundledThemeAsync("broken-theme", Arg.Any<CancellationToken>()).Returns(Error.Failure("Theme.Files", "restore failed"));
|
||||
_mockThemeRepository.UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>()).Returns(Error.Failure("Database.Error", "update failed"));
|
||||
|
||||
// Act
|
||||
await StartAndWaitForExecutionAsync(CreateSut());
|
||||
|
||||
// Assert
|
||||
await _mockThemeRepository.Received(1).UpdateAsync(
|
||||
Arg.Is<ThemeEntity>(theme => theme.ThemeId == "broken-theme" && theme.IsDeleted && theme.IsCurrent == null),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartAsync_WhenCancellationIsRequestedWhileCleaningUp_ShouldLetTheCancellationPropagate()
|
||||
{
|
||||
// Arrange
|
||||
ThemeEntity brokenTheme = _themeEntityFixture.Create(themeId: "user-theme", installSource: ThemeInstallSource.Uploaded, isDeleted: false);
|
||||
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ThemeEntity>>([brokenTheme]));
|
||||
_mockThemeService.HasThemePack("user-theme").Returns(false);
|
||||
_mockThemeService.GetBundledThemeArchivePaths().Returns([]);
|
||||
_mockThemeRepository.DeleteByIdAsync(brokenTheme.Id, Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromException<Result<Deleted>>(new OperationCanceledException()));
|
||||
|
||||
// Act
|
||||
Task executionTask = StartAndWaitForExecutionAsync(CreateSut());
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => executionTask);
|
||||
await _mockUnitOfWork.DidNotReceiveWithAnyArgs().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Invokes the protected <see cref="BackgroundService.ExecuteAsync"/> of the job and awaits its completion.
|
||||
/// </summary>
|
||||
/// <param name="sut">The job to execute.</param>
|
||||
private static async Task StartAndWaitForExecutionAsync(ThemeDetectionSyncJob sut)
|
||||
{
|
||||
MethodInfo executeAsyncMethod = typeof(ThemeDetectionSyncJob).GetMethod("ExecuteAsync", BindingFlags.Instance | BindingFlags.NonPublic)!;
|
||||
Task executingTask = (Task)executeAsyncMethod.Invoke(sut, [CancellationToken.None])!;
|
||||
await executingTask;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates the system under test wired to the mocked dependencies.
|
||||
/// </summary>
|
||||
/// <returns>The created job instance.</returns>
|
||||
private ThemeDetectionSyncJob CreateSut()
|
||||
{
|
||||
return new ThemeDetectionSyncJob(_mockServiceScopeFactory, _mockThemeService, _mockLogger);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes a bundled theme archive file into the per-test temporary directory.
|
||||
/// </summary>
|
||||
/// <param name="themeId">The theme id of the bundled archive.</param>
|
||||
/// <returns>The path of the written archive.</returns>
|
||||
private string CreateBundledArchiveFile(string themeId)
|
||||
{
|
||||
string bundledPath = Path.Combine(_testRootPath, "bundled");
|
||||
Directory.CreateDirectory(bundledPath);
|
||||
string archivePath = Path.Combine(bundledPath, $"{themeId}.zip");
|
||||
File.WriteAllBytes(archivePath, _themePackFixture.Create(themeId: themeId));
|
||||
return archivePath;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user