Centralizes and standardizes test fixtures.

This commit is contained in:
BinaryAlley committed 2026-08-15 02:58:17 -07:00
1 parent dfc513da4f
commit b648e2f054
294 files changed
+3807 -4437

No files matched your search

@@ -1,9 +1,9 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.Authentication;
using Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword;
using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.ChangePassword.Fixtures;
using Lumina.Contracts.Fixtures.Core.Requests.Authentication;
using Lumina.Contracts.Requests.Authentication;
using System.Diagnostics.CodeAnalysis;
using Lumina.Application.Common.Mapping.Authentication;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.Authentication;
@@ -28,7 +28,7 @@ public class ChangePasswordRequestMappingTests
public void ToCommand_WhenMappingRequest_ShouldMapCorrectly()
{
// Arrange
ChangePasswordRequest request = _fixture.CreateChangePasswordRequest();
ChangePasswordRequest request = _fixture.Create();
// Act
ChangePasswordCommand result = request.ToCommand();
@@ -1,7 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.Authentication;
using Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser;
using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Queries.LoginUser.Fixtures;
using Lumina.Contracts.Fixtures.Core.Requests.Authentication;
using Lumina.Contracts.Requests.Authentication;
using System.Diagnostics.CodeAnalysis;
#endregion
@@ -28,7 +28,7 @@ public class LoginRequestMappingTests
public void ToQuery_WhenMappingRequest_ShouldMapCorrectly()
{
// Arrange
LoginRequest request = _fixture.CreateLoginRequest();
LoginRequest request = _fixture.Create();
// Act
LoginUserQuery result = request.ToQuery();
@@ -1,7 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.Authentication;
using Lumina.Application.Core.UsersManagement.Authentication.Commands.RecoverPassword;
using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RecoverPassword.Fixtures;
using Lumina.Contracts.Fixtures.Core.Requests.Authentication;
using Lumina.Contracts.Requests.Authentication;
using System.Diagnostics.CodeAnalysis;
#endregion
@@ -28,7 +28,7 @@ public class RecoverPasswordRequestMappingTests
public void ToCommand_WhenMappingRequest_ShouldMapCorrectly()
{
// Arrange
RecoverPasswordRequest request = _fixture.CreateRecoverPasswordRequest();
RecoverPasswordRequest request = _fixture.Create();
// Act
RecoverPasswordCommand result = request.ToCommand();
@@ -2,7 +2,7 @@
using Lumina.Application.Common.Mapping.Authentication;
using Lumina.Application.Core.Maintenance.ApplicationSetup.Commands.SetupApplication;
using Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser;
using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RegisterUser.Fixture;
using Lumina.Contracts.Fixtures.Core.Requests.Authentication;
using Lumina.Contracts.Requests.Authentication;
using System.Diagnostics.CodeAnalysis;
#endregion
@@ -29,7 +29,7 @@ public class RegistrationRequestMappingTests
public void ToSetupCommand_WhenMappingRequest_ShouldMapCorrectly()
{
// Arrange
RegistrationRequest request = _fixture.CreateRegistrationRequest();
RegistrationRequest request = _fixture.Create();
// Act
SetupApplicationCommand result = request.ToSetupCommand();
@@ -46,7 +46,7 @@ public class RegistrationRequestMappingTests
public void ToCommand_WhenMappingRequest_ShouldMapCorrectly()
{
// Arrange
RegistrationRequest request = _fixture.CreateRegistrationRequest();
RegistrationRequest request = _fixture.Create();
// Act
RegisterUserCommand result = request.ToCommand();
@@ -1,6 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.FileSystemManagement.Common;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Fixtures;
using Lumina.Contracts.Fixtures.Core.Responses.FileSystemManagement.Common;
using Lumina.Contracts.Responses.FileSystemManagement.Common;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
@@ -1,10 +1,10 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.FileSystemManagement.Directories;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Fixtures;
using Lumina.Contracts.Responses.FileSystemManagement.Common;
using Lumina.Contracts.Responses.FileSystemManagement.Directories;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
@@ -32,11 +32,11 @@ public class DirectoryMappingTests
public void ToFileSystemTreeNodeResponse_WhenMappingDirectory_ShouldMapCorrectly()
{
// Arrange
Directory directory = _directoryFixture.CreateDirectory();
Directory directory = _directoryFixture.Create();
List<FileSystemItem> childItems =
[
_directoryFixture.CreateDirectory(),
_directoryFixture.CreateDirectory()
_directoryFixture.Create(),
_directoryFixture.Create()
];
foreach (FileSystemItem item in childItems)
directory.AddItem(item);
@@ -88,11 +88,11 @@ public class DirectoryMappingTests
public void ToResponse_WhenMappingDirectory_ShouldMapCorrectly()
{
// Arrange
Directory directory = _directoryFixture.CreateDirectory();
Directory directory = _directoryFixture.Create();
List<FileSystemItem> childItems =
[
_directoryFixture.CreateDirectory(),
_directoryFixture.CreateDirectory()
_directoryFixture.Create(),
_directoryFixture.Create()
];
foreach (FileSystemItem item in childItems)
directory.AddItem(item);
@@ -1,8 +1,7 @@
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using AutoFixture.AutoNSubstitute;
using Lumina.Application.Common.Mapping.FileSystemManagement.Directories;
using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectories;
using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Directories;
using Lumina.Contracts.Requests.FileSystemManagement.Directories;
using System.Diagnostics.CodeAnalysis;
#endregion
@@ -15,21 +14,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Direc
[ExcludeFromCodeCoverage]
public class GetDirectoriesRequestMappingTests
{
private readonly IFixture _fixture;
/// <summary>
/// Initializes a new instance of the <see cref="GetDirectoriesRequestMappingTests"/> class.
/// </summary>
public GetDirectoriesRequestMappingTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
}
private readonly GetDirectoriesRequestFixture _getDirectoriesRequestFixture = new();
[Fact]
public void ToQuery_WhenMappingGetDirectoriesRequest_ShouldMapCorrectly()
{
// Arrange
GetDirectoriesRequest request = _fixture.Create<GetDirectoriesRequest>();
GetDirectoriesRequest request = _getDirectoriesRequestFixture.Create();
// Act
GetDirectoriesQuery result = request.ToQuery();
@@ -1,20 +1,18 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.FileSystemManagement.FileSystem;
using Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.FileSystem.Fixtures;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Fixtures;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Fixtures;
using Lumina.Application.UnitTests.Core.FileSystemManagement.FileSystem.Fixtures;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Fixtures;
using Lumina.Contracts.DTO.FileSystemManagement;
using Lumina.Contracts.Responses.FileSystemManagement.Common;
using Lumina.Domain.SharedKernel.Common.Enums.FileSystem;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate;
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.FileSystem;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Lumina.Contracts.DTO.FileSystemManagement;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.FileSystem;
@@ -47,7 +45,7 @@ public class FileSystemItemMappingTests
public void ToFileSystemItemModel_WhenMappingFileSystemItem_ShouldMapCorrectly()
{
// Arrange
FileSystemPathId id = _fileSystemPathIdFixture.CreateFileSystemPathId();
FileSystemPathId id = _fileSystemPathIdFixture.Create();
string name = "TestItem";
FileSystemItemType type = FileSystemItemType.File;
FileSystemItemFixture domainModel = new(id, name, type);
@@ -69,7 +67,7 @@ public class FileSystemItemMappingTests
public void ToTreeNodeResponse_WhenMappingDirectory_ShouldMapCorrectly()
{
// Arrange
Directory directory = _directoryFixture.CreateDirectory();
Directory directory = _directoryFixture.Create();
// Act
FileSystemTreeNodeResponse result = directory.ToTreeNodeResponse();
@@ -85,7 +83,7 @@ public class FileSystemItemMappingTests
public void ToTreeNodeResponse_WhenMappingFile_ShouldMapCorrectly()
{
// Arrange
File file = _fileFixture.CreateFile();
File file = _fileFixture.Create();
// Act
FileSystemTreeNodeResponse result = file.ToTreeNodeResponse();
@@ -141,7 +139,7 @@ public class FileSystemItemMappingTests
public void ToFileSystemItemModel_WhenMappingDifferentFileSystemItems_ShouldMapCorrectly(string name, FileSystemItemType type)
{
// Arrange
FileSystemPathId id = _fileSystemPathIdFixture.CreateFileSystemPathId();
FileSystemPathId id = _fileSystemPathIdFixture.Create();
FileSystemItemFixture domainModel = new(id, name, type);
// Act
@@ -161,8 +159,8 @@ public class FileSystemItemMappingTests
// Arrange
List<FileSystemItem> domainModels =
[
_directoryFixture.CreateDirectory(),
_fileFixture.CreateFile(),
_directoryFixture.Create(),
_fileFixture.Create(),
_windowsRootItemFixture.Create(),
_unixRootItemFixture.Create()
];
@@ -174,7 +172,7 @@ public class FileSystemItemMappingTests
Assert.NotNull(result);
Assert.Equal(domainModels.Count, result.Count());
List<FileSystemTreeNodeResponse> resultList = result.ToList();
List<FileSystemTreeNodeResponse> resultList = [.. result];
for (int i = 0; i < resultList.Count; i++)
{
Assert.Equal(domainModels[i].Name, resultList[i].Name);
@@ -189,7 +187,7 @@ public class FileSystemItemMappingTests
public void ToTreeNodeResponse_WhenMappingInvalidFileSystemItem_ShouldThrowArgumentException()
{
// Arrange
FileSystemPathId id = _fileSystemPathIdFixture.CreateFileSystemPathId();
FileSystemPathId id = _fileSystemPathIdFixture.Create();
string name = "TestItem";
FileSystemItemType type = FileSystemItemType.File;
FileSystemItemFixture invalidItem = new(id, name, type);
@@ -212,8 +210,8 @@ public class FileSystemItemMappingTests
Assert.NotNull(result);
Assert.Equal(domainModels.Count(), result.Count());
List<FileSystemTreeNodeResponse> resultList = result.ToList();
List<FileSystemItem> domainModelsList = domainModels.ToList();
List<FileSystemTreeNodeResponse> resultList = [.. result];
List<FileSystemItem> domainModelsList = [.. domainModels];
for (int i = 0; i < resultList.Count; i++)
{
Assert.Equal(domainModelsList[i].Name, resultList[i].Name);
@@ -1,26 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.FileSystem;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.FileSystem.Fixtures;
/// <summary>
/// Fixture class for the <see cref="FileSystemItem"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class FileSystemItemFixture : FileSystemItem
{
/// <summary>
/// Initializes a new instance of the <see cref="FileSystemItemFixture"/> class.
/// </summary>
/// <param name="id">The unique identifier for the file system path.</param>
/// <param name="name">The name of the file system item.</param>
/// <param name="fileSystemItemType">The type of the file system item.</param>
public FileSystemItemFixture(FileSystemPathId id, string name, FileSystemItemType fileSystemItemType)
: base(id, name, fileSystemItemType)
{
}
}
@@ -1,10 +1,9 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.FileSystemManagement.Files;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Fixtures;
using Lumina.Contracts.Responses.FileSystemManagement.Common;
using Lumina.Contracts.Responses.FileSystemManagement.Files;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
@@ -33,7 +32,7 @@ public class FileMappingTests
public void ToFileSystemTreeNodeResponse_WhenMappingFile_ShouldMapCorrectly()
{
// Arrange
File domainModel = _fileFixture.CreateFile();
File domainModel = _fileFixture.Create();
// Act
FileSystemTreeNodeResponse result = domainModel.ToFileSystemTreeNodeResponse();
@@ -60,8 +59,8 @@ public class FileMappingTests
Assert.NotNull(result);
Assert.Equal(domainModels.Count(), result.Count());
List<FileSystemTreeNodeResponse> resultList = result.ToList();
List<File> domainModelsList = domainModels.ToList();
List<FileSystemTreeNodeResponse> resultList = [.. result];
List<File> domainModelsList = [.. domainModels];
for (int i = 0; i < resultList.Count; i++)
{
Assert.Equal(domainModelsList[i].Name, resultList[i].Name);
@@ -77,7 +76,7 @@ public class FileMappingTests
public void ToResponse_WhenMappingFile_ShouldMapCorrectly()
{
// Arrange
File domainModel = _fileFixture.CreateFile();
File domainModel = _fileFixture.Create();
// Act
FileResponse result = domainModel.ToResponse();
@@ -104,8 +103,8 @@ public class FileMappingTests
Assert.NotNull(result);
Assert.Equal(domainModels.Count(), result.Count());
List<FileResponse> resultList = result.ToList();
List<File> domainModelsList = domainModels.ToList();
List<FileResponse> resultList = [.. result];
List<File> domainModelsList = [.. domainModels];
for (int i = 0; i < resultList.Count; i++)
{
Assert.Equal(domainModelsList[i].Name, resultList[i].Name);
@@ -1,8 +1,7 @@
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using AutoFixture.AutoNSubstitute;
using Lumina.Application.Common.Mapping.FileSystemManagement.Files;
using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetFiles;
using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Files;
using Lumina.Contracts.Requests.FileSystemManagement.Files;
using System.Diagnostics.CodeAnalysis;
#endregion
@@ -15,21 +14,20 @@ namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Files
[ExcludeFromCodeCoverage]
public class GetFilesRequestMappingTests
{
private readonly IFixture _fixture;
private readonly GetFilesRequestFixture _getFilesRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetFilesRequestMappingTests"/> class.
/// </summary>
public GetFilesRequestMappingTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
}
[Fact]
public void ToQuery_WhenMappingGetFilesRequest_ShouldMapCorrectly()
{
// Arrange
GetFilesRequest request = _fixture.Create<GetFilesRequest>();
GetFilesRequest request = _getFilesRequestFixture.Create();
// Act
GetFilesQuery result = request.ToQuery();
@@ -1,8 +1,7 @@
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using AutoFixture.AutoNSubstitute;
using Lumina.Application.Common.Mapping.FileSystemManagement.Files;
using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetTreeFiles;
using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Files;
using Lumina.Contracts.Requests.FileSystemManagement.Files;
using System.Diagnostics.CodeAnalysis;
#endregion
@@ -15,21 +14,20 @@ namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Files
[ExcludeFromCodeCoverage]
public class GetTreeFilesRequestMappingTests
{
private readonly IFixture _fixture;
private readonly GetTreeFilesRequestFixture _getTreeFilesRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetTreeFilesRequestMappingTests"/> class.
/// </summary>
public GetTreeFilesRequestMappingTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
}
[Fact]
public void ToQuery_WhenMappingGetTreeFilesRequest_ShouldMapCorrectly()
{
// Arrange
GetTreeFilesRequest request = _fixture.Create<GetTreeFilesRequest>();
GetTreeFilesRequest request = _getTreeFilesRequestFixture.Create();
// Act
GetTreeFilesQuery result = request.ToQuery();
@@ -1,8 +1,7 @@
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using AutoFixture.AutoNSubstitute;
using Lumina.Application.Common.Mapping.FileSystemManagement.Paths;
using Lumina.Application.Core.FileSystemManagement.Paths.Queries.CheckPathExists;
using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Path;
using Lumina.Contracts.Requests.FileSystemManagement.Path;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
@@ -17,21 +16,20 @@ namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Paths
[ExcludeFromCodeCoverage]
public class CheckPathExistsRequestMappingTests
{
private readonly IFixture _fixture;
private readonly CheckPathExistsRequestFixture _checkPathExistsRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="CheckPathExistsRequestMappingTests"/> class.
/// </summary>
public CheckPathExistsRequestMappingTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
}
[Fact]
public void ToQuery_WhenMappingCheckPathExistsRequest_ShouldMapCorrectly()
{
// Arrange
CheckPathExistsRequest request = _fixture.Create<CheckPathExistsRequest>();
CheckPathExistsRequest request = _checkPathExistsRequestFixture.Create();
// Act
CheckPathExistsQuery result = request.ToQuery();
@@ -64,7 +62,7 @@ public class CheckPathExistsRequestMappingTests
public void ToQuery_WhenMappingMultipleRequests_ShouldMapAllCorrectly()
{
// Arrange
List<CheckPathExistsRequest> requests = _fixture.CreateMany<CheckPathExistsRequest>().ToList();
List<CheckPathExistsRequest> requests = _checkPathExistsRequestFixture.CreateMany();
// Act
List<CheckPathExistsQuery> results = requests.Select(r => r.ToQuery()).ToList();
@@ -1,8 +1,7 @@
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using AutoFixture.AutoNSubstitute;
using Lumina.Application.Common.Mapping.FileSystemManagement.Paths;
using Lumina.Application.Core.FileSystemManagement.Paths.Commands.CombinePath;
using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Path;
using Lumina.Contracts.Requests.FileSystemManagement.Path;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
@@ -17,21 +16,20 @@ namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Paths
[ExcludeFromCodeCoverage]
public class CombinePathRequestMappingTests
{
private readonly IFixture _fixture;
private readonly CombinePathRequestFixture _combinePathRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="CombinePathRequestMappingTests"/> class.
/// </summary>
public CombinePathRequestMappingTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
}
[Fact]
public void ToCommand_WhenMappingCombinePathRequest_ShouldMapCorrectly()
{
// Arrange
CombinePathRequest request = _fixture.Create<CombinePathRequest>();
CombinePathRequest request = _combinePathRequestFixture.Create();
// Act
CombinePathCommand result = request.ToCommand();
@@ -64,10 +62,10 @@ public class CombinePathRequestMappingTests
public void ToCommand_WhenMappingMultipleRequests_ShouldMapAllCorrectly()
{
// Arrange
List<CombinePathRequest> requests = _fixture.CreateMany<CombinePathRequest>().ToList();
List<CombinePathRequest> requests = _combinePathRequestFixture.CreateMany();
// Act
List<CombinePathCommand> results = requests.Select(r => r.ToCommand()).ToList();
List<CombinePathCommand> results = [.. requests.Select(r => r.ToCommand())];
// Assert
Assert.NotNull(results);
@@ -1,8 +1,7 @@
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using AutoFixture.AutoNSubstitute;
using Lumina.Application.Common.Mapping.FileSystemManagement.Paths;
using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathParent;
using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Path;
using Lumina.Contracts.Requests.FileSystemManagement.Path;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
@@ -17,21 +16,20 @@ namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Paths
[ExcludeFromCodeCoverage]
public class GetPathParentRequestMappingTests
{
private readonly IFixture _fixture;
private readonly GetPathParentRequestFixture _getPathParentRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetPathParentRequestMappingTests"/> class.
/// </summary>
public GetPathParentRequestMappingTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
}
[Fact]
public void ToQuery_WhenMappingGetPathParentRequest_ShouldMapCorrectly()
{
// Arrange
GetPathParentRequest request = _fixture.Create<GetPathParentRequest>();
GetPathParentRequest request = _getPathParentRequestFixture.Create();
// Act
GetPathParentQuery result = request.ToQuery();
@@ -62,10 +60,10 @@ public class GetPathParentRequestMappingTests
public void ToQuery_WhenMappingMultipleRequests_ShouldMapAllCorrectly()
{
// Arrange
List<GetPathParentRequest> requests = _fixture.CreateMany<GetPathParentRequest>().ToList();
List<GetPathParentRequest> requests = _getPathParentRequestFixture.CreateMany();
// Act
List<GetPathParentQuery> results = requests.Select(r => r.ToQuery()).ToList();
List<GetPathParentQuery> results = [.. requests.Select(r => r.ToQuery())];
// Assert
Assert.NotNull(results);
@@ -1,8 +1,7 @@
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using AutoFixture.AutoNSubstitute;
using Lumina.Application.Common.Mapping.FileSystemManagement.Paths;
using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathRoot;
using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Path;
using Lumina.Contracts.Requests.FileSystemManagement.Path;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
@@ -17,21 +16,20 @@ namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Paths
[ExcludeFromCodeCoverage]
public class GetPathRootRequestMappingTests
{
private readonly IFixture _fixture;
private readonly GetPathRootRequestFixture _getPathRootRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetPathRootRequestMappingTests"/> class.
/// </summary>
public GetPathRootRequestMappingTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
}
[Fact]
public void ToQuery_WhenMappingGetPathRootRequest_ShouldMapCorrectly()
{
// Arrange
GetPathRootRequest request = _fixture.Create<GetPathRootRequest>();
GetPathRootRequest request = _getPathRootRequestFixture.Create();
// Act
GetPathRootQuery result = request.ToQuery();
@@ -63,10 +61,10 @@ public class GetPathRootRequestMappingTests
public void ToQuery_WhenMappingMultipleRequests_ShouldMapAllCorrectly()
{
// Arrange
List<GetPathRootRequest> requests = _fixture.CreateMany<GetPathRootRequest>().ToList();
List<GetPathRootRequest> requests = _getPathRootRequestFixture.CreateMany();
// Act
List<GetPathRootQuery> results = requests.Select(r => r.ToQuery()).ToList();
List<GetPathRootQuery> results = [.. requests.Select(r => r.ToQuery())];
// Assert
Assert.NotNull(results);
@@ -1,8 +1,7 @@
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using AutoFixture.AutoNSubstitute;
using Lumina.Application.Common.Mapping.FileSystemManagement.Paths;
using Lumina.Application.Core.FileSystemManagement.Paths.Commands.SplitPath;
using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Path;
using Lumina.Contracts.Requests.FileSystemManagement.Path;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
@@ -17,21 +16,20 @@ namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Paths
[ExcludeFromCodeCoverage]
public class SplitPathRequestMappingTests
{
private readonly IFixture _fixture;
private readonly SplitPathRequestFixture _splitPathRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="SplitPathRequestMappingTests"/> class.
/// </summary>
public SplitPathRequestMappingTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
}
[Fact]
public void ToCommand_WhenMappingSplitPathRequest_ShouldMapCorrectly()
{
// Arrange
SplitPathRequest request = _fixture.Create<SplitPathRequest>();
SplitPathRequest request = _splitPathRequestFixture.Create();
// Act
SplitPathCommand result = request.ToCommand();
@@ -63,10 +61,10 @@ public class SplitPathRequestMappingTests
public void ToCommand_WhenMappingMultipleRequests_ShouldMapAllCorrectly()
{
// Arrange
List<SplitPathRequest> requests = _fixture.CreateMany<SplitPathRequest>().ToList();
List<SplitPathRequest> requests = _splitPathRequestFixture.CreateMany();
// Act
List<SplitPathCommand> results = requests.Select(r => r.ToCommand()).ToList();
List<SplitPathCommand> results = [.. requests.Select(r => r.ToCommand())];
// Assert
Assert.NotNull(results);
@@ -1,8 +1,7 @@
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using AutoFixture.AutoNSubstitute;
using Lumina.Application.Common.Mapping.FileSystemManagement.Paths;
using Lumina.Application.Core.FileSystemManagement.Paths.Queries.ValidatePath;
using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Path;
using Lumina.Contracts.Requests.FileSystemManagement.Path;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
@@ -17,21 +16,20 @@ namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Paths
[ExcludeFromCodeCoverage]
public class ValidatePathRequestMappingTests
{
private readonly IFixture _fixture;
private readonly ValidatePathRequestFixture _validatePathRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ValidatePathRequestMappingTests"/> class.
/// </summary>
public ValidatePathRequestMappingTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
}
[Fact]
public void ToQuery_WhenMappingValidatePathRequest_ShouldMapCorrectly()
{
// Arrange
ValidatePathRequest request = _fixture.Create<ValidatePathRequest>();
ValidatePathRequest request = _validatePathRequestFixture.Create();
// Act
ValidatePathQuery result = request.ToQuery();
@@ -65,10 +63,10 @@ public class ValidatePathRequestMappingTests
public void ToQuery_WhenMappingMultipleRequests_ShouldMapAllCorrectly()
{
// Arrange
List<ValidatePathRequest> requests = _fixture.CreateMany<ValidatePathRequest>().ToList();
List<ValidatePathRequest> requests = _validatePathRequestFixture.CreateMany();
// Act
List<ValidatePathQuery> results = requests.Select(r => r.ToQuery()).ToList();
List<ValidatePathQuery> results = [.. requests.Select(r => r.ToQuery())];
// Assert
Assert.NotNull(results);
@@ -1,8 +1,7 @@
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using AutoFixture.AutoNSubstitute;
using Lumina.Application.Common.Mapping.FileSystemManagement.Thumbnails;
using Lumina.Application.Core.FileSystemManagement.Thumbnails.Queries.GetThumbnail;
using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Thumbnails;
using Lumina.Contracts.Requests.FileSystemManagement.Thumbnails;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
@@ -17,21 +16,20 @@ namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Thumb
[ExcludeFromCodeCoverage]
public class GetThumbnailRequestMappingTests
{
private readonly IFixture _fixture;
private readonly GetThumbnailRequestFixture _getThumbnailRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetThumbnailRequestMappingTests"/> class.
/// </summary>
public GetThumbnailRequestMappingTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
}
[Fact]
public void ToQuery_WhenMappingGetThumbnailRequest_ShouldMapCorrectly()
{
// Arrange
GetThumbnailRequest request = _fixture.Create<GetThumbnailRequest>();
GetThumbnailRequest request = _getThumbnailRequestFixture.Create();
// Act
GetThumbnailQuery result = request.ToQuery();
@@ -64,10 +62,10 @@ public class GetThumbnailRequestMappingTests
public void ToQuery_WhenMappingMultipleRequests_ShouldMapAllCorrectly()
{
// Arrange
List<GetThumbnailRequest> requests = _fixture.CreateMany<GetThumbnailRequest>().ToList();
List<GetThumbnailRequest> requests = _getThumbnailRequestFixture.CreateMany();
// Act
List<GetThumbnailQuery> results = requests.Select(r => r.ToQuery()).ToList();
List<GetThumbnailQuery> results = [.. requests.Select(r => r.ToQuery())];
// Assert
Assert.NotNull(results);
@@ -2,9 +2,10 @@
using AutoFixture;
using AutoFixture.AutoNSubstitute;
using Lumina.Application.Common.Mapping.FileSystemManagement.Thumbnails;
using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary;
using Lumina.Contracts.Responses.FileSystemManagement.Thumbnails;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
@@ -19,6 +20,7 @@ namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Thumb
public class ThumbnailMappingTests
{
private readonly IFixture _fixture;
private readonly ThumbnailFixture _thumbnailFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ThumbnailMappingTests"/> class.
@@ -32,7 +34,7 @@ public class ThumbnailMappingTests
public void ToResponse_WhenMappingThumbnail_ShouldMapCorrectly()
{
// Arrange
Thumbnail domainModel = _fixture.Create<Thumbnail>();
Thumbnail domainModel = _thumbnailFixture.Create();
// Act
ThumbnailResponse result = domainModel.ToResponse();
@@ -50,7 +52,7 @@ public class ThumbnailMappingTests
public void ToResponse_WhenMappingDifferentImageTypes_ShouldMapCorrectly(ImageType imageType)
{
// Arrange
byte[] bytes = _fixture.CreateMany<byte>(100).ToArray();
byte[] bytes = [.. _fixture.CreateMany<byte>(100)];
Thumbnail domainModel = new(imageType, bytes);
// Act
@@ -83,10 +85,10 @@ public class ThumbnailMappingTests
public void ToResponse_WhenMappingMultipleThumbnails_ShouldMapAllCorrectly()
{
// Arrange
List<Thumbnail> thumbnails = _fixture.CreateMany<Thumbnail>(3).ToList();
List<Thumbnail> thumbnails = _thumbnailFixture.CreateMany(3);
// Act
List<ThumbnailResponse> results = thumbnails.Select(t => t.ToResponse()).ToList();
List<ThumbnailResponse> results = [.. thumbnails.Select(t => t.ToResponse())];
// Assert
Assert.NotNull(results);
@@ -1,9 +1,9 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook;
using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook.Fixtures;
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using System;
@@ -32,7 +32,7 @@ public class AddBookRequestMappingTests
public void ToCommand_WhenMappingCompleteRequest_ShouldMapAllPropertiesCorrectly()
{
// Arrange
AddBookRequest request = _requestFixture.CreateRequestBook();
AddBookRequest request = _requestFixture.Create();
// Act
AddBookCommand result = request.ToCommand();
@@ -2,7 +2,7 @@
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.Mapping.Common.Metadata;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook.Fixtures;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Domain.Common.Primitives;
@@ -34,7 +34,7 @@ public class BookEntityMappingTests
public void ToDomainEntity_WhenMappingValidBookEntity_ShouldMapCorrectly()
{
// Arrange
BookEntity bookEntity = _bookEntityFixture.CreateBook();
BookEntity bookEntity = _bookEntityFixture.Create();
// Act
Result<Book> result = bookEntity.ToDomainEntity();
@@ -264,7 +264,7 @@ public class BookEntityMappingTests
public void ToResponse_WhenMappingBookEntity_ShouldMapAllPropertiesCorrectly()
{
// Arrange
BookEntity bookEntity = _bookEntityFixture.CreateBook();
BookEntity bookEntity = _bookEntityFixture.Create();
// Act
BookResponse result = bookEntity.ToResponse();
@@ -318,11 +318,7 @@ public class BookEntityMappingTests
public void ToDomainModels_WhenMappingMultipleBookEntities_ShouldMapAllCorrectly()
{
// Arrange
List<BookEntity> bookEntities =
[
_bookEntityFixture.CreateBook(),
_bookEntityFixture.CreateBook()
];
List<BookEntity> bookEntities = _bookEntityFixture.CreateMany(2);
// Act
IEnumerable<Result<Book>> results = bookEntities.ToDomainEntities();
@@ -337,11 +333,8 @@ public class BookEntityMappingTests
public void ToResponses_WhenMappingMultipleBookEntities_ShouldMapAllCorrectly()
{
// Arrange
List<BookEntity> bookEntities =
[
_bookEntityFixture.CreateBook(),
_bookEntityFixture.CreateBook()
];
List<BookEntity> bookEntities = _bookEntityFixture.CreateMany(2);
// Act
IEnumerable<BookResponse> results = bookEntities.ToResponses();
@@ -1,11 +1,11 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.Mapping.Common.Metadata;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
using Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
using System.Diagnostics.CodeAnalysis;
using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook.Fixtures;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
@@ -30,7 +30,7 @@ public class BookMappingTests
public void ToRepositoryEntity_WhenMappingCompleteBook_ShouldMapAllPropertiesCorrectly()
{
// Arrange
Book book = _bookFixture.CreateDomainBook();
Book book = _bookFixture.Create();
// Act
BookEntity result = book.ToRepositoryEntity();
@@ -1,10 +1,10 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook.Fixtures;
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
using Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using System;
#endregion
@@ -22,7 +22,7 @@ public class BookMetadataDtoMappingTests
public void ApplyMetadata_WhenCalledWithValidMetadata_ShouldApplyItAndMarkTheBookAsEnriched()
{
// Arrange
Book book = _bookFixture.CreateDomainBook();
Book book = _bookFixture.Create();
BookMetadataDto metadata = CreateBookMetadata("The Fellowship of the Ring", "3");
// Act
@@ -44,7 +44,7 @@ public class BookMetadataDtoMappingTests
public void ApplyMetadata_WhenCalledWithInvalidGenres_ShouldReturnError()
{
// Arrange
Book book = _bookFixture.CreateDomainBook();
Book book = _bookFixture.Create();
BookMetadataDto metadata = CreateBookMetadata("The Fellowship of the Ring", "3") with
{
Genres = [new GenreDto("")]
@@ -1,8 +1,8 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.Common.Metadata;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common;
using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Common.Fixtures;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
using System.Collections.Generic;
@@ -32,7 +32,7 @@ public class BookRatingDtoMappingTests
public void ToDomainEntity_WhenMappingCompleteBookRatinDto_ShouldMapAllPropertiesCorrectly()
{
// Arrange
BookRatingDto dto = _bookRatingDtoFixture.CreateComplete();
BookRatingDto dto = _bookRatingDtoFixture.Create();
// Act
Result<BookRating> result = dto.ToDomainEntity();
@@ -64,7 +64,7 @@ public class BookRatingDtoMappingTests
public void ToDomainEntity_WhenMappingMinimalBookRatingDto_ShouldMapRequiredPropertiesCorrectly()
{
// Arrange
BookRatingDto dto = _bookRatingDtoFixture.CreateMinimal();
BookRatingDto dto = _bookRatingDtoFixture.Create(includeOptionalProperties: false);
// Act
Result<BookRating> result = dto.ToDomainEntity();
@@ -82,7 +82,7 @@ public class BookRatingDtoMappingTests
public void ToDomainEntity_WhenMappingInvalidBookRatingDto_ShouldReturnError()
{
// Arrange
BookRatingDto dto = _bookRatingDtoFixture.CreateInvalid();
BookRatingDto dto = _bookRatingDtoFixture.Create(value: 10, maxValue: 5);
// Act
Result<BookRating> result = dto.ToDomainEntity();
@@ -97,8 +97,8 @@ public class BookRatingDtoMappingTests
// Arrange
List<BookRatingDto> dtos =
[
_bookRatingDtoFixture.CreateComplete(),
_bookRatingDtoFixture.CreateMinimal()
_bookRatingDtoFixture.Create(),
_bookRatingDtoFixture.Create(includeOptionalProperties: false)
];
// Act
@@ -131,9 +131,9 @@ public class BookRatingDtoMappingTests
// Arrange
List<BookRatingDto> dtos =
[
_bookRatingDtoFixture.CreateComplete(),
_bookRatingDtoFixture.CreateInvalid(),
_bookRatingDtoFixture.CreateMinimal()
_bookRatingDtoFixture.Create(),
_bookRatingDtoFixture.Create(value: 10, maxValue: 5),
_bookRatingDtoFixture.Create(includeOptionalProperties: false)
];
// Act
@@ -2,7 +2,7 @@
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.Mapping.Common.Metadata;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common;
using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Common.Fixtures;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
@@ -33,7 +33,7 @@ public class BookRatingEntityMappingTests
public void ToResponse_WhenMappingValidBookRatingEntity_ShouldMapCorrectly()
{
// Arrange
BookRatingEntity entity = _fixture.CreateBookRating();
BookRatingEntity entity = _fixture.Create();
// Act
BookRatingDto result = entity.ToResponse();
@@ -50,7 +50,7 @@ public class BookRatingEntityMappingTests
public void ToResponse_WhenMappingInvalidBookRatingEntity_ShouldMapToDefaults()
{
// Arrange
BookRatingEntity entity = _fixture.CreateInvalidBookRating();
BookRatingEntity entity = _fixture.Create(includeValues: false);
// Act
BookRatingDto result = entity.ToResponse();
@@ -67,12 +67,7 @@ public class BookRatingEntityMappingTests
public void ToResponses_WhenMappingMultipleBookRatingEntities_ShouldMapAllCorrectly()
{
// Arrange
List<BookRatingEntity> entities =
[
_fixture.CreateBookRating(),
_fixture.CreateBookRating()
];
List<BookRatingEntity> entities = _fixture.CreateMany(2);
// Act
IEnumerable<BookRatingDto> results = entities.ToResponses();
@@ -92,7 +87,7 @@ public class BookRatingEntityMappingTests
public void ToDomainEntity_WhenMappingValidBookRatingEntity_ShouldMapCorrectly()
{
// Arrange
BookRatingEntity entity = _fixture.CreateBookRating();
BookRatingEntity entity = _fixture.Create();
// Act
Result<BookRating> result = entity.ToDomainEntity();
@@ -110,7 +105,7 @@ public class BookRatingEntityMappingTests
public void ToDomainEntity_WhenMappingInvalidBookRatingEntity_ShouldMapToDefaults()
{
// Arrange
BookRatingEntity entity = _fixture.CreateInvalidBookRating();
BookRatingEntity entity = _fixture.Create(includeValues: false);
// Act
Result<BookRating> result = entity.ToDomainEntity();
@@ -128,11 +123,7 @@ public class BookRatingEntityMappingTests
public void ToDomainEntities_WhenMappingMultipleBookRatingEntities_ShouldMapAllCorrectly()
{
// Arrange
List<BookRatingEntity> entities =
[
_fixture.CreateBookRating(),
_fixture.CreateBookRating()
];
List<BookRatingEntity> entities = _fixture.CreateMany(2);
// Act
IEnumerable<Result<BookRating>> results = entities.ToDomainEntities();
@@ -2,8 +2,10 @@
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.Mapping.Common.Metadata;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common;
using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Common.Fixtures;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
@@ -31,7 +33,7 @@ public class BookRatingMappingTests
public void ToRepositoryEntity_WhenMappingCompleteBookRating_ShouldMapAllPropertiesCorrectly()
{
// Arrange
BookRating bookRating = _bookRatingFixture.CreateBookRating();
BookRating bookRating = _bookRatingFixture.Create();
// Act
BookRatingEntity result = bookRating.ToRepositoryEntity();
@@ -48,7 +50,7 @@ public class BookRatingMappingTests
public void ToRepositoryEntity_WhenMappingBookRatingWithoutSource_ShouldMapCorrectly()
{
// Arrange
BookRating bookRating = _bookRatingFixture.CreateBookRatingWithoutSource();
BookRating bookRating = _bookRatingFixture.Create(source: Optional<BookRatingSource>.None());
// Act
BookRatingEntity result = bookRating.ToRepositoryEntity();
@@ -65,7 +67,7 @@ public class BookRatingMappingTests
public void ToRepositoryEntity_WhenMappingBookRatingWithoutVoteCount_ShouldMapCorrectly()
{
// Arrange
BookRating bookRating = _bookRatingFixture.CreateBookRatingWithoutVoteCount();
BookRating bookRating = _bookRatingFixture.Create(voteCount: Optional<int>.None());
// Act
BookRatingEntity result = bookRating.ToRepositoryEntity();
@@ -84,9 +86,9 @@ public class BookRatingMappingTests
// Arrange
List<BookRating> bookRatings =
[
_bookRatingFixture.CreateBookRating(),
_bookRatingFixture.CreateBookRatingWithoutSource(),
_bookRatingFixture.CreateBookRatingWithoutVoteCount()
_bookRatingFixture.Create(),
_bookRatingFixture.Create(source: Optional<BookRatingSource>.None()),
_bookRatingFixture.Create(voteCount: Optional<int>.None())
];
// Act
@@ -96,7 +98,7 @@ public class BookRatingMappingTests
Assert.NotNull(results);
Assert.Equal(bookRatings.Count, results.Count());
List<BookRatingEntity> resultList = results.ToList();
List<BookRatingEntity> resultList = [.. results];
// complete rating
Assert.Equal(bookRatings[0].Value, resultList[0].Value);
@@ -1,8 +1,8 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.Common.Metadata;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common;
using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Common.Fixtures;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
@@ -33,7 +33,7 @@ public class IsbnDtoMappingTests
public void ToDomainEntity_WhenMappingValidIsbn10Dto_ShouldMapCorrectly()
{
// Arrange
IsbnDto dto = _isbnDtoFixture.CreateIsbn10();
IsbnDto dto = _isbnDtoFixture.Create(format: IsbnFormat.Isbn10);
// Act
Result<Isbn> result = dto.ToDomainEntity();
@@ -49,7 +49,7 @@ public class IsbnDtoMappingTests
public void ToDomainEntity_WhenMappingValidIsbn13Dto_ShouldMapCorrectly()
{
// Arrange
IsbnDto dto = _isbnDtoFixture.CreateIsbn13();
IsbnDto dto = _isbnDtoFixture.Create(format: IsbnFormat.Isbn13);
// Act
Result<Isbn> result = dto.ToDomainEntity();
@@ -65,7 +65,7 @@ public class IsbnDtoMappingTests
public void ToDomainEntity_WhenMappingDtoWithoutFormat_ShouldUseDefaultFormat()
{
// Arrange
IsbnDto dto = _isbnDtoFixture.CreateWithoutFormat();
IsbnDto dto = _isbnDtoFixture.Create();
// Act
Result<Isbn> result = dto.ToDomainEntity();
@@ -81,7 +81,7 @@ public class IsbnDtoMappingTests
public void ToDomainEntity_WhenMappingInvalidIsbnDto_ShouldReturnError()
{
// Arrange
IsbnDto dto = _isbnDtoFixture.CreateInvalid();
IsbnDto dto = _isbnDtoFixture.Create("invalid-isbn", IsbnFormat.Isbn13);
// Act
Result<Isbn> result = dto.ToDomainEntity();
@@ -96,9 +96,9 @@ public class IsbnDtoMappingTests
// Arrange
List<IsbnDto> dtos =
[
_isbnDtoFixture.CreateIsbn10(),
_isbnDtoFixture.CreateIsbn13(),
_isbnDtoFixture.CreateWithoutFormat()
_isbnDtoFixture.Create(format: IsbnFormat.Isbn10),
_isbnDtoFixture.Create(format: IsbnFormat.Isbn13),
_isbnDtoFixture.Create(),
];
// Act
@@ -127,9 +127,9 @@ public class IsbnDtoMappingTests
// Arrange
List<IsbnDto> dtos =
[
_isbnDtoFixture.CreateIsbn10(),
_isbnDtoFixture.CreateInvalid(),
_isbnDtoFixture.CreateIsbn13()
_isbnDtoFixture.Create(format: IsbnFormat.Isbn10),
_isbnDtoFixture.Create("invalid-isbn", IsbnFormat.Isbn13),
_isbnDtoFixture.Create(format: IsbnFormat.Isbn13)
];
// Act
@@ -2,9 +2,9 @@
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.Mapping.Common.Metadata;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common;
using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Common.Fixtures;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
@@ -32,7 +32,7 @@ public class IsbnMappingTests
public void ToRepositoryEntity_WhenMappingIsbn10_ShouldMapCorrectly()
{
// Arrange
Isbn isbn = _isbnFixture.CreateIsbn10();
Isbn isbn = _isbnFixture.Create(IsbnFormat.Isbn10);
// Act
IsbnEntity result = isbn.ToRepositoryEntity();
@@ -47,7 +47,7 @@ public class IsbnMappingTests
public void ToRepositoryEntity_WhenMappingIsbn13_ShouldMapCorrectly()
{
// Arrange
Isbn isbn = _isbnFixture.CreateIsbn13();
Isbn isbn = _isbnFixture.Create(IsbnFormat.Isbn13);
// Act
IsbnEntity result = isbn.ToRepositoryEntity();
@@ -64,9 +64,9 @@ public class IsbnMappingTests
// Arrange
List<Isbn> isbns =
[
_isbnFixture.CreateIsbn10(),
_isbnFixture.CreateIsbn13(),
_isbnFixture.CreateIsbn10()
_isbnFixture.Create(IsbnFormat.Isbn10),
_isbnFixture.Create(IsbnFormat.Isbn13),
_isbnFixture.Create(IsbnFormat.Isbn10)
];
// Act
@@ -76,7 +76,7 @@ public class IsbnMappingTests
Assert.NotNull(results);
Assert.Equal(isbns.Count, results.Count());
List<IsbnEntity> resultList = results.ToList();
List<IsbnEntity> resultList = [.. results];
for (int i = 0; i < isbns.Count; i++)
{
Assert.Equal(isbns[i].Value, resultList[i].Value);
@@ -1,74 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures;
/// <summary>
/// Fixture class for the <see cref="UserEntity"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UserEntityFixture
{
/// <summary>
/// Creates a random valid user entity.
/// </summary>
/// <param name="libraryCount">Number of libraries to generate. Default is 0.</param>
/// <returns>The created user entity.</returns>
public static UserEntity CreateUserEntity(int libraryCount = 0)
{
Guid userId = Guid.NewGuid();
List<LibraryEntity> libraries = [.. new Faker<LibraryEntity>()
.CustomInstantiator(f => new LibraryEntity
{
Id = Guid.NewGuid(),
UserId = userId,
Title = f.Commerce.ProductName(),
LibraryType = f.PickRandom<LibraryType>(),
ContentLocations = [],
CreatedOnUtc = f.Date.Past(),
CreatedBy = userId,
UpdatedOnUtc = null,
UpdatedBy = null
})
.Generate(libraryCount)];
return new Faker<UserEntity>()
.CustomInstantiator(f => new UserEntity
{
Id = userId,
Username = default!,
Password = default!,
CreatedOnUtc = default,
TotpSecret = default,
Libraries = libraries,
UserPermissions = [],
UserRole = null,
CreatedBy = userId
})
.RuleFor(x => x.Username, f => f.Internet.UserName())
.RuleFor(x => x.Password, f => Uri.EscapeDataString(f.Internet.Password()))
.RuleFor(x => x.CreatedOnUtc, f => f.Date.Past())
.RuleFor(x => x.TotpSecret, f => f.Random.Bool() ? f.Random.String2(32) : null)
.Generate();
}
/// <summary>
/// Creates a list of user entities.
/// </summary>
/// <param name="count">The number of entities to create.</param>
/// <returns>The created list.</returns>
public static List<UserEntity> CreateMany(int count = 3)
{
return Enumerable.Range(0, count)
.Select(_ => CreateUserEntity())
.ToList();
}
}
@@ -3,7 +3,7 @@ using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.Mapping.Common.Metadata;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common;
using Lumina.Application.Common.Mapping.UsersManagement.Users;
using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Responses.UsersManagement.Users;
using System;
using System.Collections.Generic;
@@ -19,11 +19,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users;
[ExcludeFromCodeCoverage]
public class UserEntityMappingTests
{
private readonly UserEntityFixture _userEntityFixture = new();
[Fact]
public void ToResponse_WhenMappingValidUserEntity_ShouldMapCorrectly()
{
// Arrange
UserEntity entity = UserEntityFixture.CreateUserEntity();
UserEntity entity = _userEntityFixture.Create();
// Act
UserResponse result = entity.ToResponse();
@@ -44,7 +46,7 @@ public class UserEntityMappingTests
public void ToResponse_WhenMappingDifferentUsernames_ShouldMapCorrectly(string username)
{
// Arrange
UserEntity entity = UserEntityFixture.CreateUserEntity();
UserEntity entity = _userEntityFixture.Create();
entity.Username = username;
// Act
@@ -59,7 +61,7 @@ public class UserEntityMappingTests
public void ToResponse_WhenMappingWithUpdatedDateTime_ShouldMapCorrectly()
{
// Arrange
UserEntity entity = UserEntityFixture.CreateUserEntity();
UserEntity entity = _userEntityFixture.Create();
entity.UpdatedOnUtc = DateTime.UtcNow.AddDays(-1);
// Act
@@ -74,7 +76,7 @@ public class UserEntityMappingTests
public void ToResponse_WhenMappingWithLibraries_ShouldNotAffectMapping()
{
// Arrange
UserEntity entity = UserEntityFixture.CreateUserEntity(2);
UserEntity entity = _userEntityFixture.Create(2);
// Act
UserResponse result = entity.ToResponse();
@@ -91,7 +93,7 @@ public class UserEntityMappingTests
public void ToResponses_WhenMappingMultipleEntities_ShouldMapCorrectly()
{
// Arrange
List<UserEntity> entities = UserEntityFixture.CreateMany(3);
List<UserEntity> entities = _userEntityFixture.CreateMany(3);
// Act
IEnumerable<UserResponse> results = entities.ToResponses();
@@ -127,7 +129,7 @@ public class UserEntityMappingTests
public void ToResponse_WhenMappingWithoutUpdatedDateTime_ShouldMapCorrectly()
{
// Arrange
UserEntity entity = UserEntityFixture.CreateUserEntity();
UserEntity entity = _userEntityFixture.Create();
entity.UpdatedOnUtc = null;
// Act
@@ -1,38 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Setup;
/// <summary>
/// Contains extension methods for the <see cref="Faker"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public static class BogusExtensions
{
/// <summary>
/// Adds <see cref="DateOnly"/> random data generation support to the <see cref="Faker"/> class.
/// </summary>
/// <param name="faker">The faker instance to extend.</param>
/// <returns>A random<see cref="DateOnly"/> instance.</returns>
public static DateOnly DateOnly(this Faker faker)
{
return System.DateOnly.FromDateTime(faker.Date.Past());
}
/// <summary>
/// Adds <see cref="DateOnly"/> random data generation within a specified interval support to the <see cref="Faker"/> class.
/// </summary>
/// <param name="faker">The faker instance to extend.</param>
/// <param name="start">The start of the interval.</param>
/// <param name="end">The end of the interval.</param>
/// <returns>A random<see cref="DateOnly"/> instance.</returns>
public static DateOnly DateOnlyBetween(this Faker faker, DateOnly start, DateOnly end)
{
DateTime startDateTime = start.ToDateTime(TimeOnly.MinValue);
DateTime endDateTime = end.ToDateTime(TimeOnly.MinValue);
return System.DateOnly.FromDateTime(faker.Date.Between(startDateTime, endDateTime));
}
}
@@ -1,27 +0,0 @@
#region ========================================================================= USING =====================================================================================
using AutoFixture.Kernel;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Setup;
/// <summary>
/// Represents a specimen builder for the <see cref="DateOnly"/> type.
/// </summary>
[ExcludeFromCodeCoverage]
public class DateOnlySpecimenBuilder : ISpecimenBuilder
{
/// <summary>
/// Adds <see cref="DateOnly"/> support to the AutoFixture library.
/// </summary>
/// <param name="request">The request to process.</param>
/// <param name="context">The context within which the specimen is created.</param>
/// <returns>A specimen based on the request.</returns>
public object Create(object request, ISpecimenContext context)
{
if (request is Type type && type == typeof(DateOnly))
return DateOnly.FromDateTime(DateTime.Now);
return new NoSpecimen();
}
}
@@ -1,27 +0,0 @@
#region ========================================================================= USING =====================================================================================
using AutoFixture.Kernel;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Setup;
/// <summary>
/// Represents a specimen builder for the <see cref="DateOnly"/> type.
/// </summary>
[ExcludeFromCodeCoverage]
public class NullableDateOnlySpecimenBuilder : ISpecimenBuilder
{
/// <summary>
/// Adds <see cref="DateOnly?"/> support to the AutoFixture library.
/// </summary>
/// <param name="request">The request to process.</param>
/// <param name="context">The context within which the specimen is created.</param>
/// <returns>A specimen based on the request.</returns>
public object Create(object request, ISpecimenContext context)
{
if (request is Type type && type == typeof(DateOnly?))
return (DateOnly?)DateOnly.FromDateTime(DateTime.Now);
return new NoSpecimen();
}
}
@@ -7,7 +7,7 @@ using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.Admin.Authorization.Roles.Commands.AddRole;
using Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Commands.AddRole.Fixtures;
using Lumina.Application.Fixtures.Core.Admin.Authorization.Roles.Commands.AddRole;
using Lumina.Contracts.Responses.Authorization;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
@@ -64,7 +64,7 @@ public class AddRoleCommandHandlerTests
public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError()
{
// Arrange
AddRoleCommand command = _addRoleCommandFixture.CreateCommand();
AddRoleCommand command = _addRoleCommandFixture.Create();
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>())
.Returns(false);
@@ -81,7 +81,7 @@ public class AddRoleCommandHandlerTests
public async Task HandleAsync_WhenInsertRoleFails_ShouldReturnError()
{
// Arrange
AddRoleCommand command = _addRoleCommandFixture.CreateCommand();
AddRoleCommand command = _addRoleCommandFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to insert role");
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>())
@@ -102,7 +102,7 @@ public class AddRoleCommandHandlerTests
public async Task HandleAsync_WhenGetRoleByNameFails_ShouldReturnError()
{
// Arrange
AddRoleCommand command = _addRoleCommandFixture.CreateCommand();
AddRoleCommand command = _addRoleCommandFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to get role");
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>())
@@ -124,7 +124,7 @@ public class AddRoleCommandHandlerTests
public async Task HandleAsync_WhenGetRoleByNameReturnsNull_ShouldReturnError()
{
// Arrange
AddRoleCommand command = _addRoleCommandFixture.CreateCommand();
AddRoleCommand command = _addRoleCommandFixture.Create();
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>())
.Returns(true);
@@ -145,7 +145,7 @@ public class AddRoleCommandHandlerTests
public async Task HandleAsync_WhenAllOperationsSucceed_ShouldReturnSuccessResponse()
{
// Arrange
AddRoleCommand command = _addRoleCommandFixture.CreateCommand();
AddRoleCommand command = _addRoleCommandFixture.Create();
Guid roleId = Guid.NewGuid();
RoleEntity role = new()
{
@@ -1,8 +1,8 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Errors;
using Lumina.Application.Core.Admin.Authorization.Roles.Commands.AddRole;
using Lumina.Application.Fixtures.Core.Admin.Authorization.Roles.Commands.AddRole;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Commands.AddRole.Fixtures;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
@@ -33,7 +33,7 @@ public class AddRoleCommandValidatorTests
public void Validate_WhenRoleNameIsNull_ShouldHaveValidationError()
{
// Arrange
AddRoleCommand command = _fixture.CreateCommand();
AddRoleCommand command = _fixture.Create();
command = command with { RoleName = null! };
// Act
@@ -47,7 +47,7 @@ public class AddRoleCommandValidatorTests
public void Validate_WhenRoleNameIsEmpty_ShouldHaveValidationError()
{
// Arrange
AddRoleCommand command = _fixture.CreateCommand();
AddRoleCommand command = _fixture.Create();
command = command with { RoleName = string.Empty };
// Act
@@ -61,7 +61,7 @@ public class AddRoleCommandValidatorTests
public void Validate_WhenRoleNameIsWhitespace_ShouldHaveValidationError()
{
// Arrange
AddRoleCommand command = _fixture.CreateCommand();
AddRoleCommand command = _fixture.Create();
command = command with { RoleName = " " };
// Act
@@ -75,7 +75,7 @@ public class AddRoleCommandValidatorTests
public void Validate_WhenPermissionsIsNull_ShouldHaveValidationError()
{
// Arrange
AddRoleCommand command = _fixture.CreateCommand();
AddRoleCommand command = _fixture.Create();
command = command with { Permissions = null! };
// Act
@@ -89,7 +89,7 @@ public class AddRoleCommandValidatorTests
public void Validate_WhenPermissionsIsEmpty_ShouldHaveValidationError()
{
// Arrange
AddRoleCommand command = _fixture.CreateCommand();
AddRoleCommand command = _fixture.Create();
command = command with { Permissions = [] };
// Act
@@ -103,7 +103,7 @@ public class AddRoleCommandValidatorTests
public void Validate_WhenPermissionContainsEmptyGuid_ShouldHaveValidationError()
{
// Arrange
AddRoleCommand command = _fixture.CreateCommand();
AddRoleCommand command = _fixture.Create();
command = command with { Permissions = [Guid.Empty, Guid.NewGuid()] };
// Act
@@ -117,7 +117,7 @@ public class AddRoleCommandValidatorTests
public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError()
{
// Arrange
AddRoleCommand command = _fixture.CreateCommand();
AddRoleCommand command = _fixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
@@ -1,34 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.Admin.Authorization.Roles.Commands.AddRole;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Commands.AddRole.Fixtures;
/// <summary>
/// Fixture class for the <see cref="AddRoleCommand"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddRoleCommandFixture
{
/// <summary>
/// Creates a random valid command to add a role.
/// </summary>
/// <param name="permissionCount">The number of permissions to generate.</param>
/// <returns>The created command to add a role.</returns>
public AddRoleCommand CreateCommand(int permissionCount = 3)
{
return new Faker<AddRoleCommand>()
.CustomInstantiator(f => new AddRoleCommand(
default!,
default!))
.RuleFor(x => x.RoleName, f => f.Random.String2(f.Random.Number(1, 50)))
.RuleFor(x => x.Permissions, f => Enumerable.Range(0, permissionCount)
.Select(_ => Guid.NewGuid())
.ToList())
.Generate();
}
}
@@ -7,7 +7,7 @@ using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.Admin.Authorization.Roles.Commands.DeleteRole;
using Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Commands.DeleteRole.Fixtures;
using Lumina.Application.Fixtures.Core.Admin.Authorization.Roles.Commands.DeleteRole;
using Lumina.Domain.Common.Primitives;
using NSubstitute;
using System;
@@ -61,7 +61,7 @@ public class DeleteRoleCommandHandlerTests
public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError()
{
// Arrange
DeleteRoleCommand command = _deleteRoleCommandFixture.CreateCommand();
DeleteRoleCommand command = _deleteRoleCommandFixture.Create();
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>())
.Returns(false);
@@ -78,7 +78,7 @@ public class DeleteRoleCommandHandlerTests
public async Task HandleAsync_WhenRoleDoesNotExist_ShouldReturnRoleNotFoundError()
{
// Arrange
DeleteRoleCommand command = _deleteRoleCommandFixture.CreateCommand();
DeleteRoleCommand command = _deleteRoleCommandFixture.Create();
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>())
.Returns(true);
@@ -98,7 +98,7 @@ public class DeleteRoleCommandHandlerTests
public async Task HandleAsync_WhenDeletingAdminRole_ShouldReturnAdminRoleCannotBeDeletedError()
{
// Arrange
DeleteRoleCommand command = _deleteRoleCommandFixture.CreateCommand();
DeleteRoleCommand command = _deleteRoleCommandFixture.Create();
RoleEntity adminRole = new() { Id = command.RoleId, RoleName = "Admin" };
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>())
@@ -119,7 +119,7 @@ public class DeleteRoleCommandHandlerTests
public async Task HandleAsync_WhenGetRoleByIdFails_ShouldReturnError()
{
// Arrange
DeleteRoleCommand command = _deleteRoleCommandFixture.CreateCommand();
DeleteRoleCommand command = _deleteRoleCommandFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to get role");
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>())
@@ -140,7 +140,7 @@ public class DeleteRoleCommandHandlerTests
public async Task HandleAsync_WhenDeleteRoleFails_ShouldReturnError()
{
// Arrange
DeleteRoleCommand command = _deleteRoleCommandFixture.CreateCommand();
DeleteRoleCommand command = _deleteRoleCommandFixture.Create();
RoleEntity role = new() { Id = command.RoleId, RoleName = "TestRole" };
Error error = Error.Failure("Database.Error", "Failed to delete role");
@@ -164,7 +164,7 @@ public class DeleteRoleCommandHandlerTests
public async Task HandleAsync_WhenAllOperationsSucceed_ShouldReturnSuccess()
{
// Arrange
DeleteRoleCommand command = _deleteRoleCommandFixture.CreateCommand();
DeleteRoleCommand command = _deleteRoleCommandFixture.Create();
RoleEntity role = new() { Id = command.RoleId, RoleName = "TestRole" };
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>())
@@ -1,27 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.Admin.Authorization.Roles.Commands.DeleteRole;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Commands.DeleteRole.Fixtures;
/// <summary>
/// Fixture class for the <see cref="DeleteRoleCommand"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeleteRoleCommandFixture
{
/// <summary>
/// Creates a random valid command to delete a role.
/// </summary>
/// <returns>The created command.</returns>
public DeleteRoleCommand CreateCommand()
{
return new Faker<DeleteRoleCommand>()
.CustomInstantiator(f => new DeleteRoleCommand(
Guid.NewGuid()))
.Generate();
}
}
@@ -1,46 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.Admin.Authorization.Roles.Commands.UpdateRole;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Commands.UpdateRole.Fixtures;
/// <summary>
/// Fixture class for the <see cref="UpdateRoleCommand"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateRoleCommandFixture
{
private readonly Faker _faker;
/// <summary>
/// Initializes a new instance of the <see cref="UpdateRoleCommandFixture"/> class.
/// </summary>
public UpdateRoleCommandFixture()
{
_faker = new Faker();
}
/// <summary>
/// Creates a random valid command to update a role.
/// </summary>
/// <param name="permissionCount">The number of permissions to generate.</param>
/// <returns>The created command to update a role.</returns>
public UpdateRoleCommand CreateCommand(int permissionCount = 3)
{
return new Faker<UpdateRoleCommand>()
.CustomInstantiator(f => new UpdateRoleCommand(
default,
default!,
default!))
.RuleFor(x => x.RoleId, f => Guid.NewGuid())
.RuleFor(x => x.RoleName, f => f.Random.String2(f.Random.Number(1, 50)))
.RuleFor(x => x.Permissions, f => Enumerable.Range(0, permissionCount)
.Select(_ => Guid.NewGuid())
.ToList())
.Generate();
}
}
@@ -7,7 +7,7 @@ using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.Admin.Authorization.Roles.Commands.UpdateRole;
using Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Commands.UpdateRole.Fixtures;
using Lumina.Application.Fixtures.Core.Admin.Authorization.Roles.Commands.UpdateRole;
using Lumina.Contracts.Responses.Authorization;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
@@ -64,7 +64,7 @@ public class UpdateRoleCommandHandlerTests
public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError()
{
// Arrange
UpdateRoleCommand command = _updateRoleCommandFixture.CreateCommand();
UpdateRoleCommand command = _updateRoleCommandFixture.Create();
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>())
.Returns(false);
@@ -81,7 +81,7 @@ public class UpdateRoleCommandHandlerTests
public async Task HandleAsync_WhenUpdateRoleFails_ShouldReturnError()
{
// Arrange
UpdateRoleCommand command = _updateRoleCommandFixture.CreateCommand();
UpdateRoleCommand command = _updateRoleCommandFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to update role");
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>())
@@ -102,7 +102,7 @@ public class UpdateRoleCommandHandlerTests
public async Task HandleAsync_WhenGetRoleByIdFails_ShouldReturnError()
{
// Arrange
UpdateRoleCommand command = _updateRoleCommandFixture.CreateCommand();
UpdateRoleCommand command = _updateRoleCommandFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to get role");
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>())
@@ -124,7 +124,7 @@ public class UpdateRoleCommandHandlerTests
public async Task HandleAsync_WhenGetRoleByIdReturnsNull_ShouldReturnError()
{
// Arrange
UpdateRoleCommand command = _updateRoleCommandFixture.CreateCommand();
UpdateRoleCommand command = _updateRoleCommandFixture.Create();
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>())
.Returns(true);
@@ -145,7 +145,7 @@ public class UpdateRoleCommandHandlerTests
public async Task HandleAsync_WhenAllOperationsSucceed_ShouldReturnSuccessResponse()
{
// Arrange
UpdateRoleCommand command = _updateRoleCommandFixture.CreateCommand();
UpdateRoleCommand command = _updateRoleCommandFixture.Create();
RoleEntity role = new()
{
Id = command.RoleId,
@@ -1,8 +1,8 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Errors;
using Lumina.Application.Core.Admin.Authorization.Roles.Commands.UpdateRole;
using Lumina.Application.Fixtures.Core.Admin.Authorization.Roles.Commands.UpdateRole;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Commands.UpdateRole.Fixtures;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
@@ -33,7 +33,7 @@ public class UpdateRoleCommandValidatorTests
public void Validate_WhenRoleIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
UpdateRoleCommand command = _fixture.CreateCommand();
UpdateRoleCommand command = _fixture.Create();
command = command with { RoleId = Guid.Empty };
// Act
@@ -47,7 +47,7 @@ public class UpdateRoleCommandValidatorTests
public void Validate_WhenRoleNameIsNull_ShouldHaveValidationError()
{
// Arrange
UpdateRoleCommand command = _fixture.CreateCommand();
UpdateRoleCommand command = _fixture.Create();
command = command with { RoleName = null! };
// Act
@@ -61,7 +61,7 @@ public class UpdateRoleCommandValidatorTests
public void Validate_WhenRoleNameIsEmpty_ShouldHaveValidationError()
{
// Arrange
UpdateRoleCommand command = _fixture.CreateCommand();
UpdateRoleCommand command = _fixture.Create();
command = command with { RoleName = string.Empty };
// Act
@@ -75,7 +75,7 @@ public class UpdateRoleCommandValidatorTests
public void Validate_WhenRoleNameIsWhitespace_ShouldHaveValidationError()
{
// Arrange
UpdateRoleCommand command = _fixture.CreateCommand();
UpdateRoleCommand command = _fixture.Create();
command = command with { RoleName = " " };
// Act
@@ -89,7 +89,7 @@ public class UpdateRoleCommandValidatorTests
public void Validate_WhenPermissionsIsNull_ShouldHaveValidationError()
{
// Arrange
UpdateRoleCommand command = _fixture.CreateCommand();
UpdateRoleCommand command = _fixture.Create();
command = command with { Permissions = null! };
// Act
@@ -103,7 +103,7 @@ public class UpdateRoleCommandValidatorTests
public void Validate_WhenPermissionsIsEmpty_ShouldHaveValidationError()
{
// Arrange
UpdateRoleCommand command = _fixture.CreateCommand();
UpdateRoleCommand command = _fixture.Create();
command = command with { Permissions = [] };
// Act
@@ -117,7 +117,7 @@ public class UpdateRoleCommandValidatorTests
public void Validate_WhenPermissionContainsEmptyGuid_ShouldHaveValidationError()
{
// Arrange
UpdateRoleCommand command = _fixture.CreateCommand();
UpdateRoleCommand command = _fixture.Create();
command = command with { Permissions = [Guid.Empty, Guid.NewGuid()] };
// Act
@@ -131,7 +131,7 @@ public class UpdateRoleCommandValidatorTests
public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError()
{
// Arrange
UpdateRoleCommand command = _fixture.CreateCommand();
UpdateRoleCommand command = _fixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
@@ -1,27 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRolePermissions;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Queries.GetRolePermissions.Fixtures;
/// <summary>
/// Fixture class for the <see cref="GetRolePermissionsQuery"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetRolePermissionsQueryFixture
{
/// <summary>
/// Creates a random valid query to get role permissions.
/// </summary>
/// <returns>The created query.</returns>
public GetRolePermissionsQuery CreateQuery()
{
return new Faker<GetRolePermissionsQuery>()
.CustomInstantiator(f => new GetRolePermissionsQuery(
Guid.NewGuid()))
.Generate();
}
}
@@ -7,7 +7,7 @@ using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRolePermissions;
using Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Queries.GetRolePermissions.Fixtures;
using Lumina.Application.Fixtures.Core.Admin.Authorization.Roles.Queries.GetRolePermissions;
using Lumina.Contracts.Responses.Authorization;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
@@ -63,7 +63,7 @@ public class GetRolePermissionsQueryHandlerTests
public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError()
{
// Arrange
GetRolePermissionsQuery query = _getRolePermissionsQueryFixture.CreateQuery();
GetRolePermissionsQuery query = _getRolePermissionsQueryFixture.Create();
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>())
.Returns(false);
@@ -80,7 +80,7 @@ public class GetRolePermissionsQueryHandlerTests
public async Task HandleAsync_WhenGetRoleByIdFails_ShouldReturnError()
{
// Arrange
GetRolePermissionsQuery query = _getRolePermissionsQueryFixture.CreateQuery();
GetRolePermissionsQuery query = _getRolePermissionsQueryFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to get role");
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>())
@@ -100,7 +100,7 @@ public class GetRolePermissionsQueryHandlerTests
public async Task HandleAsync_WhenRoleNotFound_ShouldReturnRoleNotFoundError()
{
// Arrange
GetRolePermissionsQuery query = _getRolePermissionsQueryFixture.CreateQuery();
GetRolePermissionsQuery query = _getRolePermissionsQueryFixture.Create();
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>())
.Returns(true);
@@ -119,7 +119,7 @@ public class GetRolePermissionsQueryHandlerTests
public async Task HandleAsync_WhenAllOperationsSucceed_ShouldReturnRolePermissions()
{
// Arrange
GetRolePermissionsQuery query = _getRolePermissionsQueryFixture.CreateQuery();
GetRolePermissionsQuery query = _getRolePermissionsQueryFixture.Create();
RoleEntity role = new()
{
Id = query.RoleId,
@@ -1,22 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRoles;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Queries.GetRoles.Fixtures;
/// <summary>
/// Fixture class for the <see cref="GetRolesQuery"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetRolesQueryFixture
{
/// <summary>
/// Creates a random valid query to get roles.
/// </summary>
/// <returns>The created query.</returns>
public GetRolesQuery CreateQuery()
{
return new GetRolesQuery();
}
}
@@ -6,7 +6,7 @@ using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRoles;
using Lumina.Application.UnitTests.Core.Admin.Authorization.Roles.Queries.GetRoles.Fixtures;
using Lumina.Application.Fixtures.Core.Admin.Authorization.Roles.Queries.GetRoles;
using Lumina.Contracts.Responses.Authorization;
using Lumina.Domain.Common.Primitives;
using NSubstitute;
@@ -58,7 +58,7 @@ public class GetRolesQueryHandlerTests
public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError()
{
// Arrange
GetRolesQuery query = _getRolesQueryFixture.CreateQuery();
GetRolesQuery query = _getRolesQueryFixture.Create();
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>())
.Returns(false);
@@ -75,7 +75,7 @@ public class GetRolesQueryHandlerTests
public async Task HandleAsync_WhenGetRolesFails_ShouldReturnError()
{
// Arrange
GetRolesQuery query = _getRolesQueryFixture.CreateQuery();
GetRolesQuery query = _getRolesQueryFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to get roles");
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>())
@@ -95,7 +95,7 @@ public class GetRolesQueryHandlerTests
public async Task HandleAsync_WhenAllOperationsSucceed_ShouldReturnRoles()
{
// Arrange
GetRolesQuery query = _getRolesQueryFixture.CreateQuery();
GetRolesQuery query = _getRolesQueryFixture.Create();
IEnumerable<RoleEntity> roles =
[
new RoleEntity { Id = Guid.NewGuid(), RoleName = "Admin" },
@@ -1,115 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
using Lumina.Domain.SharedKernel.Common.Enums.FileSystem;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Fixtures;
/// <summary>
/// Fixture class for the <see cref="Directory"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DirectoryFixture
{
private readonly Faker _faker;
/// <summary>
/// Initializes a new instance of the <see cref="DirectoryFixture"/> class.
/// </summary>
public DirectoryFixture()
{
_faker = new Faker();
}
/// <summary>
/// Creates a random valid <see cref="Directory"/>.
/// </summary>
/// <param name="path">Optional. The directory path. If not provided, a random path is generated.</param>
/// <param name="name">Optional. The directory name. If not provided, a random name is generated.</param>
/// <param name="dateCreated">Optional. The directory's creation date. If not provided, a random past date is generated.</param>
/// <param name="dateModified">Optional. The directory's modification date. If not provided, a recent date is generated.</param>
/// <param name="status">Optional. The directory's status. If not provided, a random status is assigned.</param>
/// <param name="childItems">Optional. A list of child items to be added to the directory.</param>
/// <returns>A newly created Directory instance.</returns>
/// <exception cref="InvalidOperationException">Thrown if the Directory creation fails.</exception>
public Directory CreateDirectory(
string? path = null,
string? name = null,
Optional<DateTime>? dateCreated = null,
Optional<DateTime>? dateModified = null,
FileSystemItemStatus? status = null,
List<FileSystemItem>? childItems = null)
{
path ??= _faker.System.FilePath();
name ??= _faker.System.FileName();
dateCreated ??= Optional<DateTime>.Some(_faker.Date.Past());
dateModified ??= Optional<DateTime>.Some(_faker.Date.Recent());
status ??= _faker.PickRandom<FileSystemItemStatus>();
Result<Directory> directoryResult = Directory.Create(path, name, dateCreated.Value, dateModified.Value, status.Value);
if (directoryResult.IsFailure)
throw new InvalidOperationException("Failed to create Directory: " + string.Join(", ", directoryResult.Errors));
Directory directory = directoryResult.Value;
if (childItems != null)
foreach (FileSystemItem item in childItems)
directory.AddItem(item);
return directory;
}
/// <summary>
/// Creates a list of <see cref="Directory"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<Directory> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => CreateDirectory())];
}
/// <summary>
/// Creates a list of nested <see cref="Directory"/> objects with a hierarchical structure.
/// </summary>
/// <param name="count">The number of top-level directories to create. Default is 3.</param>
/// <param name="maxDepth">The maximum depth of the directory hierarchy. Default is 3.</param>
/// <param name="maxChildrenPerDirectory">The maximum number of child items (files or directories) per directory. Default is 3.</param>
/// <returns>A list of <see cref="Directory"/> objects with nested structures.</returns>
public List<Directory> CreateManyNested(int count = 3, int maxDepth = 3, int maxChildrenPerDirectory = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => CreateNestedDirectory(1, maxDepth, maxChildrenPerDirectory))];
}
/// <summary>
/// Recursively creates a nested <see cref="Directory"/> structure.
/// </summary>
/// <param name="currentDepth">The current depth in the directory hierarchy.</param>
/// <param name="maxDepth">The maximum allowed depth for the directory hierarchy.</param>
/// <param name="maxChildrenPerDirectory">The maximum number of child items (files or directories) allowed per directory.</param>
/// <returns>A <see cref="Directory"/> object that may contain nested directories and files.</returns>
private Directory CreateNestedDirectory(int currentDepth, int maxDepth, int maxChildrenPerDirectory)
{
List<FileSystemItem> childItems = [];
// ensure we create at least one child if we haven't reached max depth
if (currentDepth < maxDepth)
{
// force at least 1 child, up to maxChildrenPerDirectory
int childCount = _faker.Random.Int(1, maxChildrenPerDirectory);
for (int i = 0; i < childCount; i++)
{
Directory childDirectory = CreateNestedDirectory(currentDepth + 1, maxDepth, maxChildrenPerDirectory);
Result<Updated> addResult = childDirectory.SetParent(childDirectory);
if (!addResult.IsFailure)
childItems.Add(childDirectory);
}
}
return CreateDirectory(childItems: childItems);
}
}
@@ -1,46 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.Responses.FileSystemManagement.Directories;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Fixtures;
/// <summary>
/// Fixture class for the <see cref="DirectoryResponse"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DirectoryResponseFixture
{
private readonly Faker _faker = new();
private readonly FileSystemItemDtoFixture _fileSystemItemModelFixture = new();
/// <summary>
/// Creates a random valid <see cref="DirectoryResponse"/>.
/// </summary>
/// <param name="itemCount">The number of children elements to create.</param>
/// <returns>The created <see cref="DirectoryResponse"/>.</returns>
public DirectoryResponse Create(int itemCount = 3)
{
return new DirectoryResponse(
_faker.System.FilePath(),
_faker.System.FileName(),
_faker.Date.Past(),
_faker.Date.Recent(),
_fileSystemItemModelFixture.CreateMany(itemCount)
);
}
/// <summary>
/// Creates a list of <see cref="DirectoryResponse"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <param name="itemCount">The number of children elemens to create for each element.</param>
/// <returns>The created list.</returns>
public List<DirectoryResponse> CreateMany(int count = 3, int itemCount = 3)
{
return Enumerable.Range(0, count).Select(_ => Create(itemCount)).ToList();
}
}
@@ -1,42 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.DTO.FileSystemManagement;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Fixtures;
/// <summary>
/// Fixture class for the <see cref="FileSystemItemDto"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class FileSystemItemDtoFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="FileSystemItemDto"/>.
/// </summary>
/// <returns>The created <see cref="FileSystemItemDto"/>.</returns>
public FileSystemItemDto Create()
{
return new FileSystemItemDto(
_faker.System.FilePath(),
_faker.System.FileName(),
_faker.Date.Past(),
_faker.Date.Recent()
);
}
/// <summary>
/// Creates a list of <see cref="FileSystemItemDto"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<FileSystemItemDto> CreateMany(int count = 3)
{
return Enumerable.Range(0, count).Select(_ => Create()).ToList();
}
}
@@ -1,58 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Domain.SharedKernel.Common.Enums.FileSystem;
using Lumina.Contracts.Responses.FileSystemManagement.Common;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Fixtures;
/// <summary>
/// Fixture class for the <see cref="FileSystemTreeNodeResponse"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class FileSystemTreeNodeResponseFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a single <see cref="FileSystemTreeNodeResponse"/> with a nested structure.
/// </summary>
/// <param name="currentDepth">The current depth in the tree structure. Default is 0 (root level).</param>
/// <param name="maxDepth">The maximum depth of the tree structure. Default is 2.</param>
/// <param name="maxChildren">The maximum number of children for each node. Default is 3.</param>
/// <returns>A <see cref="FileSystemTreeNodeResponse"/> with a nested structure.</returns>
public FileSystemTreeNodeResponse Create(int currentDepth = 0, int maxDepth = 2, int maxChildren = 3)
{
FileSystemTreeNodeResponse response = new()
{
Path = _faker.System.FilePath(),
Name = _faker.System.FileName(),
ItemType = FileSystemItemType.Directory,
IsExpanded = _faker.Random.Bool(),
ChildrenLoaded = true,
Children = []
};
if (currentDepth < maxDepth)
{
int childCount = _faker.Random.Int(1, maxChildren);
for (int i = 0; i < childCount; i++)
response.Children.Add(Create(currentDepth + 1, maxDepth, maxChildren));
}
return response;
}
/// <summary>
/// Creates a list of <see cref="FileSystemTreeNodeResponse"/> objects, each with a nested structure.
/// </summary>
/// <param name="count">The number of root-level nodes to create. Default is 2.</param>
/// <param name="maxDepth">The maximum depth of the tree structure for each root node. Default is 2.</param>
/// <param name="maxChildren">The maximum number of children for each node. Default is 3.</param>
/// <returns>A list of <see cref="FileSystemTreeNodeResponse"/> objects with nested structures.</returns>
public List<FileSystemTreeNodeResponse> CreateMany(int count = 2, int maxDepth = 2, int maxChildren = 3)
{
return Enumerable.Range(0, count).Select(_ => Create(0, maxDepth, maxChildren)).ToList();
}
}
@@ -1,30 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectories;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Queries.GetDirectories.Fixtures;
/// <summary>
/// Fixture class for the <see cref="GetDirectoriesQuery"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDirectoriesQueryFixture
{
/// <summary>
/// Creates a random valid query to get directories.
/// </summary>
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
/// <returns>The created query to get directories.</returns>
public static GetDirectoriesQuery CreateGetDirectoriesQuery(bool includeHiddenElements = false)
{
return new Faker<GetDirectoriesQuery>()
.CustomInstantiator(f => new GetDirectoriesQuery(
default!,
default
))
.RuleFor(x => x.Path, f => f.System.DirectoryPath())
.RuleFor(x => x.IncludeHiddenElements, f => includeHiddenElements);
}
}
@@ -3,12 +3,12 @@ using AutoFixture;
using AutoFixture.AutoNSubstitute;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectories;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Fixtures;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Queries.GetDirectories.Fixtures;
using Lumina.Application.Fixtures.Core.FileSystemManagement.Directories.Queries.GetDirectories;
using Lumina.Contracts.Responses.FileSystemManagement.Directories;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
using NSubstitute;
using System;
using System.Collections.Generic;
@@ -30,6 +30,7 @@ public class GetDirectoriesQueryHandlerTests
private readonly IDirectoryService _mockDirectoryService;
private readonly GetDirectoriesQueryHandler _sut;
private readonly DirectoryFixture _directoryFixture;
private readonly GetDirectoriesQueryFixture _getDirectoriesQueryFixture;
/// <summary>
/// Initializes a new instance of the <see cref="GetDirectoriesQueryHandlerTests"/> class.
@@ -43,13 +44,14 @@ public class GetDirectoriesQueryHandlerTests
.Returns([]);
_sut = new GetDirectoriesQueryHandler(_mockDirectoryService, mockValidator);
_directoryFixture = new DirectoryFixture();
_getDirectoriesQueryFixture = new GetDirectoriesQueryFixture();
}
[Fact]
public async Task HandleAsync_WhenCalledWithValidQueryWithoutFilesIncluded_ShouldReturnSuccessResult()
{
// Arrange
GetDirectoriesQuery getDirectoriesQuery = GetDirectoriesQueryFixture.CreateGetDirectoriesQuery(false);
GetDirectoriesQuery getDirectoriesQuery = _getDirectoriesQueryFixture.Create(includeHiddenElements: false);
IEnumerable<Directory> directories = _directoryFixture.CreateMany();
@@ -83,7 +85,7 @@ public class GetDirectoriesQueryHandlerTests
public async Task HandleAsync_WhenCalledWithValidQueryWithFilesIncluded_ShouldReturnSuccessResult()
{
// Arrange
GetDirectoriesQuery getDirectoriesQuery = GetDirectoriesQueryFixture.CreateGetDirectoriesQuery(true);
GetDirectoriesQuery getDirectoriesQuery = _getDirectoriesQueryFixture.Create(includeHiddenElements: true);
IEnumerable<Directory> directories = _directoryFixture.CreateMany();
@@ -117,7 +119,7 @@ public class GetDirectoriesQueryHandlerTests
public async Task HandleAsync_WhenDirectoryServiceReturnsError_ShouldReturnFailureResult()
{
// Arrange
GetDirectoriesQuery query = _fixture.Create<GetDirectoriesQuery>();
GetDirectoriesQuery query = _getDirectoriesQueryFixture.Create();
Error error = Error.Failure("DirectoryService.Error", "An error occurred");
_mockDirectoryService.GetSubdirectories(query.Path!, query.IncludeHiddenElements)
.Returns(error);
@@ -135,7 +137,7 @@ public class GetDirectoriesQueryHandlerTests
public async Task HandleAsync_WhenDirectoryServiceReturnsEmptyList_ShouldReturnEmptySuccessResult()
{
// Arrange
GetDirectoriesQuery query = _fixture.Create<GetDirectoriesQuery>();
GetDirectoriesQuery query = _getDirectoriesQueryFixture.Create();
Result<IEnumerable<Directory>> emptyList = Result.From(Enumerable.Empty<Directory>());
_mockDirectoryService.GetSubdirectories(query.Path!, query.IncludeHiddenElements)
.Returns(emptyList);
@@ -1,7 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectories;
using Lumina.Application.Fixtures.Core.FileSystemManagement.Directories.Queries.GetDirectories;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Queries.GetDirectories.Fixtures;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System.Collections.Generic;
@@ -17,6 +17,7 @@ namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Que
public class GetDirectoriesQueryValidatorTests
{
private readonly GetDirectoriesQueryValidator _validator;
private readonly GetDirectoriesQueryFixture _getDirectoriesQueryFixture;
/// <summary>
/// Initializes a new instance of the <see cref="GetDirectoriesQueryValidatorTests"/> class.
@@ -24,13 +25,14 @@ public class GetDirectoriesQueryValidatorTests
public GetDirectoriesQueryValidatorTests()
{
_validator = new GetDirectoriesQueryValidator();
_getDirectoriesQueryFixture = new GetDirectoriesQueryFixture();
}
[Fact]
public void Validate_WhenPathIsNull_ShouldHaveValidationError()
{
// Arrange
GetDirectoriesQuery query = GetDirectoriesQueryFixture.CreateGetDirectoriesQuery();
GetDirectoriesQuery query = _getDirectoriesQueryFixture.Create();
query = query with { Path = null! };
// Act
@@ -44,7 +46,7 @@ public class GetDirectoriesQueryValidatorTests
public void Validate_WhenPathIsEmpty_ShouldHaveValidationError()
{
// Arrange
GetDirectoriesQuery query = GetDirectoriesQueryFixture.CreateGetDirectoriesQuery();
GetDirectoriesQuery query = _getDirectoriesQueryFixture.Create();
query = query with { Path = string.Empty };
// Act
@@ -58,7 +60,7 @@ public class GetDirectoriesQueryValidatorTests
public void Validate_WhenPathIsWhitespace_ShouldHaveValidationError()
{
// Arrange
GetDirectoriesQuery query = GetDirectoriesQueryFixture.CreateGetDirectoriesQuery();
GetDirectoriesQuery query = _getDirectoriesQueryFixture.Create();
query = query with { Path = " " };
// Act
@@ -72,7 +74,7 @@ public class GetDirectoriesQueryValidatorTests
public void Validate_WhenPathIsValid_ShouldNotHaveValidationError()
{
// Arrange
GetDirectoriesQuery query = GetDirectoriesQueryFixture.CreateGetDirectoriesQuery();
GetDirectoriesQuery query = _getDirectoriesQueryFixture.Create();
query = query with { Path = "/valid/path" };
// Act
@@ -86,7 +88,7 @@ public class GetDirectoriesQueryValidatorTests
public void Validate_WhenIncludeHiddenElementsIsTrue_ShouldNotHaveValidationError()
{
// Arrange
GetDirectoriesQuery query = GetDirectoriesQueryFixture.CreateGetDirectoriesQuery();
GetDirectoriesQuery query = _getDirectoriesQueryFixture.Create();
query = query with { IncludeHiddenElements = true };
// Act
@@ -100,7 +102,7 @@ public class GetDirectoriesQueryValidatorTests
public void Validate_WhenIncludeHiddenElementsIsFalse_ShouldNotHaveValidationError()
{
// Arrange
GetDirectoriesQuery query = GetDirectoriesQueryFixture.CreateGetDirectoriesQuery();
GetDirectoriesQuery query = _getDirectoriesQueryFixture.Create();
query = query with { IncludeHiddenElements = false };
// Act
@@ -1,58 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Domain.SharedKernel.Common.Enums.FileSystem;
using Lumina.Contracts.Responses.FileSystemManagement.Common;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Drives.Queries.GetDrives.Fixtures;
/// <summary>
/// Fixture class for the <see cref="GetDrivesQueryFixture"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDrivesQueryFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a single <see cref="FileSystemTreeNodeResponse"/> with a nested structure.
/// </summary>
/// <param name="currentDepth">The current depth in the tree structure. Default is 0 (root level).</param>
/// <param name="maxDepth">The maximum depth of the tree structure. Default is 2.</param>
/// <param name="maxChildren">The maximum number of children for each node. Default is 3.</param>
/// <returns>A <see cref="FileSystemTreeNodeResponse"/> with a nested structure.</returns>
public FileSystemTreeNodeResponse Create(int currentDepth = 0, int maxDepth = 2, int maxChildren = 3)
{
FileSystemTreeNodeResponse response = new()
{
Path = _faker.System.FilePath(),
Name = _faker.System.FileName(),
ItemType = FileSystemItemType.Directory,
IsExpanded = _faker.Random.Bool(),
ChildrenLoaded = true,
Children = []
};
if (currentDepth < maxDepth)
{
int childCount = _faker.Random.Int(1, maxChildren);
for (int i = 0; i < childCount; i++)
response.Children.Add(Create(currentDepth + 1, maxDepth, maxChildren));
}
return response;
}
/// <summary>
/// Creates a list of <see cref="FileSystemTreeNodeResponse"/> objects, each with a nested structure.
/// </summary>
/// <param name="count">The number of root-level nodes to create. Default is 2.</param>
/// <param name="maxDepth">The maximum depth of the tree structure for each root node. Default is 2.</param>
/// <param name="maxChildren">The maximum number of children for each node. Default is 3.</param>
/// <returns>A list of <see cref="FileSystemTreeNodeResponse"/> objects with nested structures.</returns>
public List<FileSystemTreeNodeResponse> CreateMany(int count = 2, int maxDepth = 2, int maxChildren = 3)
{
return Enumerable.Range(0, count).Select(_ => Create(0, maxDepth, maxChildren)).ToList();
}
}
@@ -1,7 +1,6 @@
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using AutoFixture.AutoNSubstitute;
using Lumina.Application.Core.FileSystemManagement.Drives.Queries.GetDrives;
using Lumina.Application.Fixtures.Core.FileSystemManagement.Drives.Queries.GetDrives;
using Lumina.Contracts.Responses.FileSystemManagement.Common;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate;
@@ -24,17 +23,17 @@ namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Drives.Queries.
[ExcludeFromCodeCoverage]
public class GetDrivesQueryHandlerTests
{
private readonly IFixture _fixture;
private readonly IDriveService _mockDriveService;
private readonly GetDrivesQueryHandler _sut;
private readonly GetDrivesQueryFixture _getDrivesQueryFixture;
/// <summary>
/// Initializes a new instance of the <see cref="GetDrivesQueryHandlerTests"/> class.
/// </summary>
public GetDrivesQueryHandlerTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
_mockDriveService = Substitute.For<IDriveService>();
_getDrivesQueryFixture = new GetDrivesQueryFixture();
_sut = new GetDrivesQueryHandler(_mockDriveService);
}
@@ -42,7 +41,7 @@ public class GetDrivesQueryHandlerTests
public async Task HandleAsync_WhenCalled_ShouldReturnSuccessResult()
{
// Arrange
GetDrivesQuery getDrivesQuery = _fixture.Create<GetDrivesQuery>();
GetDrivesQuery getDrivesQuery = _getDrivesQueryFixture.Create();
IEnumerable<FileSystemItem> drives =
[
@@ -84,7 +83,7 @@ public class GetDrivesQueryHandlerTests
public async Task HandleAsync_WhenDriveServiceReturnsError_ShouldReturnFailureResult()
{
// Arrange
GetDrivesQuery query = _fixture.Create<GetDrivesQuery>();
GetDrivesQuery query = _getDrivesQueryFixture.Create();
Error error = Error.Failure("DriveService.Error", "An error occurred");
_mockDriveService.GetDrives()
.Returns(error);
@@ -102,7 +101,7 @@ public class GetDrivesQueryHandlerTests
public async Task HandleAsync_WhenDriveServiceReturnsEmptyList_ShouldReturnEmptySuccessResult()
{
// Arrange
GetDrivesQuery query = _fixture.Create<GetDrivesQuery>();
GetDrivesQuery query = _getDrivesQueryFixture.Create();
Result<IEnumerable<FileSystemItem>> emptyList = Result.From(Enumerable.Empty<FileSystemItem>());
_mockDriveService.GetDrives()
.Returns(emptyList);
@@ -1,33 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
using Lumina.Domain.SharedKernel.Common.Enums.FileSystem;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.FileSystem.Fixtures;
/// <summary>
/// Fixture class for the <see cref="UnixRootItem"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UnixRootItemFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="UnixRootItem"/>.
/// </summary>
/// <returns>The created <see cref="UnixRootItem"/>.</returns>
public UnixRootItem Create()
{
Result<UnixRootItem> unixRootItemResult = UnixRootItem.Create(
_faker.PickRandom<FileSystemItemStatus>()
);
if (unixRootItemResult.IsFailure)
throw new InvalidOperationException("Failed to create File: " + string.Join(", ", unixRootItemResult.Errors));
return unixRootItemResult.Value;
}
}
@@ -1,35 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
using Lumina.Domain.SharedKernel.Common.Enums.FileSystem;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.FileSystem.Fixtures;
/// <summary>
/// Fixture class for the <see cref="WindowsRootItem"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class WindowsRootItemFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="WindowsRootItem"/>.
/// </summary>
/// <returns>The created <see cref="WindowsRootItem"/>.</returns>
public WindowsRootItem Create()
{
Result<WindowsRootItem> windowsRootItemResult = WindowsRootItem.Create(
_faker.System.FilePath(),
_faker.System.FileName(),
_faker.PickRandom<FileSystemItemStatus>()
);
if (windowsRootItemResult.IsFailure)
throw new InvalidOperationException("Failed to create File: " + string.Join(", ", windowsRootItemResult.Errors));
return windowsRootItemResult.Value;
}
}
@@ -2,9 +2,10 @@
using AutoFixture;
using AutoFixture.AutoNSubstitute;
using Lumina.Application.Core.FileSystemManagement.FileSystem.Queries.GetFileSystem;
using Lumina.Domain.SharedKernel.Common.Enums.FileSystem;
using Lumina.Application.Fixtures.Core.FileSystemManagement.FileSystem.Queries.GetFileSystem;
using Lumina.Contracts.Responses.FileSystemManagement.FileSystem;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform;
using Lumina.Domain.SharedKernel.Common.Enums.FileSystem;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
@@ -24,6 +25,7 @@ public class GetFileSystemQueryHandlerTests
private readonly IPlatformContextManager _mockPlatformContextManager;
private readonly IPlatformContext _mockPlatformContext;
private readonly GetFileSystemQueryHandler _sut;
private readonly GetFileSystemQueryFixture _getFileSystemQueryFixture;
/// <summary>
/// Initializes a new instance of the <see cref="GetFileSystemQueryHandlerTests"/> class.
@@ -34,6 +36,7 @@ public class GetFileSystemQueryHandlerTests
_mockPlatformContextManager = Substitute.For<IPlatformContextManager>();
_mockPlatformContext = Substitute.For<IPlatformContext>();
_mockPlatformContextManager.GetCurrentContext().Returns(_mockPlatformContext);
_getFileSystemQueryFixture = new GetFileSystemQueryFixture();
_sut = new GetFileSystemQueryHandler(_mockPlatformContextManager);
}
@@ -43,7 +46,7 @@ public class GetFileSystemQueryHandlerTests
public async Task HandleAsync_WhenCalled_ShouldReturnCorrectFileSystemTypeResponse(PlatformType platformType)
{
// Arrange
GetFileSystemQuery query = _fixture.Create<GetFileSystemQuery>();
GetFileSystemQuery query = _getFileSystemQueryFixture.Create();
_mockPlatformContext.Platform.Returns(platformType);
// Act
@@ -59,7 +62,7 @@ public class GetFileSystemQueryHandlerTests
public async Task HandleAsync_WhenCalled_ShouldReturnValueTaskResult()
{
// Arrange
GetFileSystemQuery query = _fixture.Create<GetFileSystemQuery>();
GetFileSystemQuery query = _getFileSystemQueryFixture.Create();
_mockPlatformContext.Platform.Returns(PlatformType.Unix);
// Act
@@ -76,8 +79,8 @@ public class GetFileSystemQueryHandlerTests
public async Task HandleAsync_WhenCalled_ShouldNotDependOnQueryContent()
{
// Arrange
GetFileSystemQuery query1 = _fixture.Create<GetFileSystemQuery>();
GetFileSystemQuery query2 = _fixture.Create<GetFileSystemQuery>();
GetFileSystemQuery query1 = _getFileSystemQueryFixture.Create();
GetFileSystemQuery query2 = _getFileSystemQueryFixture.Create();
_mockPlatformContext.Platform.Returns(PlatformType.Windows);
// Act
@@ -93,7 +96,7 @@ public class GetFileSystemQueryHandlerTests
public async Task HandleAsync_WhenCalled_ShouldIgnoreCancellationToken()
{
// Arrange
GetFileSystemQuery query = _fixture.Create<GetFileSystemQuery>();
GetFileSystemQuery query = _getFileSystemQueryFixture.Create();
_mockPlatformContext.Platform.Returns(PlatformType.Unix);
CancellationToken cancellationToken = new(true);
@@ -1,81 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
using Lumina.Domain.SharedKernel.Common.Enums.FileSystem;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Fixtures;
/// <summary>
/// Fixture class for the <see cref="File"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class FileFixture
{
private readonly Faker _faker;
/// <summary>
/// Initializes a new instance of the <see cref="FileFixture"/> class.
/// </summary>
public FileFixture()
{
_faker = new Faker();
}
/// <summary>
/// Creates a random valid <see cref="File"/>.
/// </summary>
/// <returns>The created <see cref="File"/>.</returns>
public File CreateFile(
string? path = null,
string? name = null,
Optional<DateTime>? dateCreated = null,
Optional<DateTime>? dateModified = null,
long? size = null,
FileSystemItemStatus? status = null)
{
path ??= _faker.System.FilePath();
name ??= _faker.System.FileName();
dateCreated ??= Optional<DateTime>.Some(_faker.Date.Past());
dateModified ??= Optional<DateTime>.Some(_faker.Date.Recent());
size ??= _faker.Random.Long();
status ??= _faker.PickRandom<FileSystemItemStatus>();
Result<File> fileResult = File.Create(path, name, dateCreated.Value, dateModified.Value, size.Value, status.Value);
if (fileResult.IsFailure)
throw new InvalidOperationException("Failed to create File: " + string.Join(", ", fileResult.Errors));
return fileResult.Value;
}
/// <summary>
/// Creates a list of <see cref="File"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<File> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => CreateFile())];
}
/// <summary>
/// Creates a random valid <see cref="File"/>, without creationg and modification dates.
/// </summary>
/// <returns></returns>
public static File CreateFileWithoutDates()
{
return File.Create(
"/path/to/file_without_dates.txt",
"file_without_dates.txt",
Optional<DateTime>.None(),
Optional<DateTime>.None(),
2048,
FileSystemItemStatus.Accessible
).Value;
}
}
@@ -1,43 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.Responses.FileSystemManagement.Files;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Fixtures;
/// <summary>
/// Fixture class for the <see cref="FileResponse"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class FileResponseFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="FileResponse"/>.
/// </summary>
/// <returns>The created <see cref="FileResponse"/>.</returns>
public FileResponse Create()
{
return new FileResponse(
_faker.System.FilePath(),
_faker.System.FileName(),
_faker.Date.Past(),
_faker.Date.Recent(),
_faker.Random.Long()
);
}
/// <summary>
/// Creates a list of <see cref="FileResponse"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<FileResponse> CreateMany(int count = 3)
{
return Enumerable.Range(0, count).Select(_ => Create()).ToList();
}
}
@@ -1,30 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetFiles;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Queries.GetFiles.Fixtures;
/// <summary>
/// Fixture class for the <see cref="GetFilesQuery"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetFilesQueryFixture
{
/// <summary>
/// Creates a random valid query to get files.
/// </summary>
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
/// <returns>The created query to get files.</returns>
public static GetFilesQuery CreateGetFilesQuery(bool includeHiddenElements = false)
{
return new Faker<GetFilesQuery>()
.CustomInstantiator(f => new GetFilesQuery(
default!,
default
))
.RuleFor(x => x.Path, f => f.System.FilePath())
.RuleFor(x => x.IncludeHiddenElements, f => includeHiddenElements);
}
}
@@ -3,12 +3,12 @@ using AutoFixture;
using AutoFixture.AutoNSubstitute;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetFiles;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Fixtures;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Queries.GetFiles.Fixtures;
using Lumina.Application.Fixtures.Core.FileSystemManagement.Files.Queries.GetFiles;
using Lumina.Contracts.Responses.FileSystemManagement.Files;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
using NSubstitute;
using System;
using System.Collections.Generic;
@@ -30,6 +30,7 @@ public class GetFilesQueryHandlerTests
private readonly IFileService _mockFileService;
private readonly GetFilesQueryHandler _sut;
private readonly FileFixture _fileFixture;
private readonly GetFilesQueryFixture _getFilesQueryFixture;
/// <summary>
/// Initializes a new instance of the <see cref="GetFilesQueryHandlerTests"/> class.
@@ -43,13 +44,14 @@ public class GetFilesQueryHandlerTests
.Returns([]);
_sut = new GetFilesQueryHandler(_mockFileService, mockValidator);
_fileFixture = new FileFixture();
_getFilesQueryFixture = new GetFilesQueryFixture();
}
[Fact]
public async Task HandleAsync_WhenCalledWithValidQueryWithoutHiddenFiles_ShouldReturnSuccessResult()
{
// Arrange
GetFilesQuery getFilesQuery = GetFilesQueryFixture.CreateGetFilesQuery(false);
GetFilesQuery getFilesQuery = _getFilesQueryFixture.Create(includeHiddenElements: false);
IEnumerable<File> files = _fileFixture.CreateMany();
@@ -83,7 +85,7 @@ public class GetFilesQueryHandlerTests
public async Task HandleAsync_WhenCalledWithValidQueryWithHiddenFiles_ShouldReturnSuccessResult()
{
// Arrange
GetFilesQuery getFilesQuery = GetFilesQueryFixture.CreateGetFilesQuery(true);
GetFilesQuery getFilesQuery = _getFilesQueryFixture.Create(includeHiddenElements: true);
IEnumerable<File> files = _fileFixture.CreateMany();
@@ -117,7 +119,7 @@ public class GetFilesQueryHandlerTests
public async Task HandleAsync_WhenFileServiceReturnsError_ShouldReturnFailureResult()
{
// Arrange
GetFilesQuery query = _fixture.Create<GetFilesQuery>();
GetFilesQuery query = _getFilesQueryFixture.Create();
Error error = Error.Failure("FileService.Error", "An error occurred");
_mockFileService.GetFiles(query.Path!, query.IncludeHiddenElements)
.Returns(error);
@@ -135,7 +137,7 @@ public class GetFilesQueryHandlerTests
public async Task HandleAsync_WhenFileServiceReturnsEmptyList_ShouldReturnEmptySuccessResult()
{
// Arrange
GetFilesQuery query = _fixture.Create<GetFilesQuery>();
GetFilesQuery query = _getFilesQueryFixture.Create();
Result<IEnumerable<File>> emptyList = Result.From(Enumerable.Empty<File>());
_mockFileService.GetFiles(query.Path!, query.IncludeHiddenElements)
.Returns(emptyList);
@@ -1,7 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetFiles;
using Lumina.Application.Fixtures.Core.FileSystemManagement.Files.Queries.GetFiles;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Queries.GetFiles.Fixtures;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System.Collections.Generic;
@@ -17,6 +17,7 @@ namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Queries.G
public class GetFilesQueryValidatorTests
{
private readonly GetFilesQueryValidator _validator;
private readonly GetFilesQueryFixture _getFilesQueryFixture;
/// <summary>
/// Initializes a new instance of the <see cref="GetFilesQueryValidatorTests"/> class.
@@ -24,13 +25,14 @@ public class GetFilesQueryValidatorTests
public GetFilesQueryValidatorTests()
{
_validator = new GetFilesQueryValidator();
_getFilesQueryFixture = new GetFilesQueryFixture();
}
[Fact]
public void Validate_WhenPathIsNull_ShouldHaveValidationError()
{
// Arrange
GetFilesQuery query = GetFilesQueryFixture.CreateGetFilesQuery();
GetFilesQuery query = _getFilesQueryFixture.Create();
query = query with { Path = null! };
// Act
@@ -44,7 +46,7 @@ public class GetFilesQueryValidatorTests
public void Validate_WhenPathIsEmpty_ShouldHaveValidationError()
{
// Arrange
GetFilesQuery query = GetFilesQueryFixture.CreateGetFilesQuery();
GetFilesQuery query = _getFilesQueryFixture.Create();
query = query with { Path = string.Empty };
// Act
@@ -58,7 +60,7 @@ public class GetFilesQueryValidatorTests
public void Validate_WhenPathIsWhitespace_ShouldHaveValidationError()
{
// Arrange
GetFilesQuery query = GetFilesQueryFixture.CreateGetFilesQuery();
GetFilesQuery query = _getFilesQueryFixture.Create();
query = query with { Path = " " };
// Act
@@ -72,7 +74,7 @@ public class GetFilesQueryValidatorTests
public void Validate_WhenPathIsValid_ShouldNotHaveValidationError()
{
// Arrange
GetFilesQuery query = GetFilesQueryFixture.CreateGetFilesQuery();
GetFilesQuery query = _getFilesQueryFixture.Create();
query = query with { Path = "/valid/path" };
// Act
@@ -86,7 +88,7 @@ public class GetFilesQueryValidatorTests
public void Validate_WhenIncludeHiddenElementsIsTrue_ShouldNotHaveValidationError()
{
// Arrange
GetFilesQuery query = GetFilesQueryFixture.CreateGetFilesQuery();
GetFilesQuery query = _getFilesQueryFixture.Create();
query = query with { IncludeHiddenElements = true };
// Act
@@ -100,7 +102,7 @@ public class GetFilesQueryValidatorTests
public void Validate_WhenIncludeHiddenElementsIsFalse_ShouldNotHaveValidationError()
{
// Arrange
GetFilesQuery query = GetFilesQueryFixture.CreateGetFilesQuery();
GetFilesQuery query = _getFilesQueryFixture.Create();
query = query with { IncludeHiddenElements = false };
// Act
@@ -1,30 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetTreeFiles;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Queries.GetTreeFiles.Fixtures;
/// <summary>
/// Fixture class for the <see cref="GetTreeFilesQuery"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetTreeFilesQueryFixture
{
/// <summary>
/// Creates a random valid query to get files.
/// </summary>
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
/// <returns>The created query to get files.</returns>
public static GetTreeFilesQuery CreateGetFilesQuery(bool includeHiddenElements = false)
{
return new Faker<GetTreeFilesQuery>()
.CustomInstantiator(f => new GetTreeFilesQuery(
default!,
default
))
.RuleFor(x => x.Path, f => f.System.FilePath())
.RuleFor(x => x.IncludeHiddenElements, f => includeHiddenElements);
}
}
@@ -3,12 +3,12 @@ using AutoFixture;
using AutoFixture.AutoNSubstitute;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetTreeFiles;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Fixtures;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Queries.GetTreeFiles.Fixtures;
using Lumina.Application.Fixtures.Core.FileSystemManagement.Files.Queries.GetTreeFiles;
using Lumina.Contracts.Responses.FileSystemManagement.Common;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
using Lumina.Domain.SharedKernel.Common.Enums.FileSystem;
using NSubstitute;
using System.Collections.Generic;
@@ -30,6 +30,7 @@ public class GetTreeFilesQueryHandlerTests
private readonly IFileService _mockFileService;
private readonly GetTreeFilesQueryHandler _sut;
private readonly FileFixture _fileFixture;
private readonly GetTreeFilesQueryFixture _getTreeFilesQueryFixture;
/// <summary>
/// Initializes a new instance of the <see cref="GetTreeFilesQueryHandler"/> class.
@@ -43,13 +44,14 @@ public class GetTreeFilesQueryHandlerTests
.Returns([]);
_sut = new GetTreeFilesQueryHandler(_mockFileService, mockValidator);
_fileFixture = new FileFixture();
_getTreeFilesQueryFixture = new GetTreeFilesQueryFixture();
}
[Fact]
public async Task HandleAsync_WhenCalledWithValidQueryWithoutHiddenFiles_ShouldReturnSuccessResult()
{
// Arrange
GetTreeFilesQuery getFilesQuery = GetTreeFilesQueryFixture.CreateGetFilesQuery(false);
GetTreeFilesQuery getFilesQuery = _getTreeFilesQueryFixture.Create(includeHiddenElements: false);
IEnumerable<File> files = _fileFixture.CreateMany();
@@ -84,7 +86,7 @@ public class GetTreeFilesQueryHandlerTests
public async Task HandleAsync_WhenCalledWithValidQueryWithHiddenFiles_ShouldReturnSuccessResult()
{
// Arrange
GetTreeFilesQuery getFilesQuery = GetTreeFilesQueryFixture.CreateGetFilesQuery(true);
GetTreeFilesQuery getFilesQuery = _getTreeFilesQueryFixture.Create(includeHiddenElements: true);
IEnumerable<File> files = _fileFixture.CreateMany();
@@ -119,7 +121,7 @@ public class GetTreeFilesQueryHandlerTests
public async Task HandleAsync_WhenFileServiceReturnsError_ShouldReturnFailureResult()
{
// Arrange
GetTreeFilesQuery query = _fixture.Create<GetTreeFilesQuery>();
GetTreeFilesQuery query = _getTreeFilesQueryFixture.Create();
Error error = Error.Failure("FileService.Error", "An error occurred");
_mockFileService.GetFiles(query.Path!, query.IncludeHiddenElements)
.Returns(error);
@@ -137,7 +139,7 @@ public class GetTreeFilesQueryHandlerTests
public async Task HandleAsync_WhenFileServiceReturnsEmptyList_ShouldReturnEmptySuccessResult()
{
// Arrange
GetTreeFilesQuery query = _fixture.Create<GetTreeFilesQuery>();
GetTreeFilesQuery query = _getTreeFilesQueryFixture.Create();
Result<IEnumerable<File>> emptyList = Result.From(Enumerable.Empty<File>());
_mockFileService.GetFiles(query.Path!, query.IncludeHiddenElements)
.Returns(emptyList);
@@ -1,7 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetTreeFiles;
using Lumina.Application.Fixtures.Core.FileSystemManagement.Files.Queries.GetTreeFiles;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Queries.GetTreeFiles.Fixtures;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System.Collections.Generic;
@@ -17,6 +17,7 @@ namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Queries.G
public class GetTreeFilesQueryValidatorTests
{
private readonly GetTreeFilesQueryValidator _validator;
private readonly GetTreeFilesQueryFixture _getTreeFilesQueryFixture;
/// <summary>
/// Initializes a new instance of the <see cref="GetTreeFilesQueryValidatorTests"/> class.
@@ -24,13 +25,14 @@ public class GetTreeFilesQueryValidatorTests
public GetTreeFilesQueryValidatorTests()
{
_validator = new GetTreeFilesQueryValidator();
_getTreeFilesQueryFixture = new GetTreeFilesQueryFixture();
}
[Fact]
public void Validate_WhenPathIsNull_ShouldHaveValidationError()
{
// Arrange
GetTreeFilesQuery query = GetTreeFilesQueryFixture.CreateGetFilesQuery();
GetTreeFilesQuery query = _getTreeFilesQueryFixture.Create();
query = query with { Path = null! };
// Act
@@ -44,7 +46,7 @@ public class GetTreeFilesQueryValidatorTests
public void Validate_WhenPathIsEmpty_ShouldHaveValidationError()
{
// Arrange
GetTreeFilesQuery query = GetTreeFilesQueryFixture.CreateGetFilesQuery();
GetTreeFilesQuery query = _getTreeFilesQueryFixture.Create();
query = query with { Path = string.Empty };
// Act
@@ -58,7 +60,7 @@ public class GetTreeFilesQueryValidatorTests
public void Validate_WhenPathIsWhitespace_ShouldHaveValidationError()
{
// Arrange
GetTreeFilesQuery query = GetTreeFilesQueryFixture.CreateGetFilesQuery();
GetTreeFilesQuery query = _getTreeFilesQueryFixture.Create();
query = query with { Path = " " };
// Act
@@ -72,7 +74,7 @@ public class GetTreeFilesQueryValidatorTests
public void Validate_WhenPathIsValid_ShouldNotHaveValidationError()
{
// Arrange
GetTreeFilesQuery query = GetTreeFilesQueryFixture.CreateGetFilesQuery();
GetTreeFilesQuery query = _getTreeFilesQueryFixture.Create();
query = query with { Path = "/valid/path" };
// Act
@@ -86,7 +88,7 @@ public class GetTreeFilesQueryValidatorTests
public void Validate_WhenIncludeHiddenElementsIsTrue_ShouldNotHaveValidationError()
{
// Arrange
GetTreeFilesQuery query = GetTreeFilesQueryFixture.CreateGetFilesQuery();
GetTreeFilesQuery query = _getTreeFilesQueryFixture.Create();
query = query with { IncludeHiddenElements = true };
// Act
@@ -100,7 +102,7 @@ public class GetTreeFilesQueryValidatorTests
public void Validate_WhenIncludeHiddenElementsIsFalse_ShouldNotHaveValidationError()
{
// Arrange
GetTreeFilesQuery query = GetTreeFilesQueryFixture.CreateGetFilesQuery();
GetTreeFilesQuery query = _getTreeFilesQueryFixture.Create();
query = query with { IncludeHiddenElements = false };
// Act
@@ -1,42 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Fixtures;
/// <summary>
/// Fixture class for the <see cref="FileSystemPathId"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class FileSystemPathIdFixture
{
private readonly Faker _faker;
/// <summary>
/// Initializes a new instance of the <see cref="FileSystemPathIdFixture"/> class.
/// </summary>
public FileSystemPathIdFixture()
{
_faker = new Faker();
}
/// <summary>
/// Creates a random valid <see cref="FileSystemPathId"/>.
/// </summary>
/// <param name="path">The path of the file system path element.</param>
/// <returns>The created <see cref="FileSystemPathId"/>.</returns>
public FileSystemPathId CreateFileSystemPathId(string? path = null)
{
path ??= _faker.System.FilePath();
Result<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(path);
if (fileSystemPathIdResult.IsFailure)
throw new InvalidOperationException("Failed to create FileSystemPathId: " + string.Join(", ", fileSystemPathIdResult.Errors));
return fileSystemPathIdResult.Value;
}
}
@@ -1,29 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.FileSystemManagement.Paths.Commands.CombinePath;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.CombinePath.Fixtures;
/// <summary>
/// Fixture class for the <see cref="CombinePathCommand"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class CombinePathCommandFixture
{
/// <summary>
/// Creates a random valid command to combine paths.
/// </summary>
/// <returns>The created command.</returns>
public static CombinePathCommand CreateCombinePathCommand()
{
return new Faker<CombinePathCommand>()
.CustomInstantiator(f => new CombinePathCommand(
default!,
default!
))
.RuleFor(x => x.OriginalPath, f => f.System.FilePath())
.RuleFor(x => x.NewPath, f => f.System.FilePath());
}
}
@@ -1,27 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.FileSystemManagement.Paths.Commands.SplitPath;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.SplitPath.Fixtures;
/// <summary>
/// Fixture class for the <see cref="SplitPathCommand"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SplitPathCommandFixture
{
/// <summary>
/// Creates a random valid command for splitting paths.
/// </summary>
/// <returns>The created command.</returns>
public static SplitPathCommand CreateSplitPathCommand()
{
return new Faker<SplitPathCommand>()
.CustomInstantiator(f => new SplitPathCommand(
default!
))
.RuleFor(x => x.Path, f => f.System.FilePath());
}
}
@@ -1,58 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Fixtures;
/// <summary>
/// Fixture class for the <see cref="PathSegment"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PathSegmentFixture
{
private readonly Faker _faker;
/// <summary>
/// Initializes a new instance of the <see cref="PathSegmentFixture"/> class.
/// </summary>
public PathSegmentFixture()
{
_faker = new Faker();
}
/// <summary>
/// Creates a random valid <see cref="PathSegment"/>.
/// </summary>
/// <returns>The created <see cref="PathSegment"/>.</returns>
public PathSegment CreatePathSegment(
string? name = null,
bool? isDirectory = null,
bool? isDrive = null)
{
name ??= _faker.System.FileName();
isDirectory ??= true;
isDrive ??= false;
Result<PathSegment> pathResult = PathSegment.Create(name, isDirectory.Value, isDrive.Value);
if (pathResult.IsFailure)
throw new InvalidOperationException("Failed to create PathSegment: " + string.Join(", ", pathResult.Errors));
return pathResult.Value;
}
/// <summary>
/// Creates a list of <see cref="PathSegment"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<PathSegment> CreateMany(int count = 3)
{
return Enumerable.Range(0, count).Select(_ => CreatePathSegment()).ToList();
}
}
@@ -1,37 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Fixtures;
/// <summary>
/// Fixture class for the <see cref="PathSegmentResponse"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PathSegmentResponseFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="PathSegmentResponse"/>.
/// </summary>
/// <returns>The created <see cref="PathSegmentResponse"/>.</returns>
public PathSegmentResponse Create()
{
return new PathSegmentResponse(_faker.System.DirectoryPath());
}
/// <summary>
/// Creates a list of <see cref="PathSegmentResponse"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<PathSegmentResponse> CreateMany(int count = 3)
{
return Enumerable.Range(0, count).Select(_ => Create()).ToList();
}
}
@@ -1,37 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Fixtures;
/// <summary>
/// Fixture class for the <see cref="PathSeparatorResponse"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PathSeparatorResponseFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="PathSeparatorResponse"/>.
/// </summary>
/// <returns>The created <see cref="PathSeparatorResponse"/>.</returns>
public PathSeparatorResponse Create()
{
return new PathSeparatorResponse(_faker.System.DirectoryPath());
}
/// <summary>
/// Creates a list of <see cref="PathSeparatorResponse"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<PathSeparatorResponse> CreateMany(int count = 3)
{
return Enumerable.Range(0, count).Select(_ => Create()).ToList();
}
}
@@ -1,30 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.FileSystemManagement.Paths.Queries.CheckPathExists;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.CheckPathExists.Fixtures;
/// <summary>
/// Fixture class for the <see cref="CheckPathExistsQuery"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class CheckPathExistsQueryFixture
{
/// <summary>
/// Creates a random valid query to check if paths exist.
/// </summary>
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
/// <returns>The created query.</returns>
public static CheckPathExistsQuery CreateCheckPathExistsQuery(bool includeHiddenElements = true)
{
return new Faker<CheckPathExistsQuery>()
.CustomInstantiator(f => new CheckPathExistsQuery(
default!,
default
))
.RuleFor(x => x.Path, f => f.System.FilePath())
.RuleFor(x => x.IncludeHiddenElements, includeHiddenElements);
}
}
@@ -1,27 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathParent;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPathParent.Fixtures;
/// <summary>
/// Fixture class for the <see cref="GetPathParentQuery"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPathParentQueryFixture
{
/// <summary>
/// Creates a random valid query to check if paths exist.
/// </summary>
/// <returns>The created query.</returns>
public static GetPathParentQuery CreateGetPathParentQuery()
{
return new Faker<GetPathParentQuery>()
.CustomInstantiator(f => new GetPathParentQuery(
default!
))
.RuleFor(x => x.Path, f => f.System.FilePath());
}
}
@@ -1,27 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathRoot;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPathRoot.Fixtures;
/// <summary>
/// Fixture class for the <see cref="GetPathRootQuery"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPathRootQueryFixture
{
/// <summary>
/// Creates a random valid query to check if paths exist.
/// </summary>
/// <returns>The created query.</returns>
public static GetPathRootQuery CreateGetPathRootQuery()
{
return new Faker<GetPathRootQuery>()
.CustomInstantiator(f => new GetPathRootQuery(
default!
))
.RuleFor(x => x.Path, f => f.System.FilePath());
}
}
@@ -1,27 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.FileSystemManagement.Paths.Queries.ValidatePath;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.ValidatePath.Fixtures;
/// <summary>
/// Fixture class for the <see cref="ValidatePathQuery"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ValidatePathQueryFixure
{
/// <summary>
/// Creates a random valid query to check if paths exist.
/// </summary>
/// <returns>The created query.</returns>
public static ValidatePathQuery CreateValidatePathQuery()
{
return new Faker<ValidatePathQuery>()
.CustomInstantiator(f => new ValidatePathQuery(
default!
))
.RuleFor(x => x.Path, f => f.System.FilePath());
}
}
@@ -3,7 +3,7 @@ using AutoFixture;
using AutoFixture.AutoNSubstitute;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.FileSystemManagement.Paths.Commands.CombinePath;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.CombinePath.Fixtures;
using Lumina.Application.Fixtures.Core.FileSystemManagement.Paths.Commands.CombinePath;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
@@ -13,7 +13,7 @@ using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.CombinePath;
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Paths.Commands.CombinePath;
/// <summary>
/// Contains unit tests for the <see cref="CombinePathCommandHandler"/> class.
@@ -24,6 +24,7 @@ public class CombinePathCommandHandlerTests
private readonly IFixture _fixture;
private readonly IPathService _mockPathService;
private readonly CombinePathCommandHandler _sut;
private readonly CombinePathCommandFixture _combinePathCommandFixture;
/// <summary>
/// Initializes a new instance of the <see cref="CombinePathCommandHandlerTests"/> class.
@@ -36,13 +37,14 @@ public class CombinePathCommandHandlerTests
mockValidator.Validate(Arg.Any<CombinePathCommand>())
.Returns([]);
_sut = new CombinePathCommandHandler(_mockPathService, mockValidator);
_combinePathCommandFixture = new CombinePathCommandFixture();
}
[Fact]
public async Task HandleAsync_WhenCalledWithValidCommand_ShouldReturnSuccessResult()
{
// Arrange
CombinePathCommand combinePathCommand = CombinePathCommandFixture.CreateCombinePathCommand();
CombinePathCommand combinePathCommand = _combinePathCommandFixture.Create();
string combinedPath = System.IO.Path.Combine(combinePathCommand.OriginalPath!, combinePathCommand.NewPath!);
_mockPathService.CombinePath(combinePathCommand.OriginalPath!, combinePathCommand.NewPath!)
@@ -62,7 +64,7 @@ public class CombinePathCommandHandlerTests
public async Task HandleAsync_WhenPathServiceReturnsError_ShouldReturnFailureResult()
{
// Arrange
CombinePathCommand command = _fixture.Create<CombinePathCommand>();
CombinePathCommand command = _combinePathCommandFixture.Create();
Error error = Error.Failure("PathService.Error", "An error occurred");
_mockPathService.CombinePath(command.OriginalPath!, command.NewPath!)
.Returns(error);
@@ -80,7 +82,7 @@ public class CombinePathCommandHandlerTests
public async Task HandleAsync_WhenPathServiceReturnsEmptyString_ShouldReturnSuccessResultWithEmptyPath()
{
// Arrange
CombinePathCommand command = _fixture.Create<CombinePathCommand>();
CombinePathCommand command = _combinePathCommandFixture.Create();
_mockPathService.CombinePath(command.OriginalPath!, command.NewPath!)
.Returns(Result.From(string.Empty));
@@ -1,14 +1,14 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.FileSystemManagement.Paths.Commands.CombinePath;
using Lumina.Application.Fixtures.Core.FileSystemManagement.Paths.Commands.CombinePath;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.CombinePath.Fixtures;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.CombinePath;
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Paths.Commands.CombinePath;
/// <summary>
/// Contains unit tests for the <see cref="CombinePathCommandValidator"/> class.
@@ -17,6 +17,7 @@ namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.C
public class CombinePathCommandValidatorTests
{
private readonly CombinePathCommandValidator _validator;
private readonly CombinePathCommandFixture _combinePathCommandFixture;
/// <summary>
/// Initializes a new instance of the <see cref="CombinePathCommandValidatorTests"/> class.
@@ -24,13 +25,14 @@ public class CombinePathCommandValidatorTests
public CombinePathCommandValidatorTests()
{
_validator = new CombinePathCommandValidator();
_combinePathCommandFixture = new CombinePathCommandFixture();
}
[Fact]
public void Validate_WhenOriginalPathIsNull_ShouldHaveValidationError()
{
// Arrange
CombinePathCommand command = CombinePathCommandFixture.CreateCombinePathCommand();
CombinePathCommand command = _combinePathCommandFixture.Create();
command = command with { OriginalPath = null! };
// Act
@@ -44,7 +46,7 @@ public class CombinePathCommandValidatorTests
public void Validate_WhenOriginalPathIsEmpty_ShouldHaveValidationError()
{
// Arrange
CombinePathCommand command = CombinePathCommandFixture.CreateCombinePathCommand();
CombinePathCommand command = _combinePathCommandFixture.Create();
command = command with { OriginalPath = string.Empty };
// Act
@@ -58,7 +60,7 @@ public class CombinePathCommandValidatorTests
public void Validate_WhenOriginalPathIsWhitespace_ShouldHaveValidationError()
{
// Arrange
CombinePathCommand command = CombinePathCommandFixture.CreateCombinePathCommand();
CombinePathCommand command = _combinePathCommandFixture.Create();
command = command with { OriginalPath = " " };
// Act
@@ -72,7 +74,7 @@ public class CombinePathCommandValidatorTests
public void Validate_WhenNewPathIsNull_ShouldHaveValidationError()
{
// Arrange
CombinePathCommand command = CombinePathCommandFixture.CreateCombinePathCommand();
CombinePathCommand command = _combinePathCommandFixture.Create();
command = command with { NewPath = null! };
// Act
@@ -86,7 +88,7 @@ public class CombinePathCommandValidatorTests
public void Validate_WhenNewPathIsEmpty_ShouldHaveValidationError()
{
// Arrange
CombinePathCommand command = CombinePathCommandFixture.CreateCombinePathCommand();
CombinePathCommand command = _combinePathCommandFixture.Create();
command = command with { NewPath = string.Empty };
// Act
@@ -100,7 +102,7 @@ public class CombinePathCommandValidatorTests
public void Validate_WhenNewPathIsWhitespace_ShouldHaveValidationError()
{
// Arrange
CombinePathCommand command = CombinePathCommandFixture.CreateCombinePathCommand();
CombinePathCommand command = _combinePathCommandFixture.Create();
command = command with { NewPath = " " };
// Act
@@ -114,7 +116,7 @@ public class CombinePathCommandValidatorTests
public void Validate_WhenBothPathsAreValid_ShouldNotHaveValidationError()
{
// Arrange
CombinePathCommand command = CombinePathCommandFixture.CreateCombinePathCommand();
CombinePathCommand command = _combinePathCommandFixture.Create();
command = command with { OriginalPath = "/valid/path", NewPath = "new/segment" };
// Act
@@ -3,12 +3,12 @@ using AutoFixture;
using AutoFixture.AutoNSubstitute;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.FileSystemManagement.Paths.Commands.SplitPath;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.SplitPath.Fixtures;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Fixtures;
using Lumina.Application.Fixtures.Core.FileSystemManagement.Paths.Commands.SplitPath;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using NSubstitute;
using System;
using System.Collections.Generic;
@@ -18,7 +18,7 @@ using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.SplitPath;
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Paths.Commands.SplitPath;
/// <summary>
/// Contains unit tests for the <see cref="SplitPathCommandHandler"/> class.
@@ -30,6 +30,7 @@ public class SplitPathCommandHandlerTests
private readonly IPathService _mockPathService;
private readonly SplitPathCommandHandler _sut;
private readonly PathSegmentFixture _pathSegmentFixture;
private readonly SplitPathCommandFixture _splitPathCommandFixture;
/// <summary>
/// Initializes a new instance of the <see cref="SplitPathCommandHandlerTests"/> class.
@@ -43,13 +44,14 @@ public class SplitPathCommandHandlerTests
.Returns([]);
_sut = new SplitPathCommandHandler(_mockPathService, mockValidator);
_pathSegmentFixture = new PathSegmentFixture();
_splitPathCommandFixture = new SplitPathCommandFixture();
}
[Fact]
public async Task HandleAsync_WhenCalledWithValidCommand_ShouldReturnSuccessResult()
{
// Arrange
SplitPathCommand splitPathCommand = SplitPathCommandFixture.CreateSplitPathCommand();
SplitPathCommand splitPathCommand = _splitPathCommandFixture.Create();
IEnumerable<PathSegment> pathSegments = _pathSegmentFixture.CreateMany();
@@ -76,7 +78,7 @@ public class SplitPathCommandHandlerTests
public async Task HandleAsync_WhenPathServiceReturnsError_ShouldReturnFailureResult()
{
// Arrange
SplitPathCommand command = _fixture.Create<SplitPathCommand>();
SplitPathCommand command = _splitPathCommandFixture.Create();
Error error = Error.Failure("PathService.Error", "An error occurred");
_mockPathService.ParsePath(command.Path!)
.Returns(error);
@@ -94,7 +96,7 @@ public class SplitPathCommandHandlerTests
public async Task HandleAsync_WhenPathServiceReturnsEmptyList_ShouldReturnEmptySuccessResult()
{
// Arrange
SplitPathCommand command = _fixture.Create<SplitPathCommand>();
SplitPathCommand command = _splitPathCommandFixture.Create();
Result<IEnumerable<PathSegment>> emptyList = Result.From(Enumerable.Empty<PathSegment>());
_mockPathService.ParsePath(command.Path!)
.Returns(emptyList);
@@ -1,14 +1,14 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.FileSystemManagement.Paths.Commands.SplitPath;
using Lumina.Application.Fixtures.Core.FileSystemManagement.Paths.Commands.SplitPath;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.SplitPath.Fixtures;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.SplitPath;
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Paths.Commands.SplitPath;
/// <summary>
/// Contains unit tests for the <see cref="SplitPathCommandValidator"/> class.
@@ -17,6 +17,7 @@ namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.S
public class SplitPathCommandValidatorTests
{
private readonly SplitPathCommandValidator _validator;
private readonly SplitPathCommandFixture _splitPathCommandFixture;
/// <summary>
/// Initializes a new instance of the <see cref="SplitPathCommandValidatorTests"/> class.
@@ -24,13 +25,14 @@ public class SplitPathCommandValidatorTests
public SplitPathCommandValidatorTests()
{
_validator = new SplitPathCommandValidator();
_splitPathCommandFixture = new SplitPathCommandFixture();
}
[Fact]
public void Validate_WhenPathIsNull_ShouldHaveValidationError()
{
// Arrange
SplitPathCommand command = SplitPathCommandFixture.CreateSplitPathCommand();
SplitPathCommand command = _splitPathCommandFixture.Create();
command = command with { Path = null! };
// Act
@@ -44,7 +46,7 @@ public class SplitPathCommandValidatorTests
public void Validate_WhenPathIsEmpty_ShouldHaveValidationError()
{
// Arrange
SplitPathCommand command = SplitPathCommandFixture.CreateSplitPathCommand();
SplitPathCommand command = _splitPathCommandFixture.Create();
command = command with { Path = string.Empty };
// Act
@@ -58,7 +60,7 @@ public class SplitPathCommandValidatorTests
public void Validate_WhenPathIsWhitespace_ShouldHaveValidationError()
{
// Arrange
SplitPathCommand command = SplitPathCommandFixture.CreateSplitPathCommand();
SplitPathCommand command = _splitPathCommandFixture.Create();
command = command with { Path = " " };
// Act
@@ -72,7 +74,7 @@ public class SplitPathCommandValidatorTests
public void Validate_WhenPathIsValid_ShouldNotHaveValidationError()
{
// Arrange
SplitPathCommand command = SplitPathCommandFixture.CreateSplitPathCommand();
SplitPathCommand command = _splitPathCommandFixture.Create();
command = command with { Path = "/valid/path" };
// Act
@@ -1,7 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.FileSystemManagement.Paths.Queries.CheckPathExists;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.CheckPathExists.Fixtures;
using Lumina.Application.Fixtures.Core.FileSystemManagement.Paths.Queries.CheckPathExists;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
@@ -11,7 +11,7 @@ using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.CheckPathExists;
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Paths.Queries.CheckPathExists;
/// <summary>
/// Contains unit tests for the <see cref="CheckPathExistsQueryHandler"/> class.
@@ -21,6 +21,7 @@ public class CheckPathExistsQueryHandlerTests
{
private readonly IPathService _mockPathService;
private readonly CheckPathExistsQueryHandler _sut;
private readonly CheckPathExistsQueryFixture _checkPathExistsQueryFixture;
/// <summary>
/// Initializes a new instance of the <see cref="CheckPathExistsQueryHandlerTests"/> class.
@@ -28,6 +29,7 @@ public class CheckPathExistsQueryHandlerTests
public CheckPathExistsQueryHandlerTests()
{
_mockPathService = Substitute.For<IPathService>();
_checkPathExistsQueryFixture = new CheckPathExistsQueryFixture();
IValidator<CheckPathExistsQuery> mockValidator = Substitute.For<IValidator<CheckPathExistsQuery>>();
mockValidator.Validate(Arg.Any<CheckPathExistsQuery>())
.Returns([]);
@@ -38,7 +40,7 @@ public class CheckPathExistsQueryHandlerTests
public async Task HandleAsync_WhenPathExistsAndIsNotHidden_ShouldReturnTrueResponse()
{
// Arrange
CheckPathExistsQuery query = CheckPathExistsQueryFixture.CreateCheckPathExistsQuery();
CheckPathExistsQuery query = _checkPathExistsQueryFixture.Create();
_mockPathService.Exists(query.Path!).Returns(true);
// Act
@@ -54,7 +56,7 @@ public class CheckPathExistsQueryHandlerTests
public async Task HandleAsync_WhenPathExistsAndIsHiddenAndIncludeHiddenElementsIsTrue_ShouldReturnTrueResponse()
{
// Arrange
CheckPathExistsQuery query = CheckPathExistsQueryFixture.CreateCheckPathExistsQuery(true);
CheckPathExistsQuery query = _checkPathExistsQueryFixture.Create(includeHiddenElements: true);
_mockPathService.Exists(query.Path!).Returns(true);
// Act
@@ -70,7 +72,7 @@ public class CheckPathExistsQueryHandlerTests
public async Task HandleAsync_WhenPathExistsAndIsHiddenAndIncludeHiddenElementsIsFalse_ShouldReturnFalseResponse()
{
// Arrange
CheckPathExistsQuery query = CheckPathExistsQueryFixture.CreateCheckPathExistsQuery(false);
CheckPathExistsQuery query = _checkPathExistsQueryFixture.Create(includeHiddenElements: false);
_mockPathService.Exists(query.Path!, false).Returns(false);
// Act
@@ -86,7 +88,7 @@ public class CheckPathExistsQueryHandlerTests
public async Task HandleAsync_WhenPathDoesNotExist_ShouldReturnFalseResponse()
{
// Arrange
CheckPathExistsQuery query = CheckPathExistsQueryFixture.CreateCheckPathExistsQuery();
CheckPathExistsQuery query = _checkPathExistsQueryFixture.Create();
_mockPathService.Exists(query.Path!).Returns(false);
// Act
@@ -118,7 +120,7 @@ public class CheckPathExistsQueryHandlerTests
public async Task HandleAsync_WhenCancellationRequested_ShouldStillCompleteOperation()
{
// Arrange
CheckPathExistsQuery query = CheckPathExistsQueryFixture.CreateCheckPathExistsQuery();
CheckPathExistsQuery query = _checkPathExistsQueryFixture.Create();
_mockPathService.Exists(query.Path!).Returns(true);
CancellationToken cancellationToken = new(true);
@@ -1,14 +1,14 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.FileSystemManagement.Paths.Queries.CheckPathExists;
using Lumina.Application.Fixtures.Core.FileSystemManagement.Paths.Queries.CheckPathExists;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.CheckPathExists.Fixtures;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.CheckPathExists;
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Paths.Queries.CheckPathExists;
/// <summary>
/// Contains unit tests for the <see cref="CheckPathExistsQueryValidator"/> class.
@@ -17,6 +17,7 @@ namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.Ch
public class CheckPathExistsQueryValidatorTests
{
private readonly CheckPathExistsQueryValidator _validator;
private readonly CheckPathExistsQueryFixture _checkPathExistsQueryFixture;
/// <summary>
/// Initializes a new instance of the <see cref="CheckPathExistsQueryValidatorTests"/> class.
@@ -24,13 +25,14 @@ public class CheckPathExistsQueryValidatorTests
public CheckPathExistsQueryValidatorTests()
{
_validator = new CheckPathExistsQueryValidator();
_checkPathExistsQueryFixture = new CheckPathExistsQueryFixture();
}
[Fact]
public void Validate_WhenPathIsNull_ShouldHaveValidationError()
{
// Arrange
CheckPathExistsQuery query = CheckPathExistsQueryFixture.CreateCheckPathExistsQuery();
CheckPathExistsQuery query = _checkPathExistsQueryFixture.Create();
query = query with { Path = null! };
// Act
@@ -44,7 +46,7 @@ public class CheckPathExistsQueryValidatorTests
public void Validate_WhenPathIsEmpty_ShouldHaveValidationError()
{
// Arrange
CheckPathExistsQuery query = CheckPathExistsQueryFixture.CreateCheckPathExistsQuery();
CheckPathExistsQuery query = _checkPathExistsQueryFixture.Create();
query = query with { Path = string.Empty };
// Act
@@ -58,7 +60,7 @@ public class CheckPathExistsQueryValidatorTests
public void Validate_WhenPathIsWhitespace_ShouldHaveValidationError()
{
// Arrange
CheckPathExistsQuery query = CheckPathExistsQueryFixture.CreateCheckPathExistsQuery();
CheckPathExistsQuery query = _checkPathExistsQueryFixture.Create();
query = query with { Path = " " };
// Act
@@ -72,7 +74,7 @@ public class CheckPathExistsQueryValidatorTests
public void Validate_WhenPathIsValid_ShouldNotHaveValidationError()
{
// Arrange
CheckPathExistsQuery query = CheckPathExistsQueryFixture.CreateCheckPathExistsQuery();
CheckPathExistsQuery query = _checkPathExistsQueryFixture.Create();
query = query with { Path = "/valid/path" };
// Act
@@ -3,12 +3,12 @@ using AutoFixture;
using AutoFixture.AutoNSubstitute;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathParent;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Fixtures;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPathParent.Fixtures;
using Lumina.Application.Fixtures.Core.FileSystemManagement.Paths.Queries.GetPathParent;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using NSubstitute;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
@@ -17,7 +17,7 @@ using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPathParent;
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Paths.Queries.GetPathParent;
/// <summary>
/// Contains unit tests for the <see cref="GetPathParentQueryHandler"/> class.
@@ -29,6 +29,7 @@ public class GetPathParentQueryHandlerTests
private readonly IPathService _mockPathService;
private readonly GetPathParentQueryHandler _sut;
private readonly PathSegmentFixture _pathSegmentFixture;
private readonly GetPathParentQueryFixture _getPathParentQueryFixture;
public GetPathParentQueryHandlerTests()
{
@@ -39,13 +40,14 @@ public class GetPathParentQueryHandlerTests
.Returns([]);
_sut = new GetPathParentQueryHandler(_mockPathService, mockValidator);
_pathSegmentFixture = new PathSegmentFixture();
_getPathParentQueryFixture = new GetPathParentQueryFixture();
}
[Fact]
public async Task HandleAsync_WhenCalledWithValidQuery_ShouldReturnSuccessResult()
{
// Arrange
GetPathParentQuery query = GetPathParentQueryFixture.CreateGetPathParentQuery();
GetPathParentQuery query = _getPathParentQueryFixture.Create();
IEnumerable<PathSegment> pathSegments = _pathSegmentFixture.CreateMany();
@@ -69,7 +71,7 @@ public class GetPathParentQueryHandlerTests
public async Task HandleAsync_WhenPathServiceReturnsError_ShouldReturnFailureResult()
{
// Arrange
GetPathParentQuery query = _fixture.Create<GetPathParentQuery>();
GetPathParentQuery query = _getPathParentQueryFixture.Create();
Error error = Error.Failure("PathService.Error", "An error occurred");
_mockPathService.GoUpOneLevel(query.Path!)
.Returns(error);
@@ -87,7 +89,7 @@ public class GetPathParentQueryHandlerTests
public async Task HandleAsync_WhenPathServiceReturnsEmptyList_ShouldReturnEmptySuccessResult()
{
// Arrange
GetPathParentQuery query = _fixture.Create<GetPathParentQuery>();
GetPathParentQuery query = _getPathParentQueryFixture.Create();
Result<IEnumerable<PathSegment>> emptyList = Result.From(Enumerable.Empty<PathSegment>());
_mockPathService.GoUpOneLevel(query.Path!)
.Returns(emptyList);
@@ -1,14 +1,14 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathParent;
using Lumina.Application.Fixtures.Core.FileSystemManagement.Paths.Queries.GetPathParent;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPathParent.Fixtures;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPathParent;
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Paths.Queries.GetPathParent;
/// <summary>
/// Contains unit tests for the <see cref="GetPathParentQueryValidator"/> class.
@@ -17,6 +17,7 @@ namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.Ge
public class GetPathParentQueryValidatorTests
{
private readonly GetPathParentQueryValidator _validator;
private readonly GetPathParentQueryFixture _getPathParentQueryFixture;
/// <summary>
/// Initializes a new instance of the <see cref="GetPathParentQueryValidatorTests"/> class.
@@ -24,13 +25,14 @@ public class GetPathParentQueryValidatorTests
public GetPathParentQueryValidatorTests()
{
_validator = new GetPathParentQueryValidator();
_getPathParentQueryFixture = new GetPathParentQueryFixture();
}
[Fact]
public void Validate_WhenPathIsNull_ShouldHaveValidationError()
{
// Arrange
GetPathParentQuery query = GetPathParentQueryFixture.CreateGetPathParentQuery();
GetPathParentQuery query = _getPathParentQueryFixture.Create();
query = query with { Path = null! };
// Act
@@ -44,7 +46,7 @@ public class GetPathParentQueryValidatorTests
public void Validate_WhenPathIsEmpty_ShouldHaveValidationError()
{
// Arrange
GetPathParentQuery query = GetPathParentQueryFixture.CreateGetPathParentQuery();
GetPathParentQuery query = _getPathParentQueryFixture.Create();
query = query with { Path = string.Empty };
// Act
@@ -58,7 +60,7 @@ public class GetPathParentQueryValidatorTests
public void Validate_WhenPathIsWhitespace_ShouldHaveValidationError()
{
// Arrange
GetPathParentQuery query = GetPathParentQueryFixture.CreateGetPathParentQuery();
GetPathParentQuery query = _getPathParentQueryFixture.Create();
query = query with { Path = " " };
// Act
@@ -72,7 +74,7 @@ public class GetPathParentQueryValidatorTests
public void Validate_WhenPathIsValid_ShouldNotHaveValidationError()
{
// Arrange
GetPathParentQuery query = GetPathParentQueryFixture.CreateGetPathParentQuery();
GetPathParentQuery query = _getPathParentQueryFixture.Create();
query = query with { Path = "/valid/path" };
// Act
@@ -1,19 +1,19 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathRoot;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Fixtures;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPathRoot.Fixtures;
using Lumina.Application.Fixtures.Core.FileSystemManagement.Paths.Queries.GetPathRoot;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using NSubstitute;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPathRoot;
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Paths.Queries.GetPathRoot;
/// <summary>
/// Contains unit tests for the <see cref="GetPathRootQueryHandler"/> class.
@@ -24,6 +24,7 @@ public class GetPathRootQueryHandlerTests
private readonly IPathService _mockPathService;
private readonly GetPathRootQueryHandler _sut;
private readonly PathSegmentFixture _pathSegmentFixture;
private readonly GetPathRootQueryFixture _getPathRootQueryFixture;
/// <summary>
/// Initializes a new instance of the <see cref="GetPathRootQueryHandlerTests"/> class.
@@ -31,6 +32,7 @@ public class GetPathRootQueryHandlerTests
public GetPathRootQueryHandlerTests()
{
_mockPathService = Substitute.For<IPathService>();
_getPathRootQueryFixture = new GetPathRootQueryFixture();
IValidator<GetPathRootQuery> mockValidator = Substitute.For<IValidator<GetPathRootQuery>>();
mockValidator.Validate(Arg.Any<GetPathRootQuery>())
.Returns([]);
@@ -42,8 +44,8 @@ public class GetPathRootQueryHandlerTests
public async Task HandleAsync_WhenCalledWithValidQuery_ShouldReturnSuccessResult()
{
// Arrange
GetPathRootQuery query = GetPathRootQueryFixture.CreateGetPathRootQuery();
PathSegment pathSegment = _pathSegmentFixture.CreatePathSegment(isDrive: true);
GetPathRootQuery query = _getPathRootQueryFixture.Create();
PathSegment pathSegment = _pathSegmentFixture.Create(isDrive: true);
_mockPathService.GetPathRoot(query.Path!)
.Returns(Result.From(pathSegment));
@@ -62,7 +64,7 @@ public class GetPathRootQueryHandlerTests
public async Task HandleAsync_WhenPathServiceReturnsError_ShouldReturnFailureResult()
{
// Arrange
GetPathRootQuery query = GetPathRootQueryFixture.CreateGetPathRootQuery();
GetPathRootQuery query = _getPathRootQueryFixture.Create();
Error error = Error.Failure("PathService.Error", "An error occurred");
_mockPathService.GetPathRoot(query.Path!)
.Returns(error);
@@ -80,8 +82,8 @@ public class GetPathRootQueryHandlerTests
public async Task HandleAsync_WhenPathServiceReturnsRootPathSegment_ShouldReturnRootSuccessResult()
{
// Arrange
GetPathRootQuery query = GetPathRootQueryFixture.CreateGetPathRootQuery();
PathSegment rootPathSegment = _pathSegmentFixture.CreatePathSegment(name: "/", isDirectory: true, isDrive: true);
GetPathRootQuery query = _getPathRootQueryFixture.Create();
PathSegment rootPathSegment = _pathSegmentFixture.Create(name: "/", isDirectory: true, isDrive: true);
_mockPathService.GetPathRoot(query.Path!)
.Returns(Result.From(rootPathSegment));
@@ -1,14 +1,14 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathRoot;
using Lumina.Application.Fixtures.Core.FileSystemManagement.Paths.Queries.GetPathRoot;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPathRoot.Fixtures;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPathRoot;
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Paths.Queries.GetPathRoot;
/// <summary>
/// Contains unit tests for the <see cref="GetPathRootQueryValidator"/> class.
@@ -17,6 +17,7 @@ namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.Ge
public class GetPathRootQueryValidatorTests
{
private readonly GetPathRootQueryValidator _validator;
private readonly GetPathRootQueryFixture _getPathRootQueryFixture;
/// <summary>
/// Initializes a new instance of the <see cref="GetPathRootQueryValidatorTests"/> class.
@@ -24,13 +25,14 @@ public class GetPathRootQueryValidatorTests
public GetPathRootQueryValidatorTests()
{
_validator = new GetPathRootQueryValidator();
_getPathRootQueryFixture = new GetPathRootQueryFixture();
}
[Fact]
public void Validate_WhenPathIsNull_ShouldHaveValidationError()
{
// Arrange
GetPathRootQuery query = GetPathRootQueryFixture.CreateGetPathRootQuery();
GetPathRootQuery query = _getPathRootQueryFixture.Create();
query = query with { Path = null! };
// Act
@@ -44,7 +46,7 @@ public class GetPathRootQueryValidatorTests
public void Validate_WhenPathIsEmpty_ShouldHaveValidationError()
{
// Arrange
GetPathRootQuery query = GetPathRootQueryFixture.CreateGetPathRootQuery();
GetPathRootQuery query = _getPathRootQueryFixture.Create();
query = query with { Path = string.Empty };
// Act
@@ -58,7 +60,7 @@ public class GetPathRootQueryValidatorTests
public void Validate_WhenPathIsWhitespace_ShouldHaveValidationError()
{
// Arrange
GetPathRootQuery query = GetPathRootQueryFixture.CreateGetPathRootQuery();
GetPathRootQuery query = _getPathRootQueryFixture.Create();
query = query with { Path = " " };
// Act
@@ -72,7 +74,7 @@ public class GetPathRootQueryValidatorTests
public void Validate_WhenPathIsValid_ShouldNotHaveValidationError()
{
// Arrange
GetPathRootQuery query = GetPathRootQueryFixture.CreateGetPathRootQuery();
GetPathRootQuery query = _getPathRootQueryFixture.Create();
query = query with { Path = "/valid/path" };
// Act
@@ -9,7 +9,7 @@ using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.GetPathSeparator;
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Paths.Queries.GetPathSeparator;
/// <summary>
/// Contains unit tests for the <see cref="GetPathSeparatorQueryHandler"/> class.
@@ -1,7 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.FileSystemManagement.Paths.Queries.ValidatePath;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.ValidatePath.Fixtures;
using Lumina.Application.Fixtures.Core.FileSystemManagement.Paths.Queries.ValidatePath;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
@@ -12,7 +12,7 @@ using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.ValidatePath;
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Paths.Queries.ValidatePath;
/// <summary>
/// Contains unit tests for the <see cref="ValidatePathQueryHandler"/> class.
@@ -23,6 +23,7 @@ public class ValidatePathQueryHandlerTests
private readonly IPathService _mockPathService;
private readonly IValidator<ValidatePathQuery> _mockValidator;
private readonly ValidatePathQueryHandler _sut;
private readonly ValidatePathQueryFixture _validatePathQueryFixture;
/// <summary>
/// Initializes a new instance of the <see cref="ValidatePathQueryHandlerTests"/> class.
@@ -31,6 +32,7 @@ public class ValidatePathQueryHandlerTests
{
_mockPathService = Substitute.For<IPathService>();
_mockValidator = Substitute.For<IValidator<ValidatePathQuery>>();
_validatePathQueryFixture = new ValidatePathQueryFixture();
_mockValidator.Validate(Arg.Any<ValidatePathQuery>())
.Returns([]);
_sut = new ValidatePathQueryHandler(_mockPathService, _mockValidator);
@@ -40,7 +42,7 @@ public class ValidatePathQueryHandlerTests
public async Task HandleAsync_WhenCalledWithValidPath_ShouldReturnTrueResponse()
{
// Arrange
ValidatePathQuery query = ValidatePathQueryFixure.CreateValidatePathQuery();
ValidatePathQuery query = _validatePathQueryFixture.Create();
_mockPathService.IsValidPath(query.Path!).Returns(true);
// Act
@@ -56,7 +58,7 @@ public class ValidatePathQueryHandlerTests
public async Task HandleAsync_WhenCalledWithInvalidPath_ShouldReturnFalseResponse()
{
// Arrange
ValidatePathQuery query = ValidatePathQueryFixure.CreateValidatePathQuery();
ValidatePathQuery query = _validatePathQueryFixture.Create();
_mockPathService.IsValidPath(query.Path!).Returns(false);
// Act
@@ -104,7 +106,7 @@ public class ValidatePathQueryHandlerTests
public async Task HandleAsync_WhenValidatorReturnsErrors_ShouldReturnValidationErrorsWithoutCallingPathService()
{
// Arrange
ValidatePathQuery query = ValidatePathQueryFixure.CreateValidatePathQuery();
ValidatePathQuery query = _validatePathQueryFixture.Create();
_mockValidator.Validate(query)
.Returns([Errors.FileSystemManagement.PathCannotBeEmpty]);
@@ -1,14 +1,14 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.FileSystemManagement.Paths.Queries.ValidatePath;
using Lumina.Application.Fixtures.Core.FileSystemManagement.Paths.Queries.ValidatePath;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.ValidatePath.Fixtures;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.ValidatePath;
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Paths.Queries.ValidatePath;
/// <summary>
/// Contains unit tests for the <see cref="ValidatePathQueryValidator"/> class.
@@ -17,6 +17,7 @@ namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.Va
public class ValidatePathQueryValidatorTests
{
private readonly ValidatePathQueryValidator _validator;
private readonly ValidatePathQueryFixture _validatePathQueryFixture;
/// <summary>
/// Initializes a new instance of the <see cref="ValidatePathQueryValidatorTests"/> class.
@@ -24,13 +25,14 @@ public class ValidatePathQueryValidatorTests
public ValidatePathQueryValidatorTests()
{
_validator = new ValidatePathQueryValidator();
_validatePathQueryFixture = new ValidatePathQueryFixture();
}
[Fact]
public void Validate_WhenPathIsNull_ShouldHaveValidationError()
{
// Arrange
ValidatePathQuery query = ValidatePathQueryFixure.CreateValidatePathQuery();
ValidatePathQuery query = _validatePathQueryFixture.Create();
query = query with { Path = null! };
// Act
@@ -44,7 +46,7 @@ public class ValidatePathQueryValidatorTests
public void Validate_WhenPathIsEmpty_ShouldHaveValidationError()
{
// Arrange
ValidatePathQuery query = ValidatePathQueryFixure.CreateValidatePathQuery();
ValidatePathQuery query = _validatePathQueryFixture.Create();
query = query with { Path = string.Empty };
// Act
@@ -58,7 +60,7 @@ public class ValidatePathQueryValidatorTests
public void Validate_WhenPathIsWhitespace_ShouldHaveValidationError()
{
// Arrange
ValidatePathQuery query = ValidatePathQueryFixure.CreateValidatePathQuery();
ValidatePathQuery query = _validatePathQueryFixture.Create();
query = query with { Path = " " };
// Act
@@ -72,7 +74,7 @@ public class ValidatePathQueryValidatorTests
public void Validate_WhenPathIsValid_ShouldNotHaveValidationError()
{
// Arrange
ValidatePathQuery query = ValidatePathQueryFixure.CreateValidatePathQuery();
ValidatePathQuery query = _validatePathQueryFixture.Create();
query = query with { Path = "/valid/path" };
// Act
@@ -1,30 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary;
using Lumina.Contracts.Responses.FileSystemManagement.Thumbnails;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Thumbnails.Fixtures;
/// <summary>
/// Fixture class for the <see cref="ThumbnailResponse"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ThumbnailResponseFixture
{
/// <summary>
/// Creates a random valid query to get a thumbnail.
/// </summary>
/// <returns>The created query.</returns>
public static ThumbnailResponse CreateThumbnailResponse()
{
return new Faker<ThumbnailResponse>()
.CustomInstantiator(f => new ThumbnailResponse(
default,
default!
))
.RuleFor(x => x.Type, f => f.PickRandom<ImageType>())
.RuleFor(x => x.Bytes, f => f.Random.Bytes(20));
}
}
@@ -1,29 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.FileSystemManagement.Thumbnails.Queries.GetThumbnail;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Thumbnails.Queries.GetThumbnail.Fixtures;
/// <summary>
/// Fixture class for the <see cref="GetThumbnailQuery"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetThumbnailQueryFixture
{
/// <summary>
/// Creates a random valid query to get a thumbnail.
/// </summary>
/// <returns>The created query.</returns>
public static GetThumbnailQuery CreateGetThumbnailQuery()
{
return new Faker<GetThumbnailQuery>()
.CustomInstantiator(f => new GetThumbnailQuery(
default!,
default
))
.RuleFor(x => x.Path, f => f.System.FilePath())
.RuleFor(x => x.Quality, f => f.Random.Int());
}
}
@@ -3,10 +3,12 @@ using AutoFixture;
using AutoFixture.AutoNSubstitute;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.FileSystemManagement.Thumbnails.Queries.GetThumbnail;
using Lumina.Application.Fixtures.Core.FileSystemManagement.Thumbnails.Queries.GetThumbnail;
using Lumina.Contracts.Responses.FileSystemManagement.Thumbnails;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using NSubstitute;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
@@ -24,11 +26,15 @@ public class GetThumbnailQueryHandlerTests
private readonly IFixture _fixture;
private readonly IThumbnailService _mockThumbnailService;
private readonly GetThumbnailQueryHandler _sut;
private readonly GetThumbnailQueryFixture _getThumbnailQueryFixture;
private readonly ThumbnailFixture _thumbnailFixture;
public GetThumbnailQueryHandlerTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
_mockThumbnailService = Substitute.For<IThumbnailService>();
_getThumbnailQueryFixture = new GetThumbnailQueryFixture();
_thumbnailFixture = new ThumbnailFixture();
IValidator<GetThumbnailQuery> mockValidator = Substitute.For<IValidator<GetThumbnailQuery>>();
mockValidator.Validate(Arg.Any<GetThumbnailQuery>())
.Returns([]);
@@ -39,8 +45,8 @@ public class GetThumbnailQueryHandlerTests
public async Task HandleAsync_WhenCalledWithValidQuery_ShouldReturnSuccessResult()
{
// Arrange
GetThumbnailQuery query = _fixture.Create<GetThumbnailQuery>();
Thumbnail thumbnail = _fixture.Create<Thumbnail>();
GetThumbnailQuery query = _getThumbnailQueryFixture.Create();
Thumbnail thumbnail = _thumbnailFixture.Create();
_mockThumbnailService.GetThumbnailAsync(query.Path!, query.Quality, Arg.Any<CancellationToken>())
.Returns(Result.From(thumbnail));
@@ -60,7 +66,7 @@ public class GetThumbnailQueryHandlerTests
public async Task HandleAsync_WhenThumbnailServiceReturnsError_ShouldReturnFailureResult()
{
// Arrange
GetThumbnailQuery query = _fixture.Create<GetThumbnailQuery>();
GetThumbnailQuery query = _getThumbnailQueryFixture.Create();
Error error = Error.Failure("ThumbnailService.Error", "An error occurred");
_mockThumbnailService.GetThumbnailAsync(query.Path!, query.Quality, Arg.Any<CancellationToken>())
.Returns(error);
@@ -78,7 +84,7 @@ public class GetThumbnailQueryHandlerTests
public async Task HandleAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
GetThumbnailQuery query = _fixture.Create<GetThumbnailQuery>();
GetThumbnailQuery query = _getThumbnailQueryFixture.Create();
CancellationTokenSource cts = new();
cts.Cancel();
@@ -1,35 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.Maintenance.ApplicationSetup.Commands.SetupApplication;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.Maintenance.ApplicationSetup.Commands.SetupApplication.Fixtures;
/// <summary>
/// Fixture class for the <see cref="SetupApplicationCommand"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetupApplicationCommandFixture
{
/// <summary>
/// Creates a random valid command for the application setup.
/// </summary>
/// <returns>The created command.</returns>
public SetupApplicationCommand CreateSetupApplicationCommand()
{
string password = "Abcd123$";
return new Faker<SetupApplicationCommand>()
.CustomInstantiator(f => new SetupApplicationCommand(
default!,
default!,
default!,
true
))
.RuleFor(x => x.Username, f => f.Internet.UserName())
.RuleFor(x => x.Password, password)
.RuleFor(x => x.PasswordConfirm, password)
.RuleFor(x => x.Use2fa, f => f.Random.Bool())
.Generate();
}
}
@@ -9,8 +9,8 @@ using Lumina.Application.Common.Infrastructure.Security;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.Maintenance.ApplicationSetup.Commands.SetupApplication;
using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures;
using Lumina.Application.UnitTests.Core.Maintenance.ApplicationSetup.Commands.SetupApplication.Fixtures;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Core.Maintenance.ApplicationSetup.Commands.SetupApplication;
using Lumina.Contracts.Responses.Authentication;
using Lumina.Domain.Common.Primitives;
using NSubstitute;
@@ -38,6 +38,7 @@ public class SetupApplicationCommandHandlerTests
private readonly IDateTimeProvider _mockDateTimeProvider;
private readonly IDataSeedService _mockDataSeedService;
private readonly SetupApplicationCommandHandler _sut;
private readonly UserEntityFixture _userEntityFixture = new();
private readonly SetupApplicationCommandFixture _setupApplicationCommandFixture;
/// <summary>
@@ -76,7 +77,7 @@ public class SetupApplicationCommandHandlerTests
public async Task HandleAsync_WhenNoExistingUsers_ShouldCreateAdminUserWithout2FA()
{
// Arrange
SetupApplicationCommand command = _setupApplicationCommandFixture.CreateSetupApplicationCommand() with { Use2fa = false };
SetupApplicationCommand command = _setupApplicationCommandFixture.Create() with { Use2fa = false };
string hashedPassword = Uri.EscapeDataString("hashedPassword");
_mockUserRepository.GetAllAsync(Arg.Any<CancellationToken>())
@@ -112,7 +113,7 @@ public class SetupApplicationCommandHandlerTests
public async Task HandleAsync_WhenNoExistingUsersAndWith2FA_ShouldCreateAdminUserWithTOTP()
{
// Arrange
SetupApplicationCommand command = _setupApplicationCommandFixture.CreateSetupApplicationCommand() with { Use2fa = true };
SetupApplicationCommand command = _setupApplicationCommandFixture.Create() with { Use2fa = true };
string hashedPassword = Uri.EscapeDataString("hashedPassword");
byte[] totpSecret = [1, 2, 3];
string qrCodeUri = "data:image/png;base64,test";
@@ -157,8 +158,8 @@ public class SetupApplicationCommandHandlerTests
public async Task HandleAsync_WhenUserAlreadyExists_ShouldReturnError()
{
// Arrange
SetupApplicationCommand command = _setupApplicationCommandFixture.CreateSetupApplicationCommand();
UserEntity existingUser = UserEntityFixture.CreateUserEntity();
SetupApplicationCommand command = _setupApplicationCommandFixture.Create();
UserEntity existingUser = _userEntityFixture.Create();
_mockUserRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(new[] { existingUser });
@@ -179,7 +180,7 @@ public class SetupApplicationCommandHandlerTests
public async Task HandleAsync_WhenGetAllUsersReturnsError_ShouldReturnError()
{
// Arrange
SetupApplicationCommand command = _setupApplicationCommandFixture.CreateSetupApplicationCommand();
SetupApplicationCommand command = _setupApplicationCommandFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to retrieve users");
_mockUserRepository.GetAllAsync(Arg.Any<CancellationToken>())
@@ -201,7 +202,7 @@ public class SetupApplicationCommandHandlerTests
public async Task HandleAsync_WhenInsertUserReturnsError_ShouldReturnError()
{
// Arrange
SetupApplicationCommand command = _setupApplicationCommandFixture.CreateSetupApplicationCommand();
SetupApplicationCommand command = _setupApplicationCommandFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to insert user");
_mockUserRepository.GetAllAsync(Arg.Any<CancellationToken>())
@@ -225,7 +226,7 @@ public class SetupApplicationCommandHandlerTests
public async Task HandleAsync_WhenSetDefaultAuthorizationPermissionsFails_ShouldReturnError()
{
// Arrange
SetupApplicationCommand command = _setupApplicationCommandFixture.CreateSetupApplicationCommand();
SetupApplicationCommand command = _setupApplicationCommandFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to set default permissions");
_mockUserRepository.GetAllAsync(Arg.Any<CancellationToken>())
@@ -250,7 +251,7 @@ public class SetupApplicationCommandHandlerTests
public async Task HandleAsync_WhenSetDefaultAuthorizationRolesFails_ShouldReturnError()
{
// Arrange
SetupApplicationCommand command = _setupApplicationCommandFixture.CreateSetupApplicationCommand();
SetupApplicationCommand command = _setupApplicationCommandFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to set default roles");
_mockUserRepository.GetAllAsync(Arg.Any<CancellationToken>())
@@ -278,7 +279,7 @@ public class SetupApplicationCommandHandlerTests
public async Task HandleAsync_WhenSetAdminRolePermissionsFails_ShouldReturnError()
{
// Arrange
SetupApplicationCommand command = _setupApplicationCommandFixture.CreateSetupApplicationCommand();
SetupApplicationCommand command = _setupApplicationCommandFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to set admin role permissions");
_mockUserRepository.GetAllAsync(Arg.Any<CancellationToken>())
@@ -309,7 +310,7 @@ public class SetupApplicationCommandHandlerTests
public async Task HandleAsync_WhenSetAdminRoleToAdministratorAccountFails_ShouldReturnError()
{
// Arrange
SetupApplicationCommand command = _setupApplicationCommandFixture.CreateSetupApplicationCommand();
SetupApplicationCommand command = _setupApplicationCommandFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to set admin role to administrator account");
_mockUserRepository.GetAllAsync(Arg.Any<CancellationToken>())
@@ -342,7 +343,7 @@ public class SetupApplicationCommandHandlerTests
public async Task HandleAsync_WhenAllOperationsSucceed_ShouldReturnSuccessResponse()
{
// Arrange
SetupApplicationCommand command = _setupApplicationCommandFixture.CreateSetupApplicationCommand();
SetupApplicationCommand command = _setupApplicationCommandFixture.Create();
_mockUserRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(Result.From(Enumerable.Empty<UserEntity>()));
@@ -1,8 +1,8 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Errors;
using Lumina.Application.Core.Maintenance.ApplicationSetup.Commands.SetupApplication;
using Lumina.Application.Fixtures.Core.Maintenance.ApplicationSetup.Commands.SetupApplication;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Application.UnitTests.Core.Maintenance.ApplicationSetup.Commands.SetupApplication.Fixtures;
using Lumina.Domain.Common.Primitives;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
@@ -32,7 +32,7 @@ public class SetupApplicationCommandValidatorTests
public void Validate_WhenUsernameIsNull_ShouldHaveValidationError()
{
// Arrange
SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand();
SetupApplicationCommand command = _commandFixture.Create();
command = command with { Username = null };
// Act
@@ -46,7 +46,7 @@ public class SetupApplicationCommandValidatorTests
public void Validate_WhenUsernameIsEmpty_ShouldHaveValidationError()
{
// Arrange
SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand();
SetupApplicationCommand command = _commandFixture.Create();
command = command with { Username = string.Empty };
// Act
@@ -60,7 +60,7 @@ public class SetupApplicationCommandValidatorTests
public void Validate_WhenUsernameIsWhiteSpace_ShouldHaveValidationError()
{
// Arrange
SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand();
SetupApplicationCommand command = _commandFixture.Create();
command = command with { Username = " " };
// Act
@@ -74,7 +74,7 @@ public class SetupApplicationCommandValidatorTests
public void Validate_WhenPasswordIsNull_ShouldHaveValidationError()
{
// Arrange
SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand();
SetupApplicationCommand command = _commandFixture.Create();
command = command with { Password = null! };
// Act
@@ -88,7 +88,7 @@ public class SetupApplicationCommandValidatorTests
public void Validate_WhenPasswordIsEmpty_ShouldHaveValidationError()
{
// Arrange
SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand();
SetupApplicationCommand command = _commandFixture.Create();
command = command with { Password = string.Empty };
// Act
@@ -102,7 +102,7 @@ public class SetupApplicationCommandValidatorTests
public void Validate_WhenPasswordIsWhiteSpace_ShouldHaveValidationError()
{
// Arrange
SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand();
SetupApplicationCommand command = _commandFixture.Create();
command = command with { Password = " " };
// Act
@@ -116,7 +116,7 @@ public class SetupApplicationCommandValidatorTests
public void Validate_WhenPasswordConfirmIsNull_ShouldHaveValidationError()
{
// Arrange
SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand();
SetupApplicationCommand command = _commandFixture.Create();
command = command with { PasswordConfirm = null! };
// Act
@@ -130,7 +130,7 @@ public class SetupApplicationCommandValidatorTests
public void Validate_WhenPasswordConfirmIsEmpty_ShouldHaveValidationError()
{
// Arrange
SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand();
SetupApplicationCommand command = _commandFixture.Create();
command = command with { PasswordConfirm = string.Empty };
// Act
@@ -144,7 +144,7 @@ public class SetupApplicationCommandValidatorTests
public void Validate_WhenPasswordConfirmIsWhiteSpace_ShouldHaveValidationError()
{
// Arrange
SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand();
SetupApplicationCommand command = _commandFixture.Create();
command = command with { PasswordConfirm = " " };
// Act
@@ -158,7 +158,7 @@ public class SetupApplicationCommandValidatorTests
public void Validate_WhenPasswordAndPasswordConfirmDontMatch_ShouldHaveValidationError()
{
// Arrange
SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand();
SetupApplicationCommand command = _commandFixture.Create();
command = command with { PasswordConfirm = "$321Bcda" };
// Act
@@ -178,7 +178,7 @@ public class SetupApplicationCommandValidatorTests
public void Validate_WhenPasswordDoesNotMatchPattern_ShouldHaveValidationError(string password)
{
// Arrange
SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand();
SetupApplicationCommand command = _commandFixture.Create();
command = command with { Password = password, PasswordConfirm = password };
// Act
@@ -196,7 +196,7 @@ public class SetupApplicationCommandValidatorTests
public void Validate_WhenPasswordMatchesPattern_ShouldNotHaveValidationError(string password)
{
// Arrange
SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand();
SetupApplicationCommand command = _commandFixture.Create();
command = command with { Password = password, PasswordConfirm = password };
// Act
@@ -210,7 +210,7 @@ public class SetupApplicationCommandValidatorTests
public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError()
{
// Arrange
SetupApplicationCommand command = _commandFixture.CreateSetupApplicationCommand();
SetupApplicationCommand command = _commandFixture.Create();
command = command with { Password = "$321Bcda", PasswordConfirm = "$321Bcda" };
// Act
@@ -3,7 +3,7 @@ using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Core.Maintenance.ApplicationSetup.Queries.CheckInitialization;
using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Responses.UsersManagement;
using Lumina.Domain.Common.Primitives;
using NSubstitute;
@@ -25,6 +25,7 @@ public class CheckInitializationQueryHandlerTests
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IUserRepository _mockUserRepository;
private readonly CheckInitializationQueryHandler _sut;
private readonly UserEntityFixture _userEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="CheckInitializationQueryHandlerTests"/> class.
@@ -43,7 +44,7 @@ public class CheckInitializationQueryHandlerTests
public async Task HandleAsync_WhenUsersExist_ShouldReturnInitialized()
{
// Arrange
List<UserEntity> users = UserEntityFixture.CreateMany();
List<UserEntity> users = _userEntityFixture.CreateMany();
_mockUserRepository.GetAllAsync(Arg.Any<CancellationToken>())
.Returns(Result.From(users.AsEnumerable()));
@@ -1,110 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.UnitTests.Core.MediaLibrary.Management.Fixtures;
/// <summary>
/// Fixture class for the <see cref="Library"/>.
/// </summary>
[ExcludeFromCodeCoverage]
public class DomainLibraryFixture
{
private readonly Faker _faker;
private readonly Random _random = new();
/// <summary>
/// Initializes a new instance of the <see cref="DomainLibraryFixture"/> class.
/// </summary>
public DomainLibraryFixture()
{
_faker = new Faker();
}
/// <summary>
/// Creates a media library domain entity.
/// </summary>
/// <returns>The created media library entity.</returns>
public Library CreateLibrary()
{
List<string> validPaths =
[
"C:/Media",
"D:/Books",
"E:/Digital Library",
"F:/Content"
];
Result<Library> library = Library.Create(
UserId.CreateUnique(),
_faker.Random.String2(_faker.Random.Number(1, 50)),
_faker.PickRandom<LibraryType>(),
validPaths.Take(_random.Next(1, validPaths.Count)),
_faker.System.FilePath(),
_faker.Random.Bool(),
_faker.Random.Bool(),
_faker.Random.Bool(),
_faker.Random.Bool(),
_faker.Random.Bool(),
[ScanId.CreateUnique(), ScanId.CreateUnique()]
);
return library.Value;
}
public Library CreateLibraryWithSpecificValues(
Guid? id = null,
Guid? userId = null,
string? title = null,
LibraryType? libraryType = null,
IEnumerable<string>? contentLocations = null,
string? coverImage = null,
bool isEnabled = true,
bool isLocked = false,
bool downloadMetadataFromWeb = true,
bool shouldSaveMetadataInMediaDirectories = false,
bool shouldSkipUnchangedDirectoriesDuringScan = false,
IEnumerable<Guid>? scanIds = null)
{
Result<Library> library = id is null ?
Library.Create(
userId is not null ? UserId.Create(userId.Value) : UserId.CreateUnique(),
title ?? _faker.Random.String2(_faker.Random.Number(1, 50)),
libraryType ?? LibraryType.Book,
contentLocations ?? ["C:/Media"],
coverImage,
isEnabled,
isLocked,
downloadMetadataFromWeb,
shouldSaveMetadataInMediaDirectories,
shouldSkipUnchangedDirectoriesDuringScan,
scanIds?.Select(scanId => ScanId.Create(scanId)).ToList() ?? [ScanId.CreateUnique(), ScanId.CreateUnique()]
) :
Library.Create(
LibraryId.Create(id.Value),
userId is not null ? UserId.Create(userId.Value) : UserId.CreateUnique(),
title ?? _faker.Random.String2(_faker.Random.Number(1, 50)),
libraryType ?? LibraryType.Book,
contentLocations ?? ["C:/Media"],
coverImage,
isEnabled,
isLocked,
downloadMetadataFromWeb,
shouldSaveMetadataInMediaDirectories,
shouldSkipUnchangedDirectoriesDuringScan,
scanIds?.Select(scanId => ScanId.Create(scanId)).ToList() ?? [ScanId.CreateUnique(), ScanId.CreateUnique()]
);
return library.Value;
}
}
@@ -6,8 +6,8 @@ using Lumina.Application.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook.Fixtures;
using Lumina.Application.Fixtures.Common.Setup;
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook;
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
@@ -60,7 +60,7 @@ public class AddBookCommandHandlerTests
public async Task HandleAsync_WhenCalledWithValidCommand_ShouldReturnSuccessResult()
{
// Arrange
AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook();
AddBookCommand bookCommand = _commandBookFixture.Create();
_mockBookRepository.InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Created);
@@ -79,7 +79,7 @@ public class AddBookCommandHandlerTests
public async Task HandleAsync_WhenRepositoryInsertFails_ShouldReturnFailureResult()
{
// Arrange
AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook();
AddBookCommand bookCommand = _commandBookFixture.Create();
_mockBookRepository.InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
.Returns(Errors.WrittenContent.BookAlreadyExists);
@@ -98,7 +98,7 @@ public class AddBookCommandHandlerTests
public async Task HandleAsync_WhenCalledWithInvalidISBN_ShouldReturnFailureResult()
{
// Arrange
AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook();
AddBookCommand bookCommand = _commandBookFixture.Create();
bookCommand = bookCommand with { ISBNs = [new IsbnDto("invalid", IsbnFormat.Isbn13)] };
// Act
@@ -115,7 +115,7 @@ public class AddBookCommandHandlerTests
public async Task HandleAsync_WhenCalledWithInvalidRating_ShouldReturnFailureResult()
{
// Arrange
AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook();
AddBookCommand bookCommand = _commandBookFixture.Create();
bookCommand = bookCommand with { Ratings = [new BookRatingDto(-1, 5, null, null)] };
// Act
@@ -132,7 +132,7 @@ public class AddBookCommandHandlerTests
public async Task HandleAsync_WhenGenreCreationFails_ShouldReturnFailureResult()
{
// Arrange
AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook();
AddBookCommand bookCommand = _commandBookFixture.Create();
bookCommand = bookCommand with
{
Metadata = bookCommand.Metadata! with
@@ -155,7 +155,7 @@ public class AddBookCommandHandlerTests
public async Task HandleAsync_WhenTagCreationFails_ShouldReturnFailureResult()
{
// Arrange
AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook();
AddBookCommand bookCommand = _commandBookFixture.Create();
bookCommand = bookCommand with
{
Metadata = bookCommand.Metadata! with
@@ -178,7 +178,7 @@ public class AddBookCommandHandlerTests
public async Task HandleAsync_WhenReleaseInfoCreationFails_ShouldReturnFailureResult()
{
// Arrange
AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook();
AddBookCommand bookCommand = _commandBookFixture.Create();
bookCommand = bookCommand with
{
Metadata = bookCommand.Metadata! with
@@ -208,7 +208,7 @@ public class AddBookCommandHandlerTests
public async Task HandleAsync_WhenLanguageInfoCreationFails_ShouldReturnFailureResult()
{
// Arrange
AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook();
AddBookCommand bookCommand = _commandBookFixture.Create();
bookCommand = bookCommand with
{
Metadata = bookCommand.Metadata! with
@@ -231,7 +231,7 @@ public class AddBookCommandHandlerTests
public async Task HandleAsync_WhenOriginalLanguageInfoCreationFails_ShouldReturnFailureResult()
{
// Arrange
AddBookCommand bookCommand = _commandBookFixture.CreateCommandBook();
AddBookCommand bookCommand = _commandBookFixture.Create();
bookCommand = bookCommand with
{
Metadata = bookCommand.Metadata! with
@@ -1,345 +0,0 @@
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using Bogus;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook.Fixtures;
/// <summary>
/// Fixture class for the <see cref="AddBookCommand"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddBookCommandFixture
{
private readonly Fixture _fixture;
private readonly Random _random = new();
private readonly Faker _faker;
/// <summary>
/// Initializes a new instance of the <see cref="AddBookCommandFixture"/> class.
/// </summary>
public AddBookCommandFixture()
{
_fixture = new Fixture();
_fixture.Customizations.Add(new DateOnlySpecimenBuilder());
_fixture.Customizations.Add(new NullableDateOnlySpecimenBuilder());
_faker = new Faker();
}
/// <summary>
/// Creates a random valid command to add a book.
/// </summary>
/// <returns>The created command to add a book.</returns>
public AddBookCommand CreateCommandBook()
{
int releaseYear = _random.Next(2000, 2010);
int reReleaseYear = _random.Next(2010, 2020);
ReleaseInfoDto releaseInfo = new Faker<ReleaseInfoDto>()
.CustomInstantiator(f => new ReleaseInfoDto(
default,
default,
default,
default,
default,
default
))
.RuleFor(x => x.OriginalReleaseDate, _faker.DateOnlyBetween(new DateOnly(releaseYear, 1, 1), new DateOnly(releaseYear, 12, 31)))
.RuleFor(x => x.OriginalReleaseYear, releaseYear)
.RuleFor(x => x.ReReleaseDate, _faker.DateOnlyBetween(new DateOnly(reReleaseYear, 1, 1), new DateOnly(reReleaseYear, 12, 31)))
.RuleFor(x => x.ReReleaseYear, reReleaseYear)
.RuleFor(x => x.ReleaseCountry, f => f.Random.String2(2))
.RuleFor(x => x.ReleaseVersion, f => f.Random.String2(f.Random.Number(1, 50)))
.Generate();
Faker<GenreDto> genre = new Faker<GenreDto>()
.CustomInstantiator(f => new GenreDto(
default!
))
.RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50)));
Faker<TagDto> tag = new Faker<TagDto>()
.CustomInstantiator(f => new TagDto(
default!
))
.RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50)));
Faker<MediaContributorRoleDto> mediaContributorRole = new Faker<MediaContributorRoleDto>()
.CustomInstantiator(f => new MediaContributorRoleDto(
default!,
default!
))
.RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50)))
.RuleFor(e => e.Category, f => f.Random.String2(f.Random.Number(1, 50)));
Faker<MediaContributorNameDto> mediaContributorName = new Faker<MediaContributorNameDto>()
.CustomInstantiator(f => new MediaContributorNameDto(
default!,
default!
))
.RuleFor(e => e.DisplayName, f => f.Random.String2(f.Random.Number(1, 50)))
.RuleFor(e => e.LegalName, f => f.Random.String2(f.Random.Number(1, 50)));
Faker<MediaContributorDto> mediaContributor = new Faker<MediaContributorDto>()
.CustomInstantiator(f => new MediaContributorDto(
default!,
default!
))
.RuleFor(e => e.Name, mediaContributorName)
.RuleFor(e => e.Role, mediaContributorRole);
Faker<BookRatingDto> rating = new Faker<BookRatingDto>()
.CustomInstantiator(f => new BookRatingDto(
default,
default,
default,
default
))
.RuleFor(e => e.Value, _random.Next(1, 5))
.RuleFor(e => e.MaxValue, 5)
.RuleFor(e => e.Source, _fixture.Create<BookRatingSource>())
.RuleFor(e => e.VoteCount, _random.Next(1, 1000));
Faker<LanguageInfoDto> language = new Faker<LanguageInfoDto>()
.CustomInstantiator(f => new LanguageInfoDto(
default!,
default!,
default
))
.RuleFor(e => e.LanguageName, f => f.Random.String2(f.Random.Number(1, 50)))
.RuleFor(e => e.LanguageCode, f => f.Random.String2(2))
.RuleFor(e => e.NativeName, f => f.Random.String2(f.Random.Number(1, 50)));
Faker<LanguageInfoDto> originalLanguage = new Faker<LanguageInfoDto>()
.CustomInstantiator(f => new LanguageInfoDto(
default!,
default!,
default
))
.RuleFor(e => e.LanguageName, f => f.Random.String2(f.Random.Number(1, 50)))
.RuleFor(e => e.LanguageCode, f => f.Random.String2(2))
.RuleFor(e => e.NativeName, f => f.Random.String2(f.Random.Number(1, 50)));
Faker<WrittenContentMetadataDto> metadata = new Faker<WrittenContentMetadataDto>()
.CustomInstantiator(f => new WrittenContentMetadataDto(
default!,
default,
default,
default!,
default!,
default!,
default,
default,
default,
default
))
.RuleFor(x => x.Title, f => f.Random.String2(f.Random.Number(1, 255)))
.RuleFor(x => x.OriginalTitle, f => f.Random.String2(f.Random.Number(1, 255)))
.RuleFor(x => x.Description, f => f.Random.String2(f.Random.Number(1, 2000)))
.RuleFor(x => x.ReleaseInfo, releaseInfo)
.RuleFor(p => p.Genres, f => genre.Generate(f.Random.Number(1, 5)))
.RuleFor(x => x.Tags, f => tag.Generate(f.Random.Number(1, 5)))
.RuleFor(x => x.Language, language)
.RuleFor(x => x.OriginalLanguage, originalLanguage)
.RuleFor(x => x.Publisher, f => f.Random.String2(f.Random.Number(1, 100)))
.RuleFor(x => x.PageCount, _random.Next(100, 300));
Faker<IsbnDto> isbn = new Faker<IsbnDto>()
.CustomInstantiator(f => new IsbnDto(
default!,
default
))
.RuleFor(i => i.Value, f =>
{
bool isIsbn13 = f.Random.Bool();
if (isIsbn13)
{
string prefix = f.Random.Bool() ? "978" : "979";
string group = f.Random.Number(0, 99999).ToString().PadLeft(5, '0');
string publisher = f.Random.Number(0, 999999).ToString().PadLeft(6, '0');
string title = f.Random.Number(0, 99).ToString().PadLeft(2, '0');
string isbn = $"{prefix}{group[..1]}{publisher}{title}";
int sum = 0;
for (int i = 0; i < 12; i++)
sum += (i % 2 == 0 ? 1 : 3) * int.Parse(isbn[i].ToString());
int checkDigit = (10 - sum % 10) % 10;
return $"{prefix}-{group[..1]}-{publisher}-{title}-{checkDigit}";
}
else
{
int[] digits = new int[9];
for (int i = 0; i < 9; i++)
digits[i] = f.Random.Number(0, 9);
int sum = 0;
for (int i = 0; i < 9; i++)
sum += (10 - i) * digits[i];
int checkDigit = (11 - sum % 11) % 11;
string checkChar = checkDigit == 10 ? "X" : checkDigit.ToString();
return $"{digits[0]}-{digits[1]}{digits[2]}-{digits[3]}{digits[4]}{digits[5]}{digits[6]}{digits[7]}{digits[8]}-{checkChar}";
}
})
.RuleFor(i => i.Format, (f, i) => i.Value!.Length > 13 ? IsbnFormat.Isbn13 : IsbnFormat.Isbn10);
return new Faker<AddBookCommand>()
.CustomInstantiator(f => new AddBookCommand(
default,
default!,
default!,
default,
default,
default,
default,
default,
default,
default,
default,
default,
default,
default,
default,
default!,
default!,
default!,
default!
))
.RuleFor(x => x.LibraryId, _fixture.Create<Guid>())
.RuleFor(x => x.Path, f => f.System.FilePath())
.RuleFor(x => x.Metadata, metadata)
.RuleFor(x => x.Format, _fixture.Create<BookFormat>())
.RuleFor(x => x.Edition, f => f.Random.String2(f.Random.Number(1, 50)))
.RuleFor(x => x.VolumeNumber, _random.Next(1, 3))
.RuleFor(x => x.ASIN, f => f.Random.String2(10))
.RuleFor(x => x.GoodreadsId, _random.Next(100000, 500000).ToString())
.RuleFor(x => x.LCCN, f =>
{
string letters = new(Enumerable.Range(0, f.Random.Number(0, 3))
.Select(_ => f.Random.Char('a', 'z'))
.ToArray());
string digits = f.Random.String2(f.Random.Number(8, 10), "0123456789");
return letters + digits;
})
.RuleFor(x => x.OCLCNumber, f =>
{
string[] prefixes = ["ocm", "ocn", "on", "(OCoLC)"];
string prefix = f.Random.ArrayElement(prefixes);
string number;
switch (prefix)
{
case "ocm":
number = f.Random.String2(8, "0123456789");
break;
case "ocn":
number = f.Random.String2(f.Random.Number(9, 11), "0123456789");
break;
case "on":
number = f.Random.String2(10, "0123456789");
break;
case "(OCoLC)":
number = f.Random.String2(f.Random.Number(8, 10), "0123456789");
break;
default:
number = f.Random.String2(f.Random.Number(8, 10), "0123456789");
return number;
}
return prefix + number;
})
.RuleFor(x => x.OpenLibraryId, f =>
{
int firstDigit = f.Random.Number(1, 9);
string remainingDigits = f.Random.String2(f.Random.Number(0, 6), "0123456789");
char suffix = f.Random.ArrayElement(new[] { 'A', 'M', 'W' });
return $"OL{firstDigit}{remainingDigits}{suffix}";
})
.RuleFor(x => x.LibraryThingId, f => f.Random.String2(f.Random.Number(1, 50)))
.RuleFor(x => x.GoogleBooksId, f =>
{
const string VALID_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
return new string(Enumerable.Repeat(VALID_CHARS, 12)
.Select(s => s[f.Random.Number(VALID_CHARS.Length - 1)])
.ToArray());
})
.RuleFor(x => x.BarnesAndNobleId, f => f.Random.String2(10, "0123456789"))
.RuleFor(x => x.AppleBooksId, f => $"id{f.Random.Number(1, 999999)}")
.RuleFor(x => x.AppleBooksId, f => $"id{f.Random.Number(1, 999999)}")
.RuleFor(p => p.ISBNs, f => isbn.Generate(f.Random.Number(1, 5)))
.RuleFor(p => p.Ratings, f => rating.Generate(f.Random.Number(1, 5)))
.RuleFor(x => x.Contributors, f => mediaContributor.Generate(f.Random.Number(1, 5)));
}
private void ConfigureCustomRequestTypes()
{
int releaseYear = _random.Next(2000, 2010);
int reReleaseYear = _random.Next(2010, 2020);
_fixture.Register(() => new ReleaseInfoDto(
_faker.DateOnlyBetween(new DateOnly(releaseYear, 1, 1), new DateOnly(releaseYear, 12, 31)),
releaseYear,
_faker.DateOnlyBetween(new DateOnly(reReleaseYear, 1, 1), new DateOnly(reReleaseYear, 12, 31)),
reReleaseYear,
_fixture.Create<string>()[2..],
_fixture.Create<string?>()));
_fixture.Register(() => new GenreDto(
_fixture.Create<string>()
));
_fixture.Register(() => new TagDto(
_fixture.Create<string>()
));
_fixture.Register(() => new LanguageInfoDto(
_fixture.Create<string>(),
_fixture.Create<string>(),
_fixture.Create<string?>()
));
_fixture.Register(() => new IsbnDto(
_fixture.Create<string>(),
_fixture.Create<IsbnFormat>()
));
_fixture.Register(() => new BookRatingDto(
_fixture.Create<decimal>(),
_fixture.Create<decimal>(),
_fixture.Create<BookRatingSource?>(),
_fixture.Create<int?>()
));
_fixture.Register(() => new WrittenContentMetadataDto(
_fixture.Create<string>()[255..],
LimitStringLength(_fixture.Create<string?>(), 255),
LimitStringLength(_fixture.Create<string?>(), 2000),
_fixture.Create<ReleaseInfoDto>(),
_fixture.Create<List<GenreDto>>(),
_fixture.Create<List<TagDto>>(),
_fixture.Create<LanguageInfoDto?>(),
_fixture.Create<LanguageInfoDto?>(),
_fixture.Create<string?>(),
_fixture.Create<int?>()
));
_fixture.Register(() => new BookSeriesDto(
_fixture.Create<string>()
));
_fixture.Register(() => new MediaContributorRoleDto(
_fixture.Create<string>(),
_fixture.Create<string>()
));
_fixture.Register(() => new MediaContributorNameDto(
_fixture.Create<string>(),
_fixture.Create<string?>()
));
_fixture.Register(() => new MediaContributorDto(
_fixture.Create<MediaContributorNameDto>(),
_fixture.Create<MediaContributorRoleDto>()
));
}
private static string? LimitStringLength(string? input, int maxLength)
{
return input?.Length > maxLength ? input[..maxLength] : input;
}
}
Loaded 100 of 294 files, more files were not shown because too many files have changed in this diff. Show more