diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbum/GetAlbumEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbum/GetAlbumEndpoint.cs index 99b843b7..459b1a96 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbum/GetAlbumEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbum/GetAlbumEndpoint.cs @@ -16,7 +16,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibra /// /// API endpoint for the /libraries/{libraryId}/artists/{artistId}/albums/{albumId} route. /// -public class GetAlbumEndpoint : BaseEndpoint +public class GetAlbumEndpoint : BaseEndpoint { private readonly IQueryHandler> _getAlbumQueryHandler; @@ -45,7 +45,7 @@ public class GetAlbumEndpoint : BaseEndpoint /// The request object. /// Cancellation token that can be used to stop the execution. - public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) { // Take unique identifiers from the route. string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracks/GetAlbumTracksEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracks/GetAlbumTracksEndpoint.cs index 11ce25b1..4427ab78 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracks/GetAlbumTracksEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracks/GetAlbumTracksEndpoint.cs @@ -17,7 +17,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibra /// /// API endpoint for the /libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks route. /// -public class GetAlbumTracksEndpoint : BaseEndpoint +public class GetAlbumTracksEndpoint : BaseEndpoint { private readonly IQueryHandler>> _getAlbumTracksQueryHandler; @@ -46,7 +46,7 @@ public class GetAlbumTracksEndpoint : BaseEndpoint /// The request object. /// Cancellation token that can be used to stop the execution. - public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) { // Take unique identifiers from the route. string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtist/GetArtistEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtist/GetArtistEndpoint.cs index bf1efd34..be109ed4 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtist/GetArtistEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtist/GetArtistEndpoint.cs @@ -16,7 +16,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibra /// /// API endpoint for the /libraries/{libraryId}/artists/{artistId} route. /// -public class GetArtistEndpoint : BaseEndpoint +public class GetArtistEndpoint : BaseEndpoint { private readonly IQueryHandler> _getArtistQueryHandler; @@ -45,7 +45,7 @@ public class GetArtistEndpoint : BaseEndpoint /// The request object. /// Cancellation token that can be used to stop the execution. - public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) { // Take unique identifiers from the route. string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbums/GetArtistAlbumsEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbums/GetArtistAlbumsEndpoint.cs index 2df64426..a9cff1f4 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbums/GetArtistAlbumsEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbums/GetArtistAlbumsEndpoint.cs @@ -17,7 +17,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibra /// /// API endpoint for the /libraries/{libraryId}/artists/{artistId}/albums route. /// -public class GetArtistAlbumsEndpoint : BaseEndpoint +public class GetArtistAlbumsEndpoint : BaseEndpoint { private readonly IQueryHandler>> _getArtistAlbumsQueryHandler; @@ -46,7 +46,7 @@ public class GetArtistAlbumsEndpoint : BaseEndpoint /// The request object. /// Cancellation token that can be used to stop the execution. - public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) { // Take unique identifiers from the route. string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrack/GetTrackEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrack/GetTrackEndpoint.cs index 41af112b..ff734ea5 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrack/GetTrackEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrack/GetTrackEndpoint.cs @@ -16,7 +16,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibra /// /// API endpoint for the /libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId} route. /// -public class GetTrackEndpoint : BaseEndpoint +public class GetTrackEndpoint : BaseEndpoint { private readonly IQueryHandler> _getTrackQueryHandler; @@ -45,7 +45,7 @@ public class GetTrackEndpoint : BaseEndpoint /// The request object. /// Cancellation token that can be used to stop the execution. - public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) { // Take unique identifiers from the route. string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); diff --git a/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs b/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs index bb13b274..8560391b 100644 --- a/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs +++ b/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs @@ -60,12 +60,10 @@ public class ApiHttpClient : IApiHttpClient /// The API endpoint where the request is being sent. /// Cancellation token that can be used to stop the execution. /// The deserialized response containing the result of the GET request. + /// Thrown when the API returns an unsuccessful response. public async Task GetAsync(string endpoint, CancellationToken cancellationToken = default) { - using HttpRequestMessage request = new(HttpMethod.Get, endpoint); - AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader(); - if (authenticationHeader is not null) - request.Headers.Authorization = authenticationHeader; + using HttpRequestMessage request = CreateRequest(HttpMethod.Get, endpoint); return await SendRequestAsync(request, cancellationToken).ConfigureAwait(false); } @@ -78,10 +76,7 @@ public class ApiHttpClient : IApiHttpClient /// An object, which allows for asynchronous iteration over the deserialized items. public async IAsyncEnumerable GetAsyncEnumerable(string endpoint, [EnumeratorCancellation] CancellationToken cancellationToken = default) { - using HttpRequestMessage request = new(HttpMethod.Get, endpoint); - AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader(); - if (authenticationHeader is not null) - request.Headers.Authorization = authenticationHeader; + using HttpRequestMessage request = CreateRequest(HttpMethod.Get, endpoint); // Send the request and expect only headers initially - this prevents the client from buffering the entire response. using HttpResponseMessage response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); response.EnsureSuccessStatusCode(); @@ -100,25 +95,16 @@ public class ApiHttpClient : IApiHttpClient /// /// The API endpoint where the request is being sent. /// Cancellation token that can be used to stop the execution. - /// A model containing the deserialized blob. + /// A model containing the raw blob bytes and their content type. + /// Thrown when the API returns an unsuccessful response. public async Task GetBlobAsync(string endpoint, CancellationToken cancellationToken = default) { - using HttpRequestMessage request = new(HttpMethod.Get, endpoint); - AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader(); - if (authenticationHeader is not null) - request.Headers.Authorization = authenticationHeader; + using HttpRequestMessage request = CreateRequest(HttpMethod.Get, endpoint); using HttpResponseMessage response = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false); if (!response.IsSuccessStatusCode) { - // Read the content as a string, for error messages. string content = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); - ProblemDetailsDto? problemDetails = null; - try - { - problemDetails = JsonSerializer.Deserialize(content, _jsonOptions); - } - catch { /* If we can't deserialize to ProblemDetails, we'll just use the status code. */ } - throw new ApiException(problemDetails, response.StatusCode); + throw CreateApiException(content, response, request); } // If the response is successful, read it as a byte array. byte[] responseContent = await response.Content.ReadAsByteArrayAsync(cancellationToken).ConfigureAwait(false); @@ -127,30 +113,29 @@ public class ApiHttpClient : IApiHttpClient } /// - /// Sends a DELETE request to the specified as an asynchronous operation. + /// Sends a DELETE request to the specified as an asynchronous operation, discarding the response content. /// /// The API endpoint where the request is being sent. /// Cancellation token that can be used to stop the execution. + /// Thrown when the API returns an unsuccessful response. public async Task DeleteAsync(string endpoint, CancellationToken cancellationToken = default) { - using HttpRequestMessage request = new(HttpMethod.Delete, endpoint); - AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader(); - if (authenticationHeader is not null) - request.Headers.Authorization = authenticationHeader; - // Send the HTTP request and read the response. - HttpResponseMessage response = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false); - if (!response.IsSuccessStatusCode) - { - ProblemDetailsDto? problemDetails = null; - string content = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); - // Attempt to deserialize the response content to ProblemDetailsDto if the request fails. - try - { - problemDetails = JsonSerializer.Deserialize(content, _jsonOptions); - } - catch { /* If we can't deserialize to ProblemDetails, we'll just use the status code. */ } - throw new ApiException(problemDetails, response.StatusCode, request.RequestUri?.AbsolutePath); - } + using HttpRequestMessage request = CreateRequest(HttpMethod.Delete, endpoint); + await SendRequestAsync(request, cancellationToken).ConfigureAwait(false); + } + + /// + /// Sends a PUT request to the specified as an asynchronous operation, discarding the response content. + /// + /// The expected type of the payload content. + /// The API endpoint where the request is being sent. + /// The data to be serialized and sent to the API. + /// Cancellation token that can be used to stop the execution. + /// Thrown when the API returns an unsuccessful response. + public async Task PutIgnoringResponseAsync(string endpoint, TModel data, CancellationToken cancellationToken = default) + { + using HttpRequestMessage request = CreateRequestWithPayload(HttpMethod.Put, endpoint, data); + await SendRequestAsync(request, cancellationToken).ConfigureAwait(false); } /// @@ -159,35 +144,40 @@ public class ApiHttpClient : IApiHttpClient /// The expected type of the response content. /// The expected type of the payload content. /// The API endpoint where the request is being sent. - /// The data to be serialized and send to the API. + /// The data to be serialized and sent to the API. /// Cancellation token that can be used to stop the execution. /// The deserialized response containing the result of the PUT request. + /// Thrown when the API returns an unsuccessful response. public async Task PutAsync(string endpoint, TModel data, CancellationToken cancellationToken = default) { - using HttpRequestMessage request = new(HttpMethod.Put, endpoint); - AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader(); - if (authenticationHeader is not null) - request.Headers.Authorization = authenticationHeader; - request.Content = new StringContent(JsonSerializer.Serialize(data, _jsonOptions), Encoding.UTF8, "application/json"); + using HttpRequestMessage request = CreateRequestWithPayload(HttpMethod.Put, endpoint, data); return await SendRequestAsync(request, cancellationToken).ConfigureAwait(false); } /// - /// Sends a POST request to the specified as an asynchronous operation and returns the result. + /// Sends a PUT request with a multipart form containing a single file to the specified as an asynchronous operation, and returns the result. /// /// The expected type of the response content. - /// The expected type of the payload content. /// The API endpoint where the request is being sent. - /// The data to be serialized and sent to the API. + /// The stream of the file to upload, or to send a multipart form without any file. + /// The name of the file to upload, or when no file is sent. + /// The name of the form field carrying the file. /// Cancellation token that can be used to stop the execution. - /// The deserialized response containing the result of the POST request. - public async Task PostAsync(string endpoint, TModel data, CancellationToken cancellationToken = default) + /// The deserialized response containing the result of the PUT request. + /// Thrown when the API returns an unsuccessful response. + public async Task PutMultipartAsync(string endpoint, Stream? fileStream, string? fileName, string fieldName, CancellationToken cancellationToken = default) { - using HttpRequestMessage request = new(HttpMethod.Post, endpoint); - AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader(); - if (authenticationHeader is not null) - request.Headers.Authorization = authenticationHeader; - request.Content = new StringContent(JsonSerializer.Serialize(data, _jsonOptions), Encoding.UTF8, "application/json"); + using MultipartFormDataContent form = []; + if (fileStream is not null) + { + // The file is streamed as a generic binary part, since the exact content type of the uploaded file is not known. + StreamContent fileContent = new(fileStream); + fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); + form.Add(fileContent, fieldName, fileName ?? string.Empty); + } + + using HttpRequestMessage request = CreateRequest(HttpMethod.Put, endpoint); + request.Content = form; return await SendRequestAsync(request, cancellationToken).ConfigureAwait(false); } @@ -201,6 +191,7 @@ public class ApiHttpClient : IApiHttpClient /// The name of the form field carrying the file. /// Cancellation token that can be used to stop the execution. /// The deserialized response containing the result of the POST request. + /// Thrown when the API returns an unsuccessful response. public async Task PostMultipartAsync(string endpoint, Stream fileStream, string fileName, string fieldName, CancellationToken cancellationToken = default) { // The file is streamed as a generic binary part, since the exact content type of the uploaded file is not known. @@ -209,50 +200,116 @@ public class ApiHttpClient : IApiHttpClient fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); form.Add(fileContent, fieldName, fileName); - using HttpRequestMessage request = new(HttpMethod.Post, endpoint) - { - Content = form - }; - AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader(); - if (authenticationHeader is not null) - request.Headers.Authorization = authenticationHeader; + using HttpRequestMessage request = CreateRequest(HttpMethod.Post, endpoint); + request.Content = form; return await SendRequestAsync(request, cancellationToken).ConfigureAwait(false); } /// - /// Sends a PUT request with a multipart form containing a single file to the specified as an asynchronous operation and returns the result. + /// Sends a POST request without a payload to the specified as an asynchronous operation, discarding the response content. + /// + /// The API endpoint where the request is being sent. + /// Cancellation token that can be used to stop the execution. + /// Thrown when the API returns an unsuccessful response. + public async Task PostIgnoringResponseAsync(string endpoint, CancellationToken cancellationToken = default) + { + using HttpRequestMessage request = CreateRequest(HttpMethod.Post, endpoint); + await SendRequestAsync(request, cancellationToken).ConfigureAwait(false); + } + + /// + /// Sends a POST request without a payload to the specified as an asynchronous operation, and returns the result. /// /// The expected type of the response content. /// The API endpoint where the request is being sent. - /// The stream of the file to upload, or to send a multipart form without any file. - /// The name of the file to upload, or when no file is sent. - /// The name of the form field carrying the file. /// Cancellation token that can be used to stop the execution. - /// The deserialized response containing the result of the PUT request. - public async Task PutMultipartAsync(string endpoint, Stream? fileStream, string? fileName, string fieldName, CancellationToken cancellationToken = default) + /// The deserialized response containing the result of the POST request. + /// Thrown when the API returns an unsuccessful response. + public async Task PostAsync(string endpoint, CancellationToken cancellationToken = default) { - using MultipartFormDataContent form = []; - if (fileStream is not null) - { - // The file is streamed as a generic binary part, since the exact content type of the uploaded file is not known. - StreamContent fileContent = new(fileStream); - fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); - form.Add(fileContent, fieldName, fileName ?? string.Empty); - } + using HttpRequestMessage request = CreateRequest(HttpMethod.Post, endpoint); + return await SendRequestAsync(request, cancellationToken).ConfigureAwait(false); + } - using HttpRequestMessage request = new(HttpMethod.Put, endpoint) - { - Content = form - }; + /// + /// Sends a POST request to the specified as an asynchronous operation, discarding the response content. + /// + /// The expected type of the payload content. + /// The API endpoint where the request is being sent. + /// The data to be serialized and sent to the API. + /// Cancellation token that can be used to stop the execution. + /// Thrown when the API returns an unsuccessful response. + public async Task PostIgnoringResponseAsync(string endpoint, TModel data, CancellationToken cancellationToken = default) + { + using HttpRequestMessage request = CreateRequestWithPayload(HttpMethod.Post, endpoint, data); + await SendRequestAsync(request, cancellationToken).ConfigureAwait(false); + } + + /// + /// Sends a POST request to the specified as an asynchronous operation and returns the result. + /// + /// The expected type of the response content. + /// The expected type of the payload content. + /// The API endpoint where the request is being sent. + /// The data to be serialized and sent to the API. + /// Cancellation token that can be used to stop the execution. + /// The deserialized response containing the result of the POST request. + /// Thrown when the API returns an unsuccessful response. + public async Task PostAsync(string endpoint, TModel data, CancellationToken cancellationToken = default) + { + using HttpRequestMessage request = CreateRequestWithPayload(HttpMethod.Post, endpoint, data); + return await SendRequestAsync(request, cancellationToken).ConfigureAwait(false); + } + + /// + /// Creates an HTTP request for the specified and . + /// + /// The HTTP method of the request. + /// The API endpoint where the request is being sent. + /// The created . + private HttpRequestMessage CreateRequest(HttpMethod method, string endpoint) + { + HttpRequestMessage request = new(method, endpoint); AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader(); if (authenticationHeader is not null) request.Headers.Authorization = authenticationHeader; - return await SendRequestAsync(request, cancellationToken).ConfigureAwait(false); + return request; + } + + /// + /// Creates an HTTP request for the specified and , with the serialized as its JSON payload. + /// + /// The expected type of the payload content. + /// The HTTP method of the request. + /// The API endpoint where the request is being sent. + /// The data to be serialized and sent to the API. + /// The created . + private HttpRequestMessage CreateRequestWithPayload(HttpMethod method, string endpoint, TModel data) + { + HttpRequestMessage request = CreateRequest(method, endpoint); + request.Content = new StringContent(JsonSerializer.Serialize(data, _jsonOptions), Encoding.UTF8, "application/json"); + return request; + } + + /// + /// Sends an HTTP request and reads the response content. + /// If the request fails, it attempts to deserialize the response content into a and throws an . + /// + /// The to be sent. + /// Cancellation token that can be used to stop the execution. + /// The raw response content. + /// Thrown if the response is not successful, with the if available. + private async Task SendRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + using HttpResponseMessage response = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false); + string content = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + if (response.IsSuccessStatusCode) + return content; + throw CreateApiException(content, response, request); } /// /// Sends an HTTP request and deserializes the response into the specified type if the request is successful. - /// If the request fails, it attempts to deserialize the response content into a and throws an . /// /// The expected type of the response content. /// The to be sent. @@ -261,28 +318,30 @@ public class ApiHttpClient : IApiHttpClient /// Thrown if the response is not successful, with the if available. private async Task SendRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken) { - // Send the HTTP request and read the response. - HttpResponseMessage response = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false); - string content = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); - // If the response is successful, deserialize the content to TResponse and return it. - if (response.IsSuccessStatusCode) + string content = await SendRequestAsync(request, cancellationToken).ConfigureAwait(false); + // Handle empty content case. + if (string.IsNullOrEmpty(content)) + return default!; + return JsonSerializer.Deserialize(content, _jsonOptions)!; + } + + /// + /// Creates the exception thrown when an API request fails. + /// + /// The raw response content. + /// The failed HTTP response. + /// The HTTP request that failed. + /// The created . + private ApiException CreateApiException(string content, HttpResponseMessage response, HttpRequestMessage request) + { + ProblemDetailsDto? problemDetails = null; + // Attempt to deserialize the response content to ProblemDetailsDto if the request fails. + try { - // Handle empty content case. - if (string.IsNullOrEmpty(content)) - return default!; - return JsonSerializer.Deserialize(content, _jsonOptions)!; - } - else - { - ProblemDetailsDto? problemDetails = null; - // Attempt to deserialize the response content to ProblemDetailsDto if the request fails. - try - { - problemDetails = JsonSerializer.Deserialize(content, _jsonOptions); - } - catch { /* If we can't deserialize to ProblemDetails, we'll just use the status code. */ } - throw new ApiException(problemDetails, response.StatusCode, request.RequestUri?.AbsolutePath); + problemDetails = JsonSerializer.Deserialize(content, _jsonOptions); } + catch { /* If we can't deserialize to ProblemDetails, we'll just use the status code. */ } + return new ApiException(problemDetails, response.StatusCode, request.RequestUri?.AbsolutePath); } /// diff --git a/src/Lumina.Presentation.Web/Common/Api/IApiHttpClient.cs b/src/Lumina.Presentation.Web/Common/Api/IApiHttpClient.cs index 77bae8cd..ea76db0c 100644 --- a/src/Lumina.Presentation.Web/Common/Api/IApiHttpClient.cs +++ b/src/Lumina.Presentation.Web/Common/Api/IApiHttpClient.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Common.Exceptions; using System.Collections.Generic; using System.IO; using System.Threading; @@ -20,6 +21,7 @@ public interface IApiHttpClient /// The API endpoint where the request is being sent. /// Cancellation token that can be used to stop the execution. /// The deserialized response containing the result of the GET request. + /// Thrown when the API returns an unsuccessful response. Task GetAsync(string endpoint, CancellationToken cancellationToken = default); /// @@ -36,25 +38,38 @@ public interface IApiHttpClient /// /// The API endpoint where the request is being sent. /// Cancellation token that can be used to stop the execution. - /// A model containing the deserialized blob. + /// A model containing the raw blob bytes and their content type. + /// Thrown when the API returns an unsuccessful response. Task GetBlobAsync(string endpoint, CancellationToken cancellationToken = default); /// - /// Sends a DELETE request to the specified as an asynchronous operation. + /// Sends a DELETE request to the specified as an asynchronous operation, discarding the response content. /// /// The API endpoint where the request is being sent. /// Cancellation token that can be used to stop the execution. + /// Thrown when the API returns an unsuccessful response. Task DeleteAsync(string endpoint, CancellationToken cancellationToken = default); + /// + /// Sends a PUT request to the specified as an asynchronous operation, discarding the response content. + /// + /// The expected type of the payload content. + /// The API endpoint where the request is being sent. + /// The data to be serialized and sent to the API. + /// Cancellation token that can be used to stop the execution. + /// Thrown when the API returns an unsuccessful response. + Task PutIgnoringResponseAsync(string endpoint, TModel data, CancellationToken cancellationToken = default); + /// /// Sends a PUT request to the specified as an asynchronous operation and returns the result. /// /// The expected type of the response content. /// The expected type of the payload content. /// The API endpoint where the request is being sent. - /// The data to be serialized and send to the API. + /// The data to be serialized and sent to the API. /// Cancellation token that can be used to stop the execution. /// The deserialized response containing the result of the PUT request. + /// Thrown when the API returns an unsuccessful response. Task PutAsync(string endpoint, TModel data, CancellationToken cancellationToken = default); /// @@ -67,6 +82,7 @@ public interface IApiHttpClient /// The name of the form field carrying the file. /// Cancellation token that can be used to stop the execution. /// The deserialized response containing the result of the PUT request. + /// Thrown when the API returns an unsuccessful response. Task PutMultipartAsync(string endpoint, Stream? fileStream, string? fileName, string fieldName, CancellationToken cancellationToken = default); /// @@ -79,8 +95,37 @@ public interface IApiHttpClient /// The name of the form field carrying the file. /// Cancellation token that can be used to stop the execution. /// The deserialized response containing the result of the POST request. + /// Thrown when the API returns an unsuccessful response. Task PostMultipartAsync(string endpoint, Stream fileStream, string fileName, string fieldName, CancellationToken cancellationToken = default); + /// + /// Sends a POST request without a payload to the specified as an asynchronous operation, discarding the response content. + /// + /// The API endpoint where the request is being sent. + /// Cancellation token that can be used to stop the execution. + /// Thrown when the API returns an unsuccessful response. + Task PostIgnoringResponseAsync(string endpoint, CancellationToken cancellationToken = default); + + /// + /// Sends a POST request without a payload to the specified as an asynchronous operation and returns the result. + /// + /// The expected type of the response content. + /// The API endpoint where the request is being sent. + /// Cancellation token that can be used to stop the execution. + /// The deserialized response containing the result of the POST request. + /// Thrown when the API returns an unsuccessful response. + Task PostAsync(string endpoint, CancellationToken cancellationToken = default); + + /// + /// Sends a POST request to the specified as an asynchronous operation, discarding the response content. + /// + /// The expected type of the payload content. + /// The API endpoint where the request is being sent. + /// The data to be serialized and sent to the API. + /// Cancellation token that can be used to stop the execution. + /// Thrown when the API returns an unsuccessful response. + Task PostIgnoringResponseAsync(string endpoint, TModel data, CancellationToken cancellationToken = default); + /// /// Sends a POST request to the specified as an asynchronous operation and returns the result. /// @@ -90,5 +135,6 @@ public interface IApiHttpClient /// The data to be serialized and sent to the API. /// Cancellation token that can be used to stop the execution. /// The deserialized response containing the result of the POST request. + /// Thrown when the API returns an unsuccessful response. Task PostAsync(string endpoint, TModel data, CancellationToken cancellationToken = default); } diff --git a/src/Lumina.Presentation.Web/Common/Authorization/AuthorizationService.cs b/src/Lumina.Presentation.Web/Common/Authorization/AuthorizationService.cs index b4f61abd..5a407ea8 100644 --- a/src/Lumina.Presentation.Web/Common/Authorization/AuthorizationService.cs +++ b/src/Lumina.Presentation.Web/Common/Authorization/AuthorizationService.cs @@ -8,6 +8,7 @@ using Microsoft.AspNetCore.Http; using Polly.CircuitBreaker; using System; using System.Linq; +using System.Net; using System.Net.Http; using System.Security.Claims; using System.Threading; @@ -74,6 +75,13 @@ public class AuthorizationService : IAuthorizationService { return await _apiHttpClient.GetAsync($"auth/get-authorization?userId={Uri.EscapeDataString(userId)}", cancellationToken); } + catch (ApiException exception) when (exception.HttpStatusCode == HttpStatusCode.NotFound) + { + // This is the only place that knows the request was the current-user authorization check. Convert a 404 here into an explicit exception, so the middleware can + // invalidate the stale session without guessing from the request path. Do not move this classification into the middleware: it only sees a generic ApiException, + // and a caller-controlled path can contain the authorization route text. + throw new CurrentUserAuthorizationException(exception.ProblemDetails, exception.HttpStatusCode, exception.RequestPath); + } catch (Exception exception) { HttpContext? httpContext = _httpContextAccessor.HttpContext; diff --git a/src/Lumina.Presentation.Web/Common/Exceptions/CurrentUserAuthorizationException.cs b/src/Lumina.Presentation.Web/Common/Exceptions/CurrentUserAuthorizationException.cs new file mode 100644 index 00000000..475e0438 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Exceptions/CurrentUserAuthorizationException.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Common; +using System.Net; +#endregion + +namespace Lumina.Presentation.Web.Common.Exceptions; + +/// +/// Exception for an unsuccessful current-user authorization check, which means that the stored session refers to a user the API no longer knows. +/// +public class CurrentUserAuthorizationException : ApiException +{ + /// + /// Initializes a new instance of the class. + /// + /// The problem details object returned by the API. + /// The HTTP status code returned by the API. + /// The absolute path of the API endpoint that produced this exception. + public CurrentUserAuthorizationException(ProblemDetailsDto? problemDetails, HttpStatusCode httpStatusCode, string? requestPath = null) + : base(problemDetails, httpStatusCode, requestPath) + { + } +} diff --git a/src/Lumina.Presentation.Web/Common/Middlewares/ExceptionHandlingMiddleware.cs b/src/Lumina.Presentation.Web/Common/Middlewares/ExceptionHandlingMiddleware.cs index 6035e7c3..9ffee6e2 100644 --- a/src/Lumina.Presentation.Web/Common/Middlewares/ExceptionHandlingMiddleware.cs +++ b/src/Lumina.Presentation.Web/Common/Middlewares/ExceptionHandlingMiddleware.cs @@ -137,9 +137,10 @@ public class ExceptionHandlingMiddleware /// private async Task HandleNotFoundAsync(HttpContext context, ApiException apiException) { - // When the API reports the currently logged-in user no longer exists (404 from the current-user authorization check), - // the stored session is stale: sign out and send the user to the login page instead of the not-found page. - if (context.User?.Identity?.IsAuthenticated == true && IsCurrentUserAuthorizationCheck(apiException)) + // When the API reports the currently logged-in user no longer exists, the stored session is stale: sign out and send the user + // to the login page instead of the not-found page. The condition is signaled by the authorization check itself, never inferred + // from the URL of the failed request, because a caller-controlled path can contain the same text. + if (context.User?.Identity?.IsAuthenticated == true && apiException is CurrentUserAuthorizationException) { await HandleUnauthorizedAsync(context).ConfigureAwait(false); return; @@ -412,13 +413,4 @@ public class ExceptionHandlingMiddleware } } - /// - /// Determines whether the API exception originated from the authorization check of the currently logged in user. - /// - /// The API exception to inspect. - /// if the exception came from the current-user authorization endpoint, otherwise. - private static bool IsCurrentUserAuthorizationCheck(ApiException apiException) - { - return apiException.RequestPath?.Contains("/auth/get-authorization", StringComparison.OrdinalIgnoreCase) == true; - } } diff --git a/src/Lumina.Presentation.Web/Common/Requests/Common/EmptyRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Common/EmptyRequest.cs deleted file mode 100644 index 12334e34..00000000 --- a/src/Lumina.Presentation.Web/Common/Requests/Common/EmptyRequest.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace Lumina.Presentation.Web.Common.Requests.Common; - -/// -/// Record used for empty requests and responses. -/// -public record struct EmptyRequest(); diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpoint.cs index 0688c4c9..1ea93ac4 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpoint.cs @@ -5,7 +5,6 @@ using Lumina.Presentation.Web.Common.Authorization; using Lumina.Presentation.Web.Common.Requests.Scheduling; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Endpoints.Common; -using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using System.Threading; using System.Threading.Tasks; @@ -50,7 +49,7 @@ public class FireScheduledJobEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(FireScheduledJobRequest request, CancellationToken cancellationToken) { - await _apiHttpClient.PutAsync(ApiRoutes.ScheduledJobs.FIRE_SCHEDULED_JOB.Replace("{scheduledJobId}", request.ScheduledJobId.ToString()), new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest(), cancellationToken).ConfigureAwait(false); + await _apiHttpClient.PutIgnoringResponseAsync(ApiRoutes.ScheduledJobs.FIRE_SCHEDULED_JOB.Replace("{scheduledJobId}", request.ScheduledJobId.ToString()), request, cancellationToken).ConfigureAwait(false); return JsonSuccess(); } } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpoint.cs index fa6988a2..13808829 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpoint.cs @@ -5,7 +5,6 @@ using Lumina.Presentation.Web.Common.Authorization; using Lumina.Presentation.Web.Common.Requests.Scheduling; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Endpoints.Common; -using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using System.Threading; using System.Threading.Tasks; @@ -50,7 +49,7 @@ public class StartScheduledJobEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(StartScheduledJobRequest request, CancellationToken cancellationToken) { - await _apiHttpClient.PutAsync(ApiRoutes.ScheduledJobs.START_SCHEDULED_JOB.Replace("{scheduledJobId}", request.ScheduledJobId.ToString()), new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest(), cancellationToken).ConfigureAwait(false); + await _apiHttpClient.PutIgnoringResponseAsync(ApiRoutes.ScheduledJobs.START_SCHEDULED_JOB.Replace("{scheduledJobId}", request.ScheduledJobId.ToString()), request, cancellationToken).ConfigureAwait(false); return JsonSuccess(); } } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpoint.cs index 55616f57..6f0f1b57 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpoint.cs @@ -5,7 +5,6 @@ using Lumina.Presentation.Web.Common.Authorization; using Lumina.Presentation.Web.Common.Requests.Scheduling; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Endpoints.Common; -using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using System.Threading; using System.Threading.Tasks; @@ -50,7 +49,7 @@ public class StopScheduledJobEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(StopScheduledJobRequest request, CancellationToken cancellationToken) { - await _apiHttpClient.PutAsync(ApiRoutes.ScheduledJobs.STOP_SCHEDULED_JOB.Replace("{scheduledJobId}", request.ScheduledJobId.ToString()), new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest(), cancellationToken).ConfigureAwait(false); + await _apiHttpClient.PutIgnoringResponseAsync(ApiRoutes.ScheduledJobs.STOP_SCHEDULED_JOB.Replace("{scheduledJobId}", request.ScheduledJobId.ToString()), request, cancellationToken).ConfigureAwait(false); return JsonSuccess(); } } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpoint.cs index 03075603..20147765 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpoint.cs @@ -5,7 +5,6 @@ using Lumina.Presentation.Web.Common.Authorization; using Lumina.Presentation.Web.Common.Requests.Scheduling; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Endpoints.Common; -using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using System.Threading; using System.Threading.Tasks; @@ -50,7 +49,7 @@ public class UpdateSchedulerDisplayPreferencesEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(UpdateSchedulerDisplayPreferencesRequest request, CancellationToken cancellationToken) { - await _apiHttpClient.PutAsync(ApiRoutes.ScheduledJobs.UPDATE_DISPLAY_PREFERENCES, request, cancellationToken).ConfigureAwait(false); + await _apiHttpClient.PutIgnoringResponseAsync(ApiRoutes.ScheduledJobs.UPDATE_DISPLAY_PREFERENCES, request, cancellationToken).ConfigureAwait(false); return JsonSuccess(); } } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Favorites/RemoveFavorite/RemoveFavoriteEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Favorites/RemoveFavorite/RemoveFavoriteEndpoint.cs index 3d6b6fc0..b2ea8777 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Favorites/RemoveFavorite/RemoveFavoriteEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Favorites/RemoveFavorite/RemoveFavoriteEndpoint.cs @@ -4,7 +4,6 @@ using Lumina.Presentation.Web.Common.Api; using Lumina.Presentation.Web.Common.Enums.Favorites; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Endpoints.Common; -using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using System; using System.Threading; @@ -16,7 +15,7 @@ namespace Lumina.Presentation.Web.Core.Endpoints.Favorites.RemoveFavorite; /// /// API endpoint for the /{culture}/favorites/{mediaKind}/{mediaItemId}/api-remove-favorite route. /// -public class RemoveFavoriteEndpoint : BaseEndpoint +public class RemoveFavoriteEndpoint : BaseEndpoint { // A value that is not a name of FavoriteMediaKind, so the API rejects a crafted route value with its own validation error. private const string INVALID_MEDIA_KIND_PLACEHOLDER = "Invalid"; @@ -50,7 +49,7 @@ public class RemoveFavoriteEndpoint : BaseEndpoint /// The request object. /// Cancellation token that can be used to stop the execution. - public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) { // The route values are normalized before they are substituted into the upstream URL, so that a crafted value can never escape its URL segment. // The media kind must be the name of a FavoriteMediaKind member, which also rejects numeric strings and comma separated flag lists, and the Id must be a Guid. diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/RestoreMusicAlbum/RestoreMusicAlbumEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/RestoreMusicAlbum/RestoreMusicAlbumEndpoint.cs index 5a8b036a..957d2e8f 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/RestoreMusicAlbum/RestoreMusicAlbumEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/RestoreMusicAlbum/RestoreMusicAlbumEndpoint.cs @@ -3,7 +3,6 @@ using FastEndpoints; using Lumina.Presentation.Web.Common.Api; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Endpoints.Common; -using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using System; using System.Threading; @@ -57,9 +56,8 @@ public class RestoreMusicAlbumEndpoint : BaseEndpoint string queryLibraryId = HttpContext.Request.Query["libraryId"].ToString(); string libraryId = Guid.TryParse(queryLibraryId, out Guid parsedLibraryId) ? parsedLibraryId.ToString() : Guid.Empty.ToString(); - await _apiHttpClient.PostAsync( + await _apiHttpClient.PostIgnoringResponseAsync( ApiRoutes.Music.RESTORE_ALBUM.Replace("{libraryId}", libraryId).Replace("{artistId}", artistId).Replace("{albumId}", albumId), - new Web.Common.Requests.Common.EmptyRequest(), cancellationToken).ConfigureAwait(false); return JsonSuccess(new { isRestored = true }); } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/RestoreMusicArtist/RestoreMusicArtistEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/RestoreMusicArtist/RestoreMusicArtistEndpoint.cs index 6016f71e..c114a88f 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/RestoreMusicArtist/RestoreMusicArtistEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/RestoreMusicArtist/RestoreMusicArtistEndpoint.cs @@ -3,7 +3,6 @@ using FastEndpoints; using Lumina.Presentation.Web.Common.Api; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Endpoints.Common; -using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using System; using System.Threading; @@ -55,9 +54,8 @@ public class RestoreMusicArtistEndpoint : BaseEndpoint string queryLibraryId = HttpContext.Request.Query["libraryId"].ToString(); string libraryId = Guid.TryParse(queryLibraryId, out Guid parsedLibraryId) ? parsedLibraryId.ToString() : Guid.Empty.ToString(); - await _apiHttpClient.PostAsync( + await _apiHttpClient.PostIgnoringResponseAsync( ApiRoutes.Music.RESTORE_ARTIST.Replace("{libraryId}", libraryId).Replace("{artistId}", artistId), - new Web.Common.Requests.Common.EmptyRequest(), cancellationToken).ConfigureAwait(false); return JsonSuccess(new { isRestored = true }); } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/RestoreMusicTrack/RestoreMusicTrackEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/RestoreMusicTrack/RestoreMusicTrackEndpoint.cs index e79985a0..de51e0da 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/RestoreMusicTrack/RestoreMusicTrackEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/RestoreMusicTrack/RestoreMusicTrackEndpoint.cs @@ -3,7 +3,6 @@ using FastEndpoints; using Lumina.Presentation.Web.Common.Api; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Endpoints.Common; -using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using System; using System.Threading; @@ -59,9 +58,8 @@ public class RestoreMusicTrackEndpoint : BaseEndpoint string queryLibraryId = HttpContext.Request.Query["libraryId"].ToString(); string libraryId = Guid.TryParse(queryLibraryId, out Guid parsedLibraryId) ? parsedLibraryId.ToString() : Guid.Empty.ToString(); - await _apiHttpClient.PostAsync( + await _apiHttpClient.PostIgnoringResponseAsync( ApiRoutes.Music.RESTORE_TRACK.Replace("{libraryId}", libraryId).Replace("{artistId}", artistId).Replace("{albumId}", albumId).Replace("{trackId}", trackId), - new Web.Common.Requests.Common.EmptyRequest(), cancellationToken).ConfigureAwait(false); return JsonSuccess(new { isRestored = true }); } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpoint.cs index d5aa5b83..3ee6e871 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpoint.cs @@ -3,7 +3,6 @@ using FastEndpoints; using Lumina.Presentation.Web.Common.Api; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Endpoints.Common; -using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using System.Threading; using System.Threading.Tasks; @@ -47,7 +46,7 @@ public class CancelLibrariesScanEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) { - await _apiHttpClient.PostAsync(ApiRoutes.Libraries.CANCEL_LIBRARIES_SCAN, new Web.Common.Requests.Common.EmptyRequest(), cancellationToken).ConfigureAwait(false); + await _apiHttpClient.PostIgnoringResponseAsync(ApiRoutes.Libraries.CANCEL_LIBRARIES_SCAN, cancellationToken).ConfigureAwait(false); return JsonSuccess(); } } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpoint.cs index 66b4def9..578354f4 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpoint.cs @@ -4,7 +4,6 @@ using Lumina.Presentation.Web.Common.Api; using Lumina.Presentation.Web.Common.Requests.Library.Management; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Endpoints.Common; -using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using System.Threading; using System.Threading.Tasks; @@ -48,7 +47,7 @@ public class CancelLibraryScanEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(CancelLibraryScanRequest request, CancellationToken cancellationToken) { - await _apiHttpClient.PostAsync(ApiRoutes.Libraries.CANCEL_LIBRARY_SCAN.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{scanId}", request.ScanId.ToString()), new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest(), cancellationToken).ConfigureAwait(false); + await _apiHttpClient.PostIgnoringResponseAsync(ApiRoutes.Libraries.CANCEL_LIBRARY_SCAN.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{scanId}", request.ScanId.ToString()), request, cancellationToken).ConfigureAwait(false); return JsonSuccess(); } } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpoint.cs index 7c77f6f0..5493f7c1 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpoint.cs @@ -4,7 +4,6 @@ using Lumina.Presentation.Web.Common.Api; using Lumina.Presentation.Web.Common.DTO.Libraries; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Endpoints.Common; -using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using System.Threading; using System.Threading.Tasks; @@ -48,7 +47,7 @@ public class ScanLibrariesEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) { - ScanLibraryDto[] response = await _apiHttpClient.PostAsync(ApiRoutes.Libraries.SCAN_LIBRARIES, new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest(), cancellationToken).ConfigureAwait(false); + ScanLibraryDto[] response = await _apiHttpClient.PostAsync(ApiRoutes.Libraries.SCAN_LIBRARIES, cancellationToken).ConfigureAwait(false); return JsonSuccess(response); } } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpoint.cs index 19484e1c..1410f30d 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpoint.cs @@ -5,7 +5,6 @@ using Lumina.Presentation.Web.Common.DTO.Libraries; using Lumina.Presentation.Web.Common.Requests.Library.Management; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Endpoints.Common; -using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using System.Threading; using System.Threading.Tasks; @@ -49,7 +48,7 @@ public class ScanLibraryEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(ScanLibraryRequest request, CancellationToken cancellationToken) { - ScanLibraryDto response = await _apiHttpClient.PostAsync(ApiRoutes.Libraries.SCAN_LIBRARY.Replace("{id}", request.Id.ToString()), new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest(), cancellationToken).ConfigureAwait(false); + ScanLibraryDto response = await _apiHttpClient.PostAsync(ApiRoutes.Libraries.SCAN_LIBRARY.Replace("{id}", request.Id.ToString()), cancellationToken).ConfigureAwait(false); return JsonSuccess(response); } } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/RestoreBook/RestoreBookEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/RestoreBook/RestoreBookEndpoint.cs index 79203ddf..2e4b7de2 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/RestoreBook/RestoreBookEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/RestoreBook/RestoreBookEndpoint.cs @@ -3,7 +3,6 @@ using FastEndpoints; using Lumina.Presentation.Web.Common.Api; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Endpoints.Common; -using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using System; using System.Threading; @@ -56,9 +55,8 @@ public class RestoreBookEndpoint : BaseEndpoint string queryLibraryId = HttpContext.Request.Query["libraryId"].ToString(); string libraryId = Guid.TryParse(queryLibraryId, out Guid parsedLibraryId) ? parsedLibraryId.ToString() : Guid.Empty.ToString(); - await _apiHttpClient.PostAsync( + await _apiHttpClient.PostIgnoringResponseAsync( ApiRoutes.Books.RESTORE_BOOK.Replace("{libraryId}", libraryId).Replace("{bookId}", bookId), - new Web.Common.Requests.Common.EmptyRequest(), cancellationToken).ConfigureAwait(false); return JsonSuccess(new { isRestored = true }); } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/StartConsumption/StartConsumptionEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/StartConsumption/StartConsumptionEndpoint.cs index 1023d1a9..7a573cd9 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/StartConsumption/StartConsumptionEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/StartConsumption/StartConsumptionEndpoint.cs @@ -5,7 +5,6 @@ using Lumina.Presentation.Web.Common.DTO.MediaConsumption; using Lumina.Presentation.Web.Common.Enums.MediaConsumption; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Endpoints.Common; -using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using System; using System.Threading; @@ -72,7 +71,7 @@ public class StartConsumptionEndpoint : BaseEndpoint .Replace("{libraryId}", libraryId, StringComparison.Ordinal) .Replace("{mediaKind}", mediaKind, StringComparison.Ordinal) .Replace("{mediaItemId}", mediaItemId, StringComparison.Ordinal); - ConsumptionRecordDto record = await _apiHttpClient.PostAsync(endpoint, request, cancellationToken).ConfigureAwait(false); + ConsumptionRecordDto record = await _apiHttpClient.PostAsync(endpoint, cancellationToken).ConfigureAwait(false); return JsonSuccess(record); } } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpoint.cs index 9fb09752..899edfd1 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpoint.cs @@ -3,7 +3,6 @@ using FastEndpoints; using Lumina.Presentation.Web.Common.Api; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Endpoints.Common; -using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using System; using System.Threading; @@ -15,7 +14,7 @@ namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.DeletePlaylist; /// /// API endpoint for the /{culture}/playlists/item/{playlistId}/api-delete-playlist route. /// -public class DeletePlaylistEndpoint : BaseEndpoint +public class DeletePlaylistEndpoint : BaseEndpoint { private readonly IApiHttpClient _apiHttpClient; @@ -46,7 +45,7 @@ public class DeletePlaylistEndpoint : BaseEndpoint /// The request object. /// Cancellation token that can be used to stop the execution. - public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) { // The route value is normalized to a Guid before it is substituted into the upstream URL, so that a crafted value can never escape its URL segment. string routePlaylistId = HttpContext.Request.RouteValues["playlistId"]?.ToString() ?? string.Empty; diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpoint.cs index 3931a8ff..9e47e0b3 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpoint.cs @@ -5,7 +5,6 @@ using Lumina.Presentation.Web.Common.Authorization; using Lumina.Presentation.Web.Common.Requests.Plugins; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Endpoints.Common; -using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using System.Threading; using System.Threading.Tasks; @@ -50,7 +49,7 @@ public class UpdatePluginSettingsEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(UpdatePluginSettingsRequest request, CancellationToken cancellationToken) { - await _apiHttpClient.PutAsync(ApiRoutes.Plugins.UPDATE_PLUGIN_SETTINGS.Replace("{pluginId}", request.PluginId.ToString()), request, cancellationToken).ConfigureAwait(false); + await _apiHttpClient.PutIgnoringResponseAsync(ApiRoutes.Plugins.UPDATE_PLUGIN_SETTINGS.Replace("{pluginId}", request.PluginId.ToString()), request, cancellationToken).ConfigureAwait(false); return JsonSuccess(); } } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpoint.cs index 8c0be3be..6d0ec20a 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpoint.cs @@ -4,7 +4,6 @@ using Lumina.Presentation.Web.Common.Api; using Lumina.Presentation.Web.Common.DTO.UsersManagement; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Endpoints.Common; -using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using System.Threading; using System.Threading.Tasks; @@ -48,7 +47,7 @@ public class UpdatePlaybackStateEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(PlaybackStateDto request, CancellationToken cancellationToken) { - await _apiHttpClient.PutAsync(ApiRoutes.Users.UPDATE_PLAYBACK_STATE, request, cancellationToken).ConfigureAwait(false); + await _apiHttpClient.PutIgnoringResponseAsync(ApiRoutes.Users.UPDATE_PLAYBACK_STATE, request, cancellationToken).ConfigureAwait(false); return JsonSuccess(new { isUpdated = true }); } } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpoint.cs index 1dd83b01..b3e8f74d 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpoint.cs @@ -5,7 +5,6 @@ using Lumina.Presentation.Web.Common.DTO.UsersManagement; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Common.Services; using Lumina.Presentation.Web.Core.Endpoints.Common; -using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using System; using System.Security.Claims; @@ -54,7 +53,7 @@ public class UpdateUserSettingsEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(UserSettingsDto request, CancellationToken cancellationToken) { - await _apiHttpClient.PutAsync(ApiRoutes.Users.UPDATE_USER_SETTINGS, request, cancellationToken).ConfigureAwait(false); + await _apiHttpClient.PutIgnoringResponseAsync(ApiRoutes.Users.UPDATE_USER_SETTINGS, request, cancellationToken).ConfigureAwait(false); // Keep the per-user theme cache preference in sync with the stored settings, so the handler applies it immediately. Guid? userId = GetCurrentUserId(); diff --git a/src/Lumina.Presentation.Web/Core/Themes/ThemeService.cs b/src/Lumina.Presentation.Web/Core/Themes/ThemeService.cs index 42ff8bb0..da63cf7b 100644 --- a/src/Lumina.Presentation.Web/Core/Themes/ThemeService.cs +++ b/src/Lumina.Presentation.Web/Core/Themes/ThemeService.cs @@ -3,6 +3,7 @@ using Lumina.Presentation.Web.Common.Api; using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; using Lumina.Presentation.Web.Common.DTO.Themes; using Lumina.Presentation.Web.Common.Enums.Themes; +using Lumina.Presentation.Web.Common.Requests.Themes; using Lumina.Presentation.Web.Common.Routes; using System.Collections.Generic; using System.IO; @@ -68,7 +69,7 @@ public sealed class ThemeService /// Cancellation token that can be used to stop the execution. public async Task SetCurrentThemeAsync(string themeId, CancellationToken cancellationToken = default) { - await _apiHttpClient.PutAsync(ApiRoutes.Themes.SET_CURRENT_THEME, new { ThemeId = themeId }, cancellationToken).ConfigureAwait(false); + await _apiHttpClient.PutIgnoringResponseAsync(ApiRoutes.Themes.SET_CURRENT_THEME, new SetCurrentThemeRequest(themeId), cancellationToken).ConfigureAwait(false); } /// @@ -101,7 +102,7 @@ public sealed class ThemeService /// Cancellation token that can be used to stop the execution. public async Task RestoreThemeAsync(string themeId, CancellationToken cancellationToken = default) { - await _apiHttpClient.PostAsync(ApiRoutes.Themes.RESTORE_THEME.Replace("{themeId}", themeId), new { }, cancellationToken).ConfigureAwait(false); + await _apiHttpClient.PostIgnoringResponseAsync(ApiRoutes.Themes.RESTORE_THEME.Replace("{themeId}", themeId), cancellationToken).ConfigureAwait(false); } /// diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/StubApiHttpClient.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/StubApiHttpClient.cs index ac9c82b8..dd6db315 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/StubApiHttpClient.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/StubApiHttpClient.cs @@ -27,9 +27,15 @@ public class StubApiHttpClient : IApiHttpClient private readonly Dictionary> _getResponseFactories = []; private readonly Dictionary> _postResponseFactories = []; private readonly Dictionary> _putResponseFactories = []; + private readonly Dictionary _postExceptions = []; + private readonly Dictionary _putExceptions = []; + private readonly HashSet _postBodylessSuccessEndpoints = []; + private readonly Dictionary _postPayloadTypes = []; + private readonly Dictionary _putPayloadTypes = []; private readonly HashSet _deleteSuccessEndpoints = []; private readonly Dictionary _deleteExceptions = []; private BlobDataDto? _blobResponse; + private ApiException? _blobException; /// /// Gets the authorization response returned for the auth/get-authorization endpoint. @@ -121,7 +127,7 @@ public class StubApiHttpClient : IApiHttpClient /// The exception to throw. public void RegisterPostException(string endpoint, ApiException exception) { - _postResponseFactories[endpoint] = _ => throw exception; + _postExceptions[endpoint] = exception; } /// @@ -141,7 +147,7 @@ public class StubApiHttpClient : IApiHttpClient /// The exception to throw. public void RegisterPutException(string endpoint, ApiException exception) { - _putResponseFactories[endpoint] = _ => throw exception; + _putExceptions[endpoint] = exception; } /// @@ -193,6 +199,44 @@ public class StubApiHttpClient : IApiHttpClient _blobResponse = blob; } + /// + /// Registers the exception thrown when a blob endpoint is called. + /// + /// The exception to throw. + public void RegisterBlobException(ApiException exception) + { + _blobException = exception; + } + + /// + /// Registers the specified POST endpoint as accepting a bodyless request without returning a response body. + /// + /// The API endpoint for which to register success. + public void RegisterPostSuccess(string endpoint) + { + _postBodylessSuccessEndpoints.Add(endpoint); + } + + /// + /// Registers the specified POST endpoint as accepting a payload of type without returning a response body. + /// + /// The expected type of the payload content. + /// The API endpoint for which to register the payload type. + public void RegisterPostPayload(string endpoint) + { + _postPayloadTypes[endpoint] = typeof(TModel); + } + + /// + /// Registers the specified PUT endpoint as accepting a payload of type without returning a response body. + /// + /// The expected type of the payload content. + /// The API endpoint for which to register the payload type. + public void RegisterPutPayload(string endpoint) + { + _putPayloadTypes[endpoint] = typeof(TModel); + } + /// /// Resets all registered responses and captured requests, keeping only the default responses. /// @@ -201,9 +245,15 @@ public class StubApiHttpClient : IApiHttpClient _getResponseFactories.Clear(); _postResponseFactories.Clear(); _putResponseFactories.Clear(); + _postExceptions.Clear(); + _putExceptions.Clear(); + _postBodylessSuccessEndpoints.Clear(); + _postPayloadTypes.Clear(); + _putPayloadTypes.Clear(); _deleteSuccessEndpoints.Clear(); _deleteExceptions.Clear(); _blobResponse = null; + _blobException = null; AuthorizationException = null; GetEndpointsCalled.Clear(); PostRequests.Clear(); @@ -252,9 +302,11 @@ public class StubApiHttpClient : IApiHttpClient /// /// The API endpoint where the request is being sent. /// Cancellation token that can be used to stop the execution. - /// A model containing the deserialized blob. + /// A model containing the raw blob bytes and their content type. public Task GetBlobAsync(string endpoint, CancellationToken cancellationToken = default) { + if (_blobException is not null) + throw _blobException; if (_blobResponse is not null) return Task.FromResult(_blobResponse); throw new NotSupportedException("Blob retrieval is not supported by the test stub."); @@ -275,18 +327,37 @@ public class StubApiHttpClient : IApiHttpClient throw new ApiException(null, System.Net.HttpStatusCode.InternalServerError, endpoint); } + /// + /// Sends a PUT request to the specified as an asynchronous operation, discarding the response content. + /// + /// The expected type of the payload content. + /// The API endpoint where the request is being sent. + /// The data to be serialized and sent to the API. + /// Cancellation token that can be used to stop the execution. + public Task PutIgnoringResponseAsync(string endpoint, TModel data, CancellationToken cancellationToken = default) + { + PutRequests.Add((endpoint, data)); + if (_putExceptions.TryGetValue(endpoint, out ApiException? exception)) + throw exception; + if (_putPayloadTypes.TryGetValue(endpoint, out Type? expectedType) && expectedType == typeof(TModel)) + return Task.CompletedTask; + throw new InvalidOperationException($"No PUT payload of type '{typeof(TModel).Name}' is registered for the endpoint '{endpoint}'."); + } + /// /// Sends a PUT request to the specified as an asynchronous operation and returns the result. /// /// The expected type of the response content. /// The expected type of the payload content. /// The API endpoint where the request is being sent. - /// The data to be serialized and send to the API. + /// The data to be serialized and sent to the API. /// Cancellation token that can be used to stop the execution. /// The deserialized response containing the result of the PUT request. public Task PutAsync(string endpoint, TModel data, CancellationToken cancellationToken = default) { PutRequests.Add((endpoint, data)); + if (_putExceptions.TryGetValue(endpoint, out ApiException? exception)) + throw exception; if (_putResponseFactories.TryGetValue(endpoint, out Func? responseFactory)) return Task.FromResult((TResponse)responseFactory(data!)); throw new InvalidOperationException($"No PUT response is registered for the endpoint '{endpoint}'."); @@ -305,6 +376,8 @@ public class StubApiHttpClient : IApiHttpClient public Task PutMultipartAsync(string endpoint, Stream? fileStream, string? fileName, string fieldName, CancellationToken cancellationToken = default) { PutRequests.Add((endpoint, fileName)); + if (_putExceptions.TryGetValue(endpoint, out ApiException? exception)) + throw exception; if (_putResponseFactories.TryGetValue(endpoint, out Func? responseFactory)) return Task.FromResult((TResponse)responseFactory(fileName)); throw new InvalidOperationException($"No PUT response is registered for the endpoint '{endpoint}'."); @@ -323,23 +396,78 @@ public class StubApiHttpClient : IApiHttpClient public Task PostMultipartAsync(string endpoint, Stream fileStream, string fileName, string fieldName, CancellationToken cancellationToken = default) { PostRequests.Add((endpoint, fileName)); + if (_postExceptions.TryGetValue(endpoint, out ApiException? exception)) + throw exception; if (_postResponseFactories.TryGetValue(endpoint, out Func? responseFactory)) return Task.FromResult((TResponse)responseFactory(fileName)); throw new InvalidOperationException($"No POST response is registered for the endpoint '{endpoint}'."); } + /// + /// Sends a POST request without a payload to the specified as an asynchronous operation, discarding the response content. + /// + /// The API endpoint where the request is being sent. + /// Cancellation token that can be used to stop the execution. + public Task PostIgnoringResponseAsync(string endpoint, CancellationToken cancellationToken = default) + { + PostRequests.Add((endpoint, null)); + if (_postExceptions.TryGetValue(endpoint, out ApiException? exception)) + throw exception; + if (_postBodylessSuccessEndpoints.Contains(endpoint)) + return Task.CompletedTask; + throw new InvalidOperationException($"No bodyless POST success is registered for the endpoint '{endpoint}'."); + } + + /// + /// Sends a POST request without a payload to the specified as an asynchronous operation and returns the result. + /// + /// The expected type of the response content. + /// The API endpoint where the request is being sent. + /// Cancellation token that can be used to stop the execution. + /// The registered response. + public Task PostAsync(string endpoint, CancellationToken cancellationToken = default) + { + PostRequests.Add((endpoint, null)); + if (_postExceptions.TryGetValue(endpoint, out ApiException? exception)) + throw exception; + if (_postResponseFactories.TryGetValue(endpoint, out Func? responseFactory)) + return Task.FromResult((TResponse)responseFactory(new object())); + if (endpoint == ApiRoutes.Authentication.LOGIN_ACCOUNT) + return Task.FromResult((TResponse)(object)LoginResponse); + throw new InvalidOperationException($"No POST response is registered for the endpoint '{endpoint}'."); + } + + /// + /// Sends a POST request to the specified as an asynchronous operation, discarding the response content. + /// + /// The expected type of the payload content. + /// The API endpoint where the request is being sent. + /// The data to be serialized and sent to the API. + /// Cancellation token that can be used to stop the execution. + public Task PostIgnoringResponseAsync(string endpoint, TModel data, CancellationToken cancellationToken = default) + { + PostRequests.Add((endpoint, data)); + if (_postExceptions.TryGetValue(endpoint, out ApiException? exception)) + throw exception; + if (_postPayloadTypes.TryGetValue(endpoint, out Type? expectedType) && expectedType == typeof(TModel)) + return Task.CompletedTask; + throw new InvalidOperationException($"No POST payload of type '{typeof(TModel).Name}' is registered for the endpoint '{endpoint}'."); + } + /// /// Sends a POST request to the specified as an asynchronous operation and returns the result. /// /// The expected type of the response content. /// The expected type of the payload content. /// The API endpoint where the request is being sent. - /// The data to be serialized and send to the API. + /// The data to be serialized and sent to the API. /// Cancellation token that can be used to stop the execution. /// The deserialized response containing the result of the POST request. public Task PostAsync(string endpoint, TModel data, CancellationToken cancellationToken = default) { PostRequests.Add((endpoint, data)); + if (_postExceptions.TryGetValue(endpoint, out ApiException? exception)) + throw exception; if (_postResponseFactories.TryGetValue(endpoint, out Func? responseFactory)) return Task.FromResult((TResponse)responseFactory(data!)); if (endpoint == ApiRoutes.Authentication.LOGIN_ACCOUNT) diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpointTests.cs index c7938435..62995325 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpointTests.cs @@ -4,7 +4,6 @@ using Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler.FireScheduledJob; using Lumina.Presentation.Web.Fixtures.Common.Requests.Scheduling; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Lumina.Presentation.Web.IntegrationTests.Common.Setup; -using System; using System.Diagnostics.CodeAnalysis; using System.Net; using System.Net.Http; @@ -41,11 +40,11 @@ public class FireScheduledJobEndpointTests : IClassFixture _apiFactory.ApiClientStub.Reset(); FireScheduledJobRequest request = _fireScheduledJobRequestFixture.Create(); string expectedEndpoint = $"scheduled-jobs/{request.ScheduledJobId}/fire"; - _apiFactory.ApiClientStub.RegisterPutResponseFactory(expectedEndpoint, _ => new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); + _apiFactory.ApiClientStub.RegisterPutPayload(expectedEndpoint); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); HttpRequestMessage fireRequest = new(HttpMethod.Put, $"/en-us/admin/api-scheduled-jobs/{request.ScheduledJobId}/fire") { - Content = JsonContent.Create(new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()) + Content = JsonContent.Create(request) }; fireRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); fireRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpointTests.cs index 2ed51ce3..cc4c725c 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpointTests.cs @@ -40,11 +40,11 @@ public class StartScheduledJobEndpointTests : IClassFixture _apiFactory.ApiClientStub.Reset(); StartScheduledJobRequest request = _startScheduledJobRequestFixture.Create(); string expectedEndpoint = $"scheduled-jobs/{request.ScheduledJobId}/start"; - _apiFactory.ApiClientStub.RegisterPutResponseFactory(expectedEndpoint, _ => new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); + _apiFactory.ApiClientStub.RegisterPutPayload(expectedEndpoint); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); HttpRequestMessage startRequest = new(HttpMethod.Put, $"/en-us/admin/api-scheduled-jobs/{request.ScheduledJobId}/start") { - Content = JsonContent.Create(new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()) + Content = JsonContent.Create(request) }; startRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); startRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpointTests.cs index ab8c19f4..c0f56d59 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpointTests.cs @@ -40,11 +40,11 @@ public class StopScheduledJobEndpointTests : IClassFixture _apiFactory.ApiClientStub.Reset(); StopScheduledJobRequest request = _stopScheduledJobRequestFixture.Create(); string expectedEndpoint = $"scheduled-jobs/{request.ScheduledJobId}/stop"; - _apiFactory.ApiClientStub.RegisterPutResponseFactory(expectedEndpoint, _ => new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); + _apiFactory.ApiClientStub.RegisterPutPayload(expectedEndpoint); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); HttpRequestMessage stopRequest = new(HttpMethod.Put, $"/en-us/admin/api-scheduled-jobs/{request.ScheduledJobId}/stop") { - Content = JsonContent.Create(new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()) + Content = JsonContent.Create(request) }; stopRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); stopRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpointTests.cs index 942317b2..02698e1c 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpointTests.cs @@ -39,7 +39,7 @@ public class UpdateSchedulerDisplayPreferencesEndpointTests : IClassFixture new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); + _apiFactory.ApiClientStub.RegisterPutPayload("scheduled-jobs/display-preferences"); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/admin/api-scheduled-jobs/display-preferences") { diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpointTests.cs index 706407da..a2b555c1 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpointTests.cs @@ -1,10 +1,7 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.DTO.Themes; using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.RestoreTheme; -using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Lumina.Presentation.Web.IntegrationTests.Common.Setup; -using System; using System.Diagnostics.CodeAnalysis; using System.Net; using System.Net.Http; @@ -23,7 +20,6 @@ namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Themes.R public class RestoreThemeEndpointTests : IClassFixture { private readonly LuminaWebFactory _apiFactory; - private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -40,7 +36,7 @@ public class RestoreThemeEndpointTests : IClassFixture // Arrange _apiFactory.ApiClientStub.Reset(); const string THEME_ID = "test-theme"; - _apiFactory.ApiClientStub.RegisterPostResponse($"themes/{THEME_ID}/restore", _themeResponseDtoFixture.Create()); + _apiFactory.ApiClientStub.RegisterPostSuccess($"themes/{THEME_ID}/restore"); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); HttpRequestMessage restoreRequest = new(HttpMethod.Post, $"/en-us/admin/themes/api-restore-theme/{THEME_ID}") { diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs index 5c7999bc..c85f2bb1 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs @@ -1,11 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.Requests.Themes; using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.SetCurrentTheme; -using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; using Lumina.Presentation.Web.Fixtures.Common.Requests.Themes; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Lumina.Presentation.Web.IntegrationTests.Common.Setup; -using System; using System.Diagnostics.CodeAnalysis; using System.Net; using System.Net.Http; @@ -24,7 +22,6 @@ namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Themes.S public class SetCurrentThemeEndpointTests : IClassFixture { private readonly LuminaWebFactory _apiFactory; - private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new(); private readonly SetCurrentThemeRequestFixture _setCurrentThemeRequestFixture = new(); /// @@ -42,7 +39,7 @@ public class SetCurrentThemeEndpointTests : IClassFixture // Arrange _apiFactory.ApiClientStub.Reset(); const string THEME_ID = "test-theme"; - _apiFactory.ApiClientStub.RegisterPutResponse("themes/current", _themeResponseDtoFixture.Create()); + _apiFactory.ApiClientStub.RegisterPutPayload("themes/current"); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); HttpRequestMessage setCurrentThemeRequest = new(HttpMethod.Put, "/en-us/admin/themes/api-set-current-theme") { diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/RestoreMusicAlbum/RestoreMusicAlbumEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/RestoreMusicAlbum/RestoreMusicAlbumEndpointTests.cs index d62636e0..b44a729d 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/RestoreMusicAlbum/RestoreMusicAlbumEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/RestoreMusicAlbum/RestoreMusicAlbumEndpointTests.cs @@ -40,7 +40,7 @@ public class RestoreMusicAlbumEndpointTests : IClassFixture Guid libraryId = Guid.NewGuid(); Guid artistId = Guid.NewGuid(); Guid albumId = Guid.NewGuid(); - _apiFactory.ApiClientStub.RegisterPostResponse($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/restore", new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); + _apiFactory.ApiClientStub.RegisterPostSuccess($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/restore"); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); HttpRequestMessage restoreRequest = CreateRestoreRequest(artistId, albumId, libraryId); restoreRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/RestoreMusicArtist/RestoreMusicArtistEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/RestoreMusicArtist/RestoreMusicArtistEndpointTests.cs index fce2e3ea..185acb81 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/RestoreMusicArtist/RestoreMusicArtistEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/RestoreMusicArtist/RestoreMusicArtistEndpointTests.cs @@ -39,7 +39,7 @@ public class RestoreMusicArtistEndpointTests : IClassFixture _apiFactory.ApiClientStub.Reset(); Guid libraryId = Guid.NewGuid(); Guid artistId = Guid.NewGuid(); - _apiFactory.ApiClientStub.RegisterPostResponse($"libraries/{libraryId}/artists/{artistId}/restore", new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); + _apiFactory.ApiClientStub.RegisterPostSuccess($"libraries/{libraryId}/artists/{artistId}/restore"); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); HttpRequestMessage restoreRequest = CreateRestoreRequest(artistId, libraryId); restoreRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/RestoreMusicTrack/RestoreMusicTrackEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/RestoreMusicTrack/RestoreMusicTrackEndpointTests.cs index 76f7dc12..304b5aff 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/RestoreMusicTrack/RestoreMusicTrackEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/RestoreMusicTrack/RestoreMusicTrackEndpointTests.cs @@ -41,7 +41,7 @@ public class RestoreMusicTrackEndpointTests : IClassFixture Guid artistId = Guid.NewGuid(); Guid albumId = Guid.NewGuid(); Guid trackId = Guid.NewGuid(); - _apiFactory.ApiClientStub.RegisterPostResponse($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/restore", new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); + _apiFactory.ApiClientStub.RegisterPostSuccess($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/restore"); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); HttpRequestMessage restoreRequest = CreateRestoreRequest(artistId, albumId, trackId, libraryId); restoreRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointTests.cs index fc6e1bdc..48fa5826 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointTests.cs @@ -35,7 +35,7 @@ public class CancelLibrariesScanEndpointTests : IClassFixture { // Arrange _apiFactory.ApiClientStub.Reset(); - _apiFactory.ApiClientStub.RegisterPostResponseFactory("libraries/scans/cancel", _ => new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); + _apiFactory.ApiClientStub.RegisterPostSuccess("libraries/scans/cancel"); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); HttpRequestMessage cancelRequest = CreateCancelRequest("/en-us/libraries/manage/api-cancel-libraries-scan"); cancelRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointTests.cs index f34bd3e2..d6052347 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointTests.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Library.Management; using Lumina.Presentation.Web.Core.Endpoints.Library.Management.CancelLibraryScan; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Lumina.Presentation.Web.IntegrationTests.Common.Setup; @@ -38,7 +39,7 @@ public class CancelLibraryScanEndpointTests : IClassFixture _apiFactory.ApiClientStub.Reset(); Guid libraryId = Guid.NewGuid(); Guid scanId = Guid.NewGuid(); - _apiFactory.ApiClientStub.RegisterPostResponseFactory($"libraries/{libraryId}/scans/{scanId}/cancel", _ => new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); + _apiFactory.ApiClientStub.RegisterPostPayload($"libraries/{libraryId}/scans/{scanId}/cancel"); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); HttpRequestMessage cancelRequest = CreateCancelRequest($"/en-us/libraries/manage/{libraryId}/api-cancel-library-scan/{scanId}"); cancelRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); @@ -52,7 +53,11 @@ public class CancelLibraryScanEndpointTests : IClassFixture Assert.Equal(HttpStatusCode.OK, response.StatusCode); using JsonDocument json = JsonDocument.Parse(content); Assert.True(json.RootElement.GetProperty("success").GetBoolean()); - Assert.Contains(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == $"libraries/{libraryId}/scans/{scanId}/cancel"); + Assert.Contains(_apiFactory.ApiClientStub.PostRequests, postRequest => + postRequest.Endpoint == $"libraries/{libraryId}/scans/{scanId}/cancel" && + postRequest.Data is CancelLibraryScanRequest forwardedRequest && + forwardedRequest.LibraryId == libraryId && + forwardedRequest.ScanId == scanId); } /// diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/RestoreBook/RestoreBookEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/RestoreBook/RestoreBookEndpointTests.cs index 27aa079d..43401c10 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/RestoreBook/RestoreBookEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/RestoreBook/RestoreBookEndpointTests.cs @@ -39,7 +39,7 @@ public class RestoreBookEndpointTests : IClassFixture _apiFactory.ApiClientStub.Reset(); Guid libraryId = Guid.NewGuid(); Guid bookId = Guid.NewGuid(); - _apiFactory.ApiClientStub.RegisterPostResponse($"libraries/{libraryId}/books/{bookId}/restore", new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); + _apiFactory.ApiClientStub.RegisterPostSuccess($"libraries/{libraryId}/books/{bookId}/restore"); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); HttpRequestMessage restoreRequest = CreateRestoreRequest(bookId, libraryId); restoreRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs index 41fad1e6..9a0ac295 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs @@ -40,7 +40,7 @@ public class UpdatePluginSettingsEndpointTests : IClassFixture _apiFactory.ApiClientStub.Reset(); UpdatePluginSettingsRequest request = _updatePluginSettingsRequestFixture.Create(); string expectedEndpoint = $"plugins/{request.PluginId}/settings"; - _apiFactory.ApiClientStub.RegisterPutResponseFactory(expectedEndpoint, _ => new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); + _apiFactory.ApiClientStub.RegisterPutPayload(expectedEndpoint); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/admin/manage-plugins/api-update-plugin-settings") { diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpointTests.cs index d3338969..fb5f799f 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpointTests.cs @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Presentation.Web.Common.DTO.UsersManagement; -using Lumina.Presentation.Web.Common.Requests.Common; using Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.UpdatePlaybackState; using Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; @@ -39,7 +38,7 @@ public class UpdatePlaybackStateEndpointTests : IClassFixture { // Arrange _apiFactory.ApiClientStub.Reset(); - _apiFactory.ApiClientStub.RegisterPutResponseFactory("users/me/settings/playback-state", _ => new EmptyRequest()); + _apiFactory.ApiClientStub.RegisterPutPayload("users/me/settings/playback-state"); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); PlaybackStateDto state = _playbackStateDtoFixture.Create(volume: 0.35, isMuted: true); @@ -61,7 +60,7 @@ public class UpdatePlaybackStateEndpointTests : IClassFixture { // Arrange _apiFactory.ApiClientStub.Reset(); - _apiFactory.ApiClientStub.RegisterPutResponseFactory("users/me/settings/playback-state", _ => new EmptyRequest()); + _apiFactory.ApiClientStub.RegisterPutPayload("users/me/settings/playback-state"); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); PlaybackStateDto state = _playbackStateDtoFixture.Create(volume: 0.0, isMuted: false); diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs index a94dd321..2e681747 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs @@ -1,7 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Presentation.Web.Common.DTO.UsersManagement; using Lumina.Presentation.Web.Common.Enums.AudioLibrary; -using Lumina.Presentation.Web.Common.Requests.Common; using Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.UpdateUserSettings; using Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; @@ -40,7 +39,7 @@ public class UpdateUserSettingsEndpointTests : IClassFixture { // Arrange _apiFactory.ApiClientStub.Reset(); - _apiFactory.ApiClientStub.RegisterPutResponseFactory("users/me/settings", _ => new EmptyRequest()); + _apiFactory.ApiClientStub.RegisterPutPayload("users/me/settings"); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); UserSettingsDto settings = _userSettingsDtoFixture.Create(isThemeCachingEnabled: true); @@ -62,7 +61,7 @@ public class UpdateUserSettingsEndpointTests : IClassFixture { // Arrange _apiFactory.ApiClientStub.Reset(); - _apiFactory.ApiClientStub.RegisterPutResponseFactory("users/me/settings", _ => new EmptyRequest()); + _apiFactory.ApiClientStub.RegisterPutPayload("users/me/settings"); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); UserSettingsDto settings = _userSettingsDtoFixture.Create( vuMeterOrientation: VuMeterOrientation.Horizontal, diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/RestoreMusicAlbum/RestoreMusicAlbumEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/RestoreMusicAlbum/RestoreMusicAlbumEndpointTests.cs index 6ac72e1e..d66256f1 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/RestoreMusicAlbum/RestoreMusicAlbumEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/RestoreMusicAlbum/RestoreMusicAlbumEndpointTests.cs @@ -40,7 +40,7 @@ public class RestoreMusicAlbumEndpointTests : IClassFixture _apiFactory.ApiClientStub.Reset(); Guid libraryId = Guid.NewGuid(); string normalizedId = Guid.Empty.ToString(); - _apiFactory.ApiClientStub.RegisterPostResponse($"libraries/{libraryId}/artists/{normalizedId}/albums/{normalizedId}/restore", new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); + _apiFactory.ApiClientStub.RegisterPostSuccess($"libraries/{libraryId}/artists/{normalizedId}/albums/{normalizedId}/restore"); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); HttpRequestMessage restoreRequest = CreateRestoreRequest(maliciousId, maliciousId, libraryId.ToString()); restoreRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); @@ -67,7 +67,7 @@ public class RestoreMusicAlbumEndpointTests : IClassFixture Guid artistId = Guid.NewGuid(); Guid albumId = Guid.NewGuid(); string normalizedId = Guid.Empty.ToString(); - _apiFactory.ApiClientStub.RegisterPostResponse($"libraries/{normalizedId}/artists/{artistId}/albums/{albumId}/restore", new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); + _apiFactory.ApiClientStub.RegisterPostSuccess($"libraries/{normalizedId}/artists/{artistId}/albums/{albumId}/restore"); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); HttpRequestMessage restoreRequest = CreateRestoreRequest(artistId.ToString(), albumId.ToString(), maliciousLibraryId); restoreRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/RestoreMusicArtist/RestoreMusicArtistEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/RestoreMusicArtist/RestoreMusicArtistEndpointTests.cs index 82f93ed0..8a482489 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/RestoreMusicArtist/RestoreMusicArtistEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/RestoreMusicArtist/RestoreMusicArtistEndpointTests.cs @@ -40,7 +40,7 @@ public class RestoreMusicArtistEndpointTests : IClassFixture _apiFactory.ApiClientStub.Reset(); Guid libraryId = Guid.NewGuid(); string normalizedId = Guid.Empty.ToString(); - _apiFactory.ApiClientStub.RegisterPostResponse($"libraries/{libraryId}/artists/{normalizedId}/restore", new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); + _apiFactory.ApiClientStub.RegisterPostSuccess($"libraries/{libraryId}/artists/{normalizedId}/restore"); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); HttpRequestMessage restoreRequest = CreateRestoreRequest(maliciousId, libraryId.ToString()); restoreRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); @@ -66,7 +66,7 @@ public class RestoreMusicArtistEndpointTests : IClassFixture _apiFactory.ApiClientStub.Reset(); Guid artistId = Guid.NewGuid(); string normalizedId = Guid.Empty.ToString(); - _apiFactory.ApiClientStub.RegisterPostResponse($"libraries/{normalizedId}/artists/{artistId}/restore", new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); + _apiFactory.ApiClientStub.RegisterPostSuccess($"libraries/{normalizedId}/artists/{artistId}/restore"); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); HttpRequestMessage restoreRequest = CreateRestoreRequest(artistId.ToString(), maliciousLibraryId); restoreRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/RestoreMusicTrack/RestoreMusicTrackEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/RestoreMusicTrack/RestoreMusicTrackEndpointTests.cs index 3f0c2305..29ce1886 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/RestoreMusicTrack/RestoreMusicTrackEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/RestoreMusicTrack/RestoreMusicTrackEndpointTests.cs @@ -2,14 +2,10 @@ using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.RestoreMusicTrack; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Lumina.Presentation.Web.SecurityTests.Common.Setup; -using System; using System.Diagnostics.CodeAnalysis; -using System.Linq; using System.Net; -using System.Net.Http; using System.Net.Http.Headers; using System.Text; -using System.Threading.Tasks; #endregion namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.RestoreMusicTrack; @@ -40,7 +36,7 @@ public class RestoreMusicTrackEndpointTests : IClassFixture _apiFactory.ApiClientStub.Reset(); Guid libraryId = Guid.NewGuid(); string normalizedId = Guid.Empty.ToString(); - _apiFactory.ApiClientStub.RegisterPostResponse($"libraries/{libraryId}/artists/{normalizedId}/albums/{normalizedId}/tracks/{normalizedId}/restore", new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); + _apiFactory.ApiClientStub.RegisterPostSuccess($"libraries/{libraryId}/artists/{normalizedId}/albums/{normalizedId}/tracks/{normalizedId}/restore"); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); HttpRequestMessage restoreRequest = CreateRestoreRequest(maliciousId, maliciousId, maliciousId, libraryId.ToString()); restoreRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); @@ -68,7 +64,7 @@ public class RestoreMusicTrackEndpointTests : IClassFixture Guid albumId = Guid.NewGuid(); Guid trackId = Guid.NewGuid(); string normalizedId = Guid.Empty.ToString(); - _apiFactory.ApiClientStub.RegisterPostResponse($"libraries/{normalizedId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/restore", new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); + _apiFactory.ApiClientStub.RegisterPostSuccess($"libraries/{normalizedId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/restore"); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); HttpRequestMessage restoreRequest = CreateRestoreRequest(artistId.ToString(), albumId.ToString(), trackId.ToString(), maliciousLibraryId); restoreRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/RestoreBook/RestoreBookEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/RestoreBook/RestoreBookEndpointTests.cs index 62cf5544..aaf203f8 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/RestoreBook/RestoreBookEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/RestoreBook/RestoreBookEndpointTests.cs @@ -36,7 +36,7 @@ public class RestoreBookEndpointTests : IClassFixture _apiFactory.ApiClientStub.Reset(); Guid libraryId = Guid.NewGuid(); string normalizedId = Guid.Empty.ToString(); - _apiFactory.ApiClientStub.RegisterPostResponse($"libraries/{libraryId}/books/{normalizedId}/restore", new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); + _apiFactory.ApiClientStub.RegisterPostSuccess($"libraries/{libraryId}/books/{normalizedId}/restore"); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); HttpRequestMessage restoreRequest = CreateRestoreRequest(maliciousId, libraryId.ToString()); restoreRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); @@ -62,7 +62,7 @@ public class RestoreBookEndpointTests : IClassFixture _apiFactory.ApiClientStub.Reset(); Guid bookId = Guid.NewGuid(); string normalizedId = Guid.Empty.ToString(); - _apiFactory.ApiClientStub.RegisterPostResponse($"libraries/{normalizedId}/books/{bookId}/restore", new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); + _apiFactory.ApiClientStub.RegisterPostSuccess($"libraries/{normalizedId}/books/{bookId}/restore"); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); HttpRequestMessage restoreRequest = CreateRestoreRequest(bookId.ToString(), maliciousLibraryId); restoreRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpointTests.cs index 94b211aa..45db72b5 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpointTests.cs @@ -1,10 +1,13 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.Exceptions; using Lumina.Presentation.Web.Core.Endpoints.Themes.ThemeAssets; using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Lumina.Presentation.Web.SecurityTests.Common.Setup; using System.Diagnostics.CodeAnalysis; using System.Net; +using System.Net.Http.Headers; #endregion namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Themes.ThemeAssets; @@ -47,6 +50,27 @@ public class ThemeAssetsEndpointTests : IClassFixture Assert.Equal(expectedBytes, content); } + [Fact] + public async Task ThemeAssets_WhenCraftedPathLooksLikeAuthorizationCheck_ShouldNotSignOutAuthenticatedUser() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterBlobException(new ApiException( + new ProblemDetailsDto { Title = "General.NotFound", Status = 404, Detail = "ThemeNotFound" }, + HttpStatusCode.NotFound, + "/api/v1/themes/test-theme/assets/auth/get-authorization")); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage request = new(HttpMethod.Get, "/theme-assets/test-theme/auth/get-authorization"); + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(request); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("/en-us/not-found", response.Headers.Location!.ToString()); + } + [Theory] [InlineData("' OR '1'='1")] // Basic SQL injection. [InlineData("'; DROP TABLE Themes--")] // Destructive injection. diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpointTests.cs index 372ed035..79ddae1e 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpointTests.cs @@ -1,17 +1,13 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Presentation.Web.Common.DTO.UsersManagement; -using Lumina.Presentation.Web.Common.Requests.Common; using Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.UpdatePlaybackState; using Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Lumina.Presentation.Web.SecurityTests.Common.Setup; -using System; using System.Diagnostics.CodeAnalysis; using System.Net; -using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; -using System.Threading.Tasks; #endregion namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Tools.Settings.UpdatePlaybackState; @@ -88,7 +84,7 @@ public class UpdatePlaybackStateEndpointTests : IClassFixture { // Arrange _apiFactory.ApiClientStub.Reset(); - _apiFactory.ApiClientStub.RegisterPutResponseFactory("users/me/settings/playback-state", _ => new EmptyRequest()); + _apiFactory.ApiClientStub.RegisterPutPayload("users/me/settings/playback-state"); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); PlaybackStateDto state = _playbackStateDtoFixture.Create(volume: 0.35, isMuted: true); HttpRequestMessage updateRequest = new(HttpMethod.Post, "/en-us/tools/settings/api-update-playback-state") diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Api/ApiHttpClientTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Api/ApiHttpClientTests.cs index 0b91d09d..7b780284 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Api/ApiHttpClientTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Api/ApiHttpClientTests.cs @@ -117,6 +117,91 @@ public class ApiHttpClientTests Assert.Contains("testuser", messageHandler.RequestBodies[0]); } + [Fact] + public async Task PostAsync_WhenCalledWithoutPayload_ShouldDeserializeResponse() + { + // Arrange + TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, """{"success":true}""")); + ApiHttpClient sut = CreateSut(messageHandler); + + // Act + SuccessResponse result = await sut.PostAsync("libraries", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal(HttpMethod.Post, messageHandler.Requests[0].Method); + Assert.Null(messageHandler.Requests[0].Content); + } + + [Fact] + public async Task PostIgnoringResponseAsync_WhenCalledWithoutPayload_ShouldSendBodylessRequestAndIgnoreNonEmptyResponse() + { + // Arrange + TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, "{}")); + ApiHttpClient sut = CreateSut(messageHandler); + + // Act + await sut.PostIgnoringResponseAsync("libraries/1", CancellationToken.None); + + // Assert + Assert.Equal(HttpMethod.Post, messageHandler.Requests[0].Method); + Assert.Null(messageHandler.Requests[0].Content); + } + + [Fact] + public async Task PostIgnoringResponseAsync_WhenUserHasTokenClaim_ShouldSendAuthorizationHeader() + { + // Arrange + TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, "{}")); + ApiHttpClient sut = CreateSut(messageHandler, token: "test-jwt-token"); + + // Act + await sut.PostIgnoringResponseAsync("libraries/1", CancellationToken.None); + + // Assert + Assert.Equal("Bearer", messageHandler.Requests[0].Headers.Authorization!.Scheme); + Assert.Equal("test-jwt-token", messageHandler.Requests[0].Headers.Authorization!.Parameter); + } + + [Fact] + public async Task PutIgnoringResponseAsync_WhenCalledWithPayload_ShouldSerializePayloadAndIgnoreNonEmptyResponse() + { + // Arrange + TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, """{"updated":true}""")); + ApiHttpClient sut = CreateSut(messageHandler); + + // Act + await sut.PutIgnoringResponseAsync("libraries/1", new { title = "Library One" }, CancellationToken.None); + + // Assert + Assert.Contains("Library One", messageHandler.RequestBodies[0]); + } + + [Fact] + public async Task PostIgnoringResponseAsync_WhenApiReturnsError_ShouldThrowApiExceptionWithProblemDetails() + { + // Arrange + string problemDetailsJson = """ + { + "type": "https://tools.ietf.org/html/rfc9110#section-15.6.1", + "title": "General.Failure", + "status": 500, + "detail": "UnexpectedFailure" + } + """; + TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.InternalServerError, problemDetailsJson)); + ApiHttpClient sut = CreateSut(messageHandler); + + // Act + ApiException exception = await Assert.ThrowsAsync(() => sut.PostIgnoringResponseAsync("libraries/1", CancellationToken.None)); + + // Assert + Assert.Equal(HttpStatusCode.InternalServerError, exception.HttpStatusCode); + Assert.NotNull(exception.ProblemDetails); + Assert.Equal("General.Failure", exception.ProblemDetails!.Title); + Assert.Equal("UnexpectedFailure", exception.ProblemDetails.Detail); + } + [Fact] public async Task DeleteAsync_WhenApiReturnsError_ShouldThrowApiException() { diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Authorization/AuthorizationServiceTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Authorization/AuthorizationServiceTests.cs index 8c9a8330..9749aa6d 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Authorization/AuthorizationServiceTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Authorization/AuthorizationServiceTests.cs @@ -148,7 +148,6 @@ public class AuthorizationServiceTests [Theory] [InlineData(HttpStatusCode.Unauthorized)] [InlineData(HttpStatusCode.Forbidden)] - [InlineData(HttpStatusCode.NotFound)] public async Task HasPermissionAsync_WhenTheApiReturnsAnAuthorizationStatusDuringAPageNavigation_ShouldRethrow(HttpStatusCode statusCode) { // Arrange @@ -160,6 +159,18 @@ public class AuthorizationServiceTests await Assert.ThrowsAsync(() => _sut.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, CancellationToken.None)); } + [Fact] + public async Task HasPermissionAsync_WhenTheApiReturnsNotFoundDuringAPageNavigation_ShouldThrowCurrentUserAuthorizationException() + { + // Arrange + _httpContext.Request.Headers.Accept = "text/html"; + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(Task.FromException(new ApiException(null, HttpStatusCode.NotFound, "/api/v1/auth/get-authorization?userId=1"))); + + // Act & Assert + await Assert.ThrowsAsync(() => _sut.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, CancellationToken.None)); + } + [Fact] public async Task HasPermissionAsync_WhenTheApiReturnsAServerErrorDuringAPageNavigation_ShouldReturnFalseAndMarkTheServerUnreachable() { diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Middlewares/ExceptionHandlingMiddlewareTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Middlewares/ExceptionHandlingMiddlewareTests.cs index fb6baeb5..7da7887d 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Middlewares/ExceptionHandlingMiddlewareTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Middlewares/ExceptionHandlingMiddlewareTests.cs @@ -220,7 +220,7 @@ public class ExceptionHandlingMiddlewareTests { // Arrange DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: true, user: CreateAuthenticatedUser(), requestServices: CreateServiceProvider()); - _nextDelegate = _ => throw new ApiException(_problemDetailsDtoFixture.Create(), HttpStatusCode.NotFound, "/api/v1/auth/get-authorization?userId=1"); + _nextDelegate = _ => throw new CurrentUserAuthorizationException(_problemDetailsDtoFixture.Create(), HttpStatusCode.NotFound, "/api/v1/auth/get-authorization?userId=1"); // Act await _sut.InvokeAsync(httpContext); @@ -237,7 +237,7 @@ public class ExceptionHandlingMiddlewareTests // Arrange DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: false, culture: null, user: CreateAuthenticatedUser(), requestServices: CreateServiceProvider()); httpContext.Request.Path = "/dashboard"; - _nextDelegate = _ => throw new ApiException(_problemDetailsDtoFixture.Create(), HttpStatusCode.NotFound, "/api/v1/auth/get-authorization?userId=1"); + _nextDelegate = _ => throw new CurrentUserAuthorizationException(_problemDetailsDtoFixture.Create(), HttpStatusCode.NotFound, "/api/v1/auth/get-authorization?userId=1"); // Act await _sut.InvokeAsync(httpContext); @@ -248,6 +248,24 @@ public class ExceptionHandlingMiddlewareTests await _mockAuthenticationService.Received(1).SignOutAsync(httpContext, CookieAuthenticationDefaults.AuthenticationScheme, Arg.Any()); } + [Fact] + public async Task InvokeAsync_WhenApiExceptionNotFoundWithCraftedAuthorizationPathAndAuthenticatedPageRequest_ShouldNotSignOut() + { + // Arrange + DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: false, culture: "en-us", user: CreateAuthenticatedUser(), requestServices: CreateServiceProvider()); + httpContext.Request.Headers.Accept = "text/html"; + httpContext.Request.Path = "/en-us/theme-assets/test-theme/auth/get-authorization"; + _nextDelegate = _ => throw new ApiException(_problemDetailsDtoFixture.Create(), HttpStatusCode.NotFound, "/api/v1/themes/test-theme/assets/auth/get-authorization"); + + // Act + await _sut.InvokeAsync(httpContext); + + // Assert + Assert.Equal(StatusCodes.Status302Found, httpContext.Response.StatusCode); + Assert.Equal("/en-us/not-found", httpContext.Response.Headers.Location.ToString()); + await _mockAuthenticationService.DidNotReceive().SignOutAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + [Fact] public async Task InvokeAsync_WhenApiExceptionForbiddenAndApiRequest_ShouldWriteFailureJsonWithProblemDetail() { diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpointTests.cs index b79ee921..6a907d06 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpointTests.cs @@ -47,9 +47,9 @@ public class FireScheduledJobEndpointTests // Assert string expectedEndpoint = ApiRoutes.ScheduledJobs.FIRE_SCHEDULED_JOB.Replace("{scheduledJobId}", request.ScheduledJobId.ToString()); - await _mockApiHttpClient.Received(1).PutAsync( + await _mockApiHttpClient.Received(1).PutIgnoringResponseAsync( expectedEndpoint, - Arg.Any(), + Arg.Is(forwardedRequest => forwardedRequest.ScheduledJobId == request.ScheduledJobId), Arg.Any()); using JsonDocument jsonDocument = JsonDocument.Parse(body); Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpointTests.cs index 0d2baa18..ad743b08 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpointTests.cs @@ -47,9 +47,9 @@ public class StartScheduledJobEndpointTests // Assert string expectedEndpoint = ApiRoutes.ScheduledJobs.START_SCHEDULED_JOB.Replace("{scheduledJobId}", request.ScheduledJobId.ToString()); - await _mockApiHttpClient.Received(1).PutAsync( + await _mockApiHttpClient.Received(1).PutIgnoringResponseAsync( expectedEndpoint, - Arg.Any(), + Arg.Is(forwardedRequest => forwardedRequest.ScheduledJobId == request.ScheduledJobId), Arg.Any()); using JsonDocument jsonDocument = JsonDocument.Parse(body); Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpointTests.cs index df66d913..70d3b2e3 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpointTests.cs @@ -47,9 +47,9 @@ public class StopScheduledJobEndpointTests // Assert string expectedEndpoint = ApiRoutes.ScheduledJobs.STOP_SCHEDULED_JOB.Replace("{scheduledJobId}", request.ScheduledJobId.ToString()); - await _mockApiHttpClient.Received(1).PutAsync( + await _mockApiHttpClient.Received(1).PutIgnoringResponseAsync( expectedEndpoint, - Arg.Any(), + Arg.Is(forwardedRequest => forwardedRequest.ScheduledJobId == request.ScheduledJobId), Arg.Any()); using JsonDocument jsonDocument = JsonDocument.Parse(body); Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpointTests.cs index c956a614..8df743d5 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpointTests.cs @@ -46,7 +46,7 @@ public class UpdateSchedulerDisplayPreferencesEndpointTests string body = await JsonResultTestHelper.GetResponseBodyAsync(result); // Assert - await _mockApiHttpClient.Received(1).PutAsync( + await _mockApiHttpClient.Received(1).PutIgnoringResponseAsync( ApiRoutes.ScheduledJobs.UPDATE_DISPLAY_PREFERENCES, Arg.Is(forwardedRequest => forwardedRequest.JobTypeFilter == request.JobTypeFilter && diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpointTests.cs index c14bcc8f..3debb65e 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpointTests.cs @@ -1,7 +1,6 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; using Lumina.Presentation.Web.Common.Api; -using Lumina.Presentation.Web.Common.DTO.Themes; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.RestoreTheme; using Lumina.Presentation.Web.Core.Themes; @@ -65,7 +64,7 @@ public class RestoreThemeEndpointTests await _sut.ExecuteAsync(_restoreThemeRequestFixture.Create(themeId: themeId), CancellationToken.None); // Assert - await _mockApiHttpClient.Received(1).PostAsync(expectedEndpoint, Arg.Any(), Arg.Any()); + await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync(expectedEndpoint, Arg.Any()); } [Theory] @@ -80,6 +79,6 @@ public class RestoreThemeEndpointTests // Assert ProblemHttpResult problemResult = Assert.IsType(result); Assert.Equal(StatusCodes.Status400BadRequest, problemResult.StatusCode); - await _mockApiHttpClient.DidNotReceive().PostAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockApiHttpClient.DidNotReceive().PostIgnoringResponseAsync(Arg.Any(), Arg.Any()); } } diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs index c1c02dcc..99bce98e 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs @@ -1,11 +1,10 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; using Lumina.Presentation.Web.Common.Api; -using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.Requests.Themes; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.SetCurrentTheme; using Lumina.Presentation.Web.Core.Themes; -using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; using Lumina.Presentation.Web.Fixtures.Common.Requests.Themes; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Microsoft.AspNetCore.Http; @@ -26,7 +25,6 @@ public class SetCurrentThemeEndpointTests { private readonly IApiHttpClient _mockApiHttpClient; private readonly SetCurrentThemeEndpoint _sut; - private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new(); private readonly SetCurrentThemeRequestFixture _setCurrentThemeRequestFixture = new(); /// @@ -44,8 +42,8 @@ public class SetCurrentThemeEndpointTests { // Arrange string themeId = "editorial-paper"; - _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(_themeResponseDtoFixture.Create()); + _mockApiHttpClient.PutIgnoringResponseAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Task.CompletedTask); // Act IResult result = await _sut.ExecuteAsync(_setCurrentThemeRequestFixture.Create(themeId: themeId), CancellationToken.None); @@ -55,9 +53,9 @@ public class SetCurrentThemeEndpointTests using (System.Text.Json.JsonDocument jsonDocument = System.Text.Json.JsonDocument.Parse(body)) Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); - await _mockApiHttpClient.Received(1).PutAsync( + await _mockApiHttpClient.Received(1).PutIgnoringResponseAsync( ApiRoutes.Themes.SET_CURRENT_THEME, - Arg.Is(payload => (payload.GetType().GetProperty("ThemeId")!.GetValue(payload) as string) == themeId), + Arg.Is(payload => payload.ThemeId == themeId), Arg.Any()); } @@ -73,6 +71,6 @@ public class SetCurrentThemeEndpointTests // Assert ProblemHttpResult problemResult = Assert.IsType(result); Assert.Equal(StatusCodes.Status400BadRequest, problemResult.StatusCode); - await _mockApiHttpClient.DidNotReceive().PutAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockApiHttpClient.DidNotReceive().PutIgnoringResponseAsync(Arg.Any(), Arg.Any(), Arg.Any()); } } diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/RestoreMusicAlbum/RestoreMusicAlbumEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/RestoreMusicAlbum/RestoreMusicAlbumEndpointTests.cs index 3b212fa0..e8426b97 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/RestoreMusicAlbum/RestoreMusicAlbumEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/RestoreMusicAlbum/RestoreMusicAlbumEndpointTests.cs @@ -30,11 +30,6 @@ public class RestoreMusicAlbumEndpointTests public RestoreMusicAlbumEndpointTests() { _mockApiHttpClient = Substitute.For(); - // The restore endpoints forward a bodyless POST upstream; returning an empty request lets every test that is not about - // cancellation focus on the URL construction instead of repeating the upstream stub. - _mockApiHttpClient.PostAsync( - Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(new Web.Common.Requests.Common.EmptyRequest()); _sut = Factory.Create(_mockApiHttpClient); } @@ -56,9 +51,8 @@ public class RestoreMusicAlbumEndpointTests string body = await JsonResultTestHelper.GetResponseBodyAsync(result); // Assert - await _mockApiHttpClient.Received(1).PostAsync( + await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync( BuildExpectedEndpoint(libraryId, artistId, albumId), - Arg.Any(), Arg.Any()); using JsonDocument jsonDocument = JsonDocument.Parse(body); Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); @@ -77,9 +71,8 @@ public class RestoreMusicAlbumEndpointTests await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); // Assert - await _mockApiHttpClient.Received(1).PostAsync( + await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync( BuildExpectedEndpoint(libraryId, Guid.Empty, albumId), - Arg.Any(), Arg.Any()); } @@ -95,9 +88,8 @@ public class RestoreMusicAlbumEndpointTests await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); // Assert - await _mockApiHttpClient.Received(1).PostAsync( + await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync( BuildExpectedEndpoint(libraryId, Guid.Empty, albumId), - Arg.Any(), Arg.Any()); } @@ -113,9 +105,8 @@ public class RestoreMusicAlbumEndpointTests await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); // Assert - await _mockApiHttpClient.Received(1).PostAsync( + await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync( BuildExpectedEndpoint(libraryId, artistId, Guid.Empty), - Arg.Any(), Arg.Any()); } @@ -131,9 +122,8 @@ public class RestoreMusicAlbumEndpointTests await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); // Assert - await _mockApiHttpClient.Received(1).PostAsync( + await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync( BuildExpectedEndpoint(libraryId, artistId, Guid.Empty), - Arg.Any(), Arg.Any()); } @@ -149,9 +139,8 @@ public class RestoreMusicAlbumEndpointTests await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); // Assert - await _mockApiHttpClient.Received(1).PostAsync( + await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync( BuildExpectedEndpoint(Guid.Empty, artistId, albumId), - Arg.Any(), Arg.Any()); } @@ -167,9 +156,8 @@ public class RestoreMusicAlbumEndpointTests await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); // Assert - await _mockApiHttpClient.Received(1).PostAsync( + await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync( BuildExpectedEndpoint(Guid.Empty, artistId, albumId), - Arg.Any(), Arg.Any()); } @@ -183,9 +171,9 @@ public class RestoreMusicAlbumEndpointTests ConfigureRequest(artistId.ToString(), albumId.ToString(), libraryId.ToString()); using CancellationTokenSource cancellationTokenSource = new(); cancellationTokenSource.Cancel(); - _mockApiHttpClient.PostAsync( - Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Task.FromCanceled(cancellationTokenSource.Token)); + _mockApiHttpClient.PostIgnoringResponseAsync( + Arg.Any(), Arg.Any()) + .Returns(Task.FromCanceled(cancellationTokenSource.Token)); // Act & Assert await Assert.ThrowsAnyAsync( diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/RestoreMusicArtist/RestoreMusicArtistEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/RestoreMusicArtist/RestoreMusicArtistEndpointTests.cs index 898b60b4..1be97fbe 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/RestoreMusicArtist/RestoreMusicArtistEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/RestoreMusicArtist/RestoreMusicArtistEndpointTests.cs @@ -30,11 +30,6 @@ public class RestoreMusicArtistEndpointTests public RestoreMusicArtistEndpointTests() { _mockApiHttpClient = Substitute.For(); - // The restore endpoints forward a bodyless POST upstream; returning an empty request lets every test that is not about - // cancellation focus on the URL construction instead of repeating the upstream stub. - _mockApiHttpClient.PostAsync( - Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(new Web.Common.Requests.Common.EmptyRequest()); _sut = Factory.Create(_mockApiHttpClient); } @@ -55,9 +50,8 @@ public class RestoreMusicArtistEndpointTests string body = await JsonResultTestHelper.GetResponseBodyAsync(result); // Assert - await _mockApiHttpClient.Received(1).PostAsync( + await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync( BuildExpectedEndpoint(libraryId, artistId), - Arg.Any(), Arg.Any()); using JsonDocument jsonDocument = JsonDocument.Parse(body); Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); @@ -75,9 +69,8 @@ public class RestoreMusicArtistEndpointTests await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); // Assert - await _mockApiHttpClient.Received(1).PostAsync( + await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync( BuildExpectedEndpoint(libraryId, Guid.Empty), - Arg.Any(), Arg.Any()); } @@ -92,9 +85,8 @@ public class RestoreMusicArtistEndpointTests await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); // Assert - await _mockApiHttpClient.Received(1).PostAsync( + await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync( BuildExpectedEndpoint(libraryId, Guid.Empty), - Arg.Any(), Arg.Any()); } @@ -109,9 +101,8 @@ public class RestoreMusicArtistEndpointTests await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); // Assert - await _mockApiHttpClient.Received(1).PostAsync( + await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync( BuildExpectedEndpoint(Guid.Empty, artistId), - Arg.Any(), Arg.Any()); } @@ -126,9 +117,8 @@ public class RestoreMusicArtistEndpointTests await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); // Assert - await _mockApiHttpClient.Received(1).PostAsync( + await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync( BuildExpectedEndpoint(Guid.Empty, artistId), - Arg.Any(), Arg.Any()); } @@ -141,9 +131,9 @@ public class RestoreMusicArtistEndpointTests ConfigureRequest(artistId.ToString(), libraryId.ToString()); using CancellationTokenSource cancellationTokenSource = new(); cancellationTokenSource.Cancel(); - _mockApiHttpClient.PostAsync( - Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Task.FromCanceled(cancellationTokenSource.Token)); + _mockApiHttpClient.PostIgnoringResponseAsync( + Arg.Any(), Arg.Any()) + .Returns(Task.FromCanceled(cancellationTokenSource.Token)); // Act & Assert await Assert.ThrowsAnyAsync( diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/RestoreMusicTrack/RestoreMusicTrackEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/RestoreMusicTrack/RestoreMusicTrackEndpointTests.cs index a654bb87..e4334cca 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/RestoreMusicTrack/RestoreMusicTrackEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/RestoreMusicTrack/RestoreMusicTrackEndpointTests.cs @@ -30,11 +30,6 @@ public class RestoreMusicTrackEndpointTests public RestoreMusicTrackEndpointTests() { _mockApiHttpClient = Substitute.For(); - // The restore endpoints forward a bodyless POST upstream; returning an empty request lets every test that is not about - // cancellation focus on the URL construction instead of repeating the upstream stub. - _mockApiHttpClient.PostAsync( - Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(new Web.Common.Requests.Common.EmptyRequest()); _sut = Factory.Create(_mockApiHttpClient); } @@ -57,9 +52,8 @@ public class RestoreMusicTrackEndpointTests string body = await JsonResultTestHelper.GetResponseBodyAsync(result); // Assert - await _mockApiHttpClient.Received(1).PostAsync( + await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync( BuildExpectedEndpoint(libraryId, artistId, albumId, trackId), - Arg.Any(), Arg.Any()); using JsonDocument jsonDocument = JsonDocument.Parse(body); Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); @@ -79,9 +73,8 @@ public class RestoreMusicTrackEndpointTests await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); // Assert - await _mockApiHttpClient.Received(1).PostAsync( + await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync( BuildExpectedEndpoint(libraryId, Guid.Empty, albumId, trackId), - Arg.Any(), Arg.Any()); } @@ -98,9 +91,8 @@ public class RestoreMusicTrackEndpointTests await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); // Assert - await _mockApiHttpClient.Received(1).PostAsync( + await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync( BuildExpectedEndpoint(libraryId, Guid.Empty, albumId, trackId), - Arg.Any(), Arg.Any()); } @@ -117,9 +109,8 @@ public class RestoreMusicTrackEndpointTests await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); // Assert - await _mockApiHttpClient.Received(1).PostAsync( + await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync( BuildExpectedEndpoint(libraryId, artistId, Guid.Empty, trackId), - Arg.Any(), Arg.Any()); } @@ -136,9 +127,8 @@ public class RestoreMusicTrackEndpointTests await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); // Assert - await _mockApiHttpClient.Received(1).PostAsync( + await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync( BuildExpectedEndpoint(libraryId, artistId, Guid.Empty, trackId), - Arg.Any(), Arg.Any()); } @@ -155,9 +145,8 @@ public class RestoreMusicTrackEndpointTests await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); // Assert - await _mockApiHttpClient.Received(1).PostAsync( + await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync( BuildExpectedEndpoint(libraryId, artistId, albumId, Guid.Empty), - Arg.Any(), Arg.Any()); } @@ -174,9 +163,8 @@ public class RestoreMusicTrackEndpointTests await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); // Assert - await _mockApiHttpClient.Received(1).PostAsync( + await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync( BuildExpectedEndpoint(libraryId, artistId, albumId, Guid.Empty), - Arg.Any(), Arg.Any()); } @@ -193,9 +181,8 @@ public class RestoreMusicTrackEndpointTests await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); // Assert - await _mockApiHttpClient.Received(1).PostAsync( + await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync( BuildExpectedEndpoint(Guid.Empty, artistId, albumId, trackId), - Arg.Any(), Arg.Any()); } @@ -212,9 +199,8 @@ public class RestoreMusicTrackEndpointTests await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); // Assert - await _mockApiHttpClient.Received(1).PostAsync( + await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync( BuildExpectedEndpoint(Guid.Empty, artistId, albumId, trackId), - Arg.Any(), Arg.Any()); } @@ -229,9 +215,9 @@ public class RestoreMusicTrackEndpointTests ConfigureRequest(artistId.ToString(), albumId.ToString(), trackId.ToString(), libraryId.ToString()); using CancellationTokenSource cancellationTokenSource = new(); cancellationTokenSource.Cancel(); - _mockApiHttpClient.PostAsync( - Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Task.FromCanceled(cancellationTokenSource.Token)); + _mockApiHttpClient.PostIgnoringResponseAsync( + Arg.Any(), Arg.Any()) + .Returns(Task.FromCanceled(cancellationTokenSource.Token)); // Act & Assert await Assert.ThrowsAnyAsync( diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/RestoreBook/RestoreBookEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/RestoreBook/RestoreBookEndpointTests.cs index e7bf88dc..f3f9ead5 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/RestoreBook/RestoreBookEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/RestoreBook/RestoreBookEndpointTests.cs @@ -40,18 +40,14 @@ public class RestoreBookEndpointTests Guid bookId = Guid.NewGuid(); Guid libraryId = Guid.NewGuid(); ConfigureRequest(bookId.ToString(), libraryId); - _mockApiHttpClient.PostAsync( - Arg.Any(), Arg.Any(), Arg.Any()) - .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( + await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync( BuildExpectedEndpoint(libraryId, bookId), - Arg.Any(), Arg.Any()); using JsonDocument jsonDocument = JsonDocument.Parse(body); Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); @@ -64,17 +60,13 @@ public class RestoreBookEndpointTests // Arrange Guid libraryId = Guid.NewGuid(); ConfigureRequest("not-a-guid", libraryId); - _mockApiHttpClient.PostAsync( - Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(new Web.Common.Requests.Common.EmptyRequest()); // Act await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); // Assert - await _mockApiHttpClient.Received(1).PostAsync( + await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync( BuildExpectedEndpoint(libraryId, Guid.Empty), - Arg.Any(), Arg.Any()); } @@ -84,17 +76,13 @@ public class RestoreBookEndpointTests // Arrange Guid bookId = Guid.NewGuid(); ConfigureRequest(bookId.ToString(), "not-a-guid"); - _mockApiHttpClient.PostAsync( - Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(new Web.Common.Requests.Common.EmptyRequest()); // Act await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); // Assert - await _mockApiHttpClient.Received(1).PostAsync( + await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync( BuildExpectedEndpoint(Guid.Empty, bookId), - Arg.Any(), Arg.Any()); } diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/MediaConsumption/StartConsumption/StartConsumptionEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/MediaConsumption/StartConsumption/StartConsumptionEndpointTests.cs index f3ccb08a..76dd4472 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/MediaConsumption/StartConsumption/StartConsumptionEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/MediaConsumption/StartConsumption/StartConsumptionEndpointTests.cs @@ -47,7 +47,7 @@ public class StartConsumptionEndpointTests // Arrange ConsumptionRecordDto expectedRecord = _consumptionRecordDtoFixture.Create(status: ConsumptionStatus.InProgress); SetRouteValues(s_libraryId, nameof(MediaKind.MusicTrack), s_mediaItemId); - _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) + _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any()) .Returns(expectedRecord); // Act @@ -77,16 +77,15 @@ public class StartConsumptionEndpointTests // Arrange ConsumptionRecordDto expectedRecord = _consumptionRecordDtoFixture.Create(); SetRouteValues(s_libraryId, nameof(MediaKind.MusicTrack), s_mediaItemId); - _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) + _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any()) .Returns(expectedRecord); // Act await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); // Assert - await _mockApiHttpClient.Received(1).PostAsync( + await _mockApiHttpClient.Received(1).PostAsync( Arg.Is(endpoint => endpoint == $"libraries/{s_libraryId}/media-items/MusicTrack/{s_mediaItemId}/consumption-records"), - Arg.Any(), Arg.Any()); } @@ -98,16 +97,15 @@ public class StartConsumptionEndpointTests _sut.HttpContext.Request.RouteValues["libraryId"] = s_libraryId; _sut.HttpContext.Request.RouteValues["mediaKind"] = nameof(MediaKind.Book); _sut.HttpContext.Request.RouteValues["mediaItemId"] = s_mediaItemId; - _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) + _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any()) .Returns(expectedRecord); // Act await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); // Assert - await _mockApiHttpClient.Received(1).PostAsync( + await _mockApiHttpClient.Received(1).PostAsync( Arg.Is(endpoint => endpoint == $"libraries/{s_libraryId}/media-items/Book/{s_mediaItemId}/consumption-records"), - Arg.Any(), Arg.Any()); } @@ -117,16 +115,15 @@ public class StartConsumptionEndpointTests // Arrange ConsumptionRecordDto expectedRecord = _consumptionRecordDtoFixture.Create(); SetRouteValues("not-a-guid", nameof(MediaKind.MusicTrack), s_mediaItemId); - _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) + _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any()) .Returns(expectedRecord); // Act await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); // Assert - await _mockApiHttpClient.Received(1).PostAsync( + await _mockApiHttpClient.Received(1).PostAsync( Arg.Is(endpoint => endpoint == $"libraries/{ZERO_GUID}/media-items/MusicTrack/{s_mediaItemId}/consumption-records"), - Arg.Any(), Arg.Any()); } @@ -136,16 +133,15 @@ public class StartConsumptionEndpointTests // Arrange ConsumptionRecordDto expectedRecord = _consumptionRecordDtoFixture.Create(); SetRouteValues(s_libraryId, nameof(MediaKind.MusicTrack), "not-a-guid"); - _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) + _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any()) .Returns(expectedRecord); // Act await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); // Assert - await _mockApiHttpClient.Received(1).PostAsync( + await _mockApiHttpClient.Received(1).PostAsync( Arg.Is(endpoint => endpoint == $"libraries/{s_libraryId}/media-items/MusicTrack/{ZERO_GUID}/consumption-records"), - Arg.Any(), Arg.Any()); } @@ -154,16 +150,15 @@ public class StartConsumptionEndpointTests { // Arrange ConsumptionRecordDto expectedRecord = _consumptionRecordDtoFixture.Create(); - _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) + _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any()) .Returns(expectedRecord); // Act await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); // Assert - await _mockApiHttpClient.Received(1).PostAsync( + await _mockApiHttpClient.Received(1).PostAsync( Arg.Is(endpoint => endpoint == $"libraries/{ZERO_GUID}/media-items/Invalid/{ZERO_GUID}/consumption-records"), - Arg.Any(), Arg.Any()); } @@ -179,16 +174,15 @@ public class StartConsumptionEndpointTests // Arrange ConsumptionRecordDto expectedRecord = _consumptionRecordDtoFixture.Create(); SetRouteValues(s_libraryId, routeMediaKind, s_mediaItemId); - _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) + _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any()) .Returns(expectedRecord); // Act await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); // Assert - await _mockApiHttpClient.Received(1).PostAsync( + await _mockApiHttpClient.Received(1).PostAsync( Arg.Is(endpoint => endpoint == $"libraries/{s_libraryId}/media-items/{expectedMediaKind}/{s_mediaItemId}/consumption-records"), - Arg.Any(), Arg.Any()); } @@ -206,16 +200,15 @@ public class StartConsumptionEndpointTests // Arrange ConsumptionRecordDto expectedRecord = _consumptionRecordDtoFixture.Create(); SetRouteValues(s_libraryId, routeMediaKind, s_mediaItemId); - _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) + _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any()) .Returns(expectedRecord); // Act await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); // Assert - await _mockApiHttpClient.Received(1).PostAsync( + await _mockApiHttpClient.Received(1).PostAsync( Arg.Is(endpoint => endpoint == $"libraries/{s_libraryId}/media-items/Invalid/{s_mediaItemId}/consumption-records"), - Arg.Any(), Arg.Any()); } @@ -225,7 +218,7 @@ public class StartConsumptionEndpointTests // Arrange ConsumptionRecordDto expectedRecord = _consumptionRecordDtoFixture.Create(); SetRouteValues(s_libraryId, nameof(MediaKind.MusicTrack), s_mediaItemId); - _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) + _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any()) .Returns(expectedRecord); // Act @@ -245,14 +238,14 @@ public class StartConsumptionEndpointTests TaskCompletionSource operationStarted = new(); TaskCompletionSource cancellationRequested = new(); SetRouteValues(s_libraryId, nameof(MediaKind.MusicTrack), s_mediaItemId); - _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) + _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any()) .Returns(callInfo => Task.Run(async () => { operationStarted.SetResult(true); await cancellationRequested.Task; - callInfo.ArgAt(2).ThrowIfCancellationRequested(); + callInfo.ArgAt(1).ThrowIfCancellationRequested(); return expectedRecord; - }, callInfo.ArgAt(2))); + }, callInfo.ArgAt(1))); // Act Task operationTask = _sut.ExecuteAsync(EmptyRequest.Instance, cts.Token); diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs index a2534b6a..b2bfe37d 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs @@ -40,8 +40,8 @@ public class UpdatePluginSettingsEndpointTests { // Arrange UpdatePluginSettingsRequest request = _updatePluginSettingsRequestFixture.Create(); - _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); + _mockApiHttpClient.PutIgnoringResponseAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Task.CompletedTask); // Act IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); @@ -49,7 +49,7 @@ public class UpdatePluginSettingsEndpointTests // Assert string expectedEndpoint = ApiRoutes.Plugins.UPDATE_PLUGIN_SETTINGS.Replace("{pluginId}", request.PluginId.ToString()); - await _mockApiHttpClient.Received(1).PutAsync( + await _mockApiHttpClient.Received(1).PutIgnoringResponseAsync( expectedEndpoint, Arg.Is(settings => settings.PluginId == request.PluginId), Arg.Any()); diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpointTests.cs index 7b2242ba..12ed538d 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpointTests.cs @@ -2,7 +2,6 @@ using FastEndpoints; using Lumina.Presentation.Web.Common.Api; using Lumina.Presentation.Web.Common.DTO.UsersManagement; -using Lumina.Presentation.Web.Common.Requests.Common; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.UpdatePlaybackState; using Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement; @@ -13,7 +12,6 @@ using System.Diagnostics.CodeAnalysis; using System.Text.Json; using System.Threading; using System.Threading.Tasks; -using WebEmptyRequest = Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest; #endregion namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Tools.Settings.UpdatePlaybackState; @@ -42,15 +40,15 @@ public class UpdatePlaybackStateEndpointTests { // Arrange PlaybackStateDto request = _playbackStateDtoFixture.Create(volume: 0.35, isMuted: true); - _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(new WebEmptyRequest()); + _mockApiHttpClient.PutIgnoringResponseAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Task.CompletedTask); // Act IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); string body = await JsonResultTestHelper.GetResponseBodyAsync(result); // Assert - await _mockApiHttpClient.Received(1).PutAsync( + await _mockApiHttpClient.Received(1).PutIgnoringResponseAsync( ApiRoutes.Users.UPDATE_PLAYBACK_STATE, Arg.Is(state => state.Volume == 0.35 && state.IsMuted == true), Arg.Any()); @@ -64,14 +62,14 @@ public class UpdatePlaybackStateEndpointTests { // Arrange PlaybackStateDto request = _playbackStateDtoFixture.Create(volume: 0.0, isMuted: false); - _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(new WebEmptyRequest()); + _mockApiHttpClient.PutIgnoringResponseAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Task.CompletedTask); // Act await _sut.ExecuteAsync(request, CancellationToken.None); // Assert - await _mockApiHttpClient.Received(1).PutAsync( + await _mockApiHttpClient.Received(1).PutIgnoringResponseAsync( ApiRoutes.Users.UPDATE_PLAYBACK_STATE, Arg.Is(state => state.Volume == 0.0 && state.IsMuted == false), Arg.Any()); @@ -82,14 +80,14 @@ public class UpdatePlaybackStateEndpointTests { // Arrange PlaybackStateDto request = _playbackStateDtoFixture.Create(includeVolume: false, includeIsMuted: false); - _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(new WebEmptyRequest()); + _mockApiHttpClient.PutIgnoringResponseAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Task.CompletedTask); // Act await _sut.ExecuteAsync(request, CancellationToken.None); // Assert - await _mockApiHttpClient.Received(1).PutAsync( + await _mockApiHttpClient.Received(1).PutIgnoringResponseAsync( ApiRoutes.Users.UPDATE_PLAYBACK_STATE, Arg.Is(state => state.Volume == null && state.IsMuted == null), Arg.Any()); diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs index 0ca6d9e8..4a02e216 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs @@ -55,15 +55,15 @@ public class UpdateUserSettingsEndpointTests { // Arrange UserSettingsDto request = _userSettingsDtoFixture.Create(); - _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(new Web.Common.Requests.Common.EmptyRequest()); + _mockApiHttpClient.PutIgnoringResponseAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Task.CompletedTask); // Act IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); string body = await JsonResultTestHelper.GetResponseBodyAsync(result); // Assert - await _mockApiHttpClient.Received(1).PutAsync( + await _mockApiHttpClient.Received(1).PutIgnoringResponseAsync( ApiRoutes.Users.UPDATE_USER_SETTINGS, Arg.Is(settings => settings.ItemsPerPage == request.ItemsPerPage && settings.IsPaginationEnabled == request.IsPaginationEnabled), Arg.Any()); @@ -86,15 +86,15 @@ public class UpdateUserSettingsEndpointTests vuMeterPeakHoldDurationInMilliseconds: 1200, vuMeterReleasePerSecond: 7.5, vuMeterPeakReleasePerSecond: 0.25); - _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(new Web.Common.Requests.Common.EmptyRequest()); + _mockApiHttpClient.PutIgnoringResponseAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Task.CompletedTask); // Act IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); // Assert Assert.NotNull(result); - await _mockApiHttpClient.Received(1).PutAsync( + await _mockApiHttpClient.Received(1).PutIgnoringResponseAsync( ApiRoutes.Users.UPDATE_USER_SETTINGS, Arg.Is(settings => settings.VuMeterOrientation == VuMeterOrientation.Horizontal && diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeServiceTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeServiceTests.cs index a14a38fb..6818f277 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeServiceTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeServiceTests.cs @@ -2,6 +2,7 @@ using Lumina.Presentation.Web.Common.Api; using Lumina.Presentation.Web.Common.DTO.Themes; using Lumina.Presentation.Web.Common.Enums.Themes; +using Lumina.Presentation.Web.Common.Requests.Themes; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Themes; using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; @@ -120,16 +121,16 @@ public class ThemeServiceTests { // Arrange string themeId = "editorial-paper"; - _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(_themeResponseDtoFixture.Create()); + _mockApiHttpClient.PutIgnoringResponseAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Task.CompletedTask); // Act await _sut.SetCurrentThemeAsync(themeId, CancellationToken.None); // Assert - await _mockApiHttpClient.Received(1).PutAsync( + await _mockApiHttpClient.Received(1).PutIgnoringResponseAsync( ApiRoutes.Themes.SET_CURRENT_THEME, - Arg.Is(payload => payload.GetType().GetProperty("ThemeId")!.GetValue(payload)!.ToString()! == themeId), + Arg.Is(payload => payload.ThemeId == themeId), Arg.Any()); }