diff --git a/src/Lumina.Application/Common/Models/Books/BookDto.cs b/src/Lumina.Application/Common/Models/Books/BookDto.cs index d05c33fc..5de751c7 100644 --- a/src/Lumina.Application/Common/Models/Books/BookDto.cs +++ b/src/Lumina.Application/Common/Models/Books/BookDto.cs @@ -9,42 +9,193 @@ namespace Lumina.Application.Common.Models.Books; /// public class BookDto : IStorageEntity { + #region ==================================================================== PROPERTIES ================================================================================= public Guid Id { get; init; } + + /// + /// Gets the title of the media item. + /// public string Title { get; init; } = null!; + + /// + /// Gets the original title of the media item. + /// public string? OriginalTitle { get; init; } + + /// + /// Gets the optional description of the media item. + /// public string? Description { get; init; } + + /// + /// Gets the optional original release date of the media item. + /// public DateOnly? OriginalReleaseDate { get; init; } + + /// + /// Gets the optional original release year of the media item. + /// This is useful when only the year of original release is known. + /// public int? OriginalReleaseYear { get; init; } + + /// + /// Gets the optional re-release or reissue date of the media item. + /// public DateOnly? ReReleaseDate { get; init; } + + /// + /// Gets the optional re-release or reissue year of the media item. + /// public int? ReReleaseYear { get; init; } + + /// + /// Gets the optional country or region of release. + /// public string? ReleaseCountry { get; init; } + + /// + /// Gets the optional release version or edition. (e.g. "Original", "Director's Cut", "2.0") + /// public string? ReleaseVersion { get; init; } + + /// + /// Gets the ISO 639-1 two-letter language code. + /// public string? LanguageCode { get; init; } + + /// + /// Gets the full name of the language in English. + /// public string? LanguageName { get; init; } + + /// + /// Gets an optional native name of the language. + /// public string? LanguageNativeName { get; init; } + + /// + /// Gets the optional ISO 639-1 two-letter original language code. + /// public string? OriginalLanguageCode { get; init; } + + /// + /// Gets the optional full name of the original language in English. + /// public string? OriginalLanguageName { get; init; } + + /// + /// Gets an optional native name of the original language. + /// public string? OriginalLanguageNativeName { get; init; } + + /// + /// Gets the list of tags associated with the media item. + /// public HashSet Tags { get; set; } = []; + + /// + /// Gets the list of genres associated with the media item. + /// public HashSet Genres { get; set; } = []; + + /// + /// Gets the publisher of the written content. + /// public string? Publisher { get; init; } + + /// + /// Gets the number of pages in the written content. + /// public int? PageCount { get; init; } + + /// + /// Gets the format of the book (e.g., Hardcover, Paperback), if applicable. + /// public string Format { get; init; } = null!; + + /// + /// Gets the edition of the book, if applicable. + /// public string? Edition { get; init; } + + /// + /// Gets the volume or book number in the series, if applicable. + /// public int? VolumeNumber { get; init; } + + /// + /// Gets the series id, if the book is part of a series. + /// //public Guid? BookSeriesId { get; init; } = null; + + /// + /// Gets the ASIN (Amazon Standard Identification Number) of the book. + /// public string? ASIN { get; init; } = null!; + + /// + /// Gets the Goodreads ID of the book. + /// public string? GoodreadsId { get; init; } = null!; + + /// + /// Gets the Library of Congress Control Number (LCCN) of the book. + /// public string? LCCN { get; init; } = null!; + + /// + /// Gets the OCLC Number (WorldCat identifier) of the book. + /// public string? OCLCNumber { get; init; } = null!; + + /// + /// Gets the Open Library ID of the book. + /// public string? OpenLibraryId { get; init; } = null!; + + /// + /// Gets the LibraryThing ID of the book. + /// public string? LibraryThingId { get; init; } = null!; + + /// + /// Gets the Google Books ID of the book. + /// public string? GoogleBooksId { get; init; } = null!; + + /// + /// Gets the Barnes & Noble ID of the book. + /// public string? BarnesAndNobleId { get; init; } = null!; + + /// + /// Gets the Apple Books ID of the book. + /// public string? AppleBooksId { get; init; } = null!; - public List ISBNs { get; init; } = []; + + /// + /// Gets the list of ISBN (International Standard Book Number) of the book. + /// + public List ISBNs { get; set; } = []; + + /// + /// Gets the list of media contributors (actors, directors, etc) starring in this book. + /// //public List ContributorIds { get; init; } = []; + + /// + /// Gets the list of ratings for this book. + /// public List Ratings { get; init; } = []; + + /// + /// Gets the time and date when the entity was added. + /// public DateTime Created { get; set; } + + /// + /// Gets the optional time and date when the entity was updated. + /// public DateTime? Updated { get; set; } + #endregion } \ No newline at end of file diff --git a/src/Lumina.DataAccess/Common/DependencyInjection/DataAccessLayerServices.cs b/src/Lumina.DataAccess/Common/DependencyInjection/DataAccessLayerServices.cs index 6aef7127..8b26ba7f 100644 --- a/src/Lumina.DataAccess/Common/DependencyInjection/DataAccessLayerServices.cs +++ b/src/Lumina.DataAccess/Common/DependencyInjection/DataAccessLayerServices.cs @@ -30,7 +30,6 @@ public static class DataAccessLayerServices { options.UseSqlite($"Data Source={Path.Combine(basePath, "Lumina.db")}"); }); - services.AddScoped(); Type[]? dataAccessLayerTypes = Assembly.GetExecutingAssembly().GetTypes(); diff --git a/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs b/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs index de9c2984..197ea781 100644 --- a/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs +++ b/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs @@ -15,7 +15,7 @@ namespace Lumina.DataAccess.Core.UoW; public class LuminaDbContext : DbContext { #region ==================================================================== PROPERTIES ================================================================================= - public DbSet Books { get; set; } = null!; + public virtual DbSet Books { get; set; } = null!; #endregion #region ====================================================================== CTOR ===================================================================================== diff --git a/src/Lumina.DataAccess/Lumina.DataAccess.csproj b/src/Lumina.DataAccess/Lumina.DataAccess.csproj index 60b3c106..737414e1 100644 --- a/src/Lumina.DataAccess/Lumina.DataAccess.csproj +++ b/src/Lumina.DataAccess/Lumina.DataAccess.csproj @@ -19,6 +19,7 @@ + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/Book.cs b/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/Book.cs index a5661eab..8059ef8d 100644 --- a/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/Book.cs +++ b/src/Lumina.Domain/Core/Aggregates/WrittenContentLibrary/BookLibraryAggregate/Book.cs @@ -1,13 +1,12 @@ #region ========================================================================= USING ===================================================================================== -using System.Diagnostics; using ErrorOr; using Lumina.Domain.Common.Enums; using Lumina.Domain.Common.Models.Core; using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Common.ValueObjects.Metadata; using Lumina.Domain.Core.Aggregates.MediaContributor.MediaContributorAggregate.ValueObjects; using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.Entities; using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.ValueObjects; +using System.Diagnostics; #endregion namespace Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate; diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Setup/BogusExtensions.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Setup/BogusExtensions.cs new file mode 100644 index 00000000..38417286 --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Setup/BogusExtensions.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.DataAccess.UnitTests.Common.Setup; + +/// +/// Contains extension methods for the class. +/// +[ExcludeFromCodeCoverage] +public static class BogusExtensions +{ + #region ===================================================================== METHODS =================================================================================== + /// + /// Adds random data generation support to the class. + /// + /// The faker instance to extend. + /// A random instance. + public static DateOnly DateOnly(this Faker faker) + { + return System.DateOnly.FromDateTime(faker.Date.Past()); + } + + /// + /// Adds random data generation within a specified interval support to the class. + /// + /// The faker instance to extend. + /// The start of the interval. + /// The end of the interval. + /// A random instance. + public static DateOnly DateOnlyBetween(this Faker faker, DateOnly start, DateOnly end) + { + var startDateTime = start.ToDateTime(TimeOnly.MinValue); + var endDateTime = end.ToDateTime(TimeOnly.MinValue); + return System.DateOnly.FromDateTime(faker.Date.Between(startDateTime, endDateTime)); + } + #endregion +} \ No newline at end of file diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Setup/DateOnlySpecimenBuilder.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Setup/DateOnlySpecimenBuilder.cs new file mode 100644 index 00000000..53bfe9c7 --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Setup/DateOnlySpecimenBuilder.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture.Kernel; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.DataAccess.UnitTests.Common.Setup; + +/// +/// Represents a specimen builder for the type. +/// +[ExcludeFromCodeCoverage] +public class DateOnlySpecimenBuilder : ISpecimenBuilder +{ + #region ===================================================================== METHODS =================================================================================== + /// + /// Adds support to the AutoFixture library. + /// + /// The request to process. + /// The context within which the specimen is created. + /// A specimen based on the request. + public object Create(object request, ISpecimenContext context) + { + if (request is Type type && type == typeof(DateOnly)) + return DateOnly.FromDateTime(DateTime.Now); + return new NoSpecimen(); + } + #endregion +} \ No newline at end of file diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Setup/NullableDateOnlySpecimenBuilder.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Setup/NullableDateOnlySpecimenBuilder.cs new file mode 100644 index 00000000..7a7dd522 --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Setup/NullableDateOnlySpecimenBuilder.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture.Kernel; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.DataAccess.UnitTests.Common.Setup; + +/// +/// Represents a specimen builder for the type. +/// +[ExcludeFromCodeCoverage] +public class NullableDateOnlySpecimenBuilder : ISpecimenBuilder +{ + #region ===================================================================== METHODS =================================================================================== + /// + /// Adds support to the AutoFixture library. + /// + /// The request to process. + /// The context within which the specimen is created. + /// A specimen based on the request. + public object Create(object request, ISpecimenContext context) + { + if (request is Type type && type == typeof(DateOnly?)) + return (DateOnly?)DateOnly.FromDateTime(DateTime.Now); + return new NoSpecimen(); + } + #endregion +} \ No newline at end of file diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs index 180bf338..caee32c5 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs @@ -1,11 +1,193 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +#region ========================================================================= USING ===================================================================================== +using EntityFrameworkCore.Testing.NSubstitute; +using ErrorOr; +using FluentAssertions; +using Lumina.Application.Common.Models.Books; +using Lumina.Application.Common.Models.Common; +using Lumina.DataAccess.Core.Repositories.Books; +using Lumina.DataAccess.Core.UoW; +using Lumina.DataAccess.UnitTests.Core.Repositories.Books.Fixtures; +using Lumina.Domain.Common.Enums; +using Lumina.Domain.Common.Errors; +using Microsoft.EntityFrameworkCore; +using System.Diagnostics.CodeAnalysis; +#endregion namespace Lumina.DataAccess.UnitTests.Core.Repositories.Books; -internal class BookRepositoryTests +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class BookRepositoryTests { -} + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly LuminaDbContext _mockContext; + private readonly BookRepository _sut; + private readonly BookDtoFixture _bookDtoFixture; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public BookRepositoryTests() + { + _mockContext = Create.MockedDbContextFor(); + _sut = new BookRepository(_mockContext); + _bookDtoFixture = new BookDtoFixture(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + [Fact] + public async Task InsertAsync_WhenBookDoesNotExist_ShouldAddBookToContextAndReturnCreated() + { + // Arrange + var bookDto = _bookDtoFixture.CreateBookDto(); + + // Act + var result = await _sut.InsertAsync(bookDto, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().Be(Result.Created); + + // Check if the book was added to the context's ChangeTracker + var addedBook = _mockContext.ChangeTracker.Entries() + .FirstOrDefault(e => e.State == EntityState.Added && e.Entity.Id == bookDto.Id); + addedBook.Should().NotBeNull(); + } + + [Fact] + public async Task InsertAsync_WhenBookAlreadyExists_ShouldReturnError() + { + // Arrange + var bookDto = _bookDtoFixture.CreateBookDto(); + + _mockContext.Books.Add(bookDto); + await _mockContext.SaveChangesAsync(); + + // Act + var result = await _sut.InsertAsync(bookDto, CancellationToken.None); + + // Assert + result.IsError.Should().BeTrue(); + result.FirstError.Should().Be(Errors.WrittenContent.BookAlreadyExists); + _mockContext.ChangeTracker.Entries().Should().HaveCount(1); // Only the existing book should be in the context} + } + + [Fact] + public async Task InsertAsync_WhenExistingTagsFound_ShouldReplaceTagsWithExistingOnes() + { + // Arrange + var existingTag = new TagDto("Existing"); + _mockContext.Set().Add(existingTag); + await _mockContext.SaveChangesAsync(); + + var bookDto = _bookDtoFixture.CreateBookDto(); + bookDto.Tags = [new("Existing"), new("New")]; + + // Act + var result = await _sut.InsertAsync(bookDto, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().Be(Result.Created); + + var addedBook = _mockContext.ChangeTracker.Entries() + .FirstOrDefault(e => e.State == EntityState.Added && e.Entity.Id == bookDto.Id); + addedBook.Should().NotBeNull(); + var addedBookEntity = addedBook!.Entity; + addedBookEntity.Tags.Should().HaveCount(2); + addedBookEntity.Tags.Should().Contain(t => t.Name == "Existing" && t == existingTag); + addedBookEntity.Tags.Should().Contain(t => t.Name == "New" && t != existingTag); + } + + [Fact] + public async Task InsertAsync_WhenExistingGenresFound_ShouldReplaceGenresWithExistingOnes() + { + // Arrange + var existingGenre = new GenreDto("Existing"); + _mockContext.Set().Add(existingGenre); + await _mockContext.SaveChangesAsync(); + + var bookDto = _bookDtoFixture.CreateBookDto(); + bookDto.Genres = [new("Existing"), new("New")]; + + // Act + var result = await _sut.InsertAsync(bookDto, CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().Be(Result.Created); + + var addedBook = _mockContext.ChangeTracker.Entries() + .FirstOrDefault(e => e.State == EntityState.Added && e.Entity.Id == bookDto.Id); + addedBook.Should().NotBeNull(); + var addedBookEntity = addedBook!.Entity; + addedBookEntity.Genres.Should().HaveCount(2); + addedBookEntity.Genres.Should().Contain(g => g.Name == "Existing" && g == existingGenre); + addedBookEntity.Genres.Should().Contain(g => g.Name == "New" && g != existingGenre); + } + + [Fact] + public async Task GetAllAsync_ShouldReturnAllBooks() + { + // Arrange + var books = new List + { + _bookDtoFixture.CreateBookDto(), + _bookDtoFixture.CreateBookDto(), + _bookDtoFixture.CreateBookDto() + }; + _mockContext.Books.AddRange(books); + await _mockContext.SaveChangesAsync(); + + // Act + var result = await _sut.GetAllAsync(CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Should().HaveCount(3); + result.Value.Should().BeEquivalentTo(books); + } + + [Fact] + public async Task GetAllAsync_WhenNoBooksExist_ShouldReturnEmptyList() + { + // Act + var result = await _sut.GetAllAsync(CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Should().BeEmpty(); + } + + [Fact] + public async Task GetAllAsync_ShouldIncludeRelatedEntities() + { + // Arrange + var book = _bookDtoFixture.CreateBookDto(); + book.Tags = [new TagDto("Tag1"), new TagDto("Tag2")]; + book.Genres = [new GenreDto("Genre1"), new GenreDto("Genre2")]; + book.ISBNs = [new IsbnDto("1234567890", IsbnFormat.Isbn10), new IsbnDto("1234567890123", IsbnFormat.Isbn13)]; + _mockContext.Books.Add(book); + await _mockContext.SaveChangesAsync(); + + // Act + var result = await _sut.GetAllAsync(CancellationToken.None); + + // Assert + result.IsError.Should().BeFalse(); + result.Value.Should().NotBeNull(); + result.Value.Should().HaveCount(1); + var retrievedBook = result.Value.First(); + retrievedBook.Tags.Should().HaveCount(2); + retrievedBook.Genres.Should().HaveCount(2); + retrievedBook.ISBNs.Should().HaveCount(2); + } + #endregion +} \ No newline at end of file diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/Fixtures/BookDtoFixture.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/Fixtures/BookDtoFixture.cs new file mode 100644 index 00000000..70401e64 --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/Fixtures/BookDtoFixture.cs @@ -0,0 +1,208 @@ +using AutoFixture; +using Bogus; +using Lumina.Application.Common.Models.Books; +using Lumina.Application.Common.Models.Common; +using Lumina.DataAccess.UnitTests.Common.Setup; +using Lumina.Domain.Common.Enums; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Lumina.DataAccess.UnitTests.Core.Repositories.Books.Fixtures; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class BookDtoFixture +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly Fixture _fixture; + private readonly Random _random = new(); + private readonly Faker _faker; + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public BookDtoFixture() + { + _fixture = new Fixture(); + _fixture.Customizations.Add(new DateOnlySpecimenBuilder()); + _fixture.Customizations.Add(new NullableDateOnlySpecimenBuilder()); + _faker = new Faker(); + ConfigureCustomTypes(); + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Creates a random valid BookDto. + /// + /// The created BookDto. + public BookDto CreateBookDto() + { + var releaseYear = _random.Next(2000, 2010); + var reReleaseYear = _random.Next(2010, 2020); + + return new Faker() + .RuleFor(x => x.Id, f => f.Random.Guid()) + .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.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))) + .RuleFor(x => x.LanguageCode, f => f.Random.String2(2)) + .RuleFor(x => x.LanguageName, f => f.Random.String2(f.Random.Number(1, 50))) + .RuleFor(x => x.LanguageNativeName, f => f.Random.String2(f.Random.Number(1, 50))) + .RuleFor(x => x.OriginalLanguageCode, f => f.Random.String2(2)) + .RuleFor(x => x.OriginalLanguageName, f => f.Random.String2(f.Random.Number(1, 50))) + .RuleFor(x => x.OriginalLanguageNativeName, f => f.Random.String2(f.Random.Number(1, 50))) + .RuleFor(x => x.Tags, f => new HashSet(CreateTags(f.Random.Number(1, 5)))) + .RuleFor(x => x.Genres, f => new HashSet(CreateGenres(f.Random.Number(1, 5)))) + .RuleFor(x => x.Publisher, f => f.Random.String2(f.Random.Number(1, 100))) + .RuleFor(x => x.PageCount, _random.Next(100, 300)) + .RuleFor(x => x.Format, f => f.PickRandom().ToString()) + .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, CreateLCCN) + .RuleFor(x => x.OCLCNumber, CreateOCLCNumber) + .RuleFor(x => x.OpenLibraryId, CreateOpenLibraryId) + .RuleFor(x => x.LibraryThingId, f => f.Random.String2(f.Random.Number(1, 50))) + .RuleFor(x => x.GoogleBooksId, CreateGoogleBooksId) + .RuleFor(x => x.BarnesAndNobleId, f => f.Random.String2(10, "0123456789")) + .RuleFor(x => x.AppleBooksId, f => $"id{f.Random.Number(1, 999999)}") + .RuleFor(x => x.ISBNs, f => CreateIsbns(f.Random.Number(1, 5))) + .RuleFor(x => x.Ratings, f => CreateBookRatings(f.Random.Number(1, 5))) + .RuleFor(x => x.Created, f => f.Date.Past()) + .RuleFor(x => x.Updated, f => f.Date.Recent()) + .Generate(); + } + + private List CreateTags(int count) + { + return new Faker() + .CustomInstantiator(f => new TagDto(f.Random.String2(f.Random.Number(1, 50)))) + .Generate(count); + } + + private List CreateGenres(int count) + { + return new Faker() + .CustomInstantiator(f => new GenreDto(f.Random.String2(f.Random.Number(1, 50)))) + .Generate(count); + } + + private string CreateLCCN(Faker f) + { + var letters = new string(Enumerable.Range(0, f.Random.Number(0, 3)) + .Select(_ => f.Random.Char('a', 'z')) + .ToArray()); + var digits = f.Random.String2(f.Random.Number(8, 10), "0123456789"); + return letters + digits; + } + + private string CreateOCLCNumber(Faker f) + { + string[] prefixes = ["ocm", "ocn", "on", "(OCoLC)"]; + var prefix = f.Random.ArrayElement(prefixes); + string number = prefix switch + { + "ocm" => f.Random.String2(8, "0123456789"), + "ocn" => f.Random.String2(f.Random.Number(9, 11), "0123456789"), + "on" => f.Random.String2(10, "0123456789"), + "(OCoLC)" => f.Random.String2(f.Random.Number(8, 10), "0123456789"), + _ => f.Random.String2(f.Random.Number(8, 10), "0123456789") + }; + return prefix + number; + } + + private string CreateOpenLibraryId(Faker f) + { + var firstDigit = f.Random.Number(1, 9); + var remainingDigits = f.Random.String2(f.Random.Number(0, 6), "0123456789"); + var suffix = f.Random.ArrayElement(new[] { 'A', 'M', 'W' }); + return $"OL{firstDigit}{remainingDigits}{suffix}"; + } + + private string CreateGoogleBooksId(Faker f) + { + const string validChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + return new string(Enumerable.Repeat(validChars, 12) + .Select(s => s[f.Random.Number(validChars.Length - 1)]) + .ToArray()); + } + + private List CreateIsbns(int count) + { + return new Faker() + .CustomInstantiator(f => new IsbnDto(CreateIsbn(f), f.PickRandom())) + .Generate(count); + } + + private string CreateIsbn(Faker f) + { + var isIsbn13 = f.Random.Bool(); + if (isIsbn13) + { + var prefix = f.Random.Bool() ? "978" : "979"; + var group = f.Random.Number(0, 99999).ToString().PadLeft(5, '0'); + var publisher = f.Random.Number(0, 999999).ToString().PadLeft(6, '0'); + var title = f.Random.Number(0, 99).ToString().PadLeft(2, '0'); + string isbn = $"{prefix}{group.Substring(0, 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.Substring(0, 1)}-{publisher}-{title}-{checkDigit}"; + } + else + { + var 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}"; + } + } + + private List CreateBookRatings(int count) + { + return new Faker() + .CustomInstantiator(f => new BookRatingDto( + f.Random.Decimal(1, 5), + 5, + f.PickRandom(), + f.Random.Number(1, 1000) + )) + .Generate(count); + } + + private void ConfigureCustomTypes() + { + _fixture.Register(() => new TagDto(_fixture.Create())); + _fixture.Register(() => new GenreDto(_fixture.Create())); + _fixture.Register(() => new IsbnDto(_fixture.Create(), _fixture.Create())); + _fixture.Register(() => new BookRatingDto( + _fixture.Create(), + _fixture.Create(), + _fixture.Create(), + _fixture.Create() + )); + } + #endregion +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Lumina.DataAccess.UnitTests.csproj b/tests/UnitTests/Lumina.DataAccess.UnitTests/Lumina.DataAccess.UnitTests.csproj index b4590b94..f187793e 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Lumina.DataAccess.UnitTests.csproj +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Lumina.DataAccess.UnitTests.csproj @@ -12,10 +12,12 @@ + +