mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-02 06:01:10 +00:00
Adds Presentation Api Layer integration tests
This commit is contained in:
1 parent
a3011297ca
commit
9d840db864
9 files changed
+1083
No files matched your search
+267
@@ -0,0 +1,267 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Enums;
|
||||
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;
|
||||
using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.Entities;
|
||||
using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.ValueObjects;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Common.Converters;
|
||||
|
||||
/// <summary>
|
||||
/// Custom JSON converter for the <see cref="Book"/> class.
|
||||
/// </summary>
|
||||
public class BookJsonConverter : JsonConverter<Book>
|
||||
{
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
/// <summary>
|
||||
/// Reads and converts JSON to a <see cref="Book"/> object.
|
||||
/// </summary>
|
||||
/// <param name="reader">The JSON reader.</param>
|
||||
/// <param name="typeToConvert">The type of the object to convert.</param>
|
||||
/// <param name="options">The serializer options.</param>
|
||||
/// <returns>The converted <see cref="Book"/> object.</returns>
|
||||
public override Book Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
|
||||
{
|
||||
using (JsonDocument doc = JsonDocument.ParseValue(ref reader))
|
||||
{
|
||||
JsonElement root = doc.RootElement;
|
||||
|
||||
var id = root.GetProperty("id").GetProperty("value").GetGuid();
|
||||
var created = root.GetProperty("created").GetDateTime();
|
||||
var metadata = DeserializeMetadata(root.GetProperty("metadata"));
|
||||
var format = Enum.Parse<BookFormat>(root.GetProperty("format").GetString()!);
|
||||
var edition = root.GetProperty("edition").GetString();
|
||||
var volumeNumber = root.GetProperty("volumeNumber").GetInt32();
|
||||
var series = DeserializeBookSeries(root.GetProperty("series"));
|
||||
var asin = root.GetProperty("asin").GetString();
|
||||
var goodreadsId = root.GetProperty("goodreadsId").GetString();
|
||||
var lccn = root.GetProperty("lccn").GetString();
|
||||
var oclcNumber = root.GetProperty("oclcNumber").GetString();
|
||||
var openLibraryId = root.GetProperty("openLibraryId").GetString();
|
||||
var libraryThingId = root.GetProperty("libraryThingId").GetString();
|
||||
var googleBooksId = root.GetProperty("googleBooksId").GetString();
|
||||
var barnesAndNobleId = root.GetProperty("barnesAndNobleId").GetString();
|
||||
var appleBooksId = root.GetProperty("appleBooksId").GetString();
|
||||
var isbns = DeserializeIsbns(root.GetProperty("isbNs"));
|
||||
var contributorIds = DeserializeContributorIds(root.GetProperty("contributors"));
|
||||
var ratings = DeserializeRatings(root.GetProperty("ratings"));
|
||||
|
||||
var createBookResult = Book.Create(
|
||||
BookId.Create(id),
|
||||
metadata,
|
||||
format,
|
||||
Optional<string>.FromNullable(edition),
|
||||
volumeNumber,
|
||||
Optional<BookSeries>.FromNullable(series),
|
||||
Optional<string>.FromNullable(asin),
|
||||
Optional<string>.FromNullable(goodreadsId),
|
||||
Optional<string>.FromNullable(lccn),
|
||||
Optional<string>.FromNullable(oclcNumber),
|
||||
Optional<string>.FromNullable(openLibraryId),
|
||||
Optional<string>.FromNullable(libraryThingId),
|
||||
Optional<string>.FromNullable(googleBooksId),
|
||||
Optional<string>.FromNullable(barnesAndNobleId),
|
||||
Optional<string>.FromNullable(appleBooksId),
|
||||
created,
|
||||
default,
|
||||
isbns,
|
||||
contributorIds,
|
||||
ratings: ratings
|
||||
);
|
||||
if (createBookResult.IsError)
|
||||
throw new JsonException($"Failed to create Book: {string.Join(", ", createBookResult.Errors)}");
|
||||
return createBookResult.Value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes a <see cref="Book"/> object to JSON. This method is not implemented.
|
||||
/// </summary>
|
||||
/// <param name="writer">The JSON writer.</param>
|
||||
/// <param name="value">The <see cref="Book"/> object to write.</param>
|
||||
/// <param name="options">The serializer options.</param>
|
||||
public override void Write(Utf8JsonWriter writer, Book value, JsonSerializerOptions options)
|
||||
{
|
||||
throw new NotImplementedException("Serialization is not implemented for Book class.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes the metadata from JSON.
|
||||
/// </summary>
|
||||
/// <param name="element">The JSON element containing the metadata.</param>
|
||||
/// <returns>The deserialized <see cref="WrittenContentMetadata"/>.</returns>
|
||||
private WrittenContentMetadata DeserializeMetadata(JsonElement element)
|
||||
{
|
||||
var title = element.GetProperty("title").GetString();
|
||||
var originalTitle = element.GetProperty("originalTitle").GetString();
|
||||
var description = element.GetProperty("description").GetString();
|
||||
var releaseInfo = DeserializeReleaseInfo(element.GetProperty("releaseInfo"));
|
||||
var genres = DeserializeGenres(element.GetProperty("genres"));
|
||||
var tags = DeserializeTags(element.GetProperty("tags"));
|
||||
var language = DeserializeLanguageInfo(element.GetProperty("language"));
|
||||
var originalLanguage = DeserializeLanguageInfo(element.GetProperty("originalLanguage"));
|
||||
var publisher = element.GetProperty("publisher").GetString();
|
||||
var pageCount = element.GetProperty("pageCount").GetInt32();
|
||||
|
||||
var metadataResult = WrittenContentMetadata.Create(
|
||||
title!,
|
||||
Optional<string>.FromNullable(originalTitle),
|
||||
Optional<string>.FromNullable(description),
|
||||
releaseInfo,
|
||||
genres,
|
||||
tags,
|
||||
Optional<LanguageInfo>.FromNullable(language),
|
||||
Optional<LanguageInfo>.FromNullable(originalLanguage),
|
||||
Optional<string>.FromNullable(publisher),
|
||||
Optional<int>.FromNullable(pageCount)
|
||||
);
|
||||
|
||||
if (metadataResult.IsError)
|
||||
{
|
||||
throw new JsonException($"Failed to create WrittenContentMetadata: {string.Join(", ", metadataResult.Errors)}");
|
||||
}
|
||||
|
||||
return metadataResult.Value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes the release info from JSON.
|
||||
/// </summary>
|
||||
/// <param name="element">The JSON element containing the release info.</param>
|
||||
/// <returns>The deserialized <see cref="ReleaseInfo"/>.</returns>
|
||||
private ReleaseInfo DeserializeReleaseInfo(JsonElement element)
|
||||
{
|
||||
var originalReleaseDate = element.TryGetProperty("originalReleaseDate", out var ordElement) ?
|
||||
DateOnly.Parse(ordElement.GetString()!) : (DateOnly?)null;
|
||||
var originalReleaseYear = element.TryGetProperty("originalReleaseYear", out var oryElement) ?
|
||||
oryElement.GetInt32() : (int?)null;
|
||||
var reReleaseDate = element.TryGetProperty("reReleaseDate", out var rrdElement) ?
|
||||
DateOnly.Parse(rrdElement.GetString()!) : (DateOnly?)null;
|
||||
var reReleaseYear = element.TryGetProperty("reReleaseYear", out var rryElement) ?
|
||||
rryElement.GetInt32() : (int?)null;
|
||||
var releaseCountry = element.TryGetProperty("releaseCountry", out var rcElement) ?
|
||||
rcElement.GetString() : null;
|
||||
var releaseVersion = element.TryGetProperty("releaseVersion", out var rvElement) ?
|
||||
rvElement.GetString() : null;
|
||||
|
||||
var releaseInfoResult = ReleaseInfo.Create(
|
||||
Optional<DateOnly>.FromNullable(originalReleaseDate),
|
||||
Optional<int>.FromNullable(originalReleaseYear),
|
||||
Optional<DateOnly>.FromNullable(reReleaseDate),
|
||||
Optional<int>.FromNullable(reReleaseYear),
|
||||
Optional<string>.FromNullable(releaseCountry),
|
||||
Optional<string>.FromNullable(releaseVersion)
|
||||
);
|
||||
|
||||
if (releaseInfoResult.IsError)
|
||||
throw new JsonException($"Failed to create ReleaseInfo: {string.Join(", ", releaseInfoResult.Errors)}");
|
||||
return releaseInfoResult.Value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes the genres from JSON.
|
||||
/// </summary>
|
||||
/// <param name="element">The JSON element containing the genres.</param>
|
||||
/// <returns>The deserialized list of <see cref="Genre"/>.</returns>
|
||||
private List<Genre> DeserializeGenres(JsonElement element)
|
||||
{
|
||||
return element.EnumerateArray()
|
||||
.Select(g => Genre.Create(g.GetProperty("name").GetString()!).Value)
|
||||
.ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes the tags from JSON.
|
||||
/// </summary>
|
||||
/// <param name="element">The JSON element containing the tags.</param>
|
||||
/// <returns>The deserialized list of <see cref="Tag"/>.</returns>
|
||||
private List<Tag> DeserializeTags(JsonElement element)
|
||||
{
|
||||
return element.EnumerateArray()
|
||||
.Select(t => Tag.Create(t.GetProperty("name").GetString()!).Value)
|
||||
.ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes the language info from JSON.
|
||||
/// </summary>
|
||||
/// <param name="element">The JSON element containing the language info.</param>
|
||||
/// <returns>The deserialized <see cref="LanguageInfo"/>.</returns>
|
||||
private LanguageInfo DeserializeLanguageInfo(JsonElement element)
|
||||
{
|
||||
var languageCode = element.GetProperty("languageCode").GetString();
|
||||
var languageName = element.GetProperty("languageName").GetString();
|
||||
var nativeName = element.TryGetProperty("nativeName", out var nnElement) ? nnElement.GetString() : null;
|
||||
|
||||
var languageInfoResult = LanguageInfo.Create(
|
||||
languageCode!,
|
||||
languageName!,
|
||||
Optional<string>.FromNullable(nativeName)
|
||||
);
|
||||
|
||||
if (languageInfoResult.IsError)
|
||||
{
|
||||
throw new JsonException($"Failed to create LanguageInfo: {string.Join(", ", languageInfoResult.Errors)}");
|
||||
}
|
||||
|
||||
return languageInfoResult.Value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes the book series from JSON.
|
||||
/// </summary>
|
||||
/// <param name="element">The JSON element containing the book series.</param>
|
||||
/// <returns>The deserialized <see cref="BookSeries"/>.</returns>
|
||||
private BookSeries DeserializeBookSeries(JsonElement element)
|
||||
{
|
||||
// TODO: implement when book series are implemented
|
||||
return null!;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes the ISBNs from JSON.
|
||||
/// </summary>
|
||||
/// <param name="element">The JSON element containing the ISBNs.</param>
|
||||
/// <returns>The deserialized list of <see cref="Isbn"/>.</returns>
|
||||
private List<Isbn> DeserializeIsbns(JsonElement element)
|
||||
{
|
||||
return element.EnumerateArray()
|
||||
.Select(i => Isbn.Create(i.GetProperty("value").GetString()!,
|
||||
Enum.Parse<IsbnFormat>(i.GetProperty("format").GetString()!)).Value)
|
||||
.ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes the contributor IDs from JSON.
|
||||
/// </summary>
|
||||
/// <param name="element">The JSON element containing the contributor IDs.</param>
|
||||
/// <returns>The deserialized list of <see cref="MediaContributorId"/>.</returns>
|
||||
private List<MediaContributorId> DeserializeContributorIds(JsonElement element)
|
||||
{
|
||||
// TODO: implement when contributors are implemented
|
||||
return new List<MediaContributorId>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes the ratings from JSON.
|
||||
/// </summary>
|
||||
/// <param name="element">The JSON element containing the ratings.</param>
|
||||
/// <returns>The deserialized list of <see cref="BookRating"/>.</returns>
|
||||
private List<BookRating> DeserializeRatings(JsonElement element)
|
||||
{
|
||||
return element.EnumerateArray()
|
||||
.Select(r => BookRating.Create(
|
||||
r.GetProperty("value").GetInt32(),
|
||||
r.GetProperty("maxValue").GetInt32(),
|
||||
Optional<BookRatingSource>.FromNullable(Enum.Parse<BookRatingSource>(r.GetProperty("source").GetString()!)),
|
||||
Optional<int>.FromNullable(r.GetProperty("voteCount").GetInt32())
|
||||
).Value)
|
||||
.ToList();
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
|
||||
/// <summary>
|
||||
/// Contains extension methods for the <see cref="Faker"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public static class BogusExtensions
|
||||
{
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
/// <summary>
|
||||
/// Adds <see cref="DateOnly"/> random data generation support to the <see cref="Faker"/> class.
|
||||
/// </summary>
|
||||
/// <param name="faker">The faker instance to extend.</param>
|
||||
/// <returns>A random<see cref="DateOnly"/> instance.</returns>
|
||||
public static DateOnly DateOnly(this Faker faker)
|
||||
{
|
||||
return System.DateOnly.FromDateTime(faker.Date.Past());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds <see cref="DateOnly"/> random data generation within a specified interval support to the <see cref="Faker"/> class.
|
||||
/// </summary>
|
||||
/// <param name="faker">The faker instance to extend.</param>
|
||||
/// <param name="start">The start of the interval.</param>
|
||||
/// <param name="end">The end of the interval.</param>
|
||||
/// <returns>A random<see cref="DateOnly"/> instance.</returns>
|
||||
public static DateOnly DateOnlyBetween(this Faker faker, DateOnly start, DateOnly end)
|
||||
{
|
||||
var startDateTime = start.ToDateTime(TimeOnly.MinValue);
|
||||
var endDateTime = end.ToDateTime(TimeOnly.MinValue);
|
||||
return System.DateOnly.FromDateTime(faker.Date.Between(startDateTime, endDateTime));
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using AutoFixture.Kernel;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a specimen builder for the <see cref="DateOnly"/> type.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DateOnlySpecimenBuilder : ISpecimenBuilder
|
||||
{
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
/// <summary>
|
||||
/// Adds <see cref="DateOnly"/> support to the AutoFixture library.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to process.</param>
|
||||
/// <param name="context">The context within which the specimen is created.</param>
|
||||
/// <returns>A specimen based on the request.</returns>
|
||||
public object Create(object request, ISpecimenContext context)
|
||||
{
|
||||
if (request is Type type && type == typeof(DateOnly))
|
||||
return DateOnly.FromDateTime(DateTime.Now);
|
||||
return new NoSpecimen();
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
|
||||
/// <summary>
|
||||
/// Factory for creating a web application for integration tests.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LuminaApiFactory : WebApplicationFactory<Program>, IDisposable
|
||||
{
|
||||
#region ================================================================== FIELD MEMBERS ================================================================================
|
||||
private readonly SqliteConnection _connection;
|
||||
#endregion
|
||||
|
||||
#region ====================================================================== CTOR =====================================================================================
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LuminaApiFactory"/> class.
|
||||
/// </summary>
|
||||
public LuminaApiFactory()
|
||||
{
|
||||
_connection = new SqliteConnection("DataSource=:memory:");
|
||||
_connection.Open();
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
/// <summary>
|
||||
/// Configures the web host for the integration tests.
|
||||
/// </summary>
|
||||
/// <param name="builder">The web host builder to configure.</param>
|
||||
protected override void ConfigureWebHost(IWebHostBuilder builder)
|
||||
{
|
||||
builder.ConfigureServices(services =>
|
||||
{
|
||||
var descriptor = services.SingleOrDefault(serviceDescriptor => serviceDescriptor.ServiceType == typeof(DbContextOptions<LuminaDbContext>));
|
||||
if (descriptor is not null)
|
||||
services.Remove(descriptor);
|
||||
services.AddDbContext<LuminaDbContext>(options =>
|
||||
{
|
||||
options.UseSqlite(_connection);
|
||||
});
|
||||
var servicePreovider = services.BuildServiceProvider();
|
||||
using (var scope = servicePreovider.CreateScope())
|
||||
{
|
||||
var scopedServices = scope.ServiceProvider;
|
||||
var dbContext = scopedServices.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Database.EnsureCreated();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the connection to the database.
|
||||
/// </summary>
|
||||
public new void Dispose()
|
||||
{
|
||||
_connection.Close();
|
||||
base.Dispose();
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using AutoFixture.Kernel;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a specimen builder for the <see cref="DateOnly"/> type.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class NullableDateOnlySpecimenBuilder : ISpecimenBuilder
|
||||
{
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
/// <summary>
|
||||
/// Adds <see cref="DateOnly?"/> support to the AutoFixture library.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to process.</param>
|
||||
/// <param name="context">The context within which the specimen is created.</param>
|
||||
/// <returns>A specimen based on the request.</returns>
|
||||
public object Create(object request, ISpecimenContext context)
|
||||
{
|
||||
if (request is Type type && type == typeof(DateOnly?))
|
||||
return (DateOnly?)DateOnly.FromDateTime(DateTime.Now);
|
||||
return new NoSpecimen();
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
+159
@@ -0,0 +1,159 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentAssertions;
|
||||
using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate;
|
||||
using Lumina.Presentation.Api.Common.Contracts.Books;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Converters;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Core.Controllers.Books.Fixtures;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Controllers.Books;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="BooksController"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class BooksControllerTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
#region ================================================================== FIELD MEMBERS ================================================================================
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly HttpClient _client;
|
||||
private readonly RequestBookFixture _requestBookFixture;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new();
|
||||
#endregion
|
||||
|
||||
#region ====================================================================== CTOR =====================================================================================
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BooksControllerTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public BooksControllerTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = _apiFactory.CreateClient();
|
||||
_requestBookFixture = new RequestBookFixture();
|
||||
_jsonOptions.Converters.Add(new BookJsonConverter());
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
[Fact]
|
||||
public async Task AddsBook_WhenCalled_ShouldAddBook()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest bookRequest = _requestBookFixture.CreateRequestBook();
|
||||
|
||||
// Act
|
||||
var response = await _client.PostAsJsonAsync("api/v1/books", bookRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
var bookResponse = await response.Content.ReadFromJsonAsync<Book>(_jsonOptions);
|
||||
response.StatusCode.Should().Be(HttpStatusCode.Created);
|
||||
bookResponse.Should().NotBeNull();
|
||||
|
||||
// metadata checks
|
||||
bookResponse!.Metadata.Title.Should().Be(bookRequest.Metadata.Title);
|
||||
bookResponse.Metadata.OriginalTitle.Value.Should().Be(bookRequest.Metadata.OriginalTitle);
|
||||
bookResponse.Metadata.Description.Value.Should().Be(bookRequest.Metadata.Description);
|
||||
bookResponse.Metadata.Publisher.Value.Should().Be(bookRequest.Metadata.Publisher);
|
||||
bookResponse.Metadata.PageCount.Value.Should().Be(bookRequest.Metadata.PageCount);
|
||||
|
||||
// releaseInfo checks
|
||||
bookResponse.Metadata.ReleaseInfo.OriginalReleaseDate.Value.Should().Be(bookRequest.Metadata.ReleaseInfo.OriginalReleaseDate);
|
||||
bookResponse.Metadata.ReleaseInfo.OriginalReleaseYear.Value.Should().Be(bookRequest.Metadata.ReleaseInfo.OriginalReleaseYear);
|
||||
bookResponse.Metadata.ReleaseInfo.ReReleaseDate.Value.Should().Be(bookRequest.Metadata.ReleaseInfo.ReReleaseDate);
|
||||
bookResponse.Metadata.ReleaseInfo.ReReleaseYear.Value.Should().Be(bookRequest.Metadata.ReleaseInfo.ReReleaseYear);
|
||||
bookResponse.Metadata.ReleaseInfo.ReleaseCountry.Value.Should().Be(bookRequest.Metadata.ReleaseInfo.ReleaseCountry);
|
||||
bookResponse.Metadata.ReleaseInfo.ReleaseVersion.Value.Should().Be(bookRequest.Metadata.ReleaseInfo.ReleaseVersion);
|
||||
|
||||
// language checks
|
||||
bookResponse.Metadata.Language.Value.LanguageCode.Should().Be(bookRequest.Metadata.Language!.LanguageCode);
|
||||
bookResponse.Metadata.Language.Value.LanguageName.Should().Be(bookRequest.Metadata.Language.LanguageName);
|
||||
bookResponse.Metadata.Language.Value.NativeName.Value.Should().Be(bookRequest.Metadata.Language.NativeName);
|
||||
|
||||
// original language checks
|
||||
bookResponse.Metadata.OriginalLanguage.Value.LanguageCode.Should().Be(bookRequest.Metadata.OriginalLanguage!.LanguageCode);
|
||||
bookResponse.Metadata.OriginalLanguage.Value.LanguageName.Should().Be(bookRequest.Metadata.OriginalLanguage.LanguageName);
|
||||
bookResponse.Metadata.OriginalLanguage.Value.NativeName.Value.Should().Be(bookRequest.Metadata.OriginalLanguage.NativeName);
|
||||
|
||||
// genres checks
|
||||
bookResponse.Metadata.Genres.Should().HaveCount(bookRequest.Metadata.Genres.Count);
|
||||
bookResponse.Metadata.Genres.Select(genre => genre.Name).Should().BeEquivalentTo(bookRequest.Metadata.Genres.Select(genre => genre.Name));
|
||||
|
||||
// tags checks
|
||||
bookResponse.Metadata.Tags.Should().HaveCount(bookRequest.Metadata.Tags.Count);
|
||||
bookResponse.Metadata.Tags.Select(tag => tag.Name).Should().BeEquivalentTo(bookRequest.Metadata.Tags.Select(tag => tag.Name));
|
||||
|
||||
// book specific properties
|
||||
bookResponse.Format.Should().Be(bookRequest.Format);
|
||||
bookResponse.Edition.Value.Should().Be(bookRequest.Edition);
|
||||
bookResponse.VolumeNumber.Value.Should().Be(bookRequest.VolumeNumber);
|
||||
bookResponse.ASIN.Value.Should().Be(bookRequest.ASIN);
|
||||
bookResponse.GoodreadsId.Value.Should().Be(bookRequest.GoodreadsId);
|
||||
bookResponse.LCCN.Value.Should().Be(bookRequest.LCCN);
|
||||
bookResponse.OCLCNumber.Value.Should().Be(bookRequest.OCLCNumber);
|
||||
bookResponse.OpenLibraryId.Value.Should().Be(bookRequest.OpenLibraryId);
|
||||
bookResponse.LibraryThingId.Value.Should().Be(bookRequest.LibraryThingId);
|
||||
bookResponse.GoogleBooksId.Value.Should().Be(bookRequest.GoogleBooksId);
|
||||
bookResponse.BarnesAndNobleId.Value.Should().Be(bookRequest.BarnesAndNobleId);
|
||||
bookResponse.AppleBooksId.Value.Should().Be(bookRequest.AppleBooksId);
|
||||
|
||||
// ISBNs checks
|
||||
bookResponse.ISBNs.Should().HaveCount(bookRequest.ISBNs.Count);
|
||||
bookResponse.ISBNs.Should().HaveCount(bookRequest.ISBNs.Count);
|
||||
bookResponse.ISBNs.Select(isbn => new { isbn.Value, isbn.Format })
|
||||
.Should().BeEquivalentTo(bookRequest.ISBNs.Select(isbn => new { isbn.Value, isbn.Format }));
|
||||
|
||||
// contributors checks
|
||||
// TODO: update when contributors are implemented
|
||||
// bookResponse.Contributors.Should().HaveCount(bookRequest.Contributors.Count);
|
||||
|
||||
// ratings checks
|
||||
bookResponse.Ratings.Should().HaveCount(bookRequest.Ratings.Count);
|
||||
bookResponse.Ratings.Should().HaveCount(bookRequest.Ratings.Count);
|
||||
bookResponse.Ratings.Select(bookRating => new { Source = bookRating.Source.Value, bookRating.Value, bookRating.MaxValue, VoteCount = bookRating.VoteCount.Value })
|
||||
.Should().BeEquivalentTo(bookRequest.Ratings.Select(bookRating => new { bookRating.Source, bookRating.Value, bookRating.MaxValue, bookRating.VoteCount }));
|
||||
|
||||
// series checks
|
||||
if (bookRequest.Series is not null)
|
||||
{
|
||||
bookResponse.Series.Should().NotBeNull();
|
||||
bookResponse.Series.Value.Metadata.Title.Should().Be(bookRequest.Series.Title);
|
||||
}
|
||||
else
|
||||
bookResponse.Series.Value.Should().BeNull();
|
||||
|
||||
// check Location header
|
||||
response.Headers.Location.Should().NotBeNull();
|
||||
var locationUri = response.Headers.Location!.ToString();
|
||||
locationUri.Should().StartWith("/api/v1/books/");
|
||||
|
||||
// extract ID from Location header
|
||||
var idFromHeader = locationUri.Split('/').Last();
|
||||
|
||||
// compare with bookResponse id
|
||||
bookResponse!.Id.ToString().Should().Be(idFromHeader);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetBooks_WhenCalled_ShouldReturnBooks()
|
||||
{
|
||||
// Arrange
|
||||
var response = await _client.GetAsync("/api/v1/books");
|
||||
|
||||
// Act
|
||||
response.EnsureSuccessStatusCode();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
response.StatusCode.Should().Be(HttpStatusCode.OK);
|
||||
var bookResponse = await response.Content.ReadFromJsonAsync<Book[]>(_jsonOptions);
|
||||
bookResponse.Should().NotBeNull();
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using AutoFixture;
|
||||
using Lumina.Domain.Common.Enums;
|
||||
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;
|
||||
using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.Entities;
|
||||
using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.ValueObjects;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Controllers.Books.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="BooksControllerTests"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DomainBookFixture
|
||||
{
|
||||
#region ================================================================== FIELD MEMBERS ================================================================================
|
||||
private readonly Fixture _fixture;
|
||||
#endregion
|
||||
|
||||
#region ====================================================================== CTOR =====================================================================================
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DomainBookFixture"/> class.
|
||||
/// </summary>
|
||||
public DomainBookFixture()
|
||||
{
|
||||
_fixture = new Fixture();
|
||||
_fixture.Customizations.Add(new DateOnlySpecimenBuilder());
|
||||
_fixture.Customizations.Add(new NullableDateOnlySpecimenBuilder());
|
||||
ConfigureCustomDomainTypes();
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
public Book CreateDomainBook()
|
||||
{
|
||||
return Book.Create(
|
||||
_fixture.Create<WrittenContentMetadata>(),
|
||||
_fixture.Create<BookFormat>(),
|
||||
_fixture.Create<Optional<string>>(),
|
||||
_fixture.Create<Optional<int>>(),
|
||||
_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>>()
|
||||
).Value;
|
||||
}
|
||||
|
||||
private void ConfigureCustomDomainTypes()
|
||||
{
|
||||
_fixture.Register(() => Optional<string>.Some(_fixture.Create<string>()));
|
||||
_fixture.Register(() => Optional<int>.Some(_fixture.Create<int>()));
|
||||
|
||||
_fixture.Register(() => ReleaseInfo.Create(
|
||||
_fixture.Create<Optional<DateOnly>>(),
|
||||
_fixture.Create<Optional<int>>(),
|
||||
_fixture.Create<Optional<DateOnly>>(),
|
||||
_fixture.Create<Optional<int>>(),
|
||||
_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(() => Isbn.Create(
|
||||
_fixture.Create<string>(),
|
||||
_fixture.Create<IsbnFormat>()
|
||||
).Value);
|
||||
|
||||
_fixture.Register(() => BookRating.Create(
|
||||
_fixture.Create<decimal>(),
|
||||
_fixture.Create<decimal>(),
|
||||
_fixture.Create<Optional<BookRatingSource>>(),
|
||||
_fixture.Create<Optional<int>>()
|
||||
).Value);
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
+343
@@ -0,0 +1,343 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using AutoFixture;
|
||||
using Bogus;
|
||||
using Lumina.Application.Common.Models.Books;
|
||||
using Lumina.Application.Common.Models.Common;
|
||||
using Lumina.Application.Common.Models.Contributors;
|
||||
using Lumina.Domain.Common.Enums;
|
||||
using Lumina.Presentation.Api.Common.Contracts.Books;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Controllers.Books.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="BooksControllerTests"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RequestBookFixture
|
||||
{
|
||||
#region ================================================================== FIELD MEMBERS ================================================================================
|
||||
private readonly Fixture _fixture;
|
||||
private readonly Random _random = new();
|
||||
private readonly Faker _faker;
|
||||
#endregion
|
||||
|
||||
#region ====================================================================== CTOR =====================================================================================
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RequestBookFixture"/> class.
|
||||
/// </summary>
|
||||
public RequestBookFixture()
|
||||
{
|
||||
_fixture = new Fixture();
|
||||
_fixture.Customizations.Add(new DateOnlySpecimenBuilder());
|
||||
_fixture.Customizations.Add(new NullableDateOnlySpecimenBuilder());
|
||||
_faker = new Faker();
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
/// <summary>
|
||||
/// Creates a random valid request to add a book.
|
||||
/// </summary>
|
||||
/// <returns>The created request to add a book.</returns>
|
||||
public AddBookRequest CreateRequestBook()
|
||||
{
|
||||
var releaseYear = _random.Next(2000, 2010);
|
||||
var reReleaseYear = _random.Next(2010, 2020);
|
||||
|
||||
var 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();
|
||||
|
||||
var genre = new Faker<GenreDto>()
|
||||
.CustomInstantiator(f => new GenreDto(
|
||||
default!
|
||||
))
|
||||
.RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50)));
|
||||
|
||||
var tag = new Faker<TagDto>()
|
||||
.CustomInstantiator(f => new TagDto(
|
||||
default!
|
||||
))
|
||||
.RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50)));
|
||||
|
||||
var mediaContributorRole = new Faker<MediaContributorRoleDto>()
|
||||
.CustomInstantiator(f => new MediaContributorRoleDto(
|
||||
default!,
|
||||
default!
|
||||
))
|
||||
.RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50)))
|
||||
.RuleFor(e => e.Category, f => f.Random.String2(f.Random.Number(1, 50)));
|
||||
|
||||
var mediaContributor = new Faker<MediaContributorDto>()
|
||||
.CustomInstantiator(f => new MediaContributorDto(
|
||||
default!,
|
||||
default!
|
||||
))
|
||||
.RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50)))
|
||||
.RuleFor(e => e.Role, mediaContributorRole);
|
||||
|
||||
var 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));
|
||||
|
||||
var 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)));
|
||||
|
||||
var 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)));
|
||||
|
||||
var 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));
|
||||
|
||||
var isbn = new Faker<IsbnDto>()
|
||||
.CustomInstantiator(f => new IsbnDto(
|
||||
default!,
|
||||
default
|
||||
))
|
||||
.RuleFor(i => i.Value, 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}";
|
||||
}
|
||||
})
|
||||
.RuleFor(i => i.Format, (f, i) => i.Value.Length > 13 ? IsbnFormat.Isbn13 : IsbnFormat.Isbn10);
|
||||
|
||||
return new Faker<AddBookRequest>()
|
||||
.CustomInstantiator(f => new AddBookRequest(
|
||||
default!,
|
||||
default,
|
||||
default,
|
||||
default,
|
||||
default,
|
||||
default,
|
||||
default,
|
||||
default,
|
||||
default,
|
||||
default,
|
||||
default,
|
||||
default,
|
||||
default,
|
||||
default,
|
||||
default!,
|
||||
default!,
|
||||
default!
|
||||
))
|
||||
.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 =>
|
||||
{
|
||||
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;
|
||||
})
|
||||
.RuleFor(x => x.OCLCNumber, f =>
|
||||
{
|
||||
string[] prefixes = ["ocm", "ocn", "on", "(OCoLC)"];
|
||||
var 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 =>
|
||||
{
|
||||
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}";
|
||||
})
|
||||
.RuleFor(x => x.LibraryThingId, f => f.Random.String2(f.Random.Number(1, 50)))
|
||||
.RuleFor(x => x.GoogleBooksId, f =>
|
||||
{
|
||||
const string validChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
||||
return new string(Enumerable.Repeat(validChars, 12)
|
||||
.Select(s => s[f.Random.Number(validChars.Length - 1)])
|
||||
.ToArray());
|
||||
})
|
||||
.RuleFor(x => x.BarnesAndNobleId, f => f.Random.String2(10, "0123456789"))
|
||||
.RuleFor(x => x.AppleBooksId, f => $"id{f.Random.Number(1, 999999)}")
|
||||
.RuleFor(x => x.AppleBooksId, f => $"id{f.Random.Number(1, 999999)}")
|
||||
.RuleFor(p => p.ISBNs, f => isbn.Generate(f.Random.Number(1, 5)))
|
||||
.RuleFor(p => p.Ratings, f => rating.Generate(f.Random.Number(1, 5)))
|
||||
.RuleFor(x => x.Contributors, f => mediaContributor.Generate(f.Random.Number(1, 5)));
|
||||
}
|
||||
|
||||
private void ConfigureCustomRequestTypes()
|
||||
{
|
||||
var releaseYear = _random.Next(2000, 2010);
|
||||
var reReleaseYear = _random.Next(2010, 2020);
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
_fixture.Register(() => new ReleaseInfoDto(
|
||||
_faker.DateOnlyBetween(new DateOnly(releaseYear, 1, 1), new DateOnly(releaseYear, 12, 31)),
|
||||
releaseYear,
|
||||
_faker.DateOnlyBetween(new DateOnly(reReleaseYear, 1, 1), new DateOnly(reReleaseYear, 12, 31)),
|
||||
reReleaseYear,
|
||||
_fixture.Create<string>()[2..],
|
||||
_fixture.Create<string?>()));
|
||||
|
||||
_fixture.Register(() => new GenreDto(
|
||||
_fixture.Create<string>()
|
||||
));
|
||||
_fixture.Register(() => new TagDto(
|
||||
_fixture.Create<string>()
|
||||
));
|
||||
_fixture.Register(() => new LanguageInfoDto(
|
||||
_fixture.Create<string>(),
|
||||
_fixture.Create<string>(),
|
||||
_fixture.Create<string?>()
|
||||
));
|
||||
_fixture.Register(() => new IsbnDto(
|
||||
_fixture.Create<string>(),
|
||||
_fixture.Create<IsbnFormat>()
|
||||
));
|
||||
_fixture.Register(() => new BookRatingDto(
|
||||
_fixture.Create<decimal>(),
|
||||
_fixture.Create<decimal>(),
|
||||
_fixture.Create<BookRatingSource?>(),
|
||||
_fixture.Create<int?>()
|
||||
));
|
||||
_fixture.Register(() => new WrittenContentMetadataDto(
|
||||
_fixture.Create<string>()[255..],
|
||||
LimitStringLength(_fixture.Create<string?>(), 255),
|
||||
LimitStringLength(_fixture.Create<string?>(), 2000),
|
||||
_fixture.Create<ReleaseInfoDto>(),
|
||||
_fixture.Create<List<GenreDto>>(),
|
||||
_fixture.Create<List<TagDto>>(),
|
||||
_fixture.Create<LanguageInfoDto?>(),
|
||||
_fixture.Create<LanguageInfoDto?>(),
|
||||
_fixture.Create<string?>(),
|
||||
_fixture.Create<int?>()
|
||||
));
|
||||
_fixture.Register(() => new BookSeriesDto(
|
||||
_fixture.Create<string>()
|
||||
));
|
||||
_fixture.Register(() => new MediaContributorRoleDto(
|
||||
_fixture.Create<string>(),
|
||||
_fixture.Create<string>()
|
||||
));
|
||||
_fixture.Register(() => new MediaContributorDto(
|
||||
_fixture.Create<string>(),
|
||||
_fixture.Create<MediaContributorRoleDto>()
|
||||
));
|
||||
}
|
||||
|
||||
private string? LimitStringLength(string? input, int maxLength)
|
||||
{
|
||||
return input?.Length > maxLength ? input.Substring(0, maxLength) : input;
|
||||
}
|
||||
|
||||
private int? OptionalYear()
|
||||
{
|
||||
// 50% chance of returning null, 50% chance of returning a value between 1 and 9999
|
||||
return _random.Next(2) == 0 ? null : _random.Next(1, 10000);
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>true</IsTestProject>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AutoFixture.AutoNSubstitute" Version="4.18.1" />
|
||||
<PackageReference Include="AutoFixture.Xunit2" Version="4.18.1" />
|
||||
<PackageReference Include="Bogus" Version="35.6.0" />
|
||||
<PackageReference Include="coverlet.collector" Version="6.0.2">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="FluentAssertions" Version="6.12.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="8.0.8" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.0" />
|
||||
<PackageReference Include="NSubstitute" Version="5.1.0" />
|
||||
<PackageReference Include="xunit" Version="2.9.0" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Using Include="Xunit" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\src\Lumina.Presentation.Api\Lumina.Presentation.Api.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
Reference in new issue
Block a user