mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 11:11:10 +00:00
Hardens test assertions and adds missing test coverage.
This commit is contained in:
1 parent
6b86fd5805
commit
1189bbaf36
489 files changed
+39982
-512
No files matched your search
+13
-12
@@ -32,6 +32,7 @@ public class AuthorizationServiceTests
|
||||
private readonly IUserRepository _mockUserRepository;
|
||||
private readonly IAuthorizationPolicyFactory _mockAuthorizationPolicyFactory;
|
||||
private readonly AuthorizationService _sut;
|
||||
private readonly AuthorizationServiceFixture _authorizationServiceFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AuthorizationServiceTests"/> class.
|
||||
@@ -84,7 +85,7 @@ public class AuthorizationServiceTests
|
||||
public async Task HasPermissionAsync_WhenUserHasDirectPermission_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
UserEntity user = AuthorizationServiceFixture.CreateUserWithPermissions(
|
||||
UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions(
|
||||
directPermissions: [AuthorizationPermission.CanViewUsers]);
|
||||
|
||||
_mockUserRepository.GetByIdAsync(user.Id, Arg.Any<CancellationToken>())
|
||||
@@ -107,7 +108,7 @@ public class AuthorizationServiceTests
|
||||
{ "Admin", new[] { AuthorizationPermission.CanViewUsers } }
|
||||
};
|
||||
|
||||
UserEntity user = AuthorizationServiceFixture.CreateUserWithPermissions(
|
||||
UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions(
|
||||
rolePermissions: rolePermissions);
|
||||
|
||||
_mockUserRepository.GetByIdAsync(user.Id, Arg.Any<CancellationToken>())
|
||||
@@ -125,7 +126,7 @@ public class AuthorizationServiceTests
|
||||
public async Task HasPermissionAsync_WhenUserHasNoPermissions_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
UserEntity user = AuthorizationServiceFixture.CreateUserWithPermissions();
|
||||
UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions();
|
||||
|
||||
_mockUserRepository.GetByIdAsync(user.Id, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<UserEntity?>(user));
|
||||
@@ -142,7 +143,7 @@ public class AuthorizationServiceTests
|
||||
public async Task HasPermissionAsync_WhenUserHasDifferentPermission_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
UserEntity user = AuthorizationServiceFixture.CreateUserWithPermissions(
|
||||
UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions(
|
||||
directPermissions: [AuthorizationPermission.CanDeleteUsers]);
|
||||
|
||||
_mockUserRepository.GetByIdAsync(user.Id, Arg.Any<CancellationToken>())
|
||||
@@ -165,7 +166,7 @@ public class AuthorizationServiceTests
|
||||
{ "Admin", new[] { AuthorizationPermission.CanViewUsers } }
|
||||
};
|
||||
|
||||
UserEntity user = AuthorizationServiceFixture.CreateUserWithPermissions(
|
||||
UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions(
|
||||
directPermissions: [AuthorizationPermission.CanViewUsers],
|
||||
rolePermissions: rolePermissions);
|
||||
|
||||
@@ -222,7 +223,7 @@ public class AuthorizationServiceTests
|
||||
{ "Admin", Array.Empty<AuthorizationPermission>() }
|
||||
};
|
||||
|
||||
UserEntity user = AuthorizationServiceFixture.CreateUserWithPermissions(
|
||||
UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions(
|
||||
rolePermissions: rolePermissions);
|
||||
|
||||
_mockUserRepository.GetByIdAsync(user.Id, Arg.Any<CancellationToken>())
|
||||
@@ -245,7 +246,7 @@ public class AuthorizationServiceTests
|
||||
{ "", Array.Empty<AuthorizationPermission>() }
|
||||
};
|
||||
|
||||
UserEntity user = AuthorizationServiceFixture.CreateUserWithPermissions(
|
||||
UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions(
|
||||
rolePermissions: rolePermissions);
|
||||
|
||||
_mockUserRepository.GetByIdAsync(user.Id, Arg.Any<CancellationToken>())
|
||||
@@ -263,7 +264,7 @@ public class AuthorizationServiceTests
|
||||
public async Task IsInRoleAsync_WhenUserHasNoRoles_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
UserEntity user = AuthorizationServiceFixture.CreateUserWithPermissions();
|
||||
UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions();
|
||||
|
||||
_mockUserRepository.GetByIdAsync(user.Id, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<UserEntity?>(user));
|
||||
@@ -442,7 +443,7 @@ public class AuthorizationServiceTests
|
||||
public async Task GetUserAuthorizationAsync_WhenUserHasNoRolesOrPermissions_ShouldReturnEmptySets()
|
||||
{
|
||||
// Arrange
|
||||
UserEntity user = AuthorizationServiceFixture.CreateUserWithPermissions();
|
||||
UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions();
|
||||
_mockUserRepository.GetByIdAsync(user.Id, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<UserEntity?>(user));
|
||||
|
||||
@@ -461,7 +462,7 @@ public class AuthorizationServiceTests
|
||||
public async Task GetUserAuthorizationAsync_WhenUserHasOnlyDirectPermissions_ShouldReturnCorrectPermissions()
|
||||
{
|
||||
// Arrange
|
||||
UserEntity user = AuthorizationServiceFixture.CreateUserWithPermissions(
|
||||
UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions(
|
||||
directPermissions:
|
||||
[
|
||||
AuthorizationPermission.CanViewUsers,
|
||||
@@ -495,7 +496,7 @@ public class AuthorizationServiceTests
|
||||
}
|
||||
};
|
||||
|
||||
UserEntity user = AuthorizationServiceFixture.CreateUserWithPermissions(
|
||||
UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions(
|
||||
rolePermissions: rolePermissions);
|
||||
|
||||
_mockUserRepository.GetByIdAsync(user.Id, Arg.Any<CancellationToken>())
|
||||
@@ -525,7 +526,7 @@ public class AuthorizationServiceTests
|
||||
}
|
||||
};
|
||||
|
||||
UserEntity user = AuthorizationServiceFixture.CreateUserWithPermissions(
|
||||
UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions(
|
||||
directPermissions: [AuthorizationPermission.CanRegisterUsers],
|
||||
rolePermissions: rolePermissions);
|
||||
|
||||
|
||||
+10
-28
@@ -6,9 +6,9 @@ using Lumina.Application.Common.DataAccess.Repositories.Users;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.Common.Base;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Infrastructure.Core.Authorization.Policies.LibraryOwnership;
|
||||
using Lumina.Infrastructure.Fixtures.Core.Authorization;
|
||||
using NSubstitute;
|
||||
@@ -31,6 +31,8 @@ public class LibraryOwnershipPolicyTests
|
||||
private readonly IUserRepository _mockUserRepository;
|
||||
private readonly ILibraryRepository _mockLibraryRepository;
|
||||
private readonly LibraryOwnershipPolicy _sut;
|
||||
private readonly AuthorizationServiceFixture _authorizationServiceFixture = new();
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LibraryOwnershipPolicyTests"/> class.
|
||||
@@ -99,7 +101,7 @@ public class LibraryOwnershipPolicyTests
|
||||
public async Task EvaluateAsync_WhenUserIsAdmin_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
UserEntity adminUser = AuthorizationServiceFixture.CreateUserWithPermissions(
|
||||
UserEntity adminUser = _authorizationServiceFixture.CreateUserWithPermissions(
|
||||
rolePermissions: new Dictionary<string, IEnumerable<AuthorizationPermission>>
|
||||
{
|
||||
{ "Admin", [] }
|
||||
@@ -121,7 +123,7 @@ public class LibraryOwnershipPolicyTests
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
UserEntity regularUser = AuthorizationServiceFixture.CreateUserWithPermissions();
|
||||
UserEntity regularUser = _authorizationServiceFixture.CreateUserWithPermissions();
|
||||
LibraryOwnershipPolicyContext context = new(Guid.NewGuid());
|
||||
_mockUserRepository.GetByIdAsync(userId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<UserEntity?>(regularUser));
|
||||
@@ -140,7 +142,7 @@ public class LibraryOwnershipPolicyTests
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
UserEntity regularUser = AuthorizationServiceFixture.CreateUserWithPermissions();
|
||||
UserEntity regularUser = _authorizationServiceFixture.CreateUserWithPermissions();
|
||||
LibraryOwnershipPolicyContext context = new(Guid.NewGuid());
|
||||
_mockUserRepository.GetByIdAsync(userId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<UserEntity?>(regularUser));
|
||||
@@ -159,8 +161,8 @@ public class LibraryOwnershipPolicyTests
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
UserEntity regularUser = AuthorizationServiceFixture.CreateUserWithPermissions();
|
||||
LibraryEntity library = CreateLibrary(userId);
|
||||
UserEntity regularUser = _authorizationServiceFixture.CreateUserWithPermissions();
|
||||
LibraryEntity library = _libraryEntityFixture.Create(userId: userId);
|
||||
LibraryOwnershipPolicyContext context = new(library.Id);
|
||||
_mockUserRepository.GetByIdAsync(userId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<UserEntity?>(regularUser));
|
||||
@@ -179,8 +181,8 @@ public class LibraryOwnershipPolicyTests
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
UserEntity regularUser = AuthorizationServiceFixture.CreateUserWithPermissions();
|
||||
LibraryEntity library = CreateLibrary(Guid.NewGuid());
|
||||
UserEntity regularUser = _authorizationServiceFixture.CreateUserWithPermissions();
|
||||
LibraryEntity library = _libraryEntityFixture.Create(userId: Guid.NewGuid());
|
||||
LibraryOwnershipPolicyContext context = new(library.Id);
|
||||
_mockUserRepository.GetByIdAsync(userId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<UserEntity?>(regularUser));
|
||||
@@ -193,24 +195,4 @@ public class LibraryOwnershipPolicyTests
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a library entity owned by <paramref name="ownerId"/>.
|
||||
/// </summary>
|
||||
/// <param name="ownerId">The Id of the user owning the library.</param>
|
||||
/// <returns>The created library entity.</returns>
|
||||
private static LibraryEntity CreateLibrary(Guid ownerId)
|
||||
{
|
||||
return new LibraryEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = ownerId,
|
||||
Title = "Test Library",
|
||||
LibraryType = LibraryType.Book,
|
||||
ContentLocations = [],
|
||||
CreatedBy = ownerId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
};
|
||||
}
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Users;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Time;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Infrastructure.Core.Authorization.Policies.Over18;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.Authorization.Policies.Over18;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="Over18Policy"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class Over18PolicyTests
|
||||
{
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly IUserRepository _mockUserRepository;
|
||||
private readonly Over18Policy _sut;
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="Over18PolicyTests"/> class.
|
||||
/// </summary>
|
||||
public Over18PolicyTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockUserRepository = Substitute.For<IUserRepository>();
|
||||
_mockUnitOfWork.UserRepository.Returns(_mockUserRepository);
|
||||
|
||||
_sut = new Over18Policy(_mockUnitOfWork, Substitute.For<IDateTimeProvider>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EvaluateAsync_WhenUserExists_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
UserEntity user = _userEntityFixture.Create();
|
||||
_mockUserRepository.GetByIdAsync(user.Id, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<UserEntity?>(user));
|
||||
|
||||
// Act
|
||||
bool result = await _sut.EvaluateAsync(user.Id, null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EvaluateAsync_WhenUserDoesNotExist_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
_mockUserRepository.GetByIdAsync(userId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<UserEntity?>(null));
|
||||
|
||||
// Act
|
||||
bool result = await _sut.EvaluateAsync(userId, null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EvaluateAsync_WhenGetUserReturnsFailure_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
_mockUserRepository.GetByIdAsync(userId, Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Database.Error", "Failed to retrieve user"));
|
||||
|
||||
// Act
|
||||
bool result = await _sut.EvaluateAsync(userId, null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EvaluateAsync_WhenUserEntityIsNull_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
_mockUserRepository.GetByIdAsync(userId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result<UserEntity?>.Success(null));
|
||||
|
||||
// Act
|
||||
bool result = await _sut.EvaluateAsync(userId, null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
}
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Cancellation;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Cancellation;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaLibrariesScanCancellationTracker"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaLibrariesScanCancellationTrackerTests
|
||||
{
|
||||
private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void GetTokenForScan_WhenScanWasRegistered_ShouldReturnActiveToken()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibrariesScanCancellationTracker sut = new();
|
||||
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
|
||||
// Act
|
||||
sut.RegisterScan(compositeId);
|
||||
CancellationToken token = sut.GetTokenForScan(compositeId);
|
||||
|
||||
// Assert
|
||||
Assert.False(token.IsCancellationRequested);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetTokenForScan_WhenScanWasNotRegistered_ShouldReturnNone()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibrariesScanCancellationTracker sut = new();
|
||||
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
|
||||
// Act
|
||||
CancellationToken token = sut.GetTokenForScan(compositeId);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(CancellationToken.None, token);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CancelScan_WhenScanWasRegistered_ShouldCancelItsTokenAndRemoveTheScan()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibrariesScanCancellationTracker sut = new();
|
||||
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
sut.RegisterScan(compositeId);
|
||||
CancellationToken token = sut.GetTokenForScan(compositeId);
|
||||
|
||||
// Act
|
||||
sut.CancelScan(compositeId);
|
||||
|
||||
// Assert
|
||||
Assert.True(token.IsCancellationRequested);
|
||||
Assert.Equal(CancellationToken.None, sut.GetTokenForScan(compositeId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RemoveScan_WhenScanWasRegistered_ShouldCancelItsTokenAndRemoveTheScan()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibrariesScanCancellationTracker sut = new();
|
||||
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
sut.RegisterScan(compositeId);
|
||||
CancellationToken token = sut.GetTokenForScan(compositeId);
|
||||
|
||||
// Act
|
||||
sut.RemoveScan(compositeId);
|
||||
|
||||
// Assert
|
||||
Assert.True(token.IsCancellationRequested);
|
||||
Assert.Equal(CancellationToken.None, sut.GetTokenForScan(compositeId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CancelScan_WhenScanWasNotRegistered_ShouldNotThrow()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibrariesScanCancellationTracker sut = new();
|
||||
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
|
||||
// Act
|
||||
Action act = () => sut.CancelScan(compositeId);
|
||||
|
||||
// Assert
|
||||
act();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Dispose_ShouldCancelAllRegisteredScans()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibrariesScanCancellationTracker sut = new();
|
||||
MediaLibraryScanCompositeId firstCompositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
MediaLibraryScanCompositeId secondCompositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
sut.RegisterScan(firstCompositeId);
|
||||
sut.RegisterScan(secondCompositeId);
|
||||
CancellationToken firstToken = sut.GetTokenForScan(firstCompositeId);
|
||||
CancellationToken secondToken = sut.GetTokenForScan(secondCompositeId);
|
||||
|
||||
// Act
|
||||
sut.Dispose();
|
||||
|
||||
// Assert
|
||||
Assert.True(firstToken.IsCancellationRequested);
|
||||
Assert.True(secondToken.IsCancellationRequested);
|
||||
}
|
||||
}
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Domain.Common.Events;
|
||||
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.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.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.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaLibraryScanDiffJob"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaLibraryScanDiffJobTests
|
||||
{
|
||||
private readonly IServiceScopeFactory _mockServiceScopeFactory;
|
||||
private readonly IServiceScope _mockServiceScope;
|
||||
private readonly IServiceProvider _mockServiceProvider;
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly ILibraryScanStagingResultsRepository _mockStagingResultsRepository;
|
||||
private readonly IDomainEventPublisher _mockDomainEventPublisher;
|
||||
private readonly MediaLibraryScanDiffJob _sut;
|
||||
private readonly ScanIdFixture _scanIdFixture = new();
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly ScanId _scanId;
|
||||
private readonly UserId _userId;
|
||||
private readonly LibraryId _libraryId;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaLibraryScanDiffJobTests"/> class.
|
||||
/// </summary>
|
||||
public MediaLibraryScanDiffJobTests()
|
||||
{
|
||||
_mockServiceScopeFactory = Substitute.For<IServiceScopeFactory>();
|
||||
_mockServiceScope = Substitute.For<IServiceScope>();
|
||||
_mockServiceProvider = Substitute.For<IServiceProvider>();
|
||||
_mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope);
|
||||
_mockServiceScope.ServiceProvider.Returns(_mockServiceProvider);
|
||||
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockStagingResultsRepository = Substitute.For<ILibraryScanStagingResultsRepository>();
|
||||
_mockUnitOfWork.LibraryScanStagingResultsRepository.Returns(_mockStagingResultsRepository);
|
||||
_mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork);
|
||||
|
||||
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
|
||||
_mockDomainEventPublisher.PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ValueTask.CompletedTask);
|
||||
_mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher);
|
||||
|
||||
_scanId = _scanIdFixture.Create();
|
||||
_userId = _userIdFixture.Create();
|
||||
_libraryId = _libraryIdFixture.Create();
|
||||
_sut = new MediaLibraryScanDiffJob(_mockServiceScopeFactory)
|
||||
{
|
||||
ScanId = _scanId,
|
||||
UserId = _userId,
|
||||
LibraryId = _libraryId
|
||||
};
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenMarkingChangesSucceeds_ShouldCompleteAndPublishProgress()
|
||||
{
|
||||
// Arrange
|
||||
_mockStagingResultsRepository.MarkChangesAgainstSnapshotAsync(_scanId.Value, _libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Updated));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
await _mockStagingResultsRepository.Received(1).MarkChangesAgainstSnapshotAsync(_scanId.Value, _libraryId.Value, Arg.Any<CancellationToken>());
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanProgressChangedDomainEvent>(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenMarkingChangesFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
|
||||
{
|
||||
// Arrange
|
||||
_mockStagingResultsRepository.MarkChangesAgainstSnapshotAsync(_scanId.Value, _libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Database.Error", "Failed to mark the changes against the snapshot"));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
|
||||
domainEvent.LibraryId == _libraryId
|
||||
&& domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId
|
||||
&& domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldMarkJobAsCanceledAndThrow()
|
||||
{
|
||||
// Arrange
|
||||
using CancellationTokenSource cancellationTokenSource = new();
|
||||
cancellationTokenSource.Cancel();
|
||||
|
||||
// Act
|
||||
Task operation = _sut.ExecuteAsync(Guid.NewGuid(), new { }, cancellationTokenSource.Token);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operation);
|
||||
Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status);
|
||||
}
|
||||
}
|
||||
+173
@@ -0,0 +1,173 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Models.DTO.MediaLibraryScanJobPayloads;
|
||||
using Lumina.Application.Common.Infrastructure.Security;
|
||||
using Lumina.Domain.Common.Events;
|
||||
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.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.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.Application.Fixtures.Common.Infrastructure.Models.DTO.MediaLibraryScanJobPayloads;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaLibraryScanHashJob"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaLibraryScanHashJobTests
|
||||
{
|
||||
private readonly IServiceScopeFactory _mockServiceScopeFactory;
|
||||
private readonly IServiceScope _mockServiceScope;
|
||||
private readonly IServiceProvider _mockServiceProvider;
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly ILibraryScanStagingResultsRepository _mockStagingResultsRepository;
|
||||
private readonly IDomainEventPublisher _mockDomainEventPublisher;
|
||||
private readonly IFileHashService _mockFileHashService;
|
||||
private readonly MediaLibraryScanHashJob _sut;
|
||||
private readonly ScanIdFixture _scanIdFixture = new();
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly HashedFileSystemFileDtoFixture _hashedFileSystemFileDtoFixture = new();
|
||||
private readonly ScanId _scanId;
|
||||
private readonly UserId _userId;
|
||||
private readonly LibraryId _libraryId;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaLibraryScanHashJobTests"/> class.
|
||||
/// </summary>
|
||||
public MediaLibraryScanHashJobTests()
|
||||
{
|
||||
_mockServiceScopeFactory = Substitute.For<IServiceScopeFactory>();
|
||||
_mockServiceScope = Substitute.For<IServiceScope>();
|
||||
_mockServiceProvider = Substitute.For<IServiceProvider>();
|
||||
_mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope);
|
||||
_mockServiceScope.ServiceProvider.Returns(_mockServiceProvider);
|
||||
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockStagingResultsRepository = Substitute.For<ILibraryScanStagingResultsRepository>();
|
||||
_mockUnitOfWork.LibraryScanStagingResultsRepository.Returns(_mockStagingResultsRepository);
|
||||
_mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork);
|
||||
|
||||
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
|
||||
_mockDomainEventPublisher.PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ValueTask.CompletedTask);
|
||||
_mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher);
|
||||
|
||||
_mockFileHashService = Substitute.For<IFileHashService>();
|
||||
_mockServiceProvider.GetService(typeof(IFileHashService)).Returns(_mockFileHashService);
|
||||
|
||||
_scanId = _scanIdFixture.Create();
|
||||
_userId = _userIdFixture.Create();
|
||||
_libraryId = _libraryIdFixture.Create();
|
||||
_sut = new MediaLibraryScanHashJob(_mockServiceScopeFactory)
|
||||
{
|
||||
ScanId = _scanId,
|
||||
UserId = _userId,
|
||||
LibraryId = _libraryId
|
||||
};
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenFilesNeedHashing_ShouldHashAndPersistThemAndComplete()
|
||||
{
|
||||
// Arrange
|
||||
List<HashedFileSystemFileDto> filesToHash = [_hashedFileSystemFileDtoFixture.Create(path: "/books/book1.pdf"), _hashedFileSystemFileDtoFixture.Create(path: "/books/book2.pdf")];
|
||||
_mockStagingResultsRepository.GetFilesToHashCountAsync(_scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(2));
|
||||
_mockStagingResultsRepository.GetFilesToHashPageAsync(_scanId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(
|
||||
Result.From<IReadOnlyList<HashedFileSystemFileDto>>(filesToHash),
|
||||
Result.From<IReadOnlyList<HashedFileSystemFileDto>>([]));
|
||||
_mockFileHashService.HashFilesAsync(Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<Func<Task>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Task.FromResult(callInfo.Arg<IReadOnlyCollection<HashedFileSystemFileDto>>()
|
||||
.Select(file => file with { CurrentHash = 42UL })
|
||||
.ToList()));
|
||||
_mockStagingResultsRepository.UpdateFileHashesAsync(_scanId.Value, Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Updated));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
await _mockFileHashService.Received(1).HashFilesAsync(
|
||||
Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(),
|
||||
Arg.Any<Func<Task>>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockStagingResultsRepository.Received(1).UpdateFileHashesAsync(
|
||||
_scanId.Value,
|
||||
Arg.Is<IReadOnlyCollection<HashedFileSystemFileDto>>(files => files.Count == 2 && files.All(file => file.CurrentHash == 42UL)),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanProgressChangedDomainEvent>(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenNoFilesNeedHashing_ShouldCompleteWithoutHashing()
|
||||
{
|
||||
// Arrange
|
||||
_mockStagingResultsRepository.GetFilesToHashCountAsync(_scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(0));
|
||||
_mockStagingResultsRepository.GetFilesToHashPageAsync(_scanId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<HashedFileSystemFileDto>>([]));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
await _mockFileHashService.DidNotReceive().HashFilesAsync(Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<Func<Task>>(), Arg.Any<CancellationToken>());
|
||||
await _mockStagingResultsRepository.DidNotReceive().UpdateFileHashesAsync(Arg.Any<Guid>(), Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<CancellationToken>());
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanProgressChangedDomainEvent>(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCountingFilesFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
|
||||
{
|
||||
// Arrange
|
||||
_mockStagingResultsRepository.GetFilesToHashCountAsync(_scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Database.Error", "Failed to count the files to hash"));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
|
||||
await _mockFileHashService.DidNotReceive().HashFilesAsync(Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<Func<Task>>(), Arg.Any<CancellationToken>());
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
|
||||
domainEvent.LibraryId == _libraryId
|
||||
&& domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId
|
||||
&& domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldMarkJobAsCanceledAndThrow()
|
||||
{
|
||||
// Arrange
|
||||
using CancellationTokenSource cancellationTokenSource = new();
|
||||
cancellationTokenSource.Cancel();
|
||||
|
||||
// Act
|
||||
Task operation = _sut.ExecuteAsync(Guid.NewGuid(), new { }, cancellationTokenSource.Token);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operation);
|
||||
Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status);
|
||||
}
|
||||
}
|
||||
+142
@@ -0,0 +1,142 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Books;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Domain.Common.Events;
|
||||
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.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.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.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
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.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaLibraryScanMetadataEnrichmentJob"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaLibraryScanMetadataEnrichmentJobTests
|
||||
{
|
||||
private readonly IServiceScopeFactory _mockServiceScopeFactory;
|
||||
private readonly IServiceScope _mockServiceScope;
|
||||
private readonly IServiceProvider _mockServiceProvider;
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly ILibraryMetadataProviderConfigurationRepository _mockConfigurationRepository;
|
||||
private readonly IBookRepository _mockBookRepository;
|
||||
private readonly IDomainEventPublisher _mockDomainEventPublisher;
|
||||
private readonly ILogger<MediaLibraryScanMetadataEnrichmentJob> _mockLogger;
|
||||
private readonly MediaLibraryScanMetadataEnrichmentJob _sut;
|
||||
private readonly ScanIdFixture _scanIdFixture = new();
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly ScanId _scanId;
|
||||
private readonly UserId _userId;
|
||||
private readonly LibraryId _libraryId;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaLibraryScanMetadataEnrichmentJobTests"/> class.
|
||||
/// </summary>
|
||||
public MediaLibraryScanMetadataEnrichmentJobTests()
|
||||
{
|
||||
_mockServiceScopeFactory = Substitute.For<IServiceScopeFactory>();
|
||||
_mockServiceScope = Substitute.For<IServiceScope>();
|
||||
_mockServiceProvider = Substitute.For<IServiceProvider>();
|
||||
_mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope);
|
||||
_mockServiceScope.ServiceProvider.Returns(_mockServiceProvider);
|
||||
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockConfigurationRepository = Substitute.For<ILibraryMetadataProviderConfigurationRepository>();
|
||||
_mockBookRepository = Substitute.For<IBookRepository>();
|
||||
_mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockConfigurationRepository);
|
||||
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
|
||||
_mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork);
|
||||
|
||||
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
|
||||
_mockDomainEventPublisher.PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ValueTask.CompletedTask);
|
||||
_mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher);
|
||||
|
||||
_mockLogger = Substitute.For<ILogger<MediaLibraryScanMetadataEnrichmentJob>>();
|
||||
|
||||
_scanId = _scanIdFixture.Create();
|
||||
_userId = _userIdFixture.Create();
|
||||
_libraryId = _libraryIdFixture.Create();
|
||||
_sut = new MediaLibraryScanMetadataEnrichmentJob(_mockServiceScopeFactory, _mockLogger)
|
||||
{
|
||||
ScanId = _scanId,
|
||||
UserId = _userId,
|
||||
LibraryId = _libraryId
|
||||
};
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenNoBooksNeedEnrichment_ShouldCompleteAndPublishFinishedEvent()
|
||||
{
|
||||
// Arrange
|
||||
_mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>([]));
|
||||
_mockBookRepository.GetBooksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(0));
|
||||
_mockBookRepository.GetBooksNeedingMetadataAsync(_libraryId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<BookEntity>>([]));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFinishedDomainEvent>(domainEvent => domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenGettingConfigurationsFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
|
||||
{
|
||||
// Arrange
|
||||
_mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Database.Error", "Failed to get the metadata provider configurations"));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
|
||||
domainEvent.LibraryId == _libraryId
|
||||
&& domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId
|
||||
&& domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldMarkJobAsCanceledAndThrow()
|
||||
{
|
||||
// Arrange
|
||||
using CancellationTokenSource cancellationTokenSource = new();
|
||||
cancellationTokenSource.Cancel();
|
||||
|
||||
// Act
|
||||
Task operation = _sut.ExecuteAsync(Guid.NewGuid(), new { }, cancellationTokenSource.Token);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operation);
|
||||
Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status);
|
||||
}
|
||||
}
|
||||
+169
@@ -0,0 +1,169 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Books;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Domain.Common.Events;
|
||||
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.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.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.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
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.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaLibraryScanResultsSaveJob"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaLibraryScanResultsSaveJobTests
|
||||
{
|
||||
private readonly IServiceScopeFactory _mockServiceScopeFactory;
|
||||
private readonly IServiceScope _mockServiceScope;
|
||||
private readonly IServiceProvider _mockServiceProvider;
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly ILibraryScanSnapshotRepository _mockSnapshotRepository;
|
||||
private readonly IBookRepository _mockBookRepository;
|
||||
private readonly IDomainEventPublisher _mockDomainEventPublisher;
|
||||
private readonly MediaLibraryScanResultsSaveJob _sut;
|
||||
private readonly ScanIdFixture _scanIdFixture = new();
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly ScanId _scanId;
|
||||
private readonly UserId _userId;
|
||||
private readonly LibraryId _libraryId;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaLibraryScanResultsSaveJobTests"/> class.
|
||||
/// </summary>
|
||||
public MediaLibraryScanResultsSaveJobTests()
|
||||
{
|
||||
_mockServiceScopeFactory = Substitute.For<IServiceScopeFactory>();
|
||||
_mockServiceScope = Substitute.For<IServiceScope>();
|
||||
_mockServiceProvider = Substitute.For<IServiceProvider>();
|
||||
_mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope);
|
||||
_mockServiceScope.ServiceProvider.Returns(_mockServiceProvider);
|
||||
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockSnapshotRepository = Substitute.For<ILibraryScanSnapshotRepository>();
|
||||
_mockBookRepository = Substitute.For<IBookRepository>();
|
||||
_mockUnitOfWork.LibraryScanSnapshotRepository.Returns(_mockSnapshotRepository);
|
||||
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
|
||||
_mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork);
|
||||
|
||||
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
|
||||
_mockDomainEventPublisher.PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ValueTask.CompletedTask);
|
||||
_mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher);
|
||||
|
||||
_scanId = _scanIdFixture.Create();
|
||||
_userId = _userIdFixture.Create();
|
||||
_libraryId = _libraryIdFixture.Create();
|
||||
_sut = new MediaLibraryScanResultsSaveJob(_mockServiceScopeFactory)
|
||||
{
|
||||
ScanId = _scanId,
|
||||
UserId = _userId,
|
||||
LibraryId = _libraryId
|
||||
};
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenScanResultsAreApplied_ShouldCreateShellBooksAndPublishFinishedEvent()
|
||||
{
|
||||
// Arrange
|
||||
_mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<string>>(["deleted.pdf"]));
|
||||
_mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Updated));
|
||||
_mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<string>>(["book1.pdf", "book2.pdf"]));
|
||||
_mockBookRepository.GetByPathAsync(_libraryId.Value, Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<BookEntity?>(null));
|
||||
_mockBookRepository.InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Created));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryMediaItemDeletedDomainEvent>(domainEvent => domainEvent.Path == "deleted.pdf"), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.Received(1).InsertAsync(Arg.Is<BookEntity>(book => book.Path == "book1.pdf" && book.Title == "book1" && book.MetadataStatus == MetadataStatus.Pending), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.Received(1).InsertAsync(Arg.Is<BookEntity>(book => book.Path == "book2.pdf" && book.Title == "book2" && book.MetadataStatus == MetadataStatus.Pending), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFinishedDomainEvent>(domainEvent => domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenBookAlreadyExists_ShouldSkipInsertingIt()
|
||||
{
|
||||
// Arrange
|
||||
_mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<string>>([]));
|
||||
_mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Updated));
|
||||
_mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<string>>(["existing.pdf"]));
|
||||
_mockBookRepository.GetByPathAsync(_libraryId.Value, "existing.pdf", Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<BookEntity?>(_bookEntityFixture.Create(path: "existing.pdf")));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenGettingDeletedPathsFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
|
||||
{
|
||||
// Arrange
|
||||
_mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Database.Error", "Failed to get the deleted paths"));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
|
||||
domainEvent.LibraryId == _libraryId
|
||||
&& domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId
|
||||
&& domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldMarkJobAsCanceledAndThrow()
|
||||
{
|
||||
// Arrange
|
||||
using CancellationTokenSource cancellationTokenSource = new();
|
||||
cancellationTokenSource.Cancel();
|
||||
|
||||
// Act
|
||||
Task operation = _sut.ExecuteAsync(Guid.NewGuid(), new { }, cancellationTokenSource.Token);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operation);
|
||||
Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status);
|
||||
}
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Events;
|
||||
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.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ScanFailurePublisher"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ScanFailurePublisherTests
|
||||
{
|
||||
private readonly IServiceScopeFactory _mockServiceScopeFactory;
|
||||
private readonly IServiceScope _mockServiceScope;
|
||||
private readonly IServiceProvider _mockServiceProvider;
|
||||
private readonly IDomainEventPublisher _mockDomainEventPublisher;
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ScanFailurePublisherTests"/> class.
|
||||
/// </summary>
|
||||
public ScanFailurePublisherTests()
|
||||
{
|
||||
_mockServiceScopeFactory = Substitute.For<IServiceScopeFactory>();
|
||||
_mockServiceScope = Substitute.For<IServiceScope>();
|
||||
_mockServiceProvider = Substitute.For<IServiceProvider>();
|
||||
_mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope);
|
||||
_mockServiceScope.ServiceProvider.Returns(_mockServiceProvider);
|
||||
|
||||
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
|
||||
_mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PublishAsync_WhenCalled_ShouldPublishLibraryScanFailedDomainEvent()
|
||||
{
|
||||
// Arrange
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
Exception exception = new("The scan job failed");
|
||||
|
||||
// Act
|
||||
await ScanFailurePublisher.PublishAsync(_mockServiceScopeFactory, libraryId, compositeId, exception, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(
|
||||
Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
|
||||
domainEvent.LibraryId == libraryId
|
||||
&& domainEvent.MediaLibraryScanCompositeId == compositeId
|
||||
&& domainEvent.ErrorMessage == "The scan job failed"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PublishAsync_WhenPublisherThrows_ShouldNotThrow()
|
||||
{
|
||||
// Arrange
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
_mockDomainEventPublisher.PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => new ValueTask(Task.FromException(new InvalidOperationException("Publishing failed"))));
|
||||
|
||||
// Act
|
||||
Exception? caughtException = null;
|
||||
try
|
||||
{
|
||||
await ScanFailurePublisher.PublishAsync(_mockServiceScopeFactory, libraryId, compositeId, new Exception("boom"), CancellationToken.None);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
caughtException = exception;
|
||||
}
|
||||
|
||||
// Assert
|
||||
Assert.Null(caughtException);
|
||||
}
|
||||
}
|
||||
+223
@@ -0,0 +1,223 @@
|
||||
#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.Domain.Common.Events;
|
||||
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.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.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.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="BooksFileSystemDiscoveryJob"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class BooksFileSystemDiscoveryJobTests
|
||||
{
|
||||
private readonly IServiceScopeFactory _mockServiceScopeFactory;
|
||||
private readonly IServiceScope _mockServiceScope;
|
||||
private readonly IServiceProvider _mockServiceProvider;
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly ILibraryRepository _mockLibraryRepository;
|
||||
private readonly ILibraryScanStagingResultsRepository _mockStagingResultsRepository;
|
||||
private readonly IDirectoryScanFingerprintRepository _mockDirectoryScanFingerprintRepository;
|
||||
private readonly IDomainEventPublisher _mockDomainEventPublisher;
|
||||
private readonly BooksFileSystemDiscoveryJob _sut;
|
||||
private readonly ScanIdFixture _scanIdFixture = new();
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ScanId _scanId;
|
||||
private readonly UserId _userId;
|
||||
private readonly LibraryId _libraryId;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BooksFileSystemDiscoveryJobTests"/> class.
|
||||
/// </summary>
|
||||
public BooksFileSystemDiscoveryJobTests()
|
||||
{
|
||||
_mockServiceScopeFactory = Substitute.For<IServiceScopeFactory>();
|
||||
_mockServiceScope = Substitute.For<IServiceScope>();
|
||||
_mockServiceProvider = Substitute.For<IServiceProvider>();
|
||||
_mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope);
|
||||
_mockServiceScope.ServiceProvider.Returns(_mockServiceProvider);
|
||||
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
_mockStagingResultsRepository = Substitute.For<ILibraryScanStagingResultsRepository>();
|
||||
_mockDirectoryScanFingerprintRepository = Substitute.For<IDirectoryScanFingerprintRepository>();
|
||||
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
|
||||
_mockUnitOfWork.LibraryScanStagingResultsRepository.Returns(_mockStagingResultsRepository);
|
||||
_mockUnitOfWork.DirectoryScanFingerprintRepository.Returns(_mockDirectoryScanFingerprintRepository);
|
||||
_mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork);
|
||||
|
||||
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
|
||||
_mockDomainEventPublisher.PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ValueTask.CompletedTask);
|
||||
_mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher);
|
||||
|
||||
_scanId = _scanIdFixture.Create();
|
||||
_userId = _userIdFixture.Create();
|
||||
_libraryId = _libraryIdFixture.Create();
|
||||
_sut = new BooksFileSystemDiscoveryJob(_mockServiceScopeFactory)
|
||||
{
|
||||
ScanId = _scanId,
|
||||
UserId = _userId,
|
||||
LibraryId = _libraryId
|
||||
};
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenContentLocationContainsBookFiles_ShouldDiscoverAndStageThemAndComplete()
|
||||
{
|
||||
// Arrange
|
||||
using TemporaryLibraryDirectory temporaryLibraryDirectory = new();
|
||||
temporaryLibraryDirectory.CreateFile("book1.pdf", "book content");
|
||||
temporaryLibraryDirectory.CreateFile("notes.log", "not a book");
|
||||
string subdirectoryPath = temporaryLibraryDirectory.CreateSubdirectory("sub");
|
||||
File.WriteAllText(Path.Combine(subdirectoryPath, "book2.epub"), "another book content");
|
||||
|
||||
LibraryEntity libraryEntity = _libraryEntityFixture.Create(
|
||||
id: _libraryId.Value,
|
||||
userId: _userId.Value,
|
||||
title: "Test Library",
|
||||
libraryType: LibraryType.Book,
|
||||
contentLocations: [temporaryLibraryDirectory.Path],
|
||||
shouldSkipUnchangedDirectoriesDuringScan: false);
|
||||
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(libraryEntity));
|
||||
_mockStagingResultsRepository.InsertRangeAsync(Arg.Any<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Created));
|
||||
_mockDirectoryScanFingerprintRepository.UpsertRangeAsync(Arg.Any<IReadOnlyCollection<DirectoryScanFingerprintEntity>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Updated));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
IReadOnlyList<LibraryScanStagingResultsEntity>? actualEntities = _mockStagingResultsRepository.ReceivedCalls()
|
||||
.Where(call => call.GetMethodInfo().Name == nameof(ILibraryScanStagingResultsRepository.InsertRangeAsync))
|
||||
.Select(call => call.GetArguments().FirstOrDefault() as IReadOnlyList<LibraryScanStagingResultsEntity>)
|
||||
.FirstOrDefault();
|
||||
Assert.True(actualEntities is not null, $"InsertRangeAsync was not called. Received: {string.Join(", ", _mockStagingResultsRepository.ReceivedCalls().Select(call => call.GetMethodInfo().Name))}");
|
||||
Assert.Equal(
|
||||
["book1.pdf", "book2.epub"],
|
||||
actualEntities!.Select(entity => Path.GetFileName(entity.Path)).OrderBy(name => name, StringComparer.Ordinal));
|
||||
await _mockDirectoryScanFingerprintRepository.DidNotReceive().UpsertRangeAsync(Arg.Any<IReadOnlyCollection<DirectoryScanFingerprintEntity>>(), Arg.Any<CancellationToken>());
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanProgressChangedDomainEvent>(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenGettingTheLibraryFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
|
||||
{
|
||||
// Arrange
|
||||
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Database.Error", "Failed to retrieve the library"));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
|
||||
await _mockStagingResultsRepository.DidNotReceive().InsertRangeAsync(Arg.Any<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(), Arg.Any<CancellationToken>());
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
|
||||
domainEvent.LibraryId == _libraryId
|
||||
&& domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId
|
||||
&& domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryDoesNotExist_ShouldMarkJobAsFailedAndPublishFailureEvent()
|
||||
{
|
||||
// Arrange
|
||||
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(null));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
|
||||
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldMarkJobAsCanceledAndThrow()
|
||||
{
|
||||
// Arrange
|
||||
using CancellationTokenSource cancellationTokenSource = new();
|
||||
cancellationTokenSource.Cancel();
|
||||
|
||||
// Act
|
||||
Task operation = _sut.ExecuteAsync(Guid.NewGuid(), new { }, cancellationTokenSource.Token);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operation);
|
||||
Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Test helper managing a temporary library directory, deleted when the test finishes.
|
||||
/// </summary>
|
||||
private sealed class TemporaryLibraryDirectory : IDisposable
|
||||
{
|
||||
private bool _disposed;
|
||||
|
||||
public TemporaryLibraryDirectory()
|
||||
{
|
||||
Path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), $"lumina-books-discovery-{Guid.NewGuid()}");
|
||||
Directory.CreateDirectory(Path);
|
||||
}
|
||||
|
||||
public string Path { get; }
|
||||
|
||||
public void CreateFile(string fileName, string content)
|
||||
{
|
||||
File.WriteAllText(System.IO.Path.Combine(Path, fileName), content);
|
||||
}
|
||||
|
||||
public string CreateSubdirectory(string name)
|
||||
{
|
||||
string subdirectoryPath = System.IO.Path.Combine(Path, name);
|
||||
Directory.CreateDirectory(subdirectoryPath);
|
||||
return subdirectoryPath;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (!_disposed)
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.Delete(Path, recursive: true);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
// best effort cleanup of the temporary library directory
|
||||
}
|
||||
_disposed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+171
@@ -0,0 +1,171 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.Responses.MediaLibrary.Management;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Progress;
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Progress;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="DebouncedMediaLibraryScanProgressNotifier"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DebouncedMediaLibraryScanProgressNotifierTests
|
||||
{
|
||||
private readonly IHubContext<MediaLibraryScanProgressHub> _mockHubContext;
|
||||
private readonly IHubClients _mockHubClients;
|
||||
private readonly IClientProxy _mockClientProxy;
|
||||
private readonly IMediaLibrariesScanProgressTracker _mockProgressTracker;
|
||||
private readonly DebouncedMediaLibraryScanProgressNotifier _sut;
|
||||
private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new();
|
||||
private readonly MediaLibraryScanProgressFixture _mediaLibraryScanProgressFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DebouncedMediaLibraryScanProgressNotifierTests"/> class.
|
||||
/// </summary>
|
||||
public DebouncedMediaLibraryScanProgressNotifierTests()
|
||||
{
|
||||
_mockHubContext = Substitute.For<IHubContext<MediaLibraryScanProgressHub>>();
|
||||
_mockHubClients = Substitute.For<IHubClients>();
|
||||
_mockClientProxy = Substitute.For<IClientProxy>();
|
||||
_mockHubContext.Clients.Returns(_mockHubClients);
|
||||
_mockHubClients.Group(Arg.Any<string>()).Returns(_mockClientProxy);
|
||||
_mockClientProxy.SendCoreAsync(Arg.Any<string>(), Arg.Any<object?[]>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
_mockProgressTracker = Substitute.For<IMediaLibrariesScanProgressTracker>();
|
||||
_sut = new DebouncedMediaLibraryScanProgressNotifier(_mockHubContext, _mockProgressTracker);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendLibraryProgressUpdateEventAsync_WhenTokenIsCancelled_ShouldNotPublishOrQueryProgress()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
using CancellationTokenSource cancellationTokenSource = new();
|
||||
cancellationTokenSource.Cancel();
|
||||
|
||||
// Act
|
||||
await _sut.SendLibraryProgressUpdateEventAsync(compositeId, cancellationTokenSource.Token);
|
||||
|
||||
// Assert
|
||||
_mockProgressTracker.DidNotReceive().GetScanProgress(Arg.Any<MediaLibraryScanCompositeId>());
|
||||
_mockHubClients.DidNotReceive().Group(Arg.Any<string>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendLibraryProgressUpdateEventAsync_WhenProgressExists_ShouldSendProgressUpdateToGroup()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
MediaLibraryScanProgress progress = _mediaLibraryScanProgressFixture.Create(
|
||||
scanId: compositeId.ScanId,
|
||||
userId: compositeId.UserId,
|
||||
completedJobs: 1,
|
||||
totalJobs: 2,
|
||||
status: LibraryScanJobStatus.Running);
|
||||
_mockProgressTracker.GetScanProgress(compositeId).Returns(Result.From(progress));
|
||||
|
||||
// Act
|
||||
await _sut.SendLibraryProgressUpdateEventAsync(compositeId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
_mockHubClients.Received(1).Group(compositeId.ToString());
|
||||
await _mockClientProxy.Received(1).SendCoreAsync(
|
||||
"libraryScanProgressUpdateEvent",
|
||||
Arg.Is<object?[]>(args => args.Length == 1
|
||||
&& args[0] != null
|
||||
&& ((MediaLibraryScanProgressResponse)args[0]!).Status == LibraryScanJobStatus.Running.ToString()),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendLibraryProgressUpdateEventAsync_WhenProgressIsMissing_ShouldNotSendUpdate()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
_mockProgressTracker.GetScanProgress(compositeId)
|
||||
.Returns(Error.Failure("Tracking.Error", "The scan progress is missing"));
|
||||
|
||||
// Act
|
||||
await _sut.SendLibraryProgressUpdateEventAsync(compositeId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockClientProxy.DidNotReceive().SendCoreAsync(Arg.Any<string>(), Arg.Any<object?[]>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendLibraryScanFinishedEventAsync_WhenProgressExists_ShouldSendFinishedEventWithCompletedStatus()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
MediaLibraryScanProgress progress = _mediaLibraryScanProgressFixture.Create(
|
||||
scanId: compositeId.ScanId,
|
||||
userId: compositeId.UserId,
|
||||
completedJobs: 1,
|
||||
totalJobs: 2,
|
||||
status: LibraryScanJobStatus.Running);
|
||||
_mockProgressTracker.RemoveScanProgress(compositeId).Returns(Result.From(progress));
|
||||
|
||||
// Act
|
||||
await _sut.SendLibraryScanFinishedEventAsync(compositeId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockClientProxy.Received(1).SendCoreAsync(
|
||||
"libraryScanFinishedEvent",
|
||||
Arg.Is<object?[]>(args => args.Length == 1
|
||||
&& args[0] != null
|
||||
&& ((MediaLibraryScanProgressResponse)args[0]!).Status == LibraryScanJobStatus.Completed.ToString()),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendLibraryScanFinishedEventAsync_WhenProgressIsMissing_ShouldNotSendFinishedEvent()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
_mockProgressTracker.RemoveScanProgress(compositeId)
|
||||
.Returns(Error.Failure("Tracking.Error", "The scan progress is missing"));
|
||||
|
||||
// Act
|
||||
await _sut.SendLibraryScanFinishedEventAsync(compositeId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockClientProxy.DidNotReceive().SendCoreAsync(Arg.Any<string>(), Arg.Any<object?[]>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendLibraryScanFailedEventAsync_WhenProgressExists_ShouldSendFailedEventWithFailedStatus()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
MediaLibraryScanProgress progress = _mediaLibraryScanProgressFixture.Create(
|
||||
scanId: compositeId.ScanId,
|
||||
userId: compositeId.UserId,
|
||||
completedJobs: 1,
|
||||
totalJobs: 2,
|
||||
status: LibraryScanJobStatus.Running);
|
||||
_mockProgressTracker.RemoveScanProgress(compositeId).Returns(Result.From(progress));
|
||||
|
||||
// Act
|
||||
await _sut.SendLibraryScanFailedEventAsync(compositeId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockClientProxy.Received(1).SendCoreAsync(
|
||||
"libraryScanFailedEvent",
|
||||
Arg.Is<object?[]>(args => args.Length == 1
|
||||
&& args[0] != null
|
||||
&& ((MediaLibraryScanProgressResponse)args[0]!).Status == LibraryScanJobStatus.Failed.ToString()),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Progress;
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Progress;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaLibraryScanProgressHub"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaLibraryScanProgressHubTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task SubscribeToScan_WhenCalled_ShouldAddTheConnectionToTheScanGroup()
|
||||
{
|
||||
// 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();
|
||||
Guid userId = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
await sut.SubscribeToScan(scanId, userId);
|
||||
|
||||
// Assert
|
||||
await groupManager.Received(1).AddToGroupAsync("connection-1", $"{scanId}-{userId}", CancellationToken.None);
|
||||
}
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Queue;
|
||||
using NSubstitute;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Queue;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaLibrariesScanQueue"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaLibrariesScanQueueTests
|
||||
{
|
||||
private readonly MediaLibrariesScanQueue _sut = new();
|
||||
|
||||
[Fact]
|
||||
public async Task Writer_WhenJobIsWritten_ShouldAllowReadingItFromReader()
|
||||
{
|
||||
// Arrange
|
||||
IMediaLibraryScanJob job = Substitute.For<IMediaLibraryScanJob>();
|
||||
|
||||
// Act
|
||||
bool writeResult = _sut.Writer.TryWrite(job);
|
||||
IMediaLibraryScanJob readJob = await _sut.Reader.ReadAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(writeResult);
|
||||
Assert.Same(job, readJob);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Writer_WhenMultipleJobsAreWritten_ShouldReadThemInFifoOrder()
|
||||
{
|
||||
// Arrange
|
||||
IMediaLibraryScanJob firstJob = Substitute.For<IMediaLibraryScanJob>();
|
||||
IMediaLibraryScanJob secondJob = Substitute.For<IMediaLibraryScanJob>();
|
||||
|
||||
// Act
|
||||
_sut.Writer.TryWrite(firstJob);
|
||||
_sut.Writer.TryWrite(secondJob);
|
||||
IMediaLibraryScanJob firstReadJob = await _sut.Reader.ReadAsync(CancellationToken.None);
|
||||
IMediaLibraryScanJob secondReadJob = await _sut.Reader.ReadAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Same(firstJob, firstReadJob);
|
||||
Assert.Same(secondJob, secondReadJob);
|
||||
}
|
||||
}
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.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.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Queue;
|
||||
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.MediaLibrary.Management.Scanning.Queue;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaLibraryScanJobProcessorJob"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaLibraryScanJobProcessorJobTests
|
||||
{
|
||||
private readonly IMediaLibrariesScanCancellationTracker _mockCancellationTracker;
|
||||
private readonly ScanIdFixture _scanIdFixture = new();
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaLibraryScanJobProcessorJobTests"/> class.
|
||||
/// </summary>
|
||||
public MediaLibraryScanJobProcessorJobTests()
|
||||
{
|
||||
_mockCancellationTracker = Substitute.For<IMediaLibrariesScanCancellationTracker>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartAsync_WhenJobIsEnqueued_ShouldExecuteTheJobWithLinkedCancellationToken()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibrariesScanQueue queue = new();
|
||||
MediaLibraryScanJobProcessorJob sut = new(queue, _mockCancellationTracker);
|
||||
RecordingScanJob job = CreateRecordingScanJob();
|
||||
_mockCancellationTracker.GetTokenForScan(Arg.Any<MediaLibraryScanCompositeId>())
|
||||
.Returns(CancellationToken.None);
|
||||
|
||||
await sut.StartAsync(CancellationToken.None);
|
||||
|
||||
// Act
|
||||
queue.Writer.TryWrite(job);
|
||||
await job.ExecutedTask.WaitAsync(TimeSpan.FromSeconds(5));
|
||||
|
||||
// Assert
|
||||
Assert.True(job.WasExecuted);
|
||||
Assert.False(job.ReceivedCancellationToken.IsCancellationRequested);
|
||||
_mockCancellationTracker.Received(1).GetTokenForScan(
|
||||
Arg.Is<MediaLibraryScanCompositeId>(compositeId => compositeId.ScanId == job.ScanId && compositeId.UserId == job.UserId));
|
||||
|
||||
await sut.StopAsync(CancellationToken.None);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartAsync_WhenScanWasAlreadyCancelled_ShouldExecuteJobWithAlreadyCancelledLinkedToken()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibrariesScanQueue queue = new();
|
||||
MediaLibraryScanJobProcessorJob sut = new(queue, _mockCancellationTracker);
|
||||
RecordingScanJob job = CreateRecordingScanJob();
|
||||
using CancellationTokenSource scanCancellationTokenSource = new();
|
||||
scanCancellationTokenSource.Cancel();
|
||||
_mockCancellationTracker.GetTokenForScan(Arg.Any<MediaLibraryScanCompositeId>())
|
||||
.Returns(scanCancellationTokenSource.Token);
|
||||
|
||||
await sut.StartAsync(CancellationToken.None);
|
||||
|
||||
// Act
|
||||
queue.Writer.TryWrite(job);
|
||||
await job.ExecutedTask.WaitAsync(TimeSpan.FromSeconds(5));
|
||||
|
||||
// Assert
|
||||
Assert.True(job.WasExecuted);
|
||||
Assert.True(job.ReceivedCancellationToken.IsCancellationRequested);
|
||||
|
||||
await sut.StopAsync(CancellationToken.None);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a recording scan job with a random scan and user identity.
|
||||
/// </summary>
|
||||
/// <returns>The created recording scan job.</returns>
|
||||
private RecordingScanJob CreateRecordingScanJob()
|
||||
{
|
||||
return new RecordingScanJob
|
||||
{
|
||||
ScanId = _scanIdFixture.Create(),
|
||||
UserId = _userIdFixture.Create(),
|
||||
LibraryId = _libraryIdFixture.Create()
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Test double for <see cref="IMediaLibraryScanJob"/> that records the token it was executed with.
|
||||
/// </summary>
|
||||
private sealed class RecordingScanJob : IMediaLibraryScanJob
|
||||
{
|
||||
private readonly TaskCompletionSource<bool> _executed = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
public required ScanId ScanId { get; set; }
|
||||
|
||||
public required UserId UserId { get; set; }
|
||||
|
||||
public required LibraryId LibraryId { get; set; }
|
||||
|
||||
public List<IMediaLibraryScanJob> Children { get; } = [];
|
||||
|
||||
public List<IMediaLibraryScanJob> Parents { get; } = [];
|
||||
|
||||
public LibraryScanJobStatus Status { get; private set; }
|
||||
|
||||
public Task ExecutedTask => _executed.Task;
|
||||
|
||||
public bool WasExecuted { get; private set; }
|
||||
|
||||
public CancellationToken ReceivedCancellationToken { get; private set; }
|
||||
|
||||
public void AddChild(IMediaLibraryScanJob job)
|
||||
{
|
||||
}
|
||||
|
||||
public void AddParent(IMediaLibraryScanJob job)
|
||||
{
|
||||
}
|
||||
|
||||
public Task ExecuteAsync<TInput>(Guid id, TInput input, CancellationToken cancellationToken)
|
||||
{
|
||||
WasExecuted = true;
|
||||
ReceivedCancellationToken = cancellationToken;
|
||||
_executed.TrySetResult(true);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
}
|
||||
+166
@@ -0,0 +1,166 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Plugins;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Plugins;
|
||||
using Lumina.Infrastructure.Core.Plugins;
|
||||
using Lumina.Plugins.Contracts.Core.Plugins;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Reflection;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="PluginDetectionSyncJob"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PluginDetectionSyncJobTests
|
||||
{
|
||||
private readonly IServiceScopeFactory _mockServiceScopeFactory;
|
||||
private readonly IServiceScope _mockServiceScope;
|
||||
private readonly IServiceProvider _mockServiceProvider;
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly IPluginRepository _mockPluginRepository;
|
||||
private readonly IPluginManager _mockPluginManager;
|
||||
private readonly ILogger<PluginDetectionSyncJob> _mockLogger;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PluginDetectionSyncJobTests"/> class.
|
||||
/// </summary>
|
||||
public PluginDetectionSyncJobTests()
|
||||
{
|
||||
_mockServiceScopeFactory = Substitute.For<IServiceScopeFactory>();
|
||||
_mockServiceScope = Substitute.For<IServiceScope>();
|
||||
_mockServiceProvider = Substitute.For<IServiceProvider>();
|
||||
_mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope);
|
||||
_mockServiceScope.ServiceProvider.Returns(_mockServiceProvider);
|
||||
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockPluginRepository = Substitute.For<IPluginRepository>();
|
||||
_mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository);
|
||||
_mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork);
|
||||
|
||||
_mockPluginManager = Substitute.For<IPluginManager>();
|
||||
_mockLogger = Substitute.For<ILogger<PluginDetectionSyncJob>>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartAsync_WhenPluginsAreLoaded_ShouldPersistTheDetectionOfAllPlugins()
|
||||
{
|
||||
// Arrange
|
||||
IPlugin firstPlugin = CreatePlugin(Guid.NewGuid(), "First Plugin", new Version(1, 2, 3));
|
||||
IPlugin secondPlugin = CreatePlugin(Guid.NewGuid(), "Second Plugin", new Version(2, 0, 0));
|
||||
_mockPluginManager.GetPlugins().Returns([firstPlugin, secondPlugin]);
|
||||
_mockPluginRepository.UpsertAsync(Arg.Any<PluginEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Updated));
|
||||
PluginDetectionSyncJob sut = CreateSut();
|
||||
|
||||
// Act
|
||||
await StartAndWaitForExecutionAsync(sut);
|
||||
|
||||
// Assert
|
||||
await _mockPluginRepository.Received(1).UpsertAsync(
|
||||
Arg.Is<PluginEntity>(plugin => plugin.Id == firstPlugin.Id
|
||||
&& plugin.Name == firstPlugin.Name
|
||||
&& plugin.Author == firstPlugin.Author
|
||||
&& plugin.Version == firstPlugin.Version.ToString()
|
||||
&& plugin.Description == firstPlugin.Description
|
||||
&& plugin.LoadStatus == PluginLoadStatus.Loaded),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockPluginRepository.Received(1).UpsertAsync(
|
||||
Arg.Is<PluginEntity>(plugin => plugin.Id == secondPlugin.Id
|
||||
&& plugin.Name == secondPlugin.Name
|
||||
&& plugin.LoadStatus == PluginLoadStatus.Loaded),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartAsync_WhenUpsertFails_ShouldLogErrorAndContinueWithOtherPlugins()
|
||||
{
|
||||
// Arrange
|
||||
IPlugin failingPlugin = CreatePlugin(Guid.NewGuid(), "Failing Plugin", new Version(1, 0, 0));
|
||||
IPlugin successfulPlugin = CreatePlugin(Guid.NewGuid(), "Successful Plugin", new Version(1, 0, 0));
|
||||
_mockPluginManager.GetPlugins().Returns([failingPlugin, successfulPlugin]);
|
||||
_mockPluginRepository.UpsertAsync(
|
||||
Arg.Is<PluginEntity>(plugin => plugin.Id == failingPlugin.Id),
|
||||
Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Database.Error", "Failed to persist the plugin"));
|
||||
_mockPluginRepository.UpsertAsync(
|
||||
Arg.Is<PluginEntity>(plugin => plugin.Id == successfulPlugin.Id),
|
||||
Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Updated));
|
||||
PluginDetectionSyncJob sut = CreateSut();
|
||||
|
||||
// Act
|
||||
await StartAndWaitForExecutionAsync(sut);
|
||||
|
||||
// Assert
|
||||
await _mockPluginRepository.Received(1).UpsertAsync(Arg.Is<PluginEntity>(plugin => plugin.Id == successfulPlugin.Id), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartAsync_WhenNoPluginsAreLoaded_ShouldOnlySaveChanges()
|
||||
{
|
||||
// Arrange
|
||||
_mockPluginManager.GetPlugins().Returns([]);
|
||||
PluginDetectionSyncJob sut = CreateSut();
|
||||
|
||||
// Act
|
||||
await StartAndWaitForExecutionAsync(sut);
|
||||
|
||||
// Assert
|
||||
await _mockPluginRepository.DidNotReceiveWithAnyArgs().UpsertAsync(default!, Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).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(PluginDetectionSyncJob sut)
|
||||
{
|
||||
MethodInfo executeAsyncMethod = typeof(PluginDetectionSyncJob).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 PluginDetectionSyncJob CreateSut()
|
||||
{
|
||||
return new PluginDetectionSyncJob(_mockServiceScopeFactory, _mockPluginManager, [], _mockLogger);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a mocked plugin with the provided identity.
|
||||
/// </summary>
|
||||
/// <param name="id">The Id of the plugin.</param>
|
||||
/// <param name="name">The name of the plugin.</param>
|
||||
/// <param name="version">The version of the plugin.</param>
|
||||
/// <returns>The created plugin mock.</returns>
|
||||
private static IPlugin CreatePlugin(Guid id, string name, Version version)
|
||||
{
|
||||
IPlugin plugin = Substitute.For<IPlugin>();
|
||||
plugin.Id.Returns(id);
|
||||
plugin.Name.Returns(name);
|
||||
plugin.Author.Returns("Test Author");
|
||||
plugin.Version.Returns(version);
|
||||
plugin.Description.Returns("Test plugin description");
|
||||
return plugin;
|
||||
}
|
||||
}
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Infrastructure.Core.Plugins;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="PluginLoadContext"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PluginLoadContextTests
|
||||
{
|
||||
[Fact]
|
||||
public void LoadFromAssemblyName_WhenAssemblyIsResolvableFromDefaultContext_ShouldReturnTheSharedAssembly()
|
||||
{
|
||||
// Arrange
|
||||
using TemporaryPluginDirectory temporaryPluginDirectory = new();
|
||||
PluginLoadContext sut = new(temporaryPluginDirectory.Path, "test-context");
|
||||
|
||||
// Act
|
||||
Assembly result = sut.LoadFromAssemblyName(typeof(object).Assembly.GetName());
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(typeof(object).Assembly.GetName().Name, result.GetName().Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Load_WhenAssemblyExistsOnlyInPluginDirectory_ShouldLoadItFromThePluginDirectory()
|
||||
{
|
||||
// Arrange
|
||||
using TemporaryPluginDirectory temporaryPluginDirectory = new();
|
||||
string destinationPath = temporaryPluginDirectory.CopyDll(Path.Combine(AppContext.BaseDirectory, "Lumina.TestPlugin.dll"), "PluginLocalDependency.dll");
|
||||
PluginLoadContext sut = new(temporaryPluginDirectory.Path, "test-context");
|
||||
MethodInfo loadMethod = typeof(PluginLoadContext).GetMethod("Load", BindingFlags.Instance | BindingFlags.NonPublic)!;
|
||||
|
||||
// Act
|
||||
Assembly? result = (Assembly?)loadMethod.Invoke(sut, [new AssemblyName("PluginLocalDependency")]);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("Lumina.TestPlugin", result!.GetName().Name);
|
||||
Assert.Equal(destinationPath, result.Location);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LoadFromAssemblyName_WhenAssemblyIsNotFoundAnywhere_ShouldThrowFileNotFoundException()
|
||||
{
|
||||
// Arrange
|
||||
using TemporaryPluginDirectory temporaryPluginDirectory = new();
|
||||
PluginLoadContext sut = new(temporaryPluginDirectory.Path, "test-context");
|
||||
|
||||
// Act
|
||||
Action act = () => sut.LoadFromAssemblyName(new AssemblyName($"Definitely.Not.Resolvable.{Guid.NewGuid()}"));
|
||||
|
||||
// Assert
|
||||
Assert.Throws<FileNotFoundException>(act);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Test helper managing a temporary plugins directory, deleted when the test finishes.
|
||||
/// </summary>
|
||||
private sealed class TemporaryPluginDirectory : IDisposable
|
||||
{
|
||||
private bool _disposed;
|
||||
|
||||
public TemporaryPluginDirectory()
|
||||
{
|
||||
Path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), $"lumina-plugin-load-context-{Guid.NewGuid()}");
|
||||
Directory.CreateDirectory(Path);
|
||||
}
|
||||
|
||||
public string Path { get; }
|
||||
|
||||
public string CopyDll(string sourceDllPath, string destinationFileName)
|
||||
{
|
||||
string destinationPath = System.IO.Path.Combine(Path, destinationFileName);
|
||||
File.Copy(sourceDllPath, destinationPath);
|
||||
return destinationPath;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (!_disposed)
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.Delete(Path, recursive: true);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
// best effort cleanup of the temporary plugins directory
|
||||
}
|
||||
catch (UnauthorizedAccessException)
|
||||
{
|
||||
// the plugin assemblies are still locked by their load contexts, best effort cleanup only
|
||||
}
|
||||
_disposed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Infrastructure.Common.Models.DTO.Plugins;
|
||||
using Lumina.Infrastructure.Core.Plugins;
|
||||
using Lumina.Plugins.Contracts.Core.Plugins;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="PluginLoader"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PluginLoaderTests
|
||||
{
|
||||
[Fact]
|
||||
public void LoadPlugins_WhenDirectoryDoesNotExist_ShouldReturnNoPluginsAndNoErrors()
|
||||
{
|
||||
// Arrange
|
||||
string nonExistentDirectory = Path.Combine(Path.GetTempPath(), $"lumina-plugins-{Guid.NewGuid()}");
|
||||
IServiceCollection services = new ServiceCollection();
|
||||
|
||||
// Act
|
||||
PluginLoadResultDto result = PluginLoader.LoadPlugins(nonExistentDirectory, services);
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result.Plugins);
|
||||
Assert.Empty(result.Errors);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LoadPlugins_WhenDirectoryContainsInvalidAssembly_ShouldRecordError()
|
||||
{
|
||||
// Arrange
|
||||
using TemporaryPluginDirectory temporaryPluginDirectory = new();
|
||||
temporaryPluginDirectory.CreateFile("invalid.dll", "this is not a valid assembly");
|
||||
IServiceCollection services = new ServiceCollection();
|
||||
|
||||
// Act
|
||||
PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services);
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result.Plugins);
|
||||
string error = Assert.Single(result.Errors);
|
||||
Assert.Contains("invalid.dll", error);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LoadPlugins_WhenDirectoryContainsAssemblyWithoutPluginDescriptors_ShouldReturnNoPluginsAndNoErrors()
|
||||
{
|
||||
// Arrange
|
||||
using TemporaryPluginDirectory temporaryPluginDirectory = new();
|
||||
temporaryPluginDirectory.CopyDll(typeof(IPlugin).Assembly.Location);
|
||||
IServiceCollection services = new ServiceCollection();
|
||||
|
||||
// Act
|
||||
PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services);
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result.Plugins);
|
||||
Assert.Empty(result.Errors);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LoadPlugins_WhenDirectoryContainsValidPluginAssembly_ShouldLoadPluginAndRegisterItsServices()
|
||||
{
|
||||
// Arrange
|
||||
using TemporaryPluginDirectory temporaryPluginDirectory = new();
|
||||
temporaryPluginDirectory.CopyDll(GetTestPluginAssemblyPath());
|
||||
IServiceCollection services = new ServiceCollection();
|
||||
|
||||
// Act
|
||||
PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services);
|
||||
|
||||
// Assert
|
||||
IPlugin loadedPlugin = Assert.Single(result.Plugins);
|
||||
Assert.Empty(result.Errors);
|
||||
Assert.Equal(Guid.Parse("7B5A3E5D-9B7F-4A1E-8D9C-2F3A4B5C6D7E"), loadedPlugin.Id);
|
||||
Assert.Equal("Test Plugin", loadedPlugin.Name);
|
||||
Assert.Contains(services, descriptor => descriptor.ImplementationInstance as string == "plugin-services-registered");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the path of the <c>Lumina.TestPlugin</c> assembly from the test output directory.
|
||||
/// The assembly is referenced by the test project but no type from it is used, so it is not loaded
|
||||
/// into the default load context, which is what makes the plugin loading pipeline testable.
|
||||
/// </summary>
|
||||
/// <returns>The path of the test plugin assembly.</returns>
|
||||
private static string GetTestPluginAssemblyPath()
|
||||
{
|
||||
return Path.Combine(AppContext.BaseDirectory, "Lumina.TestPlugin.dll");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Test helper managing a temporary plugins directory, deleted when the test finishes.
|
||||
/// </summary>
|
||||
private sealed class TemporaryPluginDirectory : IDisposable
|
||||
{
|
||||
private bool _disposed;
|
||||
|
||||
public TemporaryPluginDirectory()
|
||||
{
|
||||
Path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), $"lumina-plugin-loader-{Guid.NewGuid()}");
|
||||
Directory.CreateDirectory(Path);
|
||||
}
|
||||
|
||||
public string Path { get; }
|
||||
|
||||
public void CreateFile(string fileName, string content)
|
||||
{
|
||||
File.WriteAllText(System.IO.Path.Combine(Path, fileName), content);
|
||||
}
|
||||
|
||||
public void CopyDll(string sourceDllPath)
|
||||
{
|
||||
File.Copy(sourceDllPath, System.IO.Path.Combine(Path, System.IO.Path.GetFileName(sourceDllPath)));
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (!_disposed)
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.Delete(Path, recursive: true);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
// best effort cleanup of the temporary plugins directory
|
||||
}
|
||||
catch (UnauthorizedAccessException)
|
||||
{
|
||||
// the plugin assemblies are still locked by their load contexts, best effort cleanup only
|
||||
}
|
||||
_disposed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Infrastructure.Core.Plugins;
|
||||
using Lumina.Plugins.Contracts.Core.Plugins;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="PluginManager"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PluginManagerTests
|
||||
{
|
||||
[Fact]
|
||||
public void GetPlugins_WhenCalled_ShouldReturnAllLoadedPlugins()
|
||||
{
|
||||
// Arrange
|
||||
IPlugin firstPlugin = CreatePlugin(Guid.NewGuid(), "First Plugin");
|
||||
IPlugin secondPlugin = CreatePlugin(Guid.NewGuid(), "Second Plugin");
|
||||
PluginManager sut = new([firstPlugin, secondPlugin]);
|
||||
|
||||
// Act
|
||||
IReadOnlyList<IPlugin> result = sut.GetPlugins();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, result.Count);
|
||||
Assert.Contains(firstPlugin, result);
|
||||
Assert.Contains(secondPlugin, result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetPlugins_WhenNoPluginsWereLoaded_ShouldReturnEmptyList()
|
||||
{
|
||||
// Arrange
|
||||
PluginManager sut = new([]);
|
||||
|
||||
// Act
|
||||
IReadOnlyList<IPlugin> result = sut.GetPlugins();
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetPlugin_WhenPluginWithIdWasLoaded_ShouldReturnThePlugin()
|
||||
{
|
||||
// Arrange
|
||||
Guid pluginId = Guid.NewGuid();
|
||||
IPlugin expectedPlugin = CreatePlugin(pluginId, "Expected Plugin");
|
||||
PluginManager sut = new([expectedPlugin, CreatePlugin(Guid.NewGuid(), "Other Plugin")]);
|
||||
|
||||
// Act
|
||||
IPlugin? result = sut.GetPlugin(pluginId);
|
||||
|
||||
// Assert
|
||||
Assert.Same(expectedPlugin, result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetPlugin_WhenPluginWithIdWasNotLoaded_ShouldReturnNull()
|
||||
{
|
||||
// Arrange
|
||||
PluginManager sut = new([CreatePlugin(Guid.NewGuid(), "Loaded Plugin")]);
|
||||
|
||||
// Act
|
||||
IPlugin? result = sut.GetPlugin(Guid.NewGuid());
|
||||
|
||||
// Assert
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a mocked plugin with the provided identity.
|
||||
/// </summary>
|
||||
/// <param name="id">The Id of the plugin.</param>
|
||||
/// <param name="name">The name of the plugin.</param>
|
||||
/// <returns>The created plugin mock.</returns>
|
||||
private static IPlugin CreatePlugin(Guid id, string name)
|
||||
{
|
||||
IPlugin plugin = Substitute.For<IPlugin>();
|
||||
plugin.Id.Returns(id);
|
||||
plugin.Name.Returns(name);
|
||||
return plugin;
|
||||
}
|
||||
}
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Infrastructure.Core.Plugins;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="PluginSettingsStore"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PluginSettingsStoreTests
|
||||
{
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly IPluginRepository _mockPluginRepository;
|
||||
private readonly ILogger<PluginSettingsStore> _mockLogger;
|
||||
private readonly PluginSettingsStore _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PluginSettingsStoreTests"/> class.
|
||||
/// </summary>
|
||||
public PluginSettingsStoreTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockPluginRepository = Substitute.For<IPluginRepository>();
|
||||
_mockLogger = Substitute.For<ILogger<PluginSettingsStore>>();
|
||||
_mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository);
|
||||
|
||||
_sut = new PluginSettingsStore(_mockUnitOfWork, _mockLogger);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetSettingsAsync_WhenPluginHasPersistedSettings_ShouldReturnDeserializedSettings()
|
||||
{
|
||||
// Arrange
|
||||
Guid pluginId = Guid.NewGuid();
|
||||
Dictionary<string, string> expectedSettings = new() { ["ApiKey"] = "test-key", ["Enabled"] = "true" };
|
||||
PluginEntity pluginEntity = CreatePluginEntity(pluginId, JsonSerializer.Serialize(expectedSettings));
|
||||
_mockPluginRepository.GetByIdAsync(pluginId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<PluginEntity?>(pluginEntity));
|
||||
|
||||
// Act
|
||||
IReadOnlyDictionary<string, string>? result = await _sut.GetSettingsAsync(pluginId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(expectedSettings, result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetSettingsAsync_WhenPluginHasNoPersistedSettings_ShouldReturnNull()
|
||||
{
|
||||
// Arrange
|
||||
Guid pluginId = Guid.NewGuid();
|
||||
PluginEntity pluginEntity = CreatePluginEntity(pluginId, settingsJson: null);
|
||||
_mockPluginRepository.GetByIdAsync(pluginId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<PluginEntity?>(pluginEntity));
|
||||
|
||||
// Act
|
||||
IReadOnlyDictionary<string, string>? result = await _sut.GetSettingsAsync(pluginId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetSettingsAsync_WhenPluginDoesNotExist_ShouldReturnNull()
|
||||
{
|
||||
// Arrange
|
||||
Guid pluginId = Guid.NewGuid();
|
||||
_mockPluginRepository.GetByIdAsync(pluginId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<PluginEntity?>(null));
|
||||
|
||||
// Act
|
||||
IReadOnlyDictionary<string, string>? result = await _sut.GetSettingsAsync(pluginId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetSettingsAsync_WhenRepositoryReturnsFailure_ShouldReturnNullAndLogWarning()
|
||||
{
|
||||
// Arrange
|
||||
Guid pluginId = Guid.NewGuid();
|
||||
_mockPluginRepository.GetByIdAsync(pluginId, Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Database.Error", "Failed to retrieve the plugin"));
|
||||
|
||||
// Act
|
||||
IReadOnlyDictionary<string, string>? result = await _sut.GetSettingsAsync(pluginId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a plugin entity with the provided identity and serialized settings.
|
||||
/// </summary>
|
||||
/// <param name="id">The Id of the plugin.</param>
|
||||
/// <param name="settingsJson">The serialized settings of the plugin.</param>
|
||||
/// <returns>The created plugin entity.</returns>
|
||||
private static PluginEntity CreatePluginEntity(Guid id, string? settingsJson)
|
||||
{
|
||||
return new PluginEntity
|
||||
{
|
||||
Id = id,
|
||||
Name = "Test Plugin",
|
||||
Author = "Test Author",
|
||||
Version = "1.0.0",
|
||||
Description = "Test plugin description",
|
||||
SettingsJson = settingsJson,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
CreatedBy = Guid.Empty,
|
||||
UpdatedBy = null
|
||||
};
|
||||
}
|
||||
}
|
||||
+185
@@ -0,0 +1,185 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Models.DTO.MediaLibraryScanJobPayloads;
|
||||
using Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.MediaLibraryScanJobPayloads;
|
||||
using Lumina.Infrastructure.Core.Security;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.IO.Hashing;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.Security;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="FileHashService"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FileHashServiceTests
|
||||
{
|
||||
private readonly FileHashService _sut = new();
|
||||
private readonly HashedFileSystemFileDtoFixture _hashedFileSystemFileDtoFixture = new();
|
||||
|
||||
[Fact]
|
||||
public async Task HashFilesAsync_WhenCalledWithFiles_ShouldInvokeCallbackAndComputeHashes()
|
||||
{
|
||||
// Arrange
|
||||
using TemporaryTestDirectory temporaryTestDirectory = new();
|
||||
string filePath1 = temporaryTestDirectory.CreateFile("book1.pdf", "content of the first book");
|
||||
string filePath2 = temporaryTestDirectory.CreateFile("book2.pdf", "content of the second book");
|
||||
List<HashedFileSystemFileDto> inputFiles =
|
||||
[
|
||||
_hashedFileSystemFileDtoFixture.Create(path: filePath1, size: new FileInfo(filePath1).Length, currentHash: 0, oldHash: 0, ticks: 0),
|
||||
_hashedFileSystemFileDtoFixture.Create(path: filePath2, size: new FileInfo(filePath2).Length, currentHash: 0, oldHash: 0, ticks: 0)
|
||||
];
|
||||
int callbackInvocationCount = 0;
|
||||
|
||||
// Act
|
||||
List<HashedFileSystemFileDto> result = await _sut.HashFilesAsync(
|
||||
inputFiles,
|
||||
() =>
|
||||
{
|
||||
callbackInvocationCount++;
|
||||
return Task.CompletedTask;
|
||||
},
|
||||
CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, result.Count);
|
||||
Assert.Equal(2, callbackInvocationCount);
|
||||
Assert.All(result, file => Assert.NotEqual(0UL, file.CurrentHash));
|
||||
// the hashing is parallelized, so the results are not guaranteed to be in the input order
|
||||
Assert.Equal(
|
||||
inputFiles.Select(file => file.Path).OrderBy(path => path, StringComparer.Ordinal),
|
||||
result.Select(file => file.Path).OrderBy(path => path, StringComparer.Ordinal));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HashFilesAsync_WhenFileIsEmpty_ShouldUseEmptyFileHash()
|
||||
{
|
||||
// Arrange
|
||||
using TemporaryTestDirectory temporaryTestDirectory = new();
|
||||
string filePath = temporaryTestDirectory.CreateFile("empty.pdf", string.Empty);
|
||||
List<HashedFileSystemFileDto> inputFiles = [_hashedFileSystemFileDtoFixture.Create(path: filePath, size: new FileInfo(filePath).Length, currentHash: 0, oldHash: 0, ticks: 0)];
|
||||
|
||||
// Act
|
||||
List<HashedFileSystemFileDto> result = await _sut.HashFilesAsync(inputFiles, () => Task.CompletedTask, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
HashedFileSystemFileDto hashedFile = Assert.Single(result);
|
||||
Assert.Equal(filePath, hashedFile.Path);
|
||||
Assert.Equal(BitConverter.ToUInt64(new XxHash64().GetCurrentHash()), hashedFile.CurrentHash);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HashFilesAsync_WhenFileContentChanges_ShouldProduceDifferentHashes()
|
||||
{
|
||||
// Arrange
|
||||
using TemporaryTestDirectory temporaryTestDirectory = new();
|
||||
string filePath = temporaryTestDirectory.CreateFile("book.pdf", "original content");
|
||||
List<HashedFileSystemFileDto> firstInputFiles = [_hashedFileSystemFileDtoFixture.Create(path: filePath, size: new FileInfo(filePath).Length, currentHash: 0, oldHash: 0, ticks: 0)];
|
||||
|
||||
// Act
|
||||
List<HashedFileSystemFileDto> firstResult = await _sut.HashFilesAsync(firstInputFiles, () => Task.CompletedTask, CancellationToken.None);
|
||||
await File.WriteAllTextAsync(filePath, "changed content");
|
||||
List<HashedFileSystemFileDto> secondInputFiles = [_hashedFileSystemFileDtoFixture.Create(path: filePath, size: new FileInfo(filePath).Length, currentHash: 0, oldHash: 0, ticks: 0)];
|
||||
List<HashedFileSystemFileDto> secondResult = await _sut.HashFilesAsync(secondInputFiles, () => Task.CompletedTask, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstResult[0].CurrentHash, secondResult[0].CurrentHash);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HashFilesAsync_WhenFileDoesNotExist_ShouldSkipFileAndNotThrow()
|
||||
{
|
||||
// Arrange
|
||||
string nonExistentFilePath = Path.Combine(Path.GetTempPath(), "does-not-exist.pdf");
|
||||
List<HashedFileSystemFileDto> inputFiles = [_hashedFileSystemFileDtoFixture.Create(path: nonExistentFilePath, size: 100, currentHash: 0, oldHash: 0, ticks: 0)];
|
||||
|
||||
// Act
|
||||
List<HashedFileSystemFileDto> result = await _sut.HashFilesAsync(inputFiles, () => Task.CompletedTask, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HashFilesAsync_WhenOneFileIsMissing_ShouldHashTheExistingFilesOnly()
|
||||
{
|
||||
// Arrange
|
||||
using TemporaryTestDirectory temporaryTestDirectory = new();
|
||||
string existingFilePath = temporaryTestDirectory.CreateFile("book.pdf", "content");
|
||||
List<HashedFileSystemFileDto> inputFiles =
|
||||
[
|
||||
_hashedFileSystemFileDtoFixture.Create(path: existingFilePath, size: new FileInfo(existingFilePath).Length, currentHash: 0, oldHash: 0, ticks: 0),
|
||||
_hashedFileSystemFileDtoFixture.Create(path: Path.Combine(temporaryTestDirectory.Path, "missing.pdf"), size: 100, currentHash: 0, oldHash: 0, ticks: 0)
|
||||
];
|
||||
|
||||
// Act
|
||||
List<HashedFileSystemFileDto> result = await _sut.HashFilesAsync(inputFiles, () => Task.CompletedTask, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
HashedFileSystemFileDto hashedFile = Assert.Single(result);
|
||||
Assert.Equal(existingFilePath, hashedFile.Path);
|
||||
Assert.NotEqual(0UL, hashedFile.CurrentHash);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HashFilesAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
using TemporaryTestDirectory temporaryTestDirectory = new();
|
||||
string filePath = temporaryTestDirectory.CreateFile("book.pdf", "content");
|
||||
List<HashedFileSystemFileDto> inputFiles = [_hashedFileSystemFileDtoFixture.Create(path: filePath, size: new FileInfo(filePath).Length, currentHash: 0, oldHash: 0, ticks: 0)];
|
||||
using CancellationTokenSource cancellationTokenSource = new();
|
||||
cancellationTokenSource.Cancel();
|
||||
|
||||
// Act
|
||||
Task<List<HashedFileSystemFileDto>> operation = _sut.HashFilesAsync(inputFiles, () => Task.CompletedTask, cancellationTokenSource.Token);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operation);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Test helper managing a temporary directory, deleted when the test finishes.
|
||||
/// </summary>
|
||||
private sealed class TemporaryTestDirectory : IDisposable
|
||||
{
|
||||
private bool _disposed;
|
||||
|
||||
public TemporaryTestDirectory()
|
||||
{
|
||||
Path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), $"lumina-file-hash-tests-{Guid.NewGuid()}");
|
||||
Directory.CreateDirectory(Path);
|
||||
}
|
||||
|
||||
public string Path { get; }
|
||||
|
||||
public string CreateFile(string fileName, string content)
|
||||
{
|
||||
string filePath = System.IO.Path.Combine(Path, fileName);
|
||||
File.WriteAllText(filePath, content);
|
||||
return filePath;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (!_disposed)
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.Delete(Path, recursive: true);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
// best effort cleanup of the temporary test directory
|
||||
}
|
||||
_disposed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Infrastructure.Core.Time;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.Time;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="DateTimeProvider"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DateTimeProviderTests
|
||||
{
|
||||
private readonly DateTimeProvider _sut = new();
|
||||
|
||||
[Fact]
|
||||
public void UtcNow_WhenCalled_ShouldReturnCurrentUtcTime()
|
||||
{
|
||||
// Arrange
|
||||
DateTime before = DateTime.UtcNow;
|
||||
|
||||
// Act
|
||||
DateTime result = _sut.UtcNow;
|
||||
|
||||
// Assert
|
||||
DateTime after = DateTime.UtcNow;
|
||||
Assert.True(result >= before && result <= after);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UtcNow_WhenCalled_ShouldReturnUtcKind()
|
||||
{
|
||||
// Act
|
||||
DateTime result = _sut.UtcNow;
|
||||
|
||||
// Assert
|
||||
Assert.Equal(DateTimeKind.Utc, result.Kind);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user