Adds book editing tests and parameterizes the shared test fixtures

This commit is contained in:
BinaryAlley committed 2026-09-06 09:37:55 -07:00
1 parent 1bfa07ba5d
commit 145185d715
354 files changed
+7118 -1743

No files matched your search

@@ -23,7 +23,7 @@ public class RoleEntityFixture
/// <param name="id">Optional. The Id of the role.</param>
/// <param name="roleName">Optional. The name of the role.</param>
/// <param name="rolePermissions">Optional. The role permission associations of the role.</param>
/// <param name="includeRolePermissions">Whether the role should include role permission associations or not.</param>
/// <param name="includeRolePermissions">Whether the role permission associations should be included, or forced to an empty collection.</param>
/// <param name="createdBy">Optional. The Id of the user that created the role.</param>
/// <param name="createdOnUtc">Optional. The time and date when the role was added.</param>
/// <returns>The created <see cref="RoleEntity"/>.</returns>
@@ -87,9 +87,10 @@ public class LibraryEntityFixture
/// Creates a list of <see cref="LibraryEntity"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <param name="userId">Optional. The Id of the user that owns the created media libraries.</param>
/// <returns>List of configured <see cref="LibraryEntity"/> instances.</returns>
public List<LibraryEntity> CreateMany(int count = 3)
public List<LibraryEntity> CreateMany(int count = 3, Guid? userId = null)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
return [.. Enumerable.Range(0, count).Select(_ => Create(userId: userId))];
}
}
@@ -28,7 +28,7 @@ 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>
/// <param name="includeMetadata">Whether the owned metadata collections (Tags, Genres, ISBNs, Ratings) should be included, or forced to empty collections.</param>
/// <returns>The created <see cref="BookEntity"/>.</returns>
public BookEntity Create(
Guid? id = null,
@@ -26,7 +26,7 @@ public class BookRatingEntityFixture
/// <param name="maxValue">Optional. The maximum possible rating value.</param>
/// <param name="source">Optional. The rating source.</param>
/// <param name="voteCount">Optional. The number of votes.</param>
/// <param name="includeValues">Whether the rating properties should be populated. Set to <see langword="false"/> to create an invalid entity.</param>
/// <param name="includeValues">Whether the rating properties should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created book rating entity.</returns>
public BookRatingEntity Create(
decimal? value = null,
@@ -26,18 +26,18 @@ public class ThemeEntityFixture
/// <param name="author">Optional author of the theme.</param>
/// <param name="version">Optional version of the theme.</param>
/// <param name="previewPath">Optional preview image path of the theme, or <see langword="null"/> when the theme has no preview.</param>
/// <param name="includePreviewPath">Whether to set <paramref name="previewPath"/>, or <see langword="null"/> when <see langword="false"/>.</param>
/// <param name="includePreviewPath">Whether the preview path should be included, or forced to <see langword="null"/>.</param>
/// <param name="installSource">Optional source the theme was installed from.</param>
/// <param name="isCurrent">Optional value indicating whether the theme is the currently active one.</param>
/// <param name="includeIsCurrent">Whether to set <paramref name="isCurrent"/>, or <see langword="null"/> when <see langword="false"/>.</param>
/// <param name="includeIsCurrent">Whether the currently active flag should be included, or forced to <see langword="null"/>.</param>
/// <param name="isDeleted">Optional value indicating whether the theme was soft deleted.</param>
/// <param name="installedAtUtc">Optional UTC timestamp when the theme was installed.</param>
/// <param name="createdOnUtc">Optional UTC timestamp when the entity was created.</param>
/// <param name="createdBy">Optional Id of the user that created the entity.</param>
/// <param name="updatedOnUtc">Optional UTC timestamp when the entity was updated.</param>
/// <param name="includeUpdatedOnUtc">Whether to set <paramref name="updatedOnUtc"/>, or <see langword="null"/> when <see langword="false"/>.</param>
/// <param name="includeUpdatedOnUtc">Whether the updated-on timestamp should be included, or forced to <see langword="null"/>.</param>
/// <param name="updatedBy">Optional Id of the user that updated the entity.</param>
/// <param name="includeUpdatedBy">Whether to set <paramref name="updatedBy"/>, or <see langword="null"/> when <see langword="false"/>.</param>
/// <param name="includeUpdatedBy">Whether the updated-by user Id should be included, or forced to <see langword="null"/>.</param>
/// <returns>A configured <see cref="ThemeEntity"/> instance.</returns>
public ThemeEntity Create(
Guid? id = null,
@@ -3,7 +3,7 @@ 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;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
@@ -18,6 +18,8 @@ namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement
[ExcludeFromCodeCoverage]
public class UserEntityFixture
{
private readonly LibraryEntityFixture _libraryEntityFixture = new();
/// <summary>
/// Creates a random valid <see cref="UserEntity"/>.
/// </summary>
@@ -27,8 +29,8 @@ public class UserEntityFixture
/// <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="includeUserRole">Whether the user role association should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeUserPermissions">Whether the user permission associations should be included, or forced to an empty collection.</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(
@@ -44,7 +46,7 @@ public class UserEntityFixture
{
Guid userId = id ?? Guid.NewGuid();
ICollection<LibraryEntity> resolvedLibraries = libraries ?? (libraryCount > 0
? CreateLibraries(libraryCount, userId)
? _libraryEntityFixture.CreateMany(libraryCount, userId)
: []);
return new Faker<UserEntity>()
@@ -77,28 +79,4 @@ public class UserEntityFixture
{
return [.. Enumerable.Range(0, count).Select(_ => Create(libraryCount))];
}
/// <summary>
/// Creates a valid collection of user libraries.
/// </summary>
/// <param name="count">The number of user libraries to create.</param>
/// <param name="userId">The unique identifier of the user for whom to create the libraries.</param>
/// <returns>A collection of <see cref="LibraryEntity"/>.</returns>
private static List<LibraryEntity> CreateLibraries(int count, Guid userId)
{
return new Faker<LibraryEntity>()
.CustomInstantiator(f => new LibraryEntity
{
Id = Guid.NewGuid(),
UserId = userId,
Title = f.Commerce.ProductName(),
LibraryType = f.PickRandom<LibraryType>(),
ContentLocations = [],
CreatedOnUtc = f.Date.Past(),
CreatedBy = userId,
UpdatedOnUtc = null,
UpdatedBy = null
})
.Generate(count);
}
}
@@ -25,7 +25,7 @@ public class ThemeManifestDtoFixture
/// <param name="author">Optional author of the theme.</param>
/// <param name="version">Optional version of the theme.</param>
/// <param name="preview">Optional preview image path of the theme, or <see langword="null"/> when the theme has no preview.</param>
/// <param name="includePreview">Whether to set <paramref name="preview"/>, or <see langword="null"/> when <see langword="false"/>.</param>
/// <param name="includePreview">Whether the preview path should be included, or forced to <see langword="null"/>.</param>
/// <param name="templates">Optional template mappings of the theme.</param>
/// <returns>A configured <see cref="ThemeManifestDto"/> instance.</returns>
public ThemeManifestDto Create(
@@ -1,15 +1,15 @@
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using Bogus;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook;
using Lumina.Application.Fixtures.Common.Setup;
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
@@ -22,173 +22,59 @@ namespace Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.Bo
[ExcludeFromCodeCoverage]
public class AddBookCommandFixture
{
private readonly Fixture _fixture = new();
private readonly Random _random = new();
private readonly Faker _faker = new();
/// <summary>
/// Initializes a new instance of the <see cref="AddBookCommandFixture"/> class.
/// </summary>
public AddBookCommandFixture()
{
_fixture.Customizations.Add(new DateOnlySpecimenBuilder());
_fixture.Customizations.Add(new NullableDateOnlySpecimenBuilder());
}
private readonly IsbnDtoFixture _isbnDtoFixture = new();
private readonly BookRatingDtoFixture _bookRatingDtoFixture = new();
private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new();
private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new();
/// <summary>
/// Creates a random valid command 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="includeMetadata">Whether the metadata 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 forced to <see langword="null"/>.</param>
/// <returns>The created command to add a book.</returns>
public AddBookCommand Create()
public AddBookCommand 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 includeMetadata = true,
bool includeOptionalProperties = true)
{
int releaseYear = _random.Next(2000, 2010);
int reReleaseYear = _random.Next(2010, 2020);
ReleaseInfoDto releaseInfo = new Faker<ReleaseInfoDto>()
.CustomInstantiator(f => new ReleaseInfoDto(
default,
default,
default,
default,
default,
default
))
.RuleFor(x => x.OriginalReleaseDate, _faker.DateOnlyBetween(new DateOnly(releaseYear, 1, 1), new DateOnly(releaseYear, 12, 31)))
.RuleFor(x => x.OriginalReleaseYear, releaseYear)
.RuleFor(x => x.ReReleaseDate, _faker.DateOnlyBetween(new DateOnly(reReleaseYear, 1, 1), new DateOnly(reReleaseYear, 12, 31)))
.RuleFor(x => x.ReReleaseYear, reReleaseYear)
.RuleFor(x => x.ReleaseCountry, f => f.Random.String2(2))
.RuleFor(x => x.ReleaseVersion, f => f.Random.String2(f.Random.Number(1, 50)))
.Generate();
Faker<GenreDto> genre = new Faker<GenreDto>()
.CustomInstantiator(f => new GenreDto(
default!
))
.RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50)));
Faker<TagDto> tag = new Faker<TagDto>()
.CustomInstantiator(f => new TagDto(
default!
))
.RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50)));
Faker<MediaContributorRoleDto> mediaContributorRole = new Faker<MediaContributorRoleDto>()
.CustomInstantiator(f => new MediaContributorRoleDto(
default!,
default!
))
.RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50)))
.RuleFor(e => e.Category, f => f.PickRandom<MediaContributorRoleCategory>());
Faker<MediaContributorNameDto> mediaContributorName = new Faker<MediaContributorNameDto>()
.CustomInstantiator(f => new MediaContributorNameDto(
default!,
default!
))
.RuleFor(e => e.DisplayName, f => f.Random.String2(f.Random.Number(1, 50)))
.RuleFor(e => e.LegalName, f => f.Random.String2(f.Random.Number(1, 50)));
Faker<MediaContributorDto> mediaContributor = new Faker<MediaContributorDto>()
.CustomInstantiator(f => new MediaContributorDto(
default!,
default!
))
.RuleFor(e => e.Name, mediaContributorName)
.RuleFor(e => e.Role, mediaContributorRole);
Faker<BookRatingDto> rating = new Faker<BookRatingDto>()
.CustomInstantiator(f => new BookRatingDto(
default,
default,
default,
default
))
.RuleFor(e => e.Value, _random.Next(1, 5))
.RuleFor(e => e.MaxValue, 5)
.RuleFor(e => e.Source, _fixture.Create<BookRatingSource>())
.RuleFor(e => e.VoteCount, _random.Next(1, 1000));
Faker<LanguageInfoDto> language = new Faker<LanguageInfoDto>()
.CustomInstantiator(f => new LanguageInfoDto(
default!,
default!,
default
))
.RuleFor(e => e.LanguageName, f => f.Random.String2(f.Random.Number(1, 50)))
.RuleFor(e => e.LanguageCode, f => f.Random.String2(2))
.RuleFor(e => e.NativeName, f => f.Random.String2(f.Random.Number(1, 50)));
Faker<LanguageInfoDto> originalLanguage = new Faker<LanguageInfoDto>()
.CustomInstantiator(f => new LanguageInfoDto(
default!,
default!,
default
))
.RuleFor(e => e.LanguageName, f => f.Random.String2(f.Random.Number(1, 50)))
.RuleFor(e => e.LanguageCode, f => f.Random.String2(2))
.RuleFor(e => e.NativeName, f => f.Random.String2(f.Random.Number(1, 50)));
Faker<WrittenContentMetadataDto> metadata = new Faker<WrittenContentMetadataDto>()
.CustomInstantiator(f => new WrittenContentMetadataDto(
default!,
default,
default,
default!,
default!,
default!,
default,
default,
default,
default
))
.RuleFor(x => x.Title, f => f.Random.String2(f.Random.Number(1, 255)))
.RuleFor(x => x.OriginalTitle, f => f.Random.String2(f.Random.Number(1, 255)))
.RuleFor(x => x.Description, f => f.Random.String2(f.Random.Number(1, 2000)))
.RuleFor(x => x.ReleaseInfo, releaseInfo)
.RuleFor(p => p.Genres, f => genre.Generate(f.Random.Number(1, 5)))
.RuleFor(x => x.Tags, f => tag.Generate(f.Random.Number(1, 5)))
.RuleFor(x => x.Language, language)
.RuleFor(x => x.OriginalLanguage, originalLanguage)
.RuleFor(x => x.Publisher, f => f.Random.String2(f.Random.Number(1, 100)))
.RuleFor(x => x.PageCount, _random.Next(100, 300));
Faker<IsbnDto> isbn = new Faker<IsbnDto>()
.CustomInstantiator(f => new IsbnDto(
default!,
default
))
.RuleFor(i => i.Value, f =>
{
bool isIsbn13 = f.Random.Bool();
if (isIsbn13)
{
string prefix = f.Random.Bool() ? "978" : "979";
string group = f.Random.Number(0, 99999).ToString().PadLeft(5, '0');
string publisher = f.Random.Number(0, 999999).ToString().PadLeft(6, '0');
string title = f.Random.Number(0, 99).ToString().PadLeft(2, '0');
string isbn = $"{prefix}{group[..1]}{publisher}{title}";
int sum = 0;
for (int i = 0; i < 12; i++)
sum += (i % 2 == 0 ? 1 : 3) * int.Parse(isbn[i].ToString());
int checkDigit = (10 - sum % 10) % 10;
return $"{prefix}-{group[..1]}-{publisher}-{title}-{checkDigit}";
}
else
{
int[] digits = new int[9];
for (int i = 0; i < 9; i++)
digits[i] = f.Random.Number(0, 9);
int sum = 0;
for (int i = 0; i < 9; i++)
sum += (10 - i) * digits[i];
int checkDigit = (11 - sum % 11) % 11;
string checkChar = checkDigit == 10 ? "X" : checkDigit.ToString();
return $"{digits[0]}-{digits[1]}{digits[2]}-{digits[3]}{digits[4]}{digits[5]}{digits[6]}{digits[7]}{digits[8]}-{checkChar}";
}
})
.RuleFor(i => i.Format, (f, i) => i.Value!.Length > 13 ? IsbnFormat.Isbn13 : IsbnFormat.Isbn10);
return new Faker<AddBookCommand>()
.CustomInstantiator(f => new AddBookCommand(
default,
@@ -211,62 +97,101 @@ public class AddBookCommandFixture
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 ?? Guid.NewGuid())
.RuleFor(x => x.Path, f => path ?? f.System.FilePath())
.RuleFor(x => x.Metadata, includeMetadata ? (metadata ?? _writtenContentMetadataDtoFixture.Create()) : null)
.RuleFor(x => x.Format, f => format ?? (includeOptionalProperties ? f.PickRandom<BookFormat>() : null))
.RuleFor(x => x.Edition, f => edition ?? (includeOptionalProperties ? f.Random.String2(f.Random.Number(1, 50)) : null))
.RuleFor(x => x.VolumeNumber, f => volumeNumber ?? (includeOptionalProperties ? (float?)f.Random.Number(1, 3) : null))
.RuleFor(x => x.Series, series)
.RuleFor(x => x.ASIN, f => asin ?? (includeOptionalProperties ? f.Random.String2(10) : null))
.RuleFor(x => x.GoodreadsId, f => goodreadsId ?? (includeOptionalProperties ? f.Random.Number(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 ? [.. _isbnDtoFixture.CreateMany(f.Random.Number(1, 3))] : null))
.RuleFor(p => p.Ratings, f => ratings ?? (includeOptionalProperties ? [.. _bookRatingDtoFixture.CreateMany(f.Random.Number(1, 3))] : null))
.RuleFor(x => x.Contributors, f => contributors ?? (includeOptionalProperties ? [.. _mediaContributorDtoFixture.CreateMany(f.Random.Number(1, 3))] : null));
}
/// <summary>
/// Creates a list of <see cref="AddBookCommand"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<AddBookCommand> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
/// <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)])]);
}
}
@@ -0,0 +1,194 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook;
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook;
/// <summary>
/// Fixture class for the <see cref="UpdateBookCommand"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateBookCommandFixture
{
private readonly IsbnDtoFixture _isbnDtoFixture = new();
private readonly BookRatingDtoFixture _bookRatingDtoFixture = new();
private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new();
private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new();
/// <summary>
/// Creates a random valid command to update a book.
/// </summary>
/// <param name="id">Optional. The Id of the book to update.</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="includeMetadata">Whether the metadata 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 forced to <see langword="null"/>.</param>
/// <returns>The created command to update a book.</returns>
public UpdateBookCommand Create(
Guid? id = 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 includeMetadata = true,
bool includeOptionalProperties = true)
{
return new Faker<UpdateBookCommand>()
.CustomInstantiator(f => new UpdateBookCommand(
default,
default!,
default,
default,
default,
default,
default,
default,
default,
default,
default,
default,
default,
default,
default,
default!,
default!,
default!
))
.RuleFor(x => x.Id, id ?? Guid.NewGuid())
.RuleFor(x => x.Metadata, includeMetadata ? (metadata ?? _writtenContentMetadataDtoFixture.Create()) : null)
.RuleFor(x => x.Format, f => format ?? (includeOptionalProperties ? f.PickRandom<BookFormat>() : null))
.RuleFor(x => x.Edition, f => edition ?? (includeOptionalProperties ? f.Random.String2(f.Random.Number(1, 50)) : null))
.RuleFor(x => x.VolumeNumber, f => volumeNumber ?? (includeOptionalProperties ? (float?)f.Random.Number(1, 3) : null))
.RuleFor(x => x.Series, series)
.RuleFor(x => x.ASIN, f => asin ?? (includeOptionalProperties ? f.Random.String2(10) : null))
.RuleFor(x => x.GoodreadsId, f => goodreadsId ?? (includeOptionalProperties ? f.Random.Number(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 ? [.. _isbnDtoFixture.CreateMany(f.Random.Number(1, 3))] : null))
.RuleFor(p => p.Ratings, f => ratings ?? (includeOptionalProperties ? [.. _bookRatingDtoFixture.CreateMany(f.Random.Number(1, 3))] : null))
.RuleFor(x => x.Contributors, f => contributors ?? (includeOptionalProperties ? [.. _mediaContributorDtoFixture.CreateMany(f.Random.Number(1, 3))] : null));
}
/// <summary>
/// Creates a list of <see cref="UpdateBookCommand"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<UpdateBookCommand> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
/// <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)])]);
}
}
@@ -0,0 +1,59 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBookCover;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Text;
#endregion
namespace Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBookCover;
/// <summary>
/// Fixture class for the <see cref="UpdateBookCoverCommand"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateBookCoverCommandFixture
{
/// <summary>
/// Creates a random valid <see cref="UpdateBookCoverCommand"/>.
/// </summary>
/// <param name="bookId">Optional. The Id of the book whose cover is updated.</param>
/// <param name="cover">Optional. The stream of the uploaded cover image file.</param>
/// <param name="fileName">Optional. The name of the uploaded cover image file.</param>
/// <param name="includeCover">Whether the cover stream should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="UpdateBookCoverCommand"/>.</returns>
public UpdateBookCoverCommand Create(
Guid? bookId = null,
Stream? cover = null,
string? fileName = null,
bool includeCover = true)
{
return new UpdateBookCoverCommand(
bookId ?? Guid.NewGuid(),
includeCover ? (cover ?? CreateCoverStream()) : null,
fileName ?? "cover.jpg"
);
}
/// <summary>
/// Creates a list of <see cref="UpdateBookCoverCommand"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="UpdateBookCoverCommand"/> instances.</returns>
public List<UpdateBookCoverCommand> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
/// <summary>
/// Creates an in-memory stream carrying a minimal file payload.
/// </summary>
/// <returns>A non-empty in-memory stream.</returns>
private static Stream CreateCoverStream()
{
byte[] payload = Encoding.UTF8.GetBytes("fake cover payload");
return new MemoryStream(payload);
}
}
@@ -0,0 +1,37 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBook;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBook;
/// <summary>
/// Fixture class for the <see cref="GetBookQuery"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetBookQueryFixture
{
/// <summary>
/// Creates a random valid <see cref="GetBookQuery"/>.
/// </summary>
/// <param name="id">Optional. The Id of the book to get.</param>
/// <returns>The created <see cref="GetBookQuery"/>.</returns>
public GetBookQuery Create(
Guid? id = null)
{
return new GetBookQuery(id ?? Guid.NewGuid());
}
/// <summary>
/// Creates a list of <see cref="GetBookQuery"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="GetBookQuery"/> instances.</returns>
public List<GetBookQuery> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -28,7 +28,7 @@ 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>
/// <param name="includePaginationData">Whether the pagination data should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created query to get books.</returns>
public GetBooksQuery Create(
Guid? libraryId = null,
@@ -30,7 +30,7 @@ public class GetBooksLiteQueryFixture
/// <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>
/// <param name="includePaginationData">Whether the pagination data should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created query to get the lightweight details of books.</returns>
public GetBooksLiteQuery Create(
Guid? libraryId = null,
@@ -20,8 +20,8 @@ public class GetScheduledJobHistoryQueryFixture
/// </summary>
/// <param name="from">Optional. The inclusive lower bound of the requested interval.</param>
/// <param name="to">Optional. The inclusive upper bound of the requested interval.</param>
/// <param name="includeFrom">Whether to include the lower bound in the query. When false, the lower bound is left unset.</param>
/// <param name="includeTo">Whether to include the upper bound in the query. When false, the upper bound is left unset.</param>
/// <param name="includeFrom">Whether the lower bound should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeTo">Whether the upper bound should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created query.</returns>
public GetScheduledJobHistoryQuery Create(
DateTime? from = null,
@@ -19,7 +19,7 @@ public class LoginUserQueryFixture
/// </summary>
/// <param name="username">Optional. The username.</param>
/// <param name="password">Optional. The password.</param>
/// <param name="includeTotpCode">Whether to include a TOTP code in the query.</param>
/// <param name="includeTotpCode">Whether the TOTP code should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created query.</returns>
public LoginUserQuery Create(
string? username = null,
@@ -20,5 +20,6 @@
<ItemGroup>
<ProjectReference Include="..\..\..\src\Lumina.Application\Lumina.Application.csproj" />
<ProjectReference Include="..\Lumina.Contracts.Fixtures\Lumina.Contracts.Fixtures.csproj" />
</ItemGroup>
</Project>
@@ -22,16 +22,22 @@ public class LanguageInfoDtoFixture
/// <param name="languageCode">Optional. The ISO code of the language.</param>
/// <param name="languageName">Optional. The name of the language in English.</param>
/// <param name="nativeName">Optional. The native name of the language.</param>
/// <param name="includeLanguageCode">Whether the language code should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeLanguageName">Whether the language name should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeNativeName">Whether the native name should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="LanguageInfoDto"/>.</returns>
public LanguageInfoDto Create(
string? languageCode = null,
string? languageName = null,
string? nativeName = null)
string? languageCode = null,
string? languageName = null,
string? nativeName = null,
bool includeLanguageCode = true,
bool includeLanguageName = true,
bool includeNativeName = true)
{
return new LanguageInfoDto(
languageCode ?? _faker.Random.String2(2),
languageName ?? _faker.Lorem.Word(),
nativeName ?? _faker.Lorem.Word());
includeLanguageCode ? (languageCode ?? _faker.Random.String2(2)) : null,
includeLanguageName ? (languageName ?? _faker.Lorem.Word()) : null,
includeNativeName ? (nativeName ?? _faker.Lorem.Word()) : null);
}
/// <summary>
@@ -15,7 +15,7 @@ namespace Lumina.Contracts.Fixtures.Core.DTO.Common;
public class ReleaseInfoDtoFixture
{
/// <summary>
/// Creates an <see cref="ReleaseInfoDto"/>, preserving the values that are not provided as <see langword="null"/>.
/// Creates a <see cref="ReleaseInfoDto"/>, preserving the values that are not provided as <see langword="null"/>.
/// </summary>
/// <param name="originalReleaseDate">Optional. The original release date of the content.</param>
/// <param name="originalReleaseYear">Optional. The original release year of the content.</param>
@@ -23,6 +23,12 @@ public class ReleaseInfoDtoFixture
/// <param name="reReleaseYear">Optional. The re-release year of the content.</param>
/// <param name="releaseCountry">Optional. The country where the content was released.</param>
/// <param name="releaseVersion">Optional. The version or edition of the content's release.</param>
/// <param name="includeOriginalReleaseDate">Whether the original release date should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeOriginalReleaseYear">Whether the original release year should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeReReleaseDate">Whether the re-release date should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeReReleaseYear">Whether the re-release year should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeReleaseCountry">Whether the release country should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeReleaseVersion">Whether the release version should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="ReleaseInfoDto"/>.</returns>
public ReleaseInfoDto Create(
DateOnly? originalReleaseDate = null,
@@ -30,15 +36,21 @@ public class ReleaseInfoDtoFixture
DateOnly? reReleaseDate = null,
int? reReleaseYear = null,
string? releaseCountry = null,
string? releaseVersion = null)
string? releaseVersion = null,
bool includeOriginalReleaseDate = true,
bool includeOriginalReleaseYear = true,
bool includeReReleaseDate = true,
bool includeReReleaseYear = true,
bool includeReleaseCountry = true,
bool includeReleaseVersion = true)
{
return new ReleaseInfoDto(
originalReleaseDate,
originalReleaseYear,
reReleaseDate,
reReleaseYear,
releaseCountry,
releaseVersion);
includeOriginalReleaseDate ? originalReleaseDate : null,
includeOriginalReleaseYear ? originalReleaseYear : null,
includeReReleaseDate ? reReleaseDate : null,
includeReReleaseYear ? reReleaseYear : null,
includeReleaseCountry ? releaseCountry : null,
includeReleaseVersion ? releaseVersion : null);
}
/// <summary>
@@ -23,15 +23,33 @@ public class MediaContributorDtoFixture
/// <param name="displayName">Optional. The display name of the media contributor.</param>
/// <param name="roleName">Optional. The name of the role assigned to the media contributor.</param>
/// <param name="roleCategory">Optional. The category of the role.</param>
/// <param name="legalName">Optional. The legal name of the media contributor.</param>
/// <param name="includeName">Whether the name should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeDisplayName">Whether the display name should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeLegalName">Whether the legal name should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeRole">Whether the role should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeRoleName">Whether the role name should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeRoleCategory">Whether the role category should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="MediaContributorDto"/>.</returns>
public MediaContributorDto Create(
string? displayName = null,
string? roleName = null,
MediaContributorRoleCategory? roleCategory = null)
MediaContributorRoleCategory? roleCategory = null,
string? legalName = null,
bool includeName = true,
bool includeDisplayName = true,
bool includeLegalName = true,
bool includeRole = true,
bool includeRoleName = true,
bool includeRoleCategory = true)
{
return new MediaContributorDto(
Name: new MediaContributorNameDto(DisplayName: displayName ?? _faker.Name.FullName(), LegalName: null),
Role: new MediaContributorRoleDto(Name: roleName ?? _faker.Commerce.Department(), Category: roleCategory ?? _faker.PickRandom<MediaContributorRoleCategory>()));
Name: includeName ? new MediaContributorNameDto(
DisplayName: includeDisplayName ? displayName ?? _faker.Name.FullName() : null,
LegalName: includeLegalName ? legalName : null) : null,
Role: includeRole ? new MediaContributorRoleDto(
Name: includeRoleName ? roleName ?? _faker.Commerce.Department() : null,
Category: includeRoleCategory ? roleCategory ?? _faker.PickRandom<MediaContributorRoleCategory>() : null) : null);
}
/// <summary>
@@ -3,6 +3,7 @@ using Bogus;
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Contracts.Fixtures.Core.DTO.Common;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using System;
using System.Collections.Generic;
@@ -19,6 +20,10 @@ namespace Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.
public class BookMetadataDtoFixture
{
private readonly Faker _faker = new();
private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new();
private readonly GenreDtoFixture _genreDtoFixture = new();
private readonly TagDtoFixture _tagDtoFixture = new();
private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new();
/// <summary>
/// Creates a random valid <see cref="BookMetadataDto"/>.
@@ -51,7 +56,7 @@ public class BookMetadataDtoFixture
/// <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>
/// <param name="includeOptionalProperties">Whether the properties that are not explicitly provided should be randomized, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="BookMetadataDto"/>.</returns>
public BookMetadataDto Create(
string? title = null,
@@ -89,10 +94,13 @@ public class BookMetadataDtoFixture
includeTitle ? title ?? (includeOptionalProperties ? _faker.Lorem.Sentence(3) : null) : null,
originalTitle,
description,
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),
releaseInfo ?? (includeOptionalProperties ? _releaseInfoDtoFixture.Create(
originalReleaseDate: new DateOnly(releaseYear, 1, 1),
originalReleaseYear: releaseYear,
releaseCountry: _faker.Address.CountryCode()) : null),
genres ?? (includeOptionalProperties ? [_genreDtoFixture.Create()] : null),
tags ?? (includeOptionalProperties ? [_tagDtoFixture.Create()] : null),
language ?? (includeOptionalProperties ? _languageInfoDtoFixture.Create() : null),
originalLanguage,
publisher,
pageCount,
@@ -26,7 +26,7 @@ public class BookRatingDtoFixture
/// <param name="maxValue">Optional. The maximum possible rating value.</param>
/// <param name="source">Optional. The rating source.</param>
/// <param name="voteCount">Optional. The number of votes.</param>
/// <param name="includeOptionalProperties">Whether the optional source and vote count should be included.</param>
/// <param name="includeOptionalProperties">Whether the optional source and vote count should be randomized, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="BookRatingDto"/>.</returns>
public BookRatingDto Create(
decimal? value = null,
@@ -38,8 +38,8 @@ public class BookRatingDtoFixture
return new BookRatingDto(
value ?? _random.Next(1, 5),
maxValue ?? 5,
includeOptionalProperties ? (source ?? _fixture.Create<BookRatingSource>()) : null,
includeOptionalProperties ? (voteCount ?? _random.Next(1, 1000)) : null
source ?? (includeOptionalProperties ? _fixture.Create<BookRatingSource>() : null),
voteCount ?? (includeOptionalProperties ? _random.Next(1, 1000) : null)
);
}
@@ -28,7 +28,7 @@ public class IsbnDtoFixture
string resolvedValue = value ?? (format == IsbnFormat.Isbn10 ? GenerateValidIsbn10() : GenerateValidIsbn13());
return new IsbnDto(
resolvedValue,
format
format ?? (resolvedValue.Length > 13 ? IsbnFormat.Isbn13 : IsbnFormat.Isbn10)
);
}
@@ -42,6 +42,10 @@ public class IsbnDtoFixture
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
/// <summary>
/// Generates a valid ISBN-10 with the correct checksum.
/// </summary>
/// <returns>A valid ISBN-10 value.</returns>
private string GenerateValidIsbn10()
{
int[] digits = new int[9];
@@ -58,6 +62,10 @@ public class IsbnDtoFixture
return $"{digits[0]}-{digits[1]}{digits[2]}-{digits[3]}{digits[4]}{digits[5]}{digits[6]}{digits[7]}{digits[8]}-{checkChar}";
}
/// <summary>
/// Generates a valid ISBN-13 with the correct checksum.
/// </summary>
/// <returns>A valid ISBN-13 value.</returns>
private string GenerateValidIsbn13()
{
string prefix = _random.Next(2) == 0 ? "978" : "979";
@@ -1,6 +1,9 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary;
using Lumina.Contracts.Fixtures.Core.DTO.Common;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
@@ -14,8 +17,14 @@ namespace Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary;
[ExcludeFromCodeCoverage]
public class WrittenContentMetadataDtoFixture
{
private readonly Faker _faker = new();
private readonly Random _random = new();
private readonly GenreDtoFixture _genreDtoFixture = new();
private readonly TagDtoFixture _tagDtoFixture = new();
private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new();
/// <summary>
/// Creates a <see cref="WrittenContentMetadataDto"/> with the requested values, leaving unspecified properties as <see langword="null"/>.
/// Creates a random valid <see cref="WrittenContentMetadataDto"/>.
/// </summary>
/// <param name="title">Optional. The title of the written content.</param>
/// <param name="originalTitle">Optional. The original title of the written content.</param>
@@ -27,6 +36,16 @@ public class WrittenContentMetadataDtoFixture
/// <param name="originalLanguage">Optional. The original language of the written content.</param>
/// <param name="publisher">Optional. The name of the publisher of the written content.</param>
/// <param name="pageCount">Optional. The number of pages in the written content.</param>
/// <param name="includeTitle">Whether the title should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeOriginalTitle">Whether the original title should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeDescription">Whether the description should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeReleaseInfo">Whether the release information should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeGenres">Whether the genres should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeTags">Whether the tags should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeLanguage">Whether the language should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeOriginalLanguage">Whether the original language should be included, or forced to <see langword="null"/>.</param>
/// <param name="includePublisher">Whether the publisher should be included, or forced to <see langword="null"/>.</param>
/// <param name="includePageCount">Whether the page count should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="WrittenContentMetadataDto"/>.</returns>
public WrittenContentMetadataDto Create(
string? title = null,
@@ -38,19 +57,29 @@ public class WrittenContentMetadataDtoFixture
LanguageInfoDto? language = null,
LanguageInfoDto? originalLanguage = null,
string? publisher = null,
int? pageCount = null)
int? pageCount = null,
bool includeTitle = true,
bool includeOriginalTitle = true,
bool includeDescription = true,
bool includeReleaseInfo = true,
bool includeGenres = true,
bool includeTags = true,
bool includeLanguage = true,
bool includeOriginalLanguage = true,
bool includePublisher = true,
bool includePageCount = true)
{
return new WrittenContentMetadataDto(
title,
originalTitle,
description,
releaseInfo,
genres,
tags,
language,
originalLanguage,
publisher,
pageCount);
includeTitle ? (title ?? _faker.Commerce.ProductName()) : null,
includeOriginalTitle ? (originalTitle ?? _faker.Commerce.ProductName()) : null,
includeDescription ? (description ?? _faker.Lorem.Paragraph()) : null,
includeReleaseInfo ? (releaseInfo ?? CreateReleaseInfo()) : null,
includeGenres ? (genres ?? [_genreDtoFixture.Create(), _genreDtoFixture.Create()]) : null,
includeTags ? (tags ?? [_tagDtoFixture.Create(), _tagDtoFixture.Create()]) : null,
includeLanguage ? (language ?? _languageInfoDtoFixture.Create()) : null,
includeOriginalLanguage ? (originalLanguage ?? _languageInfoDtoFixture.Create()) : null,
includePublisher ? (publisher ?? _faker.Company.CompanyName()) : null,
includePageCount ? (pageCount ?? _faker.Random.Int(1, 1000)) : null);
}
/// <summary>
@@ -62,4 +91,21 @@ public class WrittenContentMetadataDtoFixture
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
/// <summary>
/// Creates a random valid <see cref="ReleaseInfoDto"/> with consistent dates and years.
/// </summary>
/// <returns>The created <see cref="ReleaseInfoDto"/>.</returns>
private ReleaseInfoDto CreateReleaseInfo()
{
int originalReleaseYear = _random.Next(1900, 2026);
int reReleaseYear = _random.Next(originalReleaseYear, 2026);
return new ReleaseInfoDto(
new DateOnly(originalReleaseYear, 1, 1),
originalReleaseYear,
new DateOnly(reReleaseYear, 1, 1),
reReleaseYear,
_faker.Address.CountryCode(),
_faker.Random.String2(_faker.Random.Number(1, 50)));
}
}
@@ -20,9 +20,11 @@ public class GetDirectoriesRequestFixture
/// Creates a <see cref="GetDirectoriesRequest"/> with default or random values.
/// </summary>
/// <param name="path">Optional. The file system path for which to get the directories.</param>
/// <param name="includeHiddenElements">Optional. Whether to include hidden file system elements.</param>
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
/// <returns>The created <see cref="GetDirectoriesRequest"/>.</returns>
public GetDirectoriesRequest Create(string? path = null, bool? includeHiddenElements = null)
public GetDirectoriesRequest Create(
string? path = null,
bool? includeHiddenElements = null)
{
return new GetDirectoriesRequest(
Path: path ?? _faker.System.FilePath(),
@@ -20,9 +20,11 @@ public class GetFilesRequestFixture
/// Creates a <see cref="GetFilesRequest"/> with default or random values.
/// </summary>
/// <param name="path">Optional. The file system path for which to get the files.</param>
/// <param name="includeHiddenElements">Optional. Whether to include hidden file system elements.</param>
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
/// <returns>The created <see cref="GetFilesRequest"/>.</returns>
public GetFilesRequest Create(string? path = null, bool? includeHiddenElements = null)
public GetFilesRequest Create(
string? path = null,
bool? includeHiddenElements = null)
{
return new GetFilesRequest(
Path: path ?? _faker.System.FilePath(),
@@ -20,9 +20,11 @@ public class GetTreeFilesRequestFixture
/// Creates a <see cref="GetTreeFilesRequest"/> with default or random values.
/// </summary>
/// <param name="path">Optional. The file system path for which to get the tree files.</param>
/// <param name="includeHiddenElements">Optional. Whether to include hidden file system elements.</param>
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
/// <returns>The created <see cref="GetTreeFilesRequest"/>.</returns>
public GetTreeFilesRequest Create(string? path = null, bool? includeHiddenElements = null)
public GetTreeFilesRequest Create(
string? path = null,
bool? includeHiddenElements = null)
{
return new GetTreeFilesRequest(
Path: path ?? _faker.System.FilePath(),
@@ -20,9 +20,11 @@ public class CheckPathExistsRequestFixture
/// Creates a <see cref="CheckPathExistsRequest"/> with default or random values.
/// </summary>
/// <param name="path">Optional. The path to check.</param>
/// <param name="includeHiddenElements">Optional. Whether to include hidden elements.</param>
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
/// <returns>The created <see cref="CheckPathExistsRequest"/>.</returns>
public CheckPathExistsRequest Create(string? path = null, bool? includeHiddenElements = null)
public CheckPathExistsRequest Create(
string? path = null,
bool? includeHiddenElements = null)
{
return new CheckPathExistsRequest(
Path: path ?? _faker.System.FilePath(),
@@ -1,14 +1,13 @@
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using Bogus;
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Contracts.Fixtures.Common.Setup;
using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
@@ -23,18 +22,10 @@ namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLib
[ExcludeFromCodeCoverage]
public class AddBookRequestFixture
{
private readonly Fixture _fixture = new();
private readonly Random _random = new();
private readonly Faker _faker = new();
/// <summary>
/// Initializes a new instance of the <see cref="AddBookRequestFixture"/> class.
/// </summary>
public AddBookRequestFixture()
{
_fixture.Customizations.Add(new DateOnlySpecimenBuilder());
_fixture.Customizations.Add(new NullableDateOnlySpecimenBuilder());
}
private readonly IsbnDtoFixture _isbnDtoFixture = new();
private readonly BookRatingDtoFixture _bookRatingDtoFixture = new();
private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new();
private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new();
/// <summary>
/// Creates a random valid request to add a book.
@@ -58,7 +49,7 @@ public class AddBookRequestFixture
/// <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>
/// <param name="includeOptionalProperties">Whether the properties that are not explicitly provided should be randomized, or forced to <see langword="null"/>.</param>
/// <returns>The created request to add a book.</returns>
public AddBookRequest Create(
Guid? libraryId = null,
@@ -82,154 +73,6 @@ public class AddBookRequestFixture
List<BookRatingDto>? ratings = null,
bool includeOptionalProperties = true)
{
int releaseYear = _random.Next(2000, 2010);
int reReleaseYear = _random.Next(2010, 2020);
ReleaseInfoDto releaseInfo = new Faker<ReleaseInfoDto>()
.CustomInstantiator(f => new ReleaseInfoDto(
default,
default,
default,
default,
default,
default
))
.RuleFor(x => x.OriginalReleaseDate, _faker.DateOnlyBetween(new DateOnly(releaseYear, 1, 1), new DateOnly(releaseYear, 12, 31)))
.RuleFor(x => x.OriginalReleaseYear, releaseYear)
.RuleFor(x => x.ReReleaseDate, _faker.DateOnlyBetween(new DateOnly(reReleaseYear, 1, 1), new DateOnly(reReleaseYear, 12, 31)))
.RuleFor(x => x.ReReleaseYear, reReleaseYear)
.RuleFor(x => x.ReleaseCountry, f => f.Random.String2(2))
.RuleFor(x => x.ReleaseVersion, f => f.Random.String2(f.Random.Number(1, 50)))
.Generate();
Faker<GenreDto> genre = new Faker<GenreDto>()
.CustomInstantiator(f => new GenreDto(
default!
))
.RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50)));
Faker<TagDto> tag = new Faker<TagDto>()
.CustomInstantiator(f => new TagDto(
default!
))
.RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50)));
Faker<MediaContributorRoleDto> mediaContributorRole = new Faker<MediaContributorRoleDto>()
.CustomInstantiator(f => new MediaContributorRoleDto(
default!,
default!
))
.RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50)))
.RuleFor(e => e.Category, f => f.PickRandom<MediaContributorRoleCategory>());
Faker<MediaContributorNameDto> mediaContributorName = new Faker<MediaContributorNameDto>()
.CustomInstantiator(f => new MediaContributorNameDto(
default!,
default!
))
.RuleFor(e => e.DisplayName, f => f.Random.String2(f.Random.Number(1, 50)))
.RuleFor(e => e.LegalName, f => f.Random.String2(f.Random.Number(1, 50)));
Faker<MediaContributorDto> mediaContributor = new Faker<MediaContributorDto>()
.CustomInstantiator(f => new MediaContributorDto(
default!,
default!
))
.RuleFor(e => e.Name, mediaContributorName)
.RuleFor(e => e.Role, mediaContributorRole);
Faker<BookRatingDto> rating = new Faker<BookRatingDto>()
.CustomInstantiator(f => new BookRatingDto(
default,
default,
default,
default
))
.RuleFor(e => e.Value, _random.Next(1, 5))
.RuleFor(e => e.MaxValue, 5)
.RuleFor(e => e.Source, _fixture.Create<BookRatingSource>())
.RuleFor(e => e.VoteCount, _random.Next(1, 1000));
Faker<LanguageInfoDto> language = new Faker<LanguageInfoDto>()
.CustomInstantiator(f => new LanguageInfoDto(
default!,
default!,
default
))
.RuleFor(e => e.LanguageName, f => f.Random.String2(f.Random.Number(1, 50)))
.RuleFor(e => e.LanguageCode, f => f.Random.String2(2))
.RuleFor(e => e.NativeName, f => f.Random.String2(f.Random.Number(1, 50)));
Faker<LanguageInfoDto> originalLanguage = new Faker<LanguageInfoDto>()
.CustomInstantiator(f => new LanguageInfoDto(
default!,
default!,
default
))
.RuleFor(e => e.LanguageName, f => f.Random.String2(f.Random.Number(1, 50)))
.RuleFor(e => e.LanguageCode, f => f.Random.String2(2))
.RuleFor(e => e.NativeName, f => f.Random.String2(f.Random.Number(1, 50)));
Faker<WrittenContentMetadataDto> metadataFaker = new Faker<WrittenContentMetadataDto>()
.CustomInstantiator(f => new WrittenContentMetadataDto(
default!,
default,
default,
default!,
default!,
default!,
default,
default,
default,
default
))
.RuleFor(x => x.Title, f => f.Random.String2(f.Random.Number(1, 255)))
.RuleFor(x => x.OriginalTitle, f => f.Random.String2(f.Random.Number(1, 255)))
.RuleFor(x => x.Description, f => f.Random.String2(f.Random.Number(1, 2000)))
.RuleFor(x => x.ReleaseInfo, releaseInfo)
.RuleFor(p => p.Genres, f => genre.Generate(f.Random.Number(1, 5)))
.RuleFor(x => x.Tags, f => tag.Generate(f.Random.Number(1, 5)))
.RuleFor(x => x.Language, language)
.RuleFor(x => x.OriginalLanguage, originalLanguage)
.RuleFor(x => x.Publisher, f => f.Random.String2(f.Random.Number(1, 100)))
.RuleFor(x => x.PageCount, _random.Next(100, 300));
Faker<IsbnDto> isbn = new Faker<IsbnDto>()
.CustomInstantiator(f => new IsbnDto(
default!,
default
))
.RuleFor(i => i.Value, f =>
{
bool isIsbn13 = f.Random.Bool();
if (isIsbn13)
{
string prefix = f.Random.Bool() ? "978" : "979";
string group = f.Random.Number(0, 99999).ToString().PadLeft(5, '0');
string publisher = f.Random.Number(0, 999999).ToString().PadLeft(6, '0');
string title = f.Random.Number(0, 99).ToString().PadLeft(2, '0');
string isbn = $"{prefix}{group[..1]}{publisher}{title}";
int sum = 0;
for (int i = 0; i < 12; i++)
sum += (i % 2 == 0 ? 1 : 3) * int.Parse(isbn[i].ToString());
int checkDigit = (10 - sum % 10) % 10;
return $"{prefix}-{group[..1]}-{publisher}-{title}-{checkDigit}";
}
else
{
int[] digits = new int[9];
for (int i = 0; i < 9; i++)
digits[i] = f.Random.Number(0, 9);
int sum = 0;
for (int i = 0; i < 9; i++)
sum += (10 - i) * digits[i];
int checkDigit = (11 - sum % 11) % 11;
string checkChar = checkDigit == 10 ? "X" : checkDigit.ToString();
return $"{digits[0]}-{digits[1]}{digits[2]}-{digits[3]}{digits[4]}{digits[5]}{digits[6]}{digits[7]}{digits[8]}-{checkChar}";
}
})
.RuleFor(i => i.Format, (f, i) => i.Value!.Length > 13 ? IsbnFormat.Isbn13 : IsbnFormat.Isbn10);
return new Faker<AddBookRequest>()
.CustomInstantiator(f => new AddBookRequest(
default,
@@ -246,21 +89,21 @@ public class AddBookRequestFixture
default,
default,
default,
default!,
default,
default!,
default!,
default!,
default!
))
.RuleFor(x => x.LibraryId, libraryId ?? _fixture.Create<Guid>())
.RuleFor(x => x.LibraryId, libraryId ?? Guid.NewGuid())
.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.Metadata, metadata ?? _writtenContentMetadataDtoFixture.Create())
.RuleFor(x => x.Format, f => format ?? (includeOptionalProperties ? f.PickRandom<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.VolumeNumber, f => volumeNumber ?? (includeOptionalProperties ? (float?)f.Random.Number(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.GoodreadsId, f => goodreadsId ?? (includeOptionalProperties ? f.Random.Number(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))
@@ -268,9 +111,9 @@ public class AddBookRequestFixture
.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));
.RuleFor(p => p.ISBNs, f => isbns ?? (includeOptionalProperties ? [.. _isbnDtoFixture.CreateMany(f.Random.Number(1, 3))] : null))
.RuleFor(p => p.Ratings, f => ratings ?? (includeOptionalProperties ? [.. _bookRatingDtoFixture.CreateMany(f.Random.Number(1, 3))] : null))
.RuleFor(x => x.Contributors, f => contributors ?? (includeOptionalProperties ? [.. _mediaContributorDtoFixture.CreateMany(f.Random.Number(1, 3))] : null));
}
/// <summary>
@@ -29,6 +29,8 @@ public class GetBooksLiteRequestFixture
/// <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="includeCurrentPage">Whether the current page should be included, or forced to <see langword="null"/>.</param>
/// <param name="includePerPage">Whether the per page count should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="GetBooksLiteRequest"/>.</returns>
public GetBooksLiteRequest Create(
Guid? libraryId = null,
@@ -38,12 +40,14 @@ public class GetBooksLiteRequestFixture
string? filterAlphaKey = null,
bool shouldIgnoreThePrefixForAlphaPicker = false,
string? sortBy = null,
SortOrder? sortOrder = null)
SortOrder? sortOrder = null,
bool includeCurrentPage = true,
bool includePerPage = true)
{
return new GetBooksLiteRequest(
LibraryId: libraryId ?? _faker.Random.Guid(),
CurrentPage: currentPage ?? _faker.Random.Number(1, 100),
PerPage: perPage ?? _faker.Random.Number(1, 200),
CurrentPage: includeCurrentPage ? (currentPage ?? _faker.Random.Number(1, 100)) : null,
PerPage: includePerPage ? (perPage ?? _faker.Random.Number(1, 200)) : null,
SearchTerm: searchTerm ?? _faker.Lorem.Word(),
FilterAlphaKey: filterAlphaKey,
ShouldIgnoreThePrefixForAlphaPicker: shouldIgnoreThePrefixForAlphaPicker,
@@ -27,6 +27,8 @@ public class GetBooksRequestFixture
/// <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="includeCurrentPage">Whether the current page should be included, or forced to <see langword="null"/>.</param>
/// <param name="includePerPage">Whether the per page count should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="GetBooksRequest"/>.</returns>
public GetBooksRequest Create(
Guid? libraryId = null,
@@ -34,12 +36,14 @@ public class GetBooksRequestFixture
int? perPage = null,
string? searchTerm = null,
string? sortBy = null,
SortOrder? sortOrder = null)
SortOrder? sortOrder = null,
bool includeCurrentPage = true,
bool includePerPage = true)
{
return new GetBooksRequest(
LibraryId: libraryId ?? _faker.Random.Guid(),
CurrentPage: currentPage ?? _faker.Random.Number(1, 100),
PerPage: perPage ?? _faker.Random.Number(1, 200),
CurrentPage: includeCurrentPage ? (currentPage ?? _faker.Random.Number(1, 100)) : null,
PerPage: includePerPage ? (perPage ?? _faker.Random.Number(1, 200)) : null,
SearchTerm: searchTerm ?? _faker.Lorem.Word(),
SortBy: sortBy ?? _faker.Lorem.Word(),
SortOrder: sortOrder ?? _faker.PickRandom<SortOrder>()
@@ -0,0 +1,185 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
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
namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
/// <summary>
/// Fixture class for the <see cref="UpdateBookRequest"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateBookRequestFixture
{
private readonly IsbnDtoFixture _isbnDtoFixture = new();
private readonly BookRatingDtoFixture _bookRatingDtoFixture = new();
private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new();
private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new();
/// <summary>
/// Creates a random valid request to update a book.
/// </summary>
/// <param name="id">Optional. The Id of the book to update.</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 forced to <see langword="null"/>.</param>
/// <param name="rawId">Optional. The raw string value of the Id of the book to update. Takes precedence over <paramref name="id"/>.</param>
/// <param name="includeId">Whether the Id should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created request to update a book.</returns>
public UpdateBookRequest Create(
Guid? id = 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,
string? rawId = null,
bool includeId = true)
{
return new Faker<UpdateBookRequest>()
.CustomInstantiator(f => new UpdateBookRequest(
default,
default!,
default,
default,
default,
default,
default,
default,
default,
default,
default,
default,
default,
default,
default,
default!,
default!,
default!
))
.RuleFor(x => x.Id, f => includeId ? (rawId ?? id?.ToString() ?? Guid.NewGuid().ToString()) : null)
.RuleFor(x => x.Metadata, metadata ?? _writtenContentMetadataDtoFixture.Create())
.RuleFor(x => x.Format, f => format ?? (includeOptionalProperties ? f.PickRandom<BookFormat>() : null))
.RuleFor(x => x.Edition, f => edition ?? (includeOptionalProperties ? f.Random.String2(f.Random.Number(1, 50)) : null))
.RuleFor(x => x.VolumeNumber, f => volumeNumber ?? (includeOptionalProperties ? (float?)f.Random.Number(1, 3) : null))
.RuleFor(x => x.Series, series)
.RuleFor(x => x.ASIN, f => asin ?? (includeOptionalProperties ? f.Random.String2(10) : null))
.RuleFor(x => x.GoodreadsId, f => goodreadsId ?? (includeOptionalProperties ? f.Random.Number(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 ? [.. _isbnDtoFixture.CreateMany(f.Random.Number(1, 3))] : null))
.RuleFor(p => p.Ratings, f => ratings ?? (includeOptionalProperties ? [.. _bookRatingDtoFixture.CreateMany(f.Random.Number(1, 3))] : null))
.RuleFor(x => x.Contributors, f => contributors ?? (includeOptionalProperties ? [.. _mediaContributorDtoFixture.CreateMany(f.Random.Number(1, 3))] : 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)])]);
}
}
@@ -24,18 +24,22 @@ public class BookLiteResponseFixture
/// <param name="title">Optional. The title of the book.</param>
/// <param name="releaseYear">Optional. The release year of the book.</param>
/// <param name="coverPath">Optional. The path of the image representing the cover of the book.</param>
/// <param name="includeReleaseYear">Whether the release year should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeCoverPath">Whether the cover path should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="BookLiteResponse"/>.</returns>
public BookLiteResponse Create(
Guid? id = null,
string? title = null,
int? releaseYear = null,
string? coverPath = null)
string? coverPath = null,
bool includeReleaseYear = true,
bool includeCoverPath = true)
{
return new BookLiteResponse(
id ?? Guid.NewGuid(),
title ?? _faker.Commerce.ProductName(),
releaseYear ?? _faker.Random.Int(1900, 2024),
coverPath ?? _faker.System.FilePath()
includeReleaseYear ? (releaseYear ?? _faker.Random.Int(1900, 2024)) : null,
includeCoverPath ? (coverPath ?? _faker.System.FilePath()) : null
);
}
@@ -28,10 +28,10 @@ public class ThemeResponseFixture
/// <param name="author">Optional. The author of the theme.</param>
/// <param name="version">Optional. The version of the theme.</param>
/// <param name="previewPath">Optional. The preview image path of the theme, or <see langword="null"/> when the theme has no preview.</param>
/// <param name="includePreviewPath">Whether to set <paramref name="previewPath"/>, or <see langword="null"/> when <see langword="false"/>.</param>
/// <param name="includePreviewPath">Whether the preview path should be included, or forced to <see langword="null"/>.</param>
/// <param name="installSource">Optional. The source the theme was installed from.</param>
/// <param name="isCurrent">Optional. Whether the theme is the currently active one.</param>
/// <param name="includeIsCurrent">Whether to set <paramref name="isCurrent"/>, or <see langword="null"/> when <see langword="false"/>.</param>
/// <param name="includeIsCurrent">Whether the currently active flag should be included, or forced to <see langword="null"/>.</param>
/// <param name="installedAtUtc">Optional. The UTC timestamp when the theme was installed.</param>
/// <param name="isDeleted">Optional. Whether the theme was deleted by the user.</param>
/// <returns>The created <see cref="ThemeResponse"/>.</returns>
@@ -28,7 +28,7 @@ public class FileFixture
/// <param name="dateModified">Optional. The file's modification date. If not provided, a recent date is generated.</param>
/// <param name="size">Optional. The file size. If not provided, a random size is generated.</param>
/// <param name="status">Optional. The file's status. If not provided, a random status is assigned.</param>
/// <param name="includeDates">Whether the file should include creation and modification dates.</param>
/// <param name="includeDates">Whether the creation and modification dates should be included, or left unset.</param>
/// <returns>The created <see cref="File"/>.</returns>
public File Create(
string? path = null,
@@ -2,9 +2,11 @@
using Bogus;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
@@ -22,6 +24,9 @@ public class LibraryFixture
{
private readonly Faker _faker = new();
private readonly Random _random = new();
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly UserIdFixture _userIdFixture = new();
private readonly ScanIdFixture _scanIdFixture = new();
/// <summary>
/// Creates a random valid <see cref="Library"/> domain aggregate.
@@ -32,7 +37,7 @@ public class LibraryFixture
/// <param name="libraryType">Optional. The library type.</param>
/// <param name="contentLocations">Optional. The content locations of the library.</param>
/// <param name="coverImage">Optional. The cover image of the library.</param>
/// <param name="includeCoverImage">Whether to include a cover image or not.</param>
/// <param name="includeCoverImage">Whether the cover image should be included, or forced to <see langword="null"/>.</param>
/// <param name="isEnabled">Whether the library is enabled.</param>
/// <param name="isLocked">Whether the library is locked.</param>
/// <param name="canDownloadMetadataFromWeb">Whether metadata download from the web is enabled.</param>
@@ -63,12 +68,13 @@ public class LibraryFixture
"F:/Content"
];
List<ScanId> resolvedScanIds = scanIds is null ? [ScanId.CreateUnique(), ScanId.CreateUnique()] : [.. scanIds.Select(scanId => ScanId.Create(scanId))];
UserId resolvedUserId = userId is null ? _userIdFixture.Create() : _userIdFixture.Create(userId.Value);
List<ScanId> resolvedScanIds = scanIds is null ? [.. _scanIdFixture.CreateMany(2)] : [.. scanIds.Select(scanId => _scanIdFixture.Create(scanId))];
string? resolvedCoverImage = includeCoverImage ? (coverImage ?? _faker.System.FilePath()) : null;
Result<Library> library = id is null ?
Library.Create(
userId is not null ? UserId.Create(userId.Value) : UserId.CreateUnique(),
resolvedUserId,
title ?? _faker.Random.String2(_faker.Random.Number(1, 50)),
libraryType ?? _faker.PickRandom<LibraryType>(),
contentLocations ?? validPaths.Take(_random.Next(1, validPaths.Count)),
@@ -81,8 +87,8 @@ public class LibraryFixture
resolvedScanIds
) :
Library.Create(
LibraryId.Create(id.Value),
userId is not null ? UserId.Create(userId.Value) : UserId.CreateUnique(),
_libraryIdFixture.Create(id.Value),
resolvedUserId,
title ?? _faker.Random.String2(_faker.Random.Number(1, 50)),
libraryType ?? _faker.PickRandom<LibraryType>(),
contentLocations ?? validPaths.Take(_random.Next(1, validPaths.Count)),
@@ -29,7 +29,7 @@ public class LibraryScanFailedDomainEventFixture
/// <param name="mediaLibraryScanCompositeId">Optional. The composite identifier of the media library scan that has failed.</param>
/// <param name="occurredOnUtc">Optional. The date and time when the domain event occurred.</param>
/// <param name="errorMessage">Optional. The descriptive message of the failure.</param>
/// <param name="includeErrorMessage">Whether to include an error message in the domain event. When false, the error message is left unset.</param>
/// <param name="includeErrorMessage">Whether the error message should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="LibraryScanFailedDomainEvent"/>.</returns>
public LibraryScanFailedDomainEvent Create(
Guid? id = null,
@@ -1,13 +1,12 @@
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using Bogus;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Common.ValueObjects.Metadata;
using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Fixtures.Common.Setup;
using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using System;
@@ -24,46 +23,76 @@ namespace Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBound
[ExcludeFromCodeCoverage]
public class BookFixture
{
private readonly Fixture _fixture = new();
private readonly Faker _faker = new();
private readonly WrittenContentMetadataFixture _writtenContentMetadataFixture = new();
private readonly IsbnFixture _isbnFixture = new();
private readonly BookRatingFixture _bookRatingFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="BookFixture"/> class.
/// </summary>
public BookFixture()
{
_fixture.Customizations.Add(new DateOnlySpecimenBuilder());
_fixture.Customizations.Add(new NullableDateOnlySpecimenBuilder());
ConfigureCustomDomainTypes();
}
private readonly MediaContributorIdFixture _mediaContributorIdFixture = new();
/// <summary>
/// Creates a random valid <see cref="Book"/> domain aggregate.
/// </summary>
/// <param name="libraryId">Optional. The Id of the media library this 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 media contributors of the book.</param>
/// <param name="ratings">Optional. The ratings of the book.</param>
/// <returns>The created <see cref="Book"/> domain aggregate.</returns>
public Book Create()
public Book Create(
Guid? libraryId = null,
string? path = null,
WrittenContentMetadata? metadata = null,
BookFormat? format = null,
string? edition = null,
float? volumeNumber = null,
BookSeries? 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<Isbn>? isbns = null,
List<MediaContributorId>? contributors = null,
List<BookRating>? ratings = null)
{
return Book.Create(
LibraryId.Create(_fixture.Create<Guid>()),
_fixture.Create<string>(),
_fixture.Create<WrittenContentMetadata>(),
_fixture.Create<BookFormat>(),
_fixture.Create<Optional<string>>(),
_fixture.Create<Optional<float>>(),
_fixture.Create<Optional<BookSeries>>(),
_fixture.Create<Optional<string>>(),
_fixture.Create<Optional<string>>(),
_fixture.Create<Optional<string>>(),
_fixture.Create<Optional<string>>(),
_fixture.Create<Optional<string>>(),
_fixture.Create<Optional<string>>(),
_fixture.Create<Optional<string>>(),
_fixture.Create<Optional<string>>(),
_fixture.Create<Optional<string>>(),
_fixture.Create<List<Isbn>>(),
_fixture.Create<List<MediaContributorId>>(),
_fixture.Create<List<BookRating>>()
libraryId is null ? LibraryId.Create(Guid.NewGuid()) : LibraryId.Create(libraryId.Value),
path ?? _faker.System.FilePath(),
metadata ?? _writtenContentMetadataFixture.Create(),
format ?? _faker.PickRandom<BookFormat>(),
edition is null ? Optional<string>.Some(_faker.Commerce.ProductName()) : Optional<string>.Some(edition),
volumeNumber is null ? Optional<float>.None() : Optional<float>.Some(volumeNumber.Value),
series is null ? Optional<BookSeries>.None() : Optional<BookSeries>.Some(series),
asin is null ? Optional<string>.Some(_faker.Random.String2(10)) : Optional<string>.Some(asin),
goodreadsId is null ? Optional<string>.Some(_faker.Random.Number(100000, 500000).ToString()) : Optional<string>.Some(goodreadsId),
lccn is null ? Optional<string>.Some(_faker.Random.String2(_faker.Random.Number(8, 10))) : Optional<string>.Some(lccn),
oclcNumber is null ? Optional<string>.Some($"ocm{_faker.Random.String2(8, "0123456789")}") : Optional<string>.Some(oclcNumber),
openLibraryId is null ? Optional<string>.Some($"OL{_faker.Random.Number(100000, 999999)}{_faker.Random.ArrayElement(['A', 'M', 'W'])}") : Optional<string>.Some(openLibraryId),
libraryThingId is null ? Optional<string>.Some(_faker.Random.String2(_faker.Random.Number(1, 50))) : Optional<string>.Some(libraryThingId),
googleBooksId is null ? Optional<string>.Some(_faker.Random.String2(12)) : Optional<string>.Some(googleBooksId),
barnesAndNobleId is null ? Optional<string>.Some(_faker.Random.String2(10, "0123456789")) : Optional<string>.Some(barnesAndNobleId),
appleBooksId is null ? Optional<string>.Some($"id{_faker.Random.Number(1, 999999)}") : Optional<string>.Some(appleBooksId),
isbns ?? [.. Enumerable.Range(0, _faker.Random.Number(1, 4)).Select(_ => _isbnFixture.Create())],
contributors ?? [.. Enumerable.Range(0, _faker.Random.Number(1, 4)).Select(_ => _mediaContributorIdFixture.Create())],
ratings ?? [.. Enumerable.Range(0, _faker.Random.Number(1, 4)).Select(_ => _bookRatingFixture.Create())]
).Value;
}
@@ -76,50 +105,4 @@ public class BookFixture
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
private void ConfigureCustomDomainTypes()
{
_fixture.Register(() => Optional<string>.Some(_fixture.Create<string>()));
_fixture.Register(() => Optional<int>.Some(_fixture.Create<int>()));
_fixture.Register(() =>
{
int originalYear = Random.Shared.Next(1900, 2026);
int reReleaseYear = Random.Shared.Next(originalYear, 2026);
return ReleaseInfo.Create(
Optional<DateOnly>.Some(DateOnly.FromDateTime(new DateTime(originalYear, 1, 1))),
Optional<int>.Some(originalYear),
Optional<DateOnly>.Some(DateOnly.FromDateTime(new DateTime(reReleaseYear, 1, 1))),
Optional<int>.Some(reReleaseYear),
_fixture.Create<Optional<string>>(),
_fixture.Create<Optional<string>>()
).Value;
});
_fixture.Register(() => Genre.Create(
_fixture.Create<string>()
).Value);
_fixture.Register(() => Tag.Create(
_fixture.Create<string>()
).Value);
_fixture.Register(() => WrittenContentMetadata.Create(
_fixture.Create<string>(),
_fixture.Create<Optional<string>>(),
_fixture.Create<Optional<string>>(),
_fixture.Create<ReleaseInfo>(),
_fixture.Create<List<Genre>>(),
_fixture.Create<List<Tag>>(),
_fixture.Create<Optional<LanguageInfo>>(),
_fixture.Create<Optional<LanguageInfo>>(),
_fixture.Create<Optional<string>>(),
_fixture.Create<Optional<int>>()
).Value);
_fixture.Register(() => _isbnFixture.Create());
_fixture.Register(() => _bookRatingFixture.Create());
}
}
@@ -28,7 +28,7 @@ public sealed class ThemePackFixture
/// <param name="templates">Optional template mappings written to the manifest.</param>
/// <param name="preview">Optional preview path written to the manifest, or <see langword="null"/> to omit the preview.</param>
/// <param name="defaultTemplateContent">Optional content for the default template file.</param>
/// <param name="includePreviewAsset">Whether to include the preview asset file in the archive.</param>
/// <param name="includePreviewAsset">Whether to include the preview asset file in the archive or not.</param>
/// <param name="additionalFiles">Optional additional files written into the archive.</param>
/// <returns>The created theme pack ZIP archive.</returns>
public byte[] Create(
@@ -267,6 +267,24 @@ public class StubApiHttpClient : IApiHttpClient
throw new InvalidOperationException($"No PUT response is registered for the endpoint '{endpoint}'.");
}
/// <summary>
/// Sends a PUT request with a multipart form containing a single file to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the result.
/// </summary>
/// <typeparam name="TResponse">The expected type of the response content.</typeparam>
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
/// <param name="fileStream">The stream of the file to upload.</param>
/// <param name="fileName">The name of the file to upload.</param>
/// <param name="fieldName">The name of the form field carrying the file.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The deserialized response containing the result of the PUT request.</returns>
public Task<TResponse> PutMultipartAsync<TResponse>(string endpoint, Stream fileStream, string fileName, string fieldName, CancellationToken cancellationToken = default)
{
PutRequests.Add((endpoint, fileName));
if (_putResponseFactories.TryGetValue(endpoint, out Func<object, object>? responseFactory))
return Task.FromResult((TResponse)responseFactory(fileName));
throw new InvalidOperationException($"No PUT response is registered for the endpoint '{endpoint}'.");
}
/// <summary>
/// Sends a POST request with a multipart form containing a single file to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the result.
/// </summary>
@@ -0,0 +1,41 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Presentation.Web.Common.DTO.Common;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
/// <summary>
/// Fixture class for generating <see cref="GenreDto"/> test data.
/// </summary>
[ExcludeFromCodeCoverage]
public class GenreDtoFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a new <see cref="GenreDto"/> instance with randomized test data.
/// </summary>
/// <param name="name">Optional. The name of the genre.</param>
/// <returns>A configured <see cref="GenreDto"/> instance.</returns>
public GenreDto Create(string? name = null)
{
return new GenreDto
{
Name = name ?? _faker.Lorem.Word()
};
}
/// <summary>
/// Creates multiple <see cref="GenreDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="GenreDto"/> instances.</returns>
public List<GenreDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,48 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Presentation.Web.Common.DTO.Common;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
/// <summary>
/// Fixture class for generating <see cref="LanguageInfoDto"/> test data.
/// </summary>
[ExcludeFromCodeCoverage]
public class LanguageInfoDtoFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a new <see cref="LanguageInfoDto"/> instance with randomized test data.
/// </summary>
/// <param name="languageCode">Optional. The ISO 639-1 two-letter language code.</param>
/// <param name="languageName">Optional. The name of the language in English.</param>
/// <param name="nativeName">Optional. The native name of the language.</param>
/// <returns>A configured <see cref="LanguageInfoDto"/> instance.</returns>
public LanguageInfoDto Create(
string? languageCode = null,
string? languageName = null,
string? nativeName = null)
{
return new LanguageInfoDto
{
LanguageCode = languageCode ?? _faker.Random.String2(2, "abcdefghijklmnopqrstuvwxyz"),
LanguageName = languageName ?? _faker.Address.Country(),
NativeName = nativeName ?? _faker.Lorem.Word()
};
}
/// <summary>
/// Creates multiple <see cref="LanguageInfoDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="LanguageInfoDto"/> instances.</returns>
public List<LanguageInfoDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,64 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Presentation.Web.Common.DTO.Common;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
/// <summary>
/// Fixture class for generating <see cref="ReleaseInfoDto"/> test data.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReleaseInfoDtoFixture
{
private readonly Faker _faker = new();
private readonly Random _random = new();
/// <summary>
/// Creates a new <see cref="ReleaseInfoDto"/> instance with randomized test data.
/// </summary>
/// <param name="originalReleaseDate">Optional. The original release date of the content.</param>
/// <param name="originalReleaseYear">Optional. The original release year of the content.</param>
/// <param name="reReleaseDate">Optional. The re-release date of the content.</param>
/// <param name="reReleaseYear">Optional. The re-release year of the content.</param>
/// <param name="releaseCountry">Optional. The country where the content was released.</param>
/// <param name="releaseVersion">Optional. The version or edition of the content's release.</param>
/// <returns>A configured <see cref="ReleaseInfoDto"/> instance.</returns>
public ReleaseInfoDto Create(
DateOnly? originalReleaseDate = null,
int? originalReleaseYear = null,
DateOnly? reReleaseDate = null,
int? reReleaseYear = null,
string? releaseCountry = null,
string? releaseVersion = null)
{
int resolvedOriginalReleaseYear = originalReleaseYear ?? (originalReleaseDate?.Year ?? _random.Next(1900, 2026));
DateOnly resolvedOriginalReleaseDate = originalReleaseDate ?? new DateOnly(resolvedOriginalReleaseYear, 1, 1);
int resolvedReReleaseYear = reReleaseYear ?? (reReleaseDate?.Year ?? _random.Next(resolvedOriginalReleaseYear, resolvedOriginalReleaseYear + 100));
DateOnly resolvedReReleaseDate = reReleaseDate ?? new DateOnly(resolvedReReleaseYear, 1, 1);
return new ReleaseInfoDto
{
OriginalReleaseDate = resolvedOriginalReleaseDate,
OriginalReleaseYear = resolvedOriginalReleaseYear,
ReReleaseDate = resolvedReReleaseDate,
ReReleaseYear = resolvedReReleaseYear,
ReleaseCountry = releaseCountry ?? _faker.Address.CountryCode(),
ReleaseVersion = releaseVersion ?? _faker.Random.String2(_faker.Random.Number(1, 50))
};
}
/// <summary>
/// Creates multiple <see cref="ReleaseInfoDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="ReleaseInfoDto"/> instances.</returns>
public List<ReleaseInfoDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,41 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Presentation.Web.Common.DTO.Common;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
/// <summary>
/// Fixture class for generating <see cref="TagDto"/> test data.
/// </summary>
[ExcludeFromCodeCoverage]
public class TagDtoFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a new <see cref="TagDto"/> instance with randomized test data.
/// </summary>
/// <param name="name">Optional. The name of the tag.</param>
/// <returns>A configured <see cref="TagDto"/> instance.</returns>
public TagDto Create(string? name = null)
{
return new TagDto
{
Name = name ?? _faker.Lorem.Word()
};
}
/// <summary>
/// Creates multiple <see cref="TagDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="TagDto"/> instances.</returns>
public List<TagDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -23,7 +23,7 @@ public class DirectoryDtoFixture
/// <param name="path">Optional. The full path to the directory.</param>
/// <param name="name">Optional. The name of the directory.</param>
/// <param name="items">Optional. The children items of the directory.</param>
/// <param name="includeItems">Whether the directory should include children items, or an empty collection.</param>
/// <param name="includeItems">Whether the children items should be included, or forced to an empty collection.</param>
/// <returns>The created <see cref="DirectoryDto"/>.</returns>
public DirectoryDto Create(
string? path = null,
@@ -0,0 +1,59 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Presentation.Web.Common.DTO.MediaContributors;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.MediaContributors;
/// <summary>
/// Fixture class for generating <see cref="MediaContributorDto"/> test data.
/// </summary>
[ExcludeFromCodeCoverage]
public class MediaContributorDtoFixture
{
private static readonly string[] RoleCategories = ["Author", "Translator", "Illustrator", "Editor", "Narrator"];
private readonly Faker _faker = new();
/// <summary>
/// Creates a new <see cref="MediaContributorDto"/> instance with randomized test data.
/// </summary>
/// <param name="displayName">Optional. The name by which the contributor is popularly known.</param>
/// <param name="legalName">Optional. The legal name of the contributor.</param>
/// <param name="roleName">Optional. The name of the role of the contributor.</param>
/// <param name="roleCategory">Optional. The category of the role of the contributor.</param>
/// <returns>A configured <see cref="MediaContributorDto"/> instance.</returns>
public MediaContributorDto Create(
string? displayName = null,
string? legalName = null,
string? roleName = null,
string? roleCategory = null)
{
string resolvedRoleCategory = roleCategory ?? _faker.Random.ArrayElement(RoleCategories);
return new MediaContributorDto
{
Name = new MediaContributorNameDto
{
DisplayName = displayName ?? _faker.Name.FullName(),
LegalName = legalName ?? _faker.Name.FullName()
},
Role = new MediaContributorRoleDto
{
Name = roleName ?? resolvedRoleCategory.ToLowerInvariant(),
Category = resolvedRoleCategory
}
};
}
/// <summary>
/// Creates multiple <see cref="MediaContributorDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="MediaContributorDto"/> instances.</returns>
public List<MediaContributorDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -22,8 +22,8 @@ public class PluginSettingsDtoFixture
/// Creates a new <see cref="PluginSettingsDto"/> instance with randomized test data.
/// </summary>
/// <param name="pluginId">Optional unique identifier of the plugin.</param>
/// <param name="includeSettings">Whether to populate the current settings values, or leave them null.</param>
/// <param name="includeSchema">Whether to populate the settings schema, or leave it empty.</param>
/// <param name="includeSettings">Whether the current settings values should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeSchema">Whether the settings schema should be included, or forced to an empty collection.</param>
/// <returns>A configured <see cref="PluginSettingsDto"/> instance.</returns>
public PluginSettingsDto Create(
Guid? pluginId = null,
@@ -21,9 +21,9 @@ public class ThemeNavEntryDtoFixture
/// </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="includeUrl">Whether the URL should be included, or forced to <see langword="null"/>.</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="includeCssClass">Whether the CSS class should be included, or forced to <see langword="null"/>.</param>
/// <param name="children">Optional child links of a submenu.</param>
/// <returns>The created <see cref="ThemeNavEntryDto"/>.</returns>
public ThemeNavEntryDto Create(
@@ -28,10 +28,10 @@ public class ThemeResponseDtoFixture
/// <param name="author">Optional author of the theme.</param>
/// <param name="version">Optional semantic version of the theme.</param>
/// <param name="previewPath">Optional preview image path of the theme, or <see langword="null"/> when the theme has no preview.</param>
/// <param name="includePreviewPath">Whether to set <paramref name="previewPath"/>, or <see langword="null"/> when <see langword="false"/>.</param>
/// <param name="includePreviewPath">Whether the preview path should be included, or forced to <see langword="null"/>.</param>
/// <param name="installSource">Optional source the theme was installed from.</param>
/// <param name="isCurrent">Optional value indicating whether the theme is the active one.</param>
/// <param name="includeIsCurrent">Whether to set <paramref name="isCurrent"/>, or <see langword="null"/> when <see langword="false"/>.</param>
/// <param name="includeIsCurrent">Whether the currently active flag should be included, or forced to <see langword="null"/>.</param>
/// <param name="installedAtUtc">Optional UTC timestamp at which the theme was installed.</param>
/// <param name="isDeleted">Optional value indicating whether the theme was deleted by the user.</param>
/// <returns>A configured <see cref="ThemeResponseDto"/> instance.</returns>
@@ -0,0 +1,94 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary;
using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary;
using Lumina.Presentation.Web.Common.Enums.BookLibrary;
using Lumina.Presentation.Web.Fixtures.Common.DTO.MediaContributors;
using Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary;
using Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary;
/// <summary>
/// Fixture class for generating <see cref="BookDetailsDto"/> test data.
/// </summary>
[ExcludeFromCodeCoverage]
public class BookDetailsDtoFixture
{
private readonly Faker _faker = new();
private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new();
private readonly IsbnDtoFixture _isbnDtoFixture = new();
private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new();
private readonly BookRatingDtoFixture _bookRatingDtoFixture = new();
/// <summary>
/// Creates a new <see cref="BookDetailsDto"/> instance with randomized test data.
/// </summary>
/// <param name="id">Optional Id of the book.</param>
/// <param name="libraryId">Optional Id of the media library the book belongs to.</param>
/// <param name="path">Optional file system path of the book.</param>
/// <param name="metadata">Optional written content metadata of the book.</param>
/// <param name="includeMetadata">Whether the written content metadata should be included, or forced to <see langword="null"/>.</param>
/// <returns>A configured <see cref="BookDetailsDto"/> instance.</returns>
public BookDetailsDto Create(
Guid? id = null,
Guid? libraryId = null,
string? path = null,
WrittenContentMetadataDto? metadata = null,
bool includeMetadata = true)
{
return new BookDetailsDto
{
Id = id ?? _faker.Random.Guid(),
LibraryId = libraryId ?? _faker.Random.Guid(),
Path = path ?? _faker.System.FilePath(),
Metadata = metadata ?? (includeMetadata ? _writtenContentMetadataDtoFixture.Create() : null),
Format = _faker.PickRandom<BookFormat>(),
Edition = _faker.Random.String2(_faker.Random.Number(1, 50)),
VolumeNumber = _faker.Random.Number(1, 3),
ASIN = _faker.Random.String2(10),
GoodreadsId = _faker.Random.Number(100000, 500000).ToString(),
LCCN = "n78890351",
OCLCNumber = "ocm12345678",
OpenLibraryId = "OL123456M",
LibraryThingId = _faker.Random.String2(_faker.Random.Number(1, 50)),
GoogleBooksId = CreateGoogleBooksId(),
BarnesAndNobleId = _faker.Random.String2(10, "0123456789"),
AppleBooksId = $"id{_faker.Random.Number(1, 999999)}",
ISBNs = [.. _isbnDtoFixture.CreateMany(_faker.Random.Number(1, 3))],
Contributors = [.. _mediaContributorDtoFixture.CreateMany(_faker.Random.Number(1, 3))],
Ratings = [.. _bookRatingDtoFixture.CreateMany(_faker.Random.Number(1, 3))],
MetadataStatus = _faker.Random.String2(_faker.Random.Number(1, 20)),
LastMetadataUpdateUtc = _faker.Date.Recent(),
MetadataProvider = _faker.Random.String2(_faker.Random.Number(1, 20)),
CreatedOnUtc = _faker.Date.Past(),
UpdatedOnUtc = _faker.Date.Recent(),
CoverPath = _faker.System.FilePath()
};
}
/// <summary>
/// Creates a list of <see cref="BookDetailsDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="BookDetailsDto"/> instances.</returns>
public List<BookDetailsDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
/// <summary>
/// Generates a valid Google Books Id.
/// </summary>
/// <returns>The generated Google Books Id.</returns>
private string CreateGoogleBooksId()
{
const string VALID_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
return new string([.. Enumerable.Repeat(VALID_CHARS, 12).Select(s => s[_faker.Random.Number(VALID_CHARS.Length - 1)])]);
}
}
@@ -0,0 +1,53 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary;
using Lumina.Presentation.Web.Common.Enums.BookLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary;
/// <summary>
/// Fixture class for generating <see cref="BookRatingDto"/> test data.
/// </summary>
[ExcludeFromCodeCoverage]
public class BookRatingDtoFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a new <see cref="BookRatingDto"/> instance with randomized test data.
/// </summary>
/// <param name="value">Optional. The rating value.</param>
/// <param name="maxValue">Optional. The maximum possible rating value.</param>
/// <param name="voteCount">Optional. The number of votes the rating is based on.</param>
/// <param name="source">Optional. The source of the rating.</param>
/// <returns>A configured <see cref="BookRatingDto"/> instance.</returns>
public BookRatingDto Create(
decimal? value = null,
decimal? maxValue = null,
int? voteCount = null,
BookRatingSource? source = null)
{
return new BookRatingDto
{
Value = value ?? _faker.Random.Decimal(1, 5),
MaxValue = maxValue ?? 5,
VoteCount = voteCount ?? _faker.Random.Number(1, 1000),
Source = source ?? _faker.PickRandom<BookRatingSource>()
};
}
/// <summary>
/// Creates multiple <see cref="BookRatingDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="BookRatingDto"/> instances.</returns>
public List<BookRatingDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,41 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary;
/// <summary>
/// Fixture class for generating <see cref="BookSeriesDto"/> test data.
/// </summary>
[ExcludeFromCodeCoverage]
public class BookSeriesDtoFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a new <see cref="BookSeriesDto"/> instance with randomized test data.
/// </summary>
/// <param name="title">Optional. The title of the book series.</param>
/// <returns>A configured <see cref="BookSeriesDto"/> instance.</returns>
public BookSeriesDto Create(string? title = null)
{
return new BookSeriesDto
{
Title = title ?? _faker.Lorem.Sentence(3)
};
}
/// <summary>
/// Creates multiple <see cref="BookSeriesDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="BookSeriesDto"/> instances.</returns>
public List<BookSeriesDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,86 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary;
using Lumina.Presentation.Web.Common.Enums.BookLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary;
/// <summary>
/// Fixture class for generating <see cref="IsbnDto"/> test data.
/// </summary>
[ExcludeFromCodeCoverage]
public class IsbnDtoFixture
{
private readonly Random _random = new();
/// <summary>
/// Creates a new <see cref="IsbnDto"/> instance with a random or explicitly requested format.
/// </summary>
/// <param name="value">Optional. The ISBN value. If not provided, a valid ISBN is generated.</param>
/// <param name="format">Optional. The ISBN format. If not provided, the format is derived from the value.</param>
/// <returns>A configured <see cref="IsbnDto"/> instance.</returns>
public IsbnDto Create(string? value = null, IsbnFormat? format = null)
{
string resolvedValue = value ?? (format == IsbnFormat.Isbn10 ? GenerateValidIsbn10() : GenerateValidIsbn13());
return new IsbnDto
{
Value = resolvedValue,
Format = format ?? (resolvedValue.Length > 13 ? IsbnFormat.Isbn13 : IsbnFormat.Isbn10)
};
}
/// <summary>
/// Creates multiple <see cref="IsbnDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="IsbnDto"/> instances.</returns>
public List<IsbnDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
/// <summary>
/// Generates a valid ISBN-10 with the correct checksum.
/// </summary>
/// <returns>A valid ISBN-10 value.</returns>
private string GenerateValidIsbn10()
{
int[] digits = new int[9];
for (int i = 0; i < 9; i++)
digits[i] = _random.Next(0, 10);
int sum = 0;
for (int i = 0; i < 9; i++)
sum += (10 - i) * digits[i];
int checkDigit = (11 - sum % 11) % 11;
string checkChar = checkDigit == 10 ? "X" : checkDigit.ToString();
return $"{digits[0]}-{digits[1]}{digits[2]}-{digits[3]}{digits[4]}{digits[5]}{digits[6]}{digits[7]}{digits[8]}-{checkChar}";
}
/// <summary>
/// Generates a valid ISBN-13 with the correct checksum.
/// </summary>
/// <returns>A valid ISBN-13 value.</returns>
private string GenerateValidIsbn13()
{
string prefix = _random.Next(2) == 0 ? "978" : "979";
string group = _random.Next(0, 99999).ToString().PadLeft(5, '0');
string publisher = _random.Next(0, 999999).ToString().PadLeft(6, '0');
string title = _random.Next(0, 99).ToString().PadLeft(2, '0');
string isbn = $"{prefix}{group[..1]}{publisher}{title}";
int sum = 0;
for (int i = 0; i < 12; i++)
sum += (i % 2 == 0 ? 1 : 3) * int.Parse(isbn[i].ToString());
int checkDigit = (10 - sum % 10) % 10;
return $"{prefix}-{group[..1]}-{publisher}-{title}-{checkDigit}";
}
}
@@ -0,0 +1,75 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Presentation.Web.Common.DTO.Common;
using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary;
/// <summary>
/// Fixture class for generating <see cref="WrittenContentMetadataDto"/> test data.
/// </summary>
[ExcludeFromCodeCoverage]
public class WrittenContentMetadataDtoFixture
{
private readonly Faker _faker = new();
private readonly GenreDtoFixture _genreDtoFixture = new();
private readonly TagDtoFixture _tagDtoFixture = new();
private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new();
private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new();
/// <summary>
/// Creates a new <see cref="WrittenContentMetadataDto"/> instance with randomized test data.
/// </summary>
/// <param name="title">Optional. The title of the written content.</param>
/// <param name="originalTitle">Optional. The original title of the written content.</param>
/// <param name="description">Optional. A brief description or summary of the written content.</param>
/// <param name="releaseInfo">Optional. The release information of the written content.</param>
/// <param name="genres">Optional. The genres associated with the written content.</param>
/// <param name="tags">Optional. The tags that describe or categorize the written content.</param>
/// <param name="language">Optional. The language in which the written content is written.</param>
/// <param name="originalLanguage">Optional. The original language of the written content.</param>
/// <param name="publisher">Optional. The name of the publisher of the written content.</param>
/// <param name="pageCount">Optional. The number of pages in the written content.</param>
/// <returns>A configured <see cref="WrittenContentMetadataDto"/> instance.</returns>
public WrittenContentMetadataDto Create(
string? title = null,
string? originalTitle = null,
string? description = null,
ReleaseInfoDto? releaseInfo = null,
List<GenreDto>? genres = null,
List<TagDto>? tags = null,
LanguageInfoDto? language = null,
LanguageInfoDto? originalLanguage = null,
string? publisher = null,
int? pageCount = null)
{
return new WrittenContentMetadataDto
{
Title = title ?? _faker.Lorem.Sentence(3),
OriginalTitle = originalTitle ?? _faker.Lorem.Sentence(3),
Description = description ?? _faker.Lorem.Paragraph(),
ReleaseInfo = releaseInfo ?? _releaseInfoDtoFixture.Create(),
Genres = genres ?? [.. _genreDtoFixture.CreateMany(_faker.Random.Number(1, 3))],
Tags = tags ?? [.. _tagDtoFixture.CreateMany(_faker.Random.Number(1, 3))],
Language = language ?? _languageInfoDtoFixture.Create(),
OriginalLanguage = originalLanguage ?? _languageInfoDtoFixture.Create(),
Publisher = publisher ?? _faker.Company.CompanyName(),
PageCount = pageCount ?? _faker.Random.Int(100, 1000)
};
}
/// <summary>
/// Creates multiple <see cref="WrittenContentMetadataDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="WrittenContentMetadataDto"/> instances.</returns>
public List<WrittenContentMetadataDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -17,9 +17,11 @@ public class GetDirectoriesRequestFixture
/// Creates a new <see cref="GetDirectoriesRequest"/> instance with randomized test data.
/// </summary>
/// <param name="path">Optional file system path whose directories are retrieved.</param>
/// <param name="includeHiddenElements">Whether hidden file system elements are included or not.</param>
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
/// <returns>A configured <see cref="GetDirectoriesRequest"/> instance.</returns>
public GetDirectoriesRequest Create(string? path = null, bool includeHiddenElements = false)
public GetDirectoriesRequest Create(
string? path = null,
bool includeHiddenElements = false)
{
return new GetDirectoriesRequest(
Path: path ?? $"/media/{System.Guid.NewGuid():N}",
@@ -0,0 +1,37 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books;
/// <summary>
/// Fixture class for generating <see cref="GetBookRequest"/> test data.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetBookRequestFixture
{
/// <summary>
/// Creates a new <see cref="GetBookRequest"/> instance.
/// </summary>
/// <param name="id">Optional unique identifier of the book to retrieve.</param>
/// <returns>A configured <see cref="GetBookRequest"/> instance.</returns>
public GetBookRequest Create(
Guid? id = null)
{
return new GetBookRequest(id?.ToString() ?? Guid.NewGuid().ToString());
}
/// <summary>
/// Creates a list of <see cref="GetBookRequest"/> instances.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="GetBookRequest"/> instances.</returns>
public List<GetBookRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,84 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary;
using Lumina.Presentation.Web.Common.Enums.BookLibrary;
using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Presentation.Web.Fixtures.Common.DTO.MediaContributors;
using Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary;
using Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books;
/// <summary>
/// Fixture class for generating <see cref="UpdateBookRequest"/> test data.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateBookRequestFixture
{
private readonly Faker _faker = new();
private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new();
private readonly BookSeriesDtoFixture _bookSeriesDtoFixture = new();
private readonly IsbnDtoFixture _isbnDtoFixture = new();
private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new();
private readonly BookRatingDtoFixture _bookRatingDtoFixture = new();
/// <summary>
/// Creates a new <see cref="UpdateBookRequest"/> instance with randomized test data.
/// </summary>
/// <param name="id">Optional Id of the book to update.</param>
/// <param name="metadata">Optional written content metadata of the book.</param>
/// <param name="includeOptionalProperties">Whether the properties that are not explicitly provided should be randomized, or forced to <see langword="null"/>.</param>
/// <returns>A configured <see cref="UpdateBookRequest"/> instance.</returns>
public UpdateBookRequest Create(
Guid? id = null,
WrittenContentMetadataDto? metadata = null,
bool includeOptionalProperties = true)
{
return new UpdateBookRequest
{
Id = id?.ToString() ?? Guid.NewGuid().ToString(),
Metadata = metadata ?? (includeOptionalProperties ? _writtenContentMetadataDtoFixture.Create() : null),
Format = includeOptionalProperties ? _faker.PickRandom<BookFormat>() : null,
Edition = includeOptionalProperties ? _faker.Random.String2(_faker.Random.Number(1, 50)) : null,
VolumeNumber = includeOptionalProperties ? _faker.Random.Number(1, 3) : null,
Series = includeOptionalProperties ? _bookSeriesDtoFixture.Create() : null,
ASIN = includeOptionalProperties ? _faker.Random.String2(10) : null,
GoodreadsId = includeOptionalProperties ? _faker.Random.Number(100000, 500000).ToString() : null,
LCCN = includeOptionalProperties ? "n78890351" : null,
OCLCNumber = includeOptionalProperties ? "ocm12345678" : null,
OpenLibraryId = includeOptionalProperties ? "OL123456M" : null,
LibraryThingId = includeOptionalProperties ? _faker.Random.String2(_faker.Random.Number(1, 50)) : null,
GoogleBooksId = includeOptionalProperties ? CreateGoogleBooksId() : null,
BarnesAndNobleId = includeOptionalProperties ? _faker.Random.String2(10, "0123456789") : null,
AppleBooksId = includeOptionalProperties ? $"id{_faker.Random.Number(1, 999999)}" : null,
ISBNs = includeOptionalProperties ? [.. _isbnDtoFixture.CreateMany(_faker.Random.Number(1, 3))] : null,
Contributors = includeOptionalProperties ? [.. _mediaContributorDtoFixture.CreateMany(_faker.Random.Number(1, 3))] : null,
Ratings = includeOptionalProperties ? [.. _bookRatingDtoFixture.CreateMany(_faker.Random.Number(1, 3))] : null
};
}
/// <summary>
/// Creates a list of <see cref="UpdateBookRequest"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="UpdateBookRequest"/> instances.</returns>
public List<UpdateBookRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
/// <summary>
/// Generates a valid Google Books Id.
/// </summary>
/// <returns>The generated Google Books Id.</returns>
private string CreateGoogleBooksId()
{
const string VALID_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
return new string([.. Enumerable.Repeat(VALID_CHARS, 12).Select(s => s[_faker.Random.Number(VALID_CHARS.Length - 1)])]);
}
}
@@ -1,10 +1,25 @@
#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.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBook;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
#endregion
@@ -18,6 +33,14 @@ public class GetBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
{
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
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="GetBookEndpointTests"/> class.
@@ -38,16 +61,118 @@ public class GetBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
}
[Fact]
public async Task GetBook_WhenCalled_ShouldReturnOk()
public async Task GetBook_WhenBookBelongsToAnOwnedLibrary_ShouldReturnBookDetails()
{
// Arrange
Guid bookId = Guid.NewGuid();
Guid userId = GetCurrentUserId();
(Guid libraryId, Guid bookId) = await SeedLibraryAndBookAsync(userId, "Test Book");
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{bookId}");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
BookResponse? book = JsonSerializer.Deserialize<BookResponse>(content, _jsonOptions);
Assert.NotNull(book);
Assert.Equal(bookId, book!.Id);
Assert.Equal(libraryId, book.LibraryId);
Assert.Equal("Test Book", book.Metadata!.Title);
Assert.Equal($"/books/{bookId:N}.epub", book.Path);
}
[Fact]
public async Task GetBook_WhenBookDoesNotExist_ShouldReturnBookNotFoundProblem()
{
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{Guid.NewGuid()}");
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = JsonSerializer.Deserialize<Microsoft.AspNetCore.Mvc.ProblemDetails>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal("General.NotFound", problemDetails!.Title);
Assert.Equal("BookNotFound", problemDetails.Detail);
Assert.DoesNotContain("Exception", content, StringComparison.Ordinal);
}
[Fact]
public async Task GetBook_WhenBookBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
{
// Arrange
(Guid otherUserId, _) = await SeedOtherUserAsync();
(_, Guid bookId) = await SeedLibraryAndBookAsync(otherUserId, "Other User Book");
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{bookId}");
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
using JsonDocument problemDetails = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
Assert.Equal("General.Unauthorized", problemDetails.RootElement.GetProperty("title").GetString());
Assert.Equal("NotAuthorized", problemDetails.RootElement.GetProperty("detail").GetString());
Assert.DoesNotContain("Exception", problemDetails.RootElement.GetRawText(), StringComparison.Ordinal);
}
[Fact]
public async Task GetBook_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
// Act
HttpResponseMessage response = await unauthenticatedClient.GetAsync($"/api/v1/books/{Guid.NewGuid()}");
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
/// <summary>
/// Seeds a library owned by <paramref name="userId"/> and a book belonging to it.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <param name="title">The title of the seeded book.</param>
/// <returns>The Ids of the seeded library and book.</returns>
private async Task<(Guid libraryId, Guid bookId)> SeedLibraryAndBookAsync(Guid userId, string title)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
LibraryEntity library = _libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []);
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, path: $"/books/{bookId:N}.epub", title: title, includeMetadata: false);
dbContext.Libraries.Add(library);
dbContext.Books.Add(book);
await dbContext.SaveChangesAsync();
return (libraryId, bookId);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id.
/// </summary>
/// <returns>The Id of the seeded user and its username.</returns>
private async Task<(Guid userId, string username)> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"otheruser_{Guid.NewGuid()}";
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
await dbContext.SaveChangesAsync();
return (userId, username);
}
/// <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>
@@ -22,7 +22,7 @@ using System.Threading.Tasks;
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingAvailability;
/// <summary>
/// Contains integration tests for the <c>/books/{bookId}/reading/availability</c> route.
/// Contains integration tests for the <see cref="GetReadingAvailabilityEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetReadingAvailabilityEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
@@ -19,7 +19,7 @@ using System.Threading.Tasks;
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingManifest;
/// <summary>
/// Contains integration tests for the <c>/books/{bookId}/reading/manifest</c> route.
/// Contains integration tests for the <see cref="GetReadingManifestEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetReadingManifestEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
@@ -19,7 +19,7 @@ using System.Threading.Tasks;
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingResource;
/// <summary>
/// Contains integration tests for the <c>/books/{bookId}/reading/resources/{resourceKey}</c> route.
/// Contains integration tests for the <see cref="GetReadingResourceEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetReadingResourceEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
@@ -19,7 +19,7 @@ using System.Threading.Tasks;
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingSection;
/// <summary>
/// Contains integration tests for the <c>/books/{bookId}/reading/sections/{locationRef}</c> route.
/// Contains integration tests for the <see cref="GetReadingSectionEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetReadingSectionEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
@@ -0,0 +1,298 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
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.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.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBook;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.EntityFrameworkCore;
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;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBook;
/// <summary>
/// Contains integration tests for the <see cref="UpdateBookEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
private readonly UpdateBookRequestFixture _requestBookFixture = new();
private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new();
private readonly BookEntityFixture _bookEntityFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="UpdateBookEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public UpdateBookEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
public async Task UpdateBook_WhenCalledByOwnerWithValidData_ShouldUpdateBookAndPersistChanges()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid libraryId, Guid bookId) = await SeedLibraryAndBookAsync(userId, "Original Title");
UpdateBookRequest request = _requestBookFixture.Create(id: bookId, metadata: _writtenContentMetadataDtoFixture.Create(title: "Updated Title"), isbns: [], contributors: [], ratings: [], includeOptionalProperties: false);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/books/{bookId}", request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
BookResponse? bookResponse = JsonSerializer.Deserialize<BookResponse>(content, _jsonOptions);
Assert.NotNull(bookResponse);
Assert.Equal(bookId, bookResponse!.Id);
Assert.Equal(libraryId, bookResponse.LibraryId);
Assert.Equal("Updated Title", bookResponse.Metadata!.Title);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
BookEntity storedBook = dbContext.Books.Single(book => book.Id == bookId);
Assert.Equal("Updated Title", storedBook.Title);
}
[Fact]
public async Task UpdateBook_WhenTwoContributorsShareTheSameDisplayName_ShouldCreateOneContributorWithTwoBookLinks()
{
// Arrange
Guid userId = GetCurrentUserId();
(_, Guid bookId) = await SeedLibraryAndBookAsync(userId, "Original Title");
List<MediaContributorDto> duplicatedContributors =
[
new MediaContributorDto(
new MediaContributorNameDto("Duplicated Author", "Duplicated Author Legal"),
new MediaContributorRoleDto("author", MediaContributorRoleCategory.Author)),
new MediaContributorDto(
new MediaContributorNameDto("Duplicated Author", "Duplicated Author Legal"),
new MediaContributorRoleDto("illustrator", MediaContributorRoleCategory.Illustrator))
];
UpdateBookRequest request = _requestBookFixture.Create(id: bookId, contributors: duplicatedContributors, isbns: [], ratings: [], includeOptionalProperties: false);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/books/{bookId}", request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
MediaContributorEntity contributor = dbContext.MediaContributors.Single(mediaContributor => mediaContributor.DisplayName == "Duplicated Author");
List<BookContributorEntity> links = dbContext.Books
.Include(book => book.BookContributors)
.Single(book => book.Id == bookId)
.BookContributors
.ToList();
Assert.Equal(2, links.Count);
Assert.All(links, link => Assert.Equal(contributor.Id, link.MediaContributorId));
Assert.Contains(links, link => link.RoleName == "author");
Assert.Contains(links, link => link.RoleName == "illustrator");
}
[Fact]
public async Task UpdateBook_WhenRouteBookDoesNotExistButBodyIdExists_ShouldNotUpdateTheBodyBook()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid libraryId, Guid bodyBookId) = await SeedLibraryAndBookAsync(userId, "Body Book Title");
Guid routeId = Guid.NewGuid();
UpdateBookRequest request = _requestBookFixture.Create(id: bodyBookId, metadata: _writtenContentMetadataDtoFixture.Create(title: "Should Not Apply"));
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/books/{routeId}", request);
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
BookEntity storedBook = dbContext.Books.Single(book => book.Id == bodyBookId);
Assert.Equal("Body Book Title", storedBook.Title);
}
[Fact]
public async Task UpdateBook_WhenRouteIdIsNotParseable_ShouldReturnUnprocessableEntity()
{
// Arrange
UpdateBookRequest request = _requestBookFixture.Create();
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/books/not-a-guid", request);
// Assert
// The route value is kept as a raw string, so the unparseable Id becomes Guid.Empty in the command mapping and the
// command validator reports a clean validation error instead of failing the request binding.
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
Assert.Contains("BookIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task UpdateBook_WhenBookDoesNotExist_ShouldReturnBookNotFoundProblem()
{
// Arrange
UpdateBookRequest request = _requestBookFixture.Create();
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/books/{Guid.NewGuid()}", request);
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.NotFound", problemDetails.RootElement.GetProperty("title").GetString());
Assert.Equal("BookNotFound", problemDetails.RootElement.GetProperty("detail").GetString());
}
[Fact]
public async Task UpdateBook_WhenBookBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
{
// Arrange
(Guid otherUserId, _) = await SeedOtherUserAsync();
(_, Guid bookId) = await SeedLibraryAndBookAsync(otherUserId, "Other User Book");
UpdateBookRequest request = _requestBookFixture.Create(id: bookId);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/books/{bookId}", request);
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Unauthorized", problemDetails.RootElement.GetProperty("title").GetString());
Assert.Equal("NotAuthorized", problemDetails.RootElement.GetProperty("detail").GetString());
}
[Fact]
public async Task UpdateBook_WhenCalledWithInvalidBody_ShouldReturnUnprocessableEntity()
{
// Arrange
Guid userId = GetCurrentUserId();
(_, Guid bookId) = await SeedLibraryAndBookAsync(userId, "Original Title");
UpdateBookRequest request = _requestBookFixture.Create(id: bookId, metadata: _writtenContentMetadataDtoFixture.Create(includeTitle: false));
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/books/{bookId}", request);
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
Assert.Contains("TitleCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task UpdateBook_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
UpdateBookRequest request = _requestBookFixture.Create();
// Act
HttpResponseMessage response = await unauthenticatedClient.PutAsJsonAsync($"/api/v1/books/{Guid.NewGuid()}", request);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
/// <summary>
/// Seeds a library owned by <paramref name="userId"/> and a book belonging to it.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <param name="title">The title of the seeded book.</param>
/// <returns>The Ids of the seeded library and book.</returns>
private async Task<(Guid libraryId, Guid bookId)> SeedLibraryAndBookAsync(Guid userId, string title)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
LibraryEntity library = _libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []);
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, path: $"/books/{bookId:N}.epub", title: title, includeMetadata: false);
dbContext.Libraries.Add(library);
dbContext.Books.Add(book);
await dbContext.SaveChangesAsync();
return (libraryId, bookId);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id.
/// </summary>
/// <returns>The Id of the seeded user and its username.</returns>
private async Task<(Guid userId, string username)> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"otheruser_{Guid.NewGuid()}";
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
await dbContext.SaveChangesAsync();
return (userId, username);
}
/// <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>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
await _apiFactory.RemoveTestUserAsync();
}
}
@@ -0,0 +1,266 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
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.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBookCover;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBookCover;
/// <summary>
/// Contains integration tests for the <see cref="UpdateBookCoverEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateBookCoverEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly BookEntityFixture _bookEntityFixture = new();
private readonly BookArtworkEntityFixture _bookArtworkEntityFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="UpdateBookCoverEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public UpdateBookCoverEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
public async Task UpdateBookCover_WhenCalledByOwnerWithValidImage_ShouldReplaceTheStoredCover()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid libraryId, Guid bookId) = await SeedLibraryAndBookWithCoverAsync(userId, "/media/books/old-cover.jpg");
// Act
HttpResponseMessage response = await _client.PutAsync($"/api/v1/books/{bookId}/cover", CreateCoverForm("cover.png"));
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
string storedPath = JsonSerializer.Deserialize<string>(content)!;
Assert.False(string.IsNullOrWhiteSpace(storedPath));
Assert.Contains("cover.png", storedPath, StringComparison.OrdinalIgnoreCase);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
BookArtworkEntity coverArtwork = dbContext.Books
.SelectMany(book => book.BookArtwork)
.Single(artwork => artwork.BookId == bookId && artwork.ArtworkType == ArtworkType.Cover);
Assert.Equal(storedPath, coverArtwork.FileName);
Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status);
}
[Fact]
public async Task UpdateBookCover_WhenBookHasNoExistingCover_ShouldCreateACoverArtwork()
{
// Arrange
Guid userId = GetCurrentUserId();
(_, Guid bookId) = await SeedLibraryAndBookAsync(userId);
// Act
HttpResponseMessage response = await _client.PutAsync($"/api/v1/books/{bookId}/cover", CreateCoverForm("cover.png"));
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
string storedPath = JsonSerializer.Deserialize<string>(content)!;
Assert.False(string.IsNullOrWhiteSpace(storedPath));
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
BookArtworkEntity coverArtwork = dbContext.Books
.SelectMany(book => book.BookArtwork)
.Single(artwork => artwork.BookId == bookId && artwork.ArtworkType == ArtworkType.Cover);
Assert.Equal(storedPath, coverArtwork.FileName);
}
[Fact]
public async Task UpdateBookCover_WhenBookDoesNotExist_ShouldReturnBookNotFoundProblem()
{
// Act
HttpResponseMessage response = await _client.PutAsync($"/api/v1/books/{Guid.NewGuid()}/cover", CreateCoverForm("cover.png"));
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.NotFound", problemDetails.RootElement.GetProperty("title").GetString());
Assert.Equal("BookNotFound", problemDetails.RootElement.GetProperty("detail").GetString());
}
[Fact]
public async Task UpdateBookCover_WhenRouteIdIsNotParseable_ShouldReturnUnprocessableEntity()
{
// Act
HttpResponseMessage response = await _client.PutAsync($"/api/v1/books/not-a-guid/cover", CreateCoverForm("cover.png"));
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
Assert.Contains("BookIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task UpdateBookCover_WhenBookBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
{
// Arrange
(Guid otherUserId, _) = await SeedOtherUserAsync();
(_, Guid bookId) = await SeedLibraryAndBookAsync(otherUserId);
// Act
HttpResponseMessage response = await _client.PutAsync($"/api/v1/books/{bookId}/cover", CreateCoverForm("cover.png"));
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Unauthorized", problemDetails.RootElement.GetProperty("title").GetString());
Assert.Equal("NotAuthorized", problemDetails.RootElement.GetProperty("detail").GetString());
}
[Fact]
public async Task UpdateBookCover_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
// Act
HttpResponseMessage response = await unauthenticatedClient.PutAsync($"/api/v1/books/{Guid.NewGuid()}/cover", CreateCoverForm("cover.png"));
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
/// <summary>
/// Creates a multipart form carrying a minimal PNG-like payload.
/// </summary>
/// <param name="fileName">The name of the uploaded file.</param>
/// <returns>A configured <see cref="MultipartFormDataContent"/> instance.</returns>
private static MultipartFormDataContent CreateCoverForm(string fileName)
{
// The payload only needs to carry the PNG signature in its first bytes and exceed the header detection buffer.
byte[] payload = new byte[100];
payload[0] = 137;
payload[1] = 80;
payload[2] = 78;
payload[3] = 71;
payload[4] = 13;
payload[5] = 10;
payload[6] = 26;
payload[7] = 10;
MultipartFormDataContent form = [];
ByteArrayContent fileContent = new(payload);
fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
form.Add(fileContent, "cover", fileName);
return form;
}
/// <summary>
/// Seeds a library owned by <paramref name="userId"/> and a book with an existing cover belonging to it.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <param name="existingCoverFileName">The relative path of the existing cover of the book.</param>
/// <returns>The Ids of the seeded library and book.</returns>
private async Task<(Guid libraryId, Guid bookId)> SeedLibraryAndBookWithCoverAsync(Guid userId, string existingCoverFileName)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
LibraryEntity library = _libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []);
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, path: $"/books/{bookId:N}.epub", title: "Test Book", includeMetadata: false);
BookArtworkEntity existingCover = _bookArtworkEntityFixture.Create(bookId: bookId, artworkType: ArtworkType.Cover, fileName: existingCoverFileName, status: ArtworkStatus.Enriched);
book.BookArtwork.Add(existingCover);
dbContext.Libraries.Add(library);
dbContext.Books.Add(book);
await dbContext.SaveChangesAsync();
return (libraryId, bookId);
}
/// <summary>
/// Seeds a library owned by <paramref name="userId"/> and a book belonging to it.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Ids of the seeded library and book.</returns>
private async Task<(Guid libraryId, Guid bookId)> SeedLibraryAndBookAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
LibraryEntity library = _libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []);
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, path: $"/books/{bookId:N}.epub", title: "Test Book", includeMetadata: false);
dbContext.Libraries.Add(library);
dbContext.Books.Add(book);
await dbContext.SaveChangesAsync();
return (libraryId, bookId);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id.
/// </summary>
/// <returns>The Id of the seeded user and its username.</returns>
private async Task<(Guid userId, string username)> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"otheruser_{Guid.NewGuid()}";
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
await dbContext.SaveChangesAsync();
return (userId, username);
}
/// <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>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
await _apiFactory.RemoveTestUserAsync();
}
}
@@ -23,7 +23,7 @@ using System.Threading.Tasks;
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.GetLibraryBookReaders;
/// <summary>
/// Contains integration tests for the <c>/libraries/{libraryId}/book-readers</c> route.
/// Contains integration tests for the <see cref="GetLibraryBookReadersEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryBookReadersEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
@@ -23,7 +23,7 @@ using System.Threading.Tasks;
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.SetLibraryBookReaderEnabled;
/// <summary>
/// Contains integration tests for the <c>/libraries/{libraryId}/book-readers/{pluginId}/enabled</c> route.
/// Contains integration tests for the <see cref="SetLibraryBookReaderEnabledEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLibraryBookReaderEnabledEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
@@ -19,7 +19,7 @@ using System.Threading.Tasks;
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Authorization.Roles.AddRole;
/// <summary>
/// Contains integration tests for the <c>/{culture}/admin/api-create-role</c> route served by the <see cref="AddRoleEndpoint"/> class.
/// Contains integration tests for the <see cref="AddRoleEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddRoleEndpointTests : IClassFixture<LuminaWebFactory>
@@ -16,7 +16,7 @@ using System.Threading.Tasks;
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Authorization.Roles.DeleteRole;
/// <summary>
/// Contains integration tests for the <c>/{culture}/admin/api-delete-role/{roleId}</c> route served by the <see cref="DeleteRoleEndpoint"/> class.
/// Contains integration tests for the <see cref="DeleteRoleEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeleteRoleEndpointTests : IClassFixture<LuminaWebFactory>
@@ -17,7 +17,7 @@ using System.Threading.Tasks;
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Authorization.Roles.GetRolePermissions;
/// <summary>
/// Contains integration tests for the <c>/{culture}/admin/api-get-permissions-by-role-id/{roleId}</c> route served by the <see cref="GetRolePermissionsEndpoint"/> class.
/// Contains integration tests for the <see cref="GetRolePermissionsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetRolePermissionsEndpointTests : IClassFixture<LuminaWebFactory>
@@ -16,7 +16,7 @@ using System.Threading.Tasks;
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Authorization.Roles.GetRoles;
/// <summary>
/// Contains integration tests for the <c>/{culture}/admin/api-get-roles</c> route served by the <see cref="GetRolesEndpoint"/> class.
/// Contains integration tests for the <see cref="GetRolesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetRolesEndpointTests : IClassFixture<LuminaWebFactory>
@@ -19,7 +19,7 @@ using System.Threading.Tasks;
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Authorization.Roles.UpdateRole;
/// <summary>
/// Contains integration tests for the <c>/{culture}/admin/api-update-role</c> route served by the <see cref="UpdateRoleEndpoint"/> class.
/// Contains integration tests for the <see cref="UpdateRoleEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateRoleEndpointTests : IClassFixture<LuminaWebFactory>
@@ -17,7 +17,7 @@ using System.Threading.Tasks;
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.ManagePermissions;
/// <summary>
/// Contains integration tests for the <c>/{culture}/admin/manage-permissions</c> route served by the <see cref="ManagePermissionsViewEndpoint"/> class.
/// Contains integration tests for the <see cref="ManagePermissionsViewEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ManagePermissionsViewEndpointTests : IClassFixture<LuminaWebFactory>
@@ -15,7 +15,7 @@ using System.Threading.Tasks;
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.ManageRoles;
/// <summary>
/// Contains integration tests for the <c>/{culture}/admin/manage-roles</c> route served by the <see cref="ManageRolesViewEndpoint"/> class.
/// Contains integration tests for the <see cref="ManageRolesViewEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ManageRolesViewEndpointTests : IClassFixture<LuminaWebFactory>
@@ -18,7 +18,7 @@ using System.Threading.Tasks;
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Scheduler.AddScheduledJob;
/// <summary>
/// Contains integration tests for the <c>/{culture}/admin/api-scheduled-jobs/add</c> route served by the <see cref="AddScheduledJobEndpoint"/> class.
/// Contains integration tests for the <see cref="AddScheduledJobEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddScheduledJobEndpointTests : IClassFixture<LuminaWebFactory>
@@ -17,7 +17,7 @@ using System.Threading.Tasks;
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Scheduler.FireScheduledJob;
/// <summary>
/// Contains integration tests for the <c>/{culture}/admin/api-scheduled-jobs/{scheduledJobId}/fire</c> route served by the <see cref="FireScheduledJobEndpoint"/> class.
/// Contains integration tests for the <see cref="FireScheduledJobEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class FireScheduledJobEndpointTests : IClassFixture<LuminaWebFactory>
@@ -15,7 +15,7 @@ using System.Threading.Tasks;
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Scheduler.GetScheduledJobHistory;
/// <summary>
/// Contains integration tests for the <c>/{culture}/admin/api-scheduled-jobs/history</c> route served by the <see cref="GetScheduledJobHistoryEndpoint"/> class.
/// Contains integration tests for the <see cref="GetScheduledJobHistoryEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetScheduledJobHistoryEndpointTests : IClassFixture<LuminaWebFactory>
@@ -15,7 +15,7 @@ using System.Threading.Tasks;
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Scheduler.GetScheduledJobs;
/// <summary>
/// Contains integration tests for the <c>/{culture}/admin/api-scheduled-jobs</c> route served by the <see cref="GetScheduledJobsEndpoint"/> class.
/// Contains integration tests for the <see cref="GetScheduledJobsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetScheduledJobsEndpointTests : IClassFixture<LuminaWebFactory>
@@ -15,7 +15,7 @@ using System.Threading.Tasks;
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Scheduler.GetSchedulerDisplayPreferences;
/// <summary>
/// Contains integration tests for the <c>/{culture}/admin/api-scheduled-jobs/display-preferences</c> route served by the <see cref="GetSchedulerDisplayPreferencesEndpoint"/> class.
/// Contains integration tests for the <see cref="GetSchedulerDisplayPreferencesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetSchedulerDisplayPreferencesEndpointTests : IClassFixture<LuminaWebFactory>
@@ -16,7 +16,7 @@ using System.Threading.Tasks;
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Scheduler.RemoveScheduledJob;
/// <summary>
/// Contains integration tests for the <c>/{culture}/admin/api-scheduled-jobs/{scheduledJobId}</c> route served by the <see cref="RemoveScheduledJobEndpoint"/> class.
/// Contains integration tests for the <see cref="RemoveScheduledJobEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RemoveScheduledJobEndpointTests : IClassFixture<LuminaWebFactory>
@@ -13,7 +13,7 @@ using System.Threading.Tasks;
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Scheduler;
/// <summary>
/// Contains integration tests for the <c>/{culture}/admin/scheduled-jobs</c> route served by the <see cref="SchedulerIndexViewEndpoint"/> class.
/// Contains integration tests for the <see cref="SchedulerIndexViewEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SchedulerIndexViewEndpointTests : IClassFixture<LuminaWebFactory>
@@ -16,7 +16,7 @@ using System.Threading.Tasks;
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Scheduler.StartScheduledJob;
/// <summary>
/// Contains integration tests for the <c>/{culture}/admin/api-scheduled-jobs/{scheduledJobId}/start</c> route served by the <see cref="StartScheduledJobEndpoint"/> class.
/// Contains integration tests for the <see cref="StartScheduledJobEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class StartScheduledJobEndpointTests : IClassFixture<LuminaWebFactory>
@@ -16,7 +16,7 @@ using System.Threading.Tasks;
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Scheduler.StopScheduledJob;
/// <summary>
/// Contains integration tests for the <c>/{culture}/admin/api-scheduled-jobs/{scheduledJobId}/stop</c> route served by the <see cref="StopScheduledJobEndpoint"/> class.
/// Contains integration tests for the <see cref="StopScheduledJobEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class StopScheduledJobEndpointTests : IClassFixture<LuminaWebFactory>
@@ -16,7 +16,7 @@ using System.Threading.Tasks;
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Scheduler.UpdateSchedulerDisplayPreferences;
/// <summary>
/// Contains integration tests for the <c>/{culture}/admin/api-scheduled-jobs/display-preferences</c> route served by the <see cref="UpdateSchedulerDisplayPreferencesEndpoint"/> class.
/// Contains integration tests for the <see cref="UpdateSchedulerDisplayPreferencesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateSchedulerDisplayPreferencesEndpointTests : IClassFixture<LuminaWebFactory>
@@ -14,7 +14,7 @@ using System.Threading.Tasks;
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Themes.DeleteTheme;
/// <summary>
/// Contains integration tests for the <c>/{culture}/admin/themes/api-delete-theme/{themeId}</c> route served by the <see cref="DeleteThemeEndpoint"/> class.
/// Contains integration tests for the <see cref="DeleteThemeEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeleteThemeEndpointTests : IClassFixture<LuminaWebFactory>
@@ -13,7 +13,7 @@ using System.Threading.Tasks;
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Themes.DownloadTheme;
/// <summary>
/// Contains integration tests for the <c>/{culture}/admin/themes/api-download-theme/{themeId}</c> route served by the <see cref="DownloadThemeEndpoint"/> class.
/// Contains integration tests for the <see cref="DownloadThemeEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DownloadThemeEndpointTests : IClassFixture<LuminaWebFactory>
@@ -16,7 +16,7 @@ using System.Threading.Tasks;
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Themes.GetThemes;
/// <summary>
/// Contains integration tests for the <c>/{culture}/admin/themes/api-get-themes</c> route served by the <see cref="GetThemesEndpoint"/> class.
/// Contains integration tests for the <see cref="GetThemesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetThemesEndpointTests : IClassFixture<LuminaWebFactory>
@@ -16,7 +16,7 @@ using System.Threading.Tasks;
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Themes.InstallTheme;
/// <summary>
/// Contains integration tests for the <c>/{culture}/admin/themes/api-install-theme</c> route served by the <see cref="InstallThemeEndpoint"/> class.
/// Contains integration tests for the <see cref="InstallThemeEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class InstallThemeEndpointTests : IClassFixture<LuminaWebFactory>
@@ -17,7 +17,7 @@ using System.Threading.Tasks;
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Themes.RestoreTheme;
/// <summary>
/// Contains integration tests for the <c>/{culture}/admin/themes/api-restore-theme/{themeId}</c> route served by the <see cref="RestoreThemeEndpoint"/> class.
/// Contains integration tests for the <see cref="RestoreThemeEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreThemeEndpointTests : IClassFixture<LuminaWebFactory>
@@ -18,7 +18,7 @@ using System.Threading.Tasks;
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Themes.SetCurrentTheme;
/// <summary>
/// Contains integration tests for the <c>/{culture}/admin/themes/api-set-current-theme</c> route served by the <see cref="SetCurrentThemeEndpoint"/> class.
/// Contains integration tests for the <see cref="SetCurrentThemeEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetCurrentThemeEndpointTests : IClassFixture<LuminaWebFactory>
@@ -13,7 +13,7 @@ using System.Threading.Tasks;
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Themes;
/// <summary>
/// Contains integration tests for the <c>/{culture}/admin/manage-themes</c> route served by the <see cref="ThemesIndexViewEndpoint"/> class.
/// Contains integration tests for the <see cref="ThemesIndexViewEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ThemesIndexViewEndpointTests : IClassFixture<LuminaWebFactory>
@@ -17,7 +17,7 @@ using System.Threading.Tasks;
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.UsersManagement.Authorization.GetUserPermissions;
/// <summary>
/// Contains integration tests for the <c>/{culture}/admin/api-get-permissions-by-user-id/{userId}</c> route served by the <see cref="GetUserPermissionsEndpoint"/> class.
/// Contains integration tests for the <see cref="GetUserPermissionsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetUserPermissionsEndpointTests : IClassFixture<LuminaWebFactory>
@@ -17,7 +17,7 @@ using System.Threading.Tasks;
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.UsersManagement.Authorization.GetUserRole;
/// <summary>
/// Contains integration tests for the <c>/{culture}/admin/api-get-role-by-user-id/{userId}</c> route served by the <see cref="GetUserRoleEndpoint"/> class.
/// Contains integration tests for the <see cref="GetUserRoleEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetUserRoleEndpointTests : IClassFixture<LuminaWebFactory>
@@ -19,7 +19,7 @@ using System.Threading.Tasks;
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.UsersManagement.Authorization.UpdateUserRoleAndPermissions;
/// <summary>
/// Contains integration tests for the <c>/{culture}/admin/api-update-user-authorization</c> route served by the <see cref="UpdateUserRoleAndPermissionsEndpoint"/> class.
/// Contains integration tests for the <see cref="UpdateUserRoleAndPermissionsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateUserRoleAndPermissionsEndpointTests : IClassFixture<LuminaWebFactory>
@@ -16,7 +16,7 @@ using System.Threading.Tasks;
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.FileSystemManagement.Directories.GetDirectories;
/// <summary>
/// Contains integration tests for the <c>/directories/api-get-directories</c> route served by the <see cref="GetDirectoriesEndpoint"/> class.
/// Contains integration tests for the <see cref="GetDirectoriesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDirectoriesEndpointTests : IClassFixture<LuminaWebFactory>
@@ -15,7 +15,7 @@ using System.Threading.Tasks;
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.FileSystemManagement.Drives.GetDrives;
/// <summary>
/// Contains integration tests for the <c>/drives/api-get-drives</c> route served by the <see cref="GetDrivesEndpoint"/> class.
/// Contains integration tests for the <see cref="GetDrivesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDrivesEndpointTests : IClassFixture<LuminaWebFactory>
@@ -15,7 +15,7 @@ using System.Threading.Tasks;
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.FileSystemManagement.FileSystem.GetType;
/// <summary>
/// Contains integration tests for the <c>/file-system/api-get-type</c> route served by the <see cref="GetTypeEndpoint"/> class.
/// Contains integration tests for the <see cref="GetTypeEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetTypeEndpointTests : IClassFixture<LuminaWebFactory>
@@ -16,7 +16,7 @@ using System.Threading.Tasks;
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.FileSystemManagement.Files.GetFiles;
/// <summary>
/// Contains integration tests for the <c>/files/api-get-files</c> route served by the <see cref="GetFilesEndpoint"/> class.
/// Contains integration tests for the <see cref="GetFilesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetFilesEndpointTests : IClassFixture<LuminaWebFactory>
@@ -16,7 +16,7 @@ using System.Threading.Tasks;
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.FileSystemManagement.Files.GetTreeFiles;
/// <summary>
/// Contains integration tests for the <c>/files/api-get-tree-files</c> route served by the <see cref="GetTreeFilesEndpoint"/> class.
/// Contains integration tests for the <see cref="GetTreeFilesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetTreeFilesEndpointTests : IClassFixture<LuminaWebFactory>
@@ -15,7 +15,7 @@ using System.Threading.Tasks;
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.FileSystemManagement.Path.CheckPathExists;
/// <summary>
/// Contains integration tests for the <c>/path/api-check-path-exists</c> route served by the <see cref="CheckPathExistsEndpoint"/> class.
/// Contains integration tests for the <see cref="CheckPathExistsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class CheckPathExistsEndpointTests : IClassFixture<LuminaWebFactory>
@@ -16,7 +16,7 @@ using System.Threading.Tasks;
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.FileSystemManagement.Path.GetPathParent;
/// <summary>
/// Contains integration tests for the <c>/path/api-get-path-parent</c> route served by the <see cref="GetPathParentEndpoint"/> class.
/// Contains integration tests for the <see cref="GetPathParentEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPathParentEndpointTests : IClassFixture<LuminaWebFactory>
Loaded 100 of 354 files, more files were not shown because too many files have changed in this diff. Show more