mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 14:11:10 +00:00
Adds book deletion and restore to the web client.
Soft deletes books so the scan keeps their paths reserved, lists the deleted books on a themed page, and lets the user restore them. Updates the API, bundled themes, localization, documentation and tests. Closes #213
This commit is contained in:
1 parent
ef5ede6325
commit
f26b07d4ff
125 files changed
+9856
-378
No files matched your search
+138
@@ -0,0 +1,138 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeleteBook;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeleteBook;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="DeleteBookEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteBookEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly DeleteBookEndpoint _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteBookEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public DeleteBookEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<DeleteBookEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldDeleteBookViaApiAndReturnSuccessWithoutData()
|
||||
{
|
||||
// Arrange
|
||||
Guid bookId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ConfigureRequest(bookId.ToString(), libraryId);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
BuildExpectedEndpoint(libraryId, bookId),
|
||||
Arg.Any<CancellationToken>());
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.False(jsonDocument.RootElement.TryGetProperty("data", out JsonElement _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenBookIdIsNotParseable_ShouldForwardGuidEmptyBookIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ConfigureRequest("not-a-guid", libraryId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
BuildExpectedEndpoint(libraryId, Guid.Empty),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenBookIdIsMissing_ShouldForwardGuidEmptyBookIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
BuildExpectedEndpoint(libraryId, Guid.Empty),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryQueryIdIsNotParseable_ShouldForwardGuidEmptyLibraryIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid bookId = Guid.NewGuid();
|
||||
ConfigureRequest(bookId.ToString(), "not-a-guid");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
BuildExpectedEndpoint(Guid.Empty, bookId),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the route and query values the endpoint reads the book identity from.
|
||||
/// </summary>
|
||||
/// <param name="bookId">The raw route value of the book Id.</param>
|
||||
/// <param name="libraryId">The raw query value of the library Id.</param>
|
||||
private void ConfigureRequest(string bookId, Guid libraryId)
|
||||
{
|
||||
ConfigureRequest(bookId, libraryId.ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the route and query values the endpoint reads the book identity from.
|
||||
/// </summary>
|
||||
/// <param name="bookId">The raw route value of the book Id.</param>
|
||||
/// <param name="libraryId">The raw query value of the library Id.</param>
|
||||
private void ConfigureRequest(string bookId, string libraryId)
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = bookId;
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream endpoint the book deletion is expected to be sent to.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The normalized Id of the media library.</param>
|
||||
/// <param name="bookId">The normalized Id of the book.</param>
|
||||
/// <returns>The expected upstream endpoint.</returns>
|
||||
private static string BuildExpectedEndpoint(Guid libraryId, Guid bookId)
|
||||
{
|
||||
return ApiRoutes.Books.DELETE_BOOK
|
||||
.Replace("{libraryId}", libraryId.ToString())
|
||||
.Replace("{bookId}", bookId.ToString());
|
||||
}
|
||||
}
|
||||
+183
@@ -0,0 +1,183 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Presentation.Web.Common.Http;
|
||||
using Lumina.Presentation.Web.Common.Primitives;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Common.Services;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeletedBooks;
|
||||
using Lumina.Presentation.Web.Core.Themes;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Antiforgery;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using Microsoft.Extensions.Localization;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Reflection;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeletedBooks;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="DeletedBooksViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeletedBooksViewEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly IUrlService _mockUrlService;
|
||||
private readonly ThemePageRenderer _mockThemePageRenderer;
|
||||
private readonly IAntiforgery _mockAntiforgery;
|
||||
private readonly IStringLocalizerFactory _mockStringLocalizerFactory;
|
||||
private readonly IStringLocalizer _mockStringLocalizer;
|
||||
private readonly DeletedBooksViewEndpoint _sut;
|
||||
private readonly LibraryDtoFixture _libraryDtoFixture = new();
|
||||
private readonly DeletedBookDtoFixture _deletedBookDtoFixture = new();
|
||||
private readonly GetBooksViewRequestFixture _getBooksViewRequestFixture = new();
|
||||
private readonly ThemePageRenderResultDtoFixture _themePageRenderResultDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeletedBooksViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public DeletedBooksViewEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_mockUrlService = Substitute.For<IUrlService>();
|
||||
_mockThemePageRenderer = Substitute.For<ThemePageRenderer>(new ThemeService(_mockApiHttpClient), new ThemeTemplateEngine());
|
||||
_mockAntiforgery = Substitute.For<IAntiforgery>();
|
||||
_mockAntiforgery.GetAndStoreTokens(Arg.Any<HttpContext>())
|
||||
.Returns(new AntiforgeryTokenSet("request-token", "cookie-token", "__RequestVerificationToken", "RequestVerificationToken"));
|
||||
_mockStringLocalizer = Substitute.For<IStringLocalizer>();
|
||||
_mockStringLocalizer[Arg.Any<string>()].Returns(callInfo => new LocalizedString(
|
||||
callInfo.Arg<string>(),
|
||||
callInfo.Arg<string>() == "Title" ? "Deleted items" : $"Localized-{callInfo.Arg<string>()}"));
|
||||
_mockStringLocalizer.GetAllStrings(Arg.Any<bool>()).Returns(new LocalizedString[]
|
||||
{
|
||||
new("Title", "Deleted items"),
|
||||
new("NoDeletedItems", "There are no deleted items in this library.")
|
||||
});
|
||||
_mockStringLocalizerFactory = Substitute.For<IStringLocalizerFactory>();
|
||||
_mockStringLocalizerFactory.Create(Arg.Any<string>(), Arg.Any<string>()).Returns(_mockStringLocalizer);
|
||||
_sut = Factory.Create<DeletedBooksViewEndpoint>(_mockApiHttpClient, _mockUrlService, _mockThemePageRenderer, _mockAntiforgery, _mockStringLocalizerFactory);
|
||||
TestHttpContextFactory.ConfigureSession(_sut.HttpContext, TestHttpContextFactory.CreateSession());
|
||||
_sut.HttpContext.Request.Path = "/en-us/library/written-content-library/books-library/books/deleted-items";
|
||||
|
||||
StubUrls();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenThemeRenderingSucceeds_ShouldRenderThemedViewWithDocumentedPageData()
|
||||
{
|
||||
// Arrange
|
||||
LibraryDto library = _libraryDtoFixture.Create(title: "Books");
|
||||
DeletedBookDto[] deletedBooks = [.. _deletedBookDtoFixture.CreateMany(2)];
|
||||
_mockApiHttpClient.GetAsync<LibraryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(library);
|
||||
_mockApiHttpClient.GetAsync<DeletedBookDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(deletedBooks);
|
||||
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_themePageRenderResultDtoFixture.Create(content: "<section>deleted</section>", script: "<script>deleted</script>")));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(_getBooksViewRequestFixture.Create(libraryId: library.Id), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("/Core/Views/Shared/_ThemedView.cshtml", GetRenderedViewName(result));
|
||||
await _mockThemePageRenderer.Received(1).RenderAsync(
|
||||
Arg.Is<ThemePageDto>(page =>
|
||||
page.PageKey == "library/written-content-library/book-library/books/deleted-items" &&
|
||||
page.Title == "Deleted items" &&
|
||||
string.Equals(page.PageData["libraryId"] as string, library.Id!.Value.ToString(), StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["libraryTitle"] as string, "Books", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["restoreUrl"] as string, "http://localhost/en-us/library/written-content-library/books-library/books/00000000-0000-0000-0000-000000000000/api-restore-book", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["backUrl"] as string, $"http://localhost/en-us/library/written-content-library/books-library/books?libraryId={library.Id}", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["antiforgeryToken"] as string, "request-token", StringComparison.Ordinal) &&
|
||||
page.PageData.ContainsKey("deletedBooksJson") &&
|
||||
page.PageData.ContainsKey("strings") &&
|
||||
page.PageData.ContainsKey("stringsJson")),
|
||||
Arg.Is<string?>(requestedThemeId => requestedThemeId == null),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryIdIsNull_ShouldRedirectToHome()
|
||||
{
|
||||
// Arrange
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Home.INDEX_CULTURED).Returns("http://localhost/en-us");
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(_getBooksViewRequestFixture.Create(libraryId: null), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
RedirectHttpResult redirectResult = Assert.IsType<RedirectHttpResult>(result);
|
||||
Assert.Equal("http://localhost/en-us", redirectResult.Url);
|
||||
await _mockApiHttpClient.DidNotReceive().GetAsync<LibraryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>());
|
||||
await _mockThemePageRenderer.DidNotReceive().RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenThemeRenderingFails_ShouldFallBackToTheRazorViewWithTheDeletedBooks()
|
||||
{
|
||||
// Arrange
|
||||
LibraryDto library = _libraryDtoFixture.Create(title: "Books");
|
||||
DeletedBookDto[] deletedBooks = [.. _deletedBookDtoFixture.CreateMany(2)];
|
||||
_mockApiHttpClient.GetAsync<LibraryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(library);
|
||||
_mockApiHttpClient.GetAsync<DeletedBookDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(deletedBooks);
|
||||
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result<ThemePageRenderResultDto>.Failure(Error.Failure("Theme.Render", "The page could not be rendered.")));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(_getBooksViewRequestFixture.Create(libraryId: library.Id), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/DeletedItems.cshtml", GetRenderedViewName(result));
|
||||
DeletedBooksPageDto model = Assert.IsType<DeletedBooksPageDto>(GetRenderedModel(result));
|
||||
Assert.Equal(library.Id, model.Library.Id);
|
||||
Assert.Equal(deletedBooks, model.DeletedBooks);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the absolute URLs that the endpoint resolves for the deleted items page.
|
||||
/// </summary>
|
||||
private void StubUrls()
|
||||
{
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Books.INDEX).Returns("http://localhost/en-us/library/written-content-library/books-library/books");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Books.RESTORE_BOOK, Arg.Any<object?>())
|
||||
.Returns("http://localhost/en-us/library/written-content-library/books-library/books/00000000-0000-0000-0000-000000000000/api-restore-book");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the private view name of the rendered <see cref="RazorViewResult"/>, which the result does not expose publicly.
|
||||
/// </summary>
|
||||
/// <param name="result">The result returned by the endpoint under test.</param>
|
||||
/// <returns>The name or path of the rendered view.</returns>
|
||||
private static string GetRenderedViewName(IResult result)
|
||||
{
|
||||
RazorViewResult viewResult = Assert.IsType<RazorViewResult>(result);
|
||||
FieldInfo? viewNameField = typeof(RazorViewResult).GetField("_viewName", BindingFlags.Instance | BindingFlags.NonPublic);
|
||||
Assert.NotNull(viewNameField);
|
||||
return (string)viewNameField.GetValue(viewResult)!;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the private model of the rendered <see cref="RazorViewResult"/>, which the result does not expose publicly.
|
||||
/// </summary>
|
||||
/// <param name="result">The result returned by the endpoint under test.</param>
|
||||
/// <returns>The model passed to the rendered view.</returns>
|
||||
private static object? GetRenderedModel(IResult result)
|
||||
{
|
||||
RazorViewResult viewResult = Assert.IsType<RazorViewResult>(result);
|
||||
FieldInfo? modelField = typeof(RazorViewResult).GetField("_model", BindingFlags.Instance | BindingFlags.NonPublic);
|
||||
Assert.NotNull(modelField);
|
||||
return modelField.GetValue(viewResult);
|
||||
}
|
||||
}
|
||||
+11
@@ -84,6 +84,8 @@ public class BooksIndexViewEndpointTests
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Books.GET_LIBRARY_ITEMS).Returns("http://localhost/en-us/library/written-content-library/books-library/books/api-get-library-items");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Settings.GET_USER_SETTINGS).Returns("http://localhost/en-us/tools/settings/api-get-user-settings");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Books.READ, Arg.Any<object>()).Returns("http://localhost/en-us/library/written-content-library/books-library/books/00000000-0000-0000-0000-000000000000/read");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Books.DELETE_BOOK, Arg.Any<object>()).Returns("http://localhost/en-us/library/written-content-library/books-library/books/00000000-0000-0000-0000-000000000000/api-delete-book");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.Books.DELETED_BOOKS).Returns("http://localhost/en-us/library/written-content-library/books-library/books/deleted-items");
|
||||
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_themePageRenderResultDtoFixture.Create(content: "<section>content</section>", script: "<script>script</script>")));
|
||||
|
||||
@@ -99,6 +101,7 @@ public class BooksIndexViewEndpointTests
|
||||
page.PageData.ContainsKey("libraryId") &&
|
||||
page.PageData.ContainsKey("settingsUrl") &&
|
||||
page.PageData.ContainsKey("strings") &&
|
||||
page.PageData.ContainsKey("stringsJson") &&
|
||||
string.Equals(
|
||||
page.PageData["itemsUrl"] as string,
|
||||
"http://localhost/en-us/library/written-content-library/books-library/books/api-get-library-items",
|
||||
@@ -106,6 +109,14 @@ public class BooksIndexViewEndpointTests
|
||||
string.Equals(
|
||||
page.PageData["readUrl"] as string,
|
||||
"http://localhost/en-us/library/written-content-library/books-library/books/00000000-0000-0000-0000-000000000000/read",
|
||||
StringComparison.Ordinal) &&
|
||||
string.Equals(
|
||||
page.PageData["deleteUrl"] as string,
|
||||
"http://localhost/en-us/library/written-content-library/books-library/books/00000000-0000-0000-0000-000000000000/api-delete-book",
|
||||
StringComparison.Ordinal) &&
|
||||
string.Equals(
|
||||
page.PageData["deletedBooksUrl"] as string,
|
||||
"http://localhost/en-us/library/written-content-library/books-library/books/deleted-items",
|
||||
StringComparison.Ordinal)),
|
||||
Arg.Is<string?>(requestedThemeId => requestedThemeId == null),
|
||||
Arg.Any<CancellationToken>());
|
||||
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.RestoreBook;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.RestoreBook;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="RestoreBookEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RestoreBookEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly RestoreBookEndpoint _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RestoreBookEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public RestoreBookEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<RestoreBookEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldRestoreBookViaApiAndReturnSuccessPayload()
|
||||
{
|
||||
// Arrange
|
||||
Guid bookId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ConfigureRequest(bookId.ToString(), libraryId);
|
||||
_mockApiHttpClient.PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
|
||||
Arg.Any<string>(), Arg.Any<Web.Common.Requests.Common.EmptyRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new Web.Common.Requests.Common.EmptyRequest());
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
|
||||
BuildExpectedEndpoint(libraryId, bookId),
|
||||
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("data").GetProperty("isRestored").GetBoolean());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenBookIdIsNotParseable_ShouldForwardGuidEmptyBookIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ConfigureRequest("not-a-guid", libraryId);
|
||||
_mockApiHttpClient.PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
|
||||
Arg.Any<string>(), Arg.Any<Web.Common.Requests.Common.EmptyRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new Web.Common.Requests.Common.EmptyRequest());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
|
||||
BuildExpectedEndpoint(libraryId, Guid.Empty),
|
||||
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryQueryIdIsNotParseable_ShouldForwardGuidEmptyLibraryIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid bookId = Guid.NewGuid();
|
||||
ConfigureRequest(bookId.ToString(), "not-a-guid");
|
||||
_mockApiHttpClient.PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
|
||||
Arg.Any<string>(), Arg.Any<Web.Common.Requests.Common.EmptyRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new Web.Common.Requests.Common.EmptyRequest());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
|
||||
BuildExpectedEndpoint(Guid.Empty, bookId),
|
||||
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the route and query values the endpoint reads the book identity from.
|
||||
/// </summary>
|
||||
/// <param name="bookId">The raw route value of the book Id.</param>
|
||||
/// <param name="libraryId">The raw query value of the library Id.</param>
|
||||
private void ConfigureRequest(string bookId, Guid libraryId)
|
||||
{
|
||||
ConfigureRequest(bookId, libraryId.ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the route and query values the endpoint reads the book identity from.
|
||||
/// </summary>
|
||||
/// <param name="bookId">The raw route value of the book Id.</param>
|
||||
/// <param name="libraryId">The raw query value of the library Id.</param>
|
||||
private void ConfigureRequest(string bookId, string libraryId)
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = bookId;
|
||||
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream endpoint the book restoration is expected to be sent to.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The normalized Id of the media library.</param>
|
||||
/// <param name="bookId">The normalized Id of the book.</param>
|
||||
/// <returns>The expected upstream endpoint.</returns>
|
||||
private static string BuildExpectedEndpoint(Guid libraryId, Guid bookId)
|
||||
{
|
||||
return ApiRoutes.Books.RESTORE_BOOK
|
||||
.Replace("{libraryId}", libraryId.ToString())
|
||||
.Replace("{bookId}", bookId.ToString());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user