mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-02 02:01:10 +00:00
Standardizes test conventions and documentation
This commit is contained in:
1 parent
7aeed04255
commit
f42dc709de
190 files changed
+2180
-2814
No files matched your search
+23
-12
@@ -2,6 +2,7 @@
|
||||
using Bogus;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
@@ -20,23 +21,33 @@ public class RolePermissionEntityFixture
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="RolePermissionEntity"/>.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional. The Id of the role permission association.</param>
|
||||
/// <param name="roleId">Optional. The Id of the role the permission is granted to.</param>
|
||||
/// <param name="role">Optional. The role the permission is granted to.</param>
|
||||
/// <param name="permissionId">Optional. The Id of the permission granted to the role.</param>
|
||||
/// <param name="permission">Optional. The permission granted to the role.</param>
|
||||
/// <returns>The created <see cref="RolePermissionEntity"/>.</returns>
|
||||
public RolePermissionEntity Create()
|
||||
public RolePermissionEntity Create(
|
||||
Guid? id = null,
|
||||
Guid? roleId = null,
|
||||
RoleEntity? role = null,
|
||||
Guid? permissionId = null,
|
||||
PermissionEntity? permission = null)
|
||||
{
|
||||
PermissionEntity permission = new()
|
||||
RoleEntity resolvedRole = role ?? new RoleEntity
|
||||
{
|
||||
Id = _faker.Random.Guid(),
|
||||
PermissionName = _faker.PickRandom<AuthorizationPermission>(),
|
||||
Id = roleId ?? _faker.Random.Guid(),
|
||||
RoleName = _faker.Random.String2(10),
|
||||
CreatedOnUtc = _faker.Date.Past(),
|
||||
CreatedBy = _faker.Random.Guid(),
|
||||
UpdatedOnUtc = _faker.Date.Recent(),
|
||||
UpdatedBy = _faker.Random.Guid()
|
||||
};
|
||||
|
||||
RoleEntity role = new()
|
||||
PermissionEntity resolvedPermission = permission ?? new PermissionEntity
|
||||
{
|
||||
Id = _faker.Random.Guid(),
|
||||
RoleName = _faker.Random.String2(10),
|
||||
Id = permissionId ?? _faker.Random.Guid(),
|
||||
PermissionName = _faker.PickRandom<AuthorizationPermission>(),
|
||||
CreatedOnUtc = _faker.Date.Past(),
|
||||
CreatedBy = _faker.Random.Guid(),
|
||||
UpdatedOnUtc = _faker.Date.Recent(),
|
||||
@@ -46,11 +57,11 @@ public class RolePermissionEntityFixture
|
||||
return new Faker<RolePermissionEntity>()
|
||||
.CustomInstantiator(f => new RolePermissionEntity
|
||||
{
|
||||
Id = f.Random.Guid(),
|
||||
RoleId = role.Id,
|
||||
Role = role,
|
||||
PermissionId = permission.Id,
|
||||
Permission = permission,
|
||||
Id = id ?? f.Random.Guid(),
|
||||
RoleId = resolvedRole.Id,
|
||||
Role = role ?? resolvedRole,
|
||||
PermissionId = resolvedPermission.Id,
|
||||
Permission = permission ?? resolvedPermission,
|
||||
CreatedOnUtc = f.Date.Past(),
|
||||
CreatedBy = f.Random.Guid(),
|
||||
UpdatedOnUtc = f.Date.Recent(),
|
||||
|
||||
+10
-4
@@ -20,16 +20,22 @@ public class UserAuthorizationEntityFixture
|
||||
/// </summary>
|
||||
/// <param name="userId">Optional. The user Id to use. If null, a random GUID will be generated.</param>
|
||||
/// <param name="isAdmin">Whether the user should have admin role.</param>
|
||||
/// <param name="role">Optional. The role associated to the user. If null, it is derived from the <paramref name="isAdmin"/> flag.</param>
|
||||
/// <param name="permissions">Optional. The permissions associated to the user. If null, a default set is generated.</param>
|
||||
/// <returns>The created entity.</returns>
|
||||
public UserAuthorizationEntity Create(Guid? userId = null, bool isAdmin = false)
|
||||
public UserAuthorizationEntity Create(
|
||||
Guid? userId = null,
|
||||
bool isAdmin = false,
|
||||
string? role = null,
|
||||
IReadOnlySet<AuthorizationPermission>? permissions = null)
|
||||
{
|
||||
string role = isAdmin ? "Admin" : string.Empty;
|
||||
string resolvedRole = role ?? (isAdmin ? "Admin" : string.Empty);
|
||||
|
||||
return new UserAuthorizationEntity
|
||||
{
|
||||
UserId = userId ?? Guid.NewGuid(),
|
||||
Role = role,
|
||||
Permissions = new HashSet<AuthorizationPermission>
|
||||
Role = resolvedRole,
|
||||
Permissions = permissions ?? new HashSet<AuthorizationPermission>
|
||||
{
|
||||
AuthorizationPermission.CanViewUsers,
|
||||
AuthorizationPermission.CanRegisterUsers
|
||||
|
||||
+40
-22
@@ -1,6 +1,8 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
@@ -14,36 +16,52 @@ namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization;
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UserRoleEntityFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="UserRoleEntity"/>.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional. The Id of the user role association.</param>
|
||||
/// <param name="userId">Optional. The Id of the user the role is granted to.</param>
|
||||
/// <param name="user">Optional. The user the role is granted to.</param>
|
||||
/// <param name="roleId">Optional. The Id of the role granted to the user.</param>
|
||||
/// <param name="role">Optional. The role granted to the user.</param>
|
||||
/// <returns>The created <see cref="UserRoleEntity"/>.</returns>
|
||||
public UserRoleEntity Create()
|
||||
public UserRoleEntity Create(
|
||||
Guid? id = null,
|
||||
Guid? userId = null,
|
||||
UserEntity? user = null,
|
||||
Guid? roleId = null,
|
||||
RoleEntity? role = null)
|
||||
{
|
||||
UserEntity resolvedUser = user ?? new UserEntity
|
||||
{
|
||||
Id = userId ?? _faker.Random.Guid(),
|
||||
Username = _faker.Internet.UserName(),
|
||||
Password = _faker.Internet.Password(),
|
||||
Libraries = [],
|
||||
UserRole = null,
|
||||
UserPermissions = [],
|
||||
CreatedOnUtc = _faker.Date.Past(),
|
||||
CreatedBy = _faker.Random.Guid()
|
||||
};
|
||||
|
||||
RoleEntity resolvedRole = role ?? new RoleEntity
|
||||
{
|
||||
Id = roleId ?? _faker.Random.Guid(),
|
||||
RoleName = _faker.Random.String2(_faker.Random.Number(1, 50)),
|
||||
CreatedOnUtc = _faker.Date.Past(),
|
||||
CreatedBy = _faker.Random.Guid()
|
||||
};
|
||||
|
||||
return new Faker<UserRoleEntity>()
|
||||
.CustomInstantiator(f => new UserRoleEntity
|
||||
{
|
||||
Id = f.Random.Guid(),
|
||||
UserId = f.Random.Guid(),
|
||||
User = new()
|
||||
{
|
||||
Id = f.Random.Guid(),
|
||||
Username = f.Internet.UserName(),
|
||||
Password = f.Internet.Password(),
|
||||
Libraries = [],
|
||||
UserRole = null,
|
||||
UserPermissions = [],
|
||||
CreatedOnUtc = f.Date.Past(),
|
||||
CreatedBy = f.Random.Guid()
|
||||
},
|
||||
RoleId = f.Random.Guid(),
|
||||
Role = new()
|
||||
{
|
||||
Id = f.Random.Guid(),
|
||||
RoleName = f.Random.String2(f.Random.Number(1, 50)),
|
||||
CreatedOnUtc = f.Date.Past(),
|
||||
CreatedBy = f.Random.Guid()
|
||||
},
|
||||
Id = id ?? f.Random.Guid(),
|
||||
UserId = resolvedUser.Id,
|
||||
User = user ?? resolvedUser,
|
||||
RoleId = resolvedRole.Id,
|
||||
Role = role ?? resolvedRole,
|
||||
CreatedOnUtc = f.Date.Past(),
|
||||
CreatedBy = f.Random.Guid()
|
||||
})
|
||||
|
||||
+7
-5
@@ -28,13 +28,15 @@ public class BookEntityFixture
|
||||
/// <param name="path">Optional. The file system path of the book.</param>
|
||||
/// <param name="title">Optional. The title of the book.</param>
|
||||
/// <param name="originalTitle">Optional. The original title of the book.</param>
|
||||
/// <param name="includeMetadata">Whether the book should include its owned metadata collections (Tags, Genres, ISBNs, Ratings) or not.</param>
|
||||
/// <returns>The created <see cref="BookEntity"/>.</returns>
|
||||
public BookEntity Create(
|
||||
Guid? id = null,
|
||||
Guid? libraryId = null,
|
||||
string? path = null,
|
||||
string? title = null,
|
||||
string? originalTitle = null)
|
||||
string? originalTitle = null,
|
||||
bool includeMetadata = true)
|
||||
{
|
||||
int releaseYear = _random.Next(2000, 2010);
|
||||
int reReleaseYear = _random.Next(2010, 2020);
|
||||
@@ -58,8 +60,8 @@ public class BookEntityFixture
|
||||
.RuleFor(x => x.OriginalLanguageCode, f => f.Random.String2(2))
|
||||
.RuleFor(x => x.OriginalLanguageName, f => f.Random.String2(f.Random.Number(1, 50)))
|
||||
.RuleFor(x => x.OriginalLanguageNativeName, f => f.Random.String2(f.Random.Number(1, 50)))
|
||||
.RuleFor(x => x.Tags, f => [.. CreateTags(f.Random.Number(1, 5))])
|
||||
.RuleFor(x => x.Genres, f => [.. CreateGenres(f.Random.Number(1, 5))])
|
||||
.RuleFor(x => x.Tags, f => includeMetadata ? [.. CreateTags(f.Random.Number(1, 5))] : [])
|
||||
.RuleFor(x => x.Genres, f => includeMetadata ? [.. CreateGenres(f.Random.Number(1, 5))] : [])
|
||||
.RuleFor(x => x.Publisher, f => f.Random.String2(f.Random.Number(1, 100)))
|
||||
.RuleFor(x => x.PageCount, _random.Next(100, 300))
|
||||
.RuleFor(x => x.Format, f => f.PickRandom<BookFormat>())
|
||||
@@ -74,8 +76,8 @@ public class BookEntityFixture
|
||||
.RuleFor(x => x.GoogleBooksId, CreateGoogleBooksId)
|
||||
.RuleFor(x => x.BarnesAndNobleId, f => f.Random.String2(10, "0123456789"))
|
||||
.RuleFor(x => x.AppleBooksId, f => $"id{f.Random.Number(1, 999999)}")
|
||||
.RuleFor(x => x.ISBNs, f => CreateIsbns(f.Random.Number(1, 5)))
|
||||
.RuleFor(x => x.Ratings, f => CreateBookRatings(f.Random.Number(1, 5)))
|
||||
.RuleFor(x => x.ISBNs, f => includeMetadata ? CreateIsbns(f.Random.Number(1, 5)) : [])
|
||||
.RuleFor(x => x.Ratings, f => includeMetadata ? CreateBookRatings(f.Random.Number(1, 5)) : [])
|
||||
.RuleFor(x => x.CreatedOnUtc, f => f.Date.Past())
|
||||
.RuleFor(x => x.UpdatedOnUtc, f => f.Date.Recent())
|
||||
.Generate();
|
||||
|
||||
+23
-7
@@ -1,5 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
@@ -23,13 +24,28 @@ public class UserEntityFixture
|
||||
/// <param name="libraryCount">Number of libraries to generate. Default is 0.</param>
|
||||
/// <param name="username">Optional username to pin, or <see langword="null"/> to generate a random one.</param>
|
||||
/// <param name="password">Optional password to pin, or <see langword="null"/> to generate a random one.</param>
|
||||
/// <param name="id">Optional Id to pin, or <see langword="null"/> to generate a random one.</param>
|
||||
/// <param name="userRole">Optional user role association to pin when including it.</param>
|
||||
/// <param name="userPermissions">Optional user permission associations to pin when including them.</param>
|
||||
/// <param name="includeUserRole">Whether the user should include a user role association or not.</param>
|
||||
/// <param name="includeUserPermissions">Whether the user should include user permission associations or not.</param>
|
||||
/// <param name="libraries">Optional collection of libraries to pin for the user, or <see langword="null"/> to generate them based on <paramref name="libraryCount"/>.</param>
|
||||
/// <returns>The created user entity.</returns>
|
||||
public UserEntity Create(int libraryCount = 0, string? username = null, string? password = null)
|
||||
public UserEntity Create(
|
||||
int libraryCount = 0,
|
||||
string? username = null,
|
||||
string? password = null,
|
||||
Guid? id = null,
|
||||
UserRoleEntity? userRole = null,
|
||||
IEnumerable<UserPermissionEntity>? userPermissions = null,
|
||||
bool includeUserRole = false,
|
||||
bool includeUserPermissions = false,
|
||||
ICollection<LibraryEntity>? libraries = null)
|
||||
{
|
||||
Guid userId = Guid.NewGuid();
|
||||
List<LibraryEntity> libraries = libraryCount > 0
|
||||
Guid userId = id ?? Guid.NewGuid();
|
||||
ICollection<LibraryEntity> resolvedLibraries = libraries ?? (libraryCount > 0
|
||||
? CreateLibraries(libraryCount, userId)
|
||||
: [];
|
||||
: []);
|
||||
|
||||
return new Faker<UserEntity>()
|
||||
.CustomInstantiator(f => new UserEntity
|
||||
@@ -39,9 +55,9 @@ public class UserEntityFixture
|
||||
Password = default!,
|
||||
CreatedOnUtc = default,
|
||||
TotpSecret = default,
|
||||
Libraries = libraries,
|
||||
UserPermissions = [],
|
||||
UserRole = null,
|
||||
Libraries = resolvedLibraries,
|
||||
UserPermissions = includeUserPermissions ? (userPermissions ?? []).ToList() : [],
|
||||
UserRole = includeUserRole ? userRole : null,
|
||||
CreatedBy = userId
|
||||
})
|
||||
.RuleFor(x => x.Username, f => username ?? f.Internet.UserName())
|
||||
|
||||
+5
-3
@@ -28,20 +28,22 @@ public class GetBooksQueryFixture
|
||||
/// <param name="searchTerm">Optional. The search term used to filter results.</param>
|
||||
/// <param name="sortBy">Optional. The name of the field by which to sort the results.</param>
|
||||
/// <param name="sortOrder">Optional. The direction in which to sort the results.</param>
|
||||
/// <param name="includePaginationData">Whether the query should include pagination data or not.</param>
|
||||
/// <returns>The created query to get books.</returns>
|
||||
public GetBooksQuery Create(
|
||||
Guid? libraryId = null,
|
||||
PaginationDataDto? paginationData = null,
|
||||
string? searchTerm = null,
|
||||
string? sortBy = null,
|
||||
SortOrder? sortOrder = null)
|
||||
SortOrder? sortOrder = null,
|
||||
bool includePaginationData = true)
|
||||
{
|
||||
return new GetBooksQuery(
|
||||
paginationData ?? new PaginationDataDto
|
||||
includePaginationData ? paginationData ?? new PaginationDataDto
|
||||
{
|
||||
CurrentPage = _faker.Random.Number(1, 100),
|
||||
PerPage = _faker.Random.Number(1, 200)
|
||||
},
|
||||
} : null,
|
||||
new LibraryFilterDto
|
||||
{
|
||||
LibraryId = libraryId ?? _faker.Random.Guid(),
|
||||
|
||||
+8
-6
@@ -27,31 +27,33 @@ public class GetBooksLiteQueryFixture
|
||||
/// <param name="paginationData">Optional. The pagination data of the query.</param>
|
||||
/// <param name="searchTerm">Optional. The search term used to filter results.</param>
|
||||
/// <param name="filterAlphaKey">Optional. The alpha key used to filter the results by the first character of their title, for the alpha picker.</param>
|
||||
/// <param name="ignoreThePrefixForAlphaPicker">Optional. Whether the leading "The " prefix of a title should be ignored when computing the alpha key, or not.</param>
|
||||
/// <param name="shouldIgnoreThePrefixForAlphaPicker">Optional. Whether the leading "The " prefix of a title should be ignored when computing the alpha key, or not.</param>
|
||||
/// <param name="sortBy">Optional. The name of the field by which to sort the results.</param>
|
||||
/// <param name="sortOrder">Optional. The direction in which to sort the results.</param>
|
||||
/// <param name="includePaginationData">Whether the query should include pagination data or not.</param>
|
||||
/// <returns>The created query to get the lightweight details of books.</returns>
|
||||
public GetBooksLiteQuery Create(
|
||||
Guid? libraryId = null,
|
||||
PaginationDataDto? paginationData = null,
|
||||
string? searchTerm = null,
|
||||
string? filterAlphaKey = null,
|
||||
bool ignoreThePrefixForAlphaPicker = false,
|
||||
bool shouldIgnoreThePrefixForAlphaPicker = false,
|
||||
string? sortBy = null,
|
||||
SortOrder? sortOrder = null)
|
||||
SortOrder? sortOrder = null,
|
||||
bool includePaginationData = true)
|
||||
{
|
||||
return new GetBooksLiteQuery(
|
||||
paginationData ?? new PaginationDataDto
|
||||
includePaginationData ? paginationData ?? new PaginationDataDto
|
||||
{
|
||||
CurrentPage = _faker.Random.Number(1, 100),
|
||||
PerPage = _faker.Random.Number(1, 200)
|
||||
},
|
||||
} : null,
|
||||
new LibraryFilterDto
|
||||
{
|
||||
LibraryId = libraryId ?? _faker.Random.Guid(),
|
||||
SearchTerm = searchTerm,
|
||||
FilterAlphaKey = filterAlphaKey,
|
||||
IgnoreThePrefixForAlphaPicker = ignoreThePrefixForAlphaPicker
|
||||
ShouldIgnoreThePrefixForAlphaPicker = shouldIgnoreThePrefixForAlphaPicker
|
||||
},
|
||||
sortBy,
|
||||
sortOrder ?? _faker.PickRandom<SortOrder>()
|
||||
|
||||
+70
-29
@@ -1,6 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using Lumina.Contracts.DTO.MediaContributors;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
|
||||
using System;
|
||||
@@ -25,53 +26,93 @@ public class BookMetadataDtoFixture
|
||||
/// <param name="title">Optional. The title of the book.</param>
|
||||
/// <param name="originalTitle">Optional. The original title of the book.</param>
|
||||
/// <param name="description">Optional. A brief description or summary of the book.</param>
|
||||
/// <param name="goodreadsId">Optional. The Goodreads ID of the book.</param>
|
||||
/// <param name="format">Optional. The format of the book.</param>
|
||||
/// <param name="releaseInfo">Optional. The release information of the book.</param>
|
||||
/// <param name="genres">Optional. The genres of the book.</param>
|
||||
/// <param name="tags">Optional. The tags of the book.</param>
|
||||
/// <param name="language">Optional. The language of the book.</param>
|
||||
/// <param name="originalLanguage">Optional. The original language of the book.</param>
|
||||
/// <param name="publisher">Optional. The name of the publisher of the book.</param>
|
||||
/// <param name="pageCount">Optional. The number of pages in the book.</param>
|
||||
/// <param name="includeOptionalProperties">Whether optional properties should be included.</param>
|
||||
/// <param name="format">Optional. The format of the book.</param>
|
||||
/// <param name="edition">Optional. The edition of the book.</param>
|
||||
/// <param name="volumeNumber">Optional. The volume or book number in the series.</param>
|
||||
/// <param name="series">Optional. The series the book is part of.</param>
|
||||
/// <param name="asin">Optional. The ASIN of the book.</param>
|
||||
/// <param name="goodreadsId">Optional. The Goodreads ID of the book.</param>
|
||||
/// <param name="lccn">Optional. The LCCN of the book.</param>
|
||||
/// <param name="oclcNumber">Optional. The OCLC number of the book.</param>
|
||||
/// <param name="openLibraryId">Optional. The Open Library ID of the book.</param>
|
||||
/// <param name="libraryThingId">Optional. The LibraryThing ID of the book.</param>
|
||||
/// <param name="googleBooksId">Optional. The Google Books ID of the book.</param>
|
||||
/// <param name="barnesAndNobleId">Optional. The Barnes and Noble ID of the book.</param>
|
||||
/// <param name="appleBooksId">Optional. The Apple Books ID of the book.</param>
|
||||
/// <param name="isbns">Optional. The ISBNs of the book.</param>
|
||||
/// <param name="contributors">Optional. The contributors of the book.</param>
|
||||
/// <param name="ratings">Optional. The ratings of the book.</param>
|
||||
/// <param name="coverImagePath">Optional. The path of the cover image of the book.</param>
|
||||
/// <param name="includeTitle">Whether the title should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeOptionalProperties">Whether the properties that are not explicitly provided should be randomized, or left <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="BookMetadataDto"/>.</returns>
|
||||
public BookMetadataDto Create(
|
||||
string? title = null,
|
||||
string? originalTitle = null,
|
||||
string? description = null,
|
||||
string? goodreadsId = null,
|
||||
BookFormat? format = null,
|
||||
ReleaseInfoDto? releaseInfo = null,
|
||||
List<GenreDto>? genres = null,
|
||||
List<TagDto>? tags = null,
|
||||
LanguageInfoDto? language = null,
|
||||
LanguageInfoDto? originalLanguage = null,
|
||||
string? publisher = null,
|
||||
int? pageCount = null,
|
||||
BookFormat? format = null,
|
||||
string? edition = null,
|
||||
float? volumeNumber = null,
|
||||
BookSeriesDto? series = null,
|
||||
string? asin = null,
|
||||
string? goodreadsId = null,
|
||||
string? lccn = null,
|
||||
string? oclcNumber = null,
|
||||
string? openLibraryId = null,
|
||||
string? libraryThingId = null,
|
||||
string? googleBooksId = null,
|
||||
string? barnesAndNobleId = null,
|
||||
string? appleBooksId = null,
|
||||
List<IsbnDto>? isbns = null,
|
||||
List<MediaContributorDto>? contributors = null,
|
||||
List<BookRatingDto>? ratings = null,
|
||||
string? coverImagePath = null,
|
||||
bool includeTitle = true,
|
||||
bool includeOptionalProperties = true)
|
||||
{
|
||||
int releaseYear = _faker.Random.Int(1900, 2024);
|
||||
return new BookMetadataDto(
|
||||
title ?? _faker.Lorem.Sentence(3),
|
||||
includeTitle ? title ?? (includeOptionalProperties ? _faker.Lorem.Sentence(3) : null) : null,
|
||||
originalTitle,
|
||||
description,
|
||||
includeOptionalProperties
|
||||
? new ReleaseInfoDto(new DateOnly(releaseYear, 1, 1), releaseYear, null, null, _faker.Address.CountryCode(), null)
|
||||
: null,
|
||||
includeOptionalProperties ? [new GenreDto(_faker.Lorem.Word())] : null,
|
||||
includeOptionalProperties ? [new TagDto(_faker.Lorem.Word())] : null,
|
||||
includeOptionalProperties ? new LanguageInfoDto("en", "English", "English") : null,
|
||||
null,
|
||||
releaseInfo ?? (includeOptionalProperties ? new ReleaseInfoDto(new DateOnly(releaseYear, 1, 1), releaseYear, null, null, _faker.Address.CountryCode(), null) : null),
|
||||
genres ?? (includeOptionalProperties ? [new GenreDto(_faker.Lorem.Word())] : null),
|
||||
tags ?? (includeOptionalProperties ? [new TagDto(_faker.Lorem.Word())] : null),
|
||||
language ?? (includeOptionalProperties ? new LanguageInfoDto("en", "English", "English") : null),
|
||||
originalLanguage,
|
||||
publisher,
|
||||
pageCount,
|
||||
format ?? _faker.PickRandom<BookFormat>(),
|
||||
null,
|
||||
includeOptionalProperties ? _faker.Random.Int(1, 10) : null,
|
||||
null,
|
||||
null,
|
||||
format ?? (includeOptionalProperties ? _faker.PickRandom<BookFormat>() : null),
|
||||
edition,
|
||||
volumeNumber ?? (includeOptionalProperties ? _faker.Random.Int(1, 10) : null),
|
||||
series,
|
||||
asin,
|
||||
goodreadsId,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null);
|
||||
lccn,
|
||||
oclcNumber,
|
||||
openLibraryId,
|
||||
libraryThingId,
|
||||
googleBooksId,
|
||||
barnesAndNobleId,
|
||||
appleBooksId,
|
||||
isbns,
|
||||
contributors,
|
||||
ratings,
|
||||
coverImagePath);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+129
-59
@@ -9,6 +9,7 @@ using Lumina.Contracts.Fixtures.Common.Setup;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
@@ -37,8 +38,48 @@ public class AddBookRequestFixture
|
||||
/// <summary>
|
||||
/// Creates a random valid request to add a book.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">Optional. The Id of the media library the book belongs to.</param>
|
||||
/// <param name="path">Optional. The file system path of the book.</param>
|
||||
/// <param name="metadata">Optional. The written content metadata of the book.</param>
|
||||
/// <param name="format">Optional. The format of the book.</param>
|
||||
/// <param name="edition">Optional. The edition of the book.</param>
|
||||
/// <param name="volumeNumber">Optional. The volume or book number in the series.</param>
|
||||
/// <param name="series">Optional. The series the book is part of.</param>
|
||||
/// <param name="asin">Optional. The ASIN of the book.</param>
|
||||
/// <param name="goodreadsId">Optional. The Goodreads Id of the book.</param>
|
||||
/// <param name="lccn">Optional. The LCCN of the book.</param>
|
||||
/// <param name="oclcNumber">Optional. The OCLC number of the book.</param>
|
||||
/// <param name="openLibraryId">Optional. The Open Library Id of the book.</param>
|
||||
/// <param name="libraryThingId">Optional. The LibraryThing Id of the book.</param>
|
||||
/// <param name="googleBooksId">Optional. The Google Books Id of the book.</param>
|
||||
/// <param name="barnesAndNobleId">Optional. The Barnes and Noble Id of the book.</param>
|
||||
/// <param name="appleBooksId">Optional. The Apple Books Id of the book.</param>
|
||||
/// <param name="isbns">Optional. The ISBNs of the book.</param>
|
||||
/// <param name="contributors">Optional. The contributors of the book.</param>
|
||||
/// <param name="ratings">Optional. The ratings of the book.</param>
|
||||
/// <param name="includeOptionalProperties">Whether the properties that are not explicitly provided should be randomized, or left <see langword="null"/>.</param>
|
||||
/// <returns>The created request to add a book.</returns>
|
||||
public AddBookRequest Create()
|
||||
public AddBookRequest Create(
|
||||
Guid? libraryId = null,
|
||||
string? path = null,
|
||||
WrittenContentMetadataDto? metadata = null,
|
||||
BookFormat? format = null,
|
||||
string? edition = null,
|
||||
float? volumeNumber = null,
|
||||
BookSeriesDto? series = null,
|
||||
string? asin = null,
|
||||
string? goodreadsId = null,
|
||||
string? lccn = null,
|
||||
string? oclcNumber = null,
|
||||
string? openLibraryId = null,
|
||||
string? libraryThingId = null,
|
||||
string? googleBooksId = null,
|
||||
string? barnesAndNobleId = null,
|
||||
string? appleBooksId = null,
|
||||
List<IsbnDto>? isbns = null,
|
||||
List<MediaContributorDto>? contributors = null,
|
||||
List<BookRatingDto>? ratings = null,
|
||||
bool includeOptionalProperties = true)
|
||||
{
|
||||
int releaseYear = _random.Next(2000, 2010);
|
||||
int reReleaseYear = _random.Next(2010, 2020);
|
||||
@@ -128,7 +169,7 @@ public class AddBookRequestFixture
|
||||
.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>()
|
||||
Faker<WrittenContentMetadataDto> metadataFaker = new Faker<WrittenContentMetadataDto>()
|
||||
.CustomInstantiator(f => new WrittenContentMetadataDto(
|
||||
default!,
|
||||
default,
|
||||
@@ -210,62 +251,91 @@ public class AddBookRequestFixture
|
||||
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'))]);
|
||||
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(['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)])]);
|
||||
})
|
||||
.RuleFor(x => x.BarnesAndNobleId, f => f.Random.String2(10, "0123456789"))
|
||||
.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)));
|
||||
.RuleFor(x => x.LibraryId, libraryId ?? _fixture.Create<Guid>())
|
||||
.RuleFor(x => x.Path, f => path ?? f.System.FilePath())
|
||||
.RuleFor(x => x.Metadata, metadata ?? metadataFaker)
|
||||
.RuleFor(x => x.Format, format ?? (includeOptionalProperties ? _fixture.Create<BookFormat>() : null))
|
||||
.RuleFor(x => x.Edition, f => edition ?? (includeOptionalProperties ? f.Random.String2(f.Random.Number(1, 50)) : null))
|
||||
.RuleFor(x => x.VolumeNumber, volumeNumber ?? (includeOptionalProperties ? (float?)_random.Next(1, 3) : null))
|
||||
.RuleFor(x => x.Series, series)
|
||||
.RuleFor(x => x.ASIN, f => asin ?? (includeOptionalProperties ? f.Random.String2(10) : null))
|
||||
.RuleFor(x => x.GoodreadsId, goodreadsId ?? (includeOptionalProperties ? _random.Next(100000, 500000).ToString() : null))
|
||||
.RuleFor(x => x.LCCN, f => lccn ?? (includeOptionalProperties ? CreateLccn(f) : null))
|
||||
.RuleFor(x => x.OCLCNumber, f => oclcNumber ?? (includeOptionalProperties ? CreateOclcNumber(f) : null))
|
||||
.RuleFor(x => x.OpenLibraryId, f => openLibraryId ?? (includeOptionalProperties ? CreateOpenLibraryId(f) : null))
|
||||
.RuleFor(x => x.LibraryThingId, f => libraryThingId ?? (includeOptionalProperties ? f.Random.String2(f.Random.Number(1, 50)) : null))
|
||||
.RuleFor(x => x.GoogleBooksId, f => googleBooksId ?? (includeOptionalProperties ? CreateGoogleBooksId(f) : null))
|
||||
.RuleFor(x => x.BarnesAndNobleId, f => barnesAndNobleId ?? (includeOptionalProperties ? f.Random.String2(10, "0123456789") : null))
|
||||
.RuleFor(x => x.AppleBooksId, f => appleBooksId ?? (includeOptionalProperties ? $"id{f.Random.Number(1, 999999)}" : null))
|
||||
.RuleFor(p => p.ISBNs, f => isbns ?? (includeOptionalProperties ? isbn.Generate(f.Random.Number(1, 5)) : null))
|
||||
.RuleFor(p => p.Ratings, f => ratings ?? (includeOptionalProperties ? rating.Generate(f.Random.Number(1, 5)) : null))
|
||||
.RuleFor(x => x.Contributors, f => contributors ?? (includeOptionalProperties ? mediaContributor.Generate(f.Random.Number(1, 5)) : null));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generates a random LCCN (Library of Congress Control Number).
|
||||
/// </summary>
|
||||
/// <param name="faker">The faker used to generate the value.</param>
|
||||
/// <returns>The generated LCCN.</returns>
|
||||
private static string CreateLccn(Faker faker)
|
||||
{
|
||||
string letters = new([.. Enumerable.Range(0, faker.Random.Number(0, 3)).Select(_ => faker.Random.Char('a', 'z'))]);
|
||||
string digits = faker.Random.String2(faker.Random.Number(8, 10), "0123456789");
|
||||
return letters + digits;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generates a random OCLC number (WorldCat identifier).
|
||||
/// </summary>
|
||||
/// <param name="faker">The faker used to generate the value.</param>
|
||||
/// <returns>The generated OCLC number.</returns>
|
||||
private static string CreateOclcNumber(Faker faker)
|
||||
{
|
||||
string[] prefixes = ["ocm", "ocn", "on", "(OCoLC)"];
|
||||
string prefix = faker.Random.ArrayElement(prefixes);
|
||||
string number;
|
||||
switch (prefix)
|
||||
{
|
||||
case "ocm":
|
||||
number = faker.Random.String2(8, "0123456789");
|
||||
break;
|
||||
case "ocn":
|
||||
number = faker.Random.String2(faker.Random.Number(9, 11), "0123456789");
|
||||
break;
|
||||
case "on":
|
||||
number = faker.Random.String2(10, "0123456789");
|
||||
break;
|
||||
case "(OCoLC)":
|
||||
number = faker.Random.String2(faker.Random.Number(8, 10), "0123456789");
|
||||
break;
|
||||
default:
|
||||
number = faker.Random.String2(faker.Random.Number(8, 10), "0123456789");
|
||||
return number;
|
||||
}
|
||||
return prefix + number;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generates a random Open Library Id.
|
||||
/// </summary>
|
||||
/// <param name="faker">The faker used to generate the value.</param>
|
||||
/// <returns>The generated Open Library Id.</returns>
|
||||
private static string CreateOpenLibraryId(Faker faker)
|
||||
{
|
||||
int firstDigit = faker.Random.Number(1, 9);
|
||||
string remainingDigits = faker.Random.String2(faker.Random.Number(0, 6), "0123456789");
|
||||
char suffix = faker.Random.ArrayElement(['A', 'M', 'W']);
|
||||
return $"OL{firstDigit}{remainingDigits}{suffix}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generates a random Google Books Id.
|
||||
/// </summary>
|
||||
/// <param name="faker">The faker used to generate the value.</param>
|
||||
/// <returns>The generated Google Books Id.</returns>
|
||||
private static string CreateGoogleBooksId(Faker faker)
|
||||
{
|
||||
const string VALID_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
||||
return new string([.. Enumerable.Repeat(VALID_CHARS, 12).Select(s => s[faker.Random.Number(VALID_CHARS.Length - 1)])]);
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -26,7 +26,7 @@ public class GetBooksLiteRequestFixture
|
||||
/// <param name="perPage">Optional. The maximum number of books to retrieve per page.</param>
|
||||
/// <param name="searchTerm">Optional. The search term used to filter results.</param>
|
||||
/// <param name="filterAlphaKey">Optional. The alpha key used to filter the results by the first character of their title, for the alpha picker.</param>
|
||||
/// <param name="ignoreThePrefixForAlphaPicker">Optional. Whether the leading "The " prefix of a title should be ignored when computing the alpha key, or not.</param>
|
||||
/// <param name="shouldIgnoreThePrefixForAlphaPicker">Optional. Whether the leading "The " prefix of a title should be ignored when computing the alpha key, or not.</param>
|
||||
/// <param name="sortBy">Optional. The name of the field by which to sort the results.</param>
|
||||
/// <param name="sortOrder">Optional. The direction in which to sort the results.</param>
|
||||
/// <returns>The created <see cref="GetBooksLiteRequest"/>.</returns>
|
||||
@@ -36,7 +36,7 @@ public class GetBooksLiteRequestFixture
|
||||
int? perPage = null,
|
||||
string? searchTerm = null,
|
||||
string? filterAlphaKey = null,
|
||||
bool ignoreThePrefixForAlphaPicker = false,
|
||||
bool shouldIgnoreThePrefixForAlphaPicker = false,
|
||||
string? sortBy = null,
|
||||
SortOrder? sortOrder = null)
|
||||
{
|
||||
@@ -46,7 +46,7 @@ public class GetBooksLiteRequestFixture
|
||||
PerPage: perPage ?? _faker.Random.Number(1, 200),
|
||||
SearchTerm: searchTerm ?? _faker.Lorem.Word(),
|
||||
FilterAlphaKey: filterAlphaKey,
|
||||
IgnoreThePrefixForAlphaPicker: ignoreThePrefixForAlphaPicker,
|
||||
ShouldIgnoreThePrefixForAlphaPicker: shouldIgnoreThePrefixForAlphaPicker,
|
||||
SortBy: sortBy ?? _faker.Lorem.Word(),
|
||||
SortOrder: sortOrder ?? _faker.PickRandom<SortOrder>()
|
||||
);
|
||||
|
||||
+4
-3
@@ -15,6 +15,8 @@ namespace Lumina.Contracts.Fixtures.Core.Responses.FileSystemManagement.Thumbnai
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ThumbnailResponseFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="ThumbnailResponse"/>.
|
||||
/// </summary>
|
||||
@@ -23,10 +25,9 @@ public class ThumbnailResponseFixture
|
||||
/// <returns>The created <see cref="ThumbnailResponse"/>.</returns>
|
||||
public ThumbnailResponse Create(ImageType? type = null, byte[]? bytes = null)
|
||||
{
|
||||
Faker faker = new();
|
||||
return new ThumbnailResponse(
|
||||
type ?? faker.PickRandom<ImageType>(),
|
||||
bytes ?? faker.Random.Bytes(20)
|
||||
type ?? _faker.PickRandom<ImageType>(),
|
||||
bytes ?? _faker.Random.Bytes(20)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+4
-2
@@ -40,7 +40,8 @@ public class BookResponseFixture
|
||||
WrittenContentMetadataDto? metadata = null,
|
||||
BookFormat? format = null,
|
||||
MetadataStatus? metadataStatus = null,
|
||||
DateTime? createdOnUtc = null)
|
||||
DateTime? createdOnUtc = null,
|
||||
string? coverPath = null)
|
||||
{
|
||||
DateTime resolvedCreatedOnUtc = createdOnUtc ?? _faker.Date.Past().ToUniversalTime();
|
||||
return new BookResponse(
|
||||
@@ -70,7 +71,8 @@ public class BookResponseFixture
|
||||
_faker.Date.Recent().ToUniversalTime(),
|
||||
_faker.Company.CompanyName(),
|
||||
resolvedCreatedOnUtc,
|
||||
_faker.Random.Bool() ? _faker.Date.Recent().ToUniversalTime() : null
|
||||
_faker.Random.Bool() ? _faker.Date.Recent().ToUniversalTime() : null,
|
||||
coverPath ?? (_faker.Random.Bool() ? _faker.System.FilePath() : null)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -50,7 +50,7 @@ public class BookFixture
|
||||
_fixture.Create<WrittenContentMetadata>(),
|
||||
_fixture.Create<BookFormat>(),
|
||||
_fixture.Create<Optional<string>>(),
|
||||
_fixture.Create<Optional<int>>(),
|
||||
_fixture.Create<Optional<float>>(),
|
||||
_fixture.Create<Optional<BookSeries>>(),
|
||||
_fixture.Create<Optional<string>>(),
|
||||
_fixture.Create<Optional<string>>(),
|
||||
|
||||
+9
-8
@@ -15,6 +15,8 @@ namespace Lumina.Infrastructure.Fixtures.Common.Models.DTO.Configuration;
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ThemeEngineOptionsDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="ThemeEngineOptionsDto"/>.
|
||||
/// </summary>
|
||||
@@ -35,16 +37,15 @@ public class ThemeEngineOptionsDtoFixture
|
||||
long? maxSingleFileBytes = null,
|
||||
int? maxEntries = null)
|
||||
{
|
||||
Faker faker = new();
|
||||
return new ThemeEngineOptionsDto
|
||||
{
|
||||
StoragePath = storagePath ?? faker.System.DirectoryPath(),
|
||||
BundledThemesPath = bundledThemesPath ?? faker.System.DirectoryPath(),
|
||||
DefaultThemeId = defaultThemeId ?? faker.Lorem.Word(),
|
||||
MaxArchiveBytes = maxArchiveBytes ?? faker.Random.Long(1_000_000, 100_000_000),
|
||||
MaxExpandedBytes = maxExpandedBytes ?? faker.Random.Long(10_000_000, 500_000_000),
|
||||
MaxSingleFileBytes = maxSingleFileBytes ?? faker.Random.Long(1_000_000, 50_000_000),
|
||||
MaxEntries = maxEntries ?? faker.Random.Int(1, 1000)
|
||||
StoragePath = storagePath ?? _faker.System.DirectoryPath(),
|
||||
BundledThemesPath = bundledThemesPath ?? _faker.System.DirectoryPath(),
|
||||
DefaultThemeId = defaultThemeId ?? _faker.Lorem.Word(),
|
||||
MaxArchiveBytes = maxArchiveBytes ?? _faker.Random.Long(1_000_000, 100_000_000),
|
||||
MaxExpandedBytes = maxExpandedBytes ?? _faker.Random.Long(10_000_000, 500_000_000),
|
||||
MaxSingleFileBytes = maxSingleFileBytes ?? _faker.Random.Long(1_000_000, 50_000_000),
|
||||
MaxEntries = maxEntries ?? _faker.Random.Int(1, 1000)
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -10,7 +10,6 @@ using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
@@ -29,6 +28,7 @@ public class StubApiHttpClient : IApiHttpClient
|
||||
private readonly Dictionary<string, Func<object, object>> _postResponseFactories = [];
|
||||
private readonly Dictionary<string, Func<object, object>> _putResponseFactories = [];
|
||||
private readonly HashSet<string> _deleteSuccessEndpoints = [];
|
||||
private BlobDataDto? _blobResponse;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the authorization response returned for the <c>auth/get-authorization</c> endpoint.
|
||||
@@ -167,6 +167,15 @@ public class StubApiHttpClient : IApiHttpClient
|
||||
_deleteSuccessEndpoints.Add(endpoint);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers the blob response returned when a blob endpoint is called.
|
||||
/// </summary>
|
||||
/// <param name="blob">The blob response to return.</param>
|
||||
public void RegisterBlobResponse(BlobDataDto blob)
|
||||
{
|
||||
_blobResponse = blob;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resets all registered responses and captured requests, keeping only the default responses.
|
||||
/// </summary>
|
||||
@@ -176,6 +185,7 @@ public class StubApiHttpClient : IApiHttpClient
|
||||
_postResponseFactories.Clear();
|
||||
_putResponseFactories.Clear();
|
||||
_deleteSuccessEndpoints.Clear();
|
||||
_blobResponse = null;
|
||||
GetEndpointsCalled.Clear();
|
||||
PostRequests.Clear();
|
||||
PutRequests.Clear();
|
||||
@@ -222,6 +232,8 @@ public class StubApiHttpClient : IApiHttpClient
|
||||
/// <returns>A model containing the deserialized blob.</returns>
|
||||
public Task<BlobDataDto> GetBlobAsync(string endpoint, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (_blobResponse is not null)
|
||||
return Task.FromResult(_blobResponse);
|
||||
throw new NotSupportedException("Blob retrieval is not supported by the test stub.");
|
||||
}
|
||||
|
||||
|
||||
+3
-2
@@ -15,6 +15,8 @@ namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization;
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RoleDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="RoleDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
@@ -23,10 +25,9 @@ public class RoleDtoFixture
|
||||
/// <returns>A configured <see cref="RoleDto"/> instance.</returns>
|
||||
public RoleDto Create(Guid? id = null, string? roleName = null)
|
||||
{
|
||||
Faker faker = new();
|
||||
return new RoleDto(
|
||||
Id: id ?? Guid.NewGuid(),
|
||||
RoleName: roleName ?? faker.Commerce.Department()
|
||||
RoleName: roleName ?? _faker.Commerce.Department()
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+10
-10
@@ -1,7 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
@@ -15,6 +14,8 @@ namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Themes;
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ThemeInfoDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="ThemeInfoDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
@@ -37,16 +38,15 @@ public class ThemeInfoDtoFixture
|
||||
bool? isBundled = null,
|
||||
bool? isDeleted = null)
|
||||
{
|
||||
Faker faker = new();
|
||||
return new ThemeInfoDto(
|
||||
Id: id ?? faker.Lorem.Word(),
|
||||
Name: name ?? faker.Commerce.ProductName(),
|
||||
Description: description ?? faker.Lorem.Sentence(),
|
||||
Author: author ?? faker.Name.FullName(),
|
||||
Version: version ?? faker.System.Semver(),
|
||||
PreviewUrl: previewUrl ?? $"/theme-assets/{faker.Lorem.Word()}/preview.png",
|
||||
IsBundled: isBundled ?? faker.Random.Bool(),
|
||||
IsDeleted: isDeleted ?? faker.Random.Bool()
|
||||
Id: id ?? _faker.Lorem.Word(),
|
||||
Name: name ?? _faker.Commerce.ProductName(),
|
||||
Description: description ?? _faker.Lorem.Sentence(),
|
||||
Author: author ?? _faker.Name.FullName(),
|
||||
Version: version ?? _faker.System.Semver(),
|
||||
PreviewUrl: previewUrl ?? $"/theme-assets/{_faker.Lorem.Word()}/preview.png",
|
||||
IsBundled: isBundled ?? _faker.Random.Bool(),
|
||||
IsDeleted: isDeleted ?? _faker.Random.Bool()
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+5
-45
@@ -15,6 +15,9 @@ namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Themes;
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ThemeNavMenuDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly ThemeNavSectionDtoFixture _themeNavSectionDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="ThemeNavMenuDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
@@ -27,57 +30,14 @@ public class ThemeNavMenuDtoFixture
|
||||
IReadOnlyList<ThemeNavSectionDto>? mobileSections = null,
|
||||
IReadOnlyList<ThemeNavSectionDto>? menubarSections = null)
|
||||
{
|
||||
Faker faker = new();
|
||||
ThemeNavSectionDto[] generatedSections = [CreateSection()];
|
||||
ThemeNavSectionDto[] generatedSections = [_themeNavSectionDtoFixture.Create()];
|
||||
return new ThemeNavMenuDto(
|
||||
SiteName: siteName ?? faker.Company.CompanyName(),
|
||||
SiteName: siteName ?? _faker.Company.CompanyName(),
|
||||
MobileSections: mobileSections ?? generatedSections,
|
||||
MenubarSections: menubarSections ?? generatedSections
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a single <see cref="ThemeNavSectionDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="label">Optional label of the section.</param>
|
||||
/// <param name="items">Optional entries of the section.</param>
|
||||
/// <returns>A configured <see cref="ThemeNavSectionDto"/> instance.</returns>
|
||||
public ThemeNavSectionDto CreateSection(string? label = null, IReadOnlyList<ThemeNavEntryDto>? items = null)
|
||||
{
|
||||
Faker faker = new();
|
||||
return new ThemeNavSectionDto(
|
||||
Label: label ?? faker.Lorem.Word(),
|
||||
Items: items ?? [CreateEntry()]
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a single <see cref="ThemeNavEntryDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="label">Optional label of the entry.</param>
|
||||
/// <param name="url">Optional URL of the link, or <see langword="null"/> for a submenu.</param>
|
||||
/// <param name="includeUrl">Whether to set <paramref name="url"/>, or <see langword="null"/> when <see langword="false"/>.</param>
|
||||
/// <param name="cssClass">Optional CSS classes of the link.</param>
|
||||
/// <param name="includeCssClass">Whether to set <paramref name="cssClass"/>, or <see langword="null"/> when <see langword="false"/>.</param>
|
||||
/// <param name="children">Optional child links of a submenu.</param>
|
||||
/// <returns>A configured <see cref="ThemeNavEntryDto"/> instance.</returns>
|
||||
public ThemeNavEntryDto CreateEntry(
|
||||
string? label = null,
|
||||
string? url = null,
|
||||
bool includeUrl = false,
|
||||
string? cssClass = null,
|
||||
bool includeCssClass = false,
|
||||
IReadOnlyList<ThemeNavEntryDto>? children = null)
|
||||
{
|
||||
Faker faker = new();
|
||||
return new ThemeNavEntryDto(
|
||||
Label: label ?? faker.Lorem.Word(),
|
||||
Url: includeUrl ? (url ?? faker.Internet.Url()) : null,
|
||||
CssClass: includeCssClass ? (cssClass ?? faker.Lorem.Word()) : null,
|
||||
Children: children ?? []
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="ThemeNavMenuDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
|
||||
+5
-5
@@ -1,7 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
@@ -15,6 +14,8 @@ namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Themes;
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ThemePageDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="ThemePageDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
@@ -29,12 +30,11 @@ public class ThemePageDtoFixture
|
||||
string? description = null,
|
||||
IReadOnlyDictionary<string, object?>? pageData = null)
|
||||
{
|
||||
Faker faker = new();
|
||||
return new ThemePageDto
|
||||
{
|
||||
PageKey = pageKey ?? faker.Lorem.Word(),
|
||||
Title = title ?? faker.Lorem.Sentence(),
|
||||
Description = description ?? faker.Lorem.Sentence(),
|
||||
PageKey = pageKey ?? _faker.Lorem.Word(),
|
||||
Title = title ?? _faker.Lorem.Sentence(),
|
||||
Description = description ?? _faker.Lorem.Sentence(),
|
||||
PageData = pageData ?? new Dictionary<string, object?>()
|
||||
};
|
||||
}
|
||||
|
||||
+5
-3
@@ -14,6 +14,7 @@ namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Themes;
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ThemeRenderDocumentDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly ThemeInfoDtoFixture _themeInfoDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
@@ -22,12 +23,13 @@ public class ThemeRenderDocumentDtoFixture
|
||||
/// <param name="theme">Optional metadata of the resolved theme.</param>
|
||||
/// <param name="template">Optional raw template source to render.</param>
|
||||
/// <returns>A configured <see cref="ThemeRenderDocumentDto"/> instance.</returns>
|
||||
public ThemeRenderDocumentDto Create(ThemeInfoDto? theme = null, string? template = null)
|
||||
public ThemeRenderDocumentDto Create(
|
||||
ThemeInfoDto? theme = null,
|
||||
string? template = null)
|
||||
{
|
||||
Faker faker = new();
|
||||
return new ThemeRenderDocumentDto(
|
||||
Theme: theme ?? _themeInfoDtoFixture.Create(),
|
||||
Template: template ?? faker.Lorem.Paragraph()
|
||||
Template: template ?? _faker.Lorem.Paragraph()
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+11
-10
@@ -16,6 +16,8 @@ namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Themes;
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ThemeResponseDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="ThemeResponseDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
@@ -48,19 +50,18 @@ public class ThemeResponseDtoFixture
|
||||
DateTime? installedAtUtc = null,
|
||||
bool? isDeleted = null)
|
||||
{
|
||||
Faker faker = new();
|
||||
return new ThemeResponseDto(
|
||||
Id: id ?? Guid.NewGuid(),
|
||||
ThemeId: themeId ?? faker.Lorem.Word(),
|
||||
Name: name ?? faker.Commerce.ProductName(),
|
||||
Description: description ?? faker.Lorem.Sentence(),
|
||||
Author: author ?? faker.Name.FullName(),
|
||||
Version: version ?? faker.System.Semver(),
|
||||
PreviewPath: includePreviewPath ? (previewPath ?? (faker.Random.Bool() ? faker.System.FilePath() : null)) : null,
|
||||
ThemeId: themeId ?? _faker.Lorem.Word(),
|
||||
Name: name ?? _faker.Commerce.ProductName(),
|
||||
Description: description ?? _faker.Lorem.Sentence(),
|
||||
Author: author ?? _faker.Name.FullName(),
|
||||
Version: version ?? _faker.System.Semver(),
|
||||
PreviewPath: includePreviewPath ? (previewPath ?? (_faker.Random.Bool() ? _faker.System.FilePath() : null)) : null,
|
||||
InstallSource: installSource ?? ThemeInstallSource.Uploaded,
|
||||
IsCurrent: includeIsCurrent ? (isCurrent ?? (faker.Random.Bool() ? true : null)) : null,
|
||||
InstalledAtUtc: installedAtUtc ?? faker.Date.Recent(),
|
||||
IsDeleted: isDeleted ?? faker.Random.Bool()
|
||||
IsCurrent: includeIsCurrent ? (isCurrent ?? (_faker.Random.Bool() ? true : null)) : null,
|
||||
InstalledAtUtc: installedAtUtc ?? _faker.Date.Recent(),
|
||||
IsDeleted: isDeleted ?? _faker.Random.Bool()
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+4
-3
@@ -14,6 +14,8 @@ namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Themes;
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ThemeSettingsResponseDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="ThemeSettingsResponseDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
@@ -24,10 +26,9 @@ public class ThemeSettingsResponseDtoFixture
|
||||
long? maxArchiveBytes = null,
|
||||
string? defaultThemeId = null)
|
||||
{
|
||||
Faker faker = new();
|
||||
return new ThemeSettingsResponseDto(
|
||||
MaxArchiveBytes: maxArchiveBytes ?? faker.Random.Long(1024 * 1024, 256 * 1024 * 1024),
|
||||
DefaultThemeId: defaultThemeId ?? faker.Lorem.Word()
|
||||
MaxArchiveBytes: maxArchiveBytes ?? _faker.Random.Long(1024 * 1024, 256 * 1024 * 1024),
|
||||
DefaultThemeId: defaultThemeId ?? _faker.Lorem.Word()
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+2
-3
@@ -1,7 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
@@ -15,6 +14,7 @@ namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Themes;
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ThemeTemplateResponseDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
@@ -27,10 +27,9 @@ public class ThemeTemplateResponseDtoFixture
|
||||
ThemeResponseDto? theme = null,
|
||||
string? template = null)
|
||||
{
|
||||
Faker faker = new();
|
||||
return new ThemeTemplateResponseDto(
|
||||
Theme: theme ?? _themeResponseDtoFixture.Create(),
|
||||
Template: template ?? faker.Lorem.Paragraph()
|
||||
Template: template ?? _faker.Lorem.Paragraph()
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
@@ -14,15 +13,17 @@ namespace Lumina.Presentation.Web.Fixtures.Common.Models;
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SectionModelFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="SectionModel"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="text">Optional text rendered by the section.</param>
|
||||
/// <returns>A configured <see cref="SectionModel"/> instance.</returns>
|
||||
public SectionModel Create(string? text = null)
|
||||
public SectionModel Create(
|
||||
string? text = null)
|
||||
{
|
||||
Faker faker = new();
|
||||
return new SectionModel { Text = text ?? faker.Lorem.Word() };
|
||||
return new SectionModel { Text = text ?? _faker.Lorem.Word() };
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+6
-3
@@ -15,17 +15,20 @@ namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Authorization;
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddRoleRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="AddRoleRequest"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="roleName">Optional name of the role.</param>
|
||||
/// <param name="permissions">Optional collection of permission identifiers.</param>
|
||||
/// <returns>A configured <see cref="AddRoleRequest"/> instance.</returns>
|
||||
public AddRoleRequest Create(string? roleName = null, List<Guid>? permissions = null)
|
||||
public AddRoleRequest Create(
|
||||
string? roleName = null,
|
||||
List<Guid>? permissions = null)
|
||||
{
|
||||
Faker faker = new();
|
||||
return new AddRoleRequest(
|
||||
RoleName: roleName ?? faker.Commerce.Department(),
|
||||
RoleName: roleName ?? _faker.Commerce.Department(),
|
||||
Permissions: permissions ?? [Guid.NewGuid(), Guid.NewGuid()]
|
||||
);
|
||||
}
|
||||
|
||||
+3
-4
@@ -1,5 +1,4 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.Enums.Common;
|
||||
using Lumina.Presentation.Web.Common.Requests.Libraries;
|
||||
using System;
|
||||
@@ -24,7 +23,7 @@ public class GetBooksLiteRequestFixture
|
||||
/// <param name="perPage">Optional number of books to retrieve per page.</param>
|
||||
/// <param name="searchTerm">Optional search term used to filter results.</param>
|
||||
/// <param name="filterAlphaKey">Optional alpha key used to filter the results.</param>
|
||||
/// <param name="ignoreThePrefixForAlphaPicker">Whether the leading "The " prefix is ignored by the alpha picker.</param>
|
||||
/// <param name="shouldIgnoreThePrefixForAlphaPicker">Whether the leading "The " prefix is ignored by the alpha picker.</param>
|
||||
/// <param name="sortBy">Optional name of the field by which to sort the results.</param>
|
||||
/// <param name="sortOrder">Optional direction in which to sort the results.</param>
|
||||
/// <returns>A configured <see cref="GetBooksLiteRequest"/> instance.</returns>
|
||||
@@ -34,7 +33,7 @@ public class GetBooksLiteRequestFixture
|
||||
int? perPage = null,
|
||||
string? searchTerm = null,
|
||||
string? filterAlphaKey = null,
|
||||
bool ignoreThePrefixForAlphaPicker = false,
|
||||
bool shouldIgnoreThePrefixForAlphaPicker = false,
|
||||
string? sortBy = null,
|
||||
SortOrder? sortOrder = null)
|
||||
{
|
||||
@@ -45,7 +44,7 @@ public class GetBooksLiteRequestFixture
|
||||
PerPage = perPage,
|
||||
SearchTerm = searchTerm,
|
||||
FilterAlphaKey = filterAlphaKey,
|
||||
IgnoreThePrefixForAlphaPicker = ignoreThePrefixForAlphaPicker,
|
||||
ShouldIgnoreThePrefixForAlphaPicker = shouldIgnoreThePrefixForAlphaPicker,
|
||||
SortBy = sortBy,
|
||||
SortOrder = sortOrder
|
||||
};
|
||||
|
||||
+5
-3
@@ -14,16 +14,18 @@ namespace Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement.Authe
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LoginViewRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="LoginViewRequest"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="returnUrl">Optional URL to return to, after login.</param>
|
||||
/// <returns>A configured <see cref="LoginViewRequest"/> instance.</returns>
|
||||
public LoginViewRequest Create(string? returnUrl = null)
|
||||
public LoginViewRequest Create(
|
||||
string? returnUrl = null)
|
||||
{
|
||||
Faker faker = new();
|
||||
return new LoginViewRequest(
|
||||
ReturnUrl: returnUrl ?? $"/{faker.Random.AlphaNumeric(8)}"
|
||||
ReturnUrl: returnUrl ?? $"/{_faker.Random.AlphaNumeric(8)}"
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+10
-5
@@ -14,6 +14,8 @@ namespace Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement;
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ChangePasswordRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="ChangePasswordRequest"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
@@ -22,13 +24,16 @@ public class ChangePasswordRequestFixture
|
||||
/// <param name="newPassword">Optional new password.</param>
|
||||
/// <param name="newPasswordConfirm">Optional confirmation of the new password.</param>
|
||||
/// <returns>A configured <see cref="ChangePasswordRequest"/> instance.</returns>
|
||||
public ChangePasswordRequest Create(string? username = null, string? currentPassword = null, string? newPassword = null, string? newPasswordConfirm = null)
|
||||
public ChangePasswordRequest Create(
|
||||
string? username = null,
|
||||
string? currentPassword = null,
|
||||
string? newPassword = null,
|
||||
string? newPasswordConfirm = null)
|
||||
{
|
||||
Faker faker = new();
|
||||
string generatedNewPassword = newPassword ?? faker.Internet.Password(12);
|
||||
string generatedNewPassword = newPassword ?? _faker.Internet.Password(12);
|
||||
return new ChangePasswordRequest(
|
||||
Username: username ?? faker.Internet.UserName(),
|
||||
CurrentPassword: currentPassword ?? faker.Internet.Password(12),
|
||||
Username: username ?? _faker.Internet.UserName(),
|
||||
CurrentPassword: currentPassword ?? _faker.Internet.Password(12),
|
||||
NewPassword: generatedNewPassword,
|
||||
NewPasswordConfirm: newPasswordConfirm ?? generatedNewPassword
|
||||
);
|
||||
|
||||
+9
-4
@@ -14,6 +14,8 @@ namespace Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement;
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LoginRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="LoginRequest"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
@@ -22,12 +24,15 @@ public class LoginRequestFixture
|
||||
/// <param name="totpCode">Optional TOTP code.</param>
|
||||
/// <param name="returnUrl">Optional URL to return to, after login.</param>
|
||||
/// <returns>A configured <see cref="LoginRequest"/> instance.</returns>
|
||||
public LoginRequest Create(string? username = null, string? password = null, string? totpCode = null, string? returnUrl = null)
|
||||
public LoginRequest Create(
|
||||
string? username = null,
|
||||
string? password = null,
|
||||
string? totpCode = null,
|
||||
string? returnUrl = null)
|
||||
{
|
||||
Faker faker = new();
|
||||
return new LoginRequest(
|
||||
Username: username ?? faker.Internet.UserName(),
|
||||
Password: password ?? faker.Internet.Password(12),
|
||||
Username: username ?? _faker.Internet.UserName(),
|
||||
Password: password ?? _faker.Internet.Password(12),
|
||||
TotpCode: totpCode,
|
||||
ReturnUrl: returnUrl
|
||||
);
|
||||
|
||||
+6
-3
@@ -14,17 +14,20 @@ namespace Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement;
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RecoverPasswordRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="RecoverPasswordRequest"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="username">Optional username.</param>
|
||||
/// <param name="totpCode">Optional TOTP code.</param>
|
||||
/// <returns>A configured <see cref="RecoverPasswordRequest"/> instance.</returns>
|
||||
public RecoverPasswordRequest Create(string? username = null, string? totpCode = null)
|
||||
public RecoverPasswordRequest Create(
|
||||
string? username = null,
|
||||
string? totpCode = null)
|
||||
{
|
||||
Faker faker = new();
|
||||
return new RecoverPasswordRequest(
|
||||
Username: username ?? faker.Internet.UserName(),
|
||||
Username: username ?? _faker.Internet.UserName(),
|
||||
TotpCode: totpCode
|
||||
);
|
||||
}
|
||||
|
||||
+10
-4
@@ -14,6 +14,8 @@ namespace Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement;
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RegisterRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="RegisterRequest"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
@@ -23,12 +25,16 @@ public class RegisterRequestFixture
|
||||
/// <param name="registrationType">Optional registration type, e.g. "Admin" or "User".</param>
|
||||
/// <param name="use2fa">Whether two-factor authentication is enabled for the account.</param>
|
||||
/// <returns>A configured <see cref="RegisterRequest"/> instance.</returns>
|
||||
public RegisterRequest Create(string? username = null, string? password = null, string? passwordConfirm = null, string? registrationType = "User", bool use2fa = true)
|
||||
public RegisterRequest Create(
|
||||
string? username = null,
|
||||
string? password = null,
|
||||
string? passwordConfirm = null,
|
||||
string? registrationType = "User",
|
||||
bool use2fa = true)
|
||||
{
|
||||
Faker faker = new();
|
||||
string generatedPassword = password ?? faker.Internet.Password(12);
|
||||
string generatedPassword = password ?? _faker.Internet.Password(12);
|
||||
return new RegisterRequest(
|
||||
Username: username ?? faker.Internet.UserName(),
|
||||
Username: username ?? _faker.Internet.UserName(),
|
||||
Password: generatedPassword,
|
||||
PasswordConfirm: passwordConfirm ?? generatedPassword,
|
||||
RegistrationType: registrationType,
|
||||
|
||||
+6
-22
@@ -1,6 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DataAccess.Seed;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using Lumina.Contracts.Responses.Authentication;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
@@ -30,6 +31,7 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the username of the currently created test user.
|
||||
@@ -65,17 +67,8 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
// create test user
|
||||
UserEntity user = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Username = TestUsername!,
|
||||
Password = _hashService.HashString("TestPass123!"),
|
||||
Libraries = [],
|
||||
UserPermissions = [],
|
||||
UserRole = null,
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
};
|
||||
UserEntity user = _userEntityFixture.Create(username: TestUsername!, password: _hashService.HashString("TestPass123!"));
|
||||
user.TotpSecret = null;
|
||||
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
@@ -127,17 +120,8 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable
|
||||
IDataSeedService dataSeedService = scope.ServiceProvider.GetRequiredService<IDataSeedService>();
|
||||
|
||||
// create test user
|
||||
UserEntity user = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Username = TestUsername!,
|
||||
Password = _hashService.HashString("TestPass123!"),
|
||||
Libraries = [],
|
||||
UserPermissions = [],
|
||||
UserRole = null,
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
};
|
||||
UserEntity user = _userEntityFixture.Create(username: TestUsername!, password: _hashService.HashString("TestPass123!"));
|
||||
user.TotpSecret = null;
|
||||
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
+3
-7
@@ -1,6 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
@@ -28,6 +29,7 @@ public class DeleteRoleEndpointTests : IClassFixture<AuthenticatedLuminaApiFacto
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly RoleEntityFixture _roleEntityFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
@@ -60,13 +62,7 @@ public class DeleteRoleEndpointTests : IClassFixture<AuthenticatedLuminaApiFacto
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
// Create a test role first
|
||||
RoleEntity role = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
RoleName = "TestRole",
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
};
|
||||
RoleEntity role = _roleEntityFixture.Create(roleName: "TestRole");
|
||||
dbContext.Roles.Add(role);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
|
||||
+21
-23
@@ -1,7 +1,9 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Contracts.DTO.Authentication;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Authorization;
|
||||
using Lumina.Contracts.Requests.Authorization;
|
||||
using Lumina.Contracts.Responses.Authorization;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
@@ -33,6 +35,8 @@ public class UpdateRoleEndpointTests : IClassFixture<AuthenticatedLuminaApiFacto
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly RoleEntityFixture _roleEntityFixture = new();
|
||||
private readonly UpdateRoleRequestFixture _updateRoleRequestFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
@@ -64,21 +68,15 @@ public class UpdateRoleEndpointTests : IClassFixture<AuthenticatedLuminaApiFacto
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
RoleEntity role = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
RoleName = "TestRole",
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
};
|
||||
RoleEntity role = _roleEntityFixture.Create(roleName: "TestRole");
|
||||
dbContext.Roles.Add(role);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
PermissionEntity[] permissions = [.. dbContext.Permissions.Take(2)];
|
||||
UpdateRoleRequest request = new(
|
||||
RoleId: role.Id,
|
||||
RoleName: "UpdatedRole",
|
||||
Permissions: permissions.Select(p => p.Id).ToList()
|
||||
UpdateRoleRequest request = _updateRoleRequestFixture.Create(
|
||||
roleId: role.Id,
|
||||
roleName: "UpdatedRole",
|
||||
permissions: [.. permissions.Select(p => p.Id)]
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -107,10 +105,10 @@ public class UpdateRoleEndpointTests : IClassFixture<AuthenticatedLuminaApiFacto
|
||||
{
|
||||
// Arrange
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
UpdateRoleRequest request = new(
|
||||
RoleId: Guid.NewGuid(),
|
||||
RoleName: "UpdatedRole",
|
||||
Permissions: [Guid.NewGuid()]
|
||||
UpdateRoleRequest request = _updateRoleRequestFixture.Create(
|
||||
roleId: Guid.NewGuid(),
|
||||
roleName: "UpdatedRole",
|
||||
permissions: [Guid.NewGuid()]
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -136,10 +134,10 @@ public class UpdateRoleEndpointTests : IClassFixture<AuthenticatedLuminaApiFacto
|
||||
{
|
||||
// Arrange
|
||||
Guid nonExistentRoleId = Guid.NewGuid();
|
||||
UpdateRoleRequest request = new(
|
||||
RoleId: nonExistentRoleId,
|
||||
RoleName: "UpdatedRole",
|
||||
Permissions: [Guid.NewGuid()]
|
||||
UpdateRoleRequest request = _updateRoleRequestFixture.Create(
|
||||
roleId: nonExistentRoleId,
|
||||
roleName: "UpdatedRole",
|
||||
permissions: [Guid.NewGuid()]
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -165,10 +163,10 @@ public class UpdateRoleEndpointTests : IClassFixture<AuthenticatedLuminaApiFacto
|
||||
{
|
||||
// Arrange
|
||||
using CancellationTokenSource cts = new();
|
||||
UpdateRoleRequest request = new(
|
||||
RoleId: Guid.NewGuid(),
|
||||
RoleName: "UpdatedRole",
|
||||
Permissions: [Guid.NewGuid()]
|
||||
UpdateRoleRequest request = _updateRoleRequestFixture.Create(
|
||||
roleId: Guid.NewGuid(),
|
||||
roleName: "UpdatedRole",
|
||||
permissions: [Guid.NewGuid()]
|
||||
);
|
||||
|
||||
// Act & Assert
|
||||
|
||||
+5
-6
@@ -26,6 +26,7 @@ public class GetDirectoriesEndpointTests : IClassFixture<AuthenticatedLuminaApiF
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly FileSystemStructureFixture _fileSystemStructureFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
ReferenceHandler = ReferenceHandler.Preserve,
|
||||
@@ -56,8 +57,7 @@ public class GetDirectoriesEndpointTests : IClassFixture<AuthenticatedLuminaApiF
|
||||
public async Task GetDirectories_WhenCalledWithValidPathAndHiddenChildrenAndNotIncludeHiddenElements_ShouldReturnNoDirectories()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemStructureFixture fileSystemFixture = new();
|
||||
string testPath = fileSystemFixture.CreateFileSystemStructure();
|
||||
string testPath = _fileSystemStructureFixture.CreateFileSystemStructure();
|
||||
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath;
|
||||
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath; // two levels to get to the element that has a hidden element as child
|
||||
string encodedPath = Uri.EscapeDataString(testPath);
|
||||
@@ -79,7 +79,7 @@ public class GetDirectoriesEndpointTests : IClassFixture<AuthenticatedLuminaApiF
|
||||
}
|
||||
finally
|
||||
{
|
||||
fileSystemFixture.CleanupFileSystemStructure();
|
||||
_fileSystemStructureFixture.CleanupFileSystemStructure();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -87,8 +87,7 @@ public class GetDirectoriesEndpointTests : IClassFixture<AuthenticatedLuminaApiF
|
||||
public async Task GetDirectories_WhenCalledWithValidPathAndWithIncludeHiddenElements_ShouldReturnDirectoriesWithHiddenElements()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemStructureFixture fileSystemFixture = new();
|
||||
string testPath = fileSystemFixture.CreateFileSystemStructure();
|
||||
string testPath = _fileSystemStructureFixture.CreateFileSystemStructure();
|
||||
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath;
|
||||
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath; // two levels to get to the element that has a hidden element as child
|
||||
string encodedPath = Uri.EscapeDataString(testPath);
|
||||
@@ -118,7 +117,7 @@ public class GetDirectoriesEndpointTests : IClassFixture<AuthenticatedLuminaApiF
|
||||
}
|
||||
finally
|
||||
{
|
||||
fileSystemFixture.CleanupFileSystemStructure();
|
||||
_fileSystemStructureFixture.CleanupFileSystemStructure();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+7
-9
@@ -26,6 +26,7 @@ public class GetFilesEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly FileSystemStructureFixture _fileSystemStructureFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
ReferenceHandler = ReferenceHandler.Preserve,
|
||||
@@ -56,8 +57,7 @@ public class GetFilesEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
|
||||
public async Task GetFiles_WhenCalledWithValidPathAndNotIncludeHiddenElements_ShouldReturnFilesWithoutHiddenElements()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemStructureFixture fileSystemFixture = new();
|
||||
string testPath = fileSystemFixture.CreateFileSystemStructure();
|
||||
string testPath = _fileSystemStructureFixture.CreateFileSystemStructure();
|
||||
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath;
|
||||
bool includeHiddenElements = false;
|
||||
try
|
||||
@@ -85,7 +85,7 @@ public class GetFilesEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
|
||||
}
|
||||
finally
|
||||
{
|
||||
fileSystemFixture.CleanupFileSystemStructure();
|
||||
_fileSystemStructureFixture.CleanupFileSystemStructure();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -93,8 +93,7 @@ public class GetFilesEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
|
||||
public async Task GetFiles_WhenCalledWithValidPathAndHiddenChildrenAndNotIncludeHiddenElements_ShouldReturnNoFiles()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemStructureFixture fileSystemFixture = new();
|
||||
string testPath = fileSystemFixture.CreateFileSystemStructure();
|
||||
string testPath = _fileSystemStructureFixture.CreateFileSystemStructure();
|
||||
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath;
|
||||
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath; // two levels to get to the element that has a hidden element as child
|
||||
bool includeHiddenElements = false;
|
||||
@@ -117,7 +116,7 @@ public class GetFilesEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
|
||||
}
|
||||
finally
|
||||
{
|
||||
fileSystemFixture.CleanupFileSystemStructure();
|
||||
_fileSystemStructureFixture.CleanupFileSystemStructure();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -125,8 +124,7 @@ public class GetFilesEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
|
||||
public async Task GetFiles_WhenCalledWithValidPathAndWithIncludeHiddenElements_ShouldReturnFilesWithHiddenElements()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemStructureFixture fileSystemFixture = new();
|
||||
string testPath = fileSystemFixture.CreateFileSystemStructure();
|
||||
string testPath = _fileSystemStructureFixture.CreateFileSystemStructure();
|
||||
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath;
|
||||
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath; // two levels to get to the element that has a hidden element as child
|
||||
bool includeHiddenElements = true;
|
||||
@@ -158,7 +156,7 @@ public class GetFilesEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
|
||||
}
|
||||
finally
|
||||
{
|
||||
fileSystemFixture.CleanupFileSystemStructure();
|
||||
_fileSystemStructureFixture.CleanupFileSystemStructure();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+7
-9
@@ -26,6 +26,7 @@ public class GetTreeFilesEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly FileSystemStructureFixture _fileSystemStructureFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
ReferenceHandler = ReferenceHandler.Preserve,
|
||||
@@ -56,8 +57,7 @@ public class GetTreeFilesEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
|
||||
public async Task GetTreeFiles_WhenCalledWithValidPathAndNotIncludeHiddenElements_ShouldReturnTreeFilesWithoutHiddenElements()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemStructureFixture fileSystemFixture = new();
|
||||
string testPath = fileSystemFixture.CreateFileSystemStructure();
|
||||
string testPath = _fileSystemStructureFixture.CreateFileSystemStructure();
|
||||
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath;
|
||||
bool includeHiddenElements = false;
|
||||
try
|
||||
@@ -85,7 +85,7 @@ public class GetTreeFilesEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
|
||||
}
|
||||
finally
|
||||
{
|
||||
fileSystemFixture.CleanupFileSystemStructure();
|
||||
_fileSystemStructureFixture.CleanupFileSystemStructure();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -93,8 +93,7 @@ public class GetTreeFilesEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
|
||||
public async Task GetTreeFiles_WhenCalledWithValidPathAndHiddenChildrenAndNotIncludeHiddenElements_ShouldReturnNoTreeFiles()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemStructureFixture fileSystemFixture = new();
|
||||
string testPath = fileSystemFixture.CreateFileSystemStructure();
|
||||
string testPath = _fileSystemStructureFixture.CreateFileSystemStructure();
|
||||
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath;
|
||||
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath; // two levels to get to the element that has a hidden element as child
|
||||
bool includeHiddenElements = false;
|
||||
@@ -118,7 +117,7 @@ public class GetTreeFilesEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
|
||||
}
|
||||
finally
|
||||
{
|
||||
fileSystemFixture.CleanupFileSystemStructure();
|
||||
_fileSystemStructureFixture.CleanupFileSystemStructure();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -126,8 +125,7 @@ public class GetTreeFilesEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
|
||||
public async Task GetTreeFiles_WhenCalledWithValidPathAndWithIncludeHiddenElements_ShouldReturnTreeFilesWithHiddenElements()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemStructureFixture fileSystemFixture = new();
|
||||
string testPath = fileSystemFixture.CreateFileSystemStructure();
|
||||
string testPath = _fileSystemStructureFixture.CreateFileSystemStructure();
|
||||
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath;
|
||||
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath; // two levels to get to the element that has a hidden element as child
|
||||
bool includeHiddenElements = true;
|
||||
@@ -159,7 +157,7 @@ public class GetTreeFilesEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
|
||||
}
|
||||
finally
|
||||
{
|
||||
fileSystemFixture.CleanupFileSystemStructure();
|
||||
_fileSystemStructureFixture.CleanupFileSystemStructure();
|
||||
}
|
||||
}
|
||||
[Fact]
|
||||
|
||||
+22
-20
@@ -1,5 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.Management;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.Management;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
@@ -30,6 +31,7 @@ public class AddLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFacto
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly AddLibraryRequestFixture _addLibraryRequestFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
@@ -58,16 +60,16 @@ public class AddLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFacto
|
||||
public async Task AddLibrary_WhenCalledWithValidData_ShouldCreateLibrary()
|
||||
{
|
||||
// Arrange
|
||||
AddLibraryRequest request = new(
|
||||
Title: "New Library",
|
||||
LibraryType: "EBook",
|
||||
ContentLocations: ["C:/Media"],
|
||||
CoverImage: null,
|
||||
IsEnabled: true,
|
||||
IsLocked: false,
|
||||
DownloadMetadataFromWeb: true,
|
||||
ShouldSaveMetadataInMediaDirectories: false,
|
||||
ShouldSkipUnchangedDirectoriesDuringScan: true
|
||||
AddLibraryRequest request = _addLibraryRequestFixture.Create(
|
||||
title: "New Library",
|
||||
libraryType: "EBook",
|
||||
contentLocations: ["C:/Media"],
|
||||
coverImage: null,
|
||||
isEnabled: true,
|
||||
isLocked: false,
|
||||
canDownloadMetadataFromWeb: true,
|
||||
shouldSaveMetadataInMediaDirectories: false,
|
||||
shouldSkipUnchangedDirectoriesDuringScan: true
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -92,16 +94,16 @@ public class AddLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFacto
|
||||
{
|
||||
// Arrange
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
AddLibraryRequest request = new(
|
||||
Title: "New Library",
|
||||
LibraryType: "EBook",
|
||||
ContentLocations: ["C:/Media"],
|
||||
CoverImage: null,
|
||||
IsEnabled: true,
|
||||
IsLocked: false,
|
||||
DownloadMetadataFromWeb: true,
|
||||
ShouldSaveMetadataInMediaDirectories: false,
|
||||
ShouldSkipUnchangedDirectoriesDuringScan: true
|
||||
AddLibraryRequest request = _addLibraryRequestFixture.Create(
|
||||
title: "New Library",
|
||||
libraryType: "EBook",
|
||||
contentLocations: ["C:/Media"],
|
||||
coverImage: null,
|
||||
isEnabled: true,
|
||||
isLocked: false,
|
||||
canDownloadMetadataFromWeb: true,
|
||||
shouldSaveMetadataInMediaDirectories: false,
|
||||
shouldSkipUnchangedDirectoriesDuringScan: true
|
||||
);
|
||||
|
||||
// Act
|
||||
|
||||
+6
-23
@@ -1,8 +1,9 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.Management.DeleteLibrary;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
@@ -35,6 +36,8 @@ public class DeleteLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteLibraryEndpointTests"/> class.
|
||||
@@ -134,17 +137,7 @@ public class DeleteLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
dbContext.Users.Add(new UserEntity
|
||||
{
|
||||
Id = userId,
|
||||
Username = $"otheruser_{Guid.NewGuid()}",
|
||||
Password = "TestPass123!",
|
||||
Libraries = [],
|
||||
UserPermissions = [],
|
||||
UserRole = null,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
});
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return userId;
|
||||
}
|
||||
@@ -159,17 +152,7 @@ public class DeleteLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Libraries.Add(new LibraryEntity
|
||||
{
|
||||
Id = libraryId,
|
||||
UserId = userId,
|
||||
Title = "Test Library",
|
||||
LibraryType = LibraryType.EBook,
|
||||
ContentLocations = [],
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
|
||||
+3
-13
@@ -1,6 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.Management;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
@@ -33,6 +33,7 @@ public class GetEnabledLibrariesEndpointTests : IClassFixture<AuthenticatedLumin
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetEnabledLibrariesEndpointTests"/> class.
|
||||
@@ -101,18 +102,7 @@ public class GetEnabledLibrariesEndpointTests : IClassFixture<AuthenticatedLumin
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Libraries.Add(new LibraryEntity
|
||||
{
|
||||
Id = libraryId,
|
||||
UserId = userId,
|
||||
Title = title,
|
||||
LibraryType = LibraryType.EBook,
|
||||
ContentLocations = [],
|
||||
IsEnabled = isEnabled,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: LibraryType.EBook, contentLocations: [], isEnabled: isEnabled));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
|
||||
+6
-24
@@ -1,6 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.Management;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
@@ -8,7 +9,6 @@ using Lumina.Presentation.Api.Core.Endpoints.Library.Management.GetLibraries;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
@@ -34,6 +34,8 @@ public class GetLibrariesEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibrariesEndpointTests"/> class.
|
||||
@@ -100,17 +102,7 @@ public class GetLibrariesEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
dbContext.Users.Add(new UserEntity
|
||||
{
|
||||
Id = userId,
|
||||
Username = $"otheruser_{Guid.NewGuid()}",
|
||||
Password = "TestPass123!",
|
||||
Libraries = [],
|
||||
UserPermissions = [],
|
||||
UserRole = null,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
});
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return userId;
|
||||
}
|
||||
@@ -126,17 +118,7 @@ public class GetLibrariesEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Libraries.Add(new LibraryEntity
|
||||
{
|
||||
Id = libraryId,
|
||||
UserId = userId,
|
||||
Title = title,
|
||||
LibraryType = LibraryType.EBook,
|
||||
ContentLocations = [],
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: LibraryType.EBook, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
|
||||
+3
-12
@@ -1,6 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.Management;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
@@ -35,6 +35,7 @@ public class GetLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFacto
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibraryEndpointTests"/> class.
|
||||
@@ -109,17 +110,7 @@ public class GetLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFacto
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Libraries.Add(new LibraryEntity
|
||||
{
|
||||
Id = libraryId,
|
||||
UserId = userId,
|
||||
Title = title,
|
||||
LibraryType = LibraryType.EBook,
|
||||
ContentLocations = [],
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: LibraryType.EBook, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
|
||||
+3
-12
@@ -1,6 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.Management.GetLibraryScanProgress;
|
||||
@@ -33,6 +33,7 @@ public class GetLibraryScanProgressEndpointTests : IClassFixture<AuthenticatedLu
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibraryScanProgressEndpointTests"/> class.
|
||||
@@ -114,17 +115,7 @@ public class GetLibraryScanProgressEndpointTests : IClassFixture<AuthenticatedLu
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Libraries.Add(new LibraryEntity
|
||||
{
|
||||
Id = libraryId,
|
||||
UserId = userId,
|
||||
Title = "Test Library",
|
||||
LibraryType = LibraryType.EBook,
|
||||
ContentLocations = [],
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
|
||||
+3
-14
@@ -1,6 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.Management;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
@@ -34,6 +34,7 @@ public class ScanLibrariesEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ScanLibrariesEndpointTests"/> class.
|
||||
@@ -96,19 +97,7 @@ public class ScanLibrariesEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Libraries.Add(new LibraryEntity
|
||||
{
|
||||
Id = libraryId,
|
||||
UserId = userId,
|
||||
Title = "Test Library",
|
||||
LibraryType = LibraryType.EBook,
|
||||
ContentLocations = [],
|
||||
IsEnabled = true,
|
||||
IsLocked = false,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
|
||||
+3
-14
@@ -1,6 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.Management;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
@@ -35,6 +35,7 @@ public class ScanLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ScanLibraryEndpointTests"/> class.
|
||||
@@ -136,19 +137,7 @@ public class ScanLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Libraries.Add(new LibraryEntity
|
||||
{
|
||||
Id = libraryId,
|
||||
UserId = userId,
|
||||
Title = "Test Library",
|
||||
LibraryType = LibraryType.EBook,
|
||||
ContentLocations = [],
|
||||
IsEnabled = isEnabled,
|
||||
IsLocked = isLocked,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [], isEnabled: isEnabled, isLocked: isLocked));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
|
||||
+29
-35
@@ -1,6 +1,8 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.Management;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.Management;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
@@ -37,6 +39,8 @@ public class UpdateLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly UpdateLibraryRequestFixture _updateLibraryRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateLibraryEndpointTests"/> class.
|
||||
@@ -63,18 +67,18 @@ public class UpdateLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
await SeedLibraryAsync(libraryId, userId, "Original Title");
|
||||
UpdateLibraryRequest request = new(
|
||||
Id: libraryId,
|
||||
UserId: userId,
|
||||
Title: "Updated Title",
|
||||
LibraryType: "EBook",
|
||||
ContentLocations: ["C:/Media"],
|
||||
CoverImage: null,
|
||||
IsEnabled: true,
|
||||
IsLocked: false,
|
||||
DownloadMetadataFromWeb: true,
|
||||
ShouldSaveMetadataInMediaDirectories: false,
|
||||
ShouldSkipUnchangedDirectoriesDuringScan: true
|
||||
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
|
||||
id: libraryId,
|
||||
userId: userId,
|
||||
title: "Updated Title",
|
||||
libraryType: "EBook",
|
||||
contentLocations: ["C:/Media"],
|
||||
coverImage: null,
|
||||
isEnabled: true,
|
||||
isLocked: false,
|
||||
canDownloadMetadataFromWeb: true,
|
||||
shouldSaveMetadataInMediaDirectories: false,
|
||||
shouldSkipUnchangedDirectoriesDuringScan: true
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -99,18 +103,18 @@ public class UpdateLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
UpdateLibraryRequest request = new(
|
||||
Id: libraryId,
|
||||
UserId: Guid.NewGuid(),
|
||||
Title: "Updated Title",
|
||||
LibraryType: "EBook",
|
||||
ContentLocations: ["C:/Media"],
|
||||
CoverImage: null,
|
||||
IsEnabled: true,
|
||||
IsLocked: false,
|
||||
DownloadMetadataFromWeb: true,
|
||||
ShouldSaveMetadataInMediaDirectories: false,
|
||||
ShouldSkipUnchangedDirectoriesDuringScan: true
|
||||
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
|
||||
id: libraryId,
|
||||
userId: Guid.NewGuid(),
|
||||
title: "Updated Title",
|
||||
libraryType: "EBook",
|
||||
contentLocations: ["C:/Media"],
|
||||
coverImage: null,
|
||||
isEnabled: true,
|
||||
isLocked: false,
|
||||
canDownloadMetadataFromWeb: true,
|
||||
shouldSaveMetadataInMediaDirectories: false,
|
||||
shouldSkipUnchangedDirectoriesDuringScan: true
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -142,17 +146,7 @@ public class UpdateLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Libraries.Add(new LibraryEntity
|
||||
{
|
||||
Id = libraryId,
|
||||
UserId = userId,
|
||||
Title = title,
|
||||
LibraryType = LibraryType.EBook,
|
||||
ContentLocations = [],
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: LibraryType.EBook, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
|
||||
+44
-64
@@ -1,8 +1,10 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
@@ -38,6 +40,13 @@ public class GetBooksEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly BookRatingEntityFixture _bookRatingEntityFixture = new();
|
||||
private readonly GenreEntityFixture _genreEntityFixture = new();
|
||||
private readonly IsbnEntityFixture _isbnEntityFixture = new();
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly TagEntityFixture _tagEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetBooksEndpointTests"/> class.
|
||||
@@ -270,25 +279,44 @@ public class GetBooksEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
BookEntity book = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
LibraryId = libraryId,
|
||||
Path = $"/books/{Guid.NewGuid()}.epub",
|
||||
Title = title,
|
||||
Tags = [new TagEntity($"Tag-{Guid.NewGuid()}")],
|
||||
Genres = [new GenreEntity($"Genre-{Guid.NewGuid()}")],
|
||||
ISBNs = [new IsbnEntity("9780395272237", IsbnFormat.Isbn13)],
|
||||
Ratings = [new BookRatingEntity(4.5M, 5, BookRatingSource.Goodreads, 100)],
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
};
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: libraryId, title: title, path: $"/books/{Guid.NewGuid()}.epub", includeMetadata: false);
|
||||
book.Tags = [_tagEntityFixture.Create(name: $"Tag-{Guid.NewGuid()}")];
|
||||
book.Genres = [_genreEntityFixture.Create(name: $"Genre-{Guid.NewGuid()}")];
|
||||
book.ISBNs = [_isbnEntityFixture.Create(value: "9780395272237", format: IsbnFormat.Isbn13)];
|
||||
book.Ratings = [_bookRatingEntityFixture.Create(value: 4.5M, maxValue: 5, source: BookRatingSource.Goodreads, voteCount: 100)];
|
||||
dbContext.Books.Add(book);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return book;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a <see cref="LibraryEntity"/> owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library to seed.</param>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task SeedLibraryAsync(Guid libraryId, Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a <see cref="UserEntity"/> and returns its Id.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
@@ -301,54 +329,6 @@ public class GetBooksEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a <see cref="LibraryEntity"/> owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library to seed.</param>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task SeedLibraryAsync(Guid libraryId, Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Libraries.Add(new LibraryEntity
|
||||
{
|
||||
Id = libraryId,
|
||||
UserId = userId,
|
||||
Title = "Test Library",
|
||||
LibraryType = LibraryType.EBook,
|
||||
ContentLocations = [],
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a <see cref="UserEntity"/> and returns its Id.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
dbContext.Users.Add(new UserEntity
|
||||
{
|
||||
Id = userId,
|
||||
Username = $"otheruser_{Guid.NewGuid()}",
|
||||
Password = "TestPass123!",
|
||||
Libraries = [],
|
||||
UserPermissions = [],
|
||||
UserRole = null,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
});
|
||||
await dbContext.SaveChangesAsync();
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
|
||||
+37
-64
@@ -1,10 +1,12 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
@@ -16,9 +18,7 @@ using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBooksLite;
|
||||
@@ -36,6 +36,9 @@ public class GetBooksLiteEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetBooksLiteEndpointTests"/> class.
|
||||
@@ -117,7 +120,7 @@ public class GetBooksLiteEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
|
||||
await SeedBookAsync(libraryId, "Racing");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/lite?libraryId={libraryId}&filterAlphaKey=q&ignoreThePrefixForAlphaPicker=true");
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/lite?libraryId={libraryId}&filterAlphaKey=q&shouldIgnoreThePrefixForAlphaPicker=true");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
@@ -325,20 +328,38 @@ public class GetBooksLiteEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Books.Add(new BookEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
LibraryId = libraryId,
|
||||
Path = $"/books/{Guid.NewGuid()}.epub",
|
||||
Title = title,
|
||||
OriginalTitle = originalTitle,
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
dbContext.Books.Add(_bookEntityFixture.Create(libraryId: libraryId, title: title, originalTitle: originalTitle, path: $"/books/{Guid.NewGuid()}.epub", includeMetadata: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a <see cref="LibraryEntity"/> owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library to seed.</param>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task SeedLibraryAsync(Guid libraryId, Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a <see cref="UserEntity"/> and returns its Id.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
@@ -351,54 +372,6 @@ public class GetBooksLiteEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a <see cref="LibraryEntity"/> owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library to seed.</param>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task SeedLibraryAsync(Guid libraryId, Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Libraries.Add(new LibraryEntity
|
||||
{
|
||||
Id = libraryId,
|
||||
UserId = userId,
|
||||
Title = "Test Library",
|
||||
LibraryType = LibraryType.EBook,
|
||||
ContentLocations = [],
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a <see cref="UserEntity"/> and returns its Id.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
dbContext.Users.Add(new UserEntity
|
||||
{
|
||||
Id = userId,
|
||||
Username = $"otheruser_{Guid.NewGuid()}",
|
||||
Password = "TestPass123!",
|
||||
Libraries = [],
|
||||
UserPermissions = [],
|
||||
UserRole = null,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
});
|
||||
await dbContext.SaveChangesAsync();
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
|
||||
+4
-11
@@ -1,5 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.UsersManagement;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Infrastructure.Core.Security;
|
||||
@@ -25,6 +26,7 @@ public class CheckInitializationEndpointTests : IClassFixture<AuthenticatedLumin
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
@@ -117,17 +119,8 @@ public class CheckInitializationEndpointTests : IClassFixture<AuthenticatedLumin
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
UserEntity user = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Username = _testUsername,
|
||||
Password = new PasswordHashService().HashString("TestPass123!"),
|
||||
Libraries = [],
|
||||
UserPermissions = [],
|
||||
UserRole = null,
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
};
|
||||
UserEntity user = _userEntityFixture.Create(username: _testUsername, password: new PasswordHashService().HashString("TestPass123!"));
|
||||
user.TotpSecret = null;
|
||||
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
+22
-26
@@ -1,6 +1,8 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Authentication;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using Lumina.Contracts.Responses.Authentication;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
@@ -32,6 +34,8 @@ public class SetupApplicationEndpointTests : IClassFixture<AuthenticatedLuminaAp
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly RegistrationRequestFixture _registrationRequestFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
@@ -63,11 +67,11 @@ public class SetupApplicationEndpointTests : IClassFixture<AuthenticatedLuminaAp
|
||||
public async Task SetupApplication_WhenCalledWithValidRequestAnd2FA_ShouldSetupApplicationSuccessfully()
|
||||
{
|
||||
// Arrange
|
||||
RegistrationRequest request = new(
|
||||
Username: _testUsername,
|
||||
Password: "TestPass123!",
|
||||
PasswordConfirm: "TestPass123!",
|
||||
Use2fa: true
|
||||
RegistrationRequest request = _registrationRequestFixture.Create(
|
||||
username: _testUsername,
|
||||
password: "TestPass123!",
|
||||
passwordConfirm: "TestPass123!",
|
||||
use2fa: true
|
||||
);
|
||||
await _apiFactory.ResetDatabaseAsync();
|
||||
|
||||
@@ -97,11 +101,11 @@ public class SetupApplicationEndpointTests : IClassFixture<AuthenticatedLuminaAp
|
||||
public async Task SetupApplication_WhenCalledWithValidRequestWithout2FA_ShouldSetupApplicationSuccessfully()
|
||||
{
|
||||
// Arrange
|
||||
RegistrationRequest request = new(
|
||||
Username: _testUsername,
|
||||
Password: "TestPass123!",
|
||||
PasswordConfirm: "TestPass123!",
|
||||
Use2fa: false
|
||||
RegistrationRequest request = _registrationRequestFixture.Create(
|
||||
username: _testUsername,
|
||||
password: "TestPass123!",
|
||||
passwordConfirm: "TestPass123!",
|
||||
use2fa: false
|
||||
);
|
||||
await _apiFactory.ResetDatabaseAsync();
|
||||
|
||||
@@ -130,11 +134,11 @@ public class SetupApplicationEndpointTests : IClassFixture<AuthenticatedLuminaAp
|
||||
{
|
||||
// Arrange
|
||||
await CreateTestUser();
|
||||
RegistrationRequest request = new(
|
||||
Username: "another_admin",
|
||||
Password: "TestPass123!",
|
||||
PasswordConfirm: "TestPass123!",
|
||||
Use2fa: false
|
||||
RegistrationRequest request = _registrationRequestFixture.Create(
|
||||
username: "another_admin",
|
||||
password: "TestPass123!",
|
||||
passwordConfirm: "TestPass123!",
|
||||
use2fa: false
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -212,17 +216,9 @@ public class SetupApplicationEndpointTests : IClassFixture<AuthenticatedLuminaAp
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
UserEntity user = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Username = _testUsername,
|
||||
Password = new PasswordHashService().HashString("TestPass123!"),
|
||||
Libraries = [],
|
||||
UserPermissions = [],
|
||||
UserRole = null, // TODO: test default role and permissions?
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
};
|
||||
// TODO: test default role and permissions?
|
||||
UserEntity user = _userEntityFixture.Create(username: _testUsername, password: new PasswordHashService().HashString("TestPass123!"));
|
||||
user.TotpSecret = null;
|
||||
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
+3
-29
@@ -1,6 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Plugins;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetPlugins;
|
||||
@@ -9,7 +9,6 @@ using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
@@ -34,6 +33,7 @@ public class GetPluginsEndpointTests : IClassFixture<AuthenticatedLuminaApiFacto
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly List<Guid> _seededPluginIds = [];
|
||||
private readonly PluginEntityFixture _pluginEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPluginsEndpointTests"/> class.
|
||||
@@ -95,37 +95,11 @@ public class GetPluginsEndpointTests : IClassFixture<AuthenticatedLuminaApiFacto
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = GetCurrentUserId();
|
||||
dbContext.Plugins.Add(new PluginEntity
|
||||
{
|
||||
Id = pluginId,
|
||||
Name = name,
|
||||
Author = "Test Author",
|
||||
Version = "1.0.0",
|
||||
Description = "A test plugin.",
|
||||
LoadStatus = PluginLoadStatus.Loaded,
|
||||
LoadError = null,
|
||||
SettingsJson = null,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
dbContext.Plugins.Add(_pluginEntityFixture.Create(id: pluginId, name: name, loadStatus: PluginLoadStatus.Loaded, includeSettingsJson: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededPluginIds.Add(pluginId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the authenticated test user.</returns>
|
||||
private Guid GetCurrentUserId()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the seeded plugins and disposes API factory resources.
|
||||
/// </summary>
|
||||
|
||||
+27
-25
@@ -1,5 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Authentication;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using Lumina.Contracts.Responses.Authentication;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
@@ -29,6 +30,7 @@ public class ChangePasswordEndpointTests : IClassFixture<AuthenticatedLuminaApiF
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly ChangePasswordRequestFixture _changePasswordRequestFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
@@ -57,11 +59,11 @@ public class ChangePasswordEndpointTests : IClassFixture<AuthenticatedLuminaApiF
|
||||
public async Task ChangePassword_WhenCalledWithValidRequest_ShouldChangePasswordSuccessfully()
|
||||
{
|
||||
// Arrange
|
||||
ChangePasswordRequest request = new(
|
||||
Username: _apiFactory.TestUsername,
|
||||
CurrentPassword: "TestPass123!",
|
||||
NewPassword: "NewPass123!",
|
||||
NewPasswordConfirm: "NewPass123!"
|
||||
ChangePasswordRequest request = _changePasswordRequestFixture.Create(
|
||||
username: _apiFactory.TestUsername,
|
||||
currentPassword: "TestPass123!",
|
||||
newPassword: "NewPass123!",
|
||||
newPasswordConfirm: "NewPass123!"
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -82,11 +84,11 @@ public class ChangePasswordEndpointTests : IClassFixture<AuthenticatedLuminaApiF
|
||||
public async Task ChangePassword_WhenPasswordsDoNotMatch_ShouldReturnValidationError()
|
||||
{
|
||||
// Arrange
|
||||
ChangePasswordRequest request = new(
|
||||
Username: _apiFactory.TestUsername,
|
||||
CurrentPassword: "OldPass123!",
|
||||
NewPassword: "NewPass123!",
|
||||
NewPasswordConfirm: "DifferentPass123!"
|
||||
ChangePasswordRequest request = _changePasswordRequestFixture.Create(
|
||||
username: _apiFactory.TestUsername,
|
||||
currentPassword: "OldPass123!",
|
||||
newPassword: "NewPass123!",
|
||||
newPasswordConfirm: "DifferentPass123!"
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -116,11 +118,11 @@ public class ChangePasswordEndpointTests : IClassFixture<AuthenticatedLuminaApiF
|
||||
public async Task ChangePassword_WhenUserDoesNotExist_ShouldReturnNotFound()
|
||||
{
|
||||
// Arrange
|
||||
ChangePasswordRequest request = new(
|
||||
Username: "nonexistentuser",
|
||||
CurrentPassword: "OldPass123!",
|
||||
NewPassword: "NewPass123!",
|
||||
NewPasswordConfirm: "NewPass123!"
|
||||
ChangePasswordRequest request = _changePasswordRequestFixture.Create(
|
||||
username: "nonexistentuser",
|
||||
currentPassword: "OldPass123!",
|
||||
newPassword: "NewPass123!",
|
||||
newPasswordConfirm: "NewPass123!"
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -145,11 +147,11 @@ public class ChangePasswordEndpointTests : IClassFixture<AuthenticatedLuminaApiF
|
||||
public async Task ChangePassword_WhenCurrentPasswordIsIncorrect_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
ChangePasswordRequest request = new(
|
||||
Username: _apiFactory.TestUsername,
|
||||
CurrentPassword: "WrongPass123!",
|
||||
NewPassword: "NewPass123!",
|
||||
NewPasswordConfirm: "NewPass123!"
|
||||
ChangePasswordRequest request = _changePasswordRequestFixture.Create(
|
||||
username: _apiFactory.TestUsername,
|
||||
currentPassword: "WrongPass123!",
|
||||
newPassword: "NewPass123!",
|
||||
newPasswordConfirm: "NewPass123!"
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -206,11 +208,11 @@ public class ChangePasswordEndpointTests : IClassFixture<AuthenticatedLuminaApiF
|
||||
public async Task ChangePassword_WhenCancellationRequested_ShouldThrowTaskCanceledException()
|
||||
{
|
||||
// Arrange
|
||||
ChangePasswordRequest request = new(
|
||||
Username: _apiFactory.TestUsername,
|
||||
CurrentPassword: "OldPass123!",
|
||||
NewPassword: "NewPass123!",
|
||||
NewPasswordConfirm: "NewPass123!"
|
||||
ChangePasswordRequest request = _changePasswordRequestFixture.Create(
|
||||
username: _apiFactory.TestUsername,
|
||||
currentPassword: "OldPass123!",
|
||||
newPassword: "NewPass123!",
|
||||
newPasswordConfirm: "NewPass123!"
|
||||
);
|
||||
using CancellationTokenSource cts = new();
|
||||
|
||||
|
||||
+52
-69
@@ -1,6 +1,8 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.Infrastructure.Security;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Authentication;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using Lumina.Contracts.Responses.Authentication;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
@@ -33,6 +35,8 @@ public class LoginEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>,
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly PasswordHashService _hashService = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly LoginRequestFixture _loginRequestFixture = new();
|
||||
private readonly ICryptographyService _cryptographyService;
|
||||
private readonly TotpTokenGenerator _totpTokenGenerator = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
@@ -70,9 +74,9 @@ public class LoginEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>,
|
||||
{
|
||||
// Arrange
|
||||
UserEntity user = await CreateTestUser();
|
||||
LoginRequest request = new(
|
||||
Username: user.Username,
|
||||
Password: "TestPass123!"
|
||||
LoginRequest request = _loginRequestFixture.Create(
|
||||
username: user.Username,
|
||||
password: "TestPass123!"
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -101,10 +105,10 @@ public class LoginEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>,
|
||||
Totp totp = new(totpSecret);
|
||||
string validTotpCode = totp.ComputeTotp(DateTime.UtcNow);
|
||||
|
||||
LoginRequest request = new(
|
||||
Username: user.Username,
|
||||
Password: "TestPass123!",
|
||||
TotpCode: validTotpCode
|
||||
LoginRequest request = _loginRequestFixture.Create(
|
||||
username: user.Username,
|
||||
password: "TestPass123!",
|
||||
totpCode: validTotpCode
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -129,9 +133,9 @@ public class LoginEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>,
|
||||
{
|
||||
// Arrange
|
||||
UserEntity user = await CreateTestUserWithTempPassword();
|
||||
LoginRequest request = new(
|
||||
Username: user.Username,
|
||||
Password: "TempPass123!"
|
||||
LoginRequest request = _loginRequestFixture.Create(
|
||||
username: user.Username,
|
||||
password: "TempPass123!"
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -155,9 +159,9 @@ public class LoginEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>,
|
||||
{
|
||||
// Arrange
|
||||
UserEntity user = await CreateTestUserWithExpiredTempPassword();
|
||||
LoginRequest request = new(
|
||||
Username: user.Username,
|
||||
Password: "TempPass123!"
|
||||
LoginRequest request = _loginRequestFixture.Create(
|
||||
username: user.Username,
|
||||
password: "TempPass123!"
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -183,9 +187,9 @@ public class LoginEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>,
|
||||
{
|
||||
// Arrange
|
||||
UserEntity user = await CreateTestUser();
|
||||
LoginRequest request = new(
|
||||
Username: user.Username,
|
||||
Password: "WrongPass123!"
|
||||
LoginRequest request = _loginRequestFixture.Create(
|
||||
username: user.Username,
|
||||
password: "WrongPass123!"
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -211,10 +215,10 @@ public class LoginEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>,
|
||||
{
|
||||
// Arrange
|
||||
UserEntity user = await CreateTestUserWithTotp();
|
||||
LoginRequest request = new(
|
||||
Username: user.Username,
|
||||
Password: "TestPass123!",
|
||||
TotpCode: "000000"
|
||||
LoginRequest request = _loginRequestFixture.Create(
|
||||
username: user.Username,
|
||||
password: "TestPass123!",
|
||||
totpCode: "000000"
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -240,94 +244,73 @@ public class LoginEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>,
|
||||
Assert.Contains("InvalidTotpCode", errors["General.Validation"]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user without a TOTP secret in the database and returns it.
|
||||
/// </summary>
|
||||
/// <returns>The created user entity.</returns>
|
||||
private async Task<UserEntity> CreateTestUser()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
UserEntity user = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Username = _testUsername,
|
||||
Password = _hashService.HashString("TestPass123!"),
|
||||
Libraries = [],
|
||||
UserPermissions = [],
|
||||
UserRole = null,
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
};
|
||||
UserEntity user = _userEntityFixture.Create(username: _testUsername, password: _hashService.HashString("TestPass123!"));
|
||||
user.TotpSecret = null;
|
||||
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return user;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user with a TOTP secret in the database and returns it.
|
||||
/// </summary>
|
||||
/// <returns>The created user entity.</returns>
|
||||
private async Task<UserEntity> CreateTestUserWithTotp()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
byte[] totpSecret = _totpTokenGenerator.GenerateSecret();
|
||||
UserEntity user = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Username = _testUsername,
|
||||
Password = _hashService.HashString("TestPass123!"),
|
||||
TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(totpSecret)),
|
||||
Libraries = [],
|
||||
UserPermissions = [],
|
||||
UserRole = null,
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
};
|
||||
UserEntity user = _userEntityFixture.Create(username: _testUsername, password: _hashService.HashString("TestPass123!"));
|
||||
user.TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(totpSecret));
|
||||
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return user;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user with a temporary password in the database and returns it.
|
||||
/// </summary>
|
||||
/// <returns>The created user entity.</returns>
|
||||
private async Task<UserEntity> CreateTestUserWithTempPassword()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
UserEntity user = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Username = _testUsername,
|
||||
Password = _hashService.HashString("TestPass123!"),
|
||||
TempPassword = Uri.EscapeDataString(_hashService.HashString("TempPass123!")),
|
||||
TempPasswordCreated = DateTime.UtcNow,
|
||||
Libraries = [],
|
||||
UserPermissions = [],
|
||||
UserRole = null,
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
};
|
||||
UserEntity user = _userEntityFixture.Create(username: _testUsername, password: _hashService.HashString("TestPass123!"));
|
||||
user.TotpSecret = null;
|
||||
user.TempPassword = Uri.EscapeDataString(_hashService.HashString("TempPass123!"));
|
||||
user.TempPasswordCreated = DateTime.UtcNow;
|
||||
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return user;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user with an expired temporary password in the database and returns it.
|
||||
/// </summary>
|
||||
/// <returns>The created user entity.</returns>
|
||||
private async Task<UserEntity> CreateTestUserWithExpiredTempPassword()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
UserEntity user = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Username = _testUsername,
|
||||
Password = _hashService.HashString("TestPass123!"),
|
||||
TempPassword = Uri.EscapeDataString(_hashService.HashString("TempPass123!")),
|
||||
TempPasswordCreated = DateTime.UtcNow.AddMinutes(-16), // expired (> 15 minutes old)
|
||||
Libraries = [],
|
||||
UserPermissions = [],
|
||||
UserRole = null,
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
};
|
||||
UserEntity user = _userEntityFixture.Create(username: _testUsername, password: _hashService.HashString("TestPass123!"));
|
||||
user.TotpSecret = null;
|
||||
user.TempPassword = Uri.EscapeDataString(_hashService.HashString("TempPass123!"));
|
||||
user.TempPasswordCreated = DateTime.UtcNow.AddMinutes(-16); // expired (> 15 minutes old)
|
||||
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
+16
-36
@@ -1,6 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.Infrastructure.Security;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using Lumina.Contracts.Responses.Authentication;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
@@ -35,6 +36,7 @@ public class RecoverPasswordEndpointTests : IClassFixture<AuthenticatedLuminaApi
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly PasswordHashService _hashService = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly ICryptographyService _cryptographyService;
|
||||
private readonly TotpTokenGenerator _totpTokenGenerator = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
@@ -244,18 +246,8 @@ public class RecoverPasswordEndpointTests : IClassFixture<AuthenticatedLuminaApi
|
||||
using (IServiceScope scope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity userWithoutTotp = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Username = "userwithoutotp2",
|
||||
Password = _hashService.HashString("OldPass123!"),
|
||||
TotpSecret = null, // No TOTP configured
|
||||
Libraries = [],
|
||||
UserPermissions = [],
|
||||
UserRole = null,
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
};
|
||||
UserEntity userWithoutTotp = _userEntityFixture.Create(username: "userwithoutotp2", password: _hashService.HashString("OldPass123!"));
|
||||
userWithoutTotp.TotpSecret = null; // No TOTP configured
|
||||
dbContext.Users.Add(userWithoutTotp);
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
@@ -307,47 +299,35 @@ public class RecoverPasswordEndpointTests : IClassFixture<AuthenticatedLuminaApi
|
||||
Assert.IsType<TaskCanceledException>(exception);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user with a TOTP secret in the database and returns it.
|
||||
/// </summary>
|
||||
/// <returns>The created user entity.</returns>
|
||||
private async Task<UserEntity> CreateUserWithTotp()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
byte[] totpSecret = _totpTokenGenerator.GenerateSecret();
|
||||
UserEntity user = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Username = _testUsername,
|
||||
Password = _hashService.HashString("OldPass123!"),
|
||||
TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(totpSecret)),
|
||||
Libraries = [],
|
||||
UserPermissions = [],
|
||||
UserRole = null,
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
};
|
||||
UserEntity user = _userEntityFixture.Create(username: _testUsername, password: _hashService.HashString("OldPass123!"));
|
||||
user.TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(totpSecret));
|
||||
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return user;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user without a TOTP secret in the database and returns it.
|
||||
/// </summary>
|
||||
/// <returns>The created user entity.</returns>
|
||||
private async Task<UserEntity> CreateUserWithoutTotp()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
UserEntity user = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Username = _testUsername,
|
||||
Password = _hashService.HashString("OldPass123!"),
|
||||
TotpSecret = null,
|
||||
Libraries = [],
|
||||
UserPermissions = [],
|
||||
UserRole = null,
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
};
|
||||
UserEntity user = _userEntityFixture.Create(username: _testUsername, password: _hashService.HashString("OldPass123!"));
|
||||
user.TotpSecret = null;
|
||||
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
+30
-31
@@ -1,5 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Authentication;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using Lumina.Contracts.Responses.Authentication;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
@@ -29,6 +31,8 @@ public class RegisterEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly RegistrationRequestFixture _registrationRequestFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
@@ -60,11 +64,11 @@ public class RegisterEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
|
||||
public async Task Register_WhenCalledWithValidRequest_ShouldRegisterUserSuccessfully()
|
||||
{
|
||||
// Arrange
|
||||
RegistrationRequest request = new(
|
||||
Username: _testUsername,
|
||||
Password: "TestPass123!",
|
||||
PasswordConfirm: "TestPass123!",
|
||||
Use2fa: false
|
||||
RegistrationRequest request = _registrationRequestFixture.Create(
|
||||
username: _testUsername,
|
||||
password: "TestPass123!",
|
||||
passwordConfirm: "TestPass123!",
|
||||
use2fa: false
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -88,11 +92,11 @@ public class RegisterEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
|
||||
public async Task Register_WhenCalledWithValidRequestAnd2FA_ShouldRegisterUserWithTotp()
|
||||
{
|
||||
// Arrange
|
||||
RegistrationRequest request = new(
|
||||
Username: _testUsername,
|
||||
Password: "TestPass123!",
|
||||
PasswordConfirm: "TestPass123!",
|
||||
Use2fa: true
|
||||
RegistrationRequest request = _registrationRequestFixture.Create(
|
||||
username: _testUsername,
|
||||
password: "TestPass123!",
|
||||
passwordConfirm: "TestPass123!",
|
||||
use2fa: true
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -116,11 +120,11 @@ public class RegisterEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
|
||||
{
|
||||
// Arrange
|
||||
await CreateTestUser();
|
||||
RegistrationRequest request = new(
|
||||
Username: _testUsername,
|
||||
Password: "TestPass123!",
|
||||
PasswordConfirm: "TestPass123!",
|
||||
Use2fa: false
|
||||
RegistrationRequest request = _registrationRequestFixture.Create(
|
||||
username: _testUsername,
|
||||
password: "TestPass123!",
|
||||
passwordConfirm: "TestPass123!",
|
||||
use2fa: false
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -141,11 +145,11 @@ public class RegisterEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
|
||||
public async Task Register_WhenPasswordsDoNotMatch_ShouldReturnValidationError()
|
||||
{
|
||||
// Arrange
|
||||
RegistrationRequest request = new(
|
||||
Username: _testUsername,
|
||||
Password: "TestPass123!",
|
||||
PasswordConfirm: "DifferentPass123!",
|
||||
Use2fa: false
|
||||
RegistrationRequest request = _registrationRequestFixture.Create(
|
||||
username: _testUsername,
|
||||
password: "TestPass123!",
|
||||
passwordConfirm: "DifferentPass123!",
|
||||
use2fa: false
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -186,22 +190,17 @@ public class RegisterEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
|
||||
Assert.Contains("PasswordConfirmCannotBeEmpty", errors["General.Validation"]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user in the database and returns it.
|
||||
/// </summary>
|
||||
/// <returns>The created user entity.</returns>
|
||||
private async Task<UserEntity> CreateTestUser()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
UserEntity user = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Username = _testUsername,
|
||||
Password = new PasswordHashService().HashString("TestPass123!"),
|
||||
Libraries = [],
|
||||
UserPermissions = [],
|
||||
UserRole = null,
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
};
|
||||
UserEntity user = _userEntityFixture.Create(username: _testUsername, password: new PasswordHashService().HashString("TestPass123!"));
|
||||
user.TotpSecret = null;
|
||||
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
+16
-40
@@ -1,6 +1,8 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Authorization;
|
||||
using Lumina.Contracts.Requests.Authorization;
|
||||
using Lumina.Contracts.Responses.Authorization;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
@@ -34,6 +36,11 @@ public class GetAuthorizationEndpointTests : IClassFixture<AuthenticatedLuminaAp
|
||||
private readonly JsonSerializerOptions _jsonOptions;
|
||||
private HttpClient _client;
|
||||
private readonly string _testUsername;
|
||||
private readonly RoleEntityFixture _roleEntityFixture = new();
|
||||
private readonly PermissionEntityFixture _permissionEntityFixture = new();
|
||||
private readonly RolePermissionEntityFixture _rolePermissionEntityFixture = new();
|
||||
private readonly UserRoleEntityFixture _userRoleEntityFixture = new();
|
||||
private readonly GetAuthorizationRequestFixture _getAuthorizationRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetAuthorizationEndpointTests"/> class.
|
||||
@@ -78,7 +85,7 @@ public class GetAuthorizationEndpointTests : IClassFixture<AuthenticatedLuminaAp
|
||||
.ThenInclude(userPermission => userPermission.Permission)
|
||||
.FirstAsync(user => user.Username == _apiFactory.TestUsername);
|
||||
await AddRolesAndPermissionsToUser(user, dbContext);
|
||||
GetAuthorizationRequest request = new(user.Id);
|
||||
GetAuthorizationRequest request = _getAuthorizationRequestFixture.Create(userId: user.Id);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/auth/get-authorization?userId={request.UserId}");
|
||||
@@ -100,7 +107,7 @@ public class GetAuthorizationEndpointTests : IClassFixture<AuthenticatedLuminaAp
|
||||
public async Task GetAuthorization_WhenUserDoesNotExist_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
GetAuthorizationRequest request = new(Guid.NewGuid());
|
||||
GetAuthorizationRequest request = _getAuthorizationRequestFixture.Create(userId: Guid.NewGuid());
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/auth/get-authorization?userId={request.UserId}");
|
||||
@@ -124,7 +131,7 @@ public class GetAuthorizationEndpointTests : IClassFixture<AuthenticatedLuminaAp
|
||||
public async Task GetAuthorization_WhenUserIdIsEmpty_ShouldReturnValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetAuthorizationRequest request = new(Guid.Empty);
|
||||
GetAuthorizationRequest request = _getAuthorizationRequestFixture.Create(userId: Guid.Empty);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/auth/get-authorization?userId={request.UserId}");
|
||||
@@ -153,7 +160,7 @@ public class GetAuthorizationEndpointTests : IClassFixture<AuthenticatedLuminaAp
|
||||
public async Task GetAuthorization_WhenCancellationRequested_ShouldThrowTaskCanceledException()
|
||||
{
|
||||
// Arrange
|
||||
GetAuthorizationRequest request = new(Guid.NewGuid());
|
||||
GetAuthorizationRequest request = _getAuthorizationRequestFixture.Create(userId: Guid.NewGuid());
|
||||
CancellationTokenSource cts = new();
|
||||
|
||||
// Act & Assert
|
||||
@@ -165,40 +172,18 @@ public class GetAuthorizationEndpointTests : IClassFixture<AuthenticatedLuminaAp
|
||||
Assert.IsType<TaskCanceledException>(exception);
|
||||
}
|
||||
|
||||
private static async Task<UserEntity> AddRolesAndPermissionsToUser(UserEntity existingUser, LuminaDbContext dbContext)
|
||||
private async Task<UserEntity> AddRolesAndPermissionsToUser(UserEntity existingUser, LuminaDbContext dbContext)
|
||||
{
|
||||
// create and save role and permission first
|
||||
RoleEntity adminRole = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
RoleName = "Admin",
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
CreatedBy = Guid.NewGuid()
|
||||
};
|
||||
|
||||
PermissionEntity viewUsersPermission = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
PermissionName = AuthorizationPermission.CanViewUsers,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
CreatedBy = Guid.NewGuid()
|
||||
};
|
||||
RoleEntity adminRole = _roleEntityFixture.Create(roleName: "Admin");
|
||||
PermissionEntity viewUsersPermission = _permissionEntityFixture.Create(permissionName: AuthorizationPermission.CanViewUsers);
|
||||
|
||||
await dbContext.Roles.AddAsync(adminRole);
|
||||
await dbContext.Permissions.AddAsync(viewUsersPermission);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
// create role permission
|
||||
RolePermissionEntity rolePermission = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Permission = viewUsersPermission,
|
||||
PermissionId = viewUsersPermission.Id,
|
||||
Role = adminRole,
|
||||
RoleId = adminRole.Id,
|
||||
CreatedBy = existingUser.Id,
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
};
|
||||
RolePermissionEntity rolePermission = _rolePermissionEntityFixture.Create(role: adminRole, permission: viewUsersPermission);
|
||||
await dbContext.RolePermissions.AddAsync(rolePermission);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
@@ -207,16 +192,7 @@ public class GetAuthorizationEndpointTests : IClassFixture<AuthenticatedLuminaAp
|
||||
dbContext.UserRoles.Remove(existingUser.UserRole);
|
||||
|
||||
// add new user role
|
||||
UserRoleEntity userRole = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
User = existingUser,
|
||||
UserId = existingUser.Id,
|
||||
Role = adminRole,
|
||||
RoleId = adminRole.Id,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
CreatedBy = Guid.NewGuid()
|
||||
};
|
||||
UserRoleEntity userRole = _userRoleEntityFixture.Create(user: existingUser, role: adminRole);
|
||||
await dbContext.UserRoles.AddAsync(userRole);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
|
||||
+3
-9
@@ -1,6 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Contracts.Responses.Authorization;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
|
||||
@@ -30,6 +31,7 @@ public class GetUserPermissionsEndpointTests : IClassFixture<AuthenticatedLumina
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly UserPermissionEntityFixture _userPermissionEntityFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
@@ -65,15 +67,7 @@ public class GetUserPermissionsEndpointTests : IClassFixture<AuthenticatedLumina
|
||||
|
||||
// Add a direct user permission
|
||||
PermissionEntity permission = dbContext.Permissions.First();
|
||||
UserPermissionEntity userPermission = new()
|
||||
{
|
||||
UserId = user!.Id,
|
||||
PermissionId = permission.Id,
|
||||
CreatedBy = user.Id,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
User = user,
|
||||
Permission = permission,
|
||||
};
|
||||
UserPermissionEntity userPermission = _userPermissionEntityFixture.Create(user, permission);
|
||||
dbContext.UserPermissions.Add(userPermission);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
|
||||
+30
-45
@@ -1,6 +1,9 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Authorization;
|
||||
using Lumina.Contracts.Requests.Authorization;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
@@ -31,6 +34,9 @@ public class UpdateUserRoleAndPermissionsEndpointTests : IClassFixture<Authentic
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly RoleEntityFixture _roleEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly UpdateUserRoleAndPermissionsRequestFixture _updateUserRoleAndPermissionsRequestFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
@@ -63,37 +69,22 @@ public class UpdateUserRoleAndPermissionsEndpointTests : IClassFixture<Authentic
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
// create a non-admin role first
|
||||
RoleEntity editorRole = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
RoleName = "Editor",
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
};
|
||||
RoleEntity editorRole = _roleEntityFixture.Create(roleName: "Editor");
|
||||
dbContext.Roles.Add(editorRole);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
// create test user
|
||||
UserEntity user = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Username = "TestUser",
|
||||
Password = "HashedPassword",
|
||||
UserRole = null,
|
||||
UserPermissions = [],
|
||||
Libraries = [],
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
};
|
||||
UserEntity user = _userEntityFixture.Create(username: "TestUser", password: "HashedPassword");
|
||||
user.TotpSecret = null;
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
PermissionEntity[] permissions = [.. dbContext.Permissions.Take(2)];
|
||||
|
||||
UpdateUserRoleAndPermissionsRequest request = new(
|
||||
UserId: user.Id,
|
||||
RoleId: editorRole.Id,
|
||||
Permissions: permissions.Select(p => p.Id).ToList()
|
||||
UpdateUserRoleAndPermissionsRequest request = _updateUserRoleAndPermissionsRequestFixture.Create(
|
||||
userId: user.Id,
|
||||
roleId: editorRole.Id,
|
||||
permissions: permissions.Select(p => p.Id).ToList()
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -118,10 +109,10 @@ public class UpdateUserRoleAndPermissionsEndpointTests : IClassFixture<Authentic
|
||||
{
|
||||
// Arrange
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
UpdateUserRoleAndPermissionsRequest request = new(
|
||||
UserId: Guid.NewGuid(),
|
||||
RoleId: Guid.NewGuid(),
|
||||
Permissions: [Guid.NewGuid()]
|
||||
UpdateUserRoleAndPermissionsRequest request = _updateUserRoleAndPermissionsRequestFixture.Create(
|
||||
userId: Guid.NewGuid(),
|
||||
roleId: Guid.NewGuid(),
|
||||
permissions: [Guid.NewGuid()]
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -150,23 +141,17 @@ public class UpdateUserRoleAndPermissionsEndpointTests : IClassFixture<Authentic
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
// create Editor role
|
||||
RoleEntity editorRole = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
RoleName = "Editor",
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
};
|
||||
RoleEntity editorRole = _roleEntityFixture.Create(roleName: "Editor");
|
||||
dbContext.Roles.Add(editorRole);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
// get the admin user that was created by CreateAuthenticatedAdminClientAsync
|
||||
UserEntity? adminUser = dbContext.Users.FirstOrDefault(u => u.UserRole!.Role.RoleName == "Admin");
|
||||
Assert.NotNull(adminUser);
|
||||
UpdateUserRoleAndPermissionsRequest request = new(
|
||||
UserId: adminUser!.Id,
|
||||
RoleId: editorRole.Id,
|
||||
Permissions: []
|
||||
UpdateUserRoleAndPermissionsRequest request = _updateUserRoleAndPermissionsRequestFixture.Create(
|
||||
userId: adminUser!.Id,
|
||||
roleId: editorRole.Id,
|
||||
permissions: []
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -192,10 +177,10 @@ public class UpdateUserRoleAndPermissionsEndpointTests : IClassFixture<Authentic
|
||||
{
|
||||
// Arrange
|
||||
Guid nonExistentUserId = Guid.NewGuid();
|
||||
UpdateUserRoleAndPermissionsRequest request = new(
|
||||
UserId: nonExistentUserId,
|
||||
RoleId: Guid.NewGuid(),
|
||||
Permissions: [Guid.NewGuid()]
|
||||
UpdateUserRoleAndPermissionsRequest request = _updateUserRoleAndPermissionsRequestFixture.Create(
|
||||
userId: nonExistentUserId,
|
||||
roleId: Guid.NewGuid(),
|
||||
permissions: [Guid.NewGuid()]
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -221,10 +206,10 @@ public class UpdateUserRoleAndPermissionsEndpointTests : IClassFixture<Authentic
|
||||
{
|
||||
// Arrange
|
||||
using CancellationTokenSource cts = new();
|
||||
UpdateUserRoleAndPermissionsRequest request = new(
|
||||
UserId: Guid.NewGuid(),
|
||||
RoleId: Guid.NewGuid(),
|
||||
Permissions: [Guid.NewGuid()]
|
||||
UpdateUserRoleAndPermissionsRequest request = _updateUserRoleAndPermissionsRequestFixture.Create(
|
||||
userId: Guid.NewGuid(),
|
||||
roleId: Guid.NewGuid(),
|
||||
permissions: [Guid.NewGuid()]
|
||||
);
|
||||
|
||||
// Act & Assert
|
||||
|
||||
+7
-4
@@ -1,7 +1,8 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Authorization;
|
||||
using Lumina.Presentation.Web.Common.Responses.Authorization;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.GetRoles;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
@@ -21,6 +22,8 @@ namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Authoriz
|
||||
public class GetRolesEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new();
|
||||
private readonly RoleDtoFixture _roleDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetRolesEndpointTests"/> class.
|
||||
@@ -36,8 +39,8 @@ public class GetRolesEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.AuthorizationResponse = new GetAuthorizationResponse(Guid.NewGuid(), "Admin", []);
|
||||
RoleDto[] expectedRoles = [new RoleDto(Guid.NewGuid(), "Admin"), new RoleDto(Guid.NewGuid(), "User")];
|
||||
_apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []);
|
||||
RoleDto[] expectedRoles = [_roleDtoFixture.Create(id: Guid.NewGuid(), roleName: "Admin"), _roleDtoFixture.Create(id: Guid.NewGuid(), roleName: "User")];
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse("auth/roles", expectedRoles);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
@@ -57,7 +60,7 @@ public class GetRolesEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.AuthorizationResponse = new GetAuthorizationResponse(Guid.NewGuid(), "User", []);
|
||||
_apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
|
||||
+4
-2
@@ -1,6 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraries;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
@@ -20,6 +21,7 @@ namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Manage
|
||||
public class GetLibrariesEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly LibraryDtoFixture _libraryDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibrariesEndpointTests"/> class.
|
||||
@@ -37,8 +39,8 @@ public class GetLibrariesEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
LibraryDto[] expectedLibraries =
|
||||
[
|
||||
new LibraryDto { Id = Guid.NewGuid(), Title = "Books", LibraryType = "Book" },
|
||||
new LibraryDto { Id = Guid.NewGuid(), Title = "Movies", LibraryType = "Video" }
|
||||
_libraryDtoFixture.Create(id: Guid.NewGuid(), title: "Books", libraryType: "Book"),
|
||||
_libraryDtoFixture.Create(id: Guid.NewGuid(), title: "Movies", libraryType: "Video")
|
||||
];
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse("libraries", expectedLibraries);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
+6
-3
@@ -1,6 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.SaveLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
@@ -22,6 +23,7 @@ namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Manage
|
||||
public class SaveLibraryEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly LibraryDtoFixture _libraryDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SaveLibraryEndpointTests"/> class.
|
||||
@@ -37,8 +39,9 @@ public class SaveLibraryEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
LibraryDto request = new() { Title = "New Books Library", LibraryType = "Book" };
|
||||
LibraryDto expectedResponse = new() { Id = Guid.NewGuid(), Title = request.Title, LibraryType = request.LibraryType };
|
||||
LibraryDto request = _libraryDtoFixture.Create(title: "New Books Library", libraryType: "Book");
|
||||
request.Id = null;
|
||||
LibraryDto expectedResponse = _libraryDtoFixture.Create(id: Guid.NewGuid(), title: request.Title, libraryType: request.LibraryType);
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse("libraries", expectedResponse);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage saveRequest = new(HttpMethod.Post, "/en-us/libraries/manage/api-item")
|
||||
@@ -69,7 +72,7 @@ public class SaveLibraryEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage saveRequest = new(HttpMethod.Post, "/en-us/libraries/manage/api-item")
|
||||
{
|
||||
Content = JsonContent.Create(new LibraryDto { Title = "New Books Library", LibraryType = "Book" })
|
||||
Content = JsonContent.Create(_libraryDtoFixture.Create(title: "New Books Library", libraryType: "Book"))
|
||||
};
|
||||
saveRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
saveRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
+22
-13
@@ -3,13 +3,13 @@ using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Common.Requests.UsersManagement;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.Login;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
@@ -27,6 +27,8 @@ namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.UsersManagemen
|
||||
public class LoginEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly LoginRequestFixture _loginRequestFixture = new();
|
||||
private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LoginEndpointTests"/> class.
|
||||
@@ -44,7 +46,7 @@ public class LoginEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client);
|
||||
HttpRequestMessage loginRequest = CreateLoginRequest(new LoginRequest(Username: "testuser", Password: "TestPass123!"), antiforgeryToken);
|
||||
HttpRequestMessage loginRequest = CreateLoginRequest(_loginRequestFixture.Create(username: "testuser", password: "TestPass123!"), antiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.SendAsync(loginRequest);
|
||||
@@ -65,19 +67,15 @@ public class LoginEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
ProblemDetailsDto problemDetails = new()
|
||||
ProblemDetailsDto problemDetails = _problemDetailsDtoFixture.Create(title: "General.Validation", detail: "OneOrMoreValidationErrorsOccurred");
|
||||
problemDetails.Extensions = new Dictionary<string, JsonElement>
|
||||
{
|
||||
Title = "General.Validation",
|
||||
Detail = "OneOrMoreValidationErrorsOccurred",
|
||||
Extensions = new Dictionary<string, JsonElement>
|
||||
{
|
||||
["errors"] = CreateErrorsElement(["InvalidTotpCode"])
|
||||
}
|
||||
["errors"] = CreateErrorsElement(["InvalidTotpCode"])
|
||||
};
|
||||
_apiFactory.ApiClientStub.RegisterPostException("auth/login", new ApiException(problemDetails, HttpStatusCode.UnprocessableEntity, "auth/login"));
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client);
|
||||
HttpRequestMessage loginRequest = CreateLoginRequest(new LoginRequest(Username: "testuser", Password: "TestPass123!"), antiforgeryToken);
|
||||
HttpRequestMessage loginRequest = CreateLoginRequest(_loginRequestFixture.Create(username: "testuser", password: "TestPass123!"), antiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.SendAsync(loginRequest);
|
||||
@@ -94,10 +92,10 @@ public class LoginEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.RegisterPostException("auth/login", new ApiException(new ProblemDetailsDto { Title = "General.Failure", Detail = "InvalidUsernameOrPassword" }, HttpStatusCode.Forbidden, "auth/login"));
|
||||
_apiFactory.ApiClientStub.RegisterPostException("auth/login", new ApiException(_problemDetailsDtoFixture.Create(title: "General.Failure", detail: "InvalidUsernameOrPassword"), HttpStatusCode.Forbidden, "auth/login"));
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client);
|
||||
HttpRequestMessage loginRequest = CreateLoginRequest(new LoginRequest(Username: "testuser", Password: "WrongPass123!"), antiforgeryToken);
|
||||
HttpRequestMessage loginRequest = CreateLoginRequest(_loginRequestFixture.Create(username: "testuser", password: "WrongPass123!"), antiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.SendAsync(loginRequest);
|
||||
@@ -109,6 +107,12 @@ public class LoginEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
Assert.Contains("<b>", json.RootElement.GetProperty("errorMessage").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the login request that sends the given <paramref name="request"/> to the login endpoint.
|
||||
/// </summary>
|
||||
/// <param name="request">The login request to send.</param>
|
||||
/// <param name="antiforgeryToken">The antiforgery token to include in the request.</param>
|
||||
/// <returns>The configured login request.</returns>
|
||||
private static HttpRequestMessage CreateLoginRequest(LoginRequest request, string antiforgeryToken)
|
||||
{
|
||||
HttpRequestMessage loginRequest = new(HttpMethod.Post, "/en-us/auth/api-login")
|
||||
@@ -121,6 +125,11 @@ public class LoginEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
return loginRequest;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds a JSON element that contains a validation error collection carrying the given <paramref name="errorCodes"/>.
|
||||
/// </summary>
|
||||
/// <param name="errorCodes">The error codes to include in the collection.</param>
|
||||
/// <returns>The built JSON element.</returns>
|
||||
private static JsonElement CreateErrorsElement(string[] errorCodes)
|
||||
{
|
||||
using MemoryStream stream = new();
|
||||
|
||||
+21
-66
@@ -1,9 +1,11 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Authentication;
|
||||
using Lumina.Contracts.Responses.Authentication;
|
||||
using Lumina.DataAccess.Common.Interceptors;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
@@ -18,7 +20,6 @@ using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text;
|
||||
@@ -36,10 +37,16 @@ public class LuminaApiFactory : WebApplicationFactory<Program>, IDisposable
|
||||
private readonly SqliteConnection _connection;
|
||||
private readonly string _sharedInMemoryConnectionString;
|
||||
private readonly PasswordHashService _hashService = new();
|
||||
private readonly LoginRequestFixture _loginRequestFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly RoleEntityFixture _roleEntityFixture = new();
|
||||
private readonly UserRoleEntityFixture _userRoleEntityFixture = new();
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
private const string TEST_ENCRYPTION_KEY = "MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=";
|
||||
private const string SHARED_IN_MEMORY_CONNECTION_STRING_PREFIX = "Data Source=lumina-tests-{0};Mode=Memory;Cache=Shared";
|
||||
|
||||
@@ -145,43 +152,19 @@ public class LuminaApiFactory : WebApplicationFactory<Program>, IDisposable
|
||||
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"testuser_{Guid.NewGuid()}";
|
||||
UserEntity user = new()
|
||||
{
|
||||
Id = userId,
|
||||
Username = username,
|
||||
Password = _hashService.HashString("TestPass123!"),
|
||||
Libraries = [],
|
||||
UserPermissions = [],
|
||||
UserRole = null,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
};
|
||||
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: _hashService.HashString("TestPass123!"));
|
||||
user.TotpSecret = null;
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
// seed a dedicated Admin role for this test user, keeping each test isolated in the shared in-memory database
|
||||
Guid roleId = Guid.NewGuid();
|
||||
RoleEntity role = new()
|
||||
{
|
||||
Id = roleId,
|
||||
RoleName = "Admin",
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
};
|
||||
RoleEntity role = _roleEntityFixture.Create(id: roleId, roleName: "Admin", createdBy: userId, createdOnUtc: DateTime.UtcNow);
|
||||
dbContext.Roles.Add(role);
|
||||
dbContext.UserRoles.Add(new UserRoleEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = userId,
|
||||
User = user,
|
||||
RoleId = roleId,
|
||||
Role = role,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
});
|
||||
dbContext.UserRoles.Add(_userRoleEntityFixture.Create(userId: userId, user: user, roleId: roleId, role: role));
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(username, "TestPass123!"));
|
||||
HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", _loginRequestFixture.Create(username: username, password: "TestPass123!"));
|
||||
string content = await loginResponse.Content.ReadAsStringAsync();
|
||||
LoginResponse? loginResult = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
|
||||
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token);
|
||||
@@ -205,21 +188,12 @@ public class LuminaApiFactory : WebApplicationFactory<Program>, IDisposable
|
||||
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"testuser_{Guid.NewGuid()}";
|
||||
UserEntity user = new()
|
||||
{
|
||||
Id = userId,
|
||||
Username = username,
|
||||
Password = _hashService.HashString("TestPass123!"),
|
||||
Libraries = [],
|
||||
UserPermissions = [],
|
||||
UserRole = null,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
};
|
||||
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: _hashService.HashString("TestPass123!"));
|
||||
user.TotpSecret = null;
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(username, "TestPass123!"));
|
||||
HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", _loginRequestFixture.Create(username: username, password: "TestPass123!"));
|
||||
string content = await loginResponse.Content.ReadAsStringAsync();
|
||||
LoginResponse? loginResult = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
|
||||
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token);
|
||||
@@ -277,17 +251,7 @@ public class LuminaApiFactory : WebApplicationFactory<Program>, IDisposable
|
||||
{
|
||||
using IServiceScope scope = Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Libraries.Add(new LibraryEntity
|
||||
{
|
||||
Id = libraryId,
|
||||
UserId = userId,
|
||||
Title = "Test Library",
|
||||
LibraryType = LibraryType.EBook,
|
||||
ContentLocations = [],
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
@@ -300,16 +264,7 @@ public class LuminaApiFactory : WebApplicationFactory<Program>, IDisposable
|
||||
{
|
||||
using IServiceScope scope = Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Books.Add(new BookEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
LibraryId = libraryId,
|
||||
Path = $"/books/{Guid.NewGuid()}.epub",
|
||||
Title = title,
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
dbContext.Books.Add(_bookEntityFixture.Create(libraryId: libraryId, title: title, path: $"/books/{Guid.NewGuid()}.epub", includeMetadata: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
|
||||
+6
-14
@@ -1,19 +1,16 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Admin.Authorization.Roles;
|
||||
@@ -22,7 +19,7 @@ namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Admin.Authorizati
|
||||
/// Contains security tests for the <c>/auth/roles</c> route.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddRoleEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
public class AddRoleEndpointTests : IClassFixture<LuminaApiFactory>, IAsyncDisposable
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
@@ -33,6 +30,7 @@ public class AddRoleEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
private Guid _adminUserId;
|
||||
private Guid _seededPermissionId;
|
||||
private string _createdRoleName = "";
|
||||
private readonly PermissionEntityFixture _permissionEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddRoleEndpointTests"/> class.
|
||||
@@ -84,13 +82,7 @@ public class AddRoleEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
using (IServiceScope seedScope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext seedDbContext = seedScope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
seedDbContext.Permissions.Add(new PermissionEntity
|
||||
{
|
||||
Id = _seededPermissionId,
|
||||
PermissionName = AuthorizationPermission.CanDeleteUsers,
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
});
|
||||
seedDbContext.Permissions.Add(_permissionEntityFixture.Create(id: _seededPermissionId, permissionName: AuthorizationPermission.CanDeleteUsers));
|
||||
await seedDbContext.SaveChangesAsync();
|
||||
}
|
||||
var requestBody = new
|
||||
@@ -118,7 +110,7 @@ public class AddRoleEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
@@ -137,6 +129,6 @@ public class AddRoleEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
}
|
||||
dbContext.SaveChanges();
|
||||
if (_adminUserId != Guid.Empty)
|
||||
_apiFactory.RemoveAdminUserAsync(_adminUserId).GetAwaiter().GetResult();
|
||||
await _apiFactory.RemoveAdminUserAsync(_adminUserId).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
+18
-29
@@ -1,5 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Authorization;
|
||||
using Lumina.Contracts.Requests.Authorization;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
|
||||
@@ -7,14 +9,10 @@ using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Admin.Authorization.Roles;
|
||||
@@ -23,7 +21,7 @@ namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Admin.Authorizati
|
||||
/// Contains security tests for the <c>/auth/roles</c> route.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateRoleEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
public class UpdateRoleEndpointTests : IClassFixture<LuminaApiFactory>, IAsyncDisposable
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
@@ -34,6 +32,9 @@ public class UpdateRoleEndpointTests : IClassFixture<LuminaApiFactory>, IDisposa
|
||||
private Guid _adminUserId;
|
||||
private Guid _seededPermissionId;
|
||||
private Guid _seededRoleId;
|
||||
private readonly RoleEntityFixture _roleEntityFixture = new();
|
||||
private readonly PermissionEntityFixture _permissionEntityFixture = new();
|
||||
private readonly UpdateRoleRequestFixture _updateRoleRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateRoleEndpointTests"/> class.
|
||||
@@ -49,10 +50,10 @@ public class UpdateRoleEndpointTests : IClassFixture<LuminaApiFactory>, IDisposa
|
||||
public async Task UpdateRole_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
UpdateRoleRequest requestBody = new(
|
||||
RoleId: Guid.NewGuid(),
|
||||
RoleName: "Editor",
|
||||
Permissions: []
|
||||
UpdateRoleRequest requestBody = _updateRoleRequestFixture.Create(
|
||||
roleId: Guid.NewGuid(),
|
||||
roleName: "Editor",
|
||||
permissions: []
|
||||
);
|
||||
|
||||
StringContent content = new(
|
||||
@@ -88,30 +89,18 @@ public class UpdateRoleEndpointTests : IClassFixture<LuminaApiFactory>, IDisposa
|
||||
_adminUserId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
|
||||
_seededPermissionId = Guid.NewGuid();
|
||||
_seededRoleId = Guid.NewGuid();
|
||||
RoleEntity seededRole = new()
|
||||
{
|
||||
Id = _seededRoleId,
|
||||
RoleName = "ExistingRole",
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
};
|
||||
RoleEntity seededRole = _roleEntityFixture.Create(id: _seededRoleId, roleName: "ExistingRole");
|
||||
using (IServiceScope seedScope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext seedDbContext = seedScope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
seedDbContext.Permissions.Add(new PermissionEntity
|
||||
{
|
||||
Id = _seededPermissionId,
|
||||
PermissionName = AuthorizationPermission.CanDeleteUsers,
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
});
|
||||
seedDbContext.Permissions.Add(_permissionEntityFixture.Create(id: _seededPermissionId, permissionName: AuthorizationPermission.CanDeleteUsers));
|
||||
seedDbContext.Roles.Add(seededRole);
|
||||
await seedDbContext.SaveChangesAsync();
|
||||
}
|
||||
UpdateRoleRequest requestBody = new(
|
||||
RoleId: seededRole.Id,
|
||||
RoleName: maliciousRoleName,
|
||||
Permissions: [_seededPermissionId]
|
||||
UpdateRoleRequest requestBody = _updateRoleRequestFixture.Create(
|
||||
roleId: seededRole.Id,
|
||||
roleName: maliciousRoleName,
|
||||
permissions: [_seededPermissionId]
|
||||
);
|
||||
StringContent content = new(JsonSerializer.Serialize(requestBody), Encoding.UTF8, "application/json");
|
||||
|
||||
@@ -134,7 +123,7 @@ public class UpdateRoleEndpointTests : IClassFixture<LuminaApiFactory>, IDisposa
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
@@ -153,6 +142,6 @@ public class UpdateRoleEndpointTests : IClassFixture<LuminaApiFactory>, IDisposa
|
||||
}
|
||||
dbContext.SaveChanges();
|
||||
if (_adminUserId != Guid.Empty)
|
||||
_apiFactory.RemoveAdminUserAsync(_adminUserId).GetAwaiter().GetResult();
|
||||
await _apiFactory.RemoveAdminUserAsync(_adminUserId).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
+22
-24
@@ -1,19 +1,16 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.Management;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.AddLibrary;
|
||||
@@ -26,6 +23,7 @@ public class AddLibraryEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly AddLibraryRequestFixture _addLibraryRequestFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
@@ -45,16 +43,16 @@ public class AddLibraryEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
public async Task AddLibrary_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
AddLibraryRequest request = new(
|
||||
Title: "New Library",
|
||||
LibraryType: "EBook",
|
||||
ContentLocations: ["C:/Media"],
|
||||
CoverImage: null,
|
||||
IsEnabled: true,
|
||||
IsLocked: false,
|
||||
DownloadMetadataFromWeb: true,
|
||||
ShouldSaveMetadataInMediaDirectories: false,
|
||||
ShouldSkipUnchangedDirectoriesDuringScan: true
|
||||
AddLibraryRequest request = _addLibraryRequestFixture.Create(
|
||||
title: "New Library",
|
||||
libraryType: "EBook",
|
||||
contentLocations: ["C:/Media"],
|
||||
coverImage: null,
|
||||
isEnabled: true,
|
||||
isLocked: false,
|
||||
canDownloadMetadataFromWeb: true,
|
||||
shouldSaveMetadataInMediaDirectories: false,
|
||||
shouldSkipUnchangedDirectoriesDuringScan: true
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -82,16 +80,16 @@ public class AddLibraryEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
|
||||
AddLibraryRequest request = new(
|
||||
Title: maliciousTitle,
|
||||
LibraryType: "EBook",
|
||||
ContentLocations: ["C:/Media"],
|
||||
CoverImage: null,
|
||||
IsEnabled: true,
|
||||
IsLocked: false,
|
||||
DownloadMetadataFromWeb: true,
|
||||
ShouldSaveMetadataInMediaDirectories: false,
|
||||
ShouldSkipUnchangedDirectoriesDuringScan: true
|
||||
AddLibraryRequest request = _addLibraryRequestFixture.Create(
|
||||
title: maliciousTitle,
|
||||
libraryType: "EBook",
|
||||
contentLocations: ["C:/Media"],
|
||||
coverImage: null,
|
||||
isEnabled: true,
|
||||
isLocked: false,
|
||||
canDownloadMetadataFromWeb: true,
|
||||
shouldSaveMetadataInMediaDirectories: false,
|
||||
shouldSkipUnchangedDirectoriesDuringScan: true
|
||||
);
|
||||
|
||||
// Act
|
||||
|
||||
+8
-17
@@ -1,21 +1,18 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Authentication;
|
||||
using Lumina.Contracts.Responses.Authentication;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Infrastructure.Core.Security;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.CancelLibrariesScan;
|
||||
@@ -33,6 +30,8 @@ public class CancelLibrariesScanEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly LoginRequestFixture _loginRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CancelLibrariesScanEndpointTests"/> class.
|
||||
@@ -96,20 +95,12 @@ public class CancelLibrariesScanEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"testuser_{Guid.NewGuid()}";
|
||||
dbContext.Users.Add(new UserEntity
|
||||
{
|
||||
Id = userId,
|
||||
Username = username,
|
||||
Password = _hashService.HashString("TestPass123!"),
|
||||
Libraries = [],
|
||||
UserPermissions = [],
|
||||
UserRole = null,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
});
|
||||
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: _hashService.HashString("TestPass123!"));
|
||||
user.TotpSecret = null;
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(username, "TestPass123!"));
|
||||
HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", _loginRequestFixture.Create(username: username, password: "TestPass123!"));
|
||||
string content = await loginResponse.Content.ReadAsStringAsync();
|
||||
LoginResponse? loginResult = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
|
||||
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token);
|
||||
|
||||
+3
-17
@@ -1,19 +1,14 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.CancelLibraryScan;
|
||||
@@ -30,6 +25,7 @@ public class CancelLibraryScanEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CancelLibraryScanEndpointTests"/> class.
|
||||
@@ -101,17 +97,7 @@ public class CancelLibraryScanEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Libraries.Add(new LibraryEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = userId,
|
||||
Title = "Test Library",
|
||||
LibraryType = LibraryType.EBook,
|
||||
ContentLocations = [],
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
+3
-18
@@ -1,19 +1,13 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.DeleteLibrary;
|
||||
@@ -30,6 +24,7 @@ public class DeleteLibraryEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteLibraryEndpointTests"/> class.
|
||||
@@ -100,17 +95,7 @@ public class DeleteLibraryEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Libraries.Add(new LibraryEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = userId,
|
||||
Title = "Test Library",
|
||||
LibraryType = LibraryType.EBook,
|
||||
ContentLocations = [],
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
+8
-17
@@ -1,21 +1,18 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Authentication;
|
||||
using Lumina.Contracts.Responses.Authentication;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Infrastructure.Core.Security;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.GetEnabledLibraries;
|
||||
@@ -33,6 +30,8 @@ public class GetEnabledLibrariesEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly LoginRequestFixture _loginRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetEnabledLibrariesEndpointTests"/> class.
|
||||
@@ -97,20 +96,12 @@ public class GetEnabledLibrariesEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"testuser_{Guid.NewGuid()}";
|
||||
dbContext.Users.Add(new UserEntity
|
||||
{
|
||||
Id = userId,
|
||||
Username = username,
|
||||
Password = _hashService.HashString("TestPass123!"),
|
||||
Libraries = [],
|
||||
UserPermissions = [],
|
||||
UserRole = null,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
});
|
||||
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: _hashService.HashString("TestPass123!"));
|
||||
user.TotpSecret = null;
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(username, "TestPass123!"));
|
||||
HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", _loginRequestFixture.Create(username: username, password: "TestPass123!"));
|
||||
string content = await loginResponse.Content.ReadAsStringAsync();
|
||||
LoginResponse? loginResult = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
|
||||
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token);
|
||||
|
||||
+8
-17
@@ -1,21 +1,18 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Authentication;
|
||||
using Lumina.Contracts.Responses.Authentication;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Infrastructure.Core.Security;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.GetLibraries;
|
||||
@@ -33,6 +30,8 @@ public class GetLibrariesEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly LoginRequestFixture _loginRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibrariesEndpointTests"/> class.
|
||||
@@ -97,20 +96,12 @@ public class GetLibrariesEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"testuser_{Guid.NewGuid()}";
|
||||
dbContext.Users.Add(new UserEntity
|
||||
{
|
||||
Id = userId,
|
||||
Username = username,
|
||||
Password = _hashService.HashString("TestPass123!"),
|
||||
Libraries = [],
|
||||
UserPermissions = [],
|
||||
UserRole = null,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
});
|
||||
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: _hashService.HashString("TestPass123!"));
|
||||
user.TotpSecret = null;
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(username, "TestPass123!"));
|
||||
HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", _loginRequestFixture.Create(username: username, password: "TestPass123!"));
|
||||
string content = await loginResponse.Content.ReadAsStringAsync();
|
||||
LoginResponse? loginResult = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
|
||||
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token);
|
||||
|
||||
+11
-30
@@ -1,24 +1,20 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Authentication;
|
||||
using Lumina.Contracts.Responses.Authentication;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Infrastructure.Core.Security;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.GetLibrary;
|
||||
@@ -36,6 +32,9 @@ public class GetLibraryEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly LoginRequestFixture _loginRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibraryEndpointTests"/> class.
|
||||
@@ -127,17 +126,7 @@ public class GetLibraryEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Libraries.Add(new LibraryEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = userId,
|
||||
Title = "Test Library",
|
||||
LibraryType = LibraryType.EBook,
|
||||
ContentLocations = [],
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
@@ -155,20 +144,12 @@ public class GetLibraryEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"testuser_{Guid.NewGuid()}";
|
||||
dbContext.Users.Add(new UserEntity
|
||||
{
|
||||
Id = userId,
|
||||
Username = username,
|
||||
Password = _hashService.HashString("TestPass123!"),
|
||||
Libraries = [],
|
||||
UserPermissions = [],
|
||||
UserRole = null,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
});
|
||||
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: _hashService.HashString("TestPass123!"));
|
||||
user.TotpSecret = null;
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(username, "TestPass123!"));
|
||||
HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", _loginRequestFixture.Create(username: username, password: "TestPass123!"));
|
||||
string content = await loginResponse.Content.ReadAsStringAsync();
|
||||
LoginResponse? loginResult = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
|
||||
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token);
|
||||
|
||||
+3
-17
@@ -1,18 +1,13 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.GetLibraryScanProgress;
|
||||
@@ -29,6 +24,7 @@ public class GetLibraryScanProgressEndpointTests : IClassFixture<LuminaApiFactor
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibraryScanProgressEndpointTests"/> class.
|
||||
@@ -100,17 +96,7 @@ public class GetLibraryScanProgressEndpointTests : IClassFixture<LuminaApiFactor
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Libraries.Add(new LibraryEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = userId,
|
||||
Title = "Test Library",
|
||||
LibraryType = LibraryType.EBook,
|
||||
ContentLocations = [],
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
+8
-17
@@ -1,21 +1,18 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Authentication;
|
||||
using Lumina.Contracts.Responses.Authentication;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Infrastructure.Core.Security;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.GetRunningLibraryScans;
|
||||
@@ -33,6 +30,8 @@ public class GetRunningLibraryScansEndpointTests : IClassFixture<LuminaApiFactor
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly LoginRequestFixture _loginRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetRunningLibraryScansEndpointTests"/> class.
|
||||
@@ -97,20 +96,12 @@ public class GetRunningLibraryScansEndpointTests : IClassFixture<LuminaApiFactor
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"testuser_{Guid.NewGuid()}";
|
||||
dbContext.Users.Add(new UserEntity
|
||||
{
|
||||
Id = userId,
|
||||
Username = username,
|
||||
Password = _hashService.HashString("TestPass123!"),
|
||||
Libraries = [],
|
||||
UserPermissions = [],
|
||||
UserRole = null,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
});
|
||||
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: _hashService.HashString("TestPass123!"));
|
||||
user.TotpSecret = null;
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(username, "TestPass123!"));
|
||||
HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", _loginRequestFixture.Create(username: username, password: "TestPass123!"));
|
||||
string content = await loginResponse.Content.ReadAsStringAsync();
|
||||
LoginResponse? loginResult = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
|
||||
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token);
|
||||
|
||||
+8
-17
@@ -1,21 +1,18 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Authentication;
|
||||
using Lumina.Contracts.Responses.Authentication;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Infrastructure.Core.Security;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.ScanLibraries;
|
||||
@@ -33,6 +30,8 @@ public class ScanLibrariesEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly LoginRequestFixture _loginRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ScanLibrariesEndpointTests"/> class.
|
||||
@@ -96,20 +95,12 @@ public class ScanLibrariesEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"testuser_{Guid.NewGuid()}";
|
||||
dbContext.Users.Add(new UserEntity
|
||||
{
|
||||
Id = userId,
|
||||
Username = username,
|
||||
Password = _hashService.HashString("TestPass123!"),
|
||||
Libraries = [],
|
||||
UserPermissions = [],
|
||||
UserRole = null,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
});
|
||||
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: _hashService.HashString("TestPass123!"));
|
||||
user.TotpSecret = null;
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(username, "TestPass123!"));
|
||||
HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", _loginRequestFixture.Create(username: username, password: "TestPass123!"));
|
||||
string content = await loginResponse.Content.ReadAsStringAsync();
|
||||
LoginResponse? loginResult = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
|
||||
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token);
|
||||
|
||||
+3
-17
@@ -1,19 +1,14 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.ScanLibrary;
|
||||
@@ -30,6 +25,7 @@ public class ScanLibraryEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ScanLibraryEndpointTests"/> class.
|
||||
@@ -100,17 +96,7 @@ public class ScanLibraryEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Libraries.Add(new LibraryEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = userId,
|
||||
Title = "Test Library",
|
||||
LibraryType = LibraryType.EBook,
|
||||
ContentLocations = [],
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
+29
-39
@@ -1,5 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.Management;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
@@ -7,14 +9,10 @@ using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.UpdateLibrary;
|
||||
@@ -31,6 +29,8 @@ public class UpdateLibraryEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly UpdateLibraryRequestFixture _updateLibraryRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateLibraryEndpointTests"/> class.
|
||||
@@ -47,18 +47,18 @@ public class UpdateLibraryEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
// Arrange
|
||||
string libraryId = Guid.NewGuid().ToString();
|
||||
UpdateLibraryRequest request = new(
|
||||
Id: Guid.NewGuid(),
|
||||
UserId: Guid.NewGuid(),
|
||||
Title: "Updated Library",
|
||||
LibraryType: "EBook",
|
||||
ContentLocations: ["C:/Media"],
|
||||
CoverImage: null,
|
||||
IsEnabled: true,
|
||||
IsLocked: false,
|
||||
DownloadMetadataFromWeb: true,
|
||||
ShouldSaveMetadataInMediaDirectories: false,
|
||||
ShouldSkipUnchangedDirectoriesDuringScan: true
|
||||
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
|
||||
id: Guid.NewGuid(),
|
||||
userId: Guid.NewGuid(),
|
||||
title: "Updated Library",
|
||||
libraryType: "EBook",
|
||||
contentLocations: ["C:/Media"],
|
||||
coverImage: null,
|
||||
isEnabled: true,
|
||||
isLocked: false,
|
||||
canDownloadMetadataFromWeb: true,
|
||||
shouldSaveMetadataInMediaDirectories: false,
|
||||
shouldSkipUnchangedDirectoriesDuringScan: true
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -88,18 +88,18 @@ public class UpdateLibraryEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
await SeedLibraryAsync(libraryId, userId);
|
||||
UpdateLibraryRequest request = new(
|
||||
Id: libraryId,
|
||||
UserId: userId,
|
||||
Title: maliciousTitle,
|
||||
LibraryType: "EBook",
|
||||
ContentLocations: ["C:/Media"],
|
||||
CoverImage: null,
|
||||
IsEnabled: true,
|
||||
IsLocked: false,
|
||||
DownloadMetadataFromWeb: true,
|
||||
ShouldSaveMetadataInMediaDirectories: false,
|
||||
ShouldSkipUnchangedDirectoriesDuringScan: true
|
||||
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
|
||||
id: libraryId,
|
||||
userId: userId,
|
||||
title: maliciousTitle,
|
||||
libraryType: "EBook",
|
||||
contentLocations: ["C:/Media"],
|
||||
coverImage: null,
|
||||
isEnabled: true,
|
||||
isLocked: false,
|
||||
canDownloadMetadataFromWeb: true,
|
||||
shouldSaveMetadataInMediaDirectories: false,
|
||||
shouldSkipUnchangedDirectoriesDuringScan: true
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -132,17 +132,7 @@ public class UpdateLibraryEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Libraries.Add(new LibraryEntity
|
||||
{
|
||||
Id = libraryId,
|
||||
UserId = userId,
|
||||
Title = "Test Library",
|
||||
LibraryType = LibraryType.EBook,
|
||||
ContentLocations = [],
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
+31
-25
@@ -1,5 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Authentication;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using Lumina.Contracts.Responses.Authentication;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
@@ -26,6 +28,8 @@ public class ChangePasswordEndpointTests : IClassFixture<LuminaApiFactory>, IDis
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly HttpClient _client;
|
||||
private readonly PasswordHashService _hashService = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly ChangePasswordRequestFixture _changePasswordRequestFixture = new();
|
||||
private readonly string _testUsername;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
@@ -49,11 +53,11 @@ public class ChangePasswordEndpointTests : IClassFixture<LuminaApiFactory>, IDis
|
||||
public async Task ChangePassword_WithoutAuthentication_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
ChangePasswordRequest request = new(
|
||||
Username: _testUsername,
|
||||
CurrentPassword: "OldPass123!",
|
||||
NewPassword: "NewPass123!",
|
||||
NewPasswordConfirm: "NewPass123!"
|
||||
ChangePasswordRequest request = _changePasswordRequestFixture.Create(
|
||||
username: _testUsername,
|
||||
currentPassword: "OldPass123!",
|
||||
newPassword: "NewPass123!",
|
||||
newPasswordConfirm: "NewPass123!"
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -78,11 +82,11 @@ public class ChangePasswordEndpointTests : IClassFixture<LuminaApiFactory>, IDis
|
||||
{
|
||||
// Arrange
|
||||
UserEntity user = await CreateAndAuthenticateUser();
|
||||
ChangePasswordRequest request = new(
|
||||
Username: user.Username,
|
||||
CurrentPassword: "WrongPass123!",
|
||||
NewPassword: "NewPass123!",
|
||||
NewPasswordConfirm: "NewPass123!"
|
||||
ChangePasswordRequest request = _changePasswordRequestFixture.Create(
|
||||
username: user.Username,
|
||||
currentPassword: "WrongPass123!",
|
||||
newPassword: "NewPass123!",
|
||||
newPasswordConfirm: "NewPass123!"
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -106,11 +110,11 @@ public class ChangePasswordEndpointTests : IClassFixture<LuminaApiFactory>, IDis
|
||||
// Arrange
|
||||
UserEntity user = await CreateAndAuthenticateUser();
|
||||
string originalPasswordHash = user.Password;
|
||||
ChangePasswordRequest request = new(
|
||||
Username: maliciousUsername,
|
||||
CurrentPassword: "TestPass123!",
|
||||
NewPassword: "NewPass123!",
|
||||
NewPasswordConfirm: "NewPass123!"
|
||||
ChangePasswordRequest request = _changePasswordRequestFixture.Create(
|
||||
username: maliciousUsername,
|
||||
currentPassword: "TestPass123!",
|
||||
newPassword: "NewPass123!",
|
||||
newPasswordConfirm: "NewPass123!"
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -130,6 +134,12 @@ public class ChangePasswordEndpointTests : IClassFixture<LuminaApiFactory>, IDis
|
||||
Assert.Equal(originalPasswordHash, storedUser!.Password);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the given <paramref name="content"/> is a problem detail with the expected title and detail.
|
||||
/// </summary>
|
||||
/// <param name="content">The response content to assert.</param>
|
||||
/// <param name="expectedTitle">The expected title of the problem detail.</param>
|
||||
/// <param name="expectedDetail">The expected detail of the problem detail.</param>
|
||||
private void AssertProblemDetail(string content, string expectedTitle, string expectedDetail)
|
||||
{
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
@@ -138,22 +148,18 @@ public class ChangePasswordEndpointTests : IClassFixture<LuminaApiFactory>, IDis
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user, authenticates it on the client, and returns it.
|
||||
/// </summary>
|
||||
/// <returns>The created user entity.</returns>
|
||||
private async Task<UserEntity> CreateAndAuthenticateUser()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
// create test user
|
||||
UserEntity user = new()
|
||||
{
|
||||
Username = _testUsername,
|
||||
Password = _hashService.HashString("TestPass123!"),
|
||||
Libraries = [],
|
||||
UserRole = null,
|
||||
UserPermissions = [],
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
};
|
||||
UserEntity user = _userEntityFixture.Create(username: _testUsername, password: _hashService.HashString("TestPass123!"));
|
||||
user.TotpSecret = null;
|
||||
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
+40
-33
@@ -2,6 +2,7 @@
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.Infrastructure.Security;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Authentication;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using Lumina.Contracts.Responses.Authentication;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
@@ -29,6 +30,7 @@ public class LoginEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
private readonly PasswordHashService _hashService = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly LoginRequestFixture _loginRequestFixture = new();
|
||||
private readonly ICryptographyService _cryptographyService;
|
||||
private readonly TotpTokenGenerator _totpTokenGenerator = new();
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
@@ -62,9 +64,9 @@ public class LoginEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
// Arrange
|
||||
UserEntity user = await CreateTestUser();
|
||||
LoginRequest request = new(
|
||||
Username: user.Username,
|
||||
Password: "TestPass123!"
|
||||
LoginRequest request = _loginRequestFixture.Create(
|
||||
username: user.Username,
|
||||
password: "TestPass123!"
|
||||
);
|
||||
DateTimeOffset beforeRequest = DateTimeOffset.UtcNow;
|
||||
_client.DefaultRequestHeaders.Clear();
|
||||
@@ -116,13 +118,13 @@ public class LoginEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
// Arrange
|
||||
UserEntity user = await CreateTestUser();
|
||||
LoginRequest unknownUserRequest = new(
|
||||
Username: "nonexistent_user",
|
||||
Password: "TestPass123!"
|
||||
LoginRequest unknownUserRequest = _loginRequestFixture.Create(
|
||||
username: "nonexistent_user",
|
||||
password: "TestPass123!"
|
||||
);
|
||||
LoginRequest wrongPasswordRequest = new(
|
||||
Username: user.Username,
|
||||
Password: "WrongPass123!"
|
||||
LoginRequest wrongPasswordRequest = _loginRequestFixture.Create(
|
||||
username: user.Username,
|
||||
password: "WrongPass123!"
|
||||
);
|
||||
_client.DefaultRequestHeaders.Clear();
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.2");
|
||||
@@ -147,9 +149,9 @@ public class LoginEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
// set a fake IP for this test instance
|
||||
_client.DefaultRequestHeaders.Clear();
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.3");
|
||||
LoginRequest request = new(
|
||||
Username: "testuser",
|
||||
Password: "TestPass123!"
|
||||
LoginRequest request = _loginRequestFixture.Create(
|
||||
username: "testuser",
|
||||
password: "TestPass123!"
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -185,9 +187,9 @@ public class LoginEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
// Arrange
|
||||
UserEntity legitimateUser = await CreateTestUser();
|
||||
LoginRequest request = new(
|
||||
Username: maliciousUsername,
|
||||
Password: "Abcd123$"
|
||||
LoginRequest request = _loginRequestFixture.Create(
|
||||
username: maliciousUsername,
|
||||
password: "Abcd123$"
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -212,9 +214,9 @@ public class LoginEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
// Arrange
|
||||
UserEntity user = await CreateTestUser();
|
||||
LoginRequest request = new(
|
||||
Username: user.Username,
|
||||
Password: "' OR '1'='1"
|
||||
LoginRequest request = _loginRequestFixture.Create(
|
||||
username: user.Username,
|
||||
password: "' OR '1'='1"
|
||||
);
|
||||
_client.DefaultRequestHeaders.Clear();
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.11");
|
||||
@@ -234,10 +236,10 @@ public class LoginEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
// Arrange
|
||||
UserEntity user = await CreateTestUserWithTotp();
|
||||
LoginRequest request = new(
|
||||
Username: user.Username,
|
||||
Password: "TestPass123!",
|
||||
TotpCode: "' OR '1'='1"
|
||||
LoginRequest request = _loginRequestFixture.Create(
|
||||
username: user.Username,
|
||||
password: "TestPass123!",
|
||||
totpCode: "' OR '1'='1"
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -250,6 +252,12 @@ public class LoginEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
Assert.DoesNotContain("Exception", content);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the given <paramref name="content"/> is a problem detail with the expected title and detail.
|
||||
/// </summary>
|
||||
/// <param name="content">The response content to assert.</param>
|
||||
/// <param name="expectedTitle">The expected title of the problem detail.</param>
|
||||
/// <param name="expectedDetail">The expected detail of the problem detail.</param>
|
||||
private void AssertProblemDetail(string content, string expectedTitle, string expectedDetail)
|
||||
{
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
@@ -258,6 +266,10 @@ public class LoginEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user without a TOTP secret in the database and returns it.
|
||||
/// </summary>
|
||||
/// <returns>The created user entity.</returns>
|
||||
private async Task<UserEntity> CreateTestUser()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
@@ -271,23 +283,18 @@ public class LoginEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
return user;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user with a TOTP secret in the database and returns it.
|
||||
/// </summary>
|
||||
/// <returns>The created user entity.</returns>
|
||||
private async Task<UserEntity> CreateTestUserWithTotp()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
byte[] totpSecret = _totpTokenGenerator.GenerateSecret();
|
||||
UserEntity user = new()
|
||||
{
|
||||
Username = _testUsername,
|
||||
Password = _hashService.HashString("TestPass123!"),
|
||||
TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(totpSecret)),
|
||||
Libraries = [],
|
||||
UserPermissions = [],
|
||||
UserRole = null,
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
};
|
||||
UserEntity user = _userEntityFixture.Create(username: _testUsername, password: _hashService.HashString("TestPass123!"));
|
||||
user.TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(totpSecret));
|
||||
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
+36
-24
@@ -1,6 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Authentication;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Infrastructure.Core.Security;
|
||||
@@ -24,6 +25,7 @@ public class RegisterEndpointTests : IClassFixture<LuminaApiFactory>, IDisposabl
|
||||
{
|
||||
private readonly PasswordHashService _hashService = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly RegistrationRequestFixture _registrationRequestFixture = new();
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly HttpClient _client;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
@@ -46,10 +48,10 @@ public class RegisterEndpointTests : IClassFixture<LuminaApiFactory>, IDisposabl
|
||||
public async Task Register_WhenUsernameTaken_ShouldReturnUniformConflictResponse()
|
||||
{
|
||||
// Arrange
|
||||
RegistrationRequest request = new(
|
||||
Username: _testUsername,
|
||||
Password: "TestPass123!",
|
||||
PasswordConfirm: "TestPass123!"
|
||||
RegistrationRequest request = _registrationRequestFixture.Create(
|
||||
username: _testUsername,
|
||||
password: "TestPass123!",
|
||||
passwordConfirm: "TestPass123!"
|
||||
);
|
||||
_client.DefaultRequestHeaders.Clear();
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.6");
|
||||
@@ -74,10 +76,10 @@ public class RegisterEndpointTests : IClassFixture<LuminaApiFactory>, IDisposabl
|
||||
// Arrange
|
||||
_client.DefaultRequestHeaders.Clear();
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.7");
|
||||
RegistrationRequest request = new(
|
||||
Username: _testUsername,
|
||||
Password: "TestPass123!",
|
||||
PasswordConfirm: "TestPass123!"
|
||||
RegistrationRequest request = _registrationRequestFixture.Create(
|
||||
username: _testUsername,
|
||||
password: "TestPass123!",
|
||||
passwordConfirm: "TestPass123!"
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -114,10 +116,10 @@ public class RegisterEndpointTests : IClassFixture<LuminaApiFactory>, IDisposabl
|
||||
// Arrange
|
||||
// note: the register validator rejects these usernames (invalid username format) with 422 before any DB access,
|
||||
// so the malicious username never reaches a query; the 422 assertion below is the security guarantee
|
||||
RegistrationRequest request = new(
|
||||
Username: maliciousUsername,
|
||||
Password: "TestPass123!",
|
||||
PasswordConfirm: "TestPass123!"
|
||||
RegistrationRequest request = _registrationRequestFixture.Create(
|
||||
username: maliciousUsername,
|
||||
password: "TestPass123!",
|
||||
passwordConfirm: "TestPass123!"
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -141,10 +143,10 @@ public class RegisterEndpointTests : IClassFixture<LuminaApiFactory>, IDisposabl
|
||||
public async Task Register_WithWeakPassword_ShouldBeDenied(string weakPassword)
|
||||
{
|
||||
// Arrange
|
||||
RegistrationRequest request = new(
|
||||
Username: _testUsername,
|
||||
Password: weakPassword,
|
||||
PasswordConfirm: weakPassword
|
||||
RegistrationRequest request = _registrationRequestFixture.Create(
|
||||
username: _testUsername,
|
||||
password: weakPassword,
|
||||
passwordConfirm: weakPassword
|
||||
);
|
||||
_client.DefaultRequestHeaders.Clear();
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.8");
|
||||
@@ -164,10 +166,10 @@ public class RegisterEndpointTests : IClassFixture<LuminaApiFactory>, IDisposabl
|
||||
public async Task Register_WithValidPassword_ShouldAcceptPassword(string password)
|
||||
{
|
||||
// Arrange
|
||||
RegistrationRequest request = new(
|
||||
Username: _testUsername,
|
||||
Password: password,
|
||||
PasswordConfirm: password
|
||||
RegistrationRequest request = _registrationRequestFixture.Create(
|
||||
username: _testUsername,
|
||||
password: password,
|
||||
passwordConfirm: password
|
||||
);
|
||||
|
||||
// Act
|
||||
@@ -182,10 +184,10 @@ public class RegisterEndpointTests : IClassFixture<LuminaApiFactory>, IDisposabl
|
||||
{
|
||||
// Arrange
|
||||
await CreateTestUser();
|
||||
RegistrationRequest request = new(
|
||||
Username: _testUsername,
|
||||
Password: "TestPass123!",
|
||||
PasswordConfirm: "TestPass123!"
|
||||
RegistrationRequest request = _registrationRequestFixture.Create(
|
||||
username: _testUsername,
|
||||
password: "TestPass123!",
|
||||
passwordConfirm: "TestPass123!"
|
||||
);
|
||||
_client.DefaultRequestHeaders.Clear();
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.9");
|
||||
@@ -201,6 +203,12 @@ public class RegisterEndpointTests : IClassFixture<LuminaApiFactory>, IDisposabl
|
||||
Assert.DoesNotContain("salt", content);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the given <paramref name="content"/> is a problem detail with the expected title and detail.
|
||||
/// </summary>
|
||||
/// <param name="content">The response content to assert.</param>
|
||||
/// <param name="expectedTitle">The expected title of the problem detail.</param>
|
||||
/// <param name="expectedDetail">The expected detail of the problem detail.</param>
|
||||
private void AssertProblemDetail(string content, string expectedTitle, string expectedDetail)
|
||||
{
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
@@ -209,6 +217,10 @@ public class RegisterEndpointTests : IClassFixture<LuminaApiFactory>, IDisposabl
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user in the database and returns it.
|
||||
/// </summary>
|
||||
/// <returns>The created user entity.</returns>
|
||||
private async Task<UserEntity> CreateTestUser()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
|
||||
+3
@@ -41,7 +41,10 @@
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\src\Lumina.Presentation.Api\Lumina.Presentation.Api.csproj" />
|
||||
<ProjectReference Include="..\..\..\src\Lumina.Application\Lumina.Application.csproj" />
|
||||
<ProjectReference Include="..\..\..\plugins\Lumina.Plugins.Calibre\Lumina.Plugins.Calibre.csproj" />
|
||||
<ProjectReference Include="..\..\Common\Lumina.Application.Fixtures\Lumina.Application.Fixtures.csproj" />
|
||||
<ProjectReference Include="..\..\Common\Lumina.Contracts.Fixtures\Lumina.Contracts.Fixtures.csproj" />
|
||||
<ProjectReference Include="..\..\Common\Lumina.Domain.Fixtures\Lumina.Domain.Fixtures.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
+8
-8
@@ -1,14 +1,12 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Authorization;
|
||||
using Lumina.Presentation.Web.Common.Responses.Authorization;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.GetRoles;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Authorization.Roles.GetRoles;
|
||||
@@ -20,6 +18,8 @@ namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Authorizati
|
||||
public class GetRolesEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new();
|
||||
private readonly RoleDtoFixture _roleDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetRolesEndpointTests"/> class.
|
||||
@@ -50,7 +50,7 @@ public class GetRolesEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.AuthorizationResponse = new GetAuthorizationResponse(Guid.NewGuid(), "User", []);
|
||||
_apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
@@ -66,8 +66,8 @@ public class GetRolesEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.AuthorizationResponse = new GetAuthorizationResponse(Guid.NewGuid(), "Admin", []);
|
||||
RoleDto[] expectedRoles = [new RoleDto(Guid.NewGuid(), "Admin")];
|
||||
_apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []);
|
||||
RoleDto[] expectedRoles = [_roleDtoFixture.Create(id: Guid.NewGuid(), roleName: "Admin")];
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse("auth/roles", expectedRoles);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
|
||||
+5
-3
@@ -2,13 +2,10 @@
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.DeleteLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.DeleteLibrary;
|
||||
@@ -67,6 +64,11 @@ public class DeleteLibraryEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.DeleteEndpointsCalled, endpoint => endpoint == $"libraries/{libraryId}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the delete request for the library identified by <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library to delete.</param>
|
||||
/// <returns>The configured delete request.</returns>
|
||||
private static HttpRequestMessage CreateDeleteRequest(Guid libraryId)
|
||||
{
|
||||
HttpRequestMessage deleteRequest = new(HttpMethod.Delete, $"/en-us/libraries/manage/api-item/{libraryId}")
|
||||
|
||||
+12
-7
@@ -1,15 +1,13 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.SaveLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.SaveLibrary;
|
||||
@@ -21,6 +19,7 @@ namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Managemen
|
||||
public class SaveLibraryEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly LibraryDtoFixture _libraryDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SaveLibraryEndpointTests"/> class.
|
||||
@@ -37,7 +36,7 @@ public class SaveLibraryEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage saveRequest = CreateSaveRequest(new LibraryDto { Title = "New Books Library", LibraryType = "Book" });
|
||||
HttpRequestMessage saveRequest = CreateSaveRequest(_libraryDtoFixture.Create(title: "New Books Library", libraryType: "Book"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
|
||||
@@ -53,7 +52,7 @@ public class SaveLibraryEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage saveRequest = CreateSaveRequest(new LibraryDto { Title = "New Books Library", LibraryType = "Book" });
|
||||
HttpRequestMessage saveRequest = CreateSaveRequest(_libraryDtoFixture.Create(title: "New Books Library", libraryType: "Book"));
|
||||
saveRequest.Headers.Remove("RequestVerificationToken");
|
||||
saveRequest.Headers.Add("RequestVerificationToken", "invalid-antiforgery-token");
|
||||
|
||||
@@ -70,8 +69,9 @@ public class SaveLibraryEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
LibraryDto request = new() { Title = "'; DROP TABLE Libraries--", LibraryType = "Book" };
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse("libraries", new LibraryDto { Id = Guid.NewGuid(), Title = request.Title, LibraryType = request.LibraryType });
|
||||
LibraryDto request = _libraryDtoFixture.Create(title: "'; DROP TABLE Libraries--", libraryType: "Book");
|
||||
request.Id = null;
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse("libraries", _libraryDtoFixture.Create(id: Guid.NewGuid(), title: request.Title, libraryType: request.LibraryType));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage saveRequest = CreateSaveRequest(request);
|
||||
saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
@@ -86,6 +86,11 @@ public class SaveLibraryEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
Assert.DoesNotContain("Exception", content);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the save request that sends the given <paramref name="request"/> to the library save endpoint.
|
||||
/// </summary>
|
||||
/// <param name="request">The library data to send.</param>
|
||||
/// <returns>The configured save request.</returns>
|
||||
private static HttpRequestMessage CreateSaveRequest(LibraryDto request)
|
||||
{
|
||||
HttpRequestMessage saveRequest = new(HttpMethod.Post, "/en-us/libraries/manage/api-item")
|
||||
|
||||
+3
-5
@@ -1,15 +1,12 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Plugins.GetPlugins;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Plugins.GetPlugins;
|
||||
@@ -21,6 +18,7 @@ namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Plugins.GetPlugin
|
||||
public class GetPluginsEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPluginsEndpointTests"/> class.
|
||||
@@ -55,7 +53,7 @@ public class GetPluginsEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.RegisterGetException("plugins", new ApiException(
|
||||
new ProblemDetailsDto { Title = "General.Failure", Detail = "PluginNotFound" },
|
||||
_problemDetailsDtoFixture.Create(title: "General.Failure", detail: "PluginNotFound"),
|
||||
HttpStatusCode.NotFound));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/admin/manage-plugins/api-get-plugins");
|
||||
|
||||
+3
-5
@@ -1,16 +1,13 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Plugins.InstallPlugin;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Plugins.InstallPlugin;
|
||||
@@ -22,6 +19,7 @@ namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Plugins.InstallPl
|
||||
public class InstallPluginEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="InstallPluginEndpointTests"/> class.
|
||||
@@ -101,7 +99,7 @@ public class InstallPluginEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.RegisterPostException("plugins", new ApiException(
|
||||
new ProblemDetailsDto { Title = "General.Failure", Detail = "PluginArchiveNotReadable" },
|
||||
_problemDetailsDtoFixture.Create(title: "General.Failure", detail: "PluginArchiveNotReadable"),
|
||||
HttpStatusCode.Forbidden));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage installRequest = new(HttpMethod.Post, "/en-us/admin/manage-plugins/api-install-plugin")
|
||||
|
||||
+3
-5
@@ -1,18 +1,15 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Common.Requests.Plugins;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Plugins.UpdatePluginSettings;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Plugins.UpdatePluginSettings;
|
||||
@@ -24,6 +21,7 @@ namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Plugins.UpdatePlu
|
||||
public class UpdatePluginSettingsEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new();
|
||||
private readonly UpdatePluginSettingsRequestFixture _updatePluginSettingsRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
@@ -89,7 +87,7 @@ public class UpdatePluginSettingsEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
UpdatePluginSettingsRequest request = _updatePluginSettingsRequestFixture.Create();
|
||||
string endpoint = $"plugins/{request.PluginId}/settings";
|
||||
_apiFactory.ApiClientStub.RegisterPutException(endpoint, new ApiException(
|
||||
new ProblemDetailsDto { Title = "General.Failure", Detail = "PluginNotFound" },
|
||||
_problemDetailsDtoFixture.Create(title: "General.Failure", detail: "PluginNotFound"),
|
||||
HttpStatusCode.NotFound));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/admin/manage-plugins/api-update-plugin-settings")
|
||||
|
||||
+14
-8
@@ -1,18 +1,16 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Common.Requests.UsersManagement;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.Login;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.UsersManagement.Authentication.Login;
|
||||
@@ -24,6 +22,8 @@ namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.UsersManagement.A
|
||||
public class LoginEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly LoginRequestFixture _loginRequestFixture = new();
|
||||
private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LoginEndpointTests"/> class.
|
||||
@@ -44,10 +44,10 @@ public class LoginEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.RegisterPostException("auth/login", new ApiException(new ProblemDetailsDto { Title = "General.Failure", Detail = "InvalidUsernameOrPassword" }, HttpStatusCode.Forbidden, "auth/login"));
|
||||
_apiFactory.ApiClientStub.RegisterPostException("auth/login", new ApiException(_problemDetailsDtoFixture.Create(title: "General.Failure", detail: "InvalidUsernameOrPassword"), HttpStatusCode.Forbidden, "auth/login"));
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client);
|
||||
HttpRequestMessage loginRequest = CreateLoginRequest(new LoginRequest(Username: maliciousUsername, Password: "Abcd123$"), antiforgeryToken);
|
||||
HttpRequestMessage loginRequest = CreateLoginRequest(_loginRequestFixture.Create(username: maliciousUsername, password: "Abcd123$"), antiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.SendAsync(loginRequest);
|
||||
@@ -71,7 +71,7 @@ public class LoginEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client);
|
||||
HttpRequestMessage loginRequest = CreateLoginRequest(new LoginRequest(Username: "testuser", Password: "TestPass123!"), antiforgeryToken);
|
||||
HttpRequestMessage loginRequest = CreateLoginRequest(_loginRequestFixture.Create(username: "testuser", password: "TestPass123!"), antiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.SendAsync(loginRequest);
|
||||
@@ -96,7 +96,7 @@ public class LoginEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client);
|
||||
HttpRequestMessage loginRequest = CreateLoginRequest(new LoginRequest(Username: "testuser", Password: "TestPass123!"), antiforgeryToken);
|
||||
HttpRequestMessage loginRequest = CreateLoginRequest(_loginRequestFixture.Create(username: "testuser", password: "TestPass123!"), antiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.SendAsync(loginRequest);
|
||||
@@ -113,6 +113,12 @@ public class LoginEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
Assert.Contains("samesite=strict", tokenCookie, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the login request that sends the given <paramref name="request"/> to the login endpoint.
|
||||
/// </summary>
|
||||
/// <param name="request">The login request to send.</param>
|
||||
/// <param name="antiforgeryToken">The antiforgery token to include in the request.</param>
|
||||
/// <returns>The configured login request.</returns>
|
||||
private static HttpRequestMessage CreateLoginRequest(LoginRequest request, string antiforgeryToken)
|
||||
{
|
||||
HttpRequestMessage loginRequest = new(HttpMethod.Post, "/en-us/auth/api-login")
|
||||
|
||||
+9
-18
@@ -1,6 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.Mapping.Authorization;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Contracts.Responses.Authorization;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
|
||||
using System;
|
||||
@@ -17,15 +18,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.Authorization;
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PermissionEntityMappingTests
|
||||
{
|
||||
private readonly PermissionEntityFixture _permissionEntityFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenMappingValidEntity_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
PermissionEntity entity = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
PermissionName = AuthorizationPermission.CanViewUsers
|
||||
};
|
||||
PermissionEntity entity = _permissionEntityFixture.Create(permissionName: AuthorizationPermission.CanViewUsers);
|
||||
|
||||
// Act
|
||||
PermissionResponse result = entity.ToResponse();
|
||||
@@ -44,11 +43,7 @@ public class PermissionEntityMappingTests
|
||||
public void ToResponse_WhenMappingDifferentPermissions_ShouldMapCorrectly(AuthorizationPermission permission)
|
||||
{
|
||||
// Arrange
|
||||
PermissionEntity entity = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
PermissionName = permission
|
||||
};
|
||||
PermissionEntity entity = _permissionEntityFixture.Create(permissionName: permission);
|
||||
|
||||
// Act
|
||||
PermissionResponse result = entity.ToResponse();
|
||||
@@ -65,9 +60,9 @@ public class PermissionEntityMappingTests
|
||||
// Arrange
|
||||
List<PermissionEntity> entities =
|
||||
[
|
||||
new() { Id = Guid.NewGuid(), PermissionName = AuthorizationPermission.CanViewUsers },
|
||||
new() { Id = Guid.NewGuid(), PermissionName = AuthorizationPermission.CanDeleteUsers },
|
||||
new() { Id = Guid.NewGuid(), PermissionName = AuthorizationPermission.CanRegisterUsers }
|
||||
_permissionEntityFixture.Create(permissionName: AuthorizationPermission.CanViewUsers),
|
||||
_permissionEntityFixture.Create(permissionName: AuthorizationPermission.CanDeleteUsers),
|
||||
_permissionEntityFixture.Create(permissionName: AuthorizationPermission.CanRegisterUsers)
|
||||
];
|
||||
|
||||
// Act
|
||||
@@ -101,11 +96,7 @@ public class PermissionEntityMappingTests
|
||||
public void ToResponse_WhenMappingDifferentIds_ShouldMapCorrectly(string idString)
|
||||
{
|
||||
// Arrange
|
||||
PermissionEntity entity = new()
|
||||
{
|
||||
Id = Guid.Parse(idString),
|
||||
PermissionName = AuthorizationPermission.CanViewUsers
|
||||
};
|
||||
PermissionEntity entity = _permissionEntityFixture.Create(id: Guid.Parse(idString), permissionName: AuthorizationPermission.CanViewUsers);
|
||||
|
||||
// Act
|
||||
PermissionResponse result = entity.ToResponse();
|
||||
|
||||
+21
-46
@@ -1,6 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.Mapping.Authorization;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Contracts.Responses.Authorization;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
|
||||
using System;
|
||||
@@ -17,15 +18,15 @@ namespace Lumina.Application.UnitTests.Common.Mapping.Authorization;
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RoleEntityMappingTests
|
||||
{
|
||||
private readonly RoleEntityFixture _roleEntityFixture = new();
|
||||
private readonly RolePermissionEntityFixture _rolePermissionEntityFixture = new();
|
||||
private readonly PermissionEntityFixture _permissionEntityFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenMappingValidEntity_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
RoleEntity entity = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
RoleName = "Admin"
|
||||
};
|
||||
RoleEntity entity = _roleEntityFixture.Create(roleName: "Admin");
|
||||
|
||||
// Act
|
||||
RoleResponse result = entity.ToResponse();
|
||||
@@ -41,36 +42,18 @@ public class RoleEntityMappingTests
|
||||
{
|
||||
// Arrange
|
||||
Guid roleId = Guid.NewGuid();
|
||||
RoleEntity role = new()
|
||||
{
|
||||
Id = roleId,
|
||||
RoleName = "Admin"
|
||||
};
|
||||
RoleEntity role = _roleEntityFixture.Create(id: roleId, roleName: "Admin");
|
||||
|
||||
role.RolePermissions =
|
||||
[
|
||||
new()
|
||||
{
|
||||
PermissionId = Guid.NewGuid(),
|
||||
RoleId = roleId,
|
||||
Role = role,
|
||||
Permission = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
PermissionName = AuthorizationPermission.CanViewUsers
|
||||
}
|
||||
},
|
||||
new()
|
||||
{
|
||||
PermissionId = Guid.NewGuid(),
|
||||
RoleId = roleId,
|
||||
Role = role,
|
||||
Permission = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
PermissionName = AuthorizationPermission.CanDeleteUsers
|
||||
}
|
||||
}
|
||||
_rolePermissionEntityFixture.Create(
|
||||
roleId: roleId,
|
||||
role: role,
|
||||
permission: _permissionEntityFixture.Create(permissionName: AuthorizationPermission.CanViewUsers)),
|
||||
_rolePermissionEntityFixture.Create(
|
||||
roleId: roleId,
|
||||
role: role,
|
||||
permission: _permissionEntityFixture.Create(permissionName: AuthorizationPermission.CanDeleteUsers))
|
||||
];
|
||||
|
||||
// Act
|
||||
@@ -89,9 +72,9 @@ public class RoleEntityMappingTests
|
||||
// Arrange
|
||||
List<RoleEntity> entities =
|
||||
[
|
||||
new() { Id = Guid.NewGuid(), RoleName = "Admin" },
|
||||
new() { Id = Guid.NewGuid(), RoleName = "User" },
|
||||
new() { Id = Guid.NewGuid(), RoleName = "Guest" }
|
||||
_roleEntityFixture.Create(roleName: "Admin"),
|
||||
_roleEntityFixture.Create(roleName: "User"),
|
||||
_roleEntityFixture.Create(roleName: "Guest")
|
||||
];
|
||||
|
||||
// Act
|
||||
@@ -100,7 +83,7 @@ public class RoleEntityMappingTests
|
||||
// Assert
|
||||
Assert.NotNull(results);
|
||||
Assert.Equal(3, results.Count());
|
||||
List<RoleResponse> resultList = results.ToList();
|
||||
List<RoleResponse> resultList = [.. results];
|
||||
for (int i = 0; i < entities.Count; i++)
|
||||
{
|
||||
Assert.Equal(entities[i].Id, resultList[i].Id);
|
||||
@@ -129,11 +112,7 @@ public class RoleEntityMappingTests
|
||||
public void ToResponse_WhenMappingDifferentRoleNames_ShouldMapCorrectly(string roleName)
|
||||
{
|
||||
// Arrange
|
||||
RoleEntity entity = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
RoleName = roleName
|
||||
};
|
||||
RoleEntity entity = _roleEntityFixture.Create(roleName: roleName);
|
||||
|
||||
// Act
|
||||
RoleResponse result = entity.ToResponse();
|
||||
@@ -151,11 +130,7 @@ public class RoleEntityMappingTests
|
||||
public void ToResponse_WhenMappingDifferentIds_ShouldMapCorrectly(string idString)
|
||||
{
|
||||
// Arrange
|
||||
RoleEntity entity = new()
|
||||
{
|
||||
Id = Guid.Parse(idString),
|
||||
RoleName = "Admin"
|
||||
};
|
||||
RoleEntity entity = _roleEntityFixture.Create(id: Guid.Parse(idString), roleName: "Admin");
|
||||
|
||||
// Act
|
||||
RoleResponse result = entity.ToResponse();
|
||||
|
||||
+17
-25
@@ -1,6 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.Mapping.Authorization;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Contracts.Responses.Authorization;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
|
||||
using System;
|
||||
@@ -16,16 +17,15 @@ namespace Lumina.Application.UnitTests.Common.Mapping.Authorization;
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UserAuthorizationEntityMappingTests
|
||||
{
|
||||
private readonly UserAuthorizationEntityFixture _userAuthorizationEntityFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenMappingValidEntity_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
UserAuthorizationEntity entity = new()
|
||||
{
|
||||
UserId = Guid.NewGuid(),
|
||||
Role = "Admin",
|
||||
Permissions = new HashSet<AuthorizationPermission> { AuthorizationPermission.CanViewUsers }
|
||||
};
|
||||
UserAuthorizationEntity entity = _userAuthorizationEntityFixture.Create(
|
||||
role: "Admin",
|
||||
permissions: new HashSet<AuthorizationPermission> { AuthorizationPermission.CanViewUsers });
|
||||
|
||||
// Act
|
||||
AuthorizationResponse result = entity.ToResponse();
|
||||
@@ -41,12 +41,9 @@ public class UserAuthorizationEntityMappingTests
|
||||
public void ToResponse_WhenMappingEntityWithEmptyCollections_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
UserAuthorizationEntity entity = new()
|
||||
{
|
||||
UserId = Guid.NewGuid(),
|
||||
Role = string.Empty,
|
||||
Permissions = new HashSet<AuthorizationPermission>()
|
||||
};
|
||||
UserAuthorizationEntity entity = _userAuthorizationEntityFixture.Create(
|
||||
role: string.Empty,
|
||||
permissions: new HashSet<AuthorizationPermission>());
|
||||
|
||||
// Act
|
||||
AuthorizationResponse result = entity.ToResponse();
|
||||
@@ -62,17 +59,14 @@ public class UserAuthorizationEntityMappingTests
|
||||
public void ToResponse_WhenMappingEntityWithMultipleRolesAndPermissions_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
UserAuthorizationEntity entity = new()
|
||||
{
|
||||
UserId = Guid.NewGuid(),
|
||||
Role = "Admin",
|
||||
Permissions = new HashSet<AuthorizationPermission>
|
||||
UserAuthorizationEntity entity = _userAuthorizationEntityFixture.Create(
|
||||
role: "Admin",
|
||||
permissions: new HashSet<AuthorizationPermission>
|
||||
{
|
||||
AuthorizationPermission.CanViewUsers,
|
||||
AuthorizationPermission.CanDeleteUsers,
|
||||
AuthorizationPermission.CanRegisterUsers
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
// Act
|
||||
AuthorizationResponse result = entity.ToResponse();
|
||||
@@ -91,12 +85,10 @@ public class UserAuthorizationEntityMappingTests
|
||||
public void ToResponse_WhenMappingDifferentUserIds_ShouldMapCorrectly(string userIdString)
|
||||
{
|
||||
// Arrange
|
||||
UserAuthorizationEntity entity = new()
|
||||
{
|
||||
UserId = Guid.Parse(userIdString),
|
||||
Role = "Admin",
|
||||
Permissions = new HashSet<AuthorizationPermission> { AuthorizationPermission.CanViewUsers }
|
||||
};
|
||||
UserAuthorizationEntity entity = _userAuthorizationEntityFixture.Create(
|
||||
userId: Guid.Parse(userIdString),
|
||||
role: "Admin",
|
||||
permissions: new HashSet<AuthorizationPermission> { AuthorizationPermission.CanViewUsers });
|
||||
|
||||
// Act
|
||||
AuthorizationResponse result = entity.ToResponse();
|
||||
|
||||
+14
-11
@@ -1,6 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Mapping.Common.Metadata;
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.Common;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Common.ValueObjects.Metadata;
|
||||
using System.Collections.Generic;
|
||||
@@ -16,11 +17,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.Common.Metadata;
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GenreDtoMappingTests
|
||||
{
|
||||
private readonly GenreDtoFixture _genreDtoFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenMappingValidGenreDto_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
GenreDto genreDto = new("Rock");
|
||||
GenreDto genreDto = _genreDtoFixture.Create(name: "Rock");
|
||||
|
||||
// Act
|
||||
Result<Genre> result = genreDto.ToDomainEntity();
|
||||
@@ -39,7 +42,7 @@ public class GenreDtoMappingTests
|
||||
public void ToDomainEntity_WhenMappingDifferentValidGenreDtos_ShouldMapCorrectly(string name)
|
||||
{
|
||||
// Arrange
|
||||
GenreDto genreDto = new(name);
|
||||
GenreDto genreDto = _genreDtoFixture.Create(name: name);
|
||||
|
||||
// Act
|
||||
Result<Genre> result = genreDto.ToDomainEntity();
|
||||
@@ -57,7 +60,7 @@ public class GenreDtoMappingTests
|
||||
public void ToDomainEntity_WhenMappingInvalidGenreDto_ShouldReturnError(string? invalidName)
|
||||
{
|
||||
// Arrange
|
||||
GenreDto genreDto = new(invalidName);
|
||||
GenreDto genreDto = _genreDtoFixture.Create(name: invalidName, includeName: invalidName is not null);
|
||||
|
||||
// Act
|
||||
Result<Genre> result = genreDto.ToDomainEntity();
|
||||
@@ -72,10 +75,10 @@ public class GenreDtoMappingTests
|
||||
// Arrange
|
||||
List<GenreDto> genreDtos =
|
||||
[
|
||||
new GenreDto("Rock"),
|
||||
new GenreDto("Jazz"),
|
||||
new GenreDto("Classical"),
|
||||
new GenreDto("Pop")
|
||||
_genreDtoFixture.Create(name: "Rock"),
|
||||
_genreDtoFixture.Create(name: "Jazz"),
|
||||
_genreDtoFixture.Create(name: "Classical"),
|
||||
_genreDtoFixture.Create(name: "Pop")
|
||||
];
|
||||
|
||||
// Act
|
||||
@@ -99,10 +102,10 @@ public class GenreDtoMappingTests
|
||||
// Arrange
|
||||
List<GenreDto> genreDtos =
|
||||
[
|
||||
new GenreDto("Rock"),
|
||||
new GenreDto(""),
|
||||
new GenreDto("Jazz"),
|
||||
new GenreDto(" ")
|
||||
_genreDtoFixture.Create(name: "Rock"),
|
||||
_genreDtoFixture.Create(name: ""),
|
||||
_genreDtoFixture.Create(name: "Jazz"),
|
||||
_genreDtoFixture.Create(name: " ")
|
||||
];
|
||||
|
||||
// Act
|
||||
|
||||
+16
-13
@@ -1,6 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Common.Mapping.Common.Metadata;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
@@ -18,11 +19,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.Common.Metadata;
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GenreEntityMappingTests
|
||||
{
|
||||
private readonly GenreEntityFixture _genreEntityFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenMappingValidGenreEntity_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
GenreEntity entity = new("Fiction");
|
||||
GenreEntity entity = _genreEntityFixture.Create(name: "Fiction");
|
||||
|
||||
// Act
|
||||
GenreDto result = entity.ToResponse();
|
||||
@@ -40,7 +43,7 @@ public class GenreEntityMappingTests
|
||||
public void ToResponse_WhenMappingDifferentValidGenreEntities_ShouldMapCorrectly(string name)
|
||||
{
|
||||
// Arrange
|
||||
GenreEntity entity = new(name);
|
||||
GenreEntity entity = _genreEntityFixture.Create(name: name);
|
||||
|
||||
// Act
|
||||
GenreDto result = entity.ToResponse();
|
||||
@@ -57,7 +60,7 @@ public class GenreEntityMappingTests
|
||||
public void ToResponse_WhenMappingInvalidGenreEntity_ShouldMapToDefault(string? invalidName)
|
||||
{
|
||||
// Arrange
|
||||
GenreEntity entity = new(invalidName);
|
||||
GenreEntity entity = _genreEntityFixture.Create(name: invalidName, includeName: invalidName is not null);
|
||||
|
||||
// Act
|
||||
GenreDto result = entity.ToResponse();
|
||||
@@ -70,7 +73,7 @@ public class GenreEntityMappingTests
|
||||
public void ToDomainEntity_WhenMappingValidGenreEntity_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
GenreEntity entity = new("Fiction");
|
||||
GenreEntity entity = _genreEntityFixture.Create(name: "Fiction");
|
||||
|
||||
// Act
|
||||
Result<Genre> result = entity.ToDomainEntity();
|
||||
@@ -88,7 +91,7 @@ public class GenreEntityMappingTests
|
||||
public void ToDomainEntity_WhenMappingInvalidGenreEntity_ShouldMapToDefault(string? invalidName)
|
||||
{
|
||||
// Arrange
|
||||
GenreEntity entity = new(invalidName);
|
||||
GenreEntity entity = _genreEntityFixture.Create(name: invalidName, includeName: invalidName is not null);
|
||||
|
||||
// Act
|
||||
Result<Genre> result = entity.ToDomainEntity();
|
||||
@@ -104,10 +107,10 @@ public class GenreEntityMappingTests
|
||||
// Arrange
|
||||
List<GenreEntity> entities =
|
||||
[
|
||||
new GenreEntity("Fiction"),
|
||||
new GenreEntity("Mystery"),
|
||||
new GenreEntity("Romance"),
|
||||
new GenreEntity("Thriller")
|
||||
_genreEntityFixture.Create(name: "Fiction"),
|
||||
_genreEntityFixture.Create(name: "Mystery"),
|
||||
_genreEntityFixture.Create(name: "Romance"),
|
||||
_genreEntityFixture.Create(name: "Thriller")
|
||||
];
|
||||
|
||||
// Act
|
||||
@@ -131,10 +134,10 @@ public class GenreEntityMappingTests
|
||||
// Arrange
|
||||
List<GenreEntity> entities =
|
||||
[
|
||||
new GenreEntity("Fiction"),
|
||||
new GenreEntity("Mystery"),
|
||||
new GenreEntity("Romance"),
|
||||
new GenreEntity("Thriller")
|
||||
_genreEntityFixture.Create(name: "Fiction"),
|
||||
_genreEntityFixture.Create(name: "Mystery"),
|
||||
_genreEntityFixture.Create(name: "Romance"),
|
||||
_genreEntityFixture.Create(name: "Thriller")
|
||||
];
|
||||
|
||||
// Act
|
||||
|
||||
+14
-11
@@ -1,6 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Mapping.Common.Metadata;
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.Common;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Common.ValueObjects.Metadata;
|
||||
using System.Collections.Generic;
|
||||
@@ -16,11 +17,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.Common.Metadata;
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class TagDtoMappingTests
|
||||
{
|
||||
private readonly TagDtoFixture _tagDtoFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenMappingValidTagDto_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
TagDto tagDto = new("indie");
|
||||
TagDto tagDto = _tagDtoFixture.Create(name: "indie");
|
||||
|
||||
// Act
|
||||
Result<Tag> result = tagDto.ToDomainEntity();
|
||||
@@ -40,7 +43,7 @@ public class TagDtoMappingTests
|
||||
public void ToDomainEntity_WhenMappingDifferentValidTagDtos_ShouldMapCorrectly(string name)
|
||||
{
|
||||
// Arrange
|
||||
TagDto tagDto = new(name);
|
||||
TagDto tagDto = _tagDtoFixture.Create(name: name);
|
||||
|
||||
// Act
|
||||
Result<Tag> result = tagDto.ToDomainEntity();
|
||||
@@ -58,7 +61,7 @@ public class TagDtoMappingTests
|
||||
public void ToDomainEntity_WhenMappingInvalidTagDto_ShouldReturnError(string? invalidName)
|
||||
{
|
||||
// Arrange
|
||||
TagDto tagDto = new(invalidName);
|
||||
TagDto tagDto = _tagDtoFixture.Create(name: invalidName, includeName: invalidName is not null);
|
||||
|
||||
// Act
|
||||
Result<Tag> result = tagDto.ToDomainEntity();
|
||||
@@ -73,10 +76,10 @@ public class TagDtoMappingTests
|
||||
// Arrange
|
||||
List<TagDto> tagDtos =
|
||||
[
|
||||
new TagDto("indie"),
|
||||
new TagDto("electronic"),
|
||||
new TagDto("instrumental"),
|
||||
new TagDto("live")
|
||||
_tagDtoFixture.Create(name: "indie"),
|
||||
_tagDtoFixture.Create(name: "electronic"),
|
||||
_tagDtoFixture.Create(name: "instrumental"),
|
||||
_tagDtoFixture.Create(name: "live")
|
||||
];
|
||||
|
||||
// Act
|
||||
@@ -100,10 +103,10 @@ public class TagDtoMappingTests
|
||||
// Arrange
|
||||
List<TagDto> tagDtos =
|
||||
[
|
||||
new TagDto("indie"),
|
||||
new TagDto(""),
|
||||
new TagDto("electronic"),
|
||||
new TagDto(" ")
|
||||
_tagDtoFixture.Create(name: "indie"),
|
||||
_tagDtoFixture.Create(name: ""),
|
||||
_tagDtoFixture.Create(name: "electronic"),
|
||||
_tagDtoFixture.Create(name: " ")
|
||||
];
|
||||
|
||||
// Act
|
||||
|
||||
+16
-13
@@ -1,6 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Common.Mapping.Common.Metadata;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
@@ -18,11 +19,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.Common.Metadata;
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class TagEntityMappingTests
|
||||
{
|
||||
private readonly TagEntityFixture _tagEntityFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenMappingValidTagEntity_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
TagEntity entity = new("Fantasy");
|
||||
TagEntity entity = _tagEntityFixture.Create(name: "Fantasy");
|
||||
|
||||
// Act
|
||||
TagDto result = entity.ToResponse();
|
||||
@@ -40,7 +43,7 @@ public class TagEntityMappingTests
|
||||
public void ToResponse_WhenMappingDifferentValidTagEntities_ShouldMapCorrectly(string name)
|
||||
{
|
||||
// Arrange
|
||||
TagEntity entity = new(name);
|
||||
TagEntity entity = _tagEntityFixture.Create(name: name);
|
||||
|
||||
// Act
|
||||
TagDto result = entity.ToResponse();
|
||||
@@ -57,7 +60,7 @@ public class TagEntityMappingTests
|
||||
public void ToResponse_WhenMappingInvalidTagEntity_ShouldMapToDefault(string? invalidName)
|
||||
{
|
||||
// Arrange
|
||||
TagEntity entity = new(invalidName);
|
||||
TagEntity entity = _tagEntityFixture.Create(name: invalidName, includeName: invalidName is not null);
|
||||
|
||||
// Act
|
||||
TagDto result = entity.ToResponse();
|
||||
@@ -70,7 +73,7 @@ public class TagEntityMappingTests
|
||||
public void ToDomainEntity_WhenMappingValidTagEntity_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
TagEntity entity = new("Fantasy");
|
||||
TagEntity entity = _tagEntityFixture.Create(name: "Fantasy");
|
||||
|
||||
// Act
|
||||
Result<Tag> result = entity.ToDomainEntity();
|
||||
@@ -88,7 +91,7 @@ public class TagEntityMappingTests
|
||||
public void ToDomainEntity_WhenMappingInvalidTagEntity_ShouldMapToDefault(string? invalidName)
|
||||
{
|
||||
// Arrange
|
||||
TagEntity entity = new(invalidName);
|
||||
TagEntity entity = _tagEntityFixture.Create(name: invalidName, includeName: invalidName is not null);
|
||||
|
||||
// Act
|
||||
Result<Tag> result = entity.ToDomainEntity();
|
||||
@@ -104,10 +107,10 @@ public class TagEntityMappingTests
|
||||
// Arrange
|
||||
List<TagEntity> entities =
|
||||
[
|
||||
new TagEntity("Fantasy"),
|
||||
new TagEntity("Young Adult"),
|
||||
new TagEntity("Historical"),
|
||||
new TagEntity("Coming of Age")
|
||||
_tagEntityFixture.Create(name: "Fantasy"),
|
||||
_tagEntityFixture.Create(name: "Young Adult"),
|
||||
_tagEntityFixture.Create(name: "Historical"),
|
||||
_tagEntityFixture.Create(name: "Coming of Age")
|
||||
];
|
||||
|
||||
// Act
|
||||
@@ -131,10 +134,10 @@ public class TagEntityMappingTests
|
||||
// Arrange
|
||||
List<TagEntity> entities =
|
||||
[
|
||||
new TagEntity("Fantasy"),
|
||||
new TagEntity("Young Adult"),
|
||||
new TagEntity("Historical"),
|
||||
new TagEntity("Coming of Age")
|
||||
_tagEntityFixture.Create(name: "Fantasy"),
|
||||
_tagEntityFixture.Create(name: "Young Adult"),
|
||||
_tagEntityFixture.Create(name: "Historical"),
|
||||
_tagEntityFixture.Create(name: "Coming of Age")
|
||||
];
|
||||
|
||||
// Act
|
||||
|
||||
+22
-64
@@ -1,8 +1,8 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook;
|
||||
using Lumina.Contracts.DTO.MediaContributors;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
|
||||
using Lumina.Contracts.Fixtures.Core.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;
|
||||
@@ -19,6 +19,9 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenConten
|
||||
public class AddBookRequestMappingTests
|
||||
{
|
||||
private readonly AddBookRequestFixture _requestFixture = new();
|
||||
private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new();
|
||||
private readonly MediaContributorNameDtoFixture _mediaContributorNameDtoFixture = new();
|
||||
private readonly MediaContributorRoleDtoFixture _mediaContributorRoleDtoFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToCommand_WhenMappingCompleteRequest_ShouldMapAllPropertiesCorrectly()
|
||||
@@ -54,36 +57,12 @@ public class AddBookRequestMappingTests
|
||||
public void ToCommand_WhenMappingMinimalRequest_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest request = new(
|
||||
LibraryId: Guid.NewGuid(),
|
||||
Path: "/books/test.epub",
|
||||
Metadata: new WrittenContentMetadataDto(
|
||||
Title: "Test Book",
|
||||
OriginalTitle: null,
|
||||
Description: null,
|
||||
ReleaseInfo: null,
|
||||
Genres: null,
|
||||
Tags: null,
|
||||
Language: null,
|
||||
OriginalLanguage: null,
|
||||
Publisher: null,
|
||||
PageCount: null),
|
||||
Format: null,
|
||||
Edition: null,
|
||||
VolumeNumber: null,
|
||||
Series: null,
|
||||
ASIN: null,
|
||||
GoodreadsId: null,
|
||||
LCCN: null,
|
||||
OCLCNumber: null,
|
||||
OpenLibraryId: null,
|
||||
LibraryThingId: null,
|
||||
GoogleBooksId: null,
|
||||
BarnesAndNobleId: null,
|
||||
AppleBooksId: null,
|
||||
ISBNs: null,
|
||||
Contributors: null,
|
||||
Ratings: null);
|
||||
AddBookRequest request = _requestFixture.Create(
|
||||
libraryId: Guid.NewGuid(),
|
||||
path: "/books/test.epub",
|
||||
metadata: _writtenContentMetadataDtoFixture.Create(title: "Test Book"),
|
||||
includeOptionalProperties: false
|
||||
);
|
||||
|
||||
// Act
|
||||
AddBookCommand result = request.ToCommand();
|
||||
@@ -113,42 +92,21 @@ public class AddBookRequestMappingTests
|
||||
public void ToCommand_WhenMappingRequestWithCollections_ShouldMapCollectionsCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest request = new(
|
||||
LibraryId: Guid.NewGuid(),
|
||||
Path: "/books/test.epub",
|
||||
Metadata: new WrittenContentMetadataDto(
|
||||
Title: "Test Book",
|
||||
OriginalTitle: null,
|
||||
Description: null,
|
||||
ReleaseInfo: null,
|
||||
Genres: null,
|
||||
Tags: null,
|
||||
Language: null,
|
||||
OriginalLanguage: null,
|
||||
Publisher: null,
|
||||
PageCount: null),
|
||||
Format: null,
|
||||
Edition: null,
|
||||
VolumeNumber: null,
|
||||
Series: null,
|
||||
ASIN: null,
|
||||
GoodreadsId: null,
|
||||
LCCN: null,
|
||||
OCLCNumber: null,
|
||||
OpenLibraryId: null,
|
||||
LibraryThingId: null,
|
||||
GoogleBooksId: null,
|
||||
BarnesAndNobleId: null,
|
||||
AppleBooksId: null,
|
||||
ISBNs: [new("978-0-123456-78-9", IsbnFormat.Isbn13)],
|
||||
Contributors:
|
||||
AddBookRequest request = _requestFixture.Create(
|
||||
libraryId: Guid.NewGuid(),
|
||||
path: "/books/test.epub",
|
||||
metadata: _writtenContentMetadataDtoFixture.Create(title: "Test Book"),
|
||||
isbns: [new("978-0-123456-78-9", IsbnFormat.Isbn13)],
|
||||
contributors:
|
||||
[
|
||||
new(
|
||||
new MediaContributorNameDto("John Doe", "John Smith Doe"),
|
||||
new MediaContributorRoleDto("Author", "Writing")
|
||||
_mediaContributorNameDtoFixture.Create(displayName: "John Doe", legalName: "John Smith Doe"),
|
||||
_mediaContributorRoleDtoFixture.Create(name: "Author", category: "Writing")
|
||||
)
|
||||
],
|
||||
Ratings: [new(4.5m, 5m, BookRatingSource.Goodreads, 1000)]);
|
||||
ratings: [new(4.5m, 5m, BookRatingSource.Goodreads, 1000)],
|
||||
includeOptionalProperties: false
|
||||
);
|
||||
|
||||
// Act
|
||||
AddBookCommand result = request.ToCommand();
|
||||
|
||||
+26
-26
@@ -4,7 +4,8 @@ using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Common.Mapping.Common.Metadata;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DTO.Pagination;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
@@ -23,6 +24,9 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenConten
|
||||
public class BookEntityMappingTests
|
||||
{
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly IsbnDtoFixture _isbnDtoFixture = new();
|
||||
private readonly BookRatingDtoFixture _bookRatingDtoFixture = new();
|
||||
private readonly PaginatedResultDtoFixture<BookEntity> _paginatedResultDtoFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenMappingValidBookEntity_ShouldMapCorrectly()
|
||||
@@ -297,12 +301,12 @@ public class BookEntityMappingTests
|
||||
Assert.Equal(bookEntity.GoogleBooksId, result.GoogleBooksId);
|
||||
Assert.Equal(bookEntity.BarnesAndNobleId, result.BarnesAndNobleId);
|
||||
Assert.Equal(bookEntity.AppleBooksId, result.AppleBooksId);
|
||||
Assert.Equal(bookEntity.ISBNs.Select(i => new IsbnDto(i.Value, i.Format)), result.ISBNs);
|
||||
Assert.Equal(bookEntity.Ratings.Select(r => new BookRatingDto(
|
||||
r.Value,
|
||||
r.MaxValue,
|
||||
r.Source,
|
||||
r.VoteCount
|
||||
Assert.Equal(bookEntity.ISBNs.Select(i => _isbnDtoFixture.Create(value: i.Value, format: i.Format)), result.ISBNs);
|
||||
Assert.Equal(bookEntity.Ratings.Select(r => _bookRatingDtoFixture.Create(
|
||||
value: r.Value,
|
||||
maxValue: r.MaxValue,
|
||||
source: r.Source,
|
||||
voteCount: r.VoteCount
|
||||
)), result.Ratings);
|
||||
Assert.Equal(bookEntity.CreatedOnUtc, result.CreatedOnUtc);
|
||||
Assert.Equal(bookEntity.UpdatedOnUtc, result.UpdatedOnUtc);
|
||||
@@ -343,21 +347,19 @@ public class BookEntityMappingTests
|
||||
{
|
||||
// Arrange
|
||||
List<BookEntity> bookEntities = _bookEntityFixture.CreateMany(2);
|
||||
PaginatedResultDto<BookEntity> paginatedBookEntities = new()
|
||||
{
|
||||
Data = bookEntities,
|
||||
CurrentPage = 1,
|
||||
PerPage = 10,
|
||||
Count = 2,
|
||||
NumberOfPages = 1
|
||||
};
|
||||
PaginatedResultDto<BookEntity> paginatedBookEntities = _paginatedResultDtoFixture.Create(
|
||||
data: bookEntities,
|
||||
currentPage: 1,
|
||||
perPage: 10,
|
||||
count: 2,
|
||||
numberOfPages: 1);
|
||||
|
||||
// Act
|
||||
PaginatedResponse<BookResponse> result = paginatedBookEntities.ToResponses();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(paginatedBookEntities.Data.Count(), result.Data.Count());
|
||||
Assert.Equal(paginatedBookEntities.Data.Count, result.Data.Count);
|
||||
Assert.Equal(paginatedBookEntities.CurrentPage, result.CurrentPage);
|
||||
Assert.Equal(paginatedBookEntities.PerPage, result.PerPage);
|
||||
Assert.Equal(paginatedBookEntities.Count, result.Count);
|
||||
@@ -406,7 +408,7 @@ public class BookEntityMappingTests
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(results);
|
||||
Assert.Equal(bookEntities.Count, results.Count());
|
||||
Assert.Equal(bookEntities.Count, results.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -414,21 +416,19 @@ public class BookEntityMappingTests
|
||||
{
|
||||
// Arrange
|
||||
List<BookEntity> bookEntities = _bookEntityFixture.CreateMany(2);
|
||||
PaginatedResultDto<BookEntity> paginatedBookEntities = new()
|
||||
{
|
||||
Data = bookEntities,
|
||||
CurrentPage = 1,
|
||||
PerPage = 10,
|
||||
Count = 2,
|
||||
NumberOfPages = 1
|
||||
};
|
||||
PaginatedResultDto<BookEntity> paginatedBookEntities = _paginatedResultDtoFixture.Create(
|
||||
data: bookEntities,
|
||||
currentPage: 1,
|
||||
perPage: 10,
|
||||
count: 2,
|
||||
numberOfPages: 1);
|
||||
|
||||
// Act
|
||||
PaginatedResponse<BookLiteResponse> result = paginatedBookEntities.ToLiteResponses();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(paginatedBookEntities.Data.Count(), result.Data.Count());
|
||||
Assert.Equal(paginatedBookEntities.Data.Count, result.Data.Count);
|
||||
Assert.Equal(paginatedBookEntities.CurrentPage, result.CurrentPage);
|
||||
Assert.Equal(paginatedBookEntities.PerPage, result.PerPage);
|
||||
Assert.Equal(paginatedBookEntities.Count, result.Count);
|
||||
|
||||
+3
-2
@@ -1,7 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.Common;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
|
||||
@@ -21,6 +21,7 @@ public class BookMetadataDtoMappingTests
|
||||
{
|
||||
private readonly BookFixture _bookFixture = new();
|
||||
private readonly BookMetadataDtoFixture _bookMetadataDtoFixture = new();
|
||||
private readonly GenreDtoFixture _genreDtoFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ApplyMetadata_WhenCalledWithValidMetadata_ShouldApplyItAndMarkTheBookAsEnriched()
|
||||
@@ -59,7 +60,7 @@ public class BookMetadataDtoMappingTests
|
||||
title: "The Fellowship of the Ring",
|
||||
goodreadsId: "3") with
|
||||
{
|
||||
Genres = [new GenreDto("")]
|
||||
Genres = [_genreDtoFixture.Create(name: "")]
|
||||
};
|
||||
|
||||
// Act
|
||||
|
||||
+12
-9
@@ -2,6 +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.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;
|
||||
@@ -19,11 +20,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenConten
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class IsbnEntityMappingTests
|
||||
{
|
||||
private readonly IsbnEntityFixture _isbnEntityFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenMappingValidIsbnEntity_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
IsbnEntity entity = new("0-7475-3269-9", IsbnFormat.Isbn10);
|
||||
IsbnEntity entity = _isbnEntityFixture.Create(value: "0-7475-3269-9", format: IsbnFormat.Isbn10);
|
||||
|
||||
// Act
|
||||
IsbnDto result = entity.ToResponse();
|
||||
@@ -40,7 +43,7 @@ public class IsbnEntityMappingTests
|
||||
public void ToResponse_WhenMappingDifferentValidIsbnEntities_ShouldMapCorrectly(string value, IsbnFormat format)
|
||||
{
|
||||
// Arrange
|
||||
IsbnEntity entity = new(value, format);
|
||||
IsbnEntity entity = _isbnEntityFixture.Create(value: value, format: format);
|
||||
|
||||
// Act
|
||||
IsbnDto result = entity.ToResponse();
|
||||
@@ -58,7 +61,7 @@ public class IsbnEntityMappingTests
|
||||
public void ToResponse_WhenMappingInvalidIsbnEntity_ShouldPreserveValues(string? value, IsbnFormat? format)
|
||||
{
|
||||
// Arrange
|
||||
IsbnEntity entity = new(value, format);
|
||||
IsbnEntity entity = _isbnEntityFixture.Create(value: value, format: format, includeValue: value is not null);
|
||||
|
||||
// Act
|
||||
IsbnDto result = entity.ToResponse();
|
||||
@@ -72,7 +75,7 @@ public class IsbnEntityMappingTests
|
||||
public void ToDomainEntity_WhenMappingValidIsbnEntity_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
IsbnEntity entity = new("0-7475-3269-9", IsbnFormat.Isbn10);
|
||||
IsbnEntity entity = _isbnEntityFixture.Create(value: "0-7475-3269-9", format: IsbnFormat.Isbn10);
|
||||
|
||||
// Act
|
||||
Result<Isbn> result = entity.ToDomainEntity();
|
||||
@@ -91,7 +94,7 @@ public class IsbnEntityMappingTests
|
||||
public void ToDomainEntity_WhenMappingInvalidIsbnEntity_ShouldReturnError(string? invalidValue)
|
||||
{
|
||||
// Arrange
|
||||
IsbnEntity entity = new(invalidValue, null);
|
||||
IsbnEntity entity = _isbnEntityFixture.Create(value: invalidValue, includeValue: invalidValue is not null);
|
||||
|
||||
// Act
|
||||
Result<Isbn> result = entity.ToDomainEntity();
|
||||
@@ -106,8 +109,8 @@ public class IsbnEntityMappingTests
|
||||
// Arrange
|
||||
List<IsbnEntity> entities =
|
||||
[
|
||||
new IsbnEntity("0-7475-3269-9", IsbnFormat.Isbn10),
|
||||
new IsbnEntity("978-0-7475-3269-9", IsbnFormat.Isbn13)
|
||||
_isbnEntityFixture.Create(value: "0-7475-3269-9", format: IsbnFormat.Isbn10),
|
||||
_isbnEntityFixture.Create(value: "978-0-7475-3269-9", format: IsbnFormat.Isbn13)
|
||||
];
|
||||
|
||||
// Act
|
||||
@@ -132,8 +135,8 @@ public class IsbnEntityMappingTests
|
||||
// Arrange
|
||||
List<IsbnEntity> entities =
|
||||
[
|
||||
new IsbnEntity("0-7475-3269-9", IsbnFormat.Isbn10),
|
||||
new IsbnEntity("978-0-7475-3269-9", IsbnFormat.Isbn13)
|
||||
_isbnEntityFixture.Create(value: "0-7475-3269-9", format: IsbnFormat.Isbn10),
|
||||
_isbnEntityFixture.Create(value: "978-0-7475-3269-9", format: IsbnFormat.Isbn13)
|
||||
];
|
||||
|
||||
// Act
|
||||
|
||||
+13
-63
@@ -4,10 +4,11 @@ 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.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate;
|
||||
using System;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
@@ -21,6 +22,8 @@ namespace Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users;
|
||||
public class UserMappingTests
|
||||
{
|
||||
private readonly UserFixture _userFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToRepositoryEntity_WhenMappingValidUser_ShouldOnlyUpdateUsername()
|
||||
@@ -28,19 +31,7 @@ public class UserMappingTests
|
||||
// Arrange
|
||||
User domainEntity = _userFixture.Create(username: "newusername");
|
||||
|
||||
UserEntity repositoryEntity = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Username = "oldusername",
|
||||
Password = "hashedpassword",
|
||||
TotpSecret = "totpsecret",
|
||||
Libraries = [],
|
||||
UserPermissions = [],
|
||||
UserRole = null,
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedOnUtc = null
|
||||
};
|
||||
UserEntity repositoryEntity = _userEntityFixture.Create(username: "oldusername", password: "hashedpassword");
|
||||
|
||||
// Act
|
||||
UserEntity result = domainEntity.ToRepositoryEntity(repositoryEntity);
|
||||
@@ -73,18 +64,7 @@ public class UserMappingTests
|
||||
// Arrange
|
||||
User domainEntity = _userFixture.Create(username: newUsername);
|
||||
|
||||
UserEntity repositoryEntity = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Username = "oldusername",
|
||||
Password = "hashedpassword",
|
||||
Libraries = [],
|
||||
UserPermissions = [],
|
||||
UserRole = null,
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedOnUtc = null
|
||||
};
|
||||
UserEntity repositoryEntity = _userEntityFixture.Create(username: "oldusername", password: "hashedpassword");
|
||||
|
||||
// Act
|
||||
UserEntity result = domainEntity.ToRepositoryEntity(repositoryEntity);
|
||||
@@ -102,44 +82,14 @@ public class UserMappingTests
|
||||
|
||||
List<LibraryEntity> libraries =
|
||||
[
|
||||
new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = Guid.NewGuid(),
|
||||
Title = "Library 1",
|
||||
LibraryType = LibraryType.Book,
|
||||
ContentLocations = [],
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
UpdatedOnUtc = null,
|
||||
UpdatedBy = null
|
||||
},
|
||||
new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = Guid.NewGuid(),
|
||||
Title = "Library 2",
|
||||
LibraryType = LibraryType.Movie,
|
||||
ContentLocations = [],
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
UpdatedOnUtc = null,
|
||||
UpdatedBy = null
|
||||
}
|
||||
_libraryEntityFixture.Create(title: "Library 1", libraryType: LibraryType.Book, contentLocations: []),
|
||||
_libraryEntityFixture.Create(title: "Library 2", libraryType: LibraryType.Movie, contentLocations: [])
|
||||
];
|
||||
|
||||
UserEntity repositoryEntity = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Username = "oldusername",
|
||||
Password = "hashedpassword",
|
||||
Libraries = libraries,
|
||||
UserPermissions = [],
|
||||
UserRole = null,
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedOnUtc = null
|
||||
};
|
||||
UserEntity repositoryEntity = _userEntityFixture.Create(
|
||||
username: "oldusername",
|
||||
password: "hashedpassword",
|
||||
libraries: libraries);
|
||||
|
||||
// Act
|
||||
UserEntity result = domainEntity.ToRepositoryEntity(repositoryEntity);
|
||||
|
||||
Loaded 100 of 190 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user