mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-02 16:11:10 +00:00
Renames project paths from Lumina to Nemera
This commit is contained in:
1 parent
ce6fddb4c9
commit
0f659a4877
6450 files changed
No files matched your search
+568
@@ -0,0 +1,568 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Plugins.OpenLibrary.Common.Models.Contracts.Responses;
|
||||
using Lumina.Plugins.OpenLibrary.Common.Models.DTO.Settings;
|
||||
using Lumina.Plugins.OpenLibrary.Core.Api;
|
||||
using Lumina.Plugins.OpenLibrary.Core.Settings;
|
||||
using Lumina.Plugins.OpenLibrary.Fixtures.Common.Models.DTO.Settings;
|
||||
using Lumina.Plugins.OpenLibrary.Fixtures.Common.Setup;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.OpenLibrary.UnitTests.Core.Api;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="OpenLibraryHttpClient"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class OpenLibraryHttpClientTests
|
||||
{
|
||||
private readonly OpenLibrarySettingsDtoFixture _openLibrarySettingsDtoFixture = new();
|
||||
private readonly BookMetadataLookupDtoFixture _bookMetadataLookupDtoFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenHttpClientHasNoBaseAddress_ShouldSetTheDefaultOpenLibraryBaseAddress()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient httpClient = new(new StubOpenLibraryHttpMessageHandler());
|
||||
|
||||
// Act
|
||||
_ = new OpenLibraryHttpClient(httpClient, new OpenLibrarySettingsProvider(null, Guid.NewGuid(), _openLibrarySettingsDtoFixture.Create()));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(new Uri("https://openlibrary.org/"), httpClient.BaseAddress);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenHttpClientAlreadyHasBaseAddress_ShouldKeepTheExistingBaseAddress()
|
||||
{
|
||||
// Arrange
|
||||
Uri existingBaseAddress = new("https://example.com/");
|
||||
HttpClient httpClient = new(new StubOpenLibraryHttpMessageHandler())
|
||||
{
|
||||
BaseAddress = existingBaseAddress
|
||||
};
|
||||
|
||||
// Act
|
||||
_ = new OpenLibraryHttpClient(httpClient, new OpenLibrarySettingsProvider(null, Guid.NewGuid(), _openLibrarySettingsDtoFixture.Create()));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(existingBaseAddress, httpClient.BaseAddress);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetEditionAsync_WhenHttpClientHasNoUserAgent_ShouldAddTheConfiguredUserAgent()
|
||||
{
|
||||
// Arrange
|
||||
StubOpenLibraryHttpMessageHandler handler = new();
|
||||
handler.MapPath("/books/OL1M.json", """{"key":"/books/OL1M","title":"Edition Title"}""");
|
||||
HttpClient httpClient = new(handler);
|
||||
OpenLibraryHttpClient sut = new(httpClient, new OpenLibrarySettingsProvider(null, Guid.NewGuid(), _openLibrarySettingsDtoFixture.Create(userAgent: "CustomAgent/2.0")));
|
||||
|
||||
// Act
|
||||
await sut.GetEditionAsync("OL1M", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("CustomAgent/2.0", httpClient.DefaultRequestHeaders.UserAgent.ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetEditionAsync_WhenHttpClientAlreadyHasUserAgent_ShouldKeepTheExistingUserAgent()
|
||||
{
|
||||
// Arrange
|
||||
StubOpenLibraryHttpMessageHandler handler = new();
|
||||
handler.MapPath("/books/OL1M.json", """{"key":"/books/OL1M","title":"Edition Title"}""");
|
||||
HttpClient httpClient = new(handler);
|
||||
httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("ExistingAgent/1.0");
|
||||
OpenLibraryHttpClient sut = new(httpClient, new OpenLibrarySettingsProvider(null, Guid.NewGuid(), _openLibrarySettingsDtoFixture.Create(userAgent: "ConfiguredAgent/2.0")));
|
||||
|
||||
// Act
|
||||
await sut.GetEditionAsync("OL1M", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("ExistingAgent/1.0", httpClient.DefaultRequestHeaders.UserAgent.ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetEditionAsync_WhenContactEmailIsConfigured_ShouldSetTheFromHeader()
|
||||
{
|
||||
// Arrange
|
||||
StubOpenLibraryHttpMessageHandler handler = new();
|
||||
handler.MapPath("/books/OL1M.json", """{"key":"/books/OL1M","title":"Edition Title"}""");
|
||||
HttpClient httpClient = new(handler);
|
||||
OpenLibraryHttpClient sut = new(httpClient, new OpenLibrarySettingsProvider(null, Guid.NewGuid(), _openLibrarySettingsDtoFixture.Create(contactEmail: "contact@example.com")));
|
||||
|
||||
// Act
|
||||
await sut.GetEditionAsync("OL1M", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("contact@example.com", httpClient.DefaultRequestHeaders.From);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetEditionAsync_WhenContactEmailIsNotConfigured_ShouldNotSetTheFromHeader()
|
||||
{
|
||||
// Arrange
|
||||
StubOpenLibraryHttpMessageHandler handler = new();
|
||||
handler.MapPath("/books/OL1M.json", """{"key":"/books/OL1M","title":"Edition Title"}""");
|
||||
HttpClient httpClient = new(handler);
|
||||
OpenLibraryHttpClient sut = new(httpClient, new OpenLibrarySettingsProvider(null, Guid.NewGuid(), _openLibrarySettingsDtoFixture.Create(contactEmail: null)));
|
||||
|
||||
// Act
|
||||
await sut.GetEditionAsync("OL1M", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Null(httpClient.DefaultRequestHeaders.From);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetEditionByIsbnAsync_WhenEditionExists_ShouldRequestTheNormalizedIsbnEndpointAndDeserialize()
|
||||
{
|
||||
// Arrange
|
||||
StubOpenLibraryHttpMessageHandler handler = new();
|
||||
handler.MapPath("/isbn/9780306406157.json", """{"key":"/books/OL1M","title":"Edition Title"}""");
|
||||
OpenLibraryHttpClient sut = CreateSut(handler);
|
||||
|
||||
// Act
|
||||
OpenLibraryEditionResponse? result = await sut.GetEditionByIsbnAsync("978-0-306-40615-7", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("Edition Title", result!.Title);
|
||||
Assert.Equal("/isbn/9780306406157.json", handler.Requests[0].RequestUri!.AbsolutePath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetEditionByIsbnAsync_WhenEditionIsNotFound_ShouldReturnNull()
|
||||
{
|
||||
// Arrange
|
||||
StubOpenLibraryHttpMessageHandler handler = new();
|
||||
OpenLibraryHttpClient sut = CreateSut(handler);
|
||||
|
||||
// Act
|
||||
OpenLibraryEditionResponse? result = await sut.GetEditionByIsbnAsync("978-0-306-40615-7", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result);
|
||||
Assert.Single(handler.Requests);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetEditionAsync_WhenCalled_ShouldRequestTheBooksEndpointWithTheNormalizedOlid()
|
||||
{
|
||||
// Arrange
|
||||
StubOpenLibraryHttpMessageHandler handler = new();
|
||||
handler.MapPath("/books/OL123M.json", """{"key":"/books/OL123M","title":"Edition"}""");
|
||||
OpenLibraryHttpClient sut = CreateSut(handler);
|
||||
|
||||
// Act
|
||||
OpenLibraryEditionResponse? result = await sut.GetEditionAsync("/books/ol123m", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("/books/OL123M.json", handler.Requests[0].RequestUri!.AbsolutePath);
|
||||
Assert.Equal("/books/OL123M", result!.Key);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetEditionAsync_WhenOlidIsNotAnEditionId_ShouldThrowArgumentException()
|
||||
{
|
||||
// Arrange
|
||||
OpenLibraryHttpClient sut = CreateSut(new StubOpenLibraryHttpMessageHandler());
|
||||
|
||||
// Act
|
||||
async Task Act()
|
||||
{
|
||||
await sut.GetEditionAsync("OL123W", CancellationToken.None);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<ArgumentException>(Act);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetWorkAsync_WhenCalled_ShouldRequestTheWorksEndpointWithTheNormalizedOlid()
|
||||
{
|
||||
// Arrange
|
||||
StubOpenLibraryHttpMessageHandler handler = new();
|
||||
handler.MapPath("/works/OL123W.json", """{"key":"/works/OL123W","title":"Work"}""");
|
||||
OpenLibraryHttpClient sut = CreateSut(handler);
|
||||
|
||||
// Act
|
||||
OpenLibraryWorkResponse? result = await sut.GetWorkAsync("OL123W", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("/works/OL123W.json", handler.Requests[0].RequestUri!.AbsolutePath);
|
||||
Assert.Equal("Work", result!.Title);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAuthorAsync_WhenCalled_ShouldRequestTheAuthorsEndpointWithTheNormalizedOlid()
|
||||
{
|
||||
// Arrange
|
||||
StubOpenLibraryHttpMessageHandler handler = new();
|
||||
handler.MapPath("/authors/OL1A.json", """{"key":"/authors/OL1A","name":"Test Author"}""");
|
||||
OpenLibraryHttpClient sut = CreateSut(handler);
|
||||
|
||||
// Act
|
||||
OpenLibraryAuthorResponse? result = await sut.GetAuthorAsync("OL1A", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("/authors/OL1A.json", handler.Requests[0].RequestUri!.AbsolutePath);
|
||||
Assert.Equal("Test Author", result!.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRatingsAsync_WhenCalled_ShouldRequestTheRatingsEndpoint()
|
||||
{
|
||||
// Arrange
|
||||
StubOpenLibraryHttpMessageHandler handler = new();
|
||||
handler.MapPath("/works/OL123W/ratings.json", """{"summary":{"average":4.2,"count":100}}""");
|
||||
OpenLibraryHttpClient sut = CreateSut(handler);
|
||||
|
||||
// Act
|
||||
OpenLibraryRatingsResponse? result = await sut.GetRatingsAsync("OL123W", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("/works/OL123W/ratings.json", handler.Requests[0].RequestUri!.AbsolutePath);
|
||||
Assert.Equal(4.2m, result!.Summary!.Average);
|
||||
Assert.Equal(100, result.Summary.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRatingsAsync_WhenNumbersAreSerializedAsStrings_ShouldStillDeserializeThem()
|
||||
{
|
||||
// Arrange
|
||||
StubOpenLibraryHttpMessageHandler handler = new();
|
||||
handler.MapPath("/works/OL123W/ratings.json", """{"summary":{"average":"4.2","count":"100"}}""");
|
||||
OpenLibraryHttpClient sut = CreateSut(handler);
|
||||
|
||||
// Act
|
||||
OpenLibraryRatingsResponse? result = await sut.GetRatingsAsync("OL123W", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(4.2m, result!.Summary!.Average);
|
||||
Assert.Equal(100, result.Summary.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetEditionsAsync_WhenCalled_ShouldRequestTheEditionsEndpointWithTheConfiguredLimit()
|
||||
{
|
||||
// Arrange
|
||||
StubOpenLibraryHttpMessageHandler handler = new();
|
||||
handler.MapPath("/works/OL123W/editions.json", """{"entries":[{"key":"/books/OL1M","title":"Edition"}]}""");
|
||||
OpenLibraryHttpClient sut = CreateSut(handler);
|
||||
|
||||
// Act
|
||||
IReadOnlyList<OpenLibraryEditionResponse> result = await sut.GetEditionsAsync("OL123W", 50, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
OpenLibraryEditionResponse edition = Assert.Single(result);
|
||||
Assert.Equal("Edition", edition.Title);
|
||||
Assert.Equal("/works/OL123W/editions.json", handler.Requests[0].RequestUri!.AbsolutePath);
|
||||
Assert.Contains("limit=50", handler.Requests[0].RequestUri!.Query);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0, "limit=1")]
|
||||
[InlineData(1, "limit=1")]
|
||||
[InlineData(1000, "limit=1000")]
|
||||
[InlineData(5000, "limit=1000")]
|
||||
public async Task GetEditionsAsync_WhenLimitIsOutsideTheAllowedRange_ShouldClampTheLimit(int limit, string expectedQuery)
|
||||
{
|
||||
// Arrange
|
||||
StubOpenLibraryHttpMessageHandler handler = new();
|
||||
handler.MapPath("/works/OL123W/editions.json", """{"entries":[]}""");
|
||||
OpenLibraryHttpClient sut = CreateSut(handler);
|
||||
|
||||
// Act
|
||||
await sut.GetEditionsAsync("OL123W", limit, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Contains(expectedQuery, handler.Requests[0].RequestUri!.Query);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetEditionsAsync_WhenResponseHasNoEntries_ShouldReturnAnEmptyList()
|
||||
{
|
||||
// Arrange
|
||||
StubOpenLibraryHttpMessageHandler handler = new();
|
||||
handler.MapPath("/works/OL123W/editions.json", """{"entries":[]}""");
|
||||
OpenLibraryHttpClient sut = CreateSut(handler);
|
||||
|
||||
// Act
|
||||
IReadOnlyList<OpenLibraryEditionResponse> result = await sut.GetEditionsAsync("OL123W", 50, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetEditionsAsync_WhenEndpointReturnsNotFound_ShouldReturnAnEmptyList()
|
||||
{
|
||||
// Arrange
|
||||
StubOpenLibraryHttpMessageHandler handler = new();
|
||||
OpenLibraryHttpClient sut = CreateSut(handler);
|
||||
|
||||
// Act
|
||||
IReadOnlyList<OpenLibraryEditionResponse> result = await sut.GetEditionsAsync("OL123W", 50, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SearchAsync_WhenLookupContainsAllCriteria_ShouldBuildTheQueryWithAllParameters()
|
||||
{
|
||||
// Arrange
|
||||
StubOpenLibraryHttpMessageHandler handler = new();
|
||||
handler.MapPath("/search.json", """{"docs":[]}""");
|
||||
OpenLibraryHttpClient sut = CreateSut(handler);
|
||||
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(
|
||||
isbn: "978-0-306-40615-7",
|
||||
title: "The Title",
|
||||
author: "The Author",
|
||||
languageCode: "en");
|
||||
|
||||
// Act
|
||||
IReadOnlyList<OpenLibrarySearchDocumentResponse> result = await sut.SearchAsync(lookup, 5, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result);
|
||||
Assert.Equal("/search.json", handler.Requests[0].RequestUri!.AbsolutePath);
|
||||
string query = handler.Requests[0].RequestUri!.Query;
|
||||
Assert.Contains("isbn=9780306406157", query);
|
||||
Assert.Contains("title=The%20Title", query);
|
||||
Assert.Contains("author=The%20Author", query);
|
||||
Assert.Contains("language=en", query);
|
||||
Assert.Contains("fields=", query);
|
||||
Assert.Contains("limit=5", query);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SearchAsync_WhenLookupOnlyHasATitle_ShouldBuildATitleOnlyQuery()
|
||||
{
|
||||
// Arrange
|
||||
StubOpenLibraryHttpMessageHandler handler = new();
|
||||
handler.MapPath("/search.json", """{"docs":[]}""");
|
||||
OpenLibraryHttpClient sut = CreateSut(handler);
|
||||
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: "/books/title.epub", title: "Dune");
|
||||
|
||||
// Act
|
||||
await sut.SearchAsync(lookup, 5, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
string query = handler.Requests[0].RequestUri!.Query;
|
||||
Assert.Contains("title=Dune", query);
|
||||
Assert.DoesNotContain("isbn=", query);
|
||||
Assert.DoesNotContain("author=", query);
|
||||
Assert.DoesNotContain("language=", query);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0, "limit=1")]
|
||||
[InlineData(100, "limit=100")]
|
||||
[InlineData(1000, "limit=100")]
|
||||
public async Task SearchAsync_WhenLimitIsOutsideTheAllowedRange_ShouldClampTheLimit(int limit, string expectedQuery)
|
||||
{
|
||||
// Arrange
|
||||
StubOpenLibraryHttpMessageHandler handler = new();
|
||||
handler.MapPath("/search.json", """{"docs":[]}""");
|
||||
OpenLibraryHttpClient sut = CreateSut(handler);
|
||||
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: "/books/title.epub", title: "Dune");
|
||||
|
||||
// Act
|
||||
await sut.SearchAsync(lookup, limit, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Contains(expectedQuery, handler.Requests[0].RequestUri!.Query);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SearchAsync_WhenResponseContainsDocuments_ShouldReturnTheDocuments()
|
||||
{
|
||||
// Arrange
|
||||
StubOpenLibraryHttpMessageHandler handler = new();
|
||||
handler.MapPath("/search.json", """{"docs":[{"key":"/works/OL1W","title":"Doc Title"}]}""");
|
||||
OpenLibraryHttpClient sut = CreateSut(handler);
|
||||
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: "/books/title.epub", title: "Dune");
|
||||
|
||||
// Act
|
||||
IReadOnlyList<OpenLibrarySearchDocumentResponse> result = await sut.SearchAsync(lookup, 5, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
OpenLibrarySearchDocumentResponse document = Assert.Single(result);
|
||||
Assert.Equal("Doc Title", document.Title);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SearchAsync_WhenEndpointReturnsNotFound_ShouldReturnAnEmptyList()
|
||||
{
|
||||
// Arrange
|
||||
StubOpenLibraryHttpMessageHandler handler = new();
|
||||
OpenLibraryHttpClient sut = CreateSut(handler);
|
||||
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: "/books/title.epub", title: "Dune");
|
||||
|
||||
// Act
|
||||
IReadOnlyList<OpenLibrarySearchDocumentResponse> result = await sut.SearchAsync(lookup, 5, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetWorkAsync_WhenFirstAttemptFailsWithServerError_ShouldRetryAndSucceed()
|
||||
{
|
||||
// Arrange
|
||||
int attempts = 0;
|
||||
StubOpenLibraryHttpMessageHandler handler = new();
|
||||
handler.AddRoute(
|
||||
request => request.RequestUri!.AbsolutePath == "/works/OL123W.json",
|
||||
_ => attempts++ == 0
|
||||
? new HttpResponseMessage(HttpStatusCode.InternalServerError)
|
||||
: StubOpenLibraryHttpMessageHandler.CreateJsonResponse(HttpStatusCode.OK, """{"key":"/works/OL123W","title":"Work"}"""));
|
||||
OpenLibraryHttpClient sut = CreateSut(handler, _openLibrarySettingsDtoFixture.Create(minimumRequestInterval: TimeSpan.Zero));
|
||||
|
||||
// Act
|
||||
OpenLibraryWorkResponse? result = await sut.GetWorkAsync("OL123W", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("Work", result!.Title);
|
||||
Assert.Equal(2, handler.Requests.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetWorkAsync_WhenFirstAttemptFailsWithTooManyRequests_ShouldRetryAfterTheRetryAfterDelayAndSucceed()
|
||||
{
|
||||
// Arrange
|
||||
int attempts = 0;
|
||||
StubOpenLibraryHttpMessageHandler handler = new();
|
||||
handler.AddRoute(
|
||||
request => request.RequestUri!.AbsolutePath == "/works/OL123W.json",
|
||||
_ =>
|
||||
{
|
||||
if (attempts++ == 0)
|
||||
{
|
||||
HttpResponseMessage tooManyRequests = new(HttpStatusCode.TooManyRequests);
|
||||
tooManyRequests.Headers.RetryAfter = new RetryConditionHeaderValue(TimeSpan.FromMilliseconds(1));
|
||||
return tooManyRequests;
|
||||
}
|
||||
|
||||
return StubOpenLibraryHttpMessageHandler.CreateJsonResponse(HttpStatusCode.OK, """{"key":"/works/OL123W","title":"Work"}""");
|
||||
});
|
||||
OpenLibraryHttpClient sut = CreateSut(handler, _openLibrarySettingsDtoFixture.Create(minimumRequestInterval: TimeSpan.Zero));
|
||||
|
||||
// Act
|
||||
OpenLibraryWorkResponse? result = await sut.GetWorkAsync("OL123W", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("Work", result!.Title);
|
||||
Assert.Equal(2, handler.Requests.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetWorkAsync_WhenEveryAttemptFailsWithServerError_ShouldThrowHttpRequestException()
|
||||
{
|
||||
// Arrange
|
||||
StubOpenLibraryHttpMessageHandler handler = new();
|
||||
handler.AddRoute(
|
||||
request => request.RequestUri!.AbsolutePath == "/works/OL123W.json",
|
||||
_ => new HttpResponseMessage(HttpStatusCode.InternalServerError));
|
||||
OpenLibraryHttpClient sut = CreateSut(handler, _openLibrarySettingsDtoFixture.Create(minimumRequestInterval: TimeSpan.Zero));
|
||||
|
||||
// Act
|
||||
async Task Act()
|
||||
{
|
||||
await sut.GetWorkAsync("OL123W", CancellationToken.None);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<HttpRequestException>(Act);
|
||||
Assert.Equal(3, handler.Requests.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetWorkAsync_WhenEndpointReturnsBadRequest_ShouldThrowImmediately()
|
||||
{
|
||||
// Arrange
|
||||
StubOpenLibraryHttpMessageHandler handler = new();
|
||||
handler.AddRoute(
|
||||
request => request.RequestUri!.AbsolutePath == "/works/OL123W.json",
|
||||
_ => new HttpResponseMessage(HttpStatusCode.BadRequest));
|
||||
OpenLibraryHttpClient sut = CreateSut(handler, _openLibrarySettingsDtoFixture.Create(minimumRequestInterval: TimeSpan.Zero));
|
||||
|
||||
// Act
|
||||
async Task Act()
|
||||
{
|
||||
await sut.GetWorkAsync("OL123W", CancellationToken.None);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<HttpRequestException>(Act);
|
||||
Assert.Single(handler.Requests);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetWorkAsync_WhenRequestsAreCloserThanTheMinimumInterval_ShouldDelayTheSecondRequest()
|
||||
{
|
||||
// Arrange
|
||||
StubOpenLibraryHttpMessageHandler handler = new();
|
||||
handler.MapPath("/works/OL1W.json", """{"key":"/works/OL1W","title":"Work"}""");
|
||||
OpenLibraryHttpClient sut = CreateSut(handler, _openLibrarySettingsDtoFixture.Create(minimumRequestInterval: TimeSpan.FromMilliseconds(300)));
|
||||
|
||||
// Act
|
||||
Stopwatch stopwatch = Stopwatch.StartNew();
|
||||
await sut.GetWorkAsync("OL1W", CancellationToken.None);
|
||||
await sut.GetWorkAsync("OL1W", CancellationToken.None);
|
||||
stopwatch.Stop();
|
||||
|
||||
// Assert
|
||||
Assert.True(stopwatch.ElapsedMilliseconds >= 200, $"Expected the two requests to take at least 200ms, but they took {stopwatch.ElapsedMilliseconds}ms.");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetWorkAsync_WhenCancellationIsRequested_ShouldCancelTheOperation()
|
||||
{
|
||||
// Arrange
|
||||
OpenLibraryHttpClient sut = CreateSut(new StubOpenLibraryHttpMessageHandler());
|
||||
using CancellationTokenSource cancellationTokenSource = new();
|
||||
cancellationTokenSource.Cancel();
|
||||
|
||||
// Act
|
||||
async Task Act()
|
||||
{
|
||||
await sut.GetWorkAsync("OL123W", cancellationTokenSource.Token);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(Act);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates the Open Library HTTP client under test backed by the given handler and settings.
|
||||
/// </summary>
|
||||
/// <param name="handler">The stub HTTP message handler used to serve responses.</param>
|
||||
/// <param name="settings">Optional. The Open Library settings used by the client. When omitted, randomized settings are used.</param>
|
||||
/// <returns>The created <see cref="OpenLibraryHttpClient"/>.</returns>
|
||||
private OpenLibraryHttpClient CreateSut(StubOpenLibraryHttpMessageHandler handler, OpenLibrarySettingsDto? settings = null)
|
||||
{
|
||||
HttpClient httpClient = new(handler);
|
||||
OpenLibrarySettingsProvider settingsProvider = new(null, Guid.NewGuid(), settings ?? _openLibrarySettingsDtoFixture.Create(minimumRequestInterval: TimeSpan.Zero));
|
||||
return new OpenLibraryHttpClient(httpClient, settingsProvider);
|
||||
}
|
||||
}
|
||||
+453
@@ -0,0 +1,453 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
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.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Common;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using Lumina.Plugins.OpenLibrary.Common.Models.Contracts.Responses;
|
||||
using Lumina.Plugins.OpenLibrary.Core.Mapping;
|
||||
using Lumina.Plugins.OpenLibrary.Fixtures.Common.Models.Contracts.Responses;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.OpenLibrary.UnitTests.Core.Mapping;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="OpenLibraryMapper"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class OpenLibraryMapperTests
|
||||
{
|
||||
private readonly BookMetadataLookupDtoFixture _bookMetadataLookupDtoFixture = new();
|
||||
private readonly OpenLibraryEditionResponseFixture _openLibraryEditionResponseFixture = new();
|
||||
private readonly OpenLibraryWorkResponseFixture _openLibraryWorkResponseFixture = new();
|
||||
private readonly OpenLibrarySearchDocumentResponseFixture _openLibrarySearchDocumentResponseFixture = new();
|
||||
private readonly OpenLibraryAuthorResponseFixture _openLibraryAuthorResponseFixture = new();
|
||||
private readonly OpenLibraryRatingsResponseFixture _openLibraryRatingsResponseFixture = new();
|
||||
private readonly OpenLibraryRatingSummaryResponseFixture _openLibraryRatingSummaryResponseFixture = new();
|
||||
private readonly OpenLibraryKeyReferenceResponseFixture _openLibraryKeyReferenceResponseFixture = new();
|
||||
private readonly OpenLibraryWorkAuthorResponseFixture _openLibraryWorkAuthorResponseFixture = new();
|
||||
|
||||
[Theory]
|
||||
[InlineData("978-0-306-40615-7", "9780306406157")]
|
||||
[InlineData("0-306-40615-2", "0306406152")]
|
||||
[InlineData("978 0 306 40615 7", "9780306406157")]
|
||||
[InlineData("9780306406157", "9780306406157")]
|
||||
[InlineData("0-306-40615-X", "030640615X")]
|
||||
[InlineData("0-306-40615-x", "030640615X")]
|
||||
public void NormalizeIsbn_WhenIsbnIsValid_ShouldReturnTheCanonicalForm(string isbn, string expected)
|
||||
{
|
||||
// Act
|
||||
string result = OpenLibraryMapper.NormalizeIsbn(isbn);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(expected, result);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
[InlineData("123")]
|
||||
[InlineData("12345678901")]
|
||||
[InlineData("1234567890123456")]
|
||||
[InlineData("ABCDEFGHIJ")]
|
||||
[InlineData("978030640615A")]
|
||||
public void NormalizeIsbn_WhenIsbnIsInvalid_ShouldThrowArgumentException(string isbn)
|
||||
{
|
||||
// Act
|
||||
Action act = () => OpenLibraryMapper.NormalizeIsbn(isbn);
|
||||
|
||||
// Assert
|
||||
Assert.Throws<ArgumentException>(act);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("/works/OL12345W", "W", "OL12345W")]
|
||||
[InlineData("/books/OL1M", "M", "OL1M")]
|
||||
[InlineData("OL999W", "W", "OL999W")]
|
||||
[InlineData("https://openlibrary.org/works/OL2W", "W", "OL2W")]
|
||||
[InlineData("/works/ol3w", "W", "OL3W")]
|
||||
[InlineData("/works/OL123W/", "W", "OL123W")]
|
||||
public void ExtractOlid_WhenKeyContainsAMatchingOlid_ShouldReturnTheCanonicalOlid(string key, string expectedSuffix, string expected)
|
||||
{
|
||||
// Act
|
||||
string? result = OpenLibraryMapper.ExtractOlid(key, expectedSuffix[0]);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(expected, result);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null, "W")]
|
||||
[InlineData("", "W")]
|
||||
[InlineData(" ", "W")]
|
||||
[InlineData("/works/OL1A", "W")]
|
||||
[InlineData("/works/not-an-olid", "W")]
|
||||
[InlineData("OL1", "W")]
|
||||
[InlineData("/books/OL1M", "W")]
|
||||
public void ExtractOlid_WhenKeyDoesNotContainAMatchingOlid_ShouldReturnNull(string? key, string expectedSuffix)
|
||||
{
|
||||
// Act
|
||||
string? result = OpenLibraryMapper.ExtractOlid(key, expectedSuffix[0]);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("Mass Market Paperback", BookFormat.MassMarketPaperback)]
|
||||
[InlineData("mass market paperback", BookFormat.MassMarketPaperback)]
|
||||
[InlineData("Trade Paperback", BookFormat.TradePaperback)]
|
||||
[InlineData("Paperback", BookFormat.Paperback)]
|
||||
[InlineData("Softcover", BookFormat.Paperback)]
|
||||
[InlineData("Hardcover", BookFormat.Hardcover)]
|
||||
[InlineData("Hard cover", BookFormat.Hardcover)]
|
||||
[InlineData("Hardback", BookFormat.Hardcover)]
|
||||
[InlineData("Clothbound", BookFormat.Hardcover)]
|
||||
[InlineData("eBook", BookFormat.eBook)]
|
||||
[InlineData("E-book", BookFormat.eBook)]
|
||||
[InlineData("Electronic", BookFormat.eBook)]
|
||||
[InlineData("Audiobook", BookFormat.Audiobook)]
|
||||
[InlineData("Audio Book", BookFormat.Audiobook)]
|
||||
[InlineData("Audio CD", BookFormat.Audiobook)]
|
||||
[InlineData("Large Print", BookFormat.LargePrint)]
|
||||
[InlineData("Board Book", BookFormat.BoardBook)]
|
||||
[InlineData("Spiral", BookFormat.SpiralBound)]
|
||||
[InlineData("Library Binding", BookFormat.LibraryBinding)]
|
||||
[InlineData("Leather", BookFormat.LeatherBound)]
|
||||
[InlineData("Pop-up", BookFormat.PopupBook)]
|
||||
[InlineData("Popup", BookFormat.PopupBook)]
|
||||
public void MapFormat_WhenPhysicalFormatIsRecognized_ShouldReturnTheMappedBookFormat(string physicalFormat, BookFormat expected)
|
||||
{
|
||||
// Act
|
||||
BookFormat? result = OpenLibraryMapper.MapFormat(physicalFormat);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(expected, result);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
[InlineData("3D Printed")]
|
||||
[InlineData("Unknown Format")]
|
||||
public void MapFormat_WhenPhysicalFormatIsNotRecognized_ShouldReturnNull(string? physicalFormat)
|
||||
{
|
||||
// Act
|
||||
BookFormat? result = OpenLibraryMapper.MapFormat(physicalFormat);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MapSearchCandidate_WhenCalledWithASearchDocument_ShouldMapTheDocumentFields()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create();
|
||||
OpenLibrarySearchDocumentResponse document = _openLibrarySearchDocumentResponseFixture.Create(
|
||||
key: "/works/OL12345W",
|
||||
title: "Search Title",
|
||||
authorNames: ["Search Author"],
|
||||
firstPublishYear: 2003,
|
||||
publishers: ["Search Publisher"],
|
||||
subjects: ["Science fiction", "Space"],
|
||||
isbns: ["978-0-306-40615-7"],
|
||||
numberOfPagesMedian: 250,
|
||||
ratingsAverage: 4.1m,
|
||||
ratingsCount: 42,
|
||||
lccn: ["79042755"],
|
||||
oclc: ["123456789"]);
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = OpenLibraryMapper.MapSearchCandidate(lookup, document);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Search Title", result.Title);
|
||||
Assert.Equal(2003, result.ReleaseInfo!.OriginalReleaseYear);
|
||||
Assert.Equal("Search Publisher", result.Publisher);
|
||||
Assert.Equal(250, result.PageCount);
|
||||
Assert.Contains(result.Genres!, genre => genre.Name == "Science fiction");
|
||||
Assert.DoesNotContain(result.Genres!, genre => genre.Name == "Space");
|
||||
Assert.Contains(result.Tags!, tag => tag.Name == "Science fiction");
|
||||
Assert.Contains(result.Tags!, tag => tag.Name == "Space");
|
||||
Assert.Null(result.ReleaseInfo.ReleaseCountry);
|
||||
BookRatingDto rating = Assert.Single(result.Ratings!);
|
||||
Assert.Equal(4.1m, rating.Value);
|
||||
Assert.Equal(5m, rating.MaxValue);
|
||||
Assert.Equal(BookRatingSource.OpenLibrary, rating.Source);
|
||||
Assert.Equal(42, rating.VoteCount);
|
||||
Assert.Equal("79042755", result.LCCN);
|
||||
Assert.Equal("123456789", result.OCLCNumber);
|
||||
Assert.Equal("OL12345W", result.OpenLibraryId);
|
||||
Assert.Contains(result.Isbns!, isbn => isbn.Value == "9780306406157" && isbn.Format == IsbnFormat.Isbn13);
|
||||
Assert.Contains(result.Contributors!, contributor => contributor.Name!.DisplayName == "Search Author" && contributor.Role == MediaContributorRole.Author);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MapDetailed_WhenEditionAndWorkAreProvided_ShouldMapAllBookRequestFields()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(isbn: "978-0-306-40615-7");
|
||||
JsonElement identifiers = JsonDocument.Parse("""{"amazon":["B000001"],"goodreads":["12345"],"google":["gid"],"librarything":["ltid"],"barnesandnoble":["bnid"],"apple":["apid"]}""").RootElement;
|
||||
OpenLibraryEditionResponse edition = _openLibraryEditionResponseFixture.Create(
|
||||
key: "/books/OL100M",
|
||||
title: "Edition Title",
|
||||
publishDate: "2010-05-01",
|
||||
publishers: ["Publisher Co"],
|
||||
publishCountry: "nyu",
|
||||
numberOfPages: 320,
|
||||
physicalFormat: "Hardcover",
|
||||
editionName: "First Edition",
|
||||
series: ["The Series"],
|
||||
volume: "Vol. 3",
|
||||
isbn10: ["0306406152"],
|
||||
isbn13: ["9780306406157"],
|
||||
lccn: ["79042755"],
|
||||
oclcNumbers: ["1234567"],
|
||||
identifiers: identifiers,
|
||||
languages: [_openLibraryKeyReferenceResponseFixture.Create(key: "/languages/eng")],
|
||||
works: [_openLibraryKeyReferenceResponseFixture.Create(key: "/works/OL200W")],
|
||||
contributions: ["John Smith (Illustrator)"]);
|
||||
OpenLibraryWorkResponse work = _openLibraryWorkResponseFixture.Create(
|
||||
key: "/works/OL200W",
|
||||
title: "Work Title",
|
||||
originalTitle: "Original Title",
|
||||
description: JsonDocument.Parse("""{"value":"A work description"}""").RootElement,
|
||||
firstPublishDate: "1987-06-01",
|
||||
subjects: ["Science fiction", "History", "Space"],
|
||||
genres: ["Fantasy"],
|
||||
authors: [_openLibraryWorkAuthorResponseFixture.Create(author: _openLibraryKeyReferenceResponseFixture.Create(key: "/authors/OL1A"))],
|
||||
originalLanguages: [_openLibraryKeyReferenceResponseFixture.Create(key: "/languages/fre")]);
|
||||
OpenLibraryAuthorResponse author = _openLibraryAuthorResponseFixture.Create(key: "/authors/OL1A", name: "Test Author", personalName: "Test Personal Name");
|
||||
OpenLibraryRatingsResponse ratings = _openLibraryRatingsResponseFixture.Create(_openLibraryRatingSummaryResponseFixture.Create(average: 4.2m, count: 100));
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = OpenLibraryMapper.MapDetailed(lookup, edition, work, [author], ratings);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Edition Title", result.Title);
|
||||
Assert.Equal("Original Title", result.OriginalTitle);
|
||||
Assert.Equal("A work description", result.Description);
|
||||
Assert.Equal(new DateOnly(1987, 6, 1), result.ReleaseInfo!.OriginalReleaseDate);
|
||||
Assert.Equal(1987, result.ReleaseInfo.OriginalReleaseYear);
|
||||
Assert.Equal(new DateOnly(2010, 5, 1), result.ReleaseInfo.ReReleaseDate);
|
||||
Assert.Equal(2010, result.ReleaseInfo.ReReleaseYear);
|
||||
Assert.Equal(ReleaseCountry.US, result.ReleaseInfo.ReleaseCountry);
|
||||
Assert.Equal("First Edition", result.ReleaseInfo.ReleaseVersion);
|
||||
GenreDto genre = Assert.Single(result.Genres!);
|
||||
Assert.Equal("Fantasy", genre.Name);
|
||||
Assert.Equal(3, result.Tags!.Count);
|
||||
Assert.Contains(result.Tags, tag => tag.Name == "Science fiction");
|
||||
Assert.Contains(result.Tags, tag => tag.Name == "History");
|
||||
Assert.Contains(result.Tags, tag => tag.Name == "Space");
|
||||
Assert.Equal("en", result.Language!.LanguageCode);
|
||||
Assert.False(string.IsNullOrWhiteSpace(result.Language.LanguageName));
|
||||
Assert.Equal("fre", result.OriginalLanguage!.LanguageCode);
|
||||
Assert.Equal("fre", result.OriginalLanguage.LanguageName);
|
||||
Assert.Null(result.OriginalLanguage.NativeName);
|
||||
Assert.Equal("Publisher Co", result.Publisher);
|
||||
Assert.Equal(320, result.PageCount);
|
||||
Assert.Equal(BookFormat.Hardcover, result.Format);
|
||||
Assert.Equal("First Edition", result.Edition);
|
||||
Assert.Equal(3, result.VolumeNumber);
|
||||
Assert.Equal("The Series", result.Series!.Title);
|
||||
Assert.Equal("B000001", result.ASIN);
|
||||
Assert.Equal("12345", result.GoodreadsId);
|
||||
Assert.Equal("79042755", result.LCCN);
|
||||
Assert.Equal("1234567", result.OCLCNumber);
|
||||
Assert.Equal("OL100M", result.OpenLibraryId);
|
||||
Assert.Equal("ltid", result.LibraryThingId);
|
||||
Assert.Equal("gid", result.GoogleBooksId);
|
||||
Assert.Equal("bnid", result.BarnesAndNobleId);
|
||||
Assert.Equal("apid", result.AppleBooksId);
|
||||
Assert.Contains(result.Isbns!, isbn => isbn.Value == "9780306406157" && isbn.Format == IsbnFormat.Isbn13);
|
||||
Assert.Contains(result.Isbns!, isbn => isbn.Value == "0306406152" && isbn.Format == IsbnFormat.Isbn10);
|
||||
Assert.Contains(result.Contributors!, contributor => contributor.Name!.DisplayName == "Test Author" && contributor.Name.LegalName == "Test Personal Name" && contributor.Role == MediaContributorRole.Author);
|
||||
Assert.Contains(result.Contributors!, contributor => contributor.Name!.DisplayName == "John Smith" && contributor.Role == MediaContributorRole.Illustrator);
|
||||
BookRatingDto mappedRating = Assert.Single(result.Ratings!);
|
||||
Assert.Equal(4.2m, mappedRating.Value);
|
||||
Assert.Equal(5m, mappedRating.MaxValue);
|
||||
Assert.Equal(BookRatingSource.OpenLibrary, mappedRating.Source);
|
||||
Assert.Equal(100, mappedRating.VoteCount);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("nyu", ReleaseCountry.US)] // A MARC 21 state code that stands for the United States.
|
||||
[InlineData("xxu", ReleaseCountry.US)] // The MARC 21 country code of the United States.
|
||||
[InlineData("enk", ReleaseCountry.GB)] // The MARC 21 country code of England.
|
||||
[InlineData("ENK", ReleaseCountry.GB)] // The code differs only in casing.
|
||||
[InlineData("gw ", ReleaseCountry.DE)] // A two letter MARC 21 code, padded with a trailing space.
|
||||
[InlineData("fr", ReleaseCountry.FR)] // A two letter MARC 21 code without padding.
|
||||
[InlineData("abc", ReleaseCountry.CA)] // A MARC 21 province code that stands for Canada.
|
||||
[InlineData("aca", ReleaseCountry.AU)] // A MARC 21 territory code that stands for Australia.
|
||||
[InlineData("uk", ReleaseCountry.GB)] // A discontinued MARC 21 code that still appears in catalogued records.
|
||||
[InlineData("cs", ReleaseCountry.CZ)] // A discontinued MARC 21 code, mapped to the country that succeeded it.
|
||||
[InlineData("vp", null)] // A MARC 21 code that stands for various places, with no equivalent release country.
|
||||
[InlineData("zzz", null)] // An unknown MARC 21 code.
|
||||
[InlineData("", null)] // An empty MARC 21 code.
|
||||
public void MapDetailed_WhenEditionHasPublishCountry_ShouldMapTheMarcCountryCode(string? publishCountry, ReleaseCountry? expected)
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create();
|
||||
OpenLibraryEditionResponse edition = _openLibraryEditionResponseFixture.Create(publishCountry: publishCountry);
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = OpenLibraryMapper.MapDetailed(lookup, edition, null, [], null);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(expected, result.ReleaseInfo!.ReleaseCountry);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MapDetailed_WhenWorkHasNoExplicitGenres_ShouldDeriveGenresFromTheGenreLikeSubjects()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create();
|
||||
OpenLibraryWorkResponse work = _openLibraryWorkResponseFixture.Create(subjects: ["Science fiction", "History", "Space"]);
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = OpenLibraryMapper.MapDetailed(lookup, null, work, [], null);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, result.Genres!.Count);
|
||||
Assert.Contains(result.Genres, genre => genre.Name == "Science fiction");
|
||||
Assert.Contains(result.Genres, genre => genre.Name == "History");
|
||||
Assert.DoesNotContain(result.Genres, genre => genre.Name == "Space");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MapDetailed_WhenWorkHasNoFirstPublishDate_ShouldUseTheFallbackFirstPublishYear()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create();
|
||||
OpenLibrarySearchDocumentResponse fallback = _openLibrarySearchDocumentResponseFixture.Create(firstPublishYear: 2001);
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = OpenLibraryMapper.MapDetailed(lookup, null, null, [], null, fallback);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2001, result.ReleaseInfo!.OriginalReleaseYear);
|
||||
Assert.Null(result.ReleaseInfo.OriginalReleaseDate);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MapDetailed_WhenLanguageKeyIsUnknown_ShouldUseTheRawCodeAsTheLanguage()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create();
|
||||
OpenLibraryEditionResponse edition = _openLibraryEditionResponseFixture.Create(languages: [_openLibraryKeyReferenceResponseFixture.Create(key: "/languages/xxq")]);
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = OpenLibraryMapper.MapDetailed(lookup, edition, null, [], null);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result.Language);
|
||||
Assert.Equal("xxq", result.Language!.LanguageCode);
|
||||
Assert.Equal("xxq", result.Language.LanguageName);
|
||||
Assert.Null(result.Language.NativeName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MapDetailed_WhenDescriptionIsAPlainString_ShouldReadItDirectly()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create();
|
||||
OpenLibraryWorkResponse work = _openLibraryWorkResponseFixture.Create(description: JsonDocument.Parse("\"A plain description\"").RootElement);
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = OpenLibraryMapper.MapDetailed(lookup, null, work, [], null);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("A plain description", result.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MapDetailed_WhenNoExternalDataIsAvailable_ShouldMapTheLookupItselfAndLeaveTheRestNull()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(isbn: "978-0-306-40615-7");
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = OpenLibraryMapper.MapDetailed(lookup, null, null, [], null, null);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Null(result.Title);
|
||||
Assert.Null(result.Format);
|
||||
Assert.Null(result.Edition);
|
||||
Assert.Null(result.OpenLibraryId);
|
||||
Assert.Contains(result.Isbns!, isbn => isbn.Value == "9780306406157");
|
||||
Assert.Empty(result.Ratings!);
|
||||
Assert.Empty(result.Contributors!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MapDetailed_WhenRatingsAreOnlyAvailableInTheFallbackDocument_ShouldUseTheFallbackRatings()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create();
|
||||
OpenLibrarySearchDocumentResponse fallback = _openLibrarySearchDocumentResponseFixture.Create(ratingsAverage: 3.5m, ratingsCount: 10);
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = OpenLibraryMapper.MapDetailed(lookup, null, null, [], null, fallback);
|
||||
|
||||
// Assert
|
||||
BookRatingDto rating = Assert.Single(result.Ratings!);
|
||||
Assert.Equal(3.5m, rating.Value);
|
||||
Assert.Equal(10, rating.VoteCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MapDetailed_WhenVolumeIsContainedInTheEditionSeries_ShouldParseTheVolumeNumber()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create();
|
||||
OpenLibraryEditionResponse edition = _openLibraryEditionResponseFixture.Create(series: ["Book 2 of the trilogy"]);
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = OpenLibraryMapper.MapDetailed(lookup, edition, null, [], null);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, result.VolumeNumber);
|
||||
Assert.Equal("Book 2 of the trilogy", result.Series!.Title);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MapDetailed_WhenExternalIdsComeFromSourceRecordsAndFallback_ShouldMapThem()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create();
|
||||
OpenLibraryEditionResponse edition = _openLibraryEditionResponseFixture.Create(
|
||||
sourceRecords: ["amazon:B000002", "google:gid2"],
|
||||
oclcNumbers: ["999999"],
|
||||
isbn13: ["9780306406157"]);
|
||||
OpenLibrarySearchDocumentResponse fallback = _openLibrarySearchDocumentResponseFixture.Create(
|
||||
amazonIds: ["B000003"],
|
||||
goodreadsIds: ["777"],
|
||||
googleIds: ["gid3"],
|
||||
libraryThingIds: ["lt3"],
|
||||
lccn: ["79042756"],
|
||||
oclc: ["888888"]);
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = OpenLibraryMapper.MapDetailed(lookup, edition, null, [], null, fallback);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("B000002", result.ASIN);
|
||||
Assert.Equal("777", result.GoodreadsId);
|
||||
Assert.Equal("gid2", result.GoogleBooksId);
|
||||
Assert.Equal("lt3", result.LibraryThingId);
|
||||
Assert.Equal("79042756", result.LCCN);
|
||||
Assert.Equal("999999", result.OCLCNumber);
|
||||
}
|
||||
}
|
||||
+446
@@ -0,0 +1,446 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
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.MediaLibrary;
|
||||
using Lumina.Plugins.OpenLibrary.Common.Models.DTO.Settings;
|
||||
using Lumina.Plugins.OpenLibrary.Core;
|
||||
using Lumina.Plugins.OpenLibrary.Core.Api;
|
||||
using Lumina.Plugins.OpenLibrary.Core.Settings;
|
||||
using Lumina.Plugins.OpenLibrary.Fixtures.Common.Models.DTO.Settings;
|
||||
using Lumina.Plugins.OpenLibrary.Fixtures.Common.Setup;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.OpenLibrary.UnitTests.Core;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="OpenLibraryBookMetadataProvider"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class OpenLibraryBookMetadataProviderTests
|
||||
{
|
||||
private readonly OpenLibrarySettingsDtoFixture _openLibrarySettingsDtoFixture = new();
|
||||
private readonly BookMetadataLookupDtoFixture _bookMetadataLookupDtoFixture = new();
|
||||
|
||||
private const string EDITION_JSON = """{"key":"/books/OL100M","title":"Edition Title","publish_date":"2010-05-01","number_of_pages":320,"physical_format":"Hardcover","edition_name":"First Edition","series":["The Series"],"volume":"Vol. 3","publishers":["Publisher Co"],"isbn_13":["9780306406157"],"languages":[{"key":"/languages/eng"}],"works":[{"key":"/works/OL200W"}]}""";
|
||||
private const string WORK_JSON = """{"key":"/works/OL200W","title":"Work Title","first_publish_date":"2001-01-01","description":{"value":"A work description"},"subjects":["Science fiction"],"authors":[{"author":{"key":"/authors/OL1A"}}]}""";
|
||||
private const string AUTHOR_JSON = """{"key":"/authors/OL1A","name":"Test Author"}""";
|
||||
private const string RATINGS_JSON = """{"summary":{"average":4.2,"count":100}}""";
|
||||
private const string EDITIONS_JSON = """{"entries":[{"key":"/books/OL100M","title":"Edition Title","languages":[{"key":"/languages/eng"}]}]}""";
|
||||
|
||||
[Fact]
|
||||
public void Name_WhenCalled_ShouldReturnTheProviderDisplayName()
|
||||
{
|
||||
// Arrange
|
||||
OpenLibraryBookMetadataProvider sut = CreateProvider(new StubOpenLibraryHttpMessageHandler());
|
||||
|
||||
// Act
|
||||
string result = sut.Name;
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Open Library", result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SupportedLibraryTypes_WhenCalled_ShouldReturnBook()
|
||||
{
|
||||
// Arrange
|
||||
OpenLibraryBookMetadataProvider sut = CreateProvider(new StubOpenLibraryHttpMessageHandler());
|
||||
|
||||
// Act
|
||||
IReadOnlyList<LibraryType> result = sut.SupportedLibraryTypes;
|
||||
|
||||
// Assert
|
||||
Assert.Single(result);
|
||||
Assert.Equal(LibraryType.Book, result[0]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RequiresWebAccess_WhenCalled_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
OpenLibraryBookMetadataProvider sut = CreateProvider(new StubOpenLibraryHttpMessageHandler());
|
||||
|
||||
// Act
|
||||
bool result = sut.RequiresWebAccess;
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetSearchResultsAsync_WhenLookupHasAnIsbn_ShouldResolveTheExactEditionWithoutSearching()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(
|
||||
isbn: "978-0-306-40615-7",
|
||||
openLibraryId: null,
|
||||
title: null,
|
||||
author: null,
|
||||
languageCode: null);
|
||||
StubOpenLibraryHttpMessageHandler handler = new();
|
||||
handler.MapPath("/isbn/9780306406157.json", EDITION_JSON);
|
||||
handler.MapPath("/works/OL200W.json", WORK_JSON);
|
||||
handler.MapPath("/authors/OL1A.json", AUTHOR_JSON);
|
||||
handler.MapPath("/works/OL200W/ratings.json", RATINGS_JSON);
|
||||
OpenLibraryBookMetadataProvider sut = CreateProvider(handler);
|
||||
|
||||
// Act
|
||||
IReadOnlyList<BookMetadataDto> result = await sut.GetSearchResultsAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
BookMetadataDto metadata = Assert.IsType<BookMetadataDto>(Assert.Single(result));
|
||||
Assert.Equal("Edition Title", metadata.Title);
|
||||
Assert.Equal("Publisher Co", metadata.Publisher);
|
||||
Assert.Equal(320, metadata.PageCount);
|
||||
Assert.Equal(BookFormat.Hardcover, metadata.Format);
|
||||
Assert.Equal("First Edition", metadata.Edition);
|
||||
Assert.Equal(3, metadata.VolumeNumber);
|
||||
Assert.Equal("The Series", metadata.Series!.Title);
|
||||
Assert.Equal("OL100M", metadata.OpenLibraryId);
|
||||
Assert.Contains(metadata.Isbns!, isbn => isbn.Value == "9780306406157");
|
||||
Assert.DoesNotContain(handler.Requests, request => request.RequestUri!.AbsolutePath == "/search.json");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetSearchResultsAsync_WhenLookupHasAnIsbnButNoMatchExists_ShouldReturnAnEmptyList()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(
|
||||
isbn: "978-0-306-40615-7",
|
||||
openLibraryId: null,
|
||||
title: null,
|
||||
author: null,
|
||||
languageCode: null);
|
||||
OpenLibraryBookMetadataProvider sut = CreateProvider(new StubOpenLibraryHttpMessageHandler());
|
||||
|
||||
// Act
|
||||
IReadOnlyList<BookMetadataDto> result = await sut.GetSearchResultsAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetSearchResultsAsync_WhenLookupHasAWorkOpenLibraryId_ShouldResolveTheWorkAndItsBestEdition()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(
|
||||
isbn: null,
|
||||
openLibraryId: "OL200W",
|
||||
title: null,
|
||||
author: null,
|
||||
languageCode: null);
|
||||
StubOpenLibraryHttpMessageHandler handler = new();
|
||||
handler.MapPath("/works/OL200W.json", WORK_JSON);
|
||||
handler.MapPath("/works/OL200W/editions.json", EDITIONS_JSON);
|
||||
handler.MapPath("/authors/OL1A.json", AUTHOR_JSON);
|
||||
handler.MapPath("/works/OL200W/ratings.json", RATINGS_JSON);
|
||||
OpenLibraryBookMetadataProvider sut = CreateProvider(handler);
|
||||
|
||||
// Act
|
||||
IReadOnlyList<BookMetadataDto> result = await sut.GetSearchResultsAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
BookMetadataDto metadata = Assert.IsType<BookMetadataDto>(Assert.Single(result));
|
||||
Assert.Equal("Edition Title", metadata.Title);
|
||||
Assert.Equal("OL100M", metadata.OpenLibraryId);
|
||||
Assert.Contains(handler.Requests, request => request.RequestUri!.AbsolutePath == "/works/OL200W/editions.json");
|
||||
Assert.Contains(handler.Requests, request => request.RequestUri!.AbsolutePath == "/works/OL200W/ratings.json");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetSearchResultsAsync_WhenLookupHasOnlyATitle_ShouldSearchAndMapTheSearchCandidates()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: "/books/title.epub", title: "Search Title");
|
||||
StubOpenLibraryHttpMessageHandler handler = new();
|
||||
handler.MapPath("/search.json", """{"docs":[{"key":"/works/OL1W","title":"Search Title","author_name":["Search Author"],"first_publish_year":2001,"publisher":["Search Publisher"],"subject":["Science fiction"],"isbn":["9780306406157"],"number_of_pages_median":250},{"key":"/works/OL999W"}]}""");
|
||||
OpenLibraryBookMetadataProvider sut = CreateProvider(handler);
|
||||
|
||||
// Act
|
||||
IReadOnlyList<BookMetadataDto> result = await sut.GetSearchResultsAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
BookMetadataDto metadata = Assert.IsType<BookMetadataDto>(Assert.Single(result));
|
||||
Assert.Equal("Search Title", metadata.Title);
|
||||
Assert.Equal(2001, metadata.ReleaseInfo!.OriginalReleaseYear);
|
||||
Assert.Equal("Search Publisher", metadata.Publisher);
|
||||
Assert.Equal(250, metadata.PageCount);
|
||||
Assert.Contains(handler.Requests, request => request.RequestUri!.AbsolutePath == "/search.json");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetSearchResultsAsync_WhenSearchReturnsNoResults_ShouldReturnAnEmptyList()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: "/books/title.epub", title: "Search Title");
|
||||
StubOpenLibraryHttpMessageHandler handler = new();
|
||||
handler.MapPath("/search.json", """{"docs":[]}""");
|
||||
OpenLibraryBookMetadataProvider sut = CreateProvider(handler);
|
||||
|
||||
// Act
|
||||
IReadOnlyList<BookMetadataDto> result = await sut.GetSearchResultsAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetSearchResultsAsync_WhenLookupIsNull_ShouldThrowArgumentNullException()
|
||||
{
|
||||
// Arrange
|
||||
OpenLibraryBookMetadataProvider sut = CreateProvider(new StubOpenLibraryHttpMessageHandler());
|
||||
|
||||
// Act
|
||||
async Task Act()
|
||||
{
|
||||
await sut.GetSearchResultsAsync(null!, CancellationToken.None);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<ArgumentNullException>(Act);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetSearchResultsAsync_WhenLookupHasAnEmptyLibraryId_ShouldThrowArgumentException()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(libraryId: Guid.Empty);
|
||||
OpenLibraryBookMetadataProvider sut = CreateProvider(new StubOpenLibraryHttpMessageHandler());
|
||||
|
||||
// Act
|
||||
async Task Act()
|
||||
{
|
||||
await sut.GetSearchResultsAsync(lookup, CancellationToken.None);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<ArgumentException>(Act);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetSearchResultsAsync_WhenLookupHasNoPath_ShouldThrowArgumentNullException()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(includePath: false, isbn: "978-0-306-40615-7");
|
||||
OpenLibraryBookMetadataProvider sut = CreateProvider(new StubOpenLibraryHttpMessageHandler());
|
||||
|
||||
// Act
|
||||
async Task Act()
|
||||
{
|
||||
await sut.GetSearchResultsAsync(lookup, CancellationToken.None);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<ArgumentNullException>(Act);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetSearchResultsAsync_WhenLookupPathIsWhiteSpace_ShouldThrowArgumentException()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: " ", isbn: "978-0-306-40615-7");
|
||||
OpenLibraryBookMetadataProvider sut = CreateProvider(new StubOpenLibraryHttpMessageHandler());
|
||||
|
||||
// Act
|
||||
async Task Act()
|
||||
{
|
||||
await sut.GetSearchResultsAsync(lookup, CancellationToken.None);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<ArgumentException>(Act);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetSearchResultsAsync_WhenLookupHasNoSearchCriteria_ShouldThrowArgumentException()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: "/books/title.epub", isbn: null, openLibraryId: null, title: null, author: null, languageCode: null);
|
||||
OpenLibraryBookMetadataProvider sut = CreateProvider(new StubOpenLibraryHttpMessageHandler());
|
||||
|
||||
// Act
|
||||
async Task Act()
|
||||
{
|
||||
await sut.GetSearchResultsAsync(lookup, CancellationToken.None);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<ArgumentException>(Act);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenAnExactMatchExists_ShouldReturnTheMappedMetadata()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(
|
||||
isbn: "978-0-306-40615-7",
|
||||
openLibraryId: null,
|
||||
title: null,
|
||||
author: null,
|
||||
languageCode: null);
|
||||
StubOpenLibraryHttpMessageHandler handler = new();
|
||||
handler.MapPath("/isbn/9780306406157.json", EDITION_JSON);
|
||||
handler.MapPath("/works/OL200W.json", WORK_JSON);
|
||||
handler.MapPath("/authors/OL1A.json", AUTHOR_JSON);
|
||||
handler.MapPath("/works/OL200W/ratings.json", RATINGS_JSON);
|
||||
OpenLibraryBookMetadataProvider sut = CreateProvider(handler);
|
||||
|
||||
// Act
|
||||
BookMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("Edition Title", result!.Title);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenNoMatchExists_ShouldReturnNull()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(
|
||||
isbn: "978-0-306-40615-7",
|
||||
openLibraryId: null,
|
||||
title: null,
|
||||
author: null,
|
||||
languageCode: null);
|
||||
OpenLibraryBookMetadataProvider sut = CreateProvider(new StubOpenLibraryHttpMessageHandler());
|
||||
|
||||
// Act
|
||||
BookMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetBookAsync_WhenLookupHasAnEditionOpenLibraryId_ShouldResolveTheEditionWorkAuthorsAndRatings()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(
|
||||
isbn: null,
|
||||
openLibraryId: "OL100M",
|
||||
title: null,
|
||||
author: null,
|
||||
languageCode: null);
|
||||
StubOpenLibraryHttpMessageHandler handler = new();
|
||||
handler.MapPath("/books/OL100M.json", EDITION_JSON);
|
||||
handler.MapPath("/works/OL200W.json", WORK_JSON);
|
||||
handler.MapPath("/authors/OL1A.json", AUTHOR_JSON);
|
||||
handler.MapPath("/works/OL200W/ratings.json", RATINGS_JSON);
|
||||
OpenLibraryBookMetadataProvider sut = CreateProvider(handler);
|
||||
|
||||
// Act
|
||||
BookMetadataDto? result = await sut.GetBookAsync(lookup);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("Edition Title", result.Title);
|
||||
Assert.Equal("A work description", result.Description);
|
||||
Assert.Equal("OL100M", result.OpenLibraryId);
|
||||
Assert.Equal(BookFormat.Hardcover, result.Format);
|
||||
Assert.Equal(3, result.VolumeNumber);
|
||||
Assert.Contains(result.Contributors!, contributor => contributor.Name!.DisplayName == "Test Author");
|
||||
Assert.Contains(result.Ratings!, rating => rating.Value == 4.2m);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetBookAsync_WhenLookupHasAWorkOpenLibraryIdAndNoMatchingEditions_ShouldReturnABookFromTheWorkDataOnly()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(
|
||||
isbn: null,
|
||||
openLibraryId: "OL200W",
|
||||
title: null,
|
||||
author: null,
|
||||
languageCode: null);
|
||||
StubOpenLibraryHttpMessageHandler handler = new();
|
||||
handler.MapPath("/works/OL200W.json", WORK_JSON);
|
||||
handler.MapPath("/works/OL200W/editions.json", """{"entries":[]}""");
|
||||
handler.MapPath("/authors/OL1A.json", AUTHOR_JSON);
|
||||
handler.MapPath("/works/OL200W/ratings.json", RATINGS_JSON);
|
||||
OpenLibraryBookMetadataProvider sut = CreateProvider(handler);
|
||||
|
||||
// Act
|
||||
BookMetadataDto? result = await sut.GetBookAsync(lookup);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("Work Title", result.Title);
|
||||
Assert.Equal("OL200W", result.OpenLibraryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetBookAsync_WhenSearchResultHasOnlyAnEditionKey_ShouldResolveTheEditionByItsFirstEditionKey()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: "/books/title.epub", title: "Search Title");
|
||||
StubOpenLibraryHttpMessageHandler handler = new();
|
||||
handler.MapPath("/search.json", """{"docs":[{"key":"/books/OL500M","edition_key":["OL600M"]}]}""");
|
||||
handler.MapPath("/books/OL600M.json", """{"key":"/books/OL600M","title":"Fallback Edition"}""");
|
||||
OpenLibraryBookMetadataProvider sut = CreateProvider(handler);
|
||||
|
||||
// Act
|
||||
BookMetadataDto? result = await sut.GetBookAsync(lookup);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("Fallback Edition", result.Title);
|
||||
Assert.Equal("OL600M", result.OpenLibraryId);
|
||||
Assert.Contains(handler.Requests, request => request.RequestUri!.AbsolutePath == "/books/OL600M.json");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetBookAsync_WhenSearchReturnsNoResults_ShouldReturnNull()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: "/books/title.epub", title: "Search Title");
|
||||
StubOpenLibraryHttpMessageHandler handler = new();
|
||||
handler.MapPath("/search.json", """{"docs":[]}""");
|
||||
OpenLibraryBookMetadataProvider sut = CreateProvider(handler);
|
||||
|
||||
// Act
|
||||
BookMetadataDto? result = await sut.GetBookAsync(lookup);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetBookAsync_WhenOpenLibraryIdHasAnUnknownSuffix_ShouldThrowArgumentException()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(
|
||||
isbn: null,
|
||||
openLibraryId: "OL123X",
|
||||
title: null,
|
||||
author: null,
|
||||
languageCode: null);
|
||||
OpenLibraryBookMetadataProvider sut = CreateProvider(new StubOpenLibraryHttpMessageHandler());
|
||||
|
||||
// Act
|
||||
async Task Act()
|
||||
{
|
||||
await sut.GetBookAsync(lookup);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<ArgumentException>(Act);
|
||||
}
|
||||
|
||||
private OpenLibraryBookMetadataProvider CreateProvider(StubOpenLibraryHttpMessageHandler handler, OpenLibrarySettingsDto? settings = null)
|
||||
{
|
||||
OpenLibrarySettingsDto runtimeSettings = settings ?? _openLibrarySettingsDtoFixture.Create(minimumRequestInterval: TimeSpan.Zero);
|
||||
OpenLibrarySettingsProvider settingsProvider = new(null, Guid.NewGuid(), runtimeSettings);
|
||||
OpenLibraryHttpClient openLibraryHttpClient = new(new HttpClient(handler), settingsProvider);
|
||||
return new OpenLibraryBookMetadataProvider(openLibraryHttpClient, settingsProvider);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Plugins;
|
||||
using Lumina.Plugins.Contracts.Common.Models.DTO.Settings;
|
||||
using Lumina.Plugins.Contracts.Core.Metadata;
|
||||
using Lumina.Plugins.OpenLibrary.Core;
|
||||
using Lumina.Plugins.OpenLibrary.Core.Api;
|
||||
using Lumina.Plugins.OpenLibrary.Core.Settings;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.OpenLibrary.UnitTests.Core;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="OpenLibraryPlugin"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class OpenLibraryPluginTests
|
||||
{
|
||||
private readonly OpenLibraryPlugin _sut = new();
|
||||
|
||||
[Fact]
|
||||
public void Id_WhenCalled_ShouldReturnStablePluginIdentifier()
|
||||
{
|
||||
// Act
|
||||
Guid result = _sut.Id;
|
||||
|
||||
// Assert
|
||||
Assert.Equal(OpenLibraryPlugin.s_pluginId, result);
|
||||
Assert.Equal(new Guid("08b17802-7f9c-4c4b-9d7f-b507bbed3e58"), result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Name_WhenCalled_ShouldReturnPluginDisplayName()
|
||||
{
|
||||
// Act
|
||||
string result = _sut.Name;
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Open Library Metadata", result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Author_WhenCalled_ShouldReturnPluginAuthor()
|
||||
{
|
||||
// Act
|
||||
string result = _sut.Author;
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Lumina", result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Version_WhenCalled_ShouldReturnPluginVersion()
|
||||
{
|
||||
// Act
|
||||
Version result = _sut.Version;
|
||||
|
||||
// Assert
|
||||
Assert.Equal(new Version(1, 0, 0), result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Description_WhenCalled_ShouldReturnPluginDescription()
|
||||
{
|
||||
// Act
|
||||
string result = _sut.Description;
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Retrieves book and edition metadata from Open Library.", result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetSettingsSchema_WhenCalled_ShouldReturnAllDeclaredSettingsWithTheirDefaults()
|
||||
{
|
||||
// Act
|
||||
IReadOnlyList<PluginSettingDescriptorDto> result = _sut.GetSettingsSchema();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(4, result.Count);
|
||||
|
||||
PluginSettingDescriptorDto contactEmail = result[0];
|
||||
Assert.Equal(OpenLibrarySettingsKeys.CONTACT_EMAIL, contactEmail.Key);
|
||||
Assert.Equal("Contact Email", contactEmail.Label);
|
||||
Assert.Equal(PluginSettingType.Text, contactEmail.Type);
|
||||
Assert.Null(contactEmail.DefaultValue);
|
||||
|
||||
PluginSettingDescriptorDto searchResultLimit = result[1];
|
||||
Assert.Equal(OpenLibrarySettingsKeys.SEARCH_RESULT_LIMIT, searchResultLimit.Key);
|
||||
Assert.Equal("Search Result Limit", searchResultLimit.Label);
|
||||
Assert.Equal(PluginSettingType.Number, searchResultLimit.Type);
|
||||
Assert.Equal("10", searchResultLimit.DefaultValue);
|
||||
|
||||
PluginSettingDescriptorDto workEditionLimit = result[2];
|
||||
Assert.Equal(OpenLibrarySettingsKeys.WORK_EDITION_LIMIT, workEditionLimit.Key);
|
||||
Assert.Equal("Work Edition Limit", workEditionLimit.Label);
|
||||
Assert.Equal(PluginSettingType.Number, workEditionLimit.Type);
|
||||
Assert.Equal("50", workEditionLimit.DefaultValue);
|
||||
|
||||
PluginSettingDescriptorDto minimumRequestInterval = result[3];
|
||||
Assert.Equal(OpenLibrarySettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS, minimumRequestInterval.Key);
|
||||
Assert.Equal("Minimum Request Interval (seconds)", minimumRequestInterval.Label);
|
||||
Assert.Equal(PluginSettingType.Number, minimumRequestInterval.Type);
|
||||
Assert.Equal("1.1", minimumRequestInterval.DefaultValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetSettingsSchema_WhenCalledRepeatedly_ShouldReturnAnIndependentSchemaEachTime()
|
||||
{
|
||||
// Act
|
||||
IReadOnlyList<PluginSettingDescriptorDto> first = _sut.GetSettingsSchema();
|
||||
IReadOnlyList<PluginSettingDescriptorDto> second = _sut.GetSettingsSchema();
|
||||
|
||||
// Assert
|
||||
Assert.NotSame(first, second);
|
||||
Assert.Equal(first.Count, second.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RegisterServices_WhenCalled_ShouldRegisterTheKeyedMetadataProviderAndHttpClient()
|
||||
{
|
||||
// Arrange
|
||||
ServiceCollection services = new();
|
||||
|
||||
// Act
|
||||
_sut.RegisterServices(services);
|
||||
ServiceProvider serviceProvider = services.BuildServiceProvider();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(serviceProvider.GetKeyedService<IMetadataProvider>(OpenLibraryPlugin.s_pluginId));
|
||||
Assert.NotNull(serviceProvider.GetService<OpenLibraryHttpClient>());
|
||||
}
|
||||
}
|
||||
+251
@@ -0,0 +1,251 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.OpenLibrary.Common.Models.DTO.Settings;
|
||||
using Lumina.Plugins.OpenLibrary.Core.Settings;
|
||||
using Lumina.Plugins.OpenLibrary.Fixtures.Common.Models.DTO.Settings;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.OpenLibrary.UnitTests.Core.Settings;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="OpenLibrarySettingsLoader"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class OpenLibrarySettingsLoaderTests
|
||||
{
|
||||
private readonly OpenLibrarySettingsDtoFixture _openLibrarySettingsDtoFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Apply_WhenStoredSettingsContainValidValues_ShouldOverlayThemOntoTheRuntimeSettings()
|
||||
{
|
||||
// Arrange
|
||||
OpenLibrarySettingsDto settings = _openLibrarySettingsDtoFixture.Create();
|
||||
Dictionary<string, string> storedSettings = new()
|
||||
{
|
||||
[OpenLibrarySettingsKeys.CONTACT_EMAIL] = " contact@example.com ",
|
||||
[OpenLibrarySettingsKeys.SEARCH_RESULT_LIMIT] = "25",
|
||||
[OpenLibrarySettingsKeys.WORK_EDITION_LIMIT] = "75",
|
||||
[OpenLibrarySettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS] = "2.5"
|
||||
};
|
||||
|
||||
// Act
|
||||
OpenLibrarySettingsLoader.Apply(settings, storedSettings);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("contact@example.com", settings.ContactEmail);
|
||||
Assert.Equal(25, settings.SearchResultLimit);
|
||||
Assert.Equal(75, settings.WorkEditionLimit);
|
||||
Assert.Equal(TimeSpan.FromSeconds(2.5), settings.MinimumRequestInterval);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Apply_WhenStoredSettingsAreEmpty_ShouldKeepTheRuntimeSettingsDefaults()
|
||||
{
|
||||
// Arrange
|
||||
OpenLibrarySettingsDto settings = _openLibrarySettingsDtoFixture.Create(
|
||||
userAgent: "Lumina-OpenLibrary/1.0",
|
||||
searchResultLimit: 10,
|
||||
workEditionLimit: 50,
|
||||
minimumRequestInterval: TimeSpan.FromSeconds(1.1));
|
||||
Dictionary<string, string> storedSettings = [];
|
||||
|
||||
// Act
|
||||
OpenLibrarySettingsLoader.Apply(settings, storedSettings);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Lumina-OpenLibrary/1.0", settings.UserAgent);
|
||||
Assert.Null(settings.ContactEmail);
|
||||
Assert.Equal(10, settings.SearchResultLimit);
|
||||
Assert.Equal(50, settings.WorkEditionLimit);
|
||||
Assert.Equal(TimeSpan.FromSeconds(1.1), settings.MinimumRequestInterval);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Apply_WhenStoredSettingsContainUnknownKeys_ShouldIgnoreThem()
|
||||
{
|
||||
// Arrange
|
||||
OpenLibrarySettingsDto settings = _openLibrarySettingsDtoFixture.Create(searchResultLimit: 10, workEditionLimit: 50);
|
||||
Dictionary<string, string> storedSettings = new()
|
||||
{
|
||||
["UnknownSetting"] = "value"
|
||||
};
|
||||
|
||||
// Act
|
||||
OpenLibrarySettingsLoader.Apply(settings, storedSettings);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(10, settings.SearchResultLimit);
|
||||
Assert.Equal(50, settings.WorkEditionLimit);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Apply_WhenContactEmailIsWhiteSpace_ShouldSetItToNull()
|
||||
{
|
||||
// Arrange
|
||||
OpenLibrarySettingsDto settings = _openLibrarySettingsDtoFixture.Create();
|
||||
Dictionary<string, string> storedSettings = new()
|
||||
{
|
||||
[OpenLibrarySettingsKeys.CONTACT_EMAIL] = " "
|
||||
};
|
||||
|
||||
// Act
|
||||
OpenLibrarySettingsLoader.Apply(settings, storedSettings);
|
||||
|
||||
// Assert
|
||||
Assert.Null(settings.ContactEmail);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("user\r\n@example.com")] // Carriage return and line feed injection.
|
||||
[InlineData("user@example.com\r\nX-Injected: value")] // Header injection attempt.
|
||||
[InlineData("user(comment)@example.com")] // Parentheses break the from header.
|
||||
[InlineData("user\"quoted\"@example.com")] // Quotes break the header value.
|
||||
[InlineData("user example@example.com")] // An inner space is not a valid token character.
|
||||
public void Apply_WhenContactEmailContainsUnsafeCharacters_ShouldSetItToNull(string storedEmail)
|
||||
{
|
||||
// Arrange
|
||||
OpenLibrarySettingsDto settings = _openLibrarySettingsDtoFixture.Create();
|
||||
Dictionary<string, string> storedSettings = new()
|
||||
{
|
||||
[OpenLibrarySettingsKeys.CONTACT_EMAIL] = storedEmail
|
||||
};
|
||||
|
||||
// Act
|
||||
OpenLibrarySettingsLoader.Apply(settings, storedSettings);
|
||||
|
||||
// Assert
|
||||
Assert.Null(settings.ContactEmail);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Apply_WhenSearchResultLimitIsNotParsable_ShouldKeepTheCurrentValue()
|
||||
{
|
||||
// Arrange
|
||||
OpenLibrarySettingsDto settings = _openLibrarySettingsDtoFixture.Create(searchResultLimit: 10);
|
||||
Dictionary<string, string> storedSettings = new()
|
||||
{
|
||||
[OpenLibrarySettingsKeys.SEARCH_RESULT_LIMIT] = "not-a-number"
|
||||
};
|
||||
|
||||
// Act
|
||||
OpenLibrarySettingsLoader.Apply(settings, storedSettings);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(10, settings.SearchResultLimit);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Apply_WhenSearchResultLimitIsNotParsableAndCurrentValueWasChanged_ShouldKeepTheChangedValue()
|
||||
{
|
||||
// Arrange
|
||||
OpenLibrarySettingsDto settings = _openLibrarySettingsDtoFixture.Create(searchResultLimit: 7);
|
||||
Dictionary<string, string> storedSettings = new()
|
||||
{
|
||||
[OpenLibrarySettingsKeys.SEARCH_RESULT_LIMIT] = "not-a-number"
|
||||
};
|
||||
|
||||
// Act
|
||||
OpenLibrarySettingsLoader.Apply(settings, storedSettings);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(7, settings.SearchResultLimit);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("-5", 1)]
|
||||
[InlineData("0", 1)]
|
||||
[InlineData("1", 1)]
|
||||
[InlineData(" 12 ", 12)]
|
||||
[InlineData("300", 300)]
|
||||
public void Apply_WhenSearchResultLimitIsParsable_ShouldClampItToAtLeastOne(string storedValue, int expected)
|
||||
{
|
||||
// Arrange
|
||||
OpenLibrarySettingsDto settings = _openLibrarySettingsDtoFixture.Create();
|
||||
Dictionary<string, string> storedSettings = new()
|
||||
{
|
||||
[OpenLibrarySettingsKeys.SEARCH_RESULT_LIMIT] = storedValue
|
||||
};
|
||||
|
||||
// Act
|
||||
OpenLibrarySettingsLoader.Apply(settings, storedSettings);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(expected, settings.SearchResultLimit);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("-5", 1)]
|
||||
[InlineData("0", 1)]
|
||||
[InlineData("80", 80)]
|
||||
public void Apply_WhenWorkEditionLimitIsParsable_ShouldClampItToAtLeastOne(string storedValue, int expected)
|
||||
{
|
||||
// Arrange
|
||||
OpenLibrarySettingsDto settings = _openLibrarySettingsDtoFixture.Create();
|
||||
Dictionary<string, string> storedSettings = new()
|
||||
{
|
||||
[OpenLibrarySettingsKeys.WORK_EDITION_LIMIT] = storedValue
|
||||
};
|
||||
|
||||
// Act
|
||||
OpenLibrarySettingsLoader.Apply(settings, storedSettings);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(expected, settings.WorkEditionLimit);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Apply_WhenMinimumRequestIntervalIsNegative_ShouldClampItToZero()
|
||||
{
|
||||
// Arrange
|
||||
OpenLibrarySettingsDto settings = _openLibrarySettingsDtoFixture.Create();
|
||||
Dictionary<string, string> storedSettings = new()
|
||||
{
|
||||
[OpenLibrarySettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS] = "-3"
|
||||
};
|
||||
|
||||
// Act
|
||||
OpenLibrarySettingsLoader.Apply(settings, storedSettings);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(TimeSpan.Zero, settings.MinimumRequestInterval);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("1.5", 1500)]
|
||||
[InlineData("0.25", 250)]
|
||||
[InlineData("0", 0)]
|
||||
public void Apply_WhenMinimumRequestIntervalUsesInvariantCultureDecimalSeparator_ShouldParseIt(string storedValue, int expectedMilliseconds)
|
||||
{
|
||||
// Arrange
|
||||
OpenLibrarySettingsDto settings = _openLibrarySettingsDtoFixture.Create();
|
||||
Dictionary<string, string> storedSettings = new()
|
||||
{
|
||||
[OpenLibrarySettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS] = storedValue
|
||||
};
|
||||
|
||||
// Act
|
||||
OpenLibrarySettingsLoader.Apply(settings, storedSettings);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(TimeSpan.FromMilliseconds(expectedMilliseconds), settings.MinimumRequestInterval);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Apply_WhenMinimumRequestIntervalIsNotParsable_ShouldKeepTheCurrentValue()
|
||||
{
|
||||
// Arrange
|
||||
OpenLibrarySettingsDto settings = _openLibrarySettingsDtoFixture.Create(minimumRequestInterval: TimeSpan.FromSeconds(1.1));
|
||||
Dictionary<string, string> storedSettings = new()
|
||||
{
|
||||
[OpenLibrarySettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS] = "fast"
|
||||
};
|
||||
|
||||
// Act
|
||||
OpenLibrarySettingsLoader.Apply(settings, storedSettings);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(TimeSpan.FromSeconds(1.1), settings.MinimumRequestInterval);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user