mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
Merge pull request #299 from BinaryAlley/refactor/remove-custom-empty-request
Replaces the custom EmptyRequest with explicit API client operations
This commit is contained in:
70 files changed
+679
-384
No files matched your search
+2
-2
@@ -16,7 +16,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibra
|
||||
/// <summary>
|
||||
/// API endpoint for the <c>/libraries/{libraryId}/artists/{artistId}/albums/{albumId}</c> route.
|
||||
/// </summary>
|
||||
public class GetAlbumEndpoint : BaseEndpoint<FastEndpoints.EmptyRequest, IResult>
|
||||
public class GetAlbumEndpoint : BaseEndpoint<EmptyRequest, IResult>
|
||||
{
|
||||
private readonly IQueryHandler<GetAlbumQuery, Result<AlbumResponse>> _getAlbumQueryHandler;
|
||||
|
||||
@@ -45,7 +45,7 @@ public class GetAlbumEndpoint : BaseEndpoint<FastEndpoints.EmptyRequest, IResult
|
||||
/// </summary>
|
||||
/// <param name="request">The request object.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task<IResult> ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken)
|
||||
public override async Task<IResult> ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
// Take unique identifiers from the route.
|
||||
string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString();
|
||||
|
||||
+2
-2
@@ -17,7 +17,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibra
|
||||
/// <summary>
|
||||
/// API endpoint for the <c>/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks</c> route.
|
||||
/// </summary>
|
||||
public class GetAlbumTracksEndpoint : BaseEndpoint<FastEndpoints.EmptyRequest, IResult>
|
||||
public class GetAlbumTracksEndpoint : BaseEndpoint<EmptyRequest, IResult>
|
||||
{
|
||||
private readonly IQueryHandler<GetAlbumTracksQuery, Result<IReadOnlyList<TrackResponse>>> _getAlbumTracksQueryHandler;
|
||||
|
||||
@@ -46,7 +46,7 @@ public class GetAlbumTracksEndpoint : BaseEndpoint<FastEndpoints.EmptyRequest, I
|
||||
/// </summary>
|
||||
/// <param name="request">The request object.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task<IResult> ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken)
|
||||
public override async Task<IResult> ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
// Take unique identifiers from the route.
|
||||
string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString();
|
||||
|
||||
+2
-2
@@ -16,7 +16,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibra
|
||||
/// <summary>
|
||||
/// API endpoint for the <c>/libraries/{libraryId}/artists/{artistId}</c> route.
|
||||
/// </summary>
|
||||
public class GetArtistEndpoint : BaseEndpoint<FastEndpoints.EmptyRequest, IResult>
|
||||
public class GetArtistEndpoint : BaseEndpoint<EmptyRequest, IResult>
|
||||
{
|
||||
private readonly IQueryHandler<GetArtistQuery, Result<ArtistResponse>> _getArtistQueryHandler;
|
||||
|
||||
@@ -45,7 +45,7 @@ public class GetArtistEndpoint : BaseEndpoint<FastEndpoints.EmptyRequest, IResul
|
||||
/// </summary>
|
||||
/// <param name="request">The request object.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task<IResult> ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken)
|
||||
public override async Task<IResult> ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
// Take unique identifiers from the route.
|
||||
string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString();
|
||||
|
||||
+2
-2
@@ -17,7 +17,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibra
|
||||
/// <summary>
|
||||
/// API endpoint for the <c>/libraries/{libraryId}/artists/{artistId}/albums</c> route.
|
||||
/// </summary>
|
||||
public class GetArtistAlbumsEndpoint : BaseEndpoint<FastEndpoints.EmptyRequest, IResult>
|
||||
public class GetArtistAlbumsEndpoint : BaseEndpoint<EmptyRequest, IResult>
|
||||
{
|
||||
private readonly IQueryHandler<GetArtistAlbumsQuery, Result<IReadOnlyList<AlbumResponse>>> _getArtistAlbumsQueryHandler;
|
||||
|
||||
@@ -46,7 +46,7 @@ public class GetArtistAlbumsEndpoint : BaseEndpoint<FastEndpoints.EmptyRequest,
|
||||
/// </summary>
|
||||
/// <param name="request">The request object.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task<IResult> ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken)
|
||||
public override async Task<IResult> ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
// Take unique identifiers from the route.
|
||||
string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString();
|
||||
|
||||
+2
-2
@@ -16,7 +16,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibra
|
||||
/// <summary>
|
||||
/// API endpoint for the <c>/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}</c> route.
|
||||
/// </summary>
|
||||
public class GetTrackEndpoint : BaseEndpoint<FastEndpoints.EmptyRequest, IResult>
|
||||
public class GetTrackEndpoint : BaseEndpoint<EmptyRequest, IResult>
|
||||
{
|
||||
private readonly IQueryHandler<GetTrackQuery, Result<TrackResponse>> _getTrackQueryHandler;
|
||||
|
||||
@@ -45,7 +45,7 @@ public class GetTrackEndpoint : BaseEndpoint<FastEndpoints.EmptyRequest, IResult
|
||||
/// </summary>
|
||||
/// <param name="request">The request object.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task<IResult> ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken)
|
||||
public override async Task<IResult> ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
// Take unique identifiers from the route.
|
||||
string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString();
|
||||
|
||||
@@ -60,12 +60,10 @@ public class ApiHttpClient : IApiHttpClient
|
||||
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The deserialized response containing the result of the GET request.</returns>
|
||||
/// <exception cref="ApiException">Thrown when the API returns an unsuccessful response.</exception>
|
||||
public async Task<TResponse> GetAsync<TResponse>(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<TResponse>(request, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
@@ -78,10 +76,7 @@ public class ApiHttpClient : IApiHttpClient
|
||||
/// <returns>An <see cref="IAsyncEnumerable{T}"/> object, which allows for asynchronous iteration over the deserialized items.</returns>
|
||||
public async IAsyncEnumerable<TResponse?> GetAsyncEnumerable<TResponse>(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
|
||||
/// </summary>
|
||||
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>A model containing the deserialized blob.</returns>
|
||||
/// <returns>A model containing the raw blob bytes and their content type.</returns>
|
||||
/// <exception cref="ApiException">Thrown when the API returns an unsuccessful response.</exception>
|
||||
public async Task<BlobDataDto> 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<ProblemDetailsDto>(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
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends a DELETE request to the specified <paramref name="endpoint"/> as an asynchronous operation.
|
||||
/// Sends a DELETE request to the specified <paramref name="endpoint"/> as an asynchronous operation, discarding the response content.
|
||||
/// </summary>
|
||||
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <exception cref="ApiException">Thrown when the API returns an unsuccessful response.</exception>
|
||||
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<ProblemDetailsDto>(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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends a PUT request to the specified <paramref name="endpoint"/> as an asynchronous operation, discarding the response content.
|
||||
/// </summary>
|
||||
/// <typeparam name="TModel">The expected type of the payload content.</typeparam>
|
||||
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
||||
/// <param name="data">The data to be serialized and sent to the API.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <exception cref="ApiException">Thrown when the API returns an unsuccessful response.</exception>
|
||||
public async Task PutIgnoringResponseAsync<TModel>(string endpoint, TModel data, CancellationToken cancellationToken = default)
|
||||
{
|
||||
using HttpRequestMessage request = CreateRequestWithPayload(HttpMethod.Put, endpoint, data);
|
||||
await SendRequestAsync(request, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -159,35 +144,40 @@ public class ApiHttpClient : IApiHttpClient
|
||||
/// <typeparam name="TResponse">The expected type of the response content.</typeparam>
|
||||
/// <typeparam name="TModel">The expected type of the payload content.</typeparam>
|
||||
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
||||
/// <param name="data">The data to be serialized and send to the API.</param>
|
||||
/// <param name="data">The data to be serialized and sent to the API.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The deserialized response containing the result of the PUT request.</returns>
|
||||
/// <exception cref="ApiException">Thrown when the API returns an unsuccessful response.</exception>
|
||||
public async Task<TResponse> PutAsync<TResponse, TModel>(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<TResponse>(request, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends a POST request to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the result.
|
||||
/// Sends a PUT request with a multipart form containing a single file to the specified <paramref name="endpoint"/> as an asynchronous operation, and returns the result.
|
||||
/// </summary>
|
||||
/// <typeparam name="TResponse">The expected type of the response content.</typeparam>
|
||||
/// <typeparam name="TModel">The expected type of the payload content.</typeparam>
|
||||
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
||||
/// <param name="data">The data to be serialized and sent to the API.</param>
|
||||
/// <param name="fileStream">The stream of the file to upload, or <see langword="null"/> to send a multipart form without any file.</param>
|
||||
/// <param name="fileName">The name of the file to upload, or <see langword="null"/> when no file is sent.</param>
|
||||
/// <param name="fieldName">The name of the form field carrying the file.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The deserialized response containing the result of the POST request.</returns>
|
||||
public async Task<TResponse> PostAsync<TResponse, TModel>(string endpoint, TModel data, CancellationToken cancellationToken = default)
|
||||
/// <returns>The deserialized response containing the result of the PUT request.</returns>
|
||||
/// <exception cref="ApiException">Thrown when the API returns an unsuccessful response.</exception>
|
||||
public async Task<TResponse> PutMultipartAsync<TResponse>(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<TResponse>(request, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
@@ -201,6 +191,7 @@ public class ApiHttpClient : IApiHttpClient
|
||||
/// <param name="fieldName">The name of the form field carrying the file.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The deserialized response containing the result of the POST request.</returns>
|
||||
/// <exception cref="ApiException">Thrown when the API returns an unsuccessful response.</exception>
|
||||
public async Task<TResponse> PostMultipartAsync<TResponse>(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<TResponse>(request, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends a PUT request with a multipart form containing a single file to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the result.
|
||||
/// Sends a POST request without a payload to the specified <paramref name="endpoint"/> as an asynchronous operation, discarding the response content.
|
||||
/// </summary>
|
||||
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <exception cref="ApiException">Thrown when the API returns an unsuccessful response.</exception>
|
||||
public async Task PostIgnoringResponseAsync(string endpoint, CancellationToken cancellationToken = default)
|
||||
{
|
||||
using HttpRequestMessage request = CreateRequest(HttpMethod.Post, endpoint);
|
||||
await SendRequestAsync(request, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends a POST request without a payload to the specified <paramref name="endpoint"/> as an asynchronous operation, and returns the result.
|
||||
/// </summary>
|
||||
/// <typeparam name="TResponse">The expected type of the response content.</typeparam>
|
||||
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
||||
/// <param name="fileStream">The stream of the file to upload, or <see langword="null"/> to send a multipart form without any file.</param>
|
||||
/// <param name="fileName">The name of the file to upload, or <see langword="null"/> when no file is sent.</param>
|
||||
/// <param name="fieldName">The name of the form field carrying the file.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The deserialized response containing the result of the PUT request.</returns>
|
||||
public async Task<TResponse> PutMultipartAsync<TResponse>(string endpoint, Stream? fileStream, string? fileName, string fieldName, CancellationToken cancellationToken = default)
|
||||
/// <returns>The deserialized response containing the result of the POST request.</returns>
|
||||
/// <exception cref="ApiException">Thrown when the API returns an unsuccessful response.</exception>
|
||||
public async Task<TResponse> PostAsync<TResponse>(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<TResponse>(request, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
using HttpRequestMessage request = new(HttpMethod.Put, endpoint)
|
||||
{
|
||||
Content = form
|
||||
};
|
||||
/// <summary>
|
||||
/// Sends a POST request to the specified <paramref name="endpoint"/> as an asynchronous operation, discarding the response content.
|
||||
/// </summary>
|
||||
/// <typeparam name="TModel">The expected type of the payload content.</typeparam>
|
||||
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
||||
/// <param name="data">The data to be serialized and sent to the API.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <exception cref="ApiException">Thrown when the API returns an unsuccessful response.</exception>
|
||||
public async Task PostIgnoringResponseAsync<TModel>(string endpoint, TModel data, CancellationToken cancellationToken = default)
|
||||
{
|
||||
using HttpRequestMessage request = CreateRequestWithPayload(HttpMethod.Post, endpoint, data);
|
||||
await SendRequestAsync(request, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends a POST request to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the result.
|
||||
/// </summary>
|
||||
/// <typeparam name="TResponse">The expected type of the response content.</typeparam>
|
||||
/// <typeparam name="TModel">The expected type of the payload content.</typeparam>
|
||||
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
||||
/// <param name="data">The data to be serialized and sent to the API.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The deserialized response containing the result of the POST request.</returns>
|
||||
/// <exception cref="ApiException">Thrown when the API returns an unsuccessful response.</exception>
|
||||
public async Task<TResponse> PostAsync<TResponse, TModel>(string endpoint, TModel data, CancellationToken cancellationToken = default)
|
||||
{
|
||||
using HttpRequestMessage request = CreateRequestWithPayload(HttpMethod.Post, endpoint, data);
|
||||
return await SendRequestAsync<TResponse>(request, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an HTTP request for the specified <paramref name="method"/> and <paramref name="endpoint"/>.
|
||||
/// </summary>
|
||||
/// <param name="method">The HTTP method of the request.</param>
|
||||
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
||||
/// <returns>The created <see cref="HttpRequestMessage"/>.</returns>
|
||||
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<TResponse>(request, cancellationToken).ConfigureAwait(false);
|
||||
return request;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an HTTP request for the specified <paramref name="method"/> and <paramref name="endpoint"/>, with the serialized <paramref name="data"/> as its JSON payload.
|
||||
/// </summary>
|
||||
/// <typeparam name="TModel">The expected type of the payload content.</typeparam>
|
||||
/// <param name="method">The HTTP method of the request.</param>
|
||||
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
||||
/// <param name="data">The data to be serialized and sent to the API.</param>
|
||||
/// <returns>The created <see cref="HttpRequestMessage"/>.</returns>
|
||||
private HttpRequestMessage CreateRequestWithPayload<TModel>(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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends an HTTP request and reads the response content.
|
||||
/// If the request fails, it attempts to deserialize the response content into a <see cref="ProblemDetailsDto"/> and throws an <see cref="ApiException"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The <see cref="HttpRequestMessage"/> to be sent.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The raw response content.</returns>
|
||||
/// <exception cref="ApiException">Thrown if the response is not successful, with the <see cref="ProblemDetailsDto"/> if available.</exception>
|
||||
private async Task<string> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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 <see cref="ProblemDetailsDto"/> and throws an <see cref="ApiException"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="TResponse">The expected type of the response content.</typeparam>
|
||||
/// <param name="request">The <see cref="HttpRequestMessage"/> to be sent.</param>
|
||||
@@ -261,28 +318,30 @@ public class ApiHttpClient : IApiHttpClient
|
||||
/// <exception cref="ApiException">Thrown if the response is not successful, with the <see cref="ProblemDetailsDto"/> if available.</exception>
|
||||
private async Task<TResponse> SendRequestAsync<TResponse>(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<TResponse>(content, _jsonOptions)!;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates the exception thrown when an API request fails.
|
||||
/// </summary>
|
||||
/// <param name="content">The raw response content.</param>
|
||||
/// <param name="response">The failed HTTP response.</param>
|
||||
/// <param name="request">The HTTP request that failed.</param>
|
||||
/// <returns>The created <see cref="ApiException"/>.</returns>
|
||||
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<TResponse>(content, _jsonOptions)!;
|
||||
}
|
||||
else
|
||||
{
|
||||
ProblemDetailsDto? problemDetails = null;
|
||||
// Attempt to deserialize the response content to ProblemDetailsDto if the request fails.
|
||||
try
|
||||
{
|
||||
problemDetails = JsonSerializer.Deserialize<ProblemDetailsDto>(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<ProblemDetailsDto>(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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -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
|
||||
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The deserialized response containing the result of the GET request.</returns>
|
||||
/// <exception cref="ApiException">Thrown when the API returns an unsuccessful response.</exception>
|
||||
Task<TResponse> GetAsync<TResponse>(string endpoint, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
@@ -36,25 +38,38 @@ public interface IApiHttpClient
|
||||
/// </summary>
|
||||
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>A model containing the deserialized blob.</returns>
|
||||
/// <returns>A model containing the raw blob bytes and their content type.</returns>
|
||||
/// <exception cref="ApiException">Thrown when the API returns an unsuccessful response.</exception>
|
||||
Task<BlobDataDto> GetBlobAsync(string endpoint, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Sends a DELETE request to the specified <paramref name="endpoint"/> as an asynchronous operation.
|
||||
/// Sends a DELETE request to the specified <paramref name="endpoint"/> as an asynchronous operation, discarding the response content.
|
||||
/// </summary>
|
||||
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <exception cref="ApiException">Thrown when the API returns an unsuccessful response.</exception>
|
||||
Task DeleteAsync(string endpoint, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Sends a PUT request to the specified <paramref name="endpoint"/> as an asynchronous operation, discarding the response content.
|
||||
/// </summary>
|
||||
/// <typeparam name="TModel">The expected type of the payload content.</typeparam>
|
||||
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
||||
/// <param name="data">The data to be serialized and sent to the API.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <exception cref="ApiException">Thrown when the API returns an unsuccessful response.</exception>
|
||||
Task PutIgnoringResponseAsync<TModel>(string endpoint, TModel data, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Sends a PUT request to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the result.
|
||||
/// </summary>
|
||||
/// <typeparam name="TResponse">The expected type of the response content.</typeparam>
|
||||
/// <typeparam name="TModel">The expected type of the payload content.</typeparam>
|
||||
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
||||
/// <param name="data">The data to be serialized and send to the API.</param>
|
||||
/// <param name="data">The data to be serialized and sent to the API.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The deserialized response containing the result of the PUT request.</returns>
|
||||
/// <exception cref="ApiException">Thrown when the API returns an unsuccessful response.</exception>
|
||||
Task<TResponse> PutAsync<TResponse, TModel>(string endpoint, TModel data, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
@@ -67,6 +82,7 @@ public interface IApiHttpClient
|
||||
/// <param name="fieldName">The name of the form field carrying the file.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The deserialized response containing the result of the PUT request.</returns>
|
||||
/// <exception cref="ApiException">Thrown when the API returns an unsuccessful response.</exception>
|
||||
Task<TResponse> PutMultipartAsync<TResponse>(string endpoint, Stream? fileStream, string? fileName, string fieldName, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
@@ -79,8 +95,37 @@ public interface IApiHttpClient
|
||||
/// <param name="fieldName">The name of the form field carrying the file.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The deserialized response containing the result of the POST request.</returns>
|
||||
/// <exception cref="ApiException">Thrown when the API returns an unsuccessful response.</exception>
|
||||
Task<TResponse> PostMultipartAsync<TResponse>(string endpoint, Stream fileStream, string fileName, string fieldName, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Sends a POST request without a payload to the specified <paramref name="endpoint"/> as an asynchronous operation, discarding the response content.
|
||||
/// </summary>
|
||||
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <exception cref="ApiException">Thrown when the API returns an unsuccessful response.</exception>
|
||||
Task PostIgnoringResponseAsync(string endpoint, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Sends a POST request without a payload to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the result.
|
||||
/// </summary>
|
||||
/// <typeparam name="TResponse">The expected type of the response content.</typeparam>
|
||||
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The deserialized response containing the result of the POST request.</returns>
|
||||
/// <exception cref="ApiException">Thrown when the API returns an unsuccessful response.</exception>
|
||||
Task<TResponse> PostAsync<TResponse>(string endpoint, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Sends a POST request to the specified <paramref name="endpoint"/> as an asynchronous operation, discarding the response content.
|
||||
/// </summary>
|
||||
/// <typeparam name="TModel">The expected type of the payload content.</typeparam>
|
||||
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
||||
/// <param name="data">The data to be serialized and sent to the API.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <exception cref="ApiException">Thrown when the API returns an unsuccessful response.</exception>
|
||||
Task PostIgnoringResponseAsync<TModel>(string endpoint, TModel data, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Sends a POST request to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the result.
|
||||
/// </summary>
|
||||
@@ -90,5 +135,6 @@ public interface IApiHttpClient
|
||||
/// <param name="data">The data to be serialized and sent to the API.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The deserialized response containing the result of the POST request.</returns>
|
||||
/// <exception cref="ApiException">Thrown when the API returns an unsuccessful response.</exception>
|
||||
Task<TResponse> PostAsync<TResponse, TModel>(string endpoint, TModel data, CancellationToken cancellationToken = default);
|
||||
}
|
||||
@@ -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<GetAuthorizationResponse>($"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;
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using System.Net;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.Exceptions;
|
||||
|
||||
/// <summary>
|
||||
/// Exception for an unsuccessful current-user authorization check, which means that the stored session refers to a user the API no longer knows.
|
||||
/// </summary>
|
||||
public class CurrentUserAuthorizationException : ApiException
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CurrentUserAuthorizationException"/> class.
|
||||
/// </summary>
|
||||
/// <param name="problemDetails">The problem details object returned by the API.</param>
|
||||
/// <param name="httpStatusCode">The HTTP status code returned by the API.</param>
|
||||
/// <param name="requestPath">The absolute path of the API endpoint that produced this exception.</param>
|
||||
public CurrentUserAuthorizationException(ProblemDetailsDto? problemDetails, HttpStatusCode httpStatusCode, string? requestPath = null)
|
||||
: base(problemDetails, httpStatusCode, requestPath)
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -137,9 +137,10 @@ public class ExceptionHandlingMiddleware
|
||||
/// </summary>
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the API exception originated from the authorization check of the currently logged in user.
|
||||
/// </summary>
|
||||
/// <param name="apiException">The API exception to inspect.</param>
|
||||
/// <returns><see langword="true"/> if the exception came from the current-user authorization endpoint, <see langword="false"/> otherwise.</returns>
|
||||
private static bool IsCurrentUserAuthorizationCheck(ApiException apiException)
|
||||
{
|
||||
return apiException.RequestPath?.Contains("/auth/get-authorization", StringComparison.OrdinalIgnoreCase) == true;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
namespace Lumina.Presentation.Web.Common.Requests.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Record used for empty requests and responses.
|
||||
/// </summary>
|
||||
public record struct EmptyRequest();
|
||||
+1
-2
@@ -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 : BaseEndpoint<FireScheduledJobRequest, IR
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task<IResult> ExecuteAsync(FireScheduledJobRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
await _apiHttpClient.PutAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(ApiRoutes.ScheduledJobs.FIRE_SCHEDULED_JOB.Replace("{scheduledJobId}", request.ScheduledJobId.ToString()), new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest(), cancellationToken).ConfigureAwait(false);
|
||||
await _apiHttpClient.PutIgnoringResponseAsync<FireScheduledJobRequest>(ApiRoutes.ScheduledJobs.FIRE_SCHEDULED_JOB.Replace("{scheduledJobId}", request.ScheduledJobId.ToString()), request, cancellationToken).ConfigureAwait(false);
|
||||
return JsonSuccess();
|
||||
}
|
||||
}
|
||||
+1
-2
@@ -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 : BaseEndpoint<StartScheduledJobRequest,
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task<IResult> ExecuteAsync(StartScheduledJobRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
await _apiHttpClient.PutAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(ApiRoutes.ScheduledJobs.START_SCHEDULED_JOB.Replace("{scheduledJobId}", request.ScheduledJobId.ToString()), new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest(), cancellationToken).ConfigureAwait(false);
|
||||
await _apiHttpClient.PutIgnoringResponseAsync<StartScheduledJobRequest>(ApiRoutes.ScheduledJobs.START_SCHEDULED_JOB.Replace("{scheduledJobId}", request.ScheduledJobId.ToString()), request, cancellationToken).ConfigureAwait(false);
|
||||
return JsonSuccess();
|
||||
}
|
||||
}
|
||||
+1
-2
@@ -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 : BaseEndpoint<StopScheduledJobRequest, IR
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task<IResult> ExecuteAsync(StopScheduledJobRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
await _apiHttpClient.PutAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(ApiRoutes.ScheduledJobs.STOP_SCHEDULED_JOB.Replace("{scheduledJobId}", request.ScheduledJobId.ToString()), new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest(), cancellationToken).ConfigureAwait(false);
|
||||
await _apiHttpClient.PutIgnoringResponseAsync<StopScheduledJobRequest>(ApiRoutes.ScheduledJobs.STOP_SCHEDULED_JOB.Replace("{scheduledJobId}", request.ScheduledJobId.ToString()), request, cancellationToken).ConfigureAwait(false);
|
||||
return JsonSuccess();
|
||||
}
|
||||
}
|
||||
+1
-2
@@ -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 : BaseEndpoint<UpdateSche
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task<IResult> ExecuteAsync(UpdateSchedulerDisplayPreferencesRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
await _apiHttpClient.PutAsync<Web.Common.Requests.Common.EmptyRequest, UpdateSchedulerDisplayPreferencesRequest>(ApiRoutes.ScheduledJobs.UPDATE_DISPLAY_PREFERENCES, request, cancellationToken).ConfigureAwait(false);
|
||||
await _apiHttpClient.PutIgnoringResponseAsync<UpdateSchedulerDisplayPreferencesRequest>(ApiRoutes.ScheduledJobs.UPDATE_DISPLAY_PREFERENCES, request, cancellationToken).ConfigureAwait(false);
|
||||
return JsonSuccess();
|
||||
}
|
||||
}
|
||||
+2
-3
@@ -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;
|
||||
/// <summary>
|
||||
/// API endpoint for the <c>/{culture}/favorites/{mediaKind}/{mediaItemId}/api-remove-favorite</c> route.
|
||||
/// </summary>
|
||||
public class RemoveFavoriteEndpoint : BaseEndpoint<FastEndpoints.EmptyRequest, IResult>
|
||||
public class RemoveFavoriteEndpoint : BaseEndpoint<EmptyRequest, IResult>
|
||||
{
|
||||
// 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<FastEndpoints.EmptyRequest, I
|
||||
/// </summary>
|
||||
/// <param name="request">The request object.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task<IResult> ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken)
|
||||
public override async Task<IResult> 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.
|
||||
|
||||
+1
-3
@@ -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<EmptyRequest, IResult>
|
||||
string queryLibraryId = HttpContext.Request.Query["libraryId"].ToString();
|
||||
string libraryId = Guid.TryParse(queryLibraryId, out Guid parsedLibraryId) ? parsedLibraryId.ToString() : Guid.Empty.ToString();
|
||||
|
||||
await _apiHttpClient.PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
|
||||
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 });
|
||||
}
|
||||
|
||||
+1
-3
@@ -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<EmptyRequest, IResult>
|
||||
string queryLibraryId = HttpContext.Request.Query["libraryId"].ToString();
|
||||
string libraryId = Guid.TryParse(queryLibraryId, out Guid parsedLibraryId) ? parsedLibraryId.ToString() : Guid.Empty.ToString();
|
||||
|
||||
await _apiHttpClient.PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
|
||||
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 });
|
||||
}
|
||||
|
||||
+1
-3
@@ -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<EmptyRequest, IResult>
|
||||
string queryLibraryId = HttpContext.Request.Query["libraryId"].ToString();
|
||||
string libraryId = Guid.TryParse(queryLibraryId, out Guid parsedLibraryId) ? parsedLibraryId.ToString() : Guid.Empty.ToString();
|
||||
|
||||
await _apiHttpClient.PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
|
||||
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 });
|
||||
}
|
||||
|
||||
+1
-2
@@ -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<EmptyRequest, IResult>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task<IResult> ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
await _apiHttpClient.PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(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();
|
||||
}
|
||||
}
|
||||
+1
-2
@@ -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 : BaseEndpoint<CancelLibraryScanRequest,
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task<IResult> ExecuteAsync(CancelLibraryScanRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
await _apiHttpClient.PostAsync<Web.Common.Requests.Common.EmptyRequest, Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest>(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<CancelLibraryScanRequest>(ApiRoutes.Libraries.CANCEL_LIBRARY_SCAN.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{scanId}", request.ScanId.ToString()), request, cancellationToken).ConfigureAwait(false);
|
||||
return JsonSuccess();
|
||||
}
|
||||
}
|
||||
+1
-2
@@ -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<EmptyRequest, IResult>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task<IResult> ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
ScanLibraryDto[] response = await _apiHttpClient.PostAsync<ScanLibraryDto[], Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest>(ApiRoutes.Libraries.SCAN_LIBRARIES, new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest(), cancellationToken).ConfigureAwait(false);
|
||||
ScanLibraryDto[] response = await _apiHttpClient.PostAsync<ScanLibraryDto[]>(ApiRoutes.Libraries.SCAN_LIBRARIES, cancellationToken).ConfigureAwait(false);
|
||||
return JsonSuccess(response);
|
||||
}
|
||||
}
|
||||
+1
-2
@@ -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<ScanLibraryRequest, IResult>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task<IResult> ExecuteAsync(ScanLibraryRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
ScanLibraryDto response = await _apiHttpClient.PostAsync<ScanLibraryDto, Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest>(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<ScanLibraryDto>(ApiRoutes.Libraries.SCAN_LIBRARY.Replace("{id}", request.Id.ToString()), cancellationToken).ConfigureAwait(false);
|
||||
return JsonSuccess(response);
|
||||
}
|
||||
}
|
||||
+1
-3
@@ -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<EmptyRequest, IResult>
|
||||
string queryLibraryId = HttpContext.Request.Query["libraryId"].ToString();
|
||||
string libraryId = Guid.TryParse(queryLibraryId, out Guid parsedLibraryId) ? parsedLibraryId.ToString() : Guid.Empty.ToString();
|
||||
|
||||
await _apiHttpClient.PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
|
||||
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 });
|
||||
}
|
||||
|
||||
+1
-2
@@ -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<EmptyRequest, IResult>
|
||||
.Replace("{libraryId}", libraryId, StringComparison.Ordinal)
|
||||
.Replace("{mediaKind}", mediaKind, StringComparison.Ordinal)
|
||||
.Replace("{mediaItemId}", mediaItemId, StringComparison.Ordinal);
|
||||
ConsumptionRecordDto record = await _apiHttpClient.PostAsync<ConsumptionRecordDto, EmptyRequest>(endpoint, request, cancellationToken).ConfigureAwait(false);
|
||||
ConsumptionRecordDto record = await _apiHttpClient.PostAsync<ConsumptionRecordDto>(endpoint, cancellationToken).ConfigureAwait(false);
|
||||
return JsonSuccess(record);
|
||||
}
|
||||
}
|
||||
+2
-3
@@ -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;
|
||||
/// <summary>
|
||||
/// API endpoint for the <c>/{culture}/playlists/item/{playlistId}/api-delete-playlist</c> route.
|
||||
/// </summary>
|
||||
public class DeletePlaylistEndpoint : BaseEndpoint<FastEndpoints.EmptyRequest, IResult>
|
||||
public class DeletePlaylistEndpoint : BaseEndpoint<EmptyRequest, IResult>
|
||||
{
|
||||
private readonly IApiHttpClient _apiHttpClient;
|
||||
|
||||
@@ -46,7 +45,7 @@ public class DeletePlaylistEndpoint : BaseEndpoint<FastEndpoints.EmptyRequest, I
|
||||
/// </summary>
|
||||
/// <param name="request">The request object.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task<IResult> ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken)
|
||||
public override async Task<IResult> 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;
|
||||
|
||||
+1
-2
@@ -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 : BaseEndpoint<UpdatePluginSettingsReq
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task<IResult> ExecuteAsync(UpdatePluginSettingsRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
await _apiHttpClient.PutAsync<Web.Common.Requests.Common.EmptyRequest, UpdatePluginSettingsRequest>(ApiRoutes.Plugins.UPDATE_PLUGIN_SETTINGS.Replace("{pluginId}", request.PluginId.ToString()), request, cancellationToken).ConfigureAwait(false);
|
||||
await _apiHttpClient.PutIgnoringResponseAsync<UpdatePluginSettingsRequest>(ApiRoutes.Plugins.UPDATE_PLUGIN_SETTINGS.Replace("{pluginId}", request.PluginId.ToString()), request, cancellationToken).ConfigureAwait(false);
|
||||
return JsonSuccess();
|
||||
}
|
||||
}
|
||||
+1
-2
@@ -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 : BaseEndpoint<PlaybackStateDto, IResul
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task<IResult> ExecuteAsync(PlaybackStateDto request, CancellationToken cancellationToken)
|
||||
{
|
||||
await _apiHttpClient.PutAsync<Web.Common.Requests.Common.EmptyRequest, PlaybackStateDto>(ApiRoutes.Users.UPDATE_PLAYBACK_STATE, request, cancellationToken).ConfigureAwait(false);
|
||||
await _apiHttpClient.PutIgnoringResponseAsync<PlaybackStateDto>(ApiRoutes.Users.UPDATE_PLAYBACK_STATE, request, cancellationToken).ConfigureAwait(false);
|
||||
return JsonSuccess(new { isUpdated = true });
|
||||
}
|
||||
}
|
||||
+1
-2
@@ -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<UserSettingsDto, IResult>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task<IResult> ExecuteAsync(UserSettingsDto request, CancellationToken cancellationToken)
|
||||
{
|
||||
await _apiHttpClient.PutAsync<Web.Common.Requests.Common.EmptyRequest, UserSettingsDto>(ApiRoutes.Users.UPDATE_USER_SETTINGS, request, cancellationToken).ConfigureAwait(false);
|
||||
await _apiHttpClient.PutIgnoringResponseAsync<UserSettingsDto>(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();
|
||||
|
||||
@@ -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
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public async Task SetCurrentThemeAsync(string themeId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await _apiHttpClient.PutAsync<ThemeResponseDto, object>(ApiRoutes.Themes.SET_CURRENT_THEME, new { ThemeId = themeId }, cancellationToken).ConfigureAwait(false);
|
||||
await _apiHttpClient.PutIgnoringResponseAsync<SetCurrentThemeRequest>(ApiRoutes.Themes.SET_CURRENT_THEME, new SetCurrentThemeRequest(themeId), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -101,7 +102,7 @@ public sealed class ThemeService
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public async Task RestoreThemeAsync(string themeId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await _apiHttpClient.PostAsync<ThemeResponseDto, object>(ApiRoutes.Themes.RESTORE_THEME.Replace("{themeId}", themeId), new { }, cancellationToken).ConfigureAwait(false);
|
||||
await _apiHttpClient.PostIgnoringResponseAsync(ApiRoutes.Themes.RESTORE_THEME.Replace("{themeId}", themeId), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -27,9 +27,15 @@ public class StubApiHttpClient : IApiHttpClient
|
||||
private readonly Dictionary<string, Func<object>> _getResponseFactories = [];
|
||||
private readonly Dictionary<string, Func<object, object>> _postResponseFactories = [];
|
||||
private readonly Dictionary<string, Func<object, object>> _putResponseFactories = [];
|
||||
private readonly Dictionary<string, ApiException> _postExceptions = [];
|
||||
private readonly Dictionary<string, ApiException> _putExceptions = [];
|
||||
private readonly HashSet<string> _postBodylessSuccessEndpoints = [];
|
||||
private readonly Dictionary<string, Type> _postPayloadTypes = [];
|
||||
private readonly Dictionary<string, Type> _putPayloadTypes = [];
|
||||
private readonly HashSet<string> _deleteSuccessEndpoints = [];
|
||||
private readonly Dictionary<string, ApiException> _deleteExceptions = [];
|
||||
private BlobDataDto? _blobResponse;
|
||||
private ApiException? _blobException;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the authorization response returned for the <c>auth/get-authorization</c> endpoint.
|
||||
@@ -121,7 +127,7 @@ public class StubApiHttpClient : IApiHttpClient
|
||||
/// <param name="exception">The exception to throw.</param>
|
||||
public void RegisterPostException(string endpoint, ApiException exception)
|
||||
{
|
||||
_postResponseFactories[endpoint] = _ => throw exception;
|
||||
_postExceptions[endpoint] = exception;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -141,7 +147,7 @@ public class StubApiHttpClient : IApiHttpClient
|
||||
/// <param name="exception">The exception to throw.</param>
|
||||
public void RegisterPutException(string endpoint, ApiException exception)
|
||||
{
|
||||
_putResponseFactories[endpoint] = _ => throw exception;
|
||||
_putExceptions[endpoint] = exception;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -193,6 +199,44 @@ public class StubApiHttpClient : IApiHttpClient
|
||||
_blobResponse = blob;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers the exception thrown when a blob endpoint is called.
|
||||
/// </summary>
|
||||
/// <param name="exception">The exception to throw.</param>
|
||||
public void RegisterBlobException(ApiException exception)
|
||||
{
|
||||
_blobException = exception;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers the specified POST endpoint as accepting a bodyless request without returning a response body.
|
||||
/// </summary>
|
||||
/// <param name="endpoint">The API endpoint for which to register success.</param>
|
||||
public void RegisterPostSuccess(string endpoint)
|
||||
{
|
||||
_postBodylessSuccessEndpoints.Add(endpoint);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers the specified POST endpoint as accepting a payload of type <typeparamref name="TModel"/> without returning a response body.
|
||||
/// </summary>
|
||||
/// <typeparam name="TModel">The expected type of the payload content.</typeparam>
|
||||
/// <param name="endpoint">The API endpoint for which to register the payload type.</param>
|
||||
public void RegisterPostPayload<TModel>(string endpoint)
|
||||
{
|
||||
_postPayloadTypes[endpoint] = typeof(TModel);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers the specified PUT endpoint as accepting a payload of type <typeparamref name="TModel"/> without returning a response body.
|
||||
/// </summary>
|
||||
/// <typeparam name="TModel">The expected type of the payload content.</typeparam>
|
||||
/// <param name="endpoint">The API endpoint for which to register the payload type.</param>
|
||||
public void RegisterPutPayload<TModel>(string endpoint)
|
||||
{
|
||||
_putPayloadTypes[endpoint] = typeof(TModel);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resets all registered responses and captured requests, keeping only the default responses.
|
||||
/// </summary>
|
||||
@@ -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
|
||||
/// </summary>
|
||||
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>A model containing the deserialized blob.</returns>
|
||||
/// <returns>A model containing the raw blob bytes and their content type.</returns>
|
||||
public Task<BlobDataDto> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends a PUT request to the specified <paramref name="endpoint"/> as an asynchronous operation, discarding the response content.
|
||||
/// </summary>
|
||||
/// <typeparam name="TModel">The expected type of the payload content.</typeparam>
|
||||
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
||||
/// <param name="data">The data to be serialized and sent to the API.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public Task PutIgnoringResponseAsync<TModel>(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}'.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends a PUT request to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the result.
|
||||
/// </summary>
|
||||
/// <typeparam name="TResponse">The expected type of the response content.</typeparam>
|
||||
/// <typeparam name="TModel">The expected type of the payload content.</typeparam>
|
||||
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
||||
/// <param name="data">The data to be serialized and send to the API.</param>
|
||||
/// <param name="data">The data to be serialized and sent to the API.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The deserialized response containing the result of the PUT request.</returns>
|
||||
public Task<TResponse> PutAsync<TResponse, TModel>(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<object, object>? 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<TResponse> PutMultipartAsync<TResponse>(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<object, object>? 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<TResponse> PostMultipartAsync<TResponse>(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<object, object>? responseFactory))
|
||||
return Task.FromResult((TResponse)responseFactory(fileName));
|
||||
throw new InvalidOperationException($"No POST response is registered for the endpoint '{endpoint}'.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends a POST request without a payload to the specified <paramref name="endpoint"/> as an asynchronous operation, discarding the response content.
|
||||
/// </summary>
|
||||
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
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}'.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends a POST request without a payload to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the result.
|
||||
/// </summary>
|
||||
/// <typeparam name="TResponse">The expected type of the response content.</typeparam>
|
||||
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The registered response.</returns>
|
||||
public Task<TResponse> PostAsync<TResponse>(string endpoint, CancellationToken cancellationToken = default)
|
||||
{
|
||||
PostRequests.Add((endpoint, null));
|
||||
if (_postExceptions.TryGetValue(endpoint, out ApiException? exception))
|
||||
throw exception;
|
||||
if (_postResponseFactories.TryGetValue(endpoint, out Func<object, object>? 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}'.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends a POST request to the specified <paramref name="endpoint"/> as an asynchronous operation, discarding the response content.
|
||||
/// </summary>
|
||||
/// <typeparam name="TModel">The expected type of the payload content.</typeparam>
|
||||
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
||||
/// <param name="data">The data to be serialized and sent to the API.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public Task PostIgnoringResponseAsync<TModel>(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}'.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends a POST request to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the result.
|
||||
/// </summary>
|
||||
/// <typeparam name="TResponse">The expected type of the response content.</typeparam>
|
||||
/// <typeparam name="TModel">The expected type of the payload content.</typeparam>
|
||||
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
||||
/// <param name="data">The data to be serialized and send to the API.</param>
|
||||
/// <param name="data">The data to be serialized and sent to the API.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The deserialized response containing the result of the POST request.</returns>
|
||||
public Task<TResponse> PostAsync<TResponse, TModel>(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<object, object>? responseFactory))
|
||||
return Task.FromResult((TResponse)responseFactory(data!));
|
||||
if (endpoint == ApiRoutes.Authentication.LOGIN_ACCOUNT)
|
||||
|
||||
+2
-3
@@ -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<LuminaWebFactory>
|
||||
_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<FireScheduledJobRequest>(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"));
|
||||
|
||||
+2
-2
@@ -40,11 +40,11 @@ public class StartScheduledJobEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
_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<StartScheduledJobRequest>(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"));
|
||||
|
||||
+2
-2
@@ -40,11 +40,11 @@ public class StopScheduledJobEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
_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<StopScheduledJobRequest>(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"));
|
||||
|
||||
+1
-1
@@ -39,7 +39,7 @@ public class UpdateSchedulerDisplayPreferencesEndpointTests : IClassFixture<Lumi
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
UpdateSchedulerDisplayPreferencesRequest request = _updateSchedulerDisplayPreferencesRequestFixture.Create();
|
||||
_apiFactory.ApiClientStub.RegisterPutResponseFactory("scheduled-jobs/display-preferences", _ => new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest());
|
||||
_apiFactory.ApiClientStub.RegisterPutPayload<UpdateSchedulerDisplayPreferencesRequest>("scheduled-jobs/display-preferences");
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/admin/api-scheduled-jobs/display-preferences")
|
||||
{
|
||||
|
||||
+1
-5
@@ -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<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RestoreThemeEndpointTests"/> class.
|
||||
@@ -40,7 +36,7 @@ public class RestoreThemeEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
// 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}")
|
||||
{
|
||||
|
||||
+2
-5
@@ -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<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new();
|
||||
private readonly SetCurrentThemeRequestFixture _setCurrentThemeRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
@@ -42,7 +39,7 @@ public class SetCurrentThemeEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
const string THEME_ID = "test-theme";
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse("themes/current", _themeResponseDtoFixture.Create());
|
||||
_apiFactory.ApiClientStub.RegisterPutPayload<SetCurrentThemeRequest>("themes/current");
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage setCurrentThemeRequest = new(HttpMethod.Put, "/en-us/admin/themes/api-set-current-theme")
|
||||
{
|
||||
|
||||
+1
-1
@@ -40,7 +40,7 @@ public class RestoreMusicAlbumEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse<object>($"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);
|
||||
|
||||
+1
-1
@@ -39,7 +39,7 @@ public class RestoreMusicArtistEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse<object>($"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);
|
||||
|
||||
+1
-1
@@ -41,7 +41,7 @@ public class RestoreMusicTrackEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse<object>($"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);
|
||||
|
||||
+1
-1
@@ -35,7 +35,7 @@ public class CancelLibrariesScanEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
// 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);
|
||||
|
||||
+7
-2
@@ -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<LuminaWebFactory>
|
||||
_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<CancelLibraryScanRequest>($"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<LuminaWebFactory>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+1
-1
@@ -39,7 +39,7 @@ public class RestoreBookEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse<object>($"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);
|
||||
|
||||
+1
-1
@@ -40,7 +40,7 @@ public class UpdatePluginSettingsEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
_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<UpdatePluginSettingsRequest>(expectedEndpoint);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/admin/manage-plugins/api-update-plugin-settings")
|
||||
{
|
||||
|
||||
+2
-3
@@ -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<LuminaWebFactory>
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.RegisterPutResponseFactory("users/me/settings/playback-state", _ => new EmptyRequest());
|
||||
_apiFactory.ApiClientStub.RegisterPutPayload<PlaybackStateDto>("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<LuminaWebFactory>
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.RegisterPutResponseFactory("users/me/settings/playback-state", _ => new EmptyRequest());
|
||||
_apiFactory.ApiClientStub.RegisterPutPayload<PlaybackStateDto>("users/me/settings/playback-state");
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
PlaybackStateDto state = _playbackStateDtoFixture.Create(volume: 0.0, isMuted: false);
|
||||
|
||||
|
||||
+2
-3
@@ -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<LuminaWebFactory>
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.RegisterPutResponseFactory("users/me/settings", _ => new EmptyRequest());
|
||||
_apiFactory.ApiClientStub.RegisterPutPayload<UserSettingsDto>("users/me/settings");
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
UserSettingsDto settings = _userSettingsDtoFixture.Create(isThemeCachingEnabled: true);
|
||||
|
||||
@@ -62,7 +61,7 @@ public class UpdateUserSettingsEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.RegisterPutResponseFactory("users/me/settings", _ => new EmptyRequest());
|
||||
_apiFactory.ApiClientStub.RegisterPutPayload<UserSettingsDto>("users/me/settings");
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
UserSettingsDto settings = _userSettingsDtoFixture.Create(
|
||||
vuMeterOrientation: VuMeterOrientation.Horizontal,
|
||||
|
||||
+2
-2
@@ -40,7 +40,7 @@ public class RestoreMusicAlbumEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
string normalizedId = Guid.Empty.ToString();
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse<object>($"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<LuminaWebFactory>
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
string normalizedId = Guid.Empty.ToString();
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse<object>($"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);
|
||||
|
||||
+2
-2
@@ -40,7 +40,7 @@ public class RestoreMusicArtistEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
string normalizedId = Guid.Empty.ToString();
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse<object>($"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<LuminaWebFactory>
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
string normalizedId = Guid.Empty.ToString();
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse<object>($"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);
|
||||
|
||||
+2
-6
@@ -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<LuminaWebFactory>
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
string normalizedId = Guid.Empty.ToString();
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse<object>($"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<LuminaWebFactory>
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
string normalizedId = Guid.Empty.ToString();
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse<object>($"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);
|
||||
|
||||
+2
-2
@@ -36,7 +36,7 @@ public class RestoreBookEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
string normalizedId = Guid.Empty.ToString();
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse<object>($"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<LuminaWebFactory>
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
string normalizedId = Guid.Empty.ToString();
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse<object>($"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);
|
||||
|
||||
+24
@@ -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<LuminaWebFactory>
|
||||
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.
|
||||
|
||||
+1
-5
@@ -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<LuminaWebFactory>
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.RegisterPutResponseFactory("users/me/settings/playback-state", _ => new EmptyRequest());
|
||||
_apiFactory.ApiClientStub.RegisterPutPayload<PlaybackStateDto>("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")
|
||||
|
||||
@@ -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<SuccessResponse>("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<ApiException>(() => 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()
|
||||
{
|
||||
|
||||
+12
-1
@@ -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<ApiException>(() => _sut.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, CancellationToken.None));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HasPermissionAsync_WhenTheApiReturnsNotFoundDuringAPageNavigation_ShouldThrowCurrentUserAuthorizationException()
|
||||
{
|
||||
// Arrange
|
||||
_httpContext.Request.Headers.Accept = "text/html";
|
||||
_mockApiHttpClient.GetAsync<GetAuthorizationResponse>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromException<GetAuthorizationResponse>(new ApiException(null, HttpStatusCode.NotFound, "/api/v1/auth/get-authorization?userId=1")));
|
||||
|
||||
// Act & Assert
|
||||
await Assert.ThrowsAsync<CurrentUserAuthorizationException>(() => _sut.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, CancellationToken.None));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HasPermissionAsync_WhenTheApiReturnsAServerErrorDuringAPageNavigation_ShouldReturnFalseAndMarkTheServerUnreachable()
|
||||
{
|
||||
|
||||
+20
-2
@@ -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<AuthenticationProperties?>());
|
||||
}
|
||||
|
||||
[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<HttpContext>(), Arg.Any<string?>(), Arg.Any<AuthenticationProperties?>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_WhenApiExceptionForbiddenAndApiRequest_ShouldWriteFailureJsonWithProblemDetail()
|
||||
{
|
||||
|
||||
+2
-2
@@ -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<Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest, Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest>(
|
||||
await _mockApiHttpClient.Received(1).PutIgnoringResponseAsync<FireScheduledJobRequest>(
|
||||
expectedEndpoint,
|
||||
Arg.Any<Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest>(),
|
||||
Arg.Is<FireScheduledJobRequest>(forwardedRequest => forwardedRequest.ScheduledJobId == request.ScheduledJobId),
|
||||
Arg.Any<CancellationToken>());
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
|
||||
+2
-2
@@ -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<Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest, Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest>(
|
||||
await _mockApiHttpClient.Received(1).PutIgnoringResponseAsync<StartScheduledJobRequest>(
|
||||
expectedEndpoint,
|
||||
Arg.Any<Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest>(),
|
||||
Arg.Is<StartScheduledJobRequest>(forwardedRequest => forwardedRequest.ScheduledJobId == request.ScheduledJobId),
|
||||
Arg.Any<CancellationToken>());
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
|
||||
+2
-2
@@ -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<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
|
||||
await _mockApiHttpClient.Received(1).PutIgnoringResponseAsync<StopScheduledJobRequest>(
|
||||
expectedEndpoint,
|
||||
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
|
||||
Arg.Is<StopScheduledJobRequest>(forwardedRequest => forwardedRequest.ScheduledJobId == request.ScheduledJobId),
|
||||
Arg.Any<CancellationToken>());
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
|
||||
+1
-1
@@ -46,7 +46,7 @@ public class UpdateSchedulerDisplayPreferencesEndpointTests
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutAsync<Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest, UpdateSchedulerDisplayPreferencesRequest>(
|
||||
await _mockApiHttpClient.Received(1).PutIgnoringResponseAsync<UpdateSchedulerDisplayPreferencesRequest>(
|
||||
ApiRoutes.ScheduledJobs.UPDATE_DISPLAY_PREFERENCES,
|
||||
Arg.Is<UpdateSchedulerDisplayPreferencesRequest>(forwardedRequest =>
|
||||
forwardedRequest.JobTypeFilter == request.JobTypeFilter &&
|
||||
|
||||
+2
-3
@@ -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<ThemeResponseDto, object>(expectedEndpoint, Arg.Any<object>(), Arg.Any<CancellationToken>());
|
||||
await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync(expectedEndpoint, Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
@@ -80,6 +79,6 @@ public class RestoreThemeEndpointTests
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status400BadRequest, problemResult.StatusCode);
|
||||
await _mockApiHttpClient.DidNotReceive().PostAsync<ThemeResponseDto, object>(Arg.Any<string>(), Arg.Any<object>(), Arg.Any<CancellationToken>());
|
||||
await _mockApiHttpClient.DidNotReceive().PostIgnoringResponseAsync(Arg.Any<string>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+6
-8
@@ -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();
|
||||
|
||||
/// <summary>
|
||||
@@ -44,8 +42,8 @@ public class SetCurrentThemeEndpointTests
|
||||
{
|
||||
// Arrange
|
||||
string themeId = "editorial-paper";
|
||||
_mockApiHttpClient.PutAsync<ThemeResponseDto, object>(Arg.Any<string>(), Arg.Any<object>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_themeResponseDtoFixture.Create());
|
||||
_mockApiHttpClient.PutIgnoringResponseAsync<SetCurrentThemeRequest>(Arg.Any<string>(), Arg.Any<SetCurrentThemeRequest>(), Arg.Any<CancellationToken>())
|
||||
.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<ThemeResponseDto, object>(
|
||||
await _mockApiHttpClient.Received(1).PutIgnoringResponseAsync<SetCurrentThemeRequest>(
|
||||
ApiRoutes.Themes.SET_CURRENT_THEME,
|
||||
Arg.Is<object>(payload => (payload.GetType().GetProperty("ThemeId")!.GetValue(payload) as string) == themeId),
|
||||
Arg.Is<SetCurrentThemeRequest>(payload => payload.ThemeId == themeId),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
@@ -73,6 +71,6 @@ public class SetCurrentThemeEndpointTests
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status400BadRequest, problemResult.StatusCode);
|
||||
await _mockApiHttpClient.DidNotReceive().PutAsync<ThemeResponseDto, object>(Arg.Any<string>(), Arg.Any<object>(), Arg.Any<CancellationToken>());
|
||||
await _mockApiHttpClient.DidNotReceive().PutIgnoringResponseAsync<SetCurrentThemeRequest>(Arg.Any<string>(), Arg.Any<SetCurrentThemeRequest>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+10
-22
@@ -30,11 +30,6 @@ public class RestoreMusicAlbumEndpointTests
|
||||
public RestoreMusicAlbumEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
// 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<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
|
||||
Arg.Any<string>(), Arg.Any<Web.Common.Requests.Common.EmptyRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new Web.Common.Requests.Common.EmptyRequest());
|
||||
_sut = Factory.Create<RestoreMusicAlbumEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
@@ -56,9 +51,8 @@ public class RestoreMusicAlbumEndpointTests
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
|
||||
await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync(
|
||||
BuildExpectedEndpoint(libraryId, artistId, albumId),
|
||||
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
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<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
|
||||
await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync(
|
||||
BuildExpectedEndpoint(libraryId, Guid.Empty, albumId),
|
||||
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
@@ -95,9 +88,8 @@ public class RestoreMusicAlbumEndpointTests
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
|
||||
await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync(
|
||||
BuildExpectedEndpoint(libraryId, Guid.Empty, albumId),
|
||||
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
@@ -113,9 +105,8 @@ public class RestoreMusicAlbumEndpointTests
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
|
||||
await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync(
|
||||
BuildExpectedEndpoint(libraryId, artistId, Guid.Empty),
|
||||
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
@@ -131,9 +122,8 @@ public class RestoreMusicAlbumEndpointTests
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
|
||||
await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync(
|
||||
BuildExpectedEndpoint(libraryId, artistId, Guid.Empty),
|
||||
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
@@ -149,9 +139,8 @@ public class RestoreMusicAlbumEndpointTests
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
|
||||
await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync(
|
||||
BuildExpectedEndpoint(Guid.Empty, artistId, albumId),
|
||||
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
@@ -167,9 +156,8 @@ public class RestoreMusicAlbumEndpointTests
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
|
||||
await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync(
|
||||
BuildExpectedEndpoint(Guid.Empty, artistId, albumId),
|
||||
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
@@ -183,9 +171,9 @@ public class RestoreMusicAlbumEndpointTests
|
||||
ConfigureRequest(artistId.ToString(), albumId.ToString(), libraryId.ToString());
|
||||
using CancellationTokenSource cancellationTokenSource = new();
|
||||
cancellationTokenSource.Cancel();
|
||||
_mockApiHttpClient.PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
|
||||
Arg.Any<string>(), Arg.Any<Web.Common.Requests.Common.EmptyRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromCanceled<Web.Common.Requests.Common.EmptyRequest>(cancellationTokenSource.Token));
|
||||
_mockApiHttpClient.PostIgnoringResponseAsync(
|
||||
Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromCanceled(cancellationTokenSource.Token));
|
||||
|
||||
// Act & Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(
|
||||
|
||||
+8
-18
@@ -30,11 +30,6 @@ public class RestoreMusicArtistEndpointTests
|
||||
public RestoreMusicArtistEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
// 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<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
|
||||
Arg.Any<string>(), Arg.Any<Web.Common.Requests.Common.EmptyRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new Web.Common.Requests.Common.EmptyRequest());
|
||||
_sut = Factory.Create<RestoreMusicArtistEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
@@ -55,9 +50,8 @@ public class RestoreMusicArtistEndpointTests
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
|
||||
await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync(
|
||||
BuildExpectedEndpoint(libraryId, artistId),
|
||||
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
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<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
|
||||
await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync(
|
||||
BuildExpectedEndpoint(libraryId, Guid.Empty),
|
||||
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
@@ -92,9 +85,8 @@ public class RestoreMusicArtistEndpointTests
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
|
||||
await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync(
|
||||
BuildExpectedEndpoint(libraryId, Guid.Empty),
|
||||
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
@@ -109,9 +101,8 @@ public class RestoreMusicArtistEndpointTests
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
|
||||
await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync(
|
||||
BuildExpectedEndpoint(Guid.Empty, artistId),
|
||||
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
@@ -126,9 +117,8 @@ public class RestoreMusicArtistEndpointTests
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
|
||||
await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync(
|
||||
BuildExpectedEndpoint(Guid.Empty, artistId),
|
||||
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
@@ -141,9 +131,9 @@ public class RestoreMusicArtistEndpointTests
|
||||
ConfigureRequest(artistId.ToString(), libraryId.ToString());
|
||||
using CancellationTokenSource cancellationTokenSource = new();
|
||||
cancellationTokenSource.Cancel();
|
||||
_mockApiHttpClient.PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
|
||||
Arg.Any<string>(), Arg.Any<Web.Common.Requests.Common.EmptyRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromCanceled<Web.Common.Requests.Common.EmptyRequest>(cancellationTokenSource.Token));
|
||||
_mockApiHttpClient.PostIgnoringResponseAsync(
|
||||
Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromCanceled(cancellationTokenSource.Token));
|
||||
|
||||
// Act & Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(
|
||||
|
||||
+12
-26
@@ -30,11 +30,6 @@ public class RestoreMusicTrackEndpointTests
|
||||
public RestoreMusicTrackEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
// 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<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
|
||||
Arg.Any<string>(), Arg.Any<Web.Common.Requests.Common.EmptyRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new Web.Common.Requests.Common.EmptyRequest());
|
||||
_sut = Factory.Create<RestoreMusicTrackEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
@@ -57,9 +52,8 @@ public class RestoreMusicTrackEndpointTests
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
|
||||
await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync(
|
||||
BuildExpectedEndpoint(libraryId, artistId, albumId, trackId),
|
||||
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
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<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
|
||||
await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync(
|
||||
BuildExpectedEndpoint(libraryId, Guid.Empty, albumId, trackId),
|
||||
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
@@ -98,9 +91,8 @@ public class RestoreMusicTrackEndpointTests
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
|
||||
await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync(
|
||||
BuildExpectedEndpoint(libraryId, Guid.Empty, albumId, trackId),
|
||||
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
@@ -117,9 +109,8 @@ public class RestoreMusicTrackEndpointTests
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
|
||||
await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync(
|
||||
BuildExpectedEndpoint(libraryId, artistId, Guid.Empty, trackId),
|
||||
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
@@ -136,9 +127,8 @@ public class RestoreMusicTrackEndpointTests
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
|
||||
await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync(
|
||||
BuildExpectedEndpoint(libraryId, artistId, Guid.Empty, trackId),
|
||||
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
@@ -155,9 +145,8 @@ public class RestoreMusicTrackEndpointTests
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
|
||||
await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync(
|
||||
BuildExpectedEndpoint(libraryId, artistId, albumId, Guid.Empty),
|
||||
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
@@ -174,9 +163,8 @@ public class RestoreMusicTrackEndpointTests
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
|
||||
await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync(
|
||||
BuildExpectedEndpoint(libraryId, artistId, albumId, Guid.Empty),
|
||||
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
@@ -193,9 +181,8 @@ public class RestoreMusicTrackEndpointTests
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
|
||||
await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync(
|
||||
BuildExpectedEndpoint(Guid.Empty, artistId, albumId, trackId),
|
||||
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
@@ -212,9 +199,8 @@ public class RestoreMusicTrackEndpointTests
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
|
||||
await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync(
|
||||
BuildExpectedEndpoint(Guid.Empty, artistId, albumId, trackId),
|
||||
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
@@ -229,9 +215,9 @@ public class RestoreMusicTrackEndpointTests
|
||||
ConfigureRequest(artistId.ToString(), albumId.ToString(), trackId.ToString(), libraryId.ToString());
|
||||
using CancellationTokenSource cancellationTokenSource = new();
|
||||
cancellationTokenSource.Cancel();
|
||||
_mockApiHttpClient.PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
|
||||
Arg.Any<string>(), Arg.Any<Web.Common.Requests.Common.EmptyRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromCanceled<Web.Common.Requests.Common.EmptyRequest>(cancellationTokenSource.Token));
|
||||
_mockApiHttpClient.PostIgnoringResponseAsync(
|
||||
Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromCanceled(cancellationTokenSource.Token));
|
||||
|
||||
// Act & Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(
|
||||
|
||||
+3
-15
@@ -40,18 +40,14 @@ public class RestoreBookEndpointTests
|
||||
Guid bookId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ConfigureRequest(bookId.ToString(), libraryId);
|
||||
_mockApiHttpClient.PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
|
||||
Arg.Any<string>(), Arg.Any<Web.Common.Requests.Common.EmptyRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new Web.Common.Requests.Common.EmptyRequest());
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
|
||||
await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync(
|
||||
BuildExpectedEndpoint(libraryId, bookId),
|
||||
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
@@ -64,17 +60,13 @@ public class RestoreBookEndpointTests
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ConfigureRequest("not-a-guid", libraryId);
|
||||
_mockApiHttpClient.PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
|
||||
Arg.Any<string>(), Arg.Any<Web.Common.Requests.Common.EmptyRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new Web.Common.Requests.Common.EmptyRequest());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
|
||||
await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync(
|
||||
BuildExpectedEndpoint(libraryId, Guid.Empty),
|
||||
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
@@ -84,17 +76,13 @@ public class RestoreBookEndpointTests
|
||||
// Arrange
|
||||
Guid bookId = Guid.NewGuid();
|
||||
ConfigureRequest(bookId.ToString(), "not-a-guid");
|
||||
_mockApiHttpClient.PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
|
||||
Arg.Any<string>(), Arg.Any<Web.Common.Requests.Common.EmptyRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new Web.Common.Requests.Common.EmptyRequest());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
|
||||
await _mockApiHttpClient.Received(1).PostIgnoringResponseAsync(
|
||||
BuildExpectedEndpoint(Guid.Empty, bookId),
|
||||
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
|
||||
+19
-26
@@ -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<ConsumptionRecordDto, EmptyRequest>(Arg.Any<string>(), Arg.Any<EmptyRequest>(), Arg.Any<CancellationToken>())
|
||||
_mockApiHttpClient.PostAsync<ConsumptionRecordDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.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<ConsumptionRecordDto, EmptyRequest>(Arg.Any<string>(), Arg.Any<EmptyRequest>(), Arg.Any<CancellationToken>())
|
||||
_mockApiHttpClient.PostAsync<ConsumptionRecordDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedRecord);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostAsync<ConsumptionRecordDto, EmptyRequest>(
|
||||
await _mockApiHttpClient.Received(1).PostAsync<ConsumptionRecordDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == $"libraries/{s_libraryId}/media-items/MusicTrack/{s_mediaItemId}/consumption-records"),
|
||||
Arg.Any<EmptyRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
@@ -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<ConsumptionRecordDto, EmptyRequest>(Arg.Any<string>(), Arg.Any<EmptyRequest>(), Arg.Any<CancellationToken>())
|
||||
_mockApiHttpClient.PostAsync<ConsumptionRecordDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedRecord);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostAsync<ConsumptionRecordDto, EmptyRequest>(
|
||||
await _mockApiHttpClient.Received(1).PostAsync<ConsumptionRecordDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == $"libraries/{s_libraryId}/media-items/Book/{s_mediaItemId}/consumption-records"),
|
||||
Arg.Any<EmptyRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
@@ -117,16 +115,15 @@ public class StartConsumptionEndpointTests
|
||||
// Arrange
|
||||
ConsumptionRecordDto expectedRecord = _consumptionRecordDtoFixture.Create();
|
||||
SetRouteValues("not-a-guid", nameof(MediaKind.MusicTrack), s_mediaItemId);
|
||||
_mockApiHttpClient.PostAsync<ConsumptionRecordDto, EmptyRequest>(Arg.Any<string>(), Arg.Any<EmptyRequest>(), Arg.Any<CancellationToken>())
|
||||
_mockApiHttpClient.PostAsync<ConsumptionRecordDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedRecord);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostAsync<ConsumptionRecordDto, EmptyRequest>(
|
||||
await _mockApiHttpClient.Received(1).PostAsync<ConsumptionRecordDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == $"libraries/{ZERO_GUID}/media-items/MusicTrack/{s_mediaItemId}/consumption-records"),
|
||||
Arg.Any<EmptyRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
@@ -136,16 +133,15 @@ public class StartConsumptionEndpointTests
|
||||
// Arrange
|
||||
ConsumptionRecordDto expectedRecord = _consumptionRecordDtoFixture.Create();
|
||||
SetRouteValues(s_libraryId, nameof(MediaKind.MusicTrack), "not-a-guid");
|
||||
_mockApiHttpClient.PostAsync<ConsumptionRecordDto, EmptyRequest>(Arg.Any<string>(), Arg.Any<EmptyRequest>(), Arg.Any<CancellationToken>())
|
||||
_mockApiHttpClient.PostAsync<ConsumptionRecordDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedRecord);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostAsync<ConsumptionRecordDto, EmptyRequest>(
|
||||
await _mockApiHttpClient.Received(1).PostAsync<ConsumptionRecordDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == $"libraries/{s_libraryId}/media-items/MusicTrack/{ZERO_GUID}/consumption-records"),
|
||||
Arg.Any<EmptyRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
@@ -154,16 +150,15 @@ public class StartConsumptionEndpointTests
|
||||
{
|
||||
// Arrange
|
||||
ConsumptionRecordDto expectedRecord = _consumptionRecordDtoFixture.Create();
|
||||
_mockApiHttpClient.PostAsync<ConsumptionRecordDto, EmptyRequest>(Arg.Any<string>(), Arg.Any<EmptyRequest>(), Arg.Any<CancellationToken>())
|
||||
_mockApiHttpClient.PostAsync<ConsumptionRecordDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedRecord);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostAsync<ConsumptionRecordDto, EmptyRequest>(
|
||||
await _mockApiHttpClient.Received(1).PostAsync<ConsumptionRecordDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == $"libraries/{ZERO_GUID}/media-items/Invalid/{ZERO_GUID}/consumption-records"),
|
||||
Arg.Any<EmptyRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
@@ -179,16 +174,15 @@ public class StartConsumptionEndpointTests
|
||||
// Arrange
|
||||
ConsumptionRecordDto expectedRecord = _consumptionRecordDtoFixture.Create();
|
||||
SetRouteValues(s_libraryId, routeMediaKind, s_mediaItemId);
|
||||
_mockApiHttpClient.PostAsync<ConsumptionRecordDto, EmptyRequest>(Arg.Any<string>(), Arg.Any<EmptyRequest>(), Arg.Any<CancellationToken>())
|
||||
_mockApiHttpClient.PostAsync<ConsumptionRecordDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedRecord);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostAsync<ConsumptionRecordDto, EmptyRequest>(
|
||||
await _mockApiHttpClient.Received(1).PostAsync<ConsumptionRecordDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == $"libraries/{s_libraryId}/media-items/{expectedMediaKind}/{s_mediaItemId}/consumption-records"),
|
||||
Arg.Any<EmptyRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
@@ -206,16 +200,15 @@ public class StartConsumptionEndpointTests
|
||||
// Arrange
|
||||
ConsumptionRecordDto expectedRecord = _consumptionRecordDtoFixture.Create();
|
||||
SetRouteValues(s_libraryId, routeMediaKind, s_mediaItemId);
|
||||
_mockApiHttpClient.PostAsync<ConsumptionRecordDto, EmptyRequest>(Arg.Any<string>(), Arg.Any<EmptyRequest>(), Arg.Any<CancellationToken>())
|
||||
_mockApiHttpClient.PostAsync<ConsumptionRecordDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedRecord);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostAsync<ConsumptionRecordDto, EmptyRequest>(
|
||||
await _mockApiHttpClient.Received(1).PostAsync<ConsumptionRecordDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == $"libraries/{s_libraryId}/media-items/Invalid/{s_mediaItemId}/consumption-records"),
|
||||
Arg.Any<EmptyRequest>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
@@ -225,7 +218,7 @@ public class StartConsumptionEndpointTests
|
||||
// Arrange
|
||||
ConsumptionRecordDto expectedRecord = _consumptionRecordDtoFixture.Create();
|
||||
SetRouteValues(s_libraryId, nameof(MediaKind.MusicTrack), s_mediaItemId);
|
||||
_mockApiHttpClient.PostAsync<ConsumptionRecordDto, EmptyRequest>(Arg.Any<string>(), Arg.Any<EmptyRequest>(), Arg.Any<CancellationToken>())
|
||||
_mockApiHttpClient.PostAsync<ConsumptionRecordDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedRecord);
|
||||
|
||||
// Act
|
||||
@@ -245,14 +238,14 @@ public class StartConsumptionEndpointTests
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
SetRouteValues(s_libraryId, nameof(MediaKind.MusicTrack), s_mediaItemId);
|
||||
_mockApiHttpClient.PostAsync<ConsumptionRecordDto, EmptyRequest>(Arg.Any<string>(), Arg.Any<EmptyRequest>(), Arg.Any<CancellationToken>())
|
||||
_mockApiHttpClient.PostAsync<ConsumptionRecordDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.ArgAt<CancellationToken>(2).ThrowIfCancellationRequested();
|
||||
callInfo.ArgAt<CancellationToken>(1).ThrowIfCancellationRequested();
|
||||
return expectedRecord;
|
||||
}, callInfo.ArgAt<CancellationToken>(2)));
|
||||
}, callInfo.ArgAt<CancellationToken>(1)));
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(EmptyRequest.Instance, cts.Token);
|
||||
|
||||
+3
-3
@@ -40,8 +40,8 @@ public class UpdatePluginSettingsEndpointTests
|
||||
{
|
||||
// Arrange
|
||||
UpdatePluginSettingsRequest request = _updatePluginSettingsRequestFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest, UpdatePluginSettingsRequest>(Arg.Any<string>(), Arg.Any<UpdatePluginSettingsRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest());
|
||||
_mockApiHttpClient.PutIgnoringResponseAsync<UpdatePluginSettingsRequest>(Arg.Any<string>(), Arg.Any<UpdatePluginSettingsRequest>(), Arg.Any<CancellationToken>())
|
||||
.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<Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest, UpdatePluginSettingsRequest>(
|
||||
await _mockApiHttpClient.Received(1).PutIgnoringResponseAsync<UpdatePluginSettingsRequest>(
|
||||
expectedEndpoint,
|
||||
Arg.Is<UpdatePluginSettingsRequest>(settings => settings.PluginId == request.PluginId),
|
||||
Arg.Any<CancellationToken>());
|
||||
|
||||
+9
-11
@@ -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<WebEmptyRequest, PlaybackStateDto>(Arg.Any<string>(), Arg.Any<PlaybackStateDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new WebEmptyRequest());
|
||||
_mockApiHttpClient.PutIgnoringResponseAsync<PlaybackStateDto>(Arg.Any<string>(), Arg.Any<PlaybackStateDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutAsync<WebEmptyRequest, PlaybackStateDto>(
|
||||
await _mockApiHttpClient.Received(1).PutIgnoringResponseAsync<PlaybackStateDto>(
|
||||
ApiRoutes.Users.UPDATE_PLAYBACK_STATE,
|
||||
Arg.Is<PlaybackStateDto>(state => state.Volume == 0.35 && state.IsMuted == true),
|
||||
Arg.Any<CancellationToken>());
|
||||
@@ -64,14 +62,14 @@ public class UpdatePlaybackStateEndpointTests
|
||||
{
|
||||
// Arrange
|
||||
PlaybackStateDto request = _playbackStateDtoFixture.Create(volume: 0.0, isMuted: false);
|
||||
_mockApiHttpClient.PutAsync<WebEmptyRequest, PlaybackStateDto>(Arg.Any<string>(), Arg.Any<PlaybackStateDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new WebEmptyRequest());
|
||||
_mockApiHttpClient.PutIgnoringResponseAsync<PlaybackStateDto>(Arg.Any<string>(), Arg.Any<PlaybackStateDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutAsync<WebEmptyRequest, PlaybackStateDto>(
|
||||
await _mockApiHttpClient.Received(1).PutIgnoringResponseAsync<PlaybackStateDto>(
|
||||
ApiRoutes.Users.UPDATE_PLAYBACK_STATE,
|
||||
Arg.Is<PlaybackStateDto>(state => state.Volume == 0.0 && state.IsMuted == false),
|
||||
Arg.Any<CancellationToken>());
|
||||
@@ -82,14 +80,14 @@ public class UpdatePlaybackStateEndpointTests
|
||||
{
|
||||
// Arrange
|
||||
PlaybackStateDto request = _playbackStateDtoFixture.Create(includeVolume: false, includeIsMuted: false);
|
||||
_mockApiHttpClient.PutAsync<WebEmptyRequest, PlaybackStateDto>(Arg.Any<string>(), Arg.Any<PlaybackStateDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new WebEmptyRequest());
|
||||
_mockApiHttpClient.PutIgnoringResponseAsync<PlaybackStateDto>(Arg.Any<string>(), Arg.Any<PlaybackStateDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutAsync<WebEmptyRequest, PlaybackStateDto>(
|
||||
await _mockApiHttpClient.Received(1).PutIgnoringResponseAsync<PlaybackStateDto>(
|
||||
ApiRoutes.Users.UPDATE_PLAYBACK_STATE,
|
||||
Arg.Is<PlaybackStateDto>(state => state.Volume == null && state.IsMuted == null),
|
||||
Arg.Any<CancellationToken>());
|
||||
|
||||
+6
-6
@@ -55,15 +55,15 @@ public class UpdateUserSettingsEndpointTests
|
||||
{
|
||||
// Arrange
|
||||
UserSettingsDto request = _userSettingsDtoFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<Web.Common.Requests.Common.EmptyRequest, UserSettingsDto>(Arg.Any<string>(), Arg.Any<UserSettingsDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new Web.Common.Requests.Common.EmptyRequest());
|
||||
_mockApiHttpClient.PutIgnoringResponseAsync<UserSettingsDto>(Arg.Any<string>(), Arg.Any<UserSettingsDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutAsync<Web.Common.Requests.Common.EmptyRequest, UserSettingsDto>(
|
||||
await _mockApiHttpClient.Received(1).PutIgnoringResponseAsync<UserSettingsDto>(
|
||||
ApiRoutes.Users.UPDATE_USER_SETTINGS,
|
||||
Arg.Is<UserSettingsDto>(settings => settings.ItemsPerPage == request.ItemsPerPage && settings.IsPaginationEnabled == request.IsPaginationEnabled),
|
||||
Arg.Any<CancellationToken>());
|
||||
@@ -86,15 +86,15 @@ public class UpdateUserSettingsEndpointTests
|
||||
vuMeterPeakHoldDurationInMilliseconds: 1200,
|
||||
vuMeterReleasePerSecond: 7.5,
|
||||
vuMeterPeakReleasePerSecond: 0.25);
|
||||
_mockApiHttpClient.PutAsync<Web.Common.Requests.Common.EmptyRequest, UserSettingsDto>(Arg.Any<string>(), Arg.Any<UserSettingsDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new Web.Common.Requests.Common.EmptyRequest());
|
||||
_mockApiHttpClient.PutIgnoringResponseAsync<UserSettingsDto>(Arg.Any<string>(), Arg.Any<UserSettingsDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
await _mockApiHttpClient.Received(1).PutAsync<Web.Common.Requests.Common.EmptyRequest, UserSettingsDto>(
|
||||
await _mockApiHttpClient.Received(1).PutIgnoringResponseAsync<UserSettingsDto>(
|
||||
ApiRoutes.Users.UPDATE_USER_SETTINGS,
|
||||
Arg.Is<UserSettingsDto>(settings =>
|
||||
settings.VuMeterOrientation == VuMeterOrientation.Horizontal &&
|
||||
|
||||
@@ -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<ThemeResponseDto, object>(Arg.Any<string>(), Arg.Any<object>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_themeResponseDtoFixture.Create());
|
||||
_mockApiHttpClient.PutIgnoringResponseAsync<SetCurrentThemeRequest>(Arg.Any<string>(), Arg.Any<SetCurrentThemeRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
// Act
|
||||
await _sut.SetCurrentThemeAsync(themeId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutAsync<ThemeResponseDto, object>(
|
||||
await _mockApiHttpClient.Received(1).PutIgnoringResponseAsync<SetCurrentThemeRequest>(
|
||||
ApiRoutes.Themes.SET_CURRENT_THEME,
|
||||
Arg.Is<object>(payload => payload.GetType().GetProperty("ThemeId")!.GetValue(payload)!.ToString()! == themeId),
|
||||
Arg.Is<SetCurrentThemeRequest>(payload => payload.ThemeId == themeId),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user