mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
Implements tests for commit 525ac1348d
Covers the favorites feature and the playlist and favorite pagination changes with unit, integration and security tests, and fixtures for the new request, response, DTO and entity types. Also fixes the issues found while covering the commit: declares FavoriteMediaKind.None as the default value and rejects it in every favorite operation; queues the favorite added domain event only after the persisted favorite is read back; and preserves the private, no-store cache header on view pages after the antiforgery and session middlewares overwrite it.
This commit is contained in:
1 parent
468f1846f1
commit
394f6b510c
135 files changed
+19167
-13
No files matched your search
@@ -313,7 +313,7 @@ The validation errors of each operation are:
|
||||
|
||||
| Error | Operation | When |
|
||||
| --- | --- | --- |
|
||||
| `FavoriteMediaKindIsInvalid` | Add, Remove, Get Favorites, Get Favorite Status | The kind is missing where it is required, or it is a number that is not a member of the media kind enumeration. In the Remove route, the segment is not a member name of the enumeration, and numbers are not accepted. |
|
||||
| `FavoriteMediaKindIsInvalid` | Add, Remove, Get Favorites, Get Favorite Status | The kind is missing where it is required, the kind is `None`, or it is a number that is not a member of the media kind enumeration. In the Remove route, the segment is not a member name of the enumeration, and numbers are not accepted. |
|
||||
| `FavoriteMediaKindIsNotSupported` | Add | The kind is `Video` or `Photo`, which are planned and cannot be favorited yet. |
|
||||
| `FavoriteMediaItemIdCannotBeEmpty` | Add, Remove, Get Favorite Status | The item Id is missing or is the empty Guid. In the Remove route it is also reported when the segment is not a Guid. For the status request, any of the Ids is the empty Guid. |
|
||||
| `FavoriteMediaItemIdsCannotBeEmpty` | Get Favorite Status | No `mediaItemIds` were given. |
|
||||
|
||||
+4
@@ -102,3 +102,7 @@ Report `FavoriteAlreadyExists` instead of returning the existing favorite.
|
||||
|
||||
**Rejected**: a toggle rendered on several pages, and several open tabs, make a repeated add a normal event rather than an error. An idempotent add keeps the client simple, since it does not have to distinguish a created favorite from an existing one. `FavoriteAlreadyExists` remains defined in the favorites error set, but no operation produces it.
|
||||
|
||||
## Amendment: Explicit Default Media Kind (2026-10-29)
|
||||
|
||||
`FavoriteMediaKind` now declares `None = 0` as its first member and default value, so an unset kind is never mistaken for `MusicArtist`. The other members keep their order and now occupy values 1 to 6. `None` is not a favoritable kind: the application validators reject it with `FavoriteMediaKindIsInvalid`, `Favorite.IsSupported` reports it as unsupported, and no operation creates a favorite of it. A stored favorite whose kind was recorded as `None` is still rehydrated without failure, so the read paths remain tolerant of legacy or malformed rows. Because the kind is stored by name, no data migration is required.
|
||||
|
||||
+5
-4
@@ -136,10 +136,6 @@ public class AddFavoriteCommandHandler : ICommandHandler<AddFavoriteCommand, Res
|
||||
return getConcurrentFavoriteResult.Value.ToResponse();
|
||||
}
|
||||
|
||||
// Queue any domain events, to be published after the request has completed successfully.
|
||||
foreach (IDomainEvent domainEvent in favorite.GetDomainEvents())
|
||||
_domainEventsQueue.Enqueue(domainEvent);
|
||||
|
||||
// The persisted row is read back, so the response carries the timestamps the auditing interceptor actually stored.
|
||||
Result<FavoriteEntity?> getFavoriteResult = await _unitOfWork.FavoriteRepository
|
||||
.GetByMediaItemIdForUserAsync(userId, mediaKind, mediaItemId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
@@ -148,6 +144,11 @@ public class AddFavoriteCommandHandler : ICommandHandler<AddFavoriteCommand, Res
|
||||
if (getFavoriteResult.Value is null)
|
||||
return DomainErrors.Favorites.FavoriteNotFound;
|
||||
|
||||
// Queue any domain events, to be published after the request has completed successfully. The events are queued only after the persisted
|
||||
// row has been read back, so a failed read cannot announce a favorite that the request reports as failed.
|
||||
foreach (IDomainEvent domainEvent in favorite.GetDomainEvents())
|
||||
_domainEventsQueue.Enqueue(domainEvent);
|
||||
|
||||
return getFavoriteResult.Value.ToResponse();
|
||||
}
|
||||
}
|
||||
+6
@@ -2,6 +2,7 @@
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Utilities;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
@@ -26,6 +27,11 @@ public class AddFavoriteCommandValidator : AbstractValidator<AddFavoriteCommand>
|
||||
.WithError(Errors.Favorites.FavoriteMediaKindIsInvalid)
|
||||
.When(command => command.MediaKind is not null);
|
||||
|
||||
RuleFor(command => command.MediaKind)
|
||||
.Must(mediaKind => mediaKind != FavoriteMediaKind.None)
|
||||
.WithError(Errors.Favorites.FavoriteMediaKindIsInvalid)
|
||||
.When(command => command.MediaKind is not null);
|
||||
|
||||
RuleFor(command => command.MediaItemId)
|
||||
.NotNull()
|
||||
.WithError(Errors.Favorites.FavoriteMediaItemIdCannotBeEmpty);
|
||||
|
||||
+5
-2
@@ -23,9 +23,12 @@ public class RemoveFavoriteCommandValidator : AbstractValidator<RemoveFavoriteCo
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Favorites.FavoriteMediaKindIsInvalid);
|
||||
|
||||
// Only the member names are accepted, so a numeric route value that happens to parse as an enumeration value is rejected.
|
||||
// Only the member names other than the default None are accepted, so a numeric route value that happens to parse as an
|
||||
// enumeration value, or the explicit default value, is rejected.
|
||||
RuleFor(command => command.MediaKind)
|
||||
.Must(mediaKind => Enum.GetNames<FavoriteMediaKind>().Contains(mediaKind, StringComparer.OrdinalIgnoreCase))
|
||||
.Must(mediaKind => Enum.GetNames<FavoriteMediaKind>()
|
||||
.Where(mediaKindName => !string.Equals(mediaKindName, nameof(FavoriteMediaKind.None), StringComparison.Ordinal))
|
||||
.Contains(mediaKind, StringComparer.OrdinalIgnoreCase))
|
||||
.When(command => command.MediaKind is not null && command.MediaKind.Length > 0)
|
||||
.WithError(Errors.Favorites.FavoriteMediaKindIsInvalid);
|
||||
|
||||
|
||||
+6
@@ -2,6 +2,7 @@
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Utilities;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
@@ -29,6 +30,11 @@ public class GetFavoriteStatusQueryValidator : AbstractValidator<GetFavoriteStat
|
||||
.WithError(Errors.Favorites.FavoriteMediaKindIsInvalid)
|
||||
.When(query => query.MediaKind is not null);
|
||||
|
||||
RuleFor(query => query.MediaKind)
|
||||
.Must(mediaKind => mediaKind != FavoriteMediaKind.None)
|
||||
.WithError(Errors.Favorites.FavoriteMediaKindIsInvalid)
|
||||
.When(query => query.MediaKind is not null);
|
||||
|
||||
RuleFor(query => query.MediaItemIds)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Favorites.FavoriteMediaItemIdsCannotBeEmpty);
|
||||
|
||||
+6
@@ -2,6 +2,7 @@
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Utilities;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Favorites.Queries.GetFavorites;
|
||||
@@ -20,5 +21,10 @@ public class GetFavoritesQueryValidator : AbstractValidator<GetFavoritesQuery>
|
||||
.IsInEnum()
|
||||
.WithError(Errors.Favorites.FavoriteMediaKindIsInvalid)
|
||||
.When(query => query.MediaKind is not null);
|
||||
|
||||
RuleFor(query => query.MediaKind)
|
||||
.Must(mediaKind => mediaKind != FavoriteMediaKind.None)
|
||||
.WithError(Errors.Favorites.FavoriteMediaKindIsInvalid)
|
||||
.When(query => query.MediaKind is not null);
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,11 @@ namespace Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
[DebuggerDisplay("{ToString()}")]
|
||||
public enum FavoriteMediaKind
|
||||
{
|
||||
/// <summary>
|
||||
/// No media kind. Used as the default value; it is not a kind that can be marked as a favorite.
|
||||
/// </summary>
|
||||
None = 0,
|
||||
|
||||
/// <summary>
|
||||
/// A favorite that references an artist of a music library.
|
||||
/// </summary>
|
||||
|
||||
@@ -10,6 +10,11 @@ namespace Lumina.Presentation.Web.Common.Enums.Favorites;
|
||||
[DebuggerDisplay("{ToString()}")]
|
||||
public enum FavoriteMediaKind
|
||||
{
|
||||
/// <summary>
|
||||
/// No media kind. Used as the default value; it is not a kind that can be marked as a favorite.
|
||||
/// </summary>
|
||||
None = 0,
|
||||
|
||||
/// <summary>
|
||||
/// A favorite that references an artist of a music library.
|
||||
/// </summary>
|
||||
|
||||
@@ -8,4 +8,9 @@ public static class HttpContextItemKeys
|
||||
public const string ERRORS = "errors";
|
||||
public const string PENDING_SUPER_ADMIN_SETUP = "PendingSuperAdminSetup";
|
||||
public const string LAST_DISPLAYED_VIEW = "LastViewUrl";
|
||||
|
||||
/// <summary>
|
||||
/// The <c>Cache-Control</c> value chosen by the endpoint, restored when the response starts.
|
||||
/// </summary>
|
||||
public const string CACHE_CONTROL = "CacheControl";
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Http;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.Middlewares;
|
||||
|
||||
/// <summary>
|
||||
/// Middleware that restores the <c>Cache-Control</c> header chosen by an endpoint after any middleware that overwrites it.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The session middleware sets <c>Cache-Control: no-cache,no-store</c>, <c>Pragma: no-cache</c> and <c>Expires: -1</c> when it establishes
|
||||
/// a new session, and it registers that write before the endpoint runs. Response-start callbacks run in reverse registration order, so a
|
||||
/// callback registered here, before the session middleware, runs after the session middleware and can restore the endpoint's value.
|
||||
/// </remarks>
|
||||
public class CacheControlHeaderMiddleware
|
||||
{
|
||||
private readonly RequestDelegate _next;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CacheControlHeaderMiddleware"/> class.
|
||||
/// </summary>
|
||||
/// <param name="next">The next middleware in the request pipeline.</param>
|
||||
public CacheControlHeaderMiddleware(RequestDelegate next)
|
||||
{
|
||||
_next = next;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Restores the endpoint's <c>Cache-Control</c> value when the response starts, after the response-start callbacks registered later, such as the session middleware's, have run.
|
||||
/// </summary>
|
||||
/// <param name="context">The <see cref="HttpContext"/> for the current request.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
public async Task InvokeAsync(HttpContext context)
|
||||
{
|
||||
context.Response.OnStarting(() =>
|
||||
{
|
||||
if (context.Items.TryGetValue(HttpContextItemKeys.CACHE_CONTROL, out object? value) && value is string cacheControl && !string.IsNullOrEmpty(cacheControl))
|
||||
context.Response.Headers.CacheControl = cacheControl;
|
||||
return Task.CompletedTask;
|
||||
});
|
||||
await _next(context);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Middlewares;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.Utilities;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for adding the <see cref="CacheControlHeaderMiddleware"/> to the request pipeline.
|
||||
/// </summary>
|
||||
public static class CacheControlHeaderMiddlewareUtilities
|
||||
{
|
||||
/// <summary>
|
||||
/// Adds the <see cref="CacheControlHeaderMiddleware"/> to the application's request pipeline.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// It must be registered before the session middleware, so that its response-start callback runs after the one of the session middleware.
|
||||
/// </remarks>
|
||||
/// <param name="builder">The <see cref="IApplicationBuilder"/> used to configure the application's request pipeline.</param>
|
||||
/// <returns>The <see cref="IApplicationBuilder"/> for further configuration.</returns>
|
||||
public static IApplicationBuilder UseCacheControlHeader(this IApplicationBuilder builder)
|
||||
{
|
||||
return builder.UseMiddleware<CacheControlHeaderMiddleware>();
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,20 @@ public abstract class BaseEndpoint<TRequest, TResponse> : Endpoint<TRequest, TRe
|
||||
DontCatchExceptions();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the <c>Cache-Control</c> header, and remembers the chosen value so that it can be restored after later components overwrite it.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The antiforgery token generation and the session middleware both force their own <c>Cache-Control</c> value, and they can run after the
|
||||
/// endpoint has chosen one. The remembered value is restored when the response starts by the <c>CacheControlHeaderMiddleware</c>.
|
||||
/// </remarks>
|
||||
/// <param name="cacheControl">The <c>Cache-Control</c> value chosen by the endpoint.</param>
|
||||
protected void SetCacheControl(string cacheControl)
|
||||
{
|
||||
HttpContext.Response.Headers.CacheControl = cacheControl;
|
||||
HttpContext.Items[HttpContextItemKeys.CACHE_CONTROL] = cacheControl;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Renders a Razor view to the response.
|
||||
/// </summary>
|
||||
@@ -40,6 +54,13 @@ public abstract class BaseEndpoint<TRequest, TResponse> : Endpoint<TRequest, TRe
|
||||
/// <returns>An <see cref="IResult"/> that renders the view.</returns>
|
||||
protected IResult View(string viewName, object? model = null, IReadOnlyDictionary<string, object?>? viewData = null)
|
||||
{
|
||||
// A view endpoint that set the Cache-Control header directly, instead of through SetCacheControl, still has its value remembered.
|
||||
if (!HttpContext.Items.ContainsKey(HttpContextItemKeys.CACHE_CONTROL))
|
||||
{
|
||||
string cacheControl = HttpContext.Response.Headers.CacheControl.ToString();
|
||||
if (!string.IsNullOrEmpty(cacheControl))
|
||||
HttpContext.Items[HttpContextItemKeys.CACHE_CONTROL] = cacheControl;
|
||||
}
|
||||
// Store the path of the displayed view in the session, so that the login redirect after the JWT token expires points to it; ignore the login endpoint,
|
||||
// because it is incorrect to be redirected to the login URL, with the login URL as the return URL.
|
||||
if (HttpContext.Request.Path != "/en-us/auth/login")
|
||||
|
||||
+1
-1
@@ -69,7 +69,7 @@ public class FavoritesIndexViewEndpoint : BaseEndpoint<EmptyRequest, IResult>
|
||||
public override async Task<IResult> ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
// The page shows the favorites of the authenticated user, so no intermediary may store it, and the response varies by the sign in cookie.
|
||||
HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
|
||||
SetCacheControl("private, no-store");
|
||||
HttpContext.Response.Headers["Vary"] = "Cookie";
|
||||
// The page removes favorites, which submit through the form anti-forgery token, so a fresh token is issued for it.
|
||||
AntiforgeryTokenSet antiforgeryTokens = _antiforgery.GetAndStoreTokens(HttpContext);
|
||||
|
||||
+1
-1
@@ -57,7 +57,7 @@ public class RemoveFavoriteEndpoint : BaseEndpoint<FastEndpoints.EmptyRequest, I
|
||||
string routeMediaKind = HttpContext.Request.RouteValues["mediaKind"]?.ToString() ?? string.Empty;
|
||||
string mediaKind = INVALID_MEDIA_KIND_PLACEHOLDER;
|
||||
foreach (string mediaKindName in Enum.GetNames<FavoriteMediaKind>())
|
||||
if (string.Equals(mediaKindName, routeMediaKind, StringComparison.OrdinalIgnoreCase))
|
||||
if (mediaKindName != nameof(FavoriteMediaKind.None) && string.Equals(mediaKindName, routeMediaKind, StringComparison.OrdinalIgnoreCase))
|
||||
mediaKind = mediaKindName;
|
||||
string routeMediaItemId = HttpContext.Request.RouteValues["mediaItemId"]?.ToString() ?? string.Empty;
|
||||
string mediaItemId = Guid.TryParse(routeMediaItemId, out Guid parsedMediaItemId) ? parsedMediaItemId.ToString() : Guid.Empty.ToString();
|
||||
|
||||
+1
-1
@@ -70,7 +70,7 @@ public class StatisticsIndexViewEndpoint : BaseEndpoint<EmptyRequest, IResult>
|
||||
public override async Task<IResult> ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
// The page shows the statistics of the authenticated user, so no intermediary may store it, and the response varies by the sign in cookie.
|
||||
HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
|
||||
SetCacheControl("private, no-store");
|
||||
HttpContext.Response.Headers["Vary"] = "Cookie";
|
||||
string title = _localizer["Title"].Value;
|
||||
bool isAdmin = await _authorizationService.IsInRoleAsync("Admin", cancellationToken).ConfigureAwait(false);
|
||||
|
||||
+1
-1
@@ -69,7 +69,7 @@ public class PlaylistsIndexViewEndpoint : BaseEndpoint<EmptyRequest, IResult>
|
||||
public override async Task<IResult> ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
// The page shows the playlists of the authenticated user, so no intermediary may store it, and the response varies by the sign in cookie.
|
||||
HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
|
||||
SetCacheControl("private, no-store");
|
||||
HttpContext.Response.Headers["Vary"] = "Cookie";
|
||||
// The page creates and deletes playlists, which submit through the form anti-forgery token, so a fresh token is issued for it.
|
||||
AntiforgeryTokenSet antiforgeryTokens = _antiforgery.GetAndStoreTokens(HttpContext);
|
||||
|
||||
+1
-1
@@ -81,7 +81,7 @@ public class AddPlaylistViewEndpoint : BaseEndpoint<EmptyRequest, IResult>
|
||||
public override async Task<IResult> ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
// The page creates a playlist of the authenticated user, so no intermediary may store it, and the response varies by the sign in cookie.
|
||||
HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
|
||||
SetCacheControl("private, no-store");
|
||||
HttpContext.Response.Headers["Vary"] = "Cookie";
|
||||
|
||||
// The page submits through the form anti-forgery token, so a fresh token is issued for it.
|
||||
|
||||
+1
-1
@@ -83,7 +83,7 @@ public class PlaylistItemViewEndpoint : BaseEndpoint<EmptyRequest, IResult>
|
||||
public override async Task<IResult> ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
// The page shows a playlist of the authenticated user, so no intermediary may store it, and the response varies by the sign in cookie.
|
||||
HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
|
||||
SetCacheControl("private, no-store");
|
||||
HttpContext.Response.Headers["Vary"] = "Cookie";
|
||||
// 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, and an unparseable id is reported by the API as a missing playlist id.
|
||||
|
||||
@@ -97,6 +97,8 @@ public class Program
|
||||
app.UseApiExceptionHandling(); // handle any problem details returned by the API
|
||||
app.UseRouting();
|
||||
app.UseRequestLocalization(); // set the culture from the localized routes
|
||||
// restore the Cache-Control chosen by the endpoint after the antiforgery and session middlewares overwrite it
|
||||
app.UseCacheControlHeader();
|
||||
app.UseSession();
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Common.DTO.Favorites;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Fixtures.Common.DTO.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="FavoriteItemDisplayDto"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FavoriteItemDisplayDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="FavoriteItemDisplayDto"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">Optional. The Id of the media library that contains the media item.</param>
|
||||
/// <param name="title">Optional. The title of the media item.</param>
|
||||
/// <param name="collectionId">Optional. The Id of the collection that contains the media item.</param>
|
||||
/// <param name="collectionTitle">Optional. The title of the collection that contains the media item.</param>
|
||||
/// <param name="creatorId">Optional. The Id of the creator of the media item.</param>
|
||||
/// <param name="creatorName">Optional. The name of the creator of the media item.</param>
|
||||
/// <param name="coverPath">Optional. The path of the cover art of the media item.</param>
|
||||
/// <param name="includeCoverPath">Whether the cover path should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="FavoriteItemDisplayDto"/>.</returns>
|
||||
public FavoriteItemDisplayDto Create(
|
||||
Guid? libraryId = null,
|
||||
string? title = null,
|
||||
Guid? collectionId = null,
|
||||
string? collectionTitle = null,
|
||||
Guid? creatorId = null,
|
||||
string? creatorName = null,
|
||||
string? coverPath = null,
|
||||
bool includeCoverPath = true)
|
||||
{
|
||||
return new FavoriteItemDisplayDto(
|
||||
libraryId ?? _faker.Random.Guid(),
|
||||
title ?? _faker.Lorem.Sentence(3),
|
||||
collectionId ?? _faker.Random.Guid(),
|
||||
collectionTitle ?? _faker.Lorem.Sentence(3),
|
||||
creatorId ?? _faker.Random.Guid(),
|
||||
creatorName ?? _faker.Name.FullName(),
|
||||
includeCoverPath ? (coverPath ?? $"/covers/{_faker.Random.Guid()}.jpg") : null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="FavoriteItemDisplayDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="FavoriteItemDisplayDto"/> instances.</returns>
|
||||
public List<FavoriteItemDisplayDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Common.DTO.Favorites;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Favorites;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Fixtures.Common.DTO.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="FavoriteItemDto"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FavoriteItemDtoFixture
|
||||
{
|
||||
private readonly FavoriteEntityFixture _favoriteEntityFixture = new();
|
||||
private readonly FavoriteItemDisplayDtoFixture _favoriteItemDisplayDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="FavoriteItemDto"/>.
|
||||
/// </summary>
|
||||
/// <param name="favorite">Optional. The stored favorite.</param>
|
||||
/// <param name="display">Optional. The display data of the referenced media item.</param>
|
||||
/// <param name="includeDisplay">Whether the display data should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="FavoriteItemDto"/>.</returns>
|
||||
public FavoriteItemDto Create(
|
||||
FavoriteEntity? favorite = null,
|
||||
FavoriteItemDisplayDto? display = null,
|
||||
bool includeDisplay = true)
|
||||
{
|
||||
return new FavoriteItemDto(
|
||||
favorite ?? _favoriteEntityFixture.Create(),
|
||||
includeDisplay ? (display ?? _favoriteItemDisplayDtoFixture.Create()) : null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="FavoriteItemDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="FavoriteItemDto"/> instances.</returns>
|
||||
public List<FavoriteItemDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Playlists;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Common.DTO.Playlists;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Playlists;
|
||||
using Lumina.Application.Fixtures.Common.DTO.Pagination;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Fixtures.Common.DTO.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="PlaylistDetailsDto"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PlaylistDetailsDtoFixture
|
||||
{
|
||||
private readonly PlaylistEntityFixture _playlistEntityFixture = new();
|
||||
private readonly PlaylistEntryDtoFixture _playlistEntryDtoFixture = new();
|
||||
private readonly PaginatedResultDtoFixture<PlaylistEntryDto> _paginatedResultDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="PlaylistDetailsDto"/>.
|
||||
/// </summary>
|
||||
/// <param name="playlist">Optional. The stored playlist.</param>
|
||||
/// <param name="entries">Optional. The requested page of entries. Defaults to a page of random entries.</param>
|
||||
/// <returns>The created <see cref="PlaylistDetailsDto"/>.</returns>
|
||||
public PlaylistDetailsDto Create(
|
||||
PlaylistEntity? playlist = null,
|
||||
PaginatedResultDto<PlaylistEntryDto>? entries = null)
|
||||
{
|
||||
List<PlaylistEntryDto> entryDtos = _playlistEntryDtoFixture.CreateMany();
|
||||
return new PlaylistDetailsDto(
|
||||
playlist ?? _playlistEntityFixture.Create(),
|
||||
entries ?? _paginatedResultDtoFixture.Create(data: entryDtos, count: entryDtos.Count));
|
||||
}
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Common.DTO.Playlists;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Fixtures.Common.DTO.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="PlaylistEntryDisplayDto"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PlaylistEntryDisplayDtoFixture
|
||||
{
|
||||
private const int MAXIMUM_DURATION_SECONDS = 36_000;
|
||||
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="PlaylistEntryDisplayDto"/>.
|
||||
/// </summary>
|
||||
/// <param name="trackId">Optional. The Id of the track.</param>
|
||||
/// <param name="trackTitle">Optional. The title of the track.</param>
|
||||
/// <param name="durationInSeconds">Optional. The duration of the track, in seconds. Defaults to a bounded random duration.</param>
|
||||
/// <param name="libraryId">Optional. The Id of the media library that contains the track.</param>
|
||||
/// <param name="albumId">Optional. The Id of the album that contains the track.</param>
|
||||
/// <param name="albumTitle">Optional. The title of the album that contains the track.</param>
|
||||
/// <param name="artistId">Optional. The Id of the artist that produced the track.</param>
|
||||
/// <param name="artistName">Optional. The name of the artist that produced the track.</param>
|
||||
/// <param name="coverPath">Optional. The path of the cover art of the album.</param>
|
||||
/// <param name="includeCoverPath">Whether the cover path should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="PlaylistEntryDisplayDto"/>.</returns>
|
||||
public PlaylistEntryDisplayDto Create(
|
||||
Guid? trackId = null,
|
||||
string? trackTitle = null,
|
||||
int? durationInSeconds = null,
|
||||
Guid? libraryId = null,
|
||||
Guid? albumId = null,
|
||||
string? albumTitle = null,
|
||||
Guid? artistId = null,
|
||||
string? artistName = null,
|
||||
string? coverPath = null,
|
||||
bool includeCoverPath = true)
|
||||
{
|
||||
return new PlaylistEntryDisplayDto(
|
||||
trackId ?? _faker.Random.Guid(),
|
||||
trackTitle ?? _faker.Lorem.Sentence(3),
|
||||
durationInSeconds ?? _faker.Random.Int(0, MAXIMUM_DURATION_SECONDS),
|
||||
libraryId ?? _faker.Random.Guid(),
|
||||
albumId ?? _faker.Random.Guid(),
|
||||
albumTitle ?? _faker.Lorem.Sentence(3),
|
||||
artistId ?? _faker.Random.Guid(),
|
||||
artistName ?? _faker.Name.FullName(),
|
||||
includeCoverPath ? (coverPath ?? $"/covers/{_faker.Random.Guid()}.jpg") : null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="PlaylistEntryDisplayDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="PlaylistEntryDisplayDto"/> instances.</returns>
|
||||
public List<PlaylistEntryDisplayDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Playlists;
|
||||
using Lumina.Application.Common.DTO.Playlists;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Playlists;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Fixtures.Common.DTO.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="PlaylistEntryDto"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PlaylistEntryDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly PlaylistEntryEntityFixture _playlistEntryEntityFixture = new();
|
||||
private readonly PlaylistEntryDisplayDtoFixture _playlistEntryDisplayDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="PlaylistEntryDto"/>.
|
||||
/// </summary>
|
||||
/// <param name="entry">Optional. The stored playlist entry.</param>
|
||||
/// <param name="display">Optional. The display data of the referenced media item.</param>
|
||||
/// <param name="displayPosition">Optional. The dense zero based position shown to the client.</param>
|
||||
/// <param name="includeDisplay">Whether the display data should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="PlaylistEntryDto"/>.</returns>
|
||||
public PlaylistEntryDto Create(
|
||||
PlaylistEntryEntity? entry = null,
|
||||
PlaylistEntryDisplayDto? display = null,
|
||||
int? displayPosition = null,
|
||||
bool includeDisplay = true)
|
||||
{
|
||||
return new PlaylistEntryDto(
|
||||
entry ?? _playlistEntryEntityFixture.Create(),
|
||||
includeDisplay ? (display ?? _playlistEntryDisplayDtoFixture.Create()) : null,
|
||||
displayPosition ?? _faker.Random.Int(0, 1_000));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="PlaylistEntryDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="PlaylistEntryDto"/> instances.</returns>
|
||||
public List<PlaylistEntryDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="FavoriteEntity"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FavoriteEntityFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly FavoriteMediaKind[] _supportedMediaKinds =
|
||||
[
|
||||
FavoriteMediaKind.MusicArtist,
|
||||
FavoriteMediaKind.MusicAlbum,
|
||||
FavoriteMediaKind.MusicTrack,
|
||||
FavoriteMediaKind.Book
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="FavoriteEntity"/>.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional. The Id of the favorite.</param>
|
||||
/// <param name="userId">Optional. The Id of the user that owns the favorite.</param>
|
||||
/// <param name="mediaKind">Optional. The kind of the favorited media item. Defaults to a random supported kind.</param>
|
||||
/// <param name="mediaItemId">Optional. The Id of the favorited media item.</param>
|
||||
/// <param name="createdOnUtc">Optional. The date and time when the favorite was created. Defaults to a moment in the past.</param>
|
||||
/// <param name="createdBy">Optional. The Id of the user that created the row.</param>
|
||||
/// <param name="updatedOnUtc">Optional. The date and time when the favorite was last updated. Defaults to a moment at or after the creation date.</param>
|
||||
/// <param name="updatedBy">Optional. The Id of the user that last updated the row.</param>
|
||||
/// <param name="includeUpdatedOnUtc">Whether the update time should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeUpdatedBy">Whether the updating user Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="FavoriteEntity"/>.</returns>
|
||||
public FavoriteEntity Create(
|
||||
Guid? id = null,
|
||||
Guid? userId = null,
|
||||
FavoriteMediaKind? mediaKind = null,
|
||||
Guid? mediaItemId = null,
|
||||
DateTime? createdOnUtc = null,
|
||||
Guid? createdBy = null,
|
||||
DateTime? updatedOnUtc = null,
|
||||
Guid? updatedBy = null,
|
||||
bool includeUpdatedOnUtc = true,
|
||||
bool includeUpdatedBy = true)
|
||||
{
|
||||
DateTime resolvedCreatedOnUtc = createdOnUtc ?? DateTime.UtcNow.AddDays(-_faker.Random.Int(1, 30)).AddMinutes(-_faker.Random.Int(0, 59));
|
||||
|
||||
return new FavoriteEntity
|
||||
{
|
||||
Id = id ?? _faker.Random.Guid(),
|
||||
UserId = userId ?? _faker.Random.Guid(),
|
||||
MediaKind = mediaKind ?? _faker.Random.ArrayElement(_supportedMediaKinds),
|
||||
MediaItemId = mediaItemId ?? _faker.Random.Guid(),
|
||||
CreatedOnUtc = resolvedCreatedOnUtc,
|
||||
CreatedBy = createdBy ?? _faker.Random.Guid(),
|
||||
UpdatedOnUtc = includeUpdatedOnUtc ? (updatedOnUtc ?? resolvedCreatedOnUtc.AddMinutes(_faker.Random.Int(0, 120))) : null,
|
||||
UpdatedBy = includeUpdatedBy ? (updatedBy ?? _faker.Random.Guid()) : null
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="FavoriteEntity"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="FavoriteEntity"/> instances.</returns>
|
||||
public List<FavoriteEntity> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Core.Favorites.Commands.AddFavorite;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Fixtures.Core.Favorites.Commands.AddFavorite;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="AddFavoriteCommand"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddFavoriteCommandFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="AddFavoriteCommand"/>.
|
||||
/// </summary>
|
||||
/// <param name="mediaKind">Optional. The kind of the media item to favorite. Defaults to a supported kind.</param>
|
||||
/// <param name="mediaItemId">Optional. The unique identifier of the media item to favorite.</param>
|
||||
/// <param name="includeMediaKind">Whether the media kind should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMediaItemId">Whether the media item Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="AddFavoriteCommand"/>.</returns>
|
||||
public AddFavoriteCommand Create(
|
||||
FavoriteMediaKind? mediaKind = null,
|
||||
Guid? mediaItemId = null,
|
||||
bool includeMediaKind = true,
|
||||
bool includeMediaItemId = true)
|
||||
{
|
||||
return new AddFavoriteCommand(
|
||||
includeMediaKind ? (mediaKind ?? FavoriteMediaKind.MusicTrack) : null,
|
||||
includeMediaItemId ? (mediaItemId ?? _faker.Random.Guid()) : null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="AddFavoriteCommand"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="AddFavoriteCommand"/> instances.</returns>
|
||||
public List<AddFavoriteCommand> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Core.Favorites.Commands.RemoveFavorite;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Fixtures.Core.Favorites.Commands.RemoveFavorite;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="RemoveFavoriteCommand"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RemoveFavoriteCommandFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="RemoveFavoriteCommand"/>.
|
||||
/// </summary>
|
||||
/// <param name="mediaKind">Optional. The name of the kind of the favorited media item. Defaults to the name of a supported kind.</param>
|
||||
/// <param name="mediaItemId">Optional. The unique identifier of the favorited media item.</param>
|
||||
/// <param name="includeMediaKind">Whether the media kind should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMediaItemId">Whether the media item Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="RemoveFavoriteCommand"/>.</returns>
|
||||
public RemoveFavoriteCommand Create(
|
||||
string? mediaKind = null,
|
||||
string? mediaItemId = null,
|
||||
bool includeMediaKind = true,
|
||||
bool includeMediaItemId = true)
|
||||
{
|
||||
return new RemoveFavoriteCommand(
|
||||
includeMediaKind ? (mediaKind ?? nameof(FavoriteMediaKind.MusicTrack)) : null,
|
||||
includeMediaItemId ? (mediaItemId ?? _faker.Random.Guid().ToString()) : null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="RemoveFavoriteCommand"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="RemoveFavoriteCommand"/> instances.</returns>
|
||||
public List<RemoveFavoriteCommand> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Core.Favorites.Queries.GetFavoriteStatus;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Fixtures.Core.Favorites.Queries.GetFavoriteStatus;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetFavoriteStatusQuery"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetFavoriteStatusQueryFixture
|
||||
{
|
||||
private const int DEFAULT_MEDIA_ITEM_COUNT = 3;
|
||||
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="GetFavoriteStatusQuery"/>.
|
||||
/// </summary>
|
||||
/// <param name="mediaKind">Optional. The kind of the media items to check. Defaults to a supported kind.</param>
|
||||
/// <param name="mediaItemIds">Optional. The unique identifiers of the media items to check. Defaults to a bounded list of random Ids.</param>
|
||||
/// <param name="includeMediaKind">Whether the media kind should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMediaItemIds">Whether the media item Ids should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="GetFavoriteStatusQuery"/>.</returns>
|
||||
public GetFavoriteStatusQuery Create(
|
||||
FavoriteMediaKind? mediaKind = null,
|
||||
IReadOnlyList<Guid>? mediaItemIds = null,
|
||||
bool includeMediaKind = true,
|
||||
bool includeMediaItemIds = true)
|
||||
{
|
||||
return new GetFavoriteStatusQuery(
|
||||
includeMediaKind ? (mediaKind ?? FavoriteMediaKind.MusicTrack) : null,
|
||||
includeMediaItemIds ? (mediaItemIds ?? CreateRandomMediaItemIds()) : null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="GetFavoriteStatusQuery"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="GetFavoriteStatusQuery"/> instances.</returns>
|
||||
public List<GetFavoriteStatusQuery> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a bounded list of random media item Ids.
|
||||
/// </summary>
|
||||
/// <returns>The created list of media item Ids.</returns>
|
||||
private List<Guid> CreateRandomMediaItemIds()
|
||||
{
|
||||
return [.. Enumerable.Range(0, DEFAULT_MEDIA_ITEM_COUNT).Select(_ => _faker.Random.Guid())];
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Core.Favorites.Queries.GetFavorites;
|
||||
using Lumina.Application.Fixtures.Common.DTO.Pagination;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Fixtures.Core.Favorites.Queries.GetFavorites;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetFavoritesQuery"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetFavoritesQueryFixture
|
||||
{
|
||||
private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="GetFavoritesQuery"/>.
|
||||
/// </summary>
|
||||
/// <param name="mediaKind">Optional. The kind of media item to restrict the favorites to. Defaults to a supported kind.</param>
|
||||
/// <param name="paginationData">Optional. The object containing the requested pagination data. Defaults to a random page.</param>
|
||||
/// <param name="includeMediaKind">Whether the media kind should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includePaginationData">Whether the pagination data should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="GetFavoritesQuery"/>.</returns>
|
||||
public GetFavoritesQuery Create(
|
||||
FavoriteMediaKind? mediaKind = null,
|
||||
PaginationDataDto? paginationData = null,
|
||||
bool includeMediaKind = true,
|
||||
bool includePaginationData = true)
|
||||
{
|
||||
return new GetFavoritesQuery(
|
||||
includeMediaKind ? (mediaKind ?? FavoriteMediaKind.MusicTrack) : null,
|
||||
includePaginationData ? (paginationData ?? _paginationDataDtoFixture.Create()) : null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="GetFavoritesQuery"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="GetFavoritesQuery"/> instances.</returns>
|
||||
public List<GetFavoritesQuery> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Core.Playlists.Commands.CreatePlaylist;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Fixtures.Core.Playlists.Commands.CreatePlaylist;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="CreatePlaylistCommand"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class CreatePlaylistCommandFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="CreatePlaylistCommand"/>.
|
||||
/// </summary>
|
||||
/// <param name="name">Optional. The name of the playlist.</param>
|
||||
/// <param name="description">Optional. The optional description of the playlist.</param>
|
||||
/// <param name="type">Optional. The kind of media the playlist holds. Defaults to the only supported kind.</param>
|
||||
/// <param name="includeDescription">Whether the description should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeType">Whether the media type should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="CreatePlaylistCommand"/>.</returns>
|
||||
public CreatePlaylistCommand Create(
|
||||
string? name = null,
|
||||
string? description = null,
|
||||
PlaylistType? type = null,
|
||||
bool includeDescription = true,
|
||||
bool includeType = true)
|
||||
{
|
||||
return new CreatePlaylistCommand(
|
||||
name ?? _faker.Lorem.Sentence(3),
|
||||
includeDescription ? (description ?? _faker.Lorem.Sentence()) : null,
|
||||
includeType ? (type ?? PlaylistType.Music) : null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="CreatePlaylistCommand"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="CreatePlaylistCommand"/> instances.</returns>
|
||||
public List<CreatePlaylistCommand> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Core.Playlists.Queries.GetPlaylist;
|
||||
using Lumina.Application.Fixtures.Common.DTO.Pagination;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Fixtures.Core.Playlists.Queries.GetPlaylist;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetPlaylistQuery"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPlaylistQueryFixture
|
||||
{
|
||||
private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="GetPlaylistQuery"/>.
|
||||
/// </summary>
|
||||
/// <param name="playlistId">Optional. The unique identifier of the playlist. Defaults to a random Guid.</param>
|
||||
/// <param name="paginationData">Optional. The object containing the requested pagination data. Defaults to a random page.</param>
|
||||
/// <param name="includePlaylistId">Whether the playlist Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includePaginationData">Whether the pagination data should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="GetPlaylistQuery"/>.</returns>
|
||||
public GetPlaylistQuery Create(
|
||||
string? playlistId = null,
|
||||
PaginationDataDto? paginationData = null,
|
||||
bool includePlaylistId = true,
|
||||
bool includePaginationData = true)
|
||||
{
|
||||
return new GetPlaylistQuery(
|
||||
includePlaylistId ? (playlistId ?? Guid.NewGuid().ToString()) : null,
|
||||
includePaginationData ? (paginationData ?? _paginationDataDtoFixture.Create()) : null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="GetPlaylistQuery"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="GetPlaylistQuery"/> instances.</returns>
|
||||
public List<GetPlaylistQuery> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Requests.Favorites;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Fixtures.Core.Requests.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="AddFavoriteRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddFavoriteRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly FavoriteMediaKind[] _supportedMediaKinds =
|
||||
[
|
||||
FavoriteMediaKind.MusicArtist,
|
||||
FavoriteMediaKind.MusicAlbum,
|
||||
FavoriteMediaKind.MusicTrack,
|
||||
FavoriteMediaKind.Book
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="AddFavoriteRequest"/>.
|
||||
/// </summary>
|
||||
/// <param name="mediaKind">Optional. The kind of the media item to favorite. Defaults to a random supported kind.</param>
|
||||
/// <param name="mediaItemId">Optional. The Id of the media item to favorite.</param>
|
||||
/// <param name="includeMediaKind">Whether the media kind should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMediaItemId">Whether the media item Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="AddFavoriteRequest"/>.</returns>
|
||||
public AddFavoriteRequest Create(
|
||||
FavoriteMediaKind? mediaKind = null,
|
||||
Guid? mediaItemId = null,
|
||||
bool includeMediaKind = true,
|
||||
bool includeMediaItemId = true)
|
||||
{
|
||||
return new AddFavoriteRequest(
|
||||
includeMediaKind ? (mediaKind ?? _faker.Random.ArrayElement(_supportedMediaKinds)) : null,
|
||||
includeMediaItemId ? (mediaItemId ?? _faker.Random.Guid()) : null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="AddFavoriteRequest"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="AddFavoriteRequest"/> instances.</returns>
|
||||
public List<AddFavoriteRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Requests.Favorites;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Fixtures.Core.Requests.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetFavoriteStatusRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetFavoriteStatusRequestFixture
|
||||
{
|
||||
private const int DEFAULT_MEDIA_ITEM_COUNT = 3;
|
||||
|
||||
private readonly Faker _faker = new();
|
||||
private readonly FavoriteMediaKind[] _supportedMediaKinds =
|
||||
[
|
||||
FavoriteMediaKind.MusicArtist,
|
||||
FavoriteMediaKind.MusicAlbum,
|
||||
FavoriteMediaKind.MusicTrack,
|
||||
FavoriteMediaKind.Book
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="GetFavoriteStatusRequest"/>.
|
||||
/// </summary>
|
||||
/// <param name="mediaKind">Optional. The kind of the media items to check. Defaults to a random supported kind.</param>
|
||||
/// <param name="mediaItemIds">Optional. The Ids of the media items to check. Defaults to a bounded list of random Ids.</param>
|
||||
/// <param name="includeMediaKind">Whether the media kind should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMediaItemIds">Whether the media item Ids should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="GetFavoriteStatusRequest"/>.</returns>
|
||||
public GetFavoriteStatusRequest Create(
|
||||
FavoriteMediaKind? mediaKind = null,
|
||||
List<Guid>? mediaItemIds = null,
|
||||
bool includeMediaKind = true,
|
||||
bool includeMediaItemIds = true)
|
||||
{
|
||||
return new GetFavoriteStatusRequest(
|
||||
includeMediaKind ? (mediaKind ?? _faker.Random.ArrayElement(_supportedMediaKinds)) : null,
|
||||
includeMediaItemIds ? (mediaItemIds ?? CreateRandomMediaItemIds()) : null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="GetFavoriteStatusRequest"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="GetFavoriteStatusRequest"/> instances.</returns>
|
||||
public List<GetFavoriteStatusRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a bounded list of random media item Ids.
|
||||
/// </summary>
|
||||
/// <returns>The created list of media item Ids.</returns>
|
||||
private List<Guid> CreateRandomMediaItemIds()
|
||||
{
|
||||
return [.. Enumerable.Range(0, DEFAULT_MEDIA_ITEM_COUNT).Select(_ => _faker.Random.Guid())];
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Requests.Favorites;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Fixtures.Core.Requests.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetFavoritesRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetFavoritesRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly FavoriteMediaKind[] _supportedMediaKinds =
|
||||
[
|
||||
FavoriteMediaKind.MusicArtist,
|
||||
FavoriteMediaKind.MusicAlbum,
|
||||
FavoriteMediaKind.MusicTrack,
|
||||
FavoriteMediaKind.Book
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="GetFavoritesRequest"/>.
|
||||
/// </summary>
|
||||
/// <param name="mediaKind">Optional. The kind of media item to restrict the favorites to. Defaults to a random supported kind.</param>
|
||||
/// <param name="currentPage">Optional. The one based page of favorites to return. Defaults to a bounded random page.</param>
|
||||
/// <param name="perPage">Optional. The number of favorites per page. Defaults to a bounded random page size.</param>
|
||||
/// <param name="includeMediaKind">Whether the media kind should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeCurrentPage">Whether the current page should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includePerPage">Whether the per page count should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="GetFavoritesRequest"/>.</returns>
|
||||
public GetFavoritesRequest Create(
|
||||
FavoriteMediaKind? mediaKind = null,
|
||||
int? currentPage = null,
|
||||
int? perPage = null,
|
||||
bool includeMediaKind = true,
|
||||
bool includeCurrentPage = true,
|
||||
bool includePerPage = true)
|
||||
{
|
||||
return new GetFavoritesRequest(
|
||||
includeMediaKind ? (mediaKind ?? _faker.Random.ArrayElement(_supportedMediaKinds)) : null,
|
||||
includeCurrentPage ? (currentPage ?? _faker.Random.Int(1, 100)) : null,
|
||||
includePerPage ? (perPage ?? _faker.Random.Int(1, 200)) : null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="GetFavoritesRequest"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="GetFavoritesRequest"/> instances.</returns>
|
||||
public List<GetFavoritesRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Requests.Playlists;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Fixtures.Core.Requests.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetPlaylistRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPlaylistRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="GetPlaylistRequest"/>.
|
||||
/// </summary>
|
||||
/// <param name="currentPage">Optional. The one based page of entries to return. Defaults to a bounded random page.</param>
|
||||
/// <param name="perPage">Optional. The number of entries per page. Defaults to a bounded random page size.</param>
|
||||
/// <param name="includeCurrentPage">Whether the current page should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includePerPage">Whether the per page count should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="GetPlaylistRequest"/>.</returns>
|
||||
public GetPlaylistRequest Create(
|
||||
int? currentPage = null,
|
||||
int? perPage = null,
|
||||
bool includeCurrentPage = true,
|
||||
bool includePerPage = true)
|
||||
{
|
||||
return new GetPlaylistRequest(
|
||||
includeCurrentPage ? (currentPage ?? _faker.Random.Int(1, 100)) : null,
|
||||
includePerPage ? (perPage ?? _faker.Random.Int(1, 200)) : null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="GetPlaylistRequest"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="GetPlaylistRequest"/> instances.</returns>
|
||||
public List<GetPlaylistRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Responses.Favorites;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Fixtures.Core.Responses.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="FavoriteItemResponse"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FavoriteItemResponseFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly FavoriteMediaKind[] _supportedMediaKinds =
|
||||
[
|
||||
FavoriteMediaKind.MusicArtist,
|
||||
FavoriteMediaKind.MusicAlbum,
|
||||
FavoriteMediaKind.MusicTrack,
|
||||
FavoriteMediaKind.Book
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="FavoriteItemResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="mediaKind">Optional. The kind of the favorited media item. Defaults to a random supported kind.</param>
|
||||
/// <param name="mediaItemId">Optional. The Id of the favorited media item.</param>
|
||||
/// <param name="isAvailable">Optional. Whether the media item is available.</param>
|
||||
/// <param name="libraryId">Optional. The Id of the media library that contains the media item.</param>
|
||||
/// <param name="title">Optional. The title of the media item.</param>
|
||||
/// <param name="collectionId">Optional. The Id of the collection that contains the media item.</param>
|
||||
/// <param name="collectionTitle">Optional. The title of the collection that contains the media item.</param>
|
||||
/// <param name="creatorId">Optional. The Id of the creator of the media item.</param>
|
||||
/// <param name="creatorName">Optional. The name of the creator of the media item.</param>
|
||||
/// <param name="coverPath">Optional. The path of the cover art of the media item.</param>
|
||||
/// <param name="includeCoverPath">Whether the cover path should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="FavoriteItemResponse"/>.</returns>
|
||||
public FavoriteItemResponse Create(
|
||||
FavoriteMediaKind? mediaKind = null,
|
||||
Guid? mediaItemId = null,
|
||||
bool? isAvailable = null,
|
||||
Guid? libraryId = null,
|
||||
string? title = null,
|
||||
Guid? collectionId = null,
|
||||
string? collectionTitle = null,
|
||||
Guid? creatorId = null,
|
||||
string? creatorName = null,
|
||||
string? coverPath = null,
|
||||
bool includeCoverPath = true)
|
||||
{
|
||||
return new FavoriteItemResponse(
|
||||
mediaKind ?? _faker.Random.ArrayElement(_supportedMediaKinds),
|
||||
mediaItemId ?? _faker.Random.Guid(),
|
||||
isAvailable ?? _faker.Random.Bool(),
|
||||
libraryId ?? _faker.Random.Guid(),
|
||||
title ?? _faker.Lorem.Sentence(3),
|
||||
collectionId ?? _faker.Random.Guid(),
|
||||
collectionTitle ?? _faker.Lorem.Sentence(3),
|
||||
creatorId ?? _faker.Random.Guid(),
|
||||
creatorName ?? _faker.Name.FullName(),
|
||||
includeCoverPath ? (coverPath ?? $"/covers/{_faker.Random.Guid()}.jpg") : null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="FavoriteItemResponse"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="FavoriteItemResponse"/> instances.</returns>
|
||||
public List<FavoriteItemResponse> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Responses.Favorites;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Fixtures.Core.Responses.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="FavoriteResponse"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FavoriteResponseFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly FavoriteMediaKind[] _supportedMediaKinds =
|
||||
[
|
||||
FavoriteMediaKind.MusicArtist,
|
||||
FavoriteMediaKind.MusicAlbum,
|
||||
FavoriteMediaKind.MusicTrack,
|
||||
FavoriteMediaKind.Book
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="FavoriteResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional. The Id of the favorite.</param>
|
||||
/// <param name="mediaKind">Optional. The kind of the favorited media item. Defaults to a random supported kind.</param>
|
||||
/// <param name="mediaItemId">Optional. The Id of the favorited media item.</param>
|
||||
/// <param name="favoritedOnUtc">Optional. The date and time when the media item was favorited. Defaults to a moment in the past.</param>
|
||||
/// <returns>The created <see cref="FavoriteResponse"/>.</returns>
|
||||
public FavoriteResponse Create(
|
||||
Guid? id = null,
|
||||
FavoriteMediaKind? mediaKind = null,
|
||||
Guid? mediaItemId = null,
|
||||
DateTime? favoritedOnUtc = null)
|
||||
{
|
||||
return new FavoriteResponse(
|
||||
id ?? _faker.Random.Guid(),
|
||||
mediaKind ?? _faker.Random.ArrayElement(_supportedMediaKinds),
|
||||
mediaItemId ?? _faker.Random.Guid(),
|
||||
favoritedOnUtc ?? DateTime.UtcNow.AddDays(-_faker.Random.Int(1, 30)).AddMinutes(-_faker.Random.Int(0, 59)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="FavoriteResponse"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="FavoriteResponse"/> instances.</returns>
|
||||
public List<FavoriteResponse> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Responses.Favorites;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Fixtures.Core.Responses.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="FavoriteStatusResponse"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FavoriteStatusResponseFixture
|
||||
{
|
||||
private const int DEFAULT_FAVORITED_COUNT = 3;
|
||||
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="FavoriteStatusResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="favoritedMediaItemIds">Optional. The Ids of the media items that are favorites. Defaults to a bounded list of random Ids.</param>
|
||||
/// <returns>The created <see cref="FavoriteStatusResponse"/>.</returns>
|
||||
public FavoriteStatusResponse Create(IReadOnlyList<Guid>? favoritedMediaItemIds = null)
|
||||
{
|
||||
return new FavoriteStatusResponse(
|
||||
favoritedMediaItemIds ?? CreateRandomMediaItemIds());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="FavoriteStatusResponse"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="FavoriteStatusResponse"/> instances.</returns>
|
||||
public List<FavoriteStatusResponse> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a bounded list of random media item Ids.
|
||||
/// </summary>
|
||||
/// <returns>The created list of media item Ids.</returns>
|
||||
private List<Guid> CreateRandomMediaItemIds()
|
||||
{
|
||||
return [.. Enumerable.Range(0, DEFAULT_FAVORITED_COUNT).Select(_ => _faker.Random.Guid())];
|
||||
}
|
||||
}
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Responses.Playlists;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Fixtures.Core.Responses.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="PlaylistEntryResponse"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PlaylistEntryResponseFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="PlaylistEntryResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional. The Id of the entry.</param>
|
||||
/// <param name="mediaItemId">Optional. The Id of the media item referenced by the entry.</param>
|
||||
/// <param name="mediaItemType">Optional. The kind of media item referenced by the entry.</param>
|
||||
/// <param name="position">Optional. The zero based position of the entry in the playlist.</param>
|
||||
/// <param name="libraryId">Optional. The Id of the media library that contains the media item.</param>
|
||||
/// <param name="collectionId">Optional. The Id of the collection that contains the media item.</param>
|
||||
/// <param name="creatorId">Optional. The Id of the creator of the media item.</param>
|
||||
/// <param name="mediaItemTitle">Optional. The title of the media item.</param>
|
||||
/// <param name="collectionTitle">Optional. The title of the collection that contains the media item.</param>
|
||||
/// <param name="creatorName">Optional. The name of the creator of the media item.</param>
|
||||
/// <param name="durationInSeconds">Optional. The duration of the media item in seconds.</param>
|
||||
/// <param name="coverPath">Optional. The path of the cover art of the collection.</param>
|
||||
/// <param name="includeCoverPath">Whether the cover path should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="PlaylistEntryResponse"/>.</returns>
|
||||
public PlaylistEntryResponse Create(
|
||||
Guid? id = null,
|
||||
Guid? mediaItemId = null,
|
||||
PlaylistMediaItemType? mediaItemType = null,
|
||||
int? position = null,
|
||||
Guid? libraryId = null,
|
||||
Guid? collectionId = null,
|
||||
Guid? creatorId = null,
|
||||
string? mediaItemTitle = null,
|
||||
string? collectionTitle = null,
|
||||
string? creatorName = null,
|
||||
int? durationInSeconds = null,
|
||||
string? coverPath = null,
|
||||
bool includeCoverPath = true)
|
||||
{
|
||||
return new PlaylistEntryResponse(
|
||||
id ?? _faker.Random.Guid(),
|
||||
mediaItemId ?? _faker.Random.Guid(),
|
||||
mediaItemType ?? _faker.PickRandom<PlaylistMediaItemType>(),
|
||||
position ?? _faker.Random.Int(0, 1_000),
|
||||
libraryId ?? _faker.Random.Guid(),
|
||||
collectionId ?? _faker.Random.Guid(),
|
||||
creatorId ?? _faker.Random.Guid(),
|
||||
mediaItemTitle ?? _faker.Lorem.Sentence(3),
|
||||
collectionTitle ?? _faker.Lorem.Sentence(2),
|
||||
creatorName ?? _faker.Name.FullName(),
|
||||
durationInSeconds ?? _faker.Random.Int(1, 3_600),
|
||||
includeCoverPath ? (coverPath ?? $"/covers/{_faker.Random.Guid()}.jpg") : null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="PlaylistEntryResponse"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="PlaylistEntryResponse"/> instances.</returns>
|
||||
public List<PlaylistEntryResponse> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Fixtures.Responses.Common;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
using Lumina.Contracts.Responses.Playlists;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Fixtures.Core.Responses.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="PlaylistResponse"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PlaylistResponseFixture
|
||||
{
|
||||
private const int DEFAULT_ENTRY_COUNT = 3;
|
||||
|
||||
private readonly Faker _faker = new();
|
||||
private readonly PlaylistEntryResponseFixture _playlistEntryResponseFixture = new();
|
||||
private readonly PaginatedResponseFixture<PlaylistEntryResponse> _paginatedResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="PlaylistResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional. The Id of the playlist.</param>
|
||||
/// <param name="name">Optional. The name of the playlist.</param>
|
||||
/// <param name="description">Optional. The description of the playlist.</param>
|
||||
/// <param name="type">Optional. The kind of media the playlist holds.</param>
|
||||
/// <param name="entries">Optional. The page of entries of the playlist.</param>
|
||||
/// <param name="createdOnUtc">Optional. The date and time when the playlist was created.</param>
|
||||
/// <param name="updatedOnUtc">Optional. The date and time when the playlist was last updated.</param>
|
||||
/// <param name="includeDescription">Whether the description should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeUpdatedOnUtc">Whether the update time should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="PlaylistResponse"/>.</returns>
|
||||
public PlaylistResponse Create(
|
||||
Guid? id = null,
|
||||
string? name = null,
|
||||
string? description = null,
|
||||
PlaylistType? type = null,
|
||||
PaginatedResponse<PlaylistEntryResponse>? entries = null,
|
||||
DateTime? createdOnUtc = null,
|
||||
DateTime? updatedOnUtc = null,
|
||||
bool includeDescription = true,
|
||||
bool includeUpdatedOnUtc = true)
|
||||
{
|
||||
return new PlaylistResponse(
|
||||
id ?? _faker.Random.Guid(),
|
||||
name ?? _faker.Lorem.Sentence(3),
|
||||
includeDescription ? (description ?? _faker.Lorem.Sentence()) : null,
|
||||
type ?? PlaylistType.Music,
|
||||
entries ?? CreateEntriesPage(),
|
||||
createdOnUtc ?? DateTime.UtcNow.AddDays(-_faker.Random.Int(1, 30)),
|
||||
includeUpdatedOnUtc ? (updatedOnUtc ?? DateTime.UtcNow.AddMinutes(-_faker.Random.Int(1, 1_440))) : null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="PlaylistResponse"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="PlaylistResponse"/> instances.</returns>
|
||||
public List<PlaylistResponse> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a page of random playlist entries.
|
||||
/// </summary>
|
||||
/// <returns>The created page of playlist entries.</returns>
|
||||
private PaginatedResponse<PlaylistEntryResponse> CreateEntriesPage()
|
||||
{
|
||||
List<PlaylistEntryResponse> entries = [];
|
||||
for (int index = 0; index < DEFAULT_ENTRY_COUNT; index++)
|
||||
entries.Add(_playlistEntryResponseFixture.Create(position: index));
|
||||
|
||||
return _paginatedResponseFixture.Create(data: entries, currentPage: 1, perPage: DEFAULT_ENTRY_COUNT, count: DEFAULT_ENTRY_COUNT, numberOfPages: 1);
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Fixtures.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MediaItemId"/> value object.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaItemIdFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="MediaItemId"/>.
|
||||
/// </summary>
|
||||
/// <param name="value">Optional. The raw value of the media item Id.</param>
|
||||
/// <returns>The created <see cref="MediaItemId"/>.</returns>
|
||||
public MediaItemId Create(
|
||||
Guid? value = null)
|
||||
{
|
||||
return MediaItemId.Create(value ?? Guid.NewGuid());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="MediaItemId"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MediaItemId"/> instances.</returns>
|
||||
public List<MediaItemId> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Fixtures.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="UserId"/> value object.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UserIdFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="UserId"/>.
|
||||
/// </summary>
|
||||
/// <param name="value">Optional. The raw value of the user Id.</param>
|
||||
/// <returns>The created <see cref="UserId"/>.</returns>
|
||||
public UserId Create(
|
||||
Guid? value = null)
|
||||
{
|
||||
return UserId.Create(value ?? Guid.NewGuid());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="UserId"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="UserId"/> instances.</returns>
|
||||
public List<UserId> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Fixtures.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.Events;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="FavoriteAddedDomainEvent"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FavoriteAddedDomainEventFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly FavoriteIdFixture _favoriteIdFixture = new();
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
private readonly MediaItemIdFixture _mediaItemIdFixture = new();
|
||||
private readonly FavoriteMediaKind[] _supportedMediaKinds =
|
||||
[
|
||||
FavoriteMediaKind.MusicArtist,
|
||||
FavoriteMediaKind.MusicAlbum,
|
||||
FavoriteMediaKind.MusicTrack,
|
||||
FavoriteMediaKind.Book
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="FavoriteAddedDomainEvent"/>.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional. The Id of the domain event.</param>
|
||||
/// <param name="favoriteId">Optional. The unique identifier of the favorite.</param>
|
||||
/// <param name="userId">Optional. The unique identifier of the user that favorited the media item.</param>
|
||||
/// <param name="mediaItemId">Optional. The unique identifier of the favorited media item.</param>
|
||||
/// <param name="mediaKind">Optional. The kind of the favorited media item. Defaults to a random supported kind.</param>
|
||||
/// <param name="occurredOnUtc">Optional. The date and time when the domain event occurred.</param>
|
||||
/// <returns>The created <see cref="FavoriteAddedDomainEvent"/>.</returns>
|
||||
public FavoriteAddedDomainEvent Create(
|
||||
Guid? id = null,
|
||||
FavoriteId? favoriteId = null,
|
||||
UserId? userId = null,
|
||||
MediaItemId? mediaItemId = null,
|
||||
FavoriteMediaKind? mediaKind = null,
|
||||
DateTime? occurredOnUtc = null)
|
||||
{
|
||||
return new FavoriteAddedDomainEvent(
|
||||
id ?? Guid.NewGuid(),
|
||||
favoriteId ?? _favoriteIdFixture.Create(),
|
||||
userId ?? _userIdFixture.Create(),
|
||||
mediaItemId ?? _mediaItemIdFixture.Create(),
|
||||
mediaKind ?? _faker.Random.ArrayElement(_supportedMediaKinds),
|
||||
occurredOnUtc ?? DateTime.UtcNow);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="FavoriteAddedDomainEvent"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="FavoriteAddedDomainEvent"/> instances.</returns>
|
||||
public List<FavoriteAddedDomainEvent> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Fixtures.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.Events;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="FavoriteRemovedDomainEvent"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FavoriteRemovedDomainEventFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly FavoriteIdFixture _favoriteIdFixture = new();
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
private readonly MediaItemIdFixture _mediaItemIdFixture = new();
|
||||
private readonly FavoriteMediaKind[] _supportedMediaKinds =
|
||||
[
|
||||
FavoriteMediaKind.MusicArtist,
|
||||
FavoriteMediaKind.MusicAlbum,
|
||||
FavoriteMediaKind.MusicTrack,
|
||||
FavoriteMediaKind.Book
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="FavoriteRemovedDomainEvent"/>.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional. The Id of the domain event.</param>
|
||||
/// <param name="favoriteId">Optional. The unique identifier of the removed favorite.</param>
|
||||
/// <param name="userId">Optional. The unique identifier of the user that owned the favorite.</param>
|
||||
/// <param name="mediaItemId">Optional. The unique identifier of the media item that was unfavorited.</param>
|
||||
/// <param name="mediaKind">Optional. The kind of the media item that was unfavorited. Defaults to a random supported kind.</param>
|
||||
/// <param name="occurredOnUtc">Optional. The date and time when the domain event occurred.</param>
|
||||
/// <returns>The created <see cref="FavoriteRemovedDomainEvent"/>.</returns>
|
||||
public FavoriteRemovedDomainEvent Create(
|
||||
Guid? id = null,
|
||||
FavoriteId? favoriteId = null,
|
||||
UserId? userId = null,
|
||||
MediaItemId? mediaItemId = null,
|
||||
FavoriteMediaKind? mediaKind = null,
|
||||
DateTime? occurredOnUtc = null)
|
||||
{
|
||||
return new FavoriteRemovedDomainEvent(
|
||||
id ?? Guid.NewGuid(),
|
||||
favoriteId ?? _favoriteIdFixture.Create(),
|
||||
userId ?? _userIdFixture.Create(),
|
||||
mediaItemId ?? _mediaItemIdFixture.Create(),
|
||||
mediaKind ?? _faker.Random.ArrayElement(_supportedMediaKinds),
|
||||
occurredOnUtc ?? DateTime.UtcNow);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="FavoriteRemovedDomainEvent"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="FavoriteRemovedDomainEvent"/> instances.</returns>
|
||||
public List<FavoriteRemovedDomainEvent> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Fixtures.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="Favorite"/> domain aggregate.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FavoriteFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly FavoriteIdFixture _favoriteIdFixture = new();
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
private readonly MediaItemIdFixture _mediaItemIdFixture = new();
|
||||
private readonly FavoriteMediaKind[] _supportedMediaKinds =
|
||||
[
|
||||
FavoriteMediaKind.MusicArtist,
|
||||
FavoriteMediaKind.MusicAlbum,
|
||||
FavoriteMediaKind.MusicTrack,
|
||||
FavoriteMediaKind.Book
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="Favorite"/> domain aggregate, with pre-existing data.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional. The Id of the favorite.</param>
|
||||
/// <param name="userId">Optional. The Id of the user that owns the favorite.</param>
|
||||
/// <param name="mediaItemId">Optional. The Id of the favorited media item.</param>
|
||||
/// <param name="mediaKind">Optional. The kind of the favorited media item. Defaults to a random supported kind.</param>
|
||||
/// <param name="createdOnUtc">Optional. The date and time when the favorite was created. Defaults to a few days in the past.</param>
|
||||
/// <param name="updatedOnUtc">Optional. The date and time when the favorite was last updated. Defaults to a moment at or after the creation date, or to no value when <paramref name="includeUpdatedOnUtc"/> is <see langword="false"/>.</param>
|
||||
/// <param name="includeUpdatedOnUtc">Whether to generate an update date and time when <paramref name="updatedOnUtc"/> is not supplied.</param>
|
||||
/// <returns>The created <see cref="Favorite"/>.</returns>
|
||||
/// <remarks>
|
||||
/// The favorite is built through the rehydrating <see cref="Favorite.Create(FavoriteId, UserId, MediaItemId, FavoriteMediaKind, DateTime, Optional{DateTime})"/>
|
||||
/// overload, so it carries no domain events, is never marked as removed, and keeps whatever media kind it is given, including a planned one.
|
||||
/// </remarks>
|
||||
public Favorite Create(
|
||||
FavoriteId? id = null,
|
||||
UserId? userId = null,
|
||||
MediaItemId? mediaItemId = null,
|
||||
FavoriteMediaKind? mediaKind = null,
|
||||
DateTime? createdOnUtc = null,
|
||||
Optional<DateTime>? updatedOnUtc = null,
|
||||
bool includeUpdatedOnUtc = true)
|
||||
{
|
||||
DateTime resolvedCreatedOnUtc = createdOnUtc ?? DateTime.UtcNow.AddDays(-_faker.Random.Int(1, 30)).AddMinutes(-_faker.Random.Int(0, 59));
|
||||
return Favorite.Create(
|
||||
id ?? _favoriteIdFixture.Create(),
|
||||
userId ?? _userIdFixture.Create(),
|
||||
mediaItemId ?? _mediaItemIdFixture.Create(),
|
||||
mediaKind ?? _faker.Random.ArrayElement(_supportedMediaKinds),
|
||||
resolvedCreatedOnUtc,
|
||||
ResolveUpdatedOnUtc(updatedOnUtc, includeUpdatedOnUtc, resolvedCreatedOnUtc)).Value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="Favorite"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="Favorite"/> instances.</returns>
|
||||
public List<Favorite> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the update date and time of the favorite, keeping it at or after the creation date and inside the date range.
|
||||
/// </summary>
|
||||
/// <param name="updatedOnUtc">The explicitly supplied update date and time, if any.</param>
|
||||
/// <param name="includeUpdatedOnUtc">Whether to generate an update date and time when none is supplied.</param>
|
||||
/// <param name="createdOnUtc">The creation date and time of the favorite.</param>
|
||||
/// <returns>The resolved update date and time, or no value when the favorite was never updated.</returns>
|
||||
private Optional<DateTime> ResolveUpdatedOnUtc(Optional<DateTime>? updatedOnUtc, bool includeUpdatedOnUtc, DateTime createdOnUtc)
|
||||
{
|
||||
if (updatedOnUtc.HasValue)
|
||||
return updatedOnUtc.Value;
|
||||
if (!includeUpdatedOnUtc)
|
||||
return Optional<DateTime>.None();
|
||||
TimeSpan offsetFromCreation = TimeSpan.FromMinutes(_faker.Random.Int(0, 1440));
|
||||
return Optional<DateTime>.Some(DateTime.MaxValue - createdOnUtc < offsetFromCreation
|
||||
? DateTime.MaxValue
|
||||
: createdOnUtc.Add(offsetFromCreation));
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.ValueObjects;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Fixtures.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="FavoriteId"/> value object.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FavoriteIdFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="FavoriteId"/>.
|
||||
/// </summary>
|
||||
/// <param name="value">Optional. The raw value of the favorite Id.</param>
|
||||
/// <returns>The created <see cref="FavoriteId"/>.</returns>
|
||||
public FavoriteId Create(
|
||||
Guid? value = null)
|
||||
{
|
||||
return FavoriteId.Create(value ?? Guid.NewGuid());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="FavoriteId"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="FavoriteId"/> instances.</returns>
|
||||
public List<FavoriteId> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.DTO.Favorites;
|
||||
using Lumina.Presentation.Web.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="FavoriteDto"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FavoriteDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly FavoriteMediaKind[] _supportedMediaKinds =
|
||||
[
|
||||
FavoriteMediaKind.MusicArtist,
|
||||
FavoriteMediaKind.MusicAlbum,
|
||||
FavoriteMediaKind.MusicTrack,
|
||||
FavoriteMediaKind.Book
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="FavoriteDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional Id of the favorite.</param>
|
||||
/// <param name="mediaKind">Optional kind of the favorited media item.</param>
|
||||
/// <param name="mediaItemId">Optional Id of the favorited media item.</param>
|
||||
/// <param name="favoritedOnUtc">Optional date and time when the media item was favorited.</param>
|
||||
/// <returns>A configured <see cref="FavoriteDto"/> instance.</returns>
|
||||
public FavoriteDto Create(
|
||||
Guid? id = null,
|
||||
FavoriteMediaKind? mediaKind = null,
|
||||
Guid? mediaItemId = null,
|
||||
DateTime? favoritedOnUtc = null)
|
||||
{
|
||||
return new FavoriteDto(
|
||||
Id: id ?? _faker.Random.Guid(),
|
||||
MediaKind: mediaKind ?? _faker.PickRandom(_supportedMediaKinds),
|
||||
MediaItemId: mediaItemId ?? _faker.Random.Guid(),
|
||||
FavoritedOnUtc: favoritedOnUtc ?? _faker.Date.Between(new DateTime(2024, 1, 1), new DateTime(2026, 12, 31))
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="FavoriteDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="FavoriteDto"/> instances.</returns>
|
||||
public List<FavoriteDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.DTO.Favorites;
|
||||
using Lumina.Presentation.Web.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="FavoriteItemDto"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FavoriteItemDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly FavoriteMediaKind[] _supportedMediaKinds =
|
||||
[
|
||||
FavoriteMediaKind.MusicArtist,
|
||||
FavoriteMediaKind.MusicAlbum,
|
||||
FavoriteMediaKind.MusicTrack,
|
||||
FavoriteMediaKind.Book
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="FavoriteItemDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="mediaKind">Optional kind of the favorited media item.</param>
|
||||
/// <param name="mediaItemId">Optional Id of the favorited media item.</param>
|
||||
/// <param name="isAvailable">Optional value indicating whether the media item still exists and can be accessed by the user.</param>
|
||||
/// <param name="libraryId">Optional Id of the media library that contains the media item.</param>
|
||||
/// <param name="title">Optional title of the media item.</param>
|
||||
/// <param name="collectionId">Optional Id of the collection that contains the media item.</param>
|
||||
/// <param name="collectionTitle">Optional title of the collection that contains the media item.</param>
|
||||
/// <param name="creatorId">Optional Id of the creator of the media item.</param>
|
||||
/// <param name="creatorName">Optional name of the creator of the media item.</param>
|
||||
/// <param name="coverPath">Optional path of the cover art of the media item.</param>
|
||||
/// <param name="includeCoverPath">Whether the cover path should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>A configured <see cref="FavoriteItemDto"/> instance.</returns>
|
||||
public FavoriteItemDto Create(
|
||||
FavoriteMediaKind? mediaKind = null,
|
||||
Guid? mediaItemId = null,
|
||||
bool? isAvailable = null,
|
||||
Guid? libraryId = null,
|
||||
string? title = null,
|
||||
Guid? collectionId = null,
|
||||
string? collectionTitle = null,
|
||||
Guid? creatorId = null,
|
||||
string? creatorName = null,
|
||||
string? coverPath = null,
|
||||
bool includeCoverPath = true)
|
||||
{
|
||||
return new FavoriteItemDto(
|
||||
MediaKind: mediaKind ?? _faker.PickRandom(_supportedMediaKinds),
|
||||
MediaItemId: mediaItemId ?? _faker.Random.Guid(),
|
||||
IsAvailable: isAvailable ?? _faker.Random.Bool(),
|
||||
LibraryId: libraryId ?? _faker.Random.Guid(),
|
||||
Title: title ?? _faker.Lorem.Sentence(3),
|
||||
CollectionId: collectionId ?? _faker.Random.Guid(),
|
||||
CollectionTitle: collectionTitle ?? _faker.Lorem.Sentence(3),
|
||||
CreatorId: creatorId ?? _faker.Random.Guid(),
|
||||
CreatorName: creatorName ?? _faker.Name.FullName(),
|
||||
CoverPath: includeCoverPath ? (coverPath ?? $"covers/{_faker.Random.AlphaNumeric(12)}.jpg") : null
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="FavoriteItemDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="FavoriteItemDto"/> instances.</returns>
|
||||
public List<FavoriteItemDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.DTO.Favorites;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="FavoriteStatusDto"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FavoriteStatusDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="FavoriteStatusDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="favoritedMediaItemIds">Optional Ids of the media items that are favorites of the current user.</param>
|
||||
/// <param name="mediaItemCount">Optional number of random favorited media item Ids to generate, between 0 and 5.</param>
|
||||
/// <returns>A configured <see cref="FavoriteStatusDto"/> instance.</returns>
|
||||
public FavoriteStatusDto Create(
|
||||
List<Guid>? favoritedMediaItemIds = null,
|
||||
int? mediaItemCount = null)
|
||||
{
|
||||
int resolvedCount = mediaItemCount ?? _faker.Random.Int(0, 5);
|
||||
return new FavoriteStatusDto(
|
||||
FavoritedMediaItemIds: favoritedMediaItemIds ?? [.. Enumerable.Range(0, resolvedCount).Select(_ => _faker.Random.Guid())]
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="FavoriteStatusDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="FavoriteStatusDto"/> instances.</returns>
|
||||
public List<FavoriteStatusDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.DTO.Playlists;
|
||||
using Lumina.Presentation.Web.Common.Enums.Playlists;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="PlaylistDto"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PlaylistDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly PlaylistEntryDtoFixture _playlistEntryDtoFixture = new();
|
||||
private readonly PaginatedDtoFixture<PlaylistEntryDto> _paginatedDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="PlaylistDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional Id of the playlist.</param>
|
||||
/// <param name="name">Optional name of the playlist.</param>
|
||||
/// <param name="description">Optional description of the playlist.</param>
|
||||
/// <param name="type">Optional kind of media the playlist holds.</param>
|
||||
/// <param name="entries">Optional page of ordered entries of the playlist.</param>
|
||||
/// <param name="createdOnUtc">Optional date and time when the playlist was created.</param>
|
||||
/// <param name="updatedOnUtc">Optional date and time when the playlist was last updated.</param>
|
||||
/// <param name="includeDescription">Whether the description should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeUpdatedOnUtc">Whether the last update date should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>A configured <see cref="PlaylistDto"/> instance.</returns>
|
||||
public PlaylistDto Create(
|
||||
Guid? id = null,
|
||||
string? name = null,
|
||||
string? description = null,
|
||||
PlaylistType? type = null,
|
||||
PaginatedDto<PlaylistEntryDto>? entries = null,
|
||||
DateTime? createdOnUtc = null,
|
||||
DateTime? updatedOnUtc = null,
|
||||
bool includeDescription = true,
|
||||
bool includeUpdatedOnUtc = true)
|
||||
{
|
||||
DateTime resolvedCreatedOnUtc = DateTime.SpecifyKind(createdOnUtc ?? DateTime.UtcNow.AddDays(-_faker.Random.Int(1, 30)), DateTimeKind.Utc);
|
||||
DateTime resolvedUpdatedOnUtc = DateTime.SpecifyKind(updatedOnUtc ?? resolvedCreatedOnUtc.AddHours(_faker.Random.Int(1, 24)), DateTimeKind.Utc);
|
||||
return new PlaylistDto(
|
||||
Id: id ?? _faker.Random.Guid(),
|
||||
Name: name ?? _faker.Lorem.Sentence(3),
|
||||
Description: includeDescription ? (description ?? _faker.Lorem.Sentence(5)) : null,
|
||||
Type: type ?? PlaylistType.Music,
|
||||
Entries: entries ?? _paginatedDtoFixture.Create(data: _playlistEntryDtoFixture.CreateMany(_faker.Random.Int(0, 5))),
|
||||
CreatedOnUtc: resolvedCreatedOnUtc,
|
||||
UpdatedOnUtc: includeUpdatedOnUtc ? resolvedUpdatedOnUtc : null
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="PlaylistDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="PlaylistDto"/> instances.</returns>
|
||||
public List<PlaylistDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.DTO.Playlists;
|
||||
using Lumina.Presentation.Web.Common.Enums.Playlists;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="PlaylistEntryDto"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PlaylistEntryDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="PlaylistEntryDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional Id of the entry.</param>
|
||||
/// <param name="mediaItemId">Optional Id of the media item referenced by the entry.</param>
|
||||
/// <param name="mediaItemType">Optional kind of media item referenced by the entry.</param>
|
||||
/// <param name="position">Optional zero based position of the entry in the playlist.</param>
|
||||
/// <param name="libraryId">Optional Id of the media library that contains the media item.</param>
|
||||
/// <param name="collectionId">Optional Id of the collection that contains the media item.</param>
|
||||
/// <param name="creatorId">Optional Id of the creator of the media item.</param>
|
||||
/// <param name="mediaItemTitle">Optional title of the media item.</param>
|
||||
/// <param name="collectionTitle">Optional title of the collection that contains the media item.</param>
|
||||
/// <param name="creatorName">Optional name of the creator of the media item.</param>
|
||||
/// <param name="durationInSeconds">Optional duration of the media item in seconds.</param>
|
||||
/// <param name="coverPath">Optional path of the cover art of the collection.</param>
|
||||
/// <param name="includeCoverPath">Whether the cover path should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>A configured <see cref="PlaylistEntryDto"/> instance.</returns>
|
||||
public PlaylistEntryDto Create(
|
||||
Guid? id = null,
|
||||
Guid? mediaItemId = null,
|
||||
PlaylistMediaItemType? mediaItemType = null,
|
||||
int? position = null,
|
||||
Guid? libraryId = null,
|
||||
Guid? collectionId = null,
|
||||
Guid? creatorId = null,
|
||||
string? mediaItemTitle = null,
|
||||
string? collectionTitle = null,
|
||||
string? creatorName = null,
|
||||
int? durationInSeconds = null,
|
||||
string? coverPath = null,
|
||||
bool includeCoverPath = true)
|
||||
{
|
||||
return new PlaylistEntryDto(
|
||||
Id: id ?? _faker.Random.Guid(),
|
||||
MediaItemId: mediaItemId ?? _faker.Random.Guid(),
|
||||
MediaItemType: mediaItemType ?? _faker.PickRandom(PlaylistMediaItemType.MusicTrack, PlaylistMediaItemType.VideoFile),
|
||||
Position: position ?? _faker.Random.Int(0, 1000),
|
||||
LibraryId: libraryId ?? _faker.Random.Guid(),
|
||||
CollectionId: collectionId ?? _faker.Random.Guid(),
|
||||
CreatorId: creatorId ?? _faker.Random.Guid(),
|
||||
MediaItemTitle: mediaItemTitle ?? _faker.Lorem.Sentence(3),
|
||||
CollectionTitle: collectionTitle ?? _faker.Lorem.Sentence(2),
|
||||
CreatorName: creatorName ?? _faker.Name.FullName(),
|
||||
DurationInSeconds: durationInSeconds ?? _faker.Random.Int(0, 36000),
|
||||
CoverPath: includeCoverPath ? (coverPath ?? $"/artwork/{_faker.Random.Guid()}/cover.jpg") : null
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="PlaylistEntryDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="PlaylistEntryDto"/> instances.</returns>
|
||||
public List<PlaylistEntryDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.Enums.Favorites;
|
||||
using Lumina.Presentation.Web.Common.Requests.Favorites;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="AddFavoriteRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddFavoriteRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly FavoriteMediaKind[] _supportedMediaKinds =
|
||||
[
|
||||
FavoriteMediaKind.MusicArtist,
|
||||
FavoriteMediaKind.MusicAlbum,
|
||||
FavoriteMediaKind.MusicTrack,
|
||||
FavoriteMediaKind.Book
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="AddFavoriteRequest"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="mediaKind">Optional kind of the media item to favorite.</param>
|
||||
/// <param name="mediaItemId">Optional Id of the media item to favorite.</param>
|
||||
/// <param name="includeMediaKind">Whether the media kind should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMediaItemId">Whether the media item Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>A configured <see cref="AddFavoriteRequest"/> instance.</returns>
|
||||
public AddFavoriteRequest Create(
|
||||
FavoriteMediaKind? mediaKind = null,
|
||||
Guid? mediaItemId = null,
|
||||
bool includeMediaKind = true,
|
||||
bool includeMediaItemId = true)
|
||||
{
|
||||
return new AddFavoriteRequest(
|
||||
MediaKind: includeMediaKind ? (mediaKind ?? _faker.PickRandom(_supportedMediaKinds)) : null,
|
||||
MediaItemId: includeMediaItemId ? (mediaItemId ?? _faker.Random.Guid()) : null
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="AddFavoriteRequest"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="AddFavoriteRequest"/> instances.</returns>
|
||||
public List<AddFavoriteRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.Enums.Favorites;
|
||||
using Lumina.Presentation.Web.Common.Requests.Favorites;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetFavoriteStatusRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetFavoriteStatusRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly FavoriteMediaKind[] _supportedMediaKinds =
|
||||
[
|
||||
FavoriteMediaKind.MusicArtist,
|
||||
FavoriteMediaKind.MusicAlbum,
|
||||
FavoriteMediaKind.MusicTrack,
|
||||
FavoriteMediaKind.Book
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="GetFavoriteStatusRequest"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="mediaKind">Optional kind of the media items to check.</param>
|
||||
/// <param name="mediaItemIds">Optional Ids of the media items to check.</param>
|
||||
/// <param name="mediaItemCount">Optional number of random media item Ids to generate, between 1 and 5.</param>
|
||||
/// <param name="includeMediaKind">Whether the media kind should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMediaItemIds">Whether the media item Ids should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>A configured <see cref="GetFavoriteStatusRequest"/> instance.</returns>
|
||||
public GetFavoriteStatusRequest Create(
|
||||
FavoriteMediaKind? mediaKind = null,
|
||||
List<Guid>? mediaItemIds = null,
|
||||
int? mediaItemCount = null,
|
||||
bool includeMediaKind = true,
|
||||
bool includeMediaItemIds = true)
|
||||
{
|
||||
int resolvedCount = mediaItemCount ?? _faker.Random.Int(1, 5);
|
||||
return new GetFavoriteStatusRequest(
|
||||
MediaKind: includeMediaKind ? (mediaKind ?? _faker.PickRandom(_supportedMediaKinds)) : null,
|
||||
MediaItemIds: includeMediaItemIds ? (mediaItemIds ?? [.. Enumerable.Range(0, resolvedCount).Select(_ => _faker.Random.Guid())]) : null
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="GetFavoriteStatusRequest"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="GetFavoriteStatusRequest"/> instances.</returns>
|
||||
public List<GetFavoriteStatusRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.Enums.Favorites;
|
||||
using Lumina.Presentation.Web.Common.Requests.Favorites;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetFavoritesRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetFavoritesRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly FavoriteMediaKind[] _supportedMediaKinds =
|
||||
[
|
||||
FavoriteMediaKind.MusicArtist,
|
||||
FavoriteMediaKind.MusicAlbum,
|
||||
FavoriteMediaKind.MusicTrack,
|
||||
FavoriteMediaKind.Book
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="GetFavoritesRequest"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="mediaKind">Optional kind of media item to restrict the favorites to.</param>
|
||||
/// <param name="currentPage">Optional one based page of favorites to return.</param>
|
||||
/// <param name="perPage">Optional number of favorites per page.</param>
|
||||
/// <param name="includeMediaKind">Whether the media kind should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeCurrentPage">Whether the current page should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includePerPage">Whether the page size should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>A configured <see cref="GetFavoritesRequest"/> instance.</returns>
|
||||
public GetFavoritesRequest Create(
|
||||
FavoriteMediaKind? mediaKind = null,
|
||||
int? currentPage = null,
|
||||
int? perPage = null,
|
||||
bool includeMediaKind = true,
|
||||
bool includeCurrentPage = true,
|
||||
bool includePerPage = true)
|
||||
{
|
||||
return new GetFavoritesRequest(
|
||||
MediaKind: includeMediaKind ? (mediaKind ?? _faker.PickRandom(_supportedMediaKinds)) : null,
|
||||
CurrentPage: includeCurrentPage ? (currentPage ?? _faker.Random.Int(1, 10)) : null,
|
||||
PerPage: includePerPage ? (perPage ?? _faker.Random.Int(1, 100)) : null
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="GetFavoritesRequest"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="GetFavoritesRequest"/> instances.</returns>
|
||||
public List<GetFavoritesRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.Requests.Playlists;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetPlaylistRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPlaylistRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="GetPlaylistRequest"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="currentPage">Optional one based page of entries to return.</param>
|
||||
/// <param name="perPage">Optional number of entries per page.</param>
|
||||
/// <param name="includeCurrentPage">Whether the page should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includePerPage">Whether the page size should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>A configured <see cref="GetPlaylistRequest"/> instance.</returns>
|
||||
public GetPlaylistRequest Create(
|
||||
int? currentPage = null,
|
||||
int? perPage = null,
|
||||
bool includeCurrentPage = true,
|
||||
bool includePerPage = true)
|
||||
{
|
||||
return new GetPlaylistRequest(
|
||||
CurrentPage: includeCurrentPage ? (currentPage ?? _faker.Random.Int(1, 10)) : null,
|
||||
PerPage: includePerPage ? (perPage ?? _faker.Random.Int(1, 200)) : null
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="GetPlaylistRequest"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="GetPlaylistRequest"/> instances.</returns>
|
||||
public List<GetPlaylistRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+9
@@ -22,6 +22,15 @@ public class BaseEndpointFixture : BaseEndpoint<EmptyRequest, IResult>
|
||||
/// </summary>
|
||||
public string TestCulture => Culture;
|
||||
|
||||
/// <summary>
|
||||
/// Sets the <c>Cache-Control</c> header through the <see cref="BaseEndpoint.SetCacheControl(string)"/> helper.
|
||||
/// </summary>
|
||||
/// <param name="cacheControl">The <c>Cache-Control</c> value chosen by the endpoint.</param>
|
||||
public void TestSetCacheControl(string cacheControl)
|
||||
{
|
||||
SetCacheControl(cacheControl);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Renders a Razor view through the <see cref="BaseEndpoint.View(string, object?, IReadOnlyDictionary{string, object?})"/> helper.
|
||||
/// </summary>
|
||||
|
||||
+1172
File diff suppressed because it is too large.
Load diff
+385
@@ -13,6 +13,8 @@ using Lumina.DataAccess.Common.Interceptors;
|
||||
using Lumina.DataAccess.Core.Repositories.Playlists;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
@@ -41,6 +43,7 @@ public class PlaylistRepositoryTests
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenNoEditableValueChanged_ShouldNotModifyTheStoredPlaylist()
|
||||
@@ -422,6 +425,388 @@ public class PlaylistRepositoryTests
|
||||
Assert.False(await context.PlaylistEntries.AsNoTracking().AnyAsync(entry => entry.Id == firstEntry.Id));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetDetailsForUserAsync_WhenThePlaylistDoesNotExist_ShouldReturnSuccessWithNull()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-playlistrepo-details-missing-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
PlaylistRepository sut = new(context);
|
||||
|
||||
// Act
|
||||
Result<PlaylistDetailsDto?> result = await sut.GetDetailsForUserAsync(Guid.NewGuid(), Guid.NewGuid(), paginationData: null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Null(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetDetailsForUserAsync_WhenThePlaylistBelongsToAnotherUser_ShouldReturnSuccessWithNull()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-playlistrepo-details-other-user-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
PlaylistRepository sut = new(context);
|
||||
Guid ownerUserId = Guid.NewGuid();
|
||||
context.Users.Add(_userEntityFixture.Create(id: ownerUserId));
|
||||
(PlaylistEntity playlist, _) = await SeedOrderedPlaylistAsync(context, ownerUserId, entryCount: 2);
|
||||
|
||||
// Act
|
||||
Result<PlaylistDetailsDto?> result = await sut.GetDetailsForUserAsync(playlist.Id, Guid.NewGuid(), paginationData: null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Null(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetDetailsForUserAsync_WhenNoPaginationIsRequested_ShouldReturnEveryEntryWithDenseDisplayPositions()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-playlistrepo-details-all-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
PlaylistRepository sut = new(context);
|
||||
Guid userId = Guid.NewGuid();
|
||||
context.Users.Add(_userEntityFixture.Create(id: userId));
|
||||
(PlaylistEntity playlist, List<PlaylistEntryEntity> entries) = await SeedOrderedPlaylistAsync(context, userId, entryCount: 3);
|
||||
|
||||
// Act
|
||||
Result<PlaylistDetailsDto?> result = await sut.GetDetailsForUserAsync(playlist.Id, userId, paginationData: null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal([0, 1, 2], result.Value!.Entries.Data.Select(entry => entry.DisplayPosition));
|
||||
Assert.Equal(entries.Select(entry => entry.Id), result.Value.Entries.Data.Select(entry => entry.Entry.Id));
|
||||
Assert.Equal(1, result.Value.Entries.CurrentPage);
|
||||
Assert.Equal(3, result.Value.Entries.PerPage);
|
||||
Assert.Equal(3, result.Value.Entries.Count);
|
||||
Assert.Equal(1, result.Value.Entries.NumberOfPages);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetDetailsForUserAsync_WhenAPageIsRequested_ShouldReturnOnlyThatPageWithDenseDisplayPositions()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-playlistrepo-details-page-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
PlaylistRepository sut = new(context);
|
||||
Guid userId = Guid.NewGuid();
|
||||
context.Users.Add(_userEntityFixture.Create(id: userId));
|
||||
(PlaylistEntity playlist, List<PlaylistEntryEntity> entries) = await SeedOrderedPlaylistAsync(context, userId, entryCount: 5);
|
||||
PaginationDataDto firstPage = new() { CurrentPage = 1, PerPage = 2 };
|
||||
PaginationDataDto secondPage = new() { CurrentPage = 2, PerPage = 2 };
|
||||
|
||||
// Act
|
||||
Result<PlaylistDetailsDto?> firstPageResult = await sut.GetDetailsForUserAsync(playlist.Id, userId, firstPage, CancellationToken.None);
|
||||
Result<PlaylistDetailsDto?> secondPageResult = await sut.GetDetailsForUserAsync(playlist.Id, userId, secondPage, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(firstPageResult.IsFailure);
|
||||
Assert.NotNull(firstPageResult.Value);
|
||||
Assert.Equal([0, 1], firstPageResult.Value!.Entries.Data.Select(entry => entry.DisplayPosition));
|
||||
Assert.Equal([entries[0].Id, entries[1].Id], firstPageResult.Value.Entries.Data.Select(entry => entry.Entry.Id));
|
||||
Assert.Equal(1, firstPageResult.Value.Entries.CurrentPage);
|
||||
Assert.Equal(2, firstPageResult.Value.Entries.PerPage);
|
||||
Assert.Equal(5, firstPageResult.Value.Entries.Count);
|
||||
Assert.Equal(3, firstPageResult.Value.Entries.NumberOfPages);
|
||||
|
||||
Assert.False(secondPageResult.IsFailure);
|
||||
Assert.NotNull(secondPageResult.Value);
|
||||
// The display positions continue from the offset of the page, so the second page starts at 2 and not at 0.
|
||||
Assert.Equal([2, 3], secondPageResult.Value!.Entries.Data.Select(entry => entry.DisplayPosition));
|
||||
Assert.Equal([entries[2].Id, entries[3].Id], secondPageResult.Value.Entries.Data.Select(entry => entry.Entry.Id));
|
||||
Assert.Equal(2, secondPageResult.Value.Entries.CurrentPage);
|
||||
Assert.Equal(5, secondPageResult.Value.Entries.Count);
|
||||
Assert.Equal(3, secondPageResult.Value.Entries.NumberOfPages);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetDetailsForUserAsync_WhenTheRequestedPageExceedsTheLastPage_ShouldClampToTheLastPage()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-playlistrepo-details-clamp-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
PlaylistRepository sut = new(context);
|
||||
Guid userId = Guid.NewGuid();
|
||||
context.Users.Add(_userEntityFixture.Create(id: userId));
|
||||
(PlaylistEntity playlist, List<PlaylistEntryEntity> entries) = await SeedOrderedPlaylistAsync(context, userId, entryCount: 5);
|
||||
PaginationDataDto beyondLastPage = new() { CurrentPage = 99, PerPage = 2 };
|
||||
|
||||
// Act
|
||||
Result<PlaylistDetailsDto?> result = await sut.GetDetailsForUserAsync(playlist.Id, userId, beyondLastPage, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(3, result.Value!.Entries.CurrentPage);
|
||||
PlaylistEntryDto lastEntry = Assert.Single(result.Value.Entries.Data);
|
||||
Assert.Equal(entries[4].Id, lastEntry.Entry.Id);
|
||||
Assert.Equal(4, lastEntry.DisplayPosition);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetDetailsForUserAsync_WhenThePlaylistIsEmptyAndAPageIsRequested_ShouldReturnAnEmptyPage()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-playlistrepo-details-empty-page-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
PlaylistRepository sut = new(context);
|
||||
Guid userId = Guid.NewGuid();
|
||||
context.Users.Add(_userEntityFixture.Create(id: userId));
|
||||
(PlaylistEntity playlist, _) = await SeedOrderedPlaylistAsync(context, userId, entryCount: 0);
|
||||
PaginationDataDto paginationData = new() { CurrentPage = 2, PerPage = 3 };
|
||||
|
||||
// Act
|
||||
Result<PlaylistDetailsDto?> result = await sut.GetDetailsForUserAsync(playlist.Id, userId, paginationData, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Empty(result.Value!.Entries.Data);
|
||||
Assert.Equal(0, result.Value.Entries.Count);
|
||||
Assert.Equal(0, result.Value.Entries.NumberOfPages);
|
||||
Assert.Equal(1, result.Value.Entries.CurrentPage);
|
||||
Assert.Equal(3, result.Value.Entries.PerPage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetDetailsForUserAsync_WhenThePlaylistIsEmptyAndNoPaginationIsRequested_ShouldReturnAnEmptyResultWithOnePage()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-playlistrepo-details-empty-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
PlaylistRepository sut = new(context);
|
||||
Guid userId = Guid.NewGuid();
|
||||
context.Users.Add(_userEntityFixture.Create(id: userId));
|
||||
(PlaylistEntity playlist, _) = await SeedOrderedPlaylistAsync(context, userId, entryCount: 0);
|
||||
|
||||
// Act
|
||||
Result<PlaylistDetailsDto?> result = await sut.GetDetailsForUserAsync(playlist.Id, userId, paginationData: null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Empty(result.Value!.Entries.Data);
|
||||
Assert.Equal(0, result.Value.Entries.PerPage);
|
||||
Assert.Equal(0, result.Value.Entries.Count);
|
||||
Assert.Equal(1, result.Value.Entries.NumberOfPages);
|
||||
Assert.Equal(1, result.Value.Entries.CurrentPage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetDetailsForUserAsync_WhenAnEntryReferencesAMissingTrack_ShouldKeepTheEntryWithoutDisplayData()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-playlistrepo-details-missing-track-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
PlaylistRepository sut = new(context);
|
||||
Guid userId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
context.Users.Add(_userEntityFixture.Create(id: userId));
|
||||
(_, _, TrackEntity track) = await SeedTrackAsync(context, libraryId, artistName: "Existing Artist", albumTitle: "Existing Album", trackTitle: "Existing Track", coverFileName: "existing-cover.jpg");
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
PlaylistEntryEntity existingEntry = _playlistEntryEntityFixture.Create(
|
||||
playlistId: playlistId,
|
||||
mediaItemId: track.Id,
|
||||
mediaItemType: PlaylistMediaItemType.MusicTrack,
|
||||
position: 1_000_000_000L);
|
||||
PlaylistEntryEntity missingEntry = _playlistEntryEntityFixture.Create(
|
||||
playlistId: playlistId,
|
||||
mediaItemId: Guid.NewGuid(),
|
||||
mediaItemType: PlaylistMediaItemType.MusicTrack,
|
||||
position: 2_000_000_000L);
|
||||
PlaylistEntity playlist = _playlistEntityFixture.Create(
|
||||
id: playlistId,
|
||||
userId: userId,
|
||||
type: PlaylistType.Music,
|
||||
entries: [existingEntry, missingEntry],
|
||||
entryCount: 2,
|
||||
version: 0);
|
||||
context.Playlists.Add(playlist);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<PlaylistDetailsDto?> result = await sut.GetDetailsForUserAsync(playlistId, userId, paginationData: null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(2, result.Value!.Entries.Data.Count);
|
||||
PlaylistEntryDto missingItem = Assert.Single(result.Value.Entries.Data, entry => entry.Entry.Id == missingEntry.Id);
|
||||
Assert.Null(missingItem.Display);
|
||||
PlaylistEntryDto existingItem = Assert.Single(result.Value.Entries.Data, entry => entry.Entry.Id == existingEntry.Id);
|
||||
Assert.NotNull(existingItem.Display);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetDetailsForUserAsync_WhenTheEntriesReferenceMusicTracks_ShouldMapTheirDisplayData()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-playlistrepo-details-display-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
PlaylistRepository sut = new(context);
|
||||
Guid userId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
context.Users.Add(_userEntityFixture.Create(id: userId));
|
||||
string coverFileName = "album-cover.jpg";
|
||||
(ArtistEntity artist, AlbumEntity album, TrackEntity track) = await SeedTrackAsync(
|
||||
context,
|
||||
libraryId,
|
||||
artistName: "Display Artist",
|
||||
albumTitle: "Display Album",
|
||||
trackTitle: "Display Track",
|
||||
coverFileName: coverFileName);
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
PlaylistEntryEntity entry = _playlistEntryEntityFixture.Create(
|
||||
playlistId: playlistId,
|
||||
mediaItemId: track.Id,
|
||||
mediaItemType: PlaylistMediaItemType.MusicTrack,
|
||||
position: 1_000_000_000L);
|
||||
PlaylistEntity playlist = _playlistEntityFixture.Create(
|
||||
id: playlistId,
|
||||
userId: userId,
|
||||
type: PlaylistType.Music,
|
||||
entries: [entry],
|
||||
entryCount: 1,
|
||||
version: 0);
|
||||
context.Playlists.Add(playlist);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<PlaylistDetailsDto?> result = await sut.GetDetailsForUserAsync(playlistId, userId, paginationData: null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
PlaylistEntryDto item = Assert.Single(result.Value!.Entries.Data);
|
||||
Assert.NotNull(item.Display);
|
||||
Assert.Equal(track.Id, item.Display!.TrackId);
|
||||
Assert.Equal("Display Track", item.Display.TrackTitle);
|
||||
Assert.Equal(track.DurationInSeconds, item.Display.DurationInSeconds);
|
||||
Assert.Equal(libraryId, item.Display.LibraryId);
|
||||
Assert.Equal(album.Id, item.Display.AlbumId);
|
||||
Assert.Equal("Display Album", item.Display.AlbumTitle);
|
||||
Assert.Equal(artist.Id, item.Display.ArtistId);
|
||||
Assert.Equal("Display Artist", item.Display.ArtistName);
|
||||
Assert.Equal(coverFileName, item.Display.CoverPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetDetailsForUserAsync_WhenAnEntryReferencesANonMusicMediaItem_ShouldReturnNoDisplayData()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-playlistrepo-details-video-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
PlaylistRepository sut = new(context);
|
||||
Guid userId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
context.Users.Add(_userEntityFixture.Create(id: userId));
|
||||
(_, _, TrackEntity track) = await SeedTrackAsync(context, libraryId, artistName: "Video Artist", albumTitle: "Video Album", trackTitle: "Video Track", coverFileName: "video-cover.jpg");
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
// The media item Id belongs to a real track, so a null display proves the entry type is what excludes it, not a missing row.
|
||||
PlaylistEntryEntity entry = _playlistEntryEntityFixture.Create(
|
||||
playlistId: playlistId,
|
||||
mediaItemId: track.Id,
|
||||
mediaItemType: PlaylistMediaItemType.VideoFile,
|
||||
position: 1_000_000_000L);
|
||||
PlaylistEntity playlist = _playlistEntityFixture.Create(
|
||||
id: playlistId,
|
||||
userId: userId,
|
||||
type: PlaylistType.Music,
|
||||
entries: [entry],
|
||||
entryCount: 1,
|
||||
version: 0);
|
||||
context.Playlists.Add(playlist);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<PlaylistDetailsDto?> result = await sut.GetDetailsForUserAsync(playlistId, userId, paginationData: null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
PlaylistEntryDto item = Assert.Single(result.Value!.Entries.Data);
|
||||
Assert.Null(item.Display);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a playlist of the given user with the requested number of entries, each referencing a different generated media item.
|
||||
/// </summary>
|
||||
/// <param name="context">The context to seed.</param>
|
||||
/// <param name="userId">The Id of the user that owns the playlist.</param>
|
||||
/// <param name="entryCount">The number of entries the playlist receives.</param>
|
||||
/// <returns>The seeded playlist and its entries, in position order.</returns>
|
||||
private async Task<(PlaylistEntity Playlist, List<PlaylistEntryEntity> Entries)> SeedOrderedPlaylistAsync(LuminaDbContext context, Guid userId, int entryCount)
|
||||
{
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
List<PlaylistEntryEntity> entries = [.. Enumerable.Range(0, entryCount).Select(index => _playlistEntryEntityFixture.Create(
|
||||
playlistId: playlistId,
|
||||
mediaItemId: Guid.NewGuid(),
|
||||
mediaItemType: PlaylistMediaItemType.MusicTrack,
|
||||
position: (index + 1) * 1_000_000_000L))];
|
||||
PlaylistEntity playlist = _playlistEntityFixture.Create(
|
||||
id: playlistId,
|
||||
userId: userId,
|
||||
type: PlaylistType.Music,
|
||||
entries: entries,
|
||||
entryCount: entries.Count,
|
||||
version: 0);
|
||||
context.Playlists.Add(playlist);
|
||||
await context.SaveChangesAsync();
|
||||
return (playlist, entries);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds one artist, one album of that artist and one track of that album, together with the cover artwork of the album.
|
||||
/// </summary>
|
||||
/// <param name="context">The context to seed.</param>
|
||||
/// <param name="libraryId">The Id of the library the catalogue belongs to.</param>
|
||||
/// <param name="artistName">The name of the artist.</param>
|
||||
/// <param name="albumTitle">The title of the album.</param>
|
||||
/// <param name="trackTitle">The title of the track.</param>
|
||||
/// <param name="coverFileName">The file name of the cover artwork of the album.</param>
|
||||
/// <returns>The seeded artist, album and track.</returns>
|
||||
private async Task<(ArtistEntity Artist, AlbumEntity Album, TrackEntity Track)> SeedTrackAsync(
|
||||
LuminaDbContext context,
|
||||
Guid libraryId,
|
||||
string artistName,
|
||||
string albumTitle,
|
||||
string trackTitle,
|
||||
string coverFileName)
|
||||
{
|
||||
ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, name: artistName, includeAlbums: false, includeContributors: false);
|
||||
context.Artists.Add(artist);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, title: albumTitle, includeTracks: false, includeMetadata: false);
|
||||
context.Albums.Add(album);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, title: trackTitle, includeMetadata: false);
|
||||
context.Tracks.Add(track);
|
||||
context.MusicArtwork.Add(_musicArtworkEntityFixture.Create(
|
||||
ownerType: MusicArtworkOwnerType.Album,
|
||||
ownerId: album.Id,
|
||||
artworkType: ArtworkType.Cover,
|
||||
ordinal: 0,
|
||||
fileName: coverFileName));
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
return (artist, album, track);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a real SQLite backed context with the auditing interceptor attached, so that audit columns behave exactly like in production.
|
||||
/// </summary>
|
||||
|
||||
+178
@@ -1,12 +1,22 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Favorites;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Time;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.DataAccess.Common.Interceptors;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
@@ -25,6 +35,8 @@ public class UnitOfWorkTests
|
||||
{
|
||||
private readonly RoleEntityFixture _roleEntityFixture = new();
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly FavoriteEntityFixture _favoriteEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
[Fact]
|
||||
public async Task BeginTransactionAsync_WhenCalled_ShouldBeginTransactionOnTheDatabase()
|
||||
@@ -216,6 +228,150 @@ public class UnitOfWorkTests
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FavoriteRepository_WhenAccessedRepeatedly_ShouldReturnTheSameCachedInstance()
|
||||
{
|
||||
// Arrange
|
||||
(SqliteConnection anchorConnection, LuminaDbContext dbContext) = CreateSqliteContext();
|
||||
using (anchorConnection)
|
||||
{
|
||||
using (dbContext)
|
||||
{
|
||||
UnitOfWork sut = new(dbContext);
|
||||
|
||||
// Act
|
||||
IFavoriteRepository firstRepository = sut.FavoriteRepository;
|
||||
IFavoriteRepository secondRepository = sut.FavoriteRepository;
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(firstRepository);
|
||||
Assert.Same(firstRepository, secondRepository);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveChangesAsync_WhenInsertingTwoFavoritesForTheSameUserKindAndMediaItem_ShouldReturnUniqueConstraintViolationError()
|
||||
{
|
||||
// Arrange
|
||||
(SqliteConnection anchorConnection, LuminaDbContext dbContext) = CreateSqliteContext();
|
||||
using (anchorConnection)
|
||||
{
|
||||
using (dbContext)
|
||||
{
|
||||
UnitOfWork sut = new(dbContext);
|
||||
Guid userId = Guid.NewGuid();
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId));
|
||||
Result<Success> userSaveResult = await sut.SaveChangesAsync(CancellationToken.None);
|
||||
Assert.False(userSaveResult.IsFailure);
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
FavoriteEntity firstFavorite = _favoriteEntityFixture.Create(
|
||||
userId: userId,
|
||||
mediaKind: FavoriteMediaKind.MusicArtist,
|
||||
mediaItemId: mediaItemId,
|
||||
includeUpdatedOnUtc: false,
|
||||
includeUpdatedBy: false);
|
||||
_ = await sut.FavoriteRepository.InsertAsync(firstFavorite, CancellationToken.None);
|
||||
Result<Success> firstSaveResult = await sut.SaveChangesAsync(CancellationToken.None);
|
||||
Assert.False(firstSaveResult.IsFailure);
|
||||
|
||||
// stage a duplicate directly through the repository, bypassing the application level existence check, so that the unique index of the storage medium is the one that rejects it
|
||||
FavoriteEntity duplicateFavorite = _favoriteEntityFixture.Create(
|
||||
userId: userId,
|
||||
mediaKind: FavoriteMediaKind.MusicArtist,
|
||||
mediaItemId: mediaItemId,
|
||||
includeUpdatedOnUtc: false,
|
||||
includeUpdatedBy: false);
|
||||
_ = await sut.FavoriteRepository.InsertAsync(duplicateFavorite, CancellationToken.None);
|
||||
|
||||
// Act
|
||||
Result<Success> result = await sut.SaveChangesAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearTrackedEntities_WhenEntitiesAreTracked_ShouldDetachEveryEntity()
|
||||
{
|
||||
// Arrange
|
||||
(SqliteConnection anchorConnection, LuminaDbContext dbContext) = CreateSqliteContext();
|
||||
using (anchorConnection)
|
||||
{
|
||||
using (dbContext)
|
||||
{
|
||||
UnitOfWork sut = new(dbContext);
|
||||
Guid userId = Guid.NewGuid();
|
||||
UserEntity user = _userEntityFixture.Create(id: userId);
|
||||
FavoriteEntity favorite = _favoriteEntityFixture.Create(
|
||||
userId: userId,
|
||||
mediaKind: FavoriteMediaKind.MusicTrack,
|
||||
includeUpdatedOnUtc: false,
|
||||
includeUpdatedBy: false);
|
||||
dbContext.Users.Add(user);
|
||||
dbContext.Favorites.Add(favorite);
|
||||
await dbContext.SaveChangesAsync();
|
||||
Assert.Equal(2, dbContext.ChangeTracker.Entries().Count());
|
||||
|
||||
// Act
|
||||
sut.ClearTrackedEntities();
|
||||
|
||||
// Assert
|
||||
Assert.Empty(dbContext.ChangeTracker.Entries());
|
||||
Assert.Equal(EntityState.Detached, dbContext.Entry(favorite).State);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveChangesAsync_WhenInsertingAValidFavorite_ShouldPersistEveryFieldThroughTheAuditInterceptor()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
|
||||
(SqliteConnection anchorConnection, LuminaDbContext dbContext) = CreateAuditedSqliteContext(userId, utcNow);
|
||||
using (anchorConnection)
|
||||
{
|
||||
using (dbContext)
|
||||
{
|
||||
UnitOfWork sut = new(dbContext);
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId));
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
// The fixture populates the update audit columns, so the test also proves the interceptor owns them on insert.
|
||||
FavoriteEntity favorite = _favoriteEntityFixture.Create(
|
||||
userId: userId,
|
||||
mediaKind: FavoriteMediaKind.Book,
|
||||
mediaItemId: mediaItemId,
|
||||
createdOnUtc: DateTime.MinValue,
|
||||
createdBy: Guid.Empty,
|
||||
updatedOnUtc: DateTime.MaxValue,
|
||||
updatedBy: Guid.NewGuid(),
|
||||
includeUpdatedOnUtc: true,
|
||||
includeUpdatedBy: true);
|
||||
Result<Created> insertResult = await sut.FavoriteRepository.InsertAsync(favorite, CancellationToken.None);
|
||||
Assert.False(insertResult.IsFailure);
|
||||
|
||||
// Act
|
||||
Result<Success> result = await sut.SaveChangesAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
dbContext.ChangeTracker.Clear();
|
||||
FavoriteEntity storedFavorite = await dbContext.Favorites.AsNoTracking().SingleAsync(candidate => candidate.Id == favorite.Id);
|
||||
Assert.Equal(userId, storedFavorite.UserId);
|
||||
Assert.Equal(FavoriteMediaKind.Book, storedFavorite.MediaKind);
|
||||
Assert.Equal(mediaItemId, storedFavorite.MediaItemId);
|
||||
Assert.Equal(utcNow, storedFavorite.CreatedOnUtc);
|
||||
Assert.Equal(userId, storedFavorite.CreatedBy);
|
||||
Assert.Null(storedFavorite.UpdatedOnUtc);
|
||||
Assert.Null(storedFavorite.UpdatedBy);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a real SQLite in-memory context, kept alive by an anchor connection, because transactions are not supported by the in-memory provider.
|
||||
/// </summary>
|
||||
@@ -228,4 +384,26 @@ public class UnitOfWorkTests
|
||||
dbContext.Database.EnsureCreated();
|
||||
return (anchorConnection, dbContext);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a real SQLite in-memory context with the auditing interceptor attached, so that audit columns behave exactly like in production.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user reported as the current user.</param>
|
||||
/// <param name="utcNow">The current UTC time reported by the time provider.</param>
|
||||
/// <returns>A tuple containing the anchor connection and the database context.</returns>
|
||||
private static (SqliteConnection AnchorConnection, LuminaDbContext Context) CreateAuditedSqliteContext(Guid userId, DateTime utcNow)
|
||||
{
|
||||
SqliteConnection anchorConnection = new($"Data Source=luminadataccess-unitofwork-audit-tests-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
ICurrentUserService currentUserService = Substitute.For<ICurrentUserService>();
|
||||
currentUserService.UserId.Returns(userId);
|
||||
IDateTimeProvider dateTimeProvider = Substitute.For<IDateTimeProvider>();
|
||||
dateTimeProvider.UtcNow.Returns(utcNow);
|
||||
LuminaDbContext dbContext = new(new DbContextOptionsBuilder<LuminaDbContext>()
|
||||
.UseSqlite(anchorConnection.ConnectionString)
|
||||
.AddInterceptors(new UpdateAuditableEntitiesInterceptor(currentUserService, dateTimeProvider))
|
||||
.Options);
|
||||
dbContext.Database.EnsureCreated();
|
||||
return (anchorConnection, dbContext);
|
||||
}
|
||||
}
|
||||
+568
@@ -0,0 +1,568 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.Favorites;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Favorites.AddFavorite;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Favorites.AddFavorite;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="AddFavoriteEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddFavoriteEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private const string PATH = "/api/v1/users/me/favorites";
|
||||
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new();
|
||||
private readonly BookContributorEntityFixture _bookContributorEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly List<Guid> _seededLibraryIds = [];
|
||||
private readonly List<Guid> _seededUserIds = [];
|
||||
private readonly List<Guid> _seededMediaContributorIds = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddFavoriteEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public AddFavoriteEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(FavoriteMediaKind.MusicArtist)] // a favorite of an artist of a music library
|
||||
[InlineData(FavoriteMediaKind.MusicAlbum)] // a favorite of an album of a music library
|
||||
[InlineData(FavoriteMediaKind.MusicTrack)] // a favorite of a track of a music library
|
||||
[InlineData(FavoriteMediaKind.Book)] // a favorite of a book of a book library
|
||||
public async Task AddFavorite_WhenMediaItemExists_ShouldReturnTheFavoriteAndStoreOneRowForTheCaller(FavoriteMediaKind mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Dictionary<FavoriteMediaKind, Guid> mediaItemIds = await SeedCatalogueAsync(userId);
|
||||
Guid mediaItemId = mediaItemIds[mediaKind];
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, new { mediaKind = mediaKind.ToString(), mediaItemId = mediaItemId });
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
FavoriteResponse? favorite = await DeserializeAsync<FavoriteResponse>(response);
|
||||
Assert.NotNull(favorite);
|
||||
Assert.NotEqual(Guid.Empty, favorite!.Id);
|
||||
Assert.Equal(mediaKind, favorite.MediaKind);
|
||||
Assert.Equal(mediaItemId, favorite.MediaItemId);
|
||||
Assert.NotEqual(default, favorite.FavoritedOnUtc);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<FavoriteEntity> rows = await dbContext.Favorites
|
||||
.AsNoTracking()
|
||||
.Where(candidate => candidate.UserId == userId && candidate.MediaKind == mediaKind && candidate.MediaItemId == mediaItemId)
|
||||
.ToListAsync();
|
||||
FavoriteEntity row = Assert.Single(rows);
|
||||
Assert.Equal(favorite.Id, row.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddFavorite_WhenTheSameItemIsAddedTwice_ShouldReturnTheSameFavoriteAndKeepASingleRow()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid mediaItemId = await SeedTrackAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage firstResponse = await _client.PostAsJsonAsync(PATH, new { mediaKind = "MusicTrack", mediaItemId = mediaItemId });
|
||||
HttpResponseMessage secondResponse = await _client.PostAsJsonAsync(PATH, new { mediaKind = "MusicTrack", mediaItemId = mediaItemId });
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, firstResponse.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.OK, secondResponse.StatusCode);
|
||||
FavoriteResponse? firstFavorite = await DeserializeAsync<FavoriteResponse>(firstResponse);
|
||||
FavoriteResponse? secondFavorite = await DeserializeAsync<FavoriteResponse>(secondResponse);
|
||||
Assert.NotNull(firstFavorite);
|
||||
Assert.NotNull(secondFavorite);
|
||||
Assert.Equal(firstFavorite!.Id, secondFavorite!.Id);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.Equal(1, await dbContext.Favorites.CountAsync(candidate => candidate.UserId == userId && candidate.MediaItemId == mediaItemId));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(FavoriteMediaKind.MusicArtist, "ArtistNotFound")] // a missing artist is reported with the artist detail
|
||||
[InlineData(FavoriteMediaKind.MusicAlbum, "AlbumNotFound")] // a missing album is reported with the album detail
|
||||
[InlineData(FavoriteMediaKind.MusicTrack, "TrackNotFound")] // a missing track is reported with the track detail
|
||||
[InlineData(FavoriteMediaKind.Book, "BookNotFound")] // a missing book is reported with the book detail
|
||||
public async Task AddFavorite_WhenMediaItemDoesNotExist_ShouldReturnNotFoundWithTheKindSpecificDetail(FavoriteMediaKind mediaKind, string expectedDetail)
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, new { mediaKind = mediaKind.ToString(), mediaItemId = mediaItemId });
|
||||
|
||||
// Assert
|
||||
await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", expectedDetail, PATH);
|
||||
AssertCacheHeaders(response);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.False(await dbContext.Favorites.AnyAsync(candidate => candidate.UserId == userId && candidate.MediaItemId == mediaItemId));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(FavoriteMediaKind.Video)] // video libraries are not catalogued yet
|
||||
[InlineData(FavoriteMediaKind.Photo)] // photo libraries are not catalogued yet
|
||||
public async Task AddFavorite_WhenMediaKindIsPlanned_ShouldReturnValidationProblem(FavoriteMediaKind mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, new { mediaKind = mediaKind.ToString(), mediaItemId = mediaItemId });
|
||||
|
||||
// Assert
|
||||
await AssertValidationProblemAsync(response, PATH, "FavoriteMediaKindIsNotSupported");
|
||||
AssertCacheHeaders(response);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.False(await dbContext.Favorites.AnyAsync(candidate => candidate.UserId == userId && candidate.MediaItemId == mediaItemId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddFavorite_WhenMediaKindIsMissing_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, new { mediaKind = (string?)null, mediaItemId = mediaItemId });
|
||||
|
||||
// Assert
|
||||
await AssertValidationProblemAsync(response, PATH, "FavoriteMediaKindIsInvalid");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddFavorite_WhenMediaKindIsNone_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, new { mediaKind = nameof(FavoriteMediaKind.None), mediaItemId });
|
||||
|
||||
// Assert
|
||||
await AssertValidationProblemAsync(response, PATH, "FavoriteMediaKindIsInvalid");
|
||||
AssertCacheHeaders(response);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.False(await dbContext.Favorites.AnyAsync(candidate => candidate.UserId == userId && candidate.MediaItemId == mediaItemId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddFavorite_WhenMediaItemIdIsEmpty_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, new { mediaKind = "MusicTrack", mediaItemId = Guid.Empty });
|
||||
|
||||
// Assert
|
||||
await AssertValidationProblemAsync(response, PATH, "FavoriteMediaItemIdCannotBeEmpty");
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.False(await dbContext.Favorites.AnyAsync(candidate => candidate.UserId == userId && candidate.MediaItemId == Guid.Empty));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddFavorite_WhenTheBodyIsEmpty_ShouldReturnBothValidationProblems()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, new { });
|
||||
|
||||
// Assert
|
||||
await AssertValidationProblemAsync(response, PATH, "FavoriteMediaKindIsInvalid", "FavoriteMediaItemIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddFavorite_WhenMediaItemBelongsToAnotherUsersLibrary_ShouldReturnTheSameNotFoundAsAMissingItem()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherTrackId = await SeedTrackAsync(otherUserId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, new { mediaKind = "MusicTrack", mediaItemId = otherTrackId });
|
||||
|
||||
// Assert
|
||||
// The response is indistinguishable from the one of a missing item, so it cannot be used to probe another user's library.
|
||||
await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "TrackNotFound", PATH);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.False(await dbContext.Favorites.AnyAsync(candidate => candidate.MediaItemId == otherTrackId));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds one artist, one album, one track and one book owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the seeded libraries.</param>
|
||||
/// <returns>The Ids of the seeded media items, keyed by their kind.</returns>
|
||||
private async Task<Dictionary<FavoriteMediaKind, Guid>> SeedCatalogueAsync(Guid userId)
|
||||
{
|
||||
Guid musicLibraryId = await SeedLibraryAsync(userId, LibraryType.Music);
|
||||
Guid artistId = await SeedArtistAsync(musicLibraryId, "Favorite Artist");
|
||||
Guid albumId = await SeedAlbumAsync(musicLibraryId, artistId, "Favorite Album");
|
||||
Guid trackId = await SeedTrackAsync(musicLibraryId, albumId, "Favorite Track");
|
||||
await SeedAlbumCoverAsync(albumId, "favorite-cover.jpg");
|
||||
Guid bookLibraryId = await SeedLibraryAsync(userId, LibraryType.EBook);
|
||||
Guid bookId = await SeedBookAsync(bookLibraryId, "Favorite Book", "Favorite Author");
|
||||
|
||||
return new Dictionary<FavoriteMediaKind, Guid>
|
||||
{
|
||||
[FavoriteMediaKind.MusicArtist] = artistId,
|
||||
[FavoriteMediaKind.MusicAlbum] = albumId,
|
||||
[FavoriteMediaKind.MusicTrack] = trackId,
|
||||
[FavoriteMediaKind.Book] = bookId
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/> with one track, and returns the Id of that track.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the seeded library.</param>
|
||||
/// <returns>The Id of the seeded track.</returns>
|
||||
private async Task<Guid> SeedTrackAsync(Guid userId)
|
||||
{
|
||||
Guid musicLibraryId = await SeedLibraryAsync(userId, LibraryType.Music);
|
||||
Guid artistId = await SeedArtistAsync(musicLibraryId, "Single Artist");
|
||||
Guid albumId = await SeedAlbumAsync(musicLibraryId, artistId, "Single Album");
|
||||
return await SeedTrackAsync(musicLibraryId, albumId, "Single Track");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library of the given type owned by <paramref name="userId"/> and tracks it for cleanup.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the media library.</param>
|
||||
/// <param name="libraryType">The type of the media library.</param>
|
||||
/// <returns>The Id of the seeded media library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId, LibraryType libraryType)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(
|
||||
id: libraryId, userId: userId, title: $"Library-{Guid.NewGuid():N}", libraryType: libraryType, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededLibraryIds.Add(libraryId);
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an artist of the library identified by <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library the artist belongs to.</param>
|
||||
/// <param name="name">The name of the artist.</param>
|
||||
/// <returns>The Id of the seeded artist.</returns>
|
||||
private async Task<Guid> SeedArtistAsync(Guid libraryId, string name)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(
|
||||
id: artistId, libraryId: libraryId, name: name, includeAlbums: false, includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return artistId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an album of the artist identified by <paramref name="artistId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library the album belongs to.</param>
|
||||
/// <param name="artistId">The Id of the artist the album belongs to.</param>
|
||||
/// <param name="title">The title of the album.</param>
|
||||
/// <returns>The Id of the seeded album.</returns>
|
||||
private async Task<Guid> SeedAlbumAsync(Guid libraryId, Guid artistId, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AlbumEntity album = _albumEntityFixture.Create(
|
||||
id: albumId,
|
||||
artistId: artistId,
|
||||
libraryId: libraryId,
|
||||
title: title,
|
||||
includeTracks: false,
|
||||
includeMetadata: false,
|
||||
includeBarcode: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false);
|
||||
dbContext.Albums.Add(album);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return albumId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a track of the album identified by <paramref name="albumId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library the track belongs to.</param>
|
||||
/// <param name="albumId">The Id of the album the track belongs to.</param>
|
||||
/// <param name="title">The title of the track.</param>
|
||||
/// <returns>The Id of the seeded track.</returns>
|
||||
private async Task<Guid> SeedTrackAsync(Guid libraryId, Guid albumId, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
TrackEntity track = _trackEntityFixture.Create(
|
||||
id: trackId,
|
||||
albumId: albumId,
|
||||
libraryId: libraryId,
|
||||
title: title,
|
||||
includeMetadata: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false);
|
||||
dbContext.Tracks.Add(track);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return trackId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds the cover artwork of the album identified by <paramref name="albumId"/>.
|
||||
/// </summary>
|
||||
/// <param name="albumId">The Id of the album that owns the artwork.</param>
|
||||
/// <param name="fileName">The file name of the stored cover.</param>
|
||||
private async Task SeedAlbumCoverAsync(Guid albumId, string fileName)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.MusicArtwork.Add(_musicArtworkEntityFixture.Create(
|
||||
ownerType: MusicArtworkOwnerType.Album,
|
||||
ownerId: albumId,
|
||||
artworkType: ArtworkType.Cover,
|
||||
ordinal: 0,
|
||||
fileName: fileName));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a book of the library identified by <paramref name="libraryId"/>, with one author.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library the book belongs to.</param>
|
||||
/// <param name="title">The title of the book.</param>
|
||||
/// <param name="authorName">The display name of the author of the book.</param>
|
||||
/// <returns>The Id of the seeded book.</returns>
|
||||
private async Task<Guid> SeedBookAsync(Guid libraryId, string title, string authorName)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
Guid contributorId = Guid.NewGuid();
|
||||
dbContext.Books.Add(_bookEntityFixture.Create(id: bookId, libraryId: libraryId, title: title, includeMetadata: false));
|
||||
dbContext.MediaContributors.Add(_mediaContributorEntityFixture.Create(id: contributorId, displayName: authorName));
|
||||
dbContext.BookContributors.Add(_bookContributorEntityFixture.Create(bookId: bookId, mediaContributorId: contributorId, role: MediaContributorRole.Author));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededMediaContributorIds.Add(contributorId);
|
||||
return bookId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and tracks it for cleanup.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"otheruser_{Guid.NewGuid()}";
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededUserIds.Add(userId);
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the authenticated test user.</returns>
|
||||
private Guid GetCurrentUserId()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity user = dbContext.Users.First(candidate => candidate.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes the body of <paramref name="response"/> to <typeparamref name="TValue"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="TValue">The type to deserialize the body to.</typeparam>
|
||||
/// <param name="response">The HTTP response to read.</param>
|
||||
/// <returns>The deserialized body.</returns>
|
||||
private async Task<TValue?> DeserializeAsync<TValue>(HttpResponseMessage response)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
return JsonSerializer.Deserialize<TValue>(content, _jsonOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
|
||||
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is a problem details document with the expected status, title and detail.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedStatus">The expected HTTP status.</param>
|
||||
/// <param name="expectedTitle">The expected problem title.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private static async Task AssertProblemAsync(HttpResponseMessage response, HttpStatusCode expectedStatus, string expectedTitle, string expectedDetail, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(expectedStatus, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)expectedStatus, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal(expectedTitle, problemDetails["title"].GetString());
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
|
||||
AssertNoSensitiveData(content);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is a validation problem details document carrying exactly the expected error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present, in order.</param>
|
||||
private static async Task AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(422, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>();
|
||||
Assert.NotNull(errors);
|
||||
Assert.Equal(expectedErrorCodes, errors!["General.Validation"]);
|
||||
AssertNoSensitiveData(content);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response body carries no credentials, secrets or stack traces.
|
||||
/// </summary>
|
||||
/// <param name="content">The response body to assert on.</param>
|
||||
private static void AssertNoSensitiveData(string content)
|
||||
{
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the data seeded by the test and the API factory test user.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using (IServiceScope scope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<Guid> libraryIds = [.. _seededLibraryIds];
|
||||
List<Guid> albumIds = await dbContext.Albums.Where(album => libraryIds.Contains(album.LibraryId)).Select(album => album.Id).ToListAsync();
|
||||
List<Guid> bookIds = await dbContext.Books.Where(book => libraryIds.Contains(book.LibraryId)).Select(book => book.Id).ToListAsync();
|
||||
dbContext.MusicArtwork.RemoveRange(dbContext.MusicArtwork.Where(artwork => albumIds.Contains(artwork.OwnerId)));
|
||||
dbContext.BookContributors.RemoveRange(dbContext.BookContributors.Where(contributor => bookIds.Contains(contributor.BookId)));
|
||||
dbContext.Tracks.RemoveRange(dbContext.Tracks.Where(track => libraryIds.Contains(track.LibraryId)));
|
||||
dbContext.Albums.RemoveRange(dbContext.Albums.Where(album => libraryIds.Contains(album.LibraryId)));
|
||||
dbContext.Artists.RemoveRange(dbContext.Artists.Where(artist => libraryIds.Contains(artist.LibraryId)));
|
||||
dbContext.Books.RemoveRange(dbContext.Books.Where(book => libraryIds.Contains(book.LibraryId)));
|
||||
dbContext.Libraries.RemoveRange(dbContext.Libraries.Where(library => libraryIds.Contains(library.Id)));
|
||||
dbContext.MediaContributors.RemoveRange(dbContext.MediaContributors.Where(contributor => _seededMediaContributorIds.Contains(contributor.Id)));
|
||||
dbContext.Users.RemoveRange(dbContext.Users.Where(user => _seededUserIds.Contains(user.Id)));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+322
@@ -0,0 +1,322 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.Favorites;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Favorites.GetFavoriteStatus;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Favorites.GetFavoriteStatus;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetFavoriteStatusEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetFavoriteStatusEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private const string PATH = "/api/v1/users/me/favorites/status";
|
||||
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly FavoriteEntityFixture _favoriteEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly List<Guid> _seededUserIds = [];
|
||||
private readonly List<Guid> _seededFavoriteIds = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetFavoriteStatusEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetFavoriteStatusEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavoriteStatus_WhenSomeOfTheRequestedItemsAreFavorites_ShouldReturnExactlyThoseIdsOfTheCallerAndKind()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid favoritedTrackId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
Guid notFavoritedId = Guid.NewGuid();
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, favoritedTrackId);
|
||||
// The book is a favorite of the caller, but of another kind, so it must not be reported for a MusicTrack query.
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.Book, bookId);
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherUserTrackId = Guid.NewGuid();
|
||||
await SeedFavoriteAsync(otherUserId, FavoriteMediaKind.MusicTrack, otherUserTrackId);
|
||||
string url = $"{PATH}?mediaKind=MusicTrack&mediaItemIds={favoritedTrackId}&mediaItemIds={bookId}&mediaItemIds={otherUserTrackId}&mediaItemIds={notFavoritedId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
FavoriteStatusResponse? status = await DeserializeAsync<FavoriteStatusResponse>(response);
|
||||
Assert.NotNull(status);
|
||||
Guid favoritedId = Assert.Single(status!.FavoritedMediaItemIds);
|
||||
Assert.Equal(favoritedTrackId, favoritedId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavoriteStatus_WhenTheSameIdIsRequestedTwice_ShouldReturnItOnce()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid favoritedTrackId = Guid.NewGuid();
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, favoritedTrackId);
|
||||
string url = $"{PATH}?mediaKind=MusicTrack&mediaItemIds={favoritedTrackId}&mediaItemIds={favoritedTrackId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
FavoriteStatusResponse? status = await DeserializeAsync<FavoriteStatusResponse>(response);
|
||||
Assert.NotNull(status);
|
||||
Guid favoritedId = Assert.Single(status!.FavoritedMediaItemIds);
|
||||
Assert.Equal(favoritedTrackId, favoritedId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavoriteStatus_WhenOneHundredIdsAreRequested_ShouldAcceptThem()
|
||||
{
|
||||
// Arrange
|
||||
List<Guid> requestedIds = [.. Enumerable.Range(0, 100).Select(_ => Guid.NewGuid())];
|
||||
string url = $"{PATH}?mediaKind=MusicTrack&{string.Join("&", requestedIds.Select(requestedId => $"mediaItemIds={requestedId}"))}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
FavoriteStatusResponse? status = await DeserializeAsync<FavoriteStatusResponse>(response);
|
||||
Assert.NotNull(status);
|
||||
Assert.Empty(status!.FavoritedMediaItemIds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavoriteStatus_WhenMoreThanOneHundredIdsAreRequested_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
List<Guid> requestedIds = [.. Enumerable.Range(0, 101).Select(_ => Guid.NewGuid())];
|
||||
string url = $"{PATH}?mediaKind=MusicTrack&{string.Join("&", requestedIds.Select(requestedId => $"mediaItemIds={requestedId}"))}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertValidationProblemAsync(response, PATH, "FavoriteMediaItemIdsExceedMaximumCount");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavoriteStatus_WhenNoMediaItemIdsAreProvided_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}?mediaKind=MusicTrack");
|
||||
|
||||
// Assert
|
||||
await AssertValidationProblemAsync(response, PATH, "FavoriteMediaItemIdsCannotBeEmpty");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavoriteStatus_WhenTheEmptyGuidIsRequested_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}?mediaKind=MusicTrack&mediaItemIds={Guid.Empty}");
|
||||
|
||||
// Assert
|
||||
await AssertValidationProblemAsync(response, PATH, "FavoriteMediaItemIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavoriteStatus_WhenTheMediaKindIsNone_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid favoritedTrackId = Guid.NewGuid();
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, favoritedTrackId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}?mediaKind={nameof(FavoriteMediaKind.None)}&mediaItemIds={favoritedTrackId}");
|
||||
|
||||
// Assert
|
||||
await AssertValidationProblemAsync(response, PATH, "FavoriteMediaKindIsInvalid");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain(favoritedTrackId.ToString(), content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavoriteStatus_WhenTheMediaKindIsNotAMemberName_ShouldNotReturnAnyId()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid favoritedTrackId = Guid.NewGuid();
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, favoritedTrackId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}?mediaKind=NotAMediaKind&mediaItemIds={favoritedTrackId}");
|
||||
|
||||
// Assert
|
||||
// The request binds the media kind as an enumeration, so an unparseable value is answered by the generic exception handler
|
||||
// with the sanitized problem before the handler runs, and no favorite status is disclosed.
|
||||
Assert.False(response.IsSuccessStatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain(favoritedTrackId.ToString(), content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a favorite of <paramref name="userId"/> and tracks it for cleanup.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the favorite.</param>
|
||||
/// <param name="mediaKind">The kind of the favorited media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the favorited media item.</param>
|
||||
/// <returns>The Id of the seeded favorite.</returns>
|
||||
private async Task<Guid> SeedFavoriteAsync(Guid userId, FavoriteMediaKind mediaKind, Guid mediaItemId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid favoriteId = Guid.NewGuid();
|
||||
dbContext.Favorites.Add(_favoriteEntityFixture.Create(
|
||||
id: favoriteId,
|
||||
userId: userId,
|
||||
mediaKind: mediaKind,
|
||||
mediaItemId: mediaItemId,
|
||||
createdBy: userId,
|
||||
includeUpdatedOnUtc: false,
|
||||
includeUpdatedBy: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededFavoriteIds.Add(favoriteId);
|
||||
return favoriteId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and tracks it for cleanup.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"otheruser_{Guid.NewGuid()}";
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededUserIds.Add(userId);
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the authenticated test user.</returns>
|
||||
private Guid GetCurrentUserId()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity user = dbContext.Users.First(candidate => candidate.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes the body of <paramref name="response"/> to <typeparamref name="TValue"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="TValue">The type to deserialize the body to.</typeparam>
|
||||
/// <param name="response">The HTTP response to read.</param>
|
||||
/// <returns>The deserialized body.</returns>
|
||||
private async Task<TValue?> DeserializeAsync<TValue>(HttpResponseMessage response)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
return JsonSerializer.Deserialize<TValue>(content, _jsonOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
|
||||
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is a validation problem details document carrying the expected error code.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCode">The expected validation error code.</param>
|
||||
private static async Task AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstance, string expectedErrorCode)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(422, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>();
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains(expectedErrorCode, errors!["General.Validation"]);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the data seeded by the test and the API factory test user.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using (IServiceScope scope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Favorites.RemoveRange(dbContext.Favorites.Where(favorite => _seededFavoriteIds.Contains(favorite.Id)));
|
||||
dbContext.Users.RemoveRange(dbContext.Users.Where(user => _seededUserIds.Contains(user.Id)));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+638
@@ -0,0 +1,638 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
using Lumina.Contracts.Responses.Favorites;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Favorites.GetFavorites;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Favorites.GetFavorites;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetFavoritesEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetFavoritesEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private const string PATH = "/api/v1/users/me/favorites";
|
||||
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new();
|
||||
private readonly BookContributorEntityFixture _bookContributorEntityFixture = new();
|
||||
private readonly FavoriteEntityFixture _favoriteEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly List<Guid> _seededLibraryIds = [];
|
||||
private readonly List<Guid> _seededUserIds = [];
|
||||
private readonly List<Guid> _seededMediaContributorIds = [];
|
||||
private readonly List<Guid> _seededFavoriteIds = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetFavoritesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetFavoritesEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavorites_WhenFavoritesOfSeveralKindsExist_ShouldReturnOnlyTheCallersFavorites()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid musicLibraryId = await SeedLibraryAsync(userId, LibraryType.Music);
|
||||
Guid artistId = await SeedArtistAsync(musicLibraryId, "Caller Artist");
|
||||
Guid albumId = await SeedAlbumAsync(musicLibraryId, artistId, "Caller Album");
|
||||
Guid trackId = await SeedTrackAsync(musicLibraryId, albumId, "Caller Track");
|
||||
Guid bookLibraryId = await SeedLibraryAsync(userId, LibraryType.EBook);
|
||||
Guid bookId = await SeedBookAsync(bookLibraryId, "Caller Book", "Caller Author");
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, trackId);
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.Book, bookId);
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherTrackId = await SeedTrackAsync(otherUserId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(PATH);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
PaginatedResponse<FavoriteItemResponse>? favorites = await DeserializeAsync<PaginatedResponse<FavoriteItemResponse>>(response);
|
||||
Assert.NotNull(favorites);
|
||||
Assert.Equal(2, favorites!.Count);
|
||||
Assert.Equal(2, favorites.Data.Count);
|
||||
Assert.Contains(favorites.Data, favorite => favorite.MediaKind == FavoriteMediaKind.MusicTrack && favorite.MediaItemId == trackId);
|
||||
Assert.Contains(favorites.Data, favorite => favorite.MediaKind == FavoriteMediaKind.Book && favorite.MediaItemId == bookId);
|
||||
Assert.DoesNotContain(favorites.Data, favorite => favorite.MediaItemId == otherTrackId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavorites_WhenNoPaginationIsRequested_ShouldReturnEveryFavoriteInOnePageFromTheMostRecent()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid firstFavoriteId = await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, Guid.NewGuid());
|
||||
Guid secondFavoriteId = await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, Guid.NewGuid());
|
||||
Guid thirdFavoriteId = await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, Guid.NewGuid());
|
||||
DateTime now = DateTime.UtcNow;
|
||||
// The auditing interceptor stamps the creation time of an added row, so the favoriting order is restored after the insert.
|
||||
await SetCreatedOnUtcAsync(firstFavoriteId, now.AddMinutes(-30));
|
||||
await SetCreatedOnUtcAsync(secondFavoriteId, now.AddMinutes(-20));
|
||||
await SetCreatedOnUtcAsync(thirdFavoriteId, now.AddMinutes(-10));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(PATH);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
PaginatedResponse<FavoriteItemResponse>? favorites = await DeserializeAsync<PaginatedResponse<FavoriteItemResponse>>(response);
|
||||
Assert.NotNull(favorites);
|
||||
Assert.Equal(1, favorites!.CurrentPage);
|
||||
Assert.Equal(3, favorites.PerPage);
|
||||
Assert.Equal(3, favorites.Count);
|
||||
Assert.Equal(1, favorites.NumberOfPages);
|
||||
FavoriteEntity thirdFavorite = await GetFavoriteAsync(thirdFavoriteId);
|
||||
FavoriteEntity secondFavorite = await GetFavoriteAsync(secondFavoriteId);
|
||||
FavoriteEntity firstFavorite = await GetFavoriteAsync(firstFavoriteId);
|
||||
Assert.Equal(
|
||||
new[] { thirdFavorite.MediaItemId, secondFavorite.MediaItemId, firstFavorite.MediaItemId },
|
||||
favorites.Data.Select(favorite => favorite.MediaItemId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavorites_WhenAPageIsRequested_ShouldReturnDisjointRowsAndThePaginationMetadata()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
for (int index = 0; index < 5; index++)
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, Guid.NewGuid());
|
||||
string firstPageUrl = $"{PATH}?currentPage=1&perPage=2";
|
||||
string secondPageUrl = $"{PATH}?currentPage=2&perPage=2";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage firstPageResponse = await _client.GetAsync(firstPageUrl);
|
||||
HttpResponseMessage secondPageResponse = await _client.GetAsync(secondPageUrl);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, firstPageResponse.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.OK, secondPageResponse.StatusCode);
|
||||
PaginatedResponse<FavoriteItemResponse>? firstPage = await DeserializeAsync<PaginatedResponse<FavoriteItemResponse>>(firstPageResponse);
|
||||
PaginatedResponse<FavoriteItemResponse>? secondPage = await DeserializeAsync<PaginatedResponse<FavoriteItemResponse>>(secondPageResponse);
|
||||
Assert.NotNull(firstPage);
|
||||
Assert.NotNull(secondPage);
|
||||
Assert.Equal(1, firstPage!.CurrentPage);
|
||||
Assert.Equal(2, firstPage.PerPage);
|
||||
Assert.Equal(5, firstPage.Count);
|
||||
Assert.Equal(3, firstPage.NumberOfPages);
|
||||
Assert.Equal(2, firstPage.Data.Count);
|
||||
Assert.Equal(2, secondPage!.CurrentPage);
|
||||
Assert.Equal(2, secondPage.PerPage);
|
||||
Assert.Equal(5, secondPage.Count);
|
||||
Assert.Equal(3, secondPage.NumberOfPages);
|
||||
Assert.Equal(2, secondPage.Data.Count);
|
||||
Assert.Empty(firstPage.Data.Select(favorite => favorite.MediaItemId).Intersect(secondPage.Data.Select(favorite => favorite.MediaItemId)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavorites_WhenAMediaKindIsRequested_ShouldReturnOnlyThatKind()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, trackId);
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.Book, bookId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}?mediaKind=MusicTrack");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<FavoriteItemResponse>? favorites = await DeserializeAsync<PaginatedResponse<FavoriteItemResponse>>(response);
|
||||
Assert.NotNull(favorites);
|
||||
FavoriteItemResponse favorite = Assert.Single(favorites!.Data);
|
||||
Assert.Equal(FavoriteMediaKind.MusicTrack, favorite.MediaKind);
|
||||
Assert.Equal(trackId, favorite.MediaItemId);
|
||||
Assert.Equal(1, favorites.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavorites_WhenAFavoritedTrackExists_ShouldReturnTheAlbumAsTheCollectionAndTheArtistAsTheCreator()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid musicLibraryId = await SeedLibraryAsync(userId, LibraryType.Music);
|
||||
Guid artistId = await SeedArtistAsync(musicLibraryId, "Queen");
|
||||
Guid albumId = await SeedAlbumAsync(musicLibraryId, artistId, "A Night at the Opera");
|
||||
Guid trackId = await SeedTrackAsync(musicLibraryId, albumId, "Bohemian Rhapsody");
|
||||
await SeedAlbumCoverAsync(albumId, "a-night-at-the-opera-cover.jpg");
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, trackId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}?mediaKind=MusicTrack");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<FavoriteItemResponse>? favorites = await DeserializeAsync<PaginatedResponse<FavoriteItemResponse>>(response);
|
||||
Assert.NotNull(favorites);
|
||||
FavoriteItemResponse favorite = Assert.Single(favorites!.Data);
|
||||
Assert.True(favorite.IsAvailable);
|
||||
Assert.Equal(musicLibraryId, favorite.LibraryId);
|
||||
Assert.Equal("Bohemian Rhapsody", favorite.Title);
|
||||
Assert.Equal(albumId, favorite.CollectionId);
|
||||
Assert.Equal("A Night at the Opera", favorite.CollectionTitle);
|
||||
Assert.Equal(artistId, favorite.CreatorId);
|
||||
Assert.Equal("Queen", favorite.CreatorName);
|
||||
Assert.Equal("a-night-at-the-opera-cover.jpg", favorite.CoverPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavorites_WhenAFavoritedBookExists_ShouldReturnTheAuthorAsTheCreatorAndNoCollection()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid bookLibraryId = await SeedLibraryAsync(userId, LibraryType.EBook);
|
||||
Guid bookId = await SeedBookAsync(bookLibraryId, "The Fellowship of the Ring", "J. R. R. Tolkien");
|
||||
Guid authorId = _seededMediaContributorIds[^1];
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.Book, bookId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}?mediaKind=Book");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<FavoriteItemResponse>? favorites = await DeserializeAsync<PaginatedResponse<FavoriteItemResponse>>(response);
|
||||
Assert.NotNull(favorites);
|
||||
FavoriteItemResponse favorite = Assert.Single(favorites!.Data);
|
||||
Assert.True(favorite.IsAvailable);
|
||||
Assert.Equal(bookLibraryId, favorite.LibraryId);
|
||||
Assert.Equal("The Fellowship of the Ring", favorite.Title);
|
||||
Assert.Equal(Guid.Empty, favorite.CollectionId);
|
||||
Assert.Equal(string.Empty, favorite.CollectionTitle);
|
||||
Assert.Equal(authorId, favorite.CreatorId);
|
||||
Assert.Equal("J. R. R. Tolkien", favorite.CreatorName);
|
||||
Assert.Null(favorite.CoverPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavorites_WhenTheFavoritedItemWasDeleted_ShouldReturnTheRowAsUnavailableWithEmptyDisplayFields()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid deletedItemId = Guid.NewGuid();
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, deletedItemId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}?mediaKind=MusicTrack");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<FavoriteItemResponse>? favorites = await DeserializeAsync<PaginatedResponse<FavoriteItemResponse>>(response);
|
||||
Assert.NotNull(favorites);
|
||||
FavoriteItemResponse favorite = Assert.Single(favorites!.Data);
|
||||
Assert.Equal(deletedItemId, favorite.MediaItemId);
|
||||
Assert.False(favorite.IsAvailable);
|
||||
Assert.Equal(Guid.Empty, favorite.LibraryId);
|
||||
Assert.Equal(string.Empty, favorite.Title);
|
||||
Assert.Equal(Guid.Empty, favorite.CollectionId);
|
||||
Assert.Equal(string.Empty, favorite.CollectionTitle);
|
||||
Assert.Equal(Guid.Empty, favorite.CreatorId);
|
||||
Assert.Equal(string.Empty, favorite.CreatorName);
|
||||
Assert.Null(favorite.CoverPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavorites_WhenTheFavoritedItemBelongsToAnInaccessibleLibrary_ShouldStillReturnTheRowAsUnavailable()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherMusicLibraryId = await SeedLibraryAsync(otherUserId, LibraryType.Music);
|
||||
Guid otherArtistId = await SeedArtistAsync(otherMusicLibraryId, "Other Artist");
|
||||
Guid otherAlbumId = await SeedAlbumAsync(otherMusicLibraryId, otherArtistId, "Other Album");
|
||||
Guid otherTrackId = await SeedTrackAsync(otherMusicLibraryId, otherAlbumId, "Other Track");
|
||||
Guid userId = GetCurrentUserId();
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, otherTrackId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}?mediaKind=MusicTrack");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<FavoriteItemResponse>? favorites = await DeserializeAsync<PaginatedResponse<FavoriteItemResponse>>(response);
|
||||
Assert.NotNull(favorites);
|
||||
FavoriteItemResponse favorite = Assert.Single(favorites!.Data);
|
||||
Assert.Equal(otherTrackId, favorite.MediaItemId);
|
||||
Assert.False(favorite.IsAvailable);
|
||||
Assert.Equal(Guid.Empty, favorite.LibraryId);
|
||||
Assert.Equal(string.Empty, favorite.Title);
|
||||
Assert.Equal(Guid.Empty, favorite.CollectionId);
|
||||
Assert.Equal(Guid.Empty, favorite.CreatorId);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("Other Track", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Other Artist", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Other Album", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavorites_WhenTheMediaKindIsNone_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, trackId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}?mediaKind={nameof(FavoriteMediaKind.None)}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal(422, problemDetails.RootElement.GetProperty("status").GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
Assert.Contains("FavoriteMediaKindIsInvalid", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(trackId.ToString(), content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavorites_WhenTheMediaKindIsNotAMemberName_ShouldNotReturnAnyFavorite()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, trackId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}?mediaKind=NotAMediaKind");
|
||||
|
||||
// Assert
|
||||
// The request binds the media kind as an enumeration, so an unparseable value is answered by the generic exception handler
|
||||
// with the sanitized problem before the handler runs, and no favorite is disclosed.
|
||||
Assert.False(response.IsSuccessStatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain(trackId.ToString(), content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library of the given type owned by <paramref name="userId"/> and tracks it for cleanup.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the media library.</param>
|
||||
/// <param name="libraryType">The type of the media library.</param>
|
||||
/// <returns>The Id of the seeded media library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId, LibraryType libraryType)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(
|
||||
id: libraryId, userId: userId, title: $"Library-{Guid.NewGuid():N}", libraryType: libraryType, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededLibraryIds.Add(libraryId);
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an artist of the library identified by <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library the artist belongs to.</param>
|
||||
/// <param name="name">The name of the artist.</param>
|
||||
/// <returns>The Id of the seeded artist.</returns>
|
||||
private async Task<Guid> SeedArtistAsync(Guid libraryId, string name)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(
|
||||
id: artistId, libraryId: libraryId, name: name, includeAlbums: false, includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return artistId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an album of the artist identified by <paramref name="artistId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library the album belongs to.</param>
|
||||
/// <param name="artistId">The Id of the artist the album belongs to.</param>
|
||||
/// <param name="title">The title of the album.</param>
|
||||
/// <returns>The Id of the seeded album.</returns>
|
||||
private async Task<Guid> SeedAlbumAsync(Guid libraryId, Guid artistId, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AlbumEntity album = _albumEntityFixture.Create(
|
||||
id: albumId,
|
||||
artistId: artistId,
|
||||
libraryId: libraryId,
|
||||
title: title,
|
||||
includeTracks: false,
|
||||
includeMetadata: false,
|
||||
includeBarcode: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false);
|
||||
dbContext.Albums.Add(album);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return albumId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a track of the album identified by <paramref name="albumId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library the track belongs to.</param>
|
||||
/// <param name="albumId">The Id of the album the track belongs to.</param>
|
||||
/// <param name="title">The title of the track.</param>
|
||||
/// <returns>The Id of the seeded track.</returns>
|
||||
private async Task<Guid> SeedTrackAsync(Guid libraryId, Guid albumId, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
TrackEntity track = _trackEntityFixture.Create(
|
||||
id: trackId,
|
||||
albumId: albumId,
|
||||
libraryId: libraryId,
|
||||
title: title,
|
||||
includeMetadata: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false);
|
||||
dbContext.Tracks.Add(track);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return trackId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/> with one track, and returns the Id of that track.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the seeded library.</param>
|
||||
/// <returns>The Id of the seeded track.</returns>
|
||||
private async Task<Guid> SeedTrackAsync(Guid userId)
|
||||
{
|
||||
Guid musicLibraryId = await SeedLibraryAsync(userId, LibraryType.Music);
|
||||
Guid artistId = await SeedArtistAsync(musicLibraryId, "Other Artist");
|
||||
Guid albumId = await SeedAlbumAsync(musicLibraryId, artistId, "Other Album");
|
||||
return await SeedTrackAsync(musicLibraryId, albumId, "Other Track");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds the cover artwork of the album identified by <paramref name="albumId"/>.
|
||||
/// </summary>
|
||||
/// <param name="albumId">The Id of the album that owns the artwork.</param>
|
||||
/// <param name="fileName">The file name of the stored cover.</param>
|
||||
private async Task SeedAlbumCoverAsync(Guid albumId, string fileName)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.MusicArtwork.Add(_musicArtworkEntityFixture.Create(
|
||||
ownerType: MusicArtworkOwnerType.Album,
|
||||
ownerId: albumId,
|
||||
artworkType: ArtworkType.Cover,
|
||||
ordinal: 0,
|
||||
fileName: fileName));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a book of the library identified by <paramref name="libraryId"/>, with one author.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library the book belongs to.</param>
|
||||
/// <param name="title">The title of the book.</param>
|
||||
/// <param name="authorName">The display name of the author of the book.</param>
|
||||
/// <returns>The Id of the seeded book.</returns>
|
||||
private async Task<Guid> SeedBookAsync(Guid libraryId, string title, string authorName)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
Guid contributorId = Guid.NewGuid();
|
||||
dbContext.Books.Add(_bookEntityFixture.Create(id: bookId, libraryId: libraryId, title: title, includeMetadata: false));
|
||||
dbContext.MediaContributors.Add(_mediaContributorEntityFixture.Create(id: contributorId, displayName: authorName));
|
||||
dbContext.BookContributors.Add(_bookContributorEntityFixture.Create(bookId: bookId, mediaContributorId: contributorId, role: MediaContributorRole.Author));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededMediaContributorIds.Add(contributorId);
|
||||
return bookId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a favorite of <paramref name="userId"/> and tracks it for cleanup.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the favorite.</param>
|
||||
/// <param name="mediaKind">The kind of the favorited media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the favorited media item.</param>
|
||||
/// <returns>The Id of the seeded favorite.</returns>
|
||||
private async Task<Guid> SeedFavoriteAsync(Guid userId, FavoriteMediaKind mediaKind, Guid mediaItemId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid favoriteId = Guid.NewGuid();
|
||||
dbContext.Favorites.Add(_favoriteEntityFixture.Create(
|
||||
id: favoriteId,
|
||||
userId: userId,
|
||||
mediaKind: mediaKind,
|
||||
mediaItemId: mediaItemId,
|
||||
createdBy: userId,
|
||||
includeUpdatedOnUtc: false,
|
||||
includeUpdatedBy: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededFavoriteIds.Add(favoriteId);
|
||||
return favoriteId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Overrides the creation time of an already stored favorite, so the favoriting order of the test is deterministic.
|
||||
/// </summary>
|
||||
/// <param name="favoriteId">The Id of the favorite to update.</param>
|
||||
/// <param name="createdOnUtc">The creation time to store.</param>
|
||||
private async Task SetCreatedOnUtcAsync(Guid favoriteId, DateTime createdOnUtc)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
await dbContext.Favorites
|
||||
.Where(favorite => favorite.Id == favoriteId)
|
||||
.ExecuteUpdateAsync(setters => setters.SetProperty(favorite => favorite.CreatedOnUtc, createdOnUtc));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads an already stored favorite.
|
||||
/// </summary>
|
||||
/// <param name="favoriteId">The Id of the favorite to read.</param>
|
||||
/// <returns>The stored favorite.</returns>
|
||||
private async Task<FavoriteEntity> GetFavoriteAsync(Guid favoriteId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
return await dbContext.Favorites.AsNoTracking().FirstAsync(favorite => favorite.Id == favoriteId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and tracks it for cleanup.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"otheruser_{Guid.NewGuid()}";
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededUserIds.Add(userId);
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the authenticated test user.</returns>
|
||||
private Guid GetCurrentUserId()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity user = dbContext.Users.First(candidate => candidate.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes the body of <paramref name="response"/> to <typeparamref name="TValue"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="TValue">The type to deserialize the body to.</typeparam>
|
||||
/// <param name="response">The HTTP response to read.</param>
|
||||
/// <returns>The deserialized body.</returns>
|
||||
private async Task<TValue?> DeserializeAsync<TValue>(HttpResponseMessage response)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
return JsonSerializer.Deserialize<TValue>(content, _jsonOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
|
||||
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the data seeded by the test and the API factory test user.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using (IServiceScope scope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<Guid> libraryIds = [.. _seededLibraryIds];
|
||||
List<Guid> albumIds = await dbContext.Albums.Where(album => libraryIds.Contains(album.LibraryId)).Select(album => album.Id).ToListAsync();
|
||||
List<Guid> bookIds = await dbContext.Books.Where(book => libraryIds.Contains(book.LibraryId)).Select(book => book.Id).ToListAsync();
|
||||
dbContext.Favorites.RemoveRange(dbContext.Favorites.Where(favorite => _seededFavoriteIds.Contains(favorite.Id)));
|
||||
dbContext.MusicArtwork.RemoveRange(dbContext.MusicArtwork.Where(artwork => albumIds.Contains(artwork.OwnerId)));
|
||||
dbContext.BookContributors.RemoveRange(dbContext.BookContributors.Where(contributor => bookIds.Contains(contributor.BookId)));
|
||||
dbContext.Tracks.RemoveRange(dbContext.Tracks.Where(track => libraryIds.Contains(track.LibraryId)));
|
||||
dbContext.Albums.RemoveRange(dbContext.Albums.Where(album => libraryIds.Contains(album.LibraryId)));
|
||||
dbContext.Artists.RemoveRange(dbContext.Artists.Where(artist => libraryIds.Contains(artist.LibraryId)));
|
||||
dbContext.Books.RemoveRange(dbContext.Books.Where(book => libraryIds.Contains(book.LibraryId)));
|
||||
dbContext.Libraries.RemoveRange(dbContext.Libraries.Where(library => libraryIds.Contains(library.Id)));
|
||||
dbContext.MediaContributors.RemoveRange(dbContext.MediaContributors.Where(contributor => _seededMediaContributorIds.Contains(contributor.Id)));
|
||||
dbContext.Users.RemoveRange(dbContext.Users.Where(user => _seededUserIds.Contains(user.Id)));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+292
@@ -0,0 +1,292 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Favorites.RemoveFavorite;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Favorites.RemoveFavorite;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="RemoveFavoriteEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RemoveFavoriteEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly FavoriteEntityFixture _favoriteEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly List<Guid> _seededUserIds = [];
|
||||
private readonly List<Guid> _seededFavoriteIds = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RemoveFavoriteEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public RemoveFavoriteEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveFavorite_WhenTheFavoriteExists_ShouldDeleteTheCallersRowAndReturnOk()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, mediaItemId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/users/me/favorites/MusicTrack/{mediaItemId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.False(await dbContext.Favorites.AnyAsync(favorite => favorite.UserId == userId && favorite.MediaItemId == mediaItemId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveFavorite_WhenTheFavoriteDoesNotExist_ShouldReturnOkAndChangeNothing()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid otherMediaItemId = Guid.NewGuid();
|
||||
Guid seededFavoriteId = await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, otherMediaItemId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/users/me/favorites/MusicTrack/{Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.Equal(1, await dbContext.Favorites.CountAsync(favorite => favorite.UserId == userId));
|
||||
Assert.True(await dbContext.Favorites.AnyAsync(favorite => favorite.Id == seededFavoriteId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveFavorite_WhenAnotherUserFavoritedTheSameItem_ShouldRemoveOnlyTheCallersRow()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, mediaItemId);
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherFavoriteId = await SeedFavoriteAsync(otherUserId, FavoriteMediaKind.MusicTrack, mediaItemId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/users/me/favorites/MusicTrack/{mediaItemId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.False(await dbContext.Favorites.AnyAsync(favorite => favorite.UserId == userId));
|
||||
FavoriteEntity otherFavorite = await dbContext.Favorites.AsNoTracking().FirstAsync(favorite => favorite.Id == otherFavoriteId);
|
||||
Assert.Equal(otherUserId, otherFavorite.UserId);
|
||||
Assert.Equal(mediaItemId, otherFavorite.MediaItemId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveFavorite_WhenTheMediaKindIsNone_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, mediaItemId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/users/me/favorites/{nameof(FavoriteMediaKind.None)}/{mediaItemId}");
|
||||
|
||||
// Assert
|
||||
await AssertValidationProblemAsync(response, "FavoriteMediaKindIsInvalid");
|
||||
AssertCacheHeaders(response);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.True(await dbContext.Favorites.AnyAsync(favorite => favorite.UserId == userId && favorite.MediaItemId == mediaItemId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveFavorite_WhenTheMediaKindIsNotAName_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, mediaItemId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/users/me/favorites/NotAMediaKind/{mediaItemId}");
|
||||
|
||||
// Assert
|
||||
await AssertValidationProblemAsync(response, "FavoriteMediaKindIsInvalid");
|
||||
AssertCacheHeaders(response);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.True(await dbContext.Favorites.AnyAsync(favorite => favorite.UserId == userId && favorite.MediaItemId == mediaItemId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveFavorite_WhenTheMediaItemIdIsNotAGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
await SeedFavoriteAsync(userId, FavoriteMediaKind.MusicTrack, mediaItemId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync("/api/v1/users/me/favorites/MusicTrack/not-a-guid");
|
||||
|
||||
// Assert
|
||||
await AssertValidationProblemAsync(response, "FavoriteMediaItemIdCannotBeEmpty");
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.True(await dbContext.Favorites.AnyAsync(favorite => favorite.UserId == userId && favorite.MediaItemId == mediaItemId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveFavorite_WhenBothRouteValuesAreInvalid_ShouldReturnBothValidationProblems()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/users/me/favorites/NotAMediaKind/{Guid.Empty}");
|
||||
|
||||
// Assert
|
||||
await AssertValidationProblemAsync(response, "FavoriteMediaKindIsInvalid", "FavoriteMediaItemIdCannotBeEmpty");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a favorite of <paramref name="userId"/> and tracks it for cleanup.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the favorite.</param>
|
||||
/// <param name="mediaKind">The kind of the favorited media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the favorited media item.</param>
|
||||
/// <returns>The Id of the seeded favorite.</returns>
|
||||
private async Task<Guid> SeedFavoriteAsync(Guid userId, FavoriteMediaKind mediaKind, Guid mediaItemId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid favoriteId = Guid.NewGuid();
|
||||
dbContext.Favorites.Add(_favoriteEntityFixture.Create(
|
||||
id: favoriteId,
|
||||
userId: userId,
|
||||
mediaKind: mediaKind,
|
||||
mediaItemId: mediaItemId,
|
||||
createdBy: userId,
|
||||
includeUpdatedOnUtc: false,
|
||||
includeUpdatedBy: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededFavoriteIds.Add(favoriteId);
|
||||
return favoriteId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and tracks it for cleanup.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"otheruser_{Guid.NewGuid()}";
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededUserIds.Add(userId);
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the authenticated test user.</returns>
|
||||
private Guid GetCurrentUserId()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity user = dbContext.Users.First(candidate => candidate.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
|
||||
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is a validation problem details document carrying the expected error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present, in order.</param>
|
||||
private static async Task AssertValidationProblemAsync(HttpResponseMessage response, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(422, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>();
|
||||
Assert.NotNull(errors);
|
||||
Assert.Equal(expectedErrorCodes, errors!["General.Validation"]);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the data seeded by the test and the API factory test user.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using (IServiceScope scope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Favorites.RemoveRange(dbContext.Favorites.Where(favorite => _seededFavoriteIds.Contains(favorite.Id)));
|
||||
dbContext.Users.RemoveRange(dbContext.Users.Where(user => _seededUserIds.Contains(user.Id)));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+530
@@ -0,0 +1,530 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Playlists;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Playlists;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.Playlists;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Playlists.GetPlaylist;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Playlists.GetPlaylist;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetPlaylistEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPlaylistEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private const string PATH = "/api/v1/users/me/playlists";
|
||||
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
|
||||
private readonly PlaylistEntityFixture _playlistEntityFixture = new();
|
||||
private readonly PlaylistEntryEntityFixture _playlistEntryEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly List<Guid> _seededLibraryIds = [];
|
||||
private readonly List<Guid> _seededUserIds = [];
|
||||
private readonly List<Guid> _seededPlaylistIds = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPlaylistEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetPlaylistEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaylist_WhenThePlaylistExists_ShouldReturnItWithItsPageOfEntriesAndDensePositions()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid musicLibraryId = await SeedLibraryAsync(userId);
|
||||
Guid artistId = await SeedArtistAsync(musicLibraryId, "Queen");
|
||||
Guid albumId = await SeedAlbumAsync(musicLibraryId, artistId, "Innuendo");
|
||||
Guid firstTrackId = await SeedTrackAsync(musicLibraryId, albumId, "Innuendo", 393);
|
||||
Guid secondTrackId = await SeedTrackAsync(musicLibraryId, albumId, "The Show Must Go On", 262);
|
||||
await SeedAlbumCoverAsync(albumId, "innuendo-cover.jpg");
|
||||
Guid deletedTrackId = Guid.NewGuid();
|
||||
Guid playlistId = await SeedPlaylistAsync(userId, "Evening listening");
|
||||
// The stored order keys are sparse, so the response must expose dense zero based display positions instead.
|
||||
await SeedPlaylistEntryAsync(playlistId, firstTrackId, 0);
|
||||
await SeedPlaylistEntryAsync(playlistId, secondTrackId, 1_000_000_000L);
|
||||
await SeedPlaylistEntryAsync(playlistId, deletedTrackId, 2_000_000_000L);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}/{playlistId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
PlaylistResponse? playlist = await DeserializeAsync<PlaylistResponse>(response);
|
||||
Assert.NotNull(playlist);
|
||||
Assert.Equal(playlistId, playlist!.Id);
|
||||
Assert.Equal("Evening listening", playlist.Name);
|
||||
Assert.Equal(PlaylistType.Music, playlist.Type);
|
||||
Assert.Equal(3, playlist.Entries.Count);
|
||||
Assert.Equal(1, playlist.Entries.CurrentPage);
|
||||
Assert.Equal(3, playlist.Entries.PerPage);
|
||||
Assert.Equal(1, playlist.Entries.NumberOfPages);
|
||||
Assert.Equal([0, 1, 2], playlist.Entries.Data.Select(entry => entry.Position));
|
||||
|
||||
PlaylistEntryResponse firstEntry = playlist.Entries.Data[0];
|
||||
Assert.Equal(firstTrackId, firstEntry.MediaItemId);
|
||||
Assert.Equal(PlaylistMediaItemType.MusicTrack, firstEntry.MediaItemType);
|
||||
Assert.Equal(musicLibraryId, firstEntry.LibraryId);
|
||||
Assert.Equal("Innuendo", firstEntry.MediaItemTitle);
|
||||
Assert.Equal(albumId, firstEntry.CollectionId);
|
||||
Assert.Equal("Innuendo", firstEntry.CollectionTitle);
|
||||
Assert.Equal(artistId, firstEntry.CreatorId);
|
||||
Assert.Equal("Queen", firstEntry.CreatorName);
|
||||
Assert.Equal(393, firstEntry.DurationInSeconds);
|
||||
Assert.Equal("innuendo-cover.jpg", firstEntry.CoverPath);
|
||||
|
||||
PlaylistEntryResponse deletedEntry = playlist.Entries.Data[2];
|
||||
Assert.Equal(deletedTrackId, deletedEntry.MediaItemId);
|
||||
Assert.Equal(Guid.Empty, deletedEntry.LibraryId);
|
||||
Assert.Equal(string.Empty, deletedEntry.MediaItemTitle);
|
||||
Assert.Equal(Guid.Empty, deletedEntry.CollectionId);
|
||||
Assert.Equal(Guid.Empty, deletedEntry.CreatorId);
|
||||
Assert.Equal(0, deletedEntry.DurationInSeconds);
|
||||
Assert.Null(deletedEntry.CoverPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaylist_WhenThePlaylistIsEmpty_ShouldReturnAnEmptyPage()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid playlistId = await SeedPlaylistAsync(userId, "Nothing yet");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}/{playlistId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PlaylistResponse? playlist = await DeserializeAsync<PlaylistResponse>(response);
|
||||
Assert.NotNull(playlist);
|
||||
Assert.Empty(playlist!.Entries.Data);
|
||||
Assert.Equal(0, playlist.Entries.Count);
|
||||
Assert.Equal(1, playlist.Entries.CurrentPage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaylist_WhenNoPaginationIsRequested_ShouldReturnEveryEntryInOnePage()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid playlistId = await SeedPlaylistAsync(userId, "Every entry");
|
||||
for (int index = 0; index < 4; index++)
|
||||
await SeedPlaylistEntryAsync(playlistId, Guid.NewGuid(), index * 1_000_000_000L);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}/{playlistId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PlaylistResponse? playlist = await DeserializeAsync<PlaylistResponse>(response);
|
||||
Assert.NotNull(playlist);
|
||||
Assert.Equal(1, playlist!.Entries.CurrentPage);
|
||||
Assert.Equal(4, playlist.Entries.PerPage);
|
||||
Assert.Equal(4, playlist.Entries.Count);
|
||||
Assert.Equal(1, playlist.Entries.NumberOfPages);
|
||||
Assert.Equal([0, 1, 2, 3], playlist.Entries.Data.Select(entry => entry.Position));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaylist_WhenAPageIsRequested_ShouldReturnOnlyThatPageWithThePaginationMetadata()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid playlistId = await SeedPlaylistAsync(userId, "Paged playlist");
|
||||
for (int index = 0; index < 3; index++)
|
||||
await SeedPlaylistEntryAsync(playlistId, Guid.NewGuid(), index * 1_000_000_000L);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}/{playlistId}?currentPage=2&perPage=2");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
PlaylistResponse? playlist = await DeserializeAsync<PlaylistResponse>(response);
|
||||
Assert.NotNull(playlist);
|
||||
Assert.Equal(2, playlist!.Entries.CurrentPage);
|
||||
Assert.Equal(2, playlist.Entries.PerPage);
|
||||
Assert.Equal(3, playlist.Entries.Count);
|
||||
Assert.Equal(2, playlist.Entries.NumberOfPages);
|
||||
PlaylistEntryResponse entry = Assert.Single(playlist.Entries.Data);
|
||||
// The display position stays dense across pages, so the only entry of the second page is the third entry of the playlist.
|
||||
Assert.Equal(2, entry.Position);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaylist_WhenThePlaylistBelongsToAnotherUser_ShouldReturnNotFound()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherPlaylistId = await SeedPlaylistAsync(otherUserId, "Someone else's playlist");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}/{otherPlaylistId}");
|
||||
|
||||
// Assert
|
||||
await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "PlaylistNotFound", $"{PATH}/{otherPlaylistId}");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaylist_WhenThePlaylistDoesNotExist_ShouldReturnNotFound()
|
||||
{
|
||||
// Arrange
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}/{playlistId}");
|
||||
|
||||
// Assert
|
||||
await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "PlaylistNotFound", $"{PATH}/{playlistId}");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaylist_WhenThePlaylistIdIsNotAGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}/not-a-guid");
|
||||
|
||||
// Assert
|
||||
await AssertValidationProblemAsync(response, $"{PATH}/not-a-guid", "PlaylistIdCannotBeEmpty");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaylist_WhenThePlaylistIdIsEmpty_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}/{Guid.Empty}");
|
||||
|
||||
// Assert
|
||||
await AssertValidationProblemAsync(response, $"{PATH}/{Guid.Empty}", "PlaylistIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library owned by <paramref name="userId"/> and tracks it for cleanup.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the media library.</param>
|
||||
/// <returns>The Id of the seeded media library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(
|
||||
id: libraryId, userId: userId, title: $"Library-{Guid.NewGuid():N}", libraryType: LibraryType.Music, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededLibraryIds.Add(libraryId);
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an artist of the library identified by <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library the artist belongs to.</param>
|
||||
/// <param name="name">The name of the artist.</param>
|
||||
/// <returns>The Id of the seeded artist.</returns>
|
||||
private async Task<Guid> SeedArtistAsync(Guid libraryId, string name)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(
|
||||
id: artistId, libraryId: libraryId, name: name, includeAlbums: false, includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return artistId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an album of the artist identified by <paramref name="artistId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library the album belongs to.</param>
|
||||
/// <param name="artistId">The Id of the artist the album belongs to.</param>
|
||||
/// <param name="title">The title of the album.</param>
|
||||
/// <returns>The Id of the seeded album.</returns>
|
||||
private async Task<Guid> SeedAlbumAsync(Guid libraryId, Guid artistId, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AlbumEntity album = _albumEntityFixture.Create(
|
||||
id: albumId,
|
||||
artistId: artistId,
|
||||
libraryId: libraryId,
|
||||
title: title,
|
||||
includeTracks: false,
|
||||
includeMetadata: false,
|
||||
includeBarcode: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false);
|
||||
dbContext.Albums.Add(album);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return albumId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a track of the album identified by <paramref name="albumId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library the track belongs to.</param>
|
||||
/// <param name="albumId">The Id of the album the track belongs to.</param>
|
||||
/// <param name="title">The title of the track.</param>
|
||||
/// <param name="durationInSeconds">The duration of the track in seconds.</param>
|
||||
/// <returns>The Id of the seeded track.</returns>
|
||||
private async Task<Guid> SeedTrackAsync(Guid libraryId, Guid albumId, string title, int durationInSeconds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
TrackEntity track = _trackEntityFixture.Create(
|
||||
id: trackId,
|
||||
albumId: albumId,
|
||||
libraryId: libraryId,
|
||||
title: title,
|
||||
includeMetadata: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false);
|
||||
track.DurationInSeconds = durationInSeconds;
|
||||
dbContext.Tracks.Add(track);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return trackId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds the cover artwork of the album identified by <paramref name="albumId"/>.
|
||||
/// </summary>
|
||||
/// <param name="albumId">The Id of the album that owns the artwork.</param>
|
||||
/// <param name="fileName">The file name of the stored cover.</param>
|
||||
private async Task SeedAlbumCoverAsync(Guid albumId, string fileName)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.MusicArtwork.Add(_musicArtworkEntityFixture.Create(
|
||||
ownerType: MusicArtworkOwnerType.Album,
|
||||
ownerId: albumId,
|
||||
artworkType: ArtworkType.Cover,
|
||||
ordinal: 0,
|
||||
fileName: fileName));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a playlist of <paramref name="userId"/> and tracks it for cleanup.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the playlist.</param>
|
||||
/// <param name="name">The name of the playlist.</param>
|
||||
/// <returns>The Id of the seeded playlist.</returns>
|
||||
private async Task<Guid> SeedPlaylistAsync(Guid userId, string name)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
dbContext.Playlists.Add(_playlistEntityFixture.Create(
|
||||
id: playlistId,
|
||||
userId: userId,
|
||||
name: name,
|
||||
type: PlaylistType.Music,
|
||||
entryCount: 0,
|
||||
version: 0,
|
||||
createdBy: userId));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededPlaylistIds.Add(playlistId);
|
||||
return playlistId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an entry of the playlist identified by <paramref name="playlistId"/>.
|
||||
/// </summary>
|
||||
/// <param name="playlistId">The Id of the playlist the entry belongs to.</param>
|
||||
/// <param name="mediaItemId">The Id of the referenced media item.</param>
|
||||
/// <param name="position">The sparse order key of the entry.</param>
|
||||
private async Task SeedPlaylistEntryAsync(Guid playlistId, Guid mediaItemId, long position)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.PlaylistEntries.Add(_playlistEntryEntityFixture.Create(
|
||||
playlistId: playlistId,
|
||||
mediaItemId: mediaItemId,
|
||||
mediaItemType: PlaylistMediaItemType.MusicTrack,
|
||||
position: position));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and tracks it for cleanup.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"otheruser_{Guid.NewGuid()}";
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededUserIds.Add(userId);
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the authenticated test user.</returns>
|
||||
private Guid GetCurrentUserId()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity user = dbContext.Users.First(candidate => candidate.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes the body of <paramref name="response"/> to <typeparamref name="TValue"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="TValue">The type to deserialize the body to.</typeparam>
|
||||
/// <param name="response">The HTTP response to read.</param>
|
||||
/// <returns>The deserialized body.</returns>
|
||||
private async Task<TValue?> DeserializeAsync<TValue>(HttpResponseMessage response)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
return JsonSerializer.Deserialize<TValue>(content, _jsonOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
|
||||
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is a problem details document with the expected status, title and detail.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedStatus">The expected HTTP status.</param>
|
||||
/// <param name="expectedTitle">The expected problem title.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private static async Task AssertProblemAsync(HttpResponseMessage response, HttpStatusCode expectedStatus, string expectedTitle, string expectedDetail, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(expectedStatus, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)expectedStatus, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal(expectedTitle, problemDetails["title"].GetString());
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is a validation problem details document carrying the expected error code.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCode">The expected validation error code.</param>
|
||||
private static async Task AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstance, string expectedErrorCode)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(422, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>();
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains(expectedErrorCode, errors!["General.Validation"]);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the data seeded by the test and the API factory test user.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using (IServiceScope scope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<Guid> libraryIds = [.. _seededLibraryIds];
|
||||
List<Guid> playlistIds = [.. _seededPlaylistIds];
|
||||
List<Guid> albumIds = await dbContext.Albums.Where(album => libraryIds.Contains(album.LibraryId)).Select(album => album.Id).ToListAsync();
|
||||
dbContext.PlaylistEntries.RemoveRange(dbContext.PlaylistEntries.Where(entry => playlistIds.Contains(entry.PlaylistId)));
|
||||
dbContext.Playlists.RemoveRange(dbContext.Playlists.Where(playlist => playlistIds.Contains(playlist.Id)));
|
||||
dbContext.MusicArtwork.RemoveRange(dbContext.MusicArtwork.Where(artwork => albumIds.Contains(artwork.OwnerId)));
|
||||
dbContext.Tracks.RemoveRange(dbContext.Tracks.Where(track => libraryIds.Contains(track.LibraryId)));
|
||||
dbContext.Albums.RemoveRange(dbContext.Albums.Where(album => libraryIds.Contains(album.LibraryId)));
|
||||
dbContext.Artists.RemoveRange(dbContext.Artists.Where(artist => libraryIds.Contains(artist.LibraryId)));
|
||||
dbContext.Libraries.RemoveRange(dbContext.Libraries.Where(library => libraryIds.Contains(library.Id)));
|
||||
dbContext.Users.RemoveRange(dbContext.Users.Where(user => _seededUserIds.Contains(user.Id)));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Favorites;
|
||||
using Lumina.Presentation.Web.Common.Enums.Favorites;
|
||||
using Lumina.Presentation.Web.Common.Requests.Favorites;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Favorites.AddFavorite;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Favorites;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Favorites.AddFavorite;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="AddFavoriteEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddFavoriteEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string WEB_ROUTE = "/en-us/favorites/api-add-favorite";
|
||||
private const string UPSTREAM_ENDPOINT = "users/me/favorites";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly FavoriteDtoFixture _favoriteDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddFavoriteEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public AddFavoriteEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddFavorite_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardTheFavoriteAndReturnIt()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
FavoriteDto expectedFavorite = _favoriteDtoFixture.Create(
|
||||
mediaKind: FavoriteMediaKind.MusicTrack,
|
||||
mediaItemId: mediaItemId);
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse(UPSTREAM_ENDPOINT, expectedFavorite);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage addRequest = CreateAddRequest(FavoriteMediaKind.MusicTrack, mediaItemId, webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(addRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
JsonElement data = json.RootElement.GetProperty("data");
|
||||
Assert.Equal(expectedFavorite.Id, data.GetProperty("id").GetGuid());
|
||||
Assert.Equal(nameof(FavoriteMediaKind.MusicTrack), data.GetProperty("mediaKind").GetString());
|
||||
Assert.Equal(mediaItemId, data.GetProperty("mediaItemId").GetGuid());
|
||||
Assert.Equal(expectedFavorite.FavoritedOnUtc, data.GetProperty("favoritedOnUtc").GetDateTime());
|
||||
List<(string Endpoint, object? Data)> addRequests = GetAddRequests();
|
||||
(string Endpoint, object? Data) addRequestCall = Assert.Single(addRequests);
|
||||
Assert.Equal(UPSTREAM_ENDPOINT, addRequestCall.Endpoint);
|
||||
AddFavoriteRequest forwardedPayload = Assert.IsType<AddFavoriteRequest>(addRequestCall.Data);
|
||||
Assert.Equal(FavoriteMediaKind.MusicTrack, forwardedPayload.MediaKind);
|
||||
Assert.Equal(mediaItemId, forwardedPayload.MediaItemId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the add favorite requests that were sent upstream, excluding the login request performed to authenticate the test client.
|
||||
/// </summary>
|
||||
/// <returns>The list of upstream add favorite requests that were sent.</returns>
|
||||
private List<(string Endpoint, object? Data)> GetAddRequests()
|
||||
{
|
||||
return [.. _apiFactory.ApiClientStub.PostRequests
|
||||
.Where(postRequest => postRequest.Endpoint == UPSTREAM_ENDPOINT)];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the add favorite request for the specified media item.
|
||||
/// </summary>
|
||||
/// <param name="mediaKind">The kind of the media item to favorite.</param>
|
||||
/// <param name="mediaItemId">The Id of the media item to favorite.</param>
|
||||
/// <param name="antiforgeryToken">The antiforgery token to include in the request.</param>
|
||||
/// <returns>The configured add favorite request.</returns>
|
||||
private static HttpRequestMessage CreateAddRequest(FavoriteMediaKind mediaKind, Guid mediaItemId, string antiforgeryToken)
|
||||
{
|
||||
string payload = $"{{\"mediaKind\":\"{mediaKind}\",\"mediaItemId\":\"{mediaItemId}\"}}";
|
||||
HttpRequestMessage addRequest = new(HttpMethod.Post, WEB_ROUTE)
|
||||
{
|
||||
Content = new StringContent(payload, Encoding.UTF8, "application/json")
|
||||
};
|
||||
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
|
||||
addRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
addRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
addRequest.Headers.Add("RequestVerificationToken", antiforgeryToken);
|
||||
return addRequest;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Favorites;
|
||||
using Lumina.Presentation.Web.Common.Enums.Favorites;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Favorites.GetFavoriteStatus;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Favorites;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Favorites.GetFavoriteStatus;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetFavoriteStatusEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetFavoriteStatusEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string WEB_ROUTE = "/en-us/favorites/api-get-favorite-status";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly FavoriteStatusDtoFixture _favoriteStatusDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetFavoriteStatusEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetFavoriteStatusEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavoriteStatus_WhenCalledWithMediaKindAndIds_ShouldForwardThemAndSurfaceTheFavoritedIds()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
List<Guid> mediaItemIds = [Guid.NewGuid(), Guid.NewGuid()];
|
||||
string expectedUpstreamEndpoint = $"users/me/favorites/status?mediaKind=MusicTrack&mediaItemIds={mediaItemIds[0]}&mediaItemIds={mediaItemIds[1]}";
|
||||
FavoriteStatusDto expectedStatus = _favoriteStatusDtoFixture.Create(favoritedMediaItemIds: [mediaItemIds[1]]);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(expectedUpstreamEndpoint, expectedStatus);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(
|
||||
$"{WEB_ROUTE}?mediaKind=MusicTrack&mediaItemIds={mediaItemIds[0]}&mediaItemIds={mediaItemIds[1]}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
List<Guid> favoritedIds = [.. json.RootElement.GetProperty("data").GetProperty("favoritedMediaItemIds").EnumerateArray().Select(element => element.GetGuid())];
|
||||
Assert.Equal(expectedStatus.FavoritedMediaItemIds, favoritedIds);
|
||||
Assert.Equal([expectedUpstreamEndpoint], GetFavoriteStatusEndpointCalls());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavoriteStatus_WhenMediaKindAndIdsAreOmitted_ShouldForwardTheBareStatusRoute()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
const string EXPECTED_UPSTREAM_ENDPOINT = "users/me/favorites/status";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(EXPECTED_UPSTREAM_ENDPOINT, _favoriteStatusDtoFixture.Create());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(WEB_ROUTE);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal([EXPECTED_UPSTREAM_ENDPOINT], GetFavoriteStatusEndpointCalls());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the favorite status endpoints that were called upstream, excluding the requests made to authenticate the test client.
|
||||
/// </summary>
|
||||
/// <returns>The list of upstream favorite status endpoints that were called.</returns>
|
||||
private List<string> GetFavoriteStatusEndpointCalls()
|
||||
{
|
||||
return [.. _apiFactory.ApiClientStub.GetEndpointsCalled
|
||||
.Where(endpoint => endpoint.StartsWith("users/me/favorites/status", StringComparison.Ordinal))];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
+185
@@ -0,0 +1,185 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.DTO.Favorites;
|
||||
using Lumina.Presentation.Web.Common.Enums.Favorites;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Favorites.GetFavorites;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Favorites;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Favorites.GetFavorites;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetFavoritesEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetFavoritesEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string WEB_ROUTE = "/en-us/favorites/api-get-favorites";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly PaginatedDtoFixture<FavoriteItemDto> _paginatedDtoFixture = new();
|
||||
private readonly FavoriteItemDtoFixture _favoriteItemDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetFavoritesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetFavoritesEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavorites_WhenCalledByAuthenticatedUser_ShouldSurfaceThePaginatedFavoritesUnchanged()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
FavoriteItemDto expectedItem = _favoriteItemDtoFixture.Create(
|
||||
mediaKind: FavoriteMediaKind.MusicTrack,
|
||||
isAvailable: true,
|
||||
title: "Time",
|
||||
collectionTitle: "The Dark Side of the Moon",
|
||||
creatorName: "Pink Floyd",
|
||||
coverPath: "covers/dark-side-of-the-moon.jpg");
|
||||
PaginatedDto<FavoriteItemDto> expectedPage = _paginatedDtoFixture.Create(
|
||||
data: [expectedItem],
|
||||
currentPage: 1,
|
||||
perPage: 200,
|
||||
count: 1,
|
||||
numberOfPages: 1);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse("users/me/favorites?currentPage=1&perPage=200", expectedPage);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(WEB_ROUTE);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
JsonElement data = json.RootElement.GetProperty("data");
|
||||
Assert.Equal(1, data.GetProperty("currentPage").GetInt32());
|
||||
Assert.Equal(200, data.GetProperty("perPage").GetInt32());
|
||||
Assert.Equal(1, data.GetProperty("count").GetInt32());
|
||||
Assert.Equal(1, data.GetProperty("numberOfPages").GetInt32());
|
||||
JsonElement item = Assert.Single(data.GetProperty("data").EnumerateArray());
|
||||
Assert.Equal(nameof(FavoriteMediaKind.MusicTrack), item.GetProperty("mediaKind").GetString());
|
||||
Assert.Equal(expectedItem.MediaItemId, item.GetProperty("mediaItemId").GetGuid());
|
||||
Assert.True(item.GetProperty("isAvailable").GetBoolean());
|
||||
Assert.Equal(expectedItem.LibraryId, item.GetProperty("libraryId").GetGuid());
|
||||
Assert.Equal(expectedItem.Title, item.GetProperty("title").GetString());
|
||||
Assert.Equal(expectedItem.CollectionId, item.GetProperty("collectionId").GetGuid());
|
||||
Assert.Equal(expectedItem.CollectionTitle, item.GetProperty("collectionTitle").GetString());
|
||||
Assert.Equal(expectedItem.CreatorId, item.GetProperty("creatorId").GetGuid());
|
||||
Assert.Equal(expectedItem.CreatorName, item.GetProperty("creatorName").GetString());
|
||||
Assert.Equal(expectedItem.CoverPath, item.GetProperty("coverPath").GetString());
|
||||
Assert.Equal(["users/me/favorites?currentPage=1&perPage=200"], GetFavoritesEndpointCalls());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("", "users/me/favorites?currentPage=1&perPage=200")] // neither the page nor the size is supplied
|
||||
[InlineData("?currentPage=3", "users/me/favorites?currentPage=3&perPage=200")] // only the page is supplied
|
||||
[InlineData("?perPage=25", "users/me/favorites?currentPage=1&perPage=25")] // only the size is supplied
|
||||
[InlineData("?currentPage=2&perPage=50", "users/me/favorites?currentPage=2&perPage=50")] // both the page and the size are supplied
|
||||
public async Task GetFavorites_WhenCalledWithPagination_ShouldForwardTheDocumentedUpstreamUrl(string queryString, string expectedUpstreamEndpoint)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(expectedUpstreamEndpoint, _paginatedDtoFixture.Create());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"{WEB_ROUTE}{queryString}");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal([expectedUpstreamEndpoint], GetFavoritesEndpointCalls());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavorites_WhenMediaKindIsSupplied_ShouldAppendItToTheUpstreamUrl()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
const string EXPECTED_UPSTREAM_ENDPOINT = "users/me/favorites?currentPage=1&perPage=200&mediaKind=MusicTrack";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(EXPECTED_UPSTREAM_ENDPOINT, _paginatedDtoFixture.Create());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"{WEB_ROUTE}?mediaKind=MusicTrack");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal([EXPECTED_UPSTREAM_ENDPOINT], GetFavoritesEndpointCalls());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavorites_WhenMediaItemIsUnavailable_ShouldPassTheEmptyDisplayDataThroughUnchanged()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
FavoriteItemDto unavailableItem = _favoriteItemDtoFixture.Create(
|
||||
mediaKind: FavoriteMediaKind.Book,
|
||||
isAvailable: false,
|
||||
libraryId: Guid.Empty,
|
||||
title: string.Empty,
|
||||
collectionId: Guid.Empty,
|
||||
collectionTitle: string.Empty,
|
||||
creatorId: Guid.Empty,
|
||||
creatorName: string.Empty,
|
||||
includeCoverPath: false);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(
|
||||
"users/me/favorites?currentPage=1&perPage=200",
|
||||
_paginatedDtoFixture.Create(data: [unavailableItem], currentPage: 1, perPage: 200, count: 1, numberOfPages: 1));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(WEB_ROUTE);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
JsonElement item = Assert.Single(json.RootElement.GetProperty("data").GetProperty("data").EnumerateArray());
|
||||
Assert.False(item.GetProperty("isAvailable").GetBoolean());
|
||||
Assert.Equal(Guid.Empty, item.GetProperty("libraryId").GetGuid());
|
||||
Assert.Equal(string.Empty, item.GetProperty("title").GetString());
|
||||
Assert.Equal(Guid.Empty, item.GetProperty("collectionId").GetGuid());
|
||||
Assert.Equal(string.Empty, item.GetProperty("collectionTitle").GetString());
|
||||
Assert.Equal(Guid.Empty, item.GetProperty("creatorId").GetGuid());
|
||||
Assert.Equal(string.Empty, item.GetProperty("creatorName").GetString());
|
||||
Assert.Equal(JsonValueKind.Null, item.GetProperty("coverPath").ValueKind);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the favorites endpoints that were called upstream, excluding the requests made to authenticate the test client.
|
||||
/// </summary>
|
||||
/// <returns>The list of upstream favorites endpoints that were called.</returns>
|
||||
private List<string> GetFavoritesEndpointCalls()
|
||||
{
|
||||
return [.. _apiFactory.ApiClientStub.GetEndpointsCalled
|
||||
.Where(endpoint => endpoint.StartsWith("users/me/favorites", StringComparison.Ordinal))];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Favorites.Index;
|
||||
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;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Favorites.Index;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="FavoritesIndexViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FavoritesIndexViewEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string WEB_ROUTE = "/en-us/favorites";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="FavoritesIndexViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public FavoritesIndexViewEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FavoritesIndexView_WhenCalledByAuthenticatedUser_ShouldRenderTheFavoritesPage()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(WEB_ROUTE);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType);
|
||||
Assert.Contains("favorites-container", content, StringComparison.Ordinal);
|
||||
Assert.Contains("favorites-kind-filter", content, StringComparison.Ordinal);
|
||||
Assert.Contains("no-favorites", content, StringComparison.Ordinal);
|
||||
Assert.True(response.Headers.CacheControl?.Private);
|
||||
Assert.True(response.Headers.CacheControl?.NoStore);
|
||||
Assert.Contains("no-store", string.Join(", ", response.Headers.GetValues("Cache-Control")), StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains("Cookie", response.Headers.Vary);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FavoritesIndexView_WhenCalledByAuthenticatedUser_ShouldRenderTheAntiforgeryTokenAndTheLocalizedStrings()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(WEB_ROUTE);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Contains("__RequestVerificationToken", content, StringComparison.Ordinal);
|
||||
Assert.Contains("Favorites", content, StringComparison.Ordinal);
|
||||
Assert.Contains("You have no favorites yet.", content, StringComparison.Ordinal);
|
||||
Assert.Contains("Load more", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Enums.Favorites;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Favorites.RemoveFavorite;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Favorites.RemoveFavorite;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="RemoveFavoriteEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RemoveFavoriteEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RemoveFavoriteEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public RemoveFavoriteEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveFavorite_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardTheNormalizedDeleteAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
string expectedUpstreamEndpoint = $"users/me/favorites/MusicTrack/{mediaItemId}";
|
||||
_apiFactory.ApiClientStub.RegisterDeleteSuccess(expectedUpstreamEndpoint);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage removeRequest = CreateRemoveRequest(nameof(FavoriteMediaKind.MusicTrack), mediaItemId.ToString(), webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(removeRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal([expectedUpstreamEndpoint], GetRemoveEndpointCalls());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveFavorite_WhenMediaKindAndIdAreCasedDifferently_ShouldForwardTheCanonicalValuesOnly()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid mediaItemId = Guid.Parse("ABCDEFAB-CDEF-ABCD-EFAB-CDEFABCDEFAB");
|
||||
string expectedUpstreamEndpoint = $"users/me/favorites/MusicTrack/{mediaItemId}";
|
||||
_apiFactory.ApiClientStub.RegisterDeleteSuccess(expectedUpstreamEndpoint);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage removeRequest = CreateRemoveRequest("musictrack", mediaItemId.ToString().ToUpperInvariant(), webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(removeRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
List<string> removeEndpoints = GetRemoveEndpointCalls();
|
||||
Assert.Equal([expectedUpstreamEndpoint], removeEndpoints);
|
||||
Assert.DoesNotContain(mediaItemId.ToString().ToUpperInvariant(), string.Join(",", removeEndpoints), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveFavorite_WhenRouteValuesAreCrafted_ShouldForwardTheSanitizedPlaceholders()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string expectedUpstreamEndpoint = $"users/me/favorites/Invalid/{ZERO_GUID}";
|
||||
_apiFactory.ApiClientStub.RegisterDeleteSuccess(expectedUpstreamEndpoint);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage removeRequest = CreateRemoveRequest("notamediakind", "not-a-guid", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(removeRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
List<string> removeEndpoints = GetRemoveEndpointCalls();
|
||||
Assert.Equal([expectedUpstreamEndpoint], removeEndpoints);
|
||||
Assert.DoesNotContain("notamediakind", string.Join(",", removeEndpoints), StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("not-a-guid", string.Join(",", removeEndpoints), StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the remove favorite endpoints that were called upstream, excluding the requests made to authenticate the test client.
|
||||
/// </summary>
|
||||
/// <returns>The list of upstream remove favorite endpoints that were called.</returns>
|
||||
private List<string> GetRemoveEndpointCalls()
|
||||
{
|
||||
return [.. _apiFactory.ApiClientStub.DeleteEndpointsCalled
|
||||
.Where(endpoint => endpoint.StartsWith("users/me/favorites", StringComparison.Ordinal))];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the remove favorite request for the specified route values.
|
||||
/// </summary>
|
||||
/// <param name="mediaKind">The value of the media kind route segment.</param>
|
||||
/// <param name="mediaItemId">The value of the media item identifier route segment.</param>
|
||||
/// <param name="antiforgeryToken">The antiforgery token to include in the request.</param>
|
||||
/// <returns>The configured remove favorite request.</returns>
|
||||
private static HttpRequestMessage CreateRemoveRequest(string mediaKind, string mediaItemId, string antiforgeryToken)
|
||||
{
|
||||
HttpRequestMessage removeRequest = new(HttpMethod.Delete, $"/en-us/favorites/{Uri.EscapeDataString(mediaKind)}/{Uri.EscapeDataString(mediaItemId)}/api-remove-favorite")
|
||||
{
|
||||
// The front-end sends the JSON content type even for DELETE requests, which triggers the antiforgery validation.
|
||||
Content = new StringContent("{}", Encoding.UTF8, "application/json")
|
||||
};
|
||||
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
|
||||
removeRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
removeRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
removeRequest.Headers.Add("RequestVerificationToken", antiforgeryToken);
|
||||
return removeRequest;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
+176
@@ -0,0 +1,176 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Playlists;
|
||||
using Lumina.Presentation.Web.Common.Enums.Playlists;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Playlists.GetPlaylist;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Playlists;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Playlists.GetPlaylist;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetPlaylistEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPlaylistEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly PlaylistDtoFixture _playlistDtoFixture = new();
|
||||
private readonly PlaylistEntryDtoFixture _playlistEntryDtoFixture = new();
|
||||
private readonly PaginatedDtoFixture<PlaylistEntryDto> _paginatedDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPlaylistEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetPlaylistEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaylist_WhenCalledByAuthenticatedUser_ShouldForwardTheDocumentedUpstreamUrlAndSurfaceThePlaylist()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
PlaylistEntryDto expectedEntry = _playlistEntryDtoFixture.Create(
|
||||
position: 0,
|
||||
mediaItemTitle: "First track",
|
||||
mediaItemType: PlaylistMediaItemType.MusicTrack);
|
||||
PlaylistDto expectedPlaylist = _playlistDtoFixture.Create(
|
||||
id: playlistId,
|
||||
name: "Evening listening",
|
||||
description: "Quiet tracks for the end of the day.",
|
||||
entries: _paginatedDtoFixture.Create(
|
||||
data: [expectedEntry],
|
||||
currentPage: 1,
|
||||
perPage: 200,
|
||||
count: 1,
|
||||
numberOfPages: 1),
|
||||
createdOnUtc: new DateTime(2026, 10, 19, 18, 0, 0, DateTimeKind.Utc),
|
||||
updatedOnUtc: new DateTime(2026, 10, 19, 19, 30, 0, DateTimeKind.Utc));
|
||||
string expectedEndpoint = $"users/me/playlists/{playlistId}?currentPage=1&perPage=200";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, expectedPlaylist);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/playlists/item/{playlistId}/api-get-playlist");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType!.MediaType);
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(content);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
JsonElement data = jsonDocument.RootElement.GetProperty("data");
|
||||
Assert.Equal(expectedPlaylist.Id, data.GetProperty("id").GetGuid());
|
||||
Assert.Equal(expectedPlaylist.Name, data.GetProperty("name").GetString());
|
||||
Assert.Equal(expectedPlaylist.Description, data.GetProperty("description").GetString());
|
||||
Assert.Equal(nameof(PlaylistType.Music), data.GetProperty("type").GetString());
|
||||
Assert.Equal(expectedPlaylist.CreatedOnUtc, data.GetProperty("createdOnUtc").GetDateTime());
|
||||
Assert.Equal(expectedPlaylist.UpdatedOnUtc, data.GetProperty("updatedOnUtc").GetDateTime());
|
||||
JsonElement entries = data.GetProperty("entries");
|
||||
Assert.Equal(expectedPlaylist.Entries.CurrentPage, entries.GetProperty("currentPage").GetInt32());
|
||||
Assert.Equal(expectedPlaylist.Entries.PerPage, entries.GetProperty("perPage").GetInt32());
|
||||
Assert.Equal(expectedPlaylist.Entries.Count, entries.GetProperty("count").GetInt32());
|
||||
Assert.Equal(expectedPlaylist.Entries.NumberOfPages, entries.GetProperty("numberOfPages").GetInt32());
|
||||
JsonElement entry = Assert.Single(entries.GetProperty("data").EnumerateArray());
|
||||
Assert.Equal(expectedEntry.Id, entry.GetProperty("id").GetGuid());
|
||||
Assert.Equal(expectedEntry.MediaItemTitle, entry.GetProperty("mediaItemTitle").GetString());
|
||||
Assert.Equal([expectedEndpoint], GetPlaylistEndpointCalls());
|
||||
Assert.True(response.Headers.CacheControl?.Private);
|
||||
Assert.True(response.Headers.CacheControl?.NoStore);
|
||||
Assert.Contains("Cookie", response.Headers.Vary);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaylist_WhenPageParametersAreProvided_ShouldForwardThemToTheApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
string expectedEndpoint = $"users/me/playlists/{playlistId}?currentPage=2&perPage=50";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, _playlistDtoFixture.Create(id: playlistId));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/playlists/item/{playlistId}/api-get-playlist?currentPage=2&perPage=50");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal([expectedEndpoint], GetPlaylistEndpointCalls());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaylist_WhenPlaylistIdIsAnUppercaseGuid_ShouldForwardItInLowercase()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.Parse("ABCDEFAB-CDEF-ABCD-EFAB-CDEFABCDEFAB");
|
||||
string uppercasePlaylistId = playlistId.ToString().ToUpperInvariant();
|
||||
string expectedEndpoint = $"users/me/playlists/{playlistId}?currentPage=1&perPage=200";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, _playlistDtoFixture.Create(id: playlistId));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/playlists/item/{uppercasePlaylistId}/api-get-playlist");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
List<string> endpointCalls = GetPlaylistEndpointCalls();
|
||||
Assert.Equal([expectedEndpoint], endpointCalls);
|
||||
Assert.DoesNotContain(uppercasePlaylistId, string.Join(",", endpointCalls), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaylist_WhenPlaylistIdIsNotAGuid_ShouldForwardTheEmptyGuid()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string expectedEndpoint = $"users/me/playlists/{ZERO_GUID}?currentPage=1&perPage=200";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, _playlistDtoFixture.Create(id: Guid.Empty));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/playlists/item/not-a-guid/api-get-playlist");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
List<string> endpointCalls = GetPlaylistEndpointCalls();
|
||||
Assert.Equal([expectedEndpoint], endpointCalls);
|
||||
Assert.DoesNotContain("not-a-guid", string.Join(",", endpointCalls), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the playlist endpoints that were called upstream, excluding the endpoints called by the authentication helpers.
|
||||
/// </summary>
|
||||
/// <returns>The list of upstream playlist endpoints that were called.</returns>
|
||||
private List<string> GetPlaylistEndpointCalls()
|
||||
{
|
||||
return [.. _apiFactory.ApiClientStub.GetEndpointsCalled
|
||||
.Where(endpoint => endpoint.StartsWith("users/me/playlists/", StringComparison.Ordinal))];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Playlists.Item;
|
||||
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;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Playlists.Item;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="AddPlaylistViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddPlaylistViewEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string WEB_ROUTE = "/en-us/playlists/item";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddPlaylistViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public AddPlaylistViewEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddPlaylistView_WhenCalledByAuthenticatedUser_ShouldRenderTheCreatePlaylistPage()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(WEB_ROUTE);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType);
|
||||
Assert.Contains("playlist-details-form", content, StringComparison.Ordinal);
|
||||
Assert.Contains("playlist-title", content, StringComparison.Ordinal);
|
||||
Assert.Contains("Create playlist", content, StringComparison.Ordinal);
|
||||
Assert.Contains("__RequestVerificationToken", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("users/me/playlists", StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddPlaylistView_WhenCalledByAuthenticatedUser_ShouldReturnANonStorablePage()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(WEB_ROUTE);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.True(response.Headers.CacheControl?.Private);
|
||||
Assert.True(response.Headers.CacheControl?.NoStore);
|
||||
Assert.Contains("no-store", string.Join(", ", response.Headers.GetValues("Cache-Control")), StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains("Cookie", response.Headers.Vary);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Playlists;
|
||||
using Lumina.Presentation.Web.Common.Enums.Playlists;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Playlists.Item;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Playlists;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Playlists.Item;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="PlaylistItemViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PlaylistItemViewEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly PlaylistDtoFixture _playlistDtoFixture = new();
|
||||
private readonly PlaylistEntryDtoFixture _playlistEntryDtoFixture = new();
|
||||
private readonly PaginatedDtoFixture<PlaylistEntryDto> _paginatedDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PlaylistItemViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public PlaylistItemViewEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PlaylistItemView_WhenCalledByAuthenticatedUser_ShouldForwardTheDocumentedUpstreamUrlAndRenderThePlaylist()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
PlaylistEntryDto expectedEntry = _playlistEntryDtoFixture.Create(
|
||||
position: 0,
|
||||
mediaItemTitle: "First track",
|
||||
mediaItemType: PlaylistMediaItemType.MusicTrack);
|
||||
PlaylistDto expectedPlaylist = _playlistDtoFixture.Create(
|
||||
id: playlistId,
|
||||
name: "Evening listening",
|
||||
description: "Quiet tracks for the end of the day.",
|
||||
entries: _paginatedDtoFixture.Create(
|
||||
data: [expectedEntry],
|
||||
currentPage: 1,
|
||||
perPage: 200,
|
||||
count: 1,
|
||||
numberOfPages: 1));
|
||||
string expectedEndpoint = $"users/me/playlists/{playlistId}?currentPage=1&perPage=200";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, expectedPlaylist);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/playlists/item/{playlistId}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType);
|
||||
Assert.Contains("playlist-details-form", content, StringComparison.Ordinal);
|
||||
Assert.Contains(expectedPlaylist.Name, content, StringComparison.Ordinal);
|
||||
Assert.Contains(expectedPlaylist.Description!, content, StringComparison.Ordinal);
|
||||
Assert.Contains(expectedEntry.MediaItemTitle, content, StringComparison.Ordinal);
|
||||
Assert.Equal([expectedEndpoint], GetPlaylistEndpointCalls());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PlaylistItemView_WhenCalledByAuthenticatedUser_ShouldReturnANonStorablePage()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
string expectedEndpoint = $"users/me/playlists/{playlistId}?currentPage=1&perPage=200";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, _playlistDtoFixture.Create(id: playlistId));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/playlists/item/{playlistId}");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.True(response.Headers.CacheControl?.Private);
|
||||
Assert.True(response.Headers.CacheControl?.NoStore);
|
||||
Assert.Contains("no-store", string.Join(", ", response.Headers.GetValues("Cache-Control")), StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains("Cookie", response.Headers.Vary);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PlaylistItemView_WhenPlaylistIdIsNotAGuid_ShouldForwardTheEmptyGuid()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string expectedEndpoint = $"users/me/playlists/{ZERO_GUID}?currentPage=1&perPage=200";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, _playlistDtoFixture.Create(id: Guid.Empty));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/playlists/item/not-a-guid");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
List<string> endpointCalls = GetPlaylistEndpointCalls();
|
||||
Assert.Equal([expectedEndpoint], endpointCalls);
|
||||
Assert.DoesNotContain("not-a-guid", string.Join(",", endpointCalls), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the playlist endpoints that were called upstream, excluding the endpoints called by the authentication helpers.
|
||||
/// </summary>
|
||||
/// <returns>The list of upstream playlist endpoints that were called.</returns>
|
||||
private List<string> GetPlaylistEndpointCalls()
|
||||
{
|
||||
return [.. _apiFactory.ApiClientStub.GetEndpointsCalled
|
||||
.Where(endpoint => endpoint.StartsWith("users/me/playlists/", StringComparison.Ordinal))];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
+405
@@ -0,0 +1,405 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.Favorites;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Favorites.AddFavorite;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Favorites.AddFavorite;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="AddFavoriteEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddFavoriteEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt";
|
||||
private const string PATH = "/api/v1/users/me/favorites";
|
||||
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly HttpClient _client;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly List<Guid> _seededLibraryIds = [];
|
||||
private readonly List<string> _seededUsernames = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddFavoriteEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public AddFavoriteEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
// A unique X-Forwarded-For isolates rate limiting state per test.
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddFavorite_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
object body = new { mediaKind = "MusicTrack", mediaItemId = Guid.NewGuid() };
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, body);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, PATH);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; DROP TABLE Favorites--")] // destructive injection
|
||||
[InlineData("1; DELETE FROM Favorites")] // stacked statement injection
|
||||
[InlineData("../../../etc/passwd")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
[InlineData("Ünïcödé-💥")] // non ascii input
|
||||
public async Task AddFavorite_WithInjectionInMediaKind_ShouldRejectWithoutLeakingOrChangingData(string maliciousMediaKind)
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, new { mediaKind = maliciousMediaKind, mediaItemId = Guid.NewGuid() });
|
||||
|
||||
// Assert
|
||||
string content = await AssertRejectedAsync(response);
|
||||
Assert.DoesNotContain(maliciousMediaKind, content, StringComparison.Ordinal);
|
||||
await AssertFavoriteCountAsync(callerId, 0);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; DROP TABLE Favorites--")] // destructive injection
|
||||
[InlineData("1; DELETE FROM Favorites")] // stacked statement injection
|
||||
[InlineData("../../../etc/passwd")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
[InlineData("Ünïcödé-💥")] // non ascii input
|
||||
public async Task AddFavorite_WithInjectionInMediaItemId_ShouldRejectWithoutLeakingOrChangingData(string maliciousMediaItemId)
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, new { mediaKind = "MusicTrack", mediaItemId = maliciousMediaItemId });
|
||||
|
||||
// Assert
|
||||
string content = await AssertRejectedAsync(response);
|
||||
Assert.DoesNotContain(maliciousMediaItemId, content, StringComparison.Ordinal);
|
||||
await AssertFavoriteCountAsync(callerId, 0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddFavorite_WhenTheMediaItemBelongsToAnotherUsersLibrary_ShouldReturnTheSameNotFoundAsAMissingItem()
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync();
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
Guid otherTrackId = await SeedTrackAsync(otherUserId);
|
||||
Guid missingTrackId = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage existingItemResponse = await _client.PostAsJsonAsync(PATH, new { mediaKind = "MusicTrack", mediaItemId = otherTrackId });
|
||||
HttpResponseMessage missingItemResponse = await _client.PostAsJsonAsync(PATH, new { mediaKind = "MusicTrack", mediaItemId = missingTrackId });
|
||||
|
||||
// Assert
|
||||
// Both answers are indistinguishable, so the route cannot be used as an existence oracle for another user's library.
|
||||
Assert.Equal(HttpStatusCode.NotFound, existingItemResponse.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.NotFound, missingItemResponse.StatusCode);
|
||||
string existingItemContent = await existingItemResponse.Content.ReadAsStringAsync();
|
||||
string missingItemContent = await missingItemResponse.Content.ReadAsStringAsync();
|
||||
Assert.Equal(GetProblemDetail(existingItemContent), GetProblemDetail(missingItemContent));
|
||||
Assert.Equal("TrackNotFound", GetProblemDetail(existingItemContent));
|
||||
await AssertFavoriteCountAsync(callerId, 0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddFavorite_WhenSuccessful_ShouldNotLeakSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync();
|
||||
Guid trackId = await SeedTrackAsync(callerId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, new { mediaKind = "MusicTrack", mediaItemId = trackId });
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertNonCacheable(response);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
AssertNoSensitiveData(content);
|
||||
AssertNoDatabaseOnlyFields(content);
|
||||
FavoriteResponse? favorite = JsonSerializer.Deserialize<FavoriteResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(favorite);
|
||||
Assert.Equal(trackId, favorite!.MediaItemId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddFavorite_WhenTheMediaKindIsNotSupported_ShouldRejectWithNonCacheableValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
(_, string username) = await CreateAuthenticatedUserAsync();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, new { mediaKind = "Video", mediaItemId = Guid.NewGuid() });
|
||||
|
||||
// Assert
|
||||
string content = await AssertValidationProblemAsync(response, PATH, "FavoriteMediaKindIsNotSupported");
|
||||
AssertNonCacheable(response);
|
||||
Assert.DoesNotContain(username, content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user and authenticates it on <paramref name="client"/>.
|
||||
/// </summary>
|
||||
/// <returns>The Id and username of the created user.</returns>
|
||||
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync()
|
||||
{
|
||||
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
_seededUsernames.Add(username);
|
||||
return (userId, username);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id and username.
|
||||
/// </summary>
|
||||
/// <returns>The Id and username of the seeded user.</returns>
|
||||
private async Task<(Guid UserId, string Username)> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"otheruser_{Guid.NewGuid()}";
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededUsernames.Add(username);
|
||||
return (userId, username);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/> with one track, and returns the Id of that track.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the seeded library.</param>
|
||||
/// <returns>The Id of the seeded track.</returns>
|
||||
private async Task<Guid> SeedTrackAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(
|
||||
id: libraryId, userId: userId, title: $"Library-{Guid.NewGuid():N}", libraryType: LibraryType.Music, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededLibraryIds.Add(libraryId);
|
||||
Guid artistId = Guid.NewGuid();
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Security Artist", includeAlbums: false, includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
dbContext.Albums.Add(_albumEntityFixture.Create(
|
||||
id: albumId,
|
||||
artistId: artistId,
|
||||
libraryId: libraryId,
|
||||
title: "Security Album",
|
||||
includeTracks: false,
|
||||
includeMetadata: false,
|
||||
includeBarcode: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
dbContext.Tracks.Add(_trackEntityFixture.Create(
|
||||
id: trackId,
|
||||
albumId: albumId,
|
||||
libraryId: libraryId,
|
||||
title: "Security Track",
|
||||
includeMetadata: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return trackId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts how many favorites the user identified by <paramref name="userId"/> owns.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user whose favorites are counted.</param>
|
||||
/// <param name="expectedCount">The expected number of favorites.</param>
|
||||
private async Task AssertFavoriteCountAsync(Guid userId, int expectedCount)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.Equal(expectedCount, await dbContext.Favorites.CountAsync(favorite => favorite.UserId == userId));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is the unauthenticated problem document produced by the authentication middleware.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
AssertNoSensitiveData(content);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the request was rejected without succeeding, and returns the raw response body.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
|
||||
private static async Task<string> AssertRejectedAsync(HttpResponseMessage response)
|
||||
{
|
||||
Assert.False(response.IsSuccessStatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.False(string.IsNullOrWhiteSpace(content));
|
||||
AssertNoSensitiveData(content);
|
||||
return content;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts the shape of a validation problem details response and returns its raw body.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCode">The expected validation error code.</param>
|
||||
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
|
||||
private async Task<string> AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstance, string expectedErrorCode)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors!.Keys);
|
||||
Assert.Contains(expectedErrorCode, errors["General.Validation"]);
|
||||
AssertNoSensitiveData(content);
|
||||
return content;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the detail of a problem details body.
|
||||
/// </summary>
|
||||
/// <param name="content">The problem details body to read.</param>
|
||||
/// <returns>The problem detail.</returns>
|
||||
private static string? GetProblemDetail(string content)
|
||||
{
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content);
|
||||
Assert.NotNull(problemDetails);
|
||||
return problemDetails!["detail"].GetString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is not storable by any intermediary and varies by the authorization header.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertNonCacheable(HttpResponseMessage response)
|
||||
{
|
||||
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
|
||||
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response body carries no credentials, secrets or stack traces.
|
||||
/// </summary>
|
||||
/// <param name="content">The response body to assert on.</param>
|
||||
private static void AssertNoSensitiveData(string content)
|
||||
{
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response body exposes only the fields of the documented favorite response contract.
|
||||
/// </summary>
|
||||
/// <param name="content">The response body to assert on.</param>
|
||||
private static void AssertNoDatabaseOnlyFields(string content)
|
||||
{
|
||||
Assert.DoesNotContain("version", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("createdBy", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("updatedBy", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the catalogue rows seeded by the test and the test users.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_client.Dispose();
|
||||
using (IServiceScope scope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<Guid> libraryIds = [.. _seededLibraryIds];
|
||||
dbContext.Tracks.RemoveRange(dbContext.Tracks.Where(track => libraryIds.Contains(track.LibraryId)));
|
||||
dbContext.Albums.RemoveRange(dbContext.Albums.Where(album => libraryIds.Contains(album.LibraryId)));
|
||||
dbContext.Artists.RemoveRange(dbContext.Artists.Where(artist => libraryIds.Contains(artist.LibraryId)));
|
||||
dbContext.Libraries.RemoveRange(dbContext.Libraries.Where(library => libraryIds.Contains(library.Id)));
|
||||
dbContext.SaveChanges();
|
||||
}
|
||||
foreach (string username in _seededUsernames)
|
||||
_apiFactory.RemoveTestUser(username);
|
||||
}
|
||||
}
|
||||
+344
@@ -0,0 +1,344 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.Favorites;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Favorites.GetFavoriteStatus;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Favorites.GetFavoriteStatus;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetFavoriteStatusEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetFavoriteStatusEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt";
|
||||
private const string PATH = "/api/v1/users/me/favorites/status";
|
||||
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly HttpClient _client;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly FavoriteEntityFixture _favoriteEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly List<string> _seededUsernames = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetFavoriteStatusEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetFavoriteStatusEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
// A unique X-Forwarded-For isolates rate limiting state per test.
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavoriteStatus_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"{PATH}?mediaKind=MusicTrack&mediaItemIds={Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, PATH);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; DROP TABLE Favorites--")] // destructive injection
|
||||
[InlineData("1; DELETE FROM Favorites")] // stacked statement injection
|
||||
[InlineData("../../../etc/passwd")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
[InlineData("Ünïcödé-💥")] // non ascii input
|
||||
public async Task GetFavoriteStatus_WithInjectionInMediaKind_ShouldRejectWithoutLeakingOrChangingData(string maliciousMediaKind)
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync();
|
||||
Guid favoritedItemId = await SeedFavoriteAsync(callerId, FavoriteMediaKind.MusicTrack);
|
||||
string url = $"{PATH}?mediaKind={Uri.EscapeDataString(maliciousMediaKind)}&mediaItemIds={favoritedItemId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
string content = await AssertRejectedAsync(response);
|
||||
Assert.DoesNotContain(maliciousMediaKind, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(favoritedItemId.ToString(), content, StringComparison.OrdinalIgnoreCase);
|
||||
await AssertFavoriteCountAsync(callerId, 1);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; DROP TABLE Favorites--")] // destructive injection
|
||||
[InlineData("1; DELETE FROM Favorites")] // stacked statement injection
|
||||
[InlineData("../../../etc/passwd")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
[InlineData("Ünïcödé-💥")] // non ascii input
|
||||
public async Task GetFavoriteStatus_WithInjectionInMediaItemIds_ShouldRejectWithoutLeakingOrChangingData(string maliciousMediaItemId)
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync();
|
||||
Guid favoritedItemId = await SeedFavoriteAsync(callerId, FavoriteMediaKind.MusicTrack);
|
||||
string url = $"{PATH}?mediaKind=MusicTrack&mediaItemIds={favoritedItemId}&mediaItemIds={Uri.EscapeDataString(maliciousMediaItemId)}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
string content = await AssertRejectedAsync(response);
|
||||
Assert.DoesNotContain(maliciousMediaItemId, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(favoritedItemId.ToString(), content, StringComparison.OrdinalIgnoreCase);
|
||||
await AssertFavoriteCountAsync(callerId, 1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavoriteStatus_WhenSuccessful_ShouldReturnOnlyTheCallersFavoritesWithoutSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, string username) = await CreateAuthenticatedUserAsync();
|
||||
Guid callerFavoritedItemId = await SeedFavoriteAsync(callerId, FavoriteMediaKind.MusicTrack);
|
||||
(Guid otherUserId, string otherUsername) = await SeedOtherUserAsync();
|
||||
Guid otherFavoritedItemId = await SeedFavoriteAsync(otherUserId, FavoriteMediaKind.MusicTrack);
|
||||
string url = $"{PATH}?mediaKind=MusicTrack&mediaItemIds={callerFavoritedItemId}&mediaItemIds={otherFavoritedItemId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertNonCacheable(response);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
AssertNoSensitiveData(content);
|
||||
AssertNoDatabaseOnlyFields(content);
|
||||
Assert.DoesNotContain(username, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(otherUsername, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(otherFavoritedItemId.ToString(), content, StringComparison.OrdinalIgnoreCase);
|
||||
FavoriteStatusResponse? status = JsonSerializer.Deserialize<FavoriteStatusResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(status);
|
||||
Guid favoritedId = Assert.Single(status!.FavoritedMediaItemIds);
|
||||
Assert.Equal(callerFavoritedItemId, favoritedId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavoriteStatus_WhenTooManyIdsAreRequested_ShouldRejectWithNonCacheableValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync();
|
||||
Guid favoritedItemId = await SeedFavoriteAsync(callerId, FavoriteMediaKind.MusicTrack);
|
||||
List<Guid> requestedIds = [favoritedItemId, .. Enumerable.Range(0, 100).Select(_ => Guid.NewGuid())];
|
||||
string url = $"{PATH}?mediaKind=MusicTrack&{string.Join("&", requestedIds.Select(requestedId => $"mediaItemIds={requestedId}"))}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
string content = await AssertValidationProblemAsync(response, PATH, "FavoriteMediaItemIdsExceedMaximumCount");
|
||||
AssertNonCacheable(response);
|
||||
Assert.DoesNotContain(favoritedItemId.ToString(), content, StringComparison.OrdinalIgnoreCase);
|
||||
await AssertFavoriteCountAsync(callerId, 1);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user and authenticates it on <paramref name="client"/>.
|
||||
/// </summary>
|
||||
/// <returns>The Id and username of the created user.</returns>
|
||||
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync()
|
||||
{
|
||||
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
_seededUsernames.Add(username);
|
||||
return (userId, username);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id and username.
|
||||
/// </summary>
|
||||
/// <returns>The Id and username of the seeded user.</returns>
|
||||
private async Task<(Guid UserId, string Username)> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"otheruser_{Guid.NewGuid()}";
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededUsernames.Add(username);
|
||||
return (userId, username);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a favorite of <paramref name="userId"/> and returns the Id of the favorited media item.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the favorite.</param>
|
||||
/// <param name="mediaKind">The kind of the favorited media item.</param>
|
||||
/// <returns>The Id of the favorited media item.</returns>
|
||||
private async Task<Guid> SeedFavoriteAsync(Guid userId, FavoriteMediaKind mediaKind)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
dbContext.Favorites.Add(_favoriteEntityFixture.Create(
|
||||
userId: userId,
|
||||
mediaKind: mediaKind,
|
||||
mediaItemId: mediaItemId,
|
||||
createdBy: userId,
|
||||
includeUpdatedOnUtc: false,
|
||||
includeUpdatedBy: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return mediaItemId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts how many favorites the user identified by <paramref name="userId"/> owns.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user whose favorites are counted.</param>
|
||||
/// <param name="expectedCount">The expected number of favorites.</param>
|
||||
private async Task AssertFavoriteCountAsync(Guid userId, int expectedCount)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.Equal(expectedCount, await dbContext.Favorites.CountAsync(favorite => favorite.UserId == userId));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is the unauthenticated problem document produced by the authentication middleware.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
AssertNoSensitiveData(content);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the request was rejected without succeeding, and returns the raw response body.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
|
||||
private static async Task<string> AssertRejectedAsync(HttpResponseMessage response)
|
||||
{
|
||||
Assert.False(response.IsSuccessStatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.False(string.IsNullOrWhiteSpace(content));
|
||||
AssertNoSensitiveData(content);
|
||||
Assert.DoesNotContain("\"favoritedMediaItemIds\"", content, StringComparison.Ordinal);
|
||||
return content;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts the shape of a validation problem details response and returns its raw body.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCode">The expected validation error code.</param>
|
||||
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
|
||||
private async Task<string> AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstance, string expectedErrorCode)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors!.Keys);
|
||||
Assert.Contains(expectedErrorCode, errors["General.Validation"]);
|
||||
AssertNoSensitiveData(content);
|
||||
return content;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is not storable by any intermediary and varies by the authorization header.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertNonCacheable(HttpResponseMessage response)
|
||||
{
|
||||
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
|
||||
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response body carries no credentials, secrets or stack traces.
|
||||
/// </summary>
|
||||
/// <param name="content">The response body to assert on.</param>
|
||||
private static void AssertNoSensitiveData(string content)
|
||||
{
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response body exposes only the fields of the documented favorite status response contract.
|
||||
/// </summary>
|
||||
/// <param name="content">The response body to assert on.</param>
|
||||
private static void AssertNoDatabaseOnlyFields(string content)
|
||||
{
|
||||
Assert.DoesNotContain("version", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("createdBy", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("updatedBy", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("createdOnUtc", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("updatedOnUtc", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the test users created by the test.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_client.Dispose();
|
||||
foreach (string username in _seededUsernames)
|
||||
_apiFactory.RemoveTestUser(username);
|
||||
}
|
||||
}
|
||||
+318
@@ -0,0 +1,318 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
using Lumina.Contracts.Responses.Favorites;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Favorites.GetFavorites;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Favorites.GetFavorites;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetFavoritesEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetFavoritesEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt";
|
||||
private const string PATH = "/api/v1/users/me/favorites";
|
||||
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly HttpClient _client;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly FavoriteEntityFixture _favoriteEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly List<string> _seededUsernames = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetFavoritesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetFavoritesEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
// A unique X-Forwarded-For isolates rate limiting state per test.
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavorites_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(PATH);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, PATH);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; DROP TABLE Favorites--")] // destructive injection
|
||||
[InlineData("1; DELETE FROM Favorites")] // stacked statement injection
|
||||
[InlineData("../../../etc/passwd")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
[InlineData("Ünïcödé-💥")] // non ascii input
|
||||
public async Task GetFavorites_WithInjectionInMediaKind_ShouldRejectWithoutLeakingOrChangingData(string maliciousMediaKind)
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync();
|
||||
Guid favoritedItemId = await SeedFavoriteAsync(callerId, FavoriteMediaKind.MusicTrack);
|
||||
string url = $"{PATH}?mediaKind={Uri.EscapeDataString(maliciousMediaKind)}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
string content = await AssertRejectedAsync(response);
|
||||
Assert.DoesNotContain(maliciousMediaKind, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(favoritedItemId.ToString(), content, StringComparison.OrdinalIgnoreCase);
|
||||
await AssertFavoriteCountAsync(callerId, 1);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; DROP TABLE Favorites--")] // destructive injection
|
||||
[InlineData("1; DELETE FROM Favorites")] // stacked statement injection
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
[InlineData("Ünïcödé-💥")] // non ascii input
|
||||
public async Task GetFavorites_WithInjectionInCurrentPage_ShouldRejectWithoutLeakingOrChangingData(string maliciousCurrentPage)
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync();
|
||||
Guid favoritedItemId = await SeedFavoriteAsync(callerId, FavoriteMediaKind.MusicTrack);
|
||||
string url = $"{PATH}?currentPage={Uri.EscapeDataString(maliciousCurrentPage)}&perPage=10";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
string content = await AssertRejectedAsync(response);
|
||||
Assert.DoesNotContain(maliciousCurrentPage, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(favoritedItemId.ToString(), content, StringComparison.OrdinalIgnoreCase);
|
||||
await AssertFavoriteCountAsync(callerId, 1);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; DROP TABLE Favorites--")] // destructive injection
|
||||
[InlineData("1; DELETE FROM Favorites")] // stacked statement injection
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
[InlineData("Ünïcödé-💥")] // non ascii input
|
||||
public async Task GetFavorites_WithInjectionInPerPage_ShouldRejectWithoutLeakingOrChangingData(string maliciousPerPage)
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync();
|
||||
Guid favoritedItemId = await SeedFavoriteAsync(callerId, FavoriteMediaKind.MusicTrack);
|
||||
string url = $"{PATH}?currentPage=1&perPage={Uri.EscapeDataString(maliciousPerPage)}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
string content = await AssertRejectedAsync(response);
|
||||
Assert.DoesNotContain(maliciousPerPage, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(favoritedItemId.ToString(), content, StringComparison.OrdinalIgnoreCase);
|
||||
await AssertFavoriteCountAsync(callerId, 1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavorites_WhenSuccessful_ShouldReturnOnlyTheCallersFavoritesWithoutSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, string username) = await CreateAuthenticatedUserAsync();
|
||||
Guid favoritedItemId = await SeedFavoriteAsync(callerId, FavoriteMediaKind.MusicTrack);
|
||||
(Guid otherUserId, string otherUsername) = await SeedOtherUserAsync();
|
||||
Guid otherFavoritedItemId = await SeedFavoriteAsync(otherUserId, FavoriteMediaKind.MusicTrack);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(PATH);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertNonCacheable(response);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
AssertNoSensitiveData(content);
|
||||
AssertNoDatabaseOnlyFields(content);
|
||||
Assert.DoesNotContain(username, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(otherUsername, content, StringComparison.Ordinal);
|
||||
Assert.Contains(favoritedItemId.ToString(), content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(otherFavoritedItemId.ToString(), content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(otherUserId.ToString(), content, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
PaginatedResponse<FavoriteItemResponse>? favorites = JsonSerializer.Deserialize<PaginatedResponse<FavoriteItemResponse>>(content, _jsonOptions);
|
||||
Assert.NotNull(favorites);
|
||||
FavoriteItemResponse favorite = Assert.Single(favorites!.Data);
|
||||
Assert.Equal(favoritedItemId, favorite.MediaItemId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user and authenticates it on <paramref name="client"/>.
|
||||
/// </summary>
|
||||
/// <returns>The Id and username of the created user.</returns>
|
||||
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync()
|
||||
{
|
||||
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
_seededUsernames.Add(username);
|
||||
return (userId, username);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id and username.
|
||||
/// </summary>
|
||||
/// <returns>The Id and username of the seeded user.</returns>
|
||||
private async Task<(Guid UserId, string Username)> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"otheruser_{Guid.NewGuid()}";
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededUsernames.Add(username);
|
||||
return (userId, username);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a favorite of <paramref name="userId"/> and returns the Id of the favorited media item.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the favorite.</param>
|
||||
/// <param name="mediaKind">The kind of the favorited media item.</param>
|
||||
/// <returns>The Id of the favorited media item.</returns>
|
||||
private async Task<Guid> SeedFavoriteAsync(Guid userId, FavoriteMediaKind mediaKind)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
dbContext.Favorites.Add(_favoriteEntityFixture.Create(
|
||||
userId: userId,
|
||||
mediaKind: mediaKind,
|
||||
mediaItemId: mediaItemId,
|
||||
createdBy: userId,
|
||||
includeUpdatedOnUtc: false,
|
||||
includeUpdatedBy: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return mediaItemId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts how many favorites the user identified by <paramref name="userId"/> owns.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user whose favorites are counted.</param>
|
||||
/// <param name="expectedCount">The expected number of favorites.</param>
|
||||
private async Task AssertFavoriteCountAsync(Guid userId, int expectedCount)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.Equal(expectedCount, await dbContext.Favorites.CountAsync(favorite => favorite.UserId == userId));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is the unauthenticated problem document produced by the authentication middleware.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
AssertNoSensitiveData(content);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the request was rejected without succeeding, and returns the raw response body.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
|
||||
private static async Task<string> AssertRejectedAsync(HttpResponseMessage response)
|
||||
{
|
||||
Assert.False(response.IsSuccessStatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.False(string.IsNullOrWhiteSpace(content));
|
||||
AssertNoSensitiveData(content);
|
||||
Assert.DoesNotContain("\"favoritedMediaItemIds\"", content, StringComparison.Ordinal);
|
||||
return content;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is not storable by any intermediary and varies by the authorization header.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertNonCacheable(HttpResponseMessage response)
|
||||
{
|
||||
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
|
||||
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response body carries no credentials, secrets or stack traces.
|
||||
/// </summary>
|
||||
/// <param name="content">The response body to assert on.</param>
|
||||
private static void AssertNoSensitiveData(string content)
|
||||
{
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response body exposes only the fields of the documented favorites response contract.
|
||||
/// </summary>
|
||||
/// <param name="content">The response body to assert on.</param>
|
||||
private static void AssertNoDatabaseOnlyFields(string content)
|
||||
{
|
||||
Assert.DoesNotContain("version", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("createdBy", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("updatedBy", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("createdOnUtc", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("updatedOnUtc", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the test users created by the test.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_client.Dispose();
|
||||
foreach (string username in _seededUsernames)
|
||||
_apiFactory.RemoveTestUser(username);
|
||||
}
|
||||
}
|
||||
+306
@@ -0,0 +1,306 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Favorites.RemoveFavorite;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Favorites.RemoveFavorite;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="RemoveFavoriteEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RemoveFavoriteEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt";
|
||||
private const string PATH = "/api/v1/users/me/favorites";
|
||||
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly HttpClient _client;
|
||||
private readonly FavoriteEntityFixture _favoriteEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly List<string> _seededUsernames = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RemoveFavoriteEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public RemoveFavoriteEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
// A unique X-Forwarded-For isolates rate limiting state per test.
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveFavorite_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"{PATH}/MusicTrack/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; DROP TABLE Favorites--")] // destructive injection
|
||||
[InlineData("1; DELETE FROM Favorites")] // stacked statement injection
|
||||
[InlineData("../../../etc/passwd")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
[InlineData("Ünïcödé-💥")] // non ascii input
|
||||
public async Task RemoveFavorite_WithInjectionInMediaKind_ShouldRejectWithoutLeakingOrChangingData(string maliciousMediaKind)
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
await SeedFavoriteAsync(callerId, FavoriteMediaKind.MusicTrack, mediaItemId);
|
||||
string url = $"{PATH}/{Uri.EscapeDataString(maliciousMediaKind)}/{mediaItemId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
string content = await AssertValidationProblemAsync(response, $"{PATH}/", "FavoriteMediaKindIsInvalid");
|
||||
AssertNonCacheable(response);
|
||||
Assert.DoesNotContain(maliciousMediaKind, content, StringComparison.Ordinal);
|
||||
await AssertFavoriteExistsAsync(callerId, mediaItemId);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; DROP TABLE Favorites--")] // destructive injection
|
||||
[InlineData("1; DELETE FROM Favorites")] // stacked statement injection
|
||||
[InlineData("../../../etc/passwd")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
[InlineData("Ünïcödé-💥")] // non ascii input
|
||||
public async Task RemoveFavorite_WithInjectionInMediaItemId_ShouldRejectWithoutLeakingOrChangingData(string maliciousMediaItemId)
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
await SeedFavoriteAsync(callerId, FavoriteMediaKind.MusicTrack, mediaItemId);
|
||||
string url = $"{PATH}/MusicTrack/{Uri.EscapeDataString(maliciousMediaItemId)}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
string content = await AssertValidationProblemAsync(response, $"{PATH}/MusicTrack/", "FavoriteMediaItemIdCannotBeEmpty");
|
||||
AssertNonCacheable(response);
|
||||
Assert.DoesNotContain(maliciousMediaItemId, content, StringComparison.Ordinal);
|
||||
await AssertFavoriteExistsAsync(callerId, mediaItemId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveFavorite_WhenAnotherUserFavoritedTheSameItem_ShouldRemoveOnlyTheCallersRow()
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
await SeedFavoriteAsync(callerId, FavoriteMediaKind.MusicTrack, mediaItemId);
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
await SeedFavoriteAsync(otherUserId, FavoriteMediaKind.MusicTrack, mediaItemId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"{PATH}/MusicTrack/{mediaItemId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertNonCacheable(response);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
AssertNoSensitiveData(content);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.False(await dbContext.Favorites.AnyAsync(favorite => favorite.UserId == callerId));
|
||||
Assert.True(await dbContext.Favorites.AnyAsync(favorite => favorite.UserId == otherUserId && favorite.MediaItemId == mediaItemId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveFavorite_WhenSuccessful_ShouldNotLeakSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, string username) = await CreateAuthenticatedUserAsync();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
await SeedFavoriteAsync(callerId, FavoriteMediaKind.MusicTrack, mediaItemId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"{PATH}/MusicTrack/{mediaItemId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertNonCacheable(response);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
AssertNoSensitiveData(content);
|
||||
Assert.DoesNotContain(username, content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user and authenticates it on <paramref name="client"/>.
|
||||
/// </summary>
|
||||
/// <returns>The Id and username of the created user.</returns>
|
||||
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync()
|
||||
{
|
||||
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
_seededUsernames.Add(username);
|
||||
return (userId, username);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id and username.
|
||||
/// </summary>
|
||||
/// <returns>The Id and username of the seeded user.</returns>
|
||||
private async Task<(Guid UserId, string Username)> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"otheruser_{Guid.NewGuid()}";
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededUsernames.Add(username);
|
||||
return (userId, username);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a favorite of <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the favorite.</param>
|
||||
/// <param name="mediaKind">The kind of the favorited media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the favorited media item.</param>
|
||||
private async Task SeedFavoriteAsync(Guid userId, FavoriteMediaKind mediaKind, Guid mediaItemId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Favorites.Add(_favoriteEntityFixture.Create(
|
||||
userId: userId,
|
||||
mediaKind: mediaKind,
|
||||
mediaItemId: mediaItemId,
|
||||
createdBy: userId,
|
||||
includeUpdatedOnUtc: false,
|
||||
includeUpdatedBy: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the favorite of <paramref name="userId"/> on <paramref name="mediaItemId"/> still exists.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the favorite.</param>
|
||||
/// <param name="mediaItemId">The Id of the favorited media item.</param>
|
||||
private async Task AssertFavoriteExistsAsync(Guid userId, Guid mediaItemId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.True(await dbContext.Favorites.AnyAsync(favorite => favorite.UserId == userId && favorite.MediaItemId == mediaItemId));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is the unauthenticated problem document produced by the authentication middleware.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
AssertNoSensitiveData(content);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts the shape of a validation problem details response and returns its raw body.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstancePrefix">The expected prefix of the request instance path.</param>
|
||||
/// <param name="expectedErrorCode">The expected validation error code.</param>
|
||||
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
|
||||
private async Task<string> AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstancePrefix, string expectedErrorCode)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
// The instance is the routed path, which normalizes the escaping of some characters, so only its prefix is asserted.
|
||||
Assert.StartsWith(expectedInstancePrefix, problemDetails["instance"].GetString());
|
||||
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>();
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors!.Keys);
|
||||
Assert.Contains(expectedErrorCode, errors["General.Validation"]);
|
||||
AssertNoSensitiveData(content);
|
||||
return content;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is not storable by any intermediary and varies by the authorization header.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertNonCacheable(HttpResponseMessage response)
|
||||
{
|
||||
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
|
||||
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response body carries no credentials, secrets or stack traces.
|
||||
/// </summary>
|
||||
/// <param name="content">The response body to assert on.</param>
|
||||
private static void AssertNoSensitiveData(string content)
|
||||
{
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the test users created by the test.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_client.Dispose();
|
||||
foreach (string username in _seededUsernames)
|
||||
_apiFactory.RemoveTestUser(username);
|
||||
}
|
||||
}
|
||||
+435
@@ -0,0 +1,435 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Playlists;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Playlists;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.Playlists;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Playlists.GetPlaylist;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Playlists.GetPlaylist;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetPlaylistEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPlaylistEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt";
|
||||
private const string PATH = "/api/v1/users/me/playlists";
|
||||
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly HttpClient _client;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly PlaylistEntityFixture _playlistEntityFixture = new();
|
||||
private readonly PlaylistEntryEntityFixture _playlistEntryEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly List<Guid> _seededLibraryIds = [];
|
||||
private readonly List<Guid> _seededPlaylistIds = [];
|
||||
private readonly List<string> _seededUsernames = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPlaylistEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetPlaylistEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
// A unique X-Forwarded-For isolates rate limiting state per test.
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaylist_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"{PATH}/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; DROP TABLE Playlists--")] // destructive injection
|
||||
[InlineData("1; DELETE FROM Playlists")] // stacked statement injection
|
||||
[InlineData("../../../etc/passwd")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
[InlineData("Ünïcödé-💥")] // non ascii input
|
||||
public async Task GetPlaylist_WithInjectionInPlaylistId_ShouldRejectWithoutLeakingOrChangingData(string maliciousPlaylistId)
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync();
|
||||
Guid playlistId = await SeedPlaylistAsync(callerId, "Caller playlist", trackCount: 1);
|
||||
string url = $"{PATH}/{Uri.EscapeDataString(maliciousPlaylistId)}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
string content = await AssertValidationProblemAsync(response, $"{PATH}/", "PlaylistIdCannotBeEmpty");
|
||||
AssertNonCacheable(response);
|
||||
Assert.DoesNotContain(maliciousPlaylistId, content, StringComparison.Ordinal);
|
||||
await AssertPlaylistStillExistsAsync(playlistId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaylist_WhenThePlaylistBelongsToAnotherUser_ShouldReturnTheSameNotFoundAsAMissingPlaylist()
|
||||
{
|
||||
// Arrange
|
||||
(_, _) = await CreateAuthenticatedUserAsync();
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
Guid otherPlaylistId = await SeedPlaylistAsync(otherUserId, "Someone else's playlist", trackCount: 1);
|
||||
Guid missingPlaylistId = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage existingPlaylistResponse = await _client.GetAsync($"{PATH}/{otherPlaylistId}");
|
||||
HttpResponseMessage missingPlaylistResponse = await _client.GetAsync($"{PATH}/{missingPlaylistId}");
|
||||
|
||||
// Assert
|
||||
// Both answers are indistinguishable, so the route cannot be used as an existence oracle for another user's playlist.
|
||||
Assert.Equal(HttpStatusCode.NotFound, existingPlaylistResponse.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.NotFound, missingPlaylistResponse.StatusCode);
|
||||
string existingPlaylistContent = await existingPlaylistResponse.Content.ReadAsStringAsync();
|
||||
string missingPlaylistContent = await missingPlaylistResponse.Content.ReadAsStringAsync();
|
||||
Assert.Equal(GetProblemDetail(existingPlaylistContent), GetProblemDetail(missingPlaylistContent));
|
||||
Assert.Equal("PlaylistNotFound", GetProblemDetail(existingPlaylistContent));
|
||||
Assert.DoesNotContain("Someone else's playlist", existingPlaylistContent, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaylist_WhenSuccessful_ShouldReturnOnlyTheCallersPlaylistWithoutSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, string username) = await CreateAuthenticatedUserAsync();
|
||||
Guid playlistId = await SeedPlaylistAsync(callerId, "Caller playlist", trackCount: 2);
|
||||
(Guid otherUserId, string otherUsername) = await SeedOtherUserAsync();
|
||||
await SeedPlaylistAsync(otherUserId, "Other playlist", trackCount: 1);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}/{playlistId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertNonCacheable(response);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
AssertNoSensitiveData(content);
|
||||
AssertNoDatabaseOnlyFields(content);
|
||||
Assert.DoesNotContain(username, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(otherUsername, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Other playlist", content, StringComparison.Ordinal);
|
||||
|
||||
PlaylistResponse? playlist = JsonSerializer.Deserialize<PlaylistResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(playlist);
|
||||
Assert.Equal(playlistId, playlist!.Id);
|
||||
Assert.Equal("Caller playlist", playlist.Name);
|
||||
Assert.Equal(2, playlist.Entries.Data.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaylist_WhenThePlaylistDoesNotExist_ShouldRejectWithNonCacheableNotFound()
|
||||
{
|
||||
// Arrange
|
||||
await CreateAuthenticatedUserAsync();
|
||||
string url = $"{PATH}/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
string content = await AssertNotFoundAsync(response, url, "PlaylistNotFound");
|
||||
AssertNonCacheable(response);
|
||||
AssertNoSensitiveData(content);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user and authenticates it on <paramref name="client"/>.
|
||||
/// </summary>
|
||||
/// <returns>The Id and username of the created user.</returns>
|
||||
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync()
|
||||
{
|
||||
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
_seededUsernames.Add(username);
|
||||
return (userId, username);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id and username.
|
||||
/// </summary>
|
||||
/// <returns>The Id and username of the seeded user.</returns>
|
||||
private async Task<(Guid UserId, string Username)> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"otheruser_{Guid.NewGuid()}";
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededUsernames.Add(username);
|
||||
return (userId, username);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a playlist of <paramref name="userId"/> with the requested number of entries, each one referencing its own seeded track.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the playlist.</param>
|
||||
/// <param name="name">The name of the playlist.</param>
|
||||
/// <param name="trackCount">The number of entries to seed.</param>
|
||||
/// <returns>The Id of the seeded playlist.</returns>
|
||||
private async Task<Guid> SeedPlaylistAsync(Guid userId, string name, int trackCount)
|
||||
{
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(
|
||||
id: libraryId, userId: userId, title: $"Library-{Guid.NewGuid():N}", libraryType: LibraryType.Music, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededLibraryIds.Add(libraryId);
|
||||
Guid artistId = Guid.NewGuid();
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Playlist Artist", includeAlbums: false, includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
dbContext.Albums.Add(_albumEntityFixture.Create(
|
||||
id: albumId,
|
||||
artistId: artistId,
|
||||
libraryId: libraryId,
|
||||
title: "Playlist Album",
|
||||
includeTracks: false,
|
||||
includeMetadata: false,
|
||||
includeBarcode: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
dbContext.Playlists.Add(_playlistEntityFixture.Create(
|
||||
id: playlistId,
|
||||
userId: userId,
|
||||
name: name,
|
||||
type: PlaylistType.Music,
|
||||
entryCount: trackCount,
|
||||
version: 0,
|
||||
createdBy: userId));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededPlaylistIds.Add(playlistId);
|
||||
for (int index = 0; index < trackCount; index++)
|
||||
{
|
||||
Guid trackId = Guid.NewGuid();
|
||||
dbContext.Tracks.Add(_trackEntityFixture.Create(
|
||||
id: trackId,
|
||||
albumId: albumId,
|
||||
libraryId: libraryId,
|
||||
title: $"Playlist Track {index}",
|
||||
includeMetadata: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
dbContext.PlaylistEntries.Add(_playlistEntryEntityFixture.Create(
|
||||
playlistId: playlistId,
|
||||
mediaItemId: trackId,
|
||||
mediaItemType: PlaylistMediaItemType.MusicTrack,
|
||||
position: index * 1_000_000_000L));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
return playlistId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the playlist identified by <paramref name="playlistId"/> still exists.
|
||||
/// </summary>
|
||||
/// <param name="playlistId">The Id of the playlist to look up.</param>
|
||||
private async Task AssertPlaylistStillExistsAsync(Guid playlistId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.True(await dbContext.Playlists.AnyAsync(playlist => playlist.Id == playlistId));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is the unauthenticated problem document produced by the authentication middleware.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
AssertNoSensitiveData(content);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts the shape of a validation problem details response and returns its raw body.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstancePrefix">The expected prefix of the request instance path.</param>
|
||||
/// <param name="expectedErrorCode">The expected validation error code.</param>
|
||||
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
|
||||
private async Task<string> AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstancePrefix, string expectedErrorCode)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
// The instance is the routed path, which normalizes the escaping of some characters, so only its prefix is asserted.
|
||||
Assert.StartsWith(expectedInstancePrefix, problemDetails["instance"].GetString());
|
||||
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>();
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors!.Keys);
|
||||
Assert.Contains(expectedErrorCode, errors["General.Validation"]);
|
||||
AssertNoSensitiveData(content);
|
||||
return content;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts the shape of a not found problem details response and returns its raw body.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
|
||||
private async Task<string> AssertNotFoundAsync(HttpResponseMessage response, string expectedInstance, string expectedDetail)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.NotFound", problemDetails["title"].GetString());
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
|
||||
AssertNoSensitiveData(content);
|
||||
return content;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the detail of a problem details body.
|
||||
/// </summary>
|
||||
/// <param name="content">The problem details body to read.</param>
|
||||
/// <returns>The problem detail.</returns>
|
||||
private static string? GetProblemDetail(string content)
|
||||
{
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content);
|
||||
Assert.NotNull(problemDetails);
|
||||
return problemDetails!["detail"].GetString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is not storable by any intermediary and varies by the authorization header.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertNonCacheable(HttpResponseMessage response)
|
||||
{
|
||||
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
|
||||
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response body carries no credentials, secrets or stack traces.
|
||||
/// </summary>
|
||||
/// <param name="content">The response body to assert on.</param>
|
||||
private static void AssertNoSensitiveData(string content)
|
||||
{
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response body exposes only the fields of the documented playlist response contract.
|
||||
/// </summary>
|
||||
/// <param name="content">The response body to assert on.</param>
|
||||
private static void AssertNoDatabaseOnlyFields(string content)
|
||||
{
|
||||
// The creation and update times are part of the documented playlist contract, so they are not asserted absent here.
|
||||
Assert.DoesNotContain("version", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("createdBy", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("updatedBy", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the catalogue rows and playlists seeded by the test and the test users.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_client.Dispose();
|
||||
using (IServiceScope scope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<Guid> libraryIds = [.. _seededLibraryIds];
|
||||
List<Guid> playlistIds = [.. _seededPlaylistIds];
|
||||
dbContext.PlaylistEntries.RemoveRange(dbContext.PlaylistEntries.Where(entry => playlistIds.Contains(entry.PlaylistId)));
|
||||
dbContext.Playlists.RemoveRange(dbContext.Playlists.Where(playlist => playlistIds.Contains(playlist.Id)));
|
||||
dbContext.Tracks.RemoveRange(dbContext.Tracks.Where(track => libraryIds.Contains(track.LibraryId)));
|
||||
dbContext.Albums.RemoveRange(dbContext.Albums.Where(album => libraryIds.Contains(album.LibraryId)));
|
||||
dbContext.Artists.RemoveRange(dbContext.Artists.Where(artist => libraryIds.Contains(artist.LibraryId)));
|
||||
dbContext.Libraries.RemoveRange(dbContext.Libraries.Where(library => libraryIds.Contains(library.Id)));
|
||||
dbContext.SaveChanges();
|
||||
}
|
||||
foreach (string username in _seededUsernames)
|
||||
_apiFactory.RemoveTestUser(username);
|
||||
}
|
||||
}
|
||||
+211
@@ -0,0 +1,211 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Favorites;
|
||||
using Lumina.Presentation.Web.Common.Enums.Favorites;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Favorites.AddFavorite;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Favorites;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Favorites.AddFavorite;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="AddFavoriteEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddFavoriteEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string WEB_ROUTE = "/en-us/favorites/api-add-favorite";
|
||||
private const string UPSTREAM_ENDPOINT = "users/me/favorites";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly FavoriteDtoFixture _favoriteDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddFavoriteEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public AddFavoriteEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddFavorite_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client);
|
||||
HttpRequestMessage addRequest = CreateAddRequest(nameof(FavoriteMediaKind.MusicTrack), Guid.NewGuid().ToString(), antiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.SendAsync(addRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
|
||||
Assert.Empty(GetAddRequests());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddFavorite_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage addRequest = CreateAddRequest(nameof(FavoriteMediaKind.MusicTrack), Guid.NewGuid().ToString(), antiforgeryToken: null);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(addRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Empty(GetAddRequests());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddFavorite_WhenCalledWithInvalidAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage addRequest = CreateAddRequest(nameof(FavoriteMediaKind.MusicTrack), Guid.NewGuid().ToString(), "invalid-token");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(addRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Empty(GetAddRequests());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // basic SQL injection
|
||||
[InlineData("'; DROP TABLE Favorites--")] // destructive injection
|
||||
[InlineData("../../admin")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // script injection
|
||||
public async Task AddFavorite_WithInjectionPayloadInMediaKind_ShouldRejectItAndNotCallTheApi(string payload)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage addRequest = CreateAddRequest(payload, Guid.NewGuid().ToString(), webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(addRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
// The media kind is bound to an enum, so the crafted value is rejected before the endpoint executes and can never reach the API.
|
||||
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
Assert.Empty(GetAddRequests());
|
||||
Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // basic SQL injection
|
||||
[InlineData("'; DROP TABLE Favorites--")] // destructive injection
|
||||
[InlineData("../../admin")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // script injection
|
||||
public async Task AddFavorite_WithInjectionPayloadInMediaItemId_ShouldRejectItAndNotCallTheApi(string payload)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage addRequest = CreateAddRequest(nameof(FavoriteMediaKind.MusicTrack), payload, webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(addRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
// The media item Id is bound to a Guid, so the crafted value is rejected before the endpoint executes and can never reach the API.
|
||||
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
Assert.Empty(GetAddRequests());
|
||||
Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddFavorite_WhenCalledByAuthenticatedUserWithValidToken_ShouldNotLeakSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
FavoriteDto expectedFavorite = _favoriteDtoFixture.Create(mediaKind: FavoriteMediaKind.MusicTrack, mediaItemId: mediaItemId);
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse(UPSTREAM_ENDPOINT, expectedFavorite);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage addRequest = CreateAddRequest(nameof(FavoriteMediaKind.MusicTrack), mediaItemId.ToString(), webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(addRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Single(GetAddRequests());
|
||||
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the add favorite requests that were sent upstream, excluding the login request performed to authenticate the test client.
|
||||
/// </summary>
|
||||
/// <returns>The list of upstream add favorite requests that were sent.</returns>
|
||||
private List<(string Endpoint, object? Data)> GetAddRequests()
|
||||
{
|
||||
return [.. _apiFactory.ApiClientStub.PostRequests
|
||||
.Where(postRequest => postRequest.Endpoint == UPSTREAM_ENDPOINT)];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the add favorite request for the specified values.
|
||||
/// </summary>
|
||||
/// <param name="mediaKind">The value of the media kind body property.</param>
|
||||
/// <param name="mediaItemId">The value of the media item identifier body property.</param>
|
||||
/// <param name="antiforgeryToken">The antiforgery token to include in the request, or <see langword="null"/> to omit it.</param>
|
||||
/// <returns>The configured add favorite request.</returns>
|
||||
private static HttpRequestMessage CreateAddRequest(string mediaKind, string mediaItemId, string? antiforgeryToken)
|
||||
{
|
||||
string payload = JsonSerializer.Serialize(new { mediaKind, mediaItemId });
|
||||
HttpRequestMessage addRequest = new(HttpMethod.Post, WEB_ROUTE)
|
||||
{
|
||||
Content = new StringContent(payload, Encoding.UTF8, "application/json")
|
||||
};
|
||||
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
|
||||
addRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
addRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
if (antiforgeryToken is not null)
|
||||
addRequest.Headers.Add("RequestVerificationToken", antiforgeryToken);
|
||||
return addRequest;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
+160
@@ -0,0 +1,160 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Favorites;
|
||||
using Lumina.Presentation.Web.Common.Enums.Favorites;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Favorites.GetFavoriteStatus;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Favorites;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Favorites.GetFavoriteStatus;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetFavoriteStatusEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetFavoriteStatusEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string WEB_ROUTE = "/en-us/favorites/api-get-favorite-status";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly FavoriteStatusDtoFixture _favoriteStatusDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetFavoriteStatusEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetFavoriteStatusEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavoriteStatus_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.GetAsync($"{WEB_ROUTE}?mediaKind=MusicTrack&mediaItemIds={Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
|
||||
Assert.Empty(GetFavoriteStatusEndpointCalls());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // basic SQL injection
|
||||
[InlineData("'; DROP TABLE Favorites--")] // destructive injection
|
||||
[InlineData("../../admin")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // script injection
|
||||
public async Task GetFavoriteStatus_WithInjectionPayloadInMediaKind_ShouldRejectItAndNotCallTheApi(string payload)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"{WEB_ROUTE}?mediaKind={Uri.EscapeDataString(payload)}&mediaItemIds={Guid.NewGuid()}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
// The media kind is bound to an enum, so a crafted value is rejected before the endpoint executes and can never alter the upstream URL.
|
||||
// The model binding failure is returned through the application's JSON error envelope, so the test asserts the rejection and that the
|
||||
// value never reaches the API.
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Empty(GetFavoriteStatusEndpointCalls());
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // basic SQL injection
|
||||
[InlineData("'; DROP TABLE Favorites--")] // destructive injection
|
||||
[InlineData("../../admin")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // script injection
|
||||
public async Task GetFavoriteStatus_WithInjectionPayloadInMediaItemIds_ShouldRejectItAndNotCallTheApi(string payload)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"{WEB_ROUTE}?mediaKind=MusicTrack&mediaItemIds={Uri.EscapeDataString(payload)}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
// The media item Ids are bound to Guids, so a crafted value is rejected before the endpoint executes and can never alter the upstream URL.
|
||||
// The model binding failure is returned through the application's JSON error envelope, so the test asserts the rejection and that the
|
||||
// value never reaches the API.
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Empty(GetFavoriteStatusEndpointCalls());
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavoriteStatus_WhenCalledByAuthenticatedUser_ShouldReturnPrivateNoStoreResponseWithoutLeakingInternals()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
List<Guid> mediaItemIds = [Guid.NewGuid(), Guid.NewGuid()];
|
||||
string expectedUpstreamEndpoint = $"users/me/favorites/status?mediaKind=MusicTrack&mediaItemIds={mediaItemIds[0]}&mediaItemIds={mediaItemIds[1]}";
|
||||
FavoriteStatusDto expectedStatus = _favoriteStatusDtoFixture.Create(favoritedMediaItemIds: [mediaItemIds[0]]);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(expectedUpstreamEndpoint, expectedStatus);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(
|
||||
$"{WEB_ROUTE}?mediaKind=MusicTrack&mediaItemIds={mediaItemIds[0]}&mediaItemIds={mediaItemIds[1]}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.True(response.Headers.CacheControl?.Private);
|
||||
Assert.True(response.Headers.CacheControl?.NoStore);
|
||||
Assert.Contains("Cookie", response.Headers.Vary);
|
||||
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
Assert.Equal([expectedUpstreamEndpoint], GetFavoriteStatusEndpointCalls());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the favorite status endpoints that were called upstream, excluding the requests made to authenticate the test client.
|
||||
/// </summary>
|
||||
/// <returns>The list of upstream favorite status endpoints that were called.</returns>
|
||||
private List<string> GetFavoriteStatusEndpointCalls()
|
||||
{
|
||||
return [.. _apiFactory.ApiClientStub.GetEndpointsCalled
|
||||
.Where(endpoint => endpoint.StartsWith("users/me/favorites/status", StringComparison.Ordinal))];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
+161
@@ -0,0 +1,161 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Favorites;
|
||||
using Lumina.Presentation.Web.Common.Enums.Favorites;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Favorites.GetFavorites;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Favorites;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Favorites.GetFavorites;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetFavoritesEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetFavoritesEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string WEB_ROUTE = "/en-us/favorites/api-get-favorites";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly PaginatedDtoFixture<FavoriteItemDto> _paginatedDtoFixture = new();
|
||||
private readonly FavoriteItemDtoFixture _favoriteItemDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetFavoritesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetFavoritesEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavorites_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.GetAsync(WEB_ROUTE);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
|
||||
Assert.Empty(GetFavoritesEndpointCalls());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // basic SQL injection
|
||||
[InlineData("'; DROP TABLE Favorites--")] // destructive injection
|
||||
[InlineData("../../admin")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // script injection
|
||||
public async Task GetFavorites_WithInjectionPayloadInMediaKind_ShouldRejectItAndNotCallTheApi(string payload)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"{WEB_ROUTE}?mediaKind={Uri.EscapeDataString(payload)}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
// The media kind is bound to an enum, so a crafted value is rejected before the endpoint executes and can never alter the upstream URL.
|
||||
// The model binding failure is returned through the application's JSON error envelope, so the test asserts the rejection and that the
|
||||
// value never reaches the API.
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Empty(GetFavoritesEndpointCalls());
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("currentPage", "' OR '1'='1")] // basic SQL injection in the page number
|
||||
[InlineData("currentPage", "1;DROP TABLE Favorites")] // destructive injection in the page number
|
||||
[InlineData("perPage", "' OR '1'='1")] // basic SQL injection in the page size
|
||||
[InlineData("perPage", "../../admin")] // path traversal in the page size
|
||||
public async Task GetFavorites_WithInjectionPayloadInPagination_ShouldRejectItAndNotCallTheApi(string parameterName, string payload)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"{WEB_ROUTE}?{parameterName}={Uri.EscapeDataString(payload)}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
// The page bounds are bound to integers and rebuilt from the typed values, so a crafted value is rejected before the endpoint executes.
|
||||
// The model binding failure is returned through the application's JSON error envelope, so the test asserts the rejection and that the
|
||||
// value never reaches the API.
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Empty(GetFavoritesEndpointCalls());
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavorites_WhenCalledByAuthenticatedUser_ShouldReturnPrivateNoStoreResponseWithoutLeakingInternals()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
FavoriteItemDto expectedItem = _favoriteItemDtoFixture.Create(mediaKind: FavoriteMediaKind.MusicTrack);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(
|
||||
"users/me/favorites?currentPage=1&perPage=200",
|
||||
_paginatedDtoFixture.Create(data: [expectedItem], currentPage: 1, perPage: 200, count: 1, numberOfPages: 1));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(WEB_ROUTE);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.True(response.Headers.CacheControl?.Private);
|
||||
Assert.True(response.Headers.CacheControl?.NoStore);
|
||||
Assert.Contains("Cookie", response.Headers.Vary);
|
||||
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
Assert.Equal(["users/me/favorites?currentPage=1&perPage=200"], GetFavoritesEndpointCalls());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the favorites endpoints that were called upstream, excluding the requests made to authenticate the test client.
|
||||
/// </summary>
|
||||
/// <returns>The list of upstream favorites endpoints that were called.</returns>
|
||||
private List<string> GetFavoritesEndpointCalls()
|
||||
{
|
||||
return [.. _apiFactory.ApiClientStub.GetEndpointsCalled
|
||||
.Where(endpoint => endpoint.StartsWith("users/me/favorites", StringComparison.Ordinal))];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Favorites.Index;
|
||||
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.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Favorites.Index;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="FavoritesIndexViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FavoritesIndexViewEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string WEB_ROUTE = "/en-us/favorites";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="FavoritesIndexViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public FavoritesIndexViewEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FavoritesIndexView_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.GetAsync(WEB_ROUTE);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
|
||||
Assert.Empty(_apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FavoritesIndexView_WhenCalledByAuthenticatedUser_ShouldNotLeakTokensOrInternals()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(WEB_ROUTE);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Contains("favorites-container", content, StringComparison.Ordinal);
|
||||
Assert.True(response.Headers.CacheControl?.Private);
|
||||
Assert.True(response.Headers.CacheControl?.NoStore);
|
||||
Assert.Contains("no-store", string.Join(", ", response.Headers.GetValues("Cache-Control")), StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains("Cookie", response.Headers.Vary);
|
||||
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("StackTrace", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("PasswordHash", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
+213
@@ -0,0 +1,213 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Enums.Favorites;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Favorites.RemoveFavorite;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
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.Favorites.RemoveFavorite;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="RemoveFavoriteEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RemoveFavoriteEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RemoveFavoriteEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public RemoveFavoriteEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveFavorite_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client);
|
||||
HttpRequestMessage removeRequest = CreateRemoveRequest(nameof(FavoriteMediaKind.MusicTrack), Guid.NewGuid().ToString(), antiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.SendAsync(removeRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
|
||||
Assert.Empty(GetRemoveEndpointCalls());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveFavorite_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage removeRequest = CreateRemoveRequest(nameof(FavoriteMediaKind.MusicTrack), Guid.NewGuid().ToString(), antiforgeryToken: null);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(removeRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Empty(GetRemoveEndpointCalls());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveFavorite_WhenCalledWithInvalidAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage removeRequest = CreateRemoveRequest(nameof(FavoriteMediaKind.MusicTrack), Guid.NewGuid().ToString(), "invalid-token");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(removeRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Empty(GetRemoveEndpointCalls());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // basic SQL injection
|
||||
[InlineData("'; DROP TABLE Favorites--")] // destructive injection
|
||||
[InlineData("../../admin")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // script injection
|
||||
[InlineData("MusicTrack/../../admin")] // path traversal through a valid media kind prefix
|
||||
public async Task RemoveFavorite_WithInjectionPayloadInMediaKind_ShouldSanitizeItAndNotForwardTheRawValue(string payload)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
string sanitizedEndpoint = $"users/me/favorites/Invalid/{mediaItemId}";
|
||||
_apiFactory.ApiClientStub.RegisterDeleteSuccess(sanitizedEndpoint);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage removeRequest = CreateRemoveRequest(Uri.EscapeDataString(payload), mediaItemId.ToString(), webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(removeRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
// The route values are normalized before they are substituted into the upstream URL, so a crafted value can never escape its URL segment.
|
||||
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
List<string> removeEndpoints = GetRemoveEndpointCalls();
|
||||
Assert.Equal([sanitizedEndpoint], removeEndpoints);
|
||||
Assert.DoesNotContain(payload, string.Join(",", removeEndpoints), StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(Uri.EscapeDataString(payload), string.Join(",", removeEndpoints), StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // basic SQL injection
|
||||
[InlineData("'; DROP TABLE Favorites--")] // destructive injection
|
||||
[InlineData("../../admin")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // script injection
|
||||
public async Task RemoveFavorite_WithInjectionPayloadInMediaItemId_ShouldSanitizeItAndNotForwardTheRawValue(string payload)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string sanitizedEndpoint = $"users/me/favorites/MusicTrack/{ZERO_GUID}";
|
||||
_apiFactory.ApiClientStub.RegisterDeleteSuccess(sanitizedEndpoint);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage removeRequest = CreateRemoveRequest(nameof(FavoriteMediaKind.MusicTrack), Uri.EscapeDataString(payload), webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(removeRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
List<string> removeEndpoints = GetRemoveEndpointCalls();
|
||||
Assert.Equal([sanitizedEndpoint], removeEndpoints);
|
||||
Assert.DoesNotContain(payload, string.Join(",", removeEndpoints), StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(Uri.EscapeDataString(payload), string.Join(",", removeEndpoints), StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveFavorite_WhenCalledByAuthenticatedUserWithValidToken_ShouldNotLeakSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
string expectedUpstreamEndpoint = $"users/me/favorites/MusicTrack/{mediaItemId}";
|
||||
_apiFactory.ApiClientStub.RegisterDeleteSuccess(expectedUpstreamEndpoint);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage removeRequest = CreateRemoveRequest(nameof(FavoriteMediaKind.MusicTrack), mediaItemId.ToString(), webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(removeRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal([expectedUpstreamEndpoint], GetRemoveEndpointCalls());
|
||||
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the remove favorite endpoints that were called upstream, excluding the requests made to authenticate the test client.
|
||||
/// </summary>
|
||||
/// <returns>The list of upstream remove favorite endpoints that were called.</returns>
|
||||
private List<string> GetRemoveEndpointCalls()
|
||||
{
|
||||
return [.. _apiFactory.ApiClientStub.DeleteEndpointsCalled
|
||||
.Where(endpoint => endpoint.StartsWith("users/me/favorites", StringComparison.Ordinal))];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the remove favorite request for the specified route values.
|
||||
/// </summary>
|
||||
/// <param name="mediaKind">The value of the media kind route segment.</param>
|
||||
/// <param name="mediaItemId">The value of the media item identifier route segment.</param>
|
||||
/// <param name="antiforgeryToken">The antiforgery token to include in the request, or <see langword="null"/> to omit it.</param>
|
||||
/// <returns>The configured remove favorite request.</returns>
|
||||
private static HttpRequestMessage CreateRemoveRequest(string mediaKind, string mediaItemId, string? antiforgeryToken)
|
||||
{
|
||||
HttpRequestMessage removeRequest = new(HttpMethod.Delete, $"/en-us/favorites/{mediaKind}/{mediaItemId}/api-remove-favorite")
|
||||
{
|
||||
// The front-end sends the JSON content type even for DELETE requests, which triggers the antiforgery validation.
|
||||
Content = new StringContent("{}", Encoding.UTF8, "application/json")
|
||||
};
|
||||
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
|
||||
removeRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
removeRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
if (antiforgeryToken is not null)
|
||||
removeRequest.Headers.Add("RequestVerificationToken", antiforgeryToken);
|
||||
return removeRequest;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Playlists;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Playlists.GetPlaylist;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Playlists;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Playlists.GetPlaylist;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetPlaylistEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPlaylistEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly PlaylistDtoFixture _playlistDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPlaylistEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetPlaylistEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaylist_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.GetAsync($"/en-us/playlists/item/{Guid.NewGuid()}/api-get-playlist");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
|
||||
Assert.Empty(_apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaylist_WhenCalledByAuthenticatedUser_ShouldBePrivateAndNotLeakSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
string expectedEndpoint = $"users/me/playlists/{playlistId}?currentPage=1&perPage=200";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, _playlistDtoFixture.Create(id: playlistId));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/playlists/item/{playlistId}/api-get-playlist");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal([expectedEndpoint], GetPlaylistEndpointCalls());
|
||||
Assert.True(response.Headers.CacheControl?.Private);
|
||||
Assert.True(response.Headers.CacheControl?.NoStore);
|
||||
Assert.Contains("Cookie", response.Headers.Vary);
|
||||
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaylist_WhenPlaylistIdIsNotAGuid_ShouldForwardTheEmptyGuidAndNotTheRawValue()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string sanitizedEndpoint = $"users/me/playlists/{ZERO_GUID}?currentPage=1&perPage=200";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(sanitizedEndpoint, _playlistDtoFixture.Create(id: Guid.Empty));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/playlists/item/not-a-guid/api-get-playlist");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
List<string> endpointCalls = GetPlaylistEndpointCalls();
|
||||
Assert.Equal([sanitizedEndpoint], endpointCalls);
|
||||
Assert.DoesNotContain("not-a-guid", string.Join(",", endpointCalls), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // basic SQL injection
|
||||
[InlineData("1;DROP TABLE")] // destructive injection
|
||||
[InlineData("../../admin")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
[InlineData("𝕡𝕝𝕒𝕪𝕝𝕚𝕤𝕥")] // unicode payload
|
||||
public async Task GetPlaylist_WithInjectionPayloadInPlaylistId_ShouldNormalizeItAndNotForwardTheRawValue(string payload)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string sanitizedEndpoint = $"users/me/playlists/{ZERO_GUID}?currentPage=1&perPage=200";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(sanitizedEndpoint, _playlistDtoFixture.Create(id: Guid.Empty));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/playlists/item/{Uri.EscapeDataString(payload)}/api-get-playlist");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
List<string> endpointCalls = GetPlaylistEndpointCalls();
|
||||
Assert.All(endpointCalls, endpoint => Assert.Equal(sanitizedEndpoint, endpoint));
|
||||
Assert.DoesNotContain(payload, string.Join(",", endpointCalls), StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(Uri.EscapeDataString(payload), string.Join(",", endpointCalls), StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the playlist endpoints that were called upstream, excluding the endpoints called by the authentication helpers.
|
||||
/// </summary>
|
||||
/// <returns>The list of upstream playlist endpoints that were called.</returns>
|
||||
private List<string> GetPlaylistEndpointCalls()
|
||||
{
|
||||
return [.. _apiFactory.ApiClientStub.GetEndpointsCalled
|
||||
.Where(endpoint => endpoint.StartsWith("users/me/playlists/", StringComparison.Ordinal))];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Playlists.Item;
|
||||
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.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Playlists.Item;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="AddPlaylistViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddPlaylistViewEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string WEB_ROUTE = "/en-us/playlists/item";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddPlaylistViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public AddPlaylistViewEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddPlaylistView_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.GetAsync(WEB_ROUTE);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
|
||||
Assert.Empty(_apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddPlaylistView_WhenCalledByAuthenticatedUser_ShouldNotLeakSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(WEB_ROUTE);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.True(response.Headers.CacheControl?.Private);
|
||||
Assert.True(response.Headers.CacheControl?.NoStore);
|
||||
Assert.Contains("no-store", string.Join(", ", response.Headers.GetValues("Cache-Control")), StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains("Cookie", response.Headers.Vary);
|
||||
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("TestPass123!", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
+155
@@ -0,0 +1,155 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Playlists;
|
||||
using Lumina.Presentation.Web.Common.Enums.Playlists;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Playlists.Item;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Playlists;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Playlists.Item;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="PlaylistItemViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PlaylistItemViewEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly PlaylistDtoFixture _playlistDtoFixture = new();
|
||||
private readonly PlaylistEntryDtoFixture _playlistEntryDtoFixture = new();
|
||||
private readonly PaginatedDtoFixture<PlaylistEntryDto> _paginatedDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PlaylistItemViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public PlaylistItemViewEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PlaylistItemView_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.GetAsync($"/en-us/playlists/item/{Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
|
||||
Assert.Empty(_apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PlaylistItemView_WhenCalledByAuthenticatedUser_ShouldBePrivateAndNotLeakSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
PlaylistEntryDto expectedEntry = _playlistEntryDtoFixture.Create(mediaItemType: PlaylistMediaItemType.MusicTrack);
|
||||
PlaylistDto expectedPlaylist = _playlistDtoFixture.Create(
|
||||
id: playlistId,
|
||||
entries: _paginatedDtoFixture.Create(data: [expectedEntry], currentPage: 1, perPage: 200, count: 1, numberOfPages: 1));
|
||||
string expectedEndpoint = $"users/me/playlists/{playlistId}?currentPage=1&perPage=200";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, expectedPlaylist);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/playlists/item/{playlistId}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal([expectedEndpoint], GetPlaylistEndpointCalls());
|
||||
Assert.True(response.Headers.CacheControl?.Private);
|
||||
Assert.True(response.Headers.CacheControl?.NoStore);
|
||||
Assert.Contains("no-store", string.Join(", ", response.Headers.GetValues("Cache-Control")), StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains("Cookie", response.Headers.Vary);
|
||||
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PlaylistItemView_WhenPlaylistIdIsNotAGuid_ShouldForwardTheEmptyGuidAndNotTheRawValue()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string sanitizedEndpoint = $"users/me/playlists/{ZERO_GUID}?currentPage=1&perPage=200";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(sanitizedEndpoint, _playlistDtoFixture.Create(id: Guid.Empty));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/playlists/item/not-a-guid");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
List<string> endpointCalls = GetPlaylistEndpointCalls();
|
||||
Assert.Equal([sanitizedEndpoint], endpointCalls);
|
||||
Assert.DoesNotContain("not-a-guid", string.Join(",", endpointCalls), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // basic SQL injection
|
||||
[InlineData("1;DROP TABLE")] // destructive injection
|
||||
[InlineData("../../admin")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
[InlineData("𝕡𝕝𝕒𝕪𝕝𝕚𝕤𝕥")] // unicode payload
|
||||
public async Task PlaylistItemView_WithInjectionPayloadInPlaylistId_ShouldNormalizeItAndNotForwardTheRawValue(string payload)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string sanitizedEndpoint = $"users/me/playlists/{ZERO_GUID}?currentPage=1&perPage=200";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(sanitizedEndpoint, _playlistDtoFixture.Create(id: Guid.Empty));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/playlists/item/{Uri.EscapeDataString(payload)}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
List<string> endpointCalls = GetPlaylistEndpointCalls();
|
||||
Assert.All(endpointCalls, endpoint => Assert.Equal(sanitizedEndpoint, endpoint));
|
||||
Assert.DoesNotContain(payload, string.Join(",", endpointCalls), StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(Uri.EscapeDataString(payload), string.Join(",", endpointCalls), StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the playlist endpoints that were called upstream, excluding the endpoints called by the authentication helpers.
|
||||
/// </summary>
|
||||
/// <returns>The list of upstream playlist endpoints that were called.</returns>
|
||||
private List<string> GetPlaylistEndpointCalls()
|
||||
{
|
||||
return [.. _apiFactory.ApiClientStub.GetEndpointsCalled
|
||||
.Where(endpoint => endpoint.StartsWith("users/me/playlists/", StringComparison.Ordinal))];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Mapping.Favorites;
|
||||
using Lumina.Application.Core.Favorites.Commands.AddFavorite;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Favorites;
|
||||
using Lumina.Contracts.Requests.Favorites;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="AddFavoriteRequestMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddFavoriteRequestMappingTests
|
||||
{
|
||||
private readonly AddFavoriteRequestFixture _addFavoriteRequestFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToCommand_WhenEveryMemberIsSupplied_ShouldPreserveThem()
|
||||
{
|
||||
// Arrange
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
AddFavoriteRequest request = _addFavoriteRequestFixture.Create(
|
||||
mediaKind: FavoriteMediaKind.Book,
|
||||
mediaItemId: mediaItemId);
|
||||
|
||||
// Act
|
||||
AddFavoriteCommand command = request.ToCommand();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(FavoriteMediaKind.Book, command.MediaKind);
|
||||
Assert.Equal(mediaItemId, command.MediaItemId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToCommand_WhenMediaKindIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteRequest request = _addFavoriteRequestFixture.Create(includeMediaKind: false);
|
||||
|
||||
// Act
|
||||
AddFavoriteCommand command = request.ToCommand();
|
||||
|
||||
// Assert
|
||||
Assert.Null(command.MediaKind);
|
||||
Assert.NotNull(command.MediaItemId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToCommand_WhenMediaItemIdIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteRequest request = _addFavoriteRequestFixture.Create(includeMediaItemId: false);
|
||||
|
||||
// Act
|
||||
AddFavoriteCommand command = request.ToCommand();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(command.MediaKind);
|
||||
Assert.Null(command.MediaItemId);
|
||||
}
|
||||
}
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Common.Mapping.Favorites;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Contracts.Responses.Favorites;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="FavoriteEntityMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FavoriteEntityMappingTests
|
||||
{
|
||||
private readonly FavoriteEntityFixture _favoriteEntityFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenUpdatedOnUtcIsPresent_ShouldMapEveryFieldAndTheUpdateTime()
|
||||
{
|
||||
// Arrange
|
||||
Guid id = Guid.NewGuid();
|
||||
Guid userId = Guid.NewGuid();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
DateTime createdOnUtc = new(2024, 3, 1, 10, 0, 0, DateTimeKind.Utc);
|
||||
DateTime updatedOnUtc = new(2024, 3, 2, 11, 30, 0, DateTimeKind.Utc);
|
||||
FavoriteEntity entity = _favoriteEntityFixture.Create(
|
||||
id: id,
|
||||
userId: userId,
|
||||
mediaKind: FavoriteMediaKind.MusicAlbum,
|
||||
mediaItemId: mediaItemId,
|
||||
createdOnUtc: createdOnUtc,
|
||||
updatedOnUtc: updatedOnUtc);
|
||||
|
||||
// Act
|
||||
Result<Favorite> result = entity.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Favorite favorite = result.Value;
|
||||
Assert.Equal(id, favorite.Id.Value);
|
||||
Assert.Equal(userId, favorite.UserId.Value);
|
||||
Assert.Equal(mediaItemId, favorite.MediaItemId.Value);
|
||||
Assert.Equal(FavoriteMediaKind.MusicAlbum, favorite.MediaKind);
|
||||
Assert.Equal(createdOnUtc, favorite.CreatedOnUtc);
|
||||
Assert.True(favorite.UpdatedOnUtc.HasValue);
|
||||
Assert.Equal(updatedOnUtc, favorite.UpdatedOnUtc.Value);
|
||||
Assert.False(favorite.IsRemoved);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenUpdatedOnUtcIsMissing_ShouldMapNoUpdateTime()
|
||||
{
|
||||
// Arrange
|
||||
FavoriteEntity entity = _favoriteEntityFixture.Create(includeUpdatedOnUtc: false);
|
||||
|
||||
// Act
|
||||
Result<Favorite> result = entity.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.False(result.Value.UpdatedOnUtc.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenTheStoredMediaKindIsNotSupportedToday_ShouldStillRehydrateIt()
|
||||
{
|
||||
// Arrange
|
||||
FavoriteEntity entity = _favoriteEntityFixture.Create(mediaKind: FavoriteMediaKind.Video);
|
||||
|
||||
// Act
|
||||
Result<Favorite> result = entity.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal(FavoriteMediaKind.Video, result.Value.MediaKind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenMappingTheId_ShouldKeepTheSameIdentifier()
|
||||
{
|
||||
// Arrange
|
||||
Guid id = Guid.NewGuid();
|
||||
FavoriteEntity entity = _favoriteEntityFixture.Create(id: id);
|
||||
|
||||
// Act
|
||||
Result<Favorite> result = entity.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal(id, result.Value.Id.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenMappingTheEntity_ShouldMapEveryField()
|
||||
{
|
||||
// Arrange
|
||||
Guid id = Guid.NewGuid();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
DateTime createdOnUtc = new(2024, 6, 7, 8, 9, 10, DateTimeKind.Utc);
|
||||
FavoriteEntity entity = _favoriteEntityFixture.Create(
|
||||
id: id,
|
||||
mediaKind: FavoriteMediaKind.Book,
|
||||
mediaItemId: mediaItemId,
|
||||
createdOnUtc: createdOnUtc);
|
||||
|
||||
// Act
|
||||
FavoriteResponse response = entity.ToResponse();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(id, response.Id);
|
||||
Assert.Equal(FavoriteMediaKind.Book, response.MediaKind);
|
||||
Assert.Equal(mediaItemId, response.MediaItemId);
|
||||
Assert.Equal(createdOnUtc, response.FavoritedOnUtc);
|
||||
}
|
||||
}
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Common.DTO.Favorites;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Common.Mapping.Favorites;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Fixtures.Common.DTO.Favorites;
|
||||
using Lumina.Application.Fixtures.Common.DTO.Pagination;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
using Lumina.Contracts.Responses.Favorites;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="FavoriteItemDtoMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FavoriteItemDtoMappingTests
|
||||
{
|
||||
private readonly FavoriteEntityFixture _favoriteEntityFixture = new();
|
||||
private readonly FavoriteItemDtoFixture _favoriteItemDtoFixture = new();
|
||||
private readonly FavoriteItemDisplayDtoFixture _favoriteItemDisplayDtoFixture = new();
|
||||
private readonly PaginatedResultDtoFixture<FavoriteItemDto> _paginatedResultDtoFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenDisplayIsMissing_ShouldReturnAnUnavailableItemWithEmptyDisplayFields()
|
||||
{
|
||||
// Arrange
|
||||
FavoriteEntity favorite = _favoriteEntityFixture.Create(mediaKind: FavoriteMediaKind.MusicTrack);
|
||||
FavoriteItemDto item = _favoriteItemDtoFixture.Create(favorite: favorite, includeDisplay: false);
|
||||
|
||||
// Act
|
||||
FavoriteItemResponse response = item.ToResponse();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(favorite.MediaKind, response.MediaKind);
|
||||
Assert.Equal(favorite.MediaItemId, response.MediaItemId);
|
||||
Assert.False(response.IsAvailable);
|
||||
Assert.Equal(Guid.Empty, response.LibraryId);
|
||||
Assert.Equal(string.Empty, response.Title);
|
||||
Assert.Equal(Guid.Empty, response.CollectionId);
|
||||
Assert.Equal(string.Empty, response.CollectionTitle);
|
||||
Assert.Equal(Guid.Empty, response.CreatorId);
|
||||
Assert.Equal(string.Empty, response.CreatorName);
|
||||
Assert.Null(response.CoverPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenDisplayIsPresent_ShouldMapEveryDisplayField()
|
||||
{
|
||||
// Arrange
|
||||
FavoriteEntity favorite = _favoriteEntityFixture.Create(mediaKind: FavoriteMediaKind.MusicAlbum);
|
||||
FavoriteItemDisplayDto display = _favoriteItemDisplayDtoFixture.Create();
|
||||
FavoriteItemDto item = _favoriteItemDtoFixture.Create(favorite: favorite, display: display);
|
||||
|
||||
// Act
|
||||
FavoriteItemResponse response = item.ToResponse();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(favorite.MediaKind, response.MediaKind);
|
||||
Assert.Equal(favorite.MediaItemId, response.MediaItemId);
|
||||
Assert.True(response.IsAvailable);
|
||||
Assert.Equal(display.LibraryId, response.LibraryId);
|
||||
Assert.Equal(display.Title, response.Title);
|
||||
Assert.Equal(display.CollectionId, response.CollectionId);
|
||||
Assert.Equal(display.CollectionTitle, response.CollectionTitle);
|
||||
Assert.Equal(display.CreatorId, response.CreatorId);
|
||||
Assert.Equal(display.CreatorName, response.CreatorName);
|
||||
Assert.Equal(display.CoverPath, response.CoverPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenDisplayHasNoCoverPath_ShouldMapNullCoverPath()
|
||||
{
|
||||
// Arrange
|
||||
FavoriteItemDisplayDto display = _favoriteItemDisplayDtoFixture.Create(includeCoverPath: false);
|
||||
FavoriteItemDto item = _favoriteItemDtoFixture.Create(display: display);
|
||||
|
||||
// Act
|
||||
FavoriteItemResponse response = item.ToResponse();
|
||||
|
||||
// Assert
|
||||
Assert.True(response.IsAvailable);
|
||||
Assert.Null(response.CoverPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponses_WhenMappingAPage_ShouldPreserveTheOrderOfTheItemsAndThePaginationMetadata()
|
||||
{
|
||||
// Arrange
|
||||
FavoriteItemDto firstItem = _favoriteItemDtoFixture.Create(favorite: _favoriteEntityFixture.Create());
|
||||
FavoriteItemDto secondItem = _favoriteItemDtoFixture.Create(favorite: _favoriteEntityFixture.Create());
|
||||
FavoriteItemDto thirdItem = _favoriteItemDtoFixture.Create(favorite: _favoriteEntityFixture.Create(), includeDisplay: false);
|
||||
List<FavoriteItemDto> items = [firstItem, secondItem, thirdItem];
|
||||
PaginatedResultDto<FavoriteItemDto> page = _paginatedResultDtoFixture.Create(
|
||||
data: items,
|
||||
currentPage: 2,
|
||||
perPage: 3,
|
||||
count: 8,
|
||||
numberOfPages: 3);
|
||||
|
||||
// Act
|
||||
PaginatedResponse<FavoriteItemResponse> response = page.ToResponses();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(3, response.Data.Count);
|
||||
Assert.Equal(
|
||||
items.Select(item => item.Favorite.MediaItemId),
|
||||
response.Data.Select(item => item.MediaItemId));
|
||||
Assert.True(response.Data[0].IsAvailable);
|
||||
Assert.True(response.Data[1].IsAvailable);
|
||||
Assert.False(response.Data[2].IsAvailable);
|
||||
Assert.Equal(2, response.CurrentPage);
|
||||
Assert.Equal(3, response.PerPage);
|
||||
Assert.Equal(8, response.Count);
|
||||
Assert.Equal(3, response.NumberOfPages);
|
||||
}
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Common.Mapping.Favorites;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="FavoriteMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FavoriteMappingTests
|
||||
{
|
||||
private readonly FavoriteFixture _favoriteFixture = new();
|
||||
private readonly FavoriteIdFixture _favoriteIdFixture = new();
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
private readonly MediaItemIdFixture _mediaItemIdFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToRepositoryEntity_WhenUpdatedOnUtcIsPresent_ShouldMapEveryFieldAndTheAuditColumns()
|
||||
{
|
||||
// Arrange
|
||||
Guid id = Guid.NewGuid();
|
||||
Guid userId = Guid.NewGuid();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
DateTime createdOnUtc = new(2024, 2, 3, 4, 5, 6, DateTimeKind.Utc);
|
||||
DateTime updatedOnUtc = new(2024, 2, 4, 5, 6, 7, DateTimeKind.Utc);
|
||||
Favorite favorite = _favoriteFixture.Create(
|
||||
id: _favoriteIdFixture.Create(id),
|
||||
userId: _userIdFixture.Create(userId),
|
||||
mediaItemId: _mediaItemIdFixture.Create(mediaItemId),
|
||||
mediaKind: FavoriteMediaKind.Book,
|
||||
createdOnUtc: createdOnUtc,
|
||||
updatedOnUtc: Optional<DateTime>.Some(updatedOnUtc));
|
||||
|
||||
// Act
|
||||
FavoriteEntity entity = favorite.ToRepositoryEntity();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(id, entity.Id);
|
||||
Assert.Equal(userId, entity.UserId);
|
||||
Assert.Equal(FavoriteMediaKind.Book, entity.MediaKind);
|
||||
Assert.Equal(mediaItemId, entity.MediaItemId);
|
||||
Assert.Equal(createdOnUtc, entity.CreatedOnUtc);
|
||||
Assert.Equal(Guid.Empty, entity.CreatedBy);
|
||||
Assert.True(entity.UpdatedOnUtc.HasValue);
|
||||
Assert.Equal(updatedOnUtc, entity.UpdatedOnUtc.Value);
|
||||
Assert.Null(entity.UpdatedBy);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToRepositoryEntity_WhenUpdatedOnUtcIsMissing_ShouldMapNullUpdatedOnUtc()
|
||||
{
|
||||
// Arrange
|
||||
Favorite favorite = _favoriteFixture.Create(includeUpdatedOnUtc: false);
|
||||
|
||||
// Act
|
||||
FavoriteEntity entity = favorite.ToRepositoryEntity();
|
||||
|
||||
// Assert
|
||||
Assert.Null(entity.UpdatedOnUtc);
|
||||
Assert.Null(entity.UpdatedBy);
|
||||
Assert.Equal(Guid.Empty, entity.CreatedBy);
|
||||
}
|
||||
}
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Mapping.Favorites;
|
||||
using Lumina.Application.Core.Favorites.Queries.GetFavoriteStatus;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Favorites;
|
||||
using Lumina.Contracts.Requests.Favorites;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetFavoriteStatusRequestMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetFavoriteStatusRequestMappingTests
|
||||
{
|
||||
private readonly GetFavoriteStatusRequestFixture _getFavoriteStatusRequestFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenEveryMemberIsSupplied_ShouldPreserveTheKindAndTheMediaItemIdOrder()
|
||||
{
|
||||
// Arrange
|
||||
Guid firstId = Guid.NewGuid();
|
||||
Guid secondId = Guid.NewGuid();
|
||||
Guid thirdId = Guid.NewGuid();
|
||||
List<Guid> mediaItemIds = [firstId, secondId, thirdId];
|
||||
GetFavoriteStatusRequest request = _getFavoriteStatusRequestFixture.Create(
|
||||
mediaKind: FavoriteMediaKind.MusicAlbum,
|
||||
mediaItemIds: mediaItemIds);
|
||||
|
||||
// Act
|
||||
GetFavoriteStatusQuery query = request.ToQuery();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(FavoriteMediaKind.MusicAlbum, query.MediaKind);
|
||||
Assert.NotNull(query.MediaItemIds);
|
||||
Assert.Equal<Guid>(mediaItemIds, query.MediaItemIds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenMediaKindIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Arrange
|
||||
GetFavoriteStatusRequest request = _getFavoriteStatusRequestFixture.Create(includeMediaKind: false);
|
||||
|
||||
// Act
|
||||
GetFavoriteStatusQuery query = request.ToQuery();
|
||||
|
||||
// Assert
|
||||
Assert.Null(query.MediaKind);
|
||||
Assert.NotNull(query.MediaItemIds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenMediaItemIdsAreNull_ShouldPreserveNull()
|
||||
{
|
||||
// Arrange
|
||||
GetFavoriteStatusRequest request = _getFavoriteStatusRequestFixture.Create(includeMediaItemIds: false);
|
||||
|
||||
// Act
|
||||
GetFavoriteStatusQuery query = request.ToQuery();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(query.MediaKind);
|
||||
Assert.Null(query.MediaItemIds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenMediaItemIdsAreEmpty_ShouldPreserveTheEmptyList()
|
||||
{
|
||||
// Arrange
|
||||
GetFavoriteStatusRequest request = _getFavoriteStatusRequestFixture.Create(mediaItemIds: []);
|
||||
|
||||
// Act
|
||||
GetFavoriteStatusQuery query = request.ToQuery();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(query.MediaItemIds);
|
||||
Assert.Empty(query.MediaItemIds);
|
||||
}
|
||||
}
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Mapping.Favorites;
|
||||
using Lumina.Application.Core.Favorites.Queries.GetFavorites;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Favorites;
|
||||
using Lumina.Contracts.Requests.Favorites;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetFavoritesRequestMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetFavoritesRequestMappingTests
|
||||
{
|
||||
private readonly GetFavoritesRequestFixture _getFavoritesRequestFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenBothPaginationValuesAreOmitted_ShouldLeaveThePaginationDataNullAndPreserveTheMediaKind()
|
||||
{
|
||||
// Arrange
|
||||
GetFavoritesRequest request = _getFavoritesRequestFixture.Create(
|
||||
mediaKind: FavoriteMediaKind.MusicArtist,
|
||||
includeCurrentPage: false,
|
||||
includePerPage: false);
|
||||
|
||||
// Act
|
||||
GetFavoritesQuery query = request.ToQuery();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(FavoriteMediaKind.MusicArtist, query.MediaKind);
|
||||
Assert.Null(query.PaginationData);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenOnlyCurrentPageIsSupplied_ShouldPreserveItAndDefaultPerPageToTwoHundred()
|
||||
{
|
||||
// Arrange
|
||||
GetFavoritesRequest request = _getFavoritesRequestFixture.Create(
|
||||
currentPage: 42,
|
||||
includePerPage: false);
|
||||
|
||||
// Act
|
||||
GetFavoritesQuery query = request.ToQuery();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(query.PaginationData);
|
||||
Assert.Equal(42, query.PaginationData.CurrentPage);
|
||||
Assert.Equal(200, query.PaginationData.PerPage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenOnlyPerPageIsSupplied_ShouldPreserveItAndDefaultCurrentPageToOne()
|
||||
{
|
||||
// Arrange
|
||||
GetFavoritesRequest request = _getFavoritesRequestFixture.Create(
|
||||
perPage: 7,
|
||||
includeCurrentPage: false);
|
||||
|
||||
// Act
|
||||
GetFavoritesQuery query = request.ToQuery();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(query.PaginationData);
|
||||
Assert.Equal(1, query.PaginationData.CurrentPage);
|
||||
Assert.Equal(7, query.PaginationData.PerPage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenBothPaginationValuesAreSupplied_ShouldPreserveThem()
|
||||
{
|
||||
// Arrange
|
||||
GetFavoritesRequest request = _getFavoritesRequestFixture.Create(currentPage: 3, perPage: 25);
|
||||
|
||||
// Act
|
||||
GetFavoritesQuery query = request.ToQuery();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(query.PaginationData);
|
||||
Assert.Equal(3, query.PaginationData.CurrentPage);
|
||||
Assert.Equal(25, query.PaginationData.PerPage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenPaginationValuesAreBelowOne_ShouldClampThemToOne()
|
||||
{
|
||||
// Arrange
|
||||
GetFavoritesRequest request = _getFavoritesRequestFixture.Create(currentPage: 0, perPage: -5);
|
||||
|
||||
// Act
|
||||
GetFavoritesQuery query = request.ToQuery();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(query.PaginationData);
|
||||
Assert.Equal(1, query.PaginationData.CurrentPage);
|
||||
Assert.Equal(1, query.PaginationData.PerPage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenMediaKindIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Arrange
|
||||
GetFavoritesRequest request = _getFavoritesRequestFixture.Create(includeMediaKind: false);
|
||||
|
||||
// Act
|
||||
GetFavoritesQuery query = request.ToQuery();
|
||||
|
||||
// Assert
|
||||
Assert.Null(query.MediaKind);
|
||||
Assert.NotNull(query.PaginationData);
|
||||
}
|
||||
}
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Mapping.Playlists;
|
||||
using Lumina.Application.Core.Playlists.Queries.GetPlaylist;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Playlists;
|
||||
using Lumina.Contracts.Requests.Playlists;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetPlaylistRequestMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPlaylistRequestMappingTests
|
||||
{
|
||||
private readonly GetPlaylistRequestFixture _getPlaylistRequestFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenBothPaginationValuesAreOmitted_ShouldLeaveThePaginationDataNullAndPreserveThePlaylistId()
|
||||
{
|
||||
// Arrange
|
||||
string playlistId = Guid.NewGuid().ToString();
|
||||
GetPlaylistRequest request = _getPlaylistRequestFixture.Create(
|
||||
includeCurrentPage: false,
|
||||
includePerPage: false);
|
||||
|
||||
// Act
|
||||
GetPlaylistQuery query = request.ToQuery(playlistId);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(playlistId, query.PlaylistId);
|
||||
Assert.Null(query.PaginationData);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenOnlyCurrentPageIsSupplied_ShouldPreserveItAndDefaultPerPageToTwoHundred()
|
||||
{
|
||||
// Arrange
|
||||
GetPlaylistRequest request = _getPlaylistRequestFixture.Create(
|
||||
currentPage: 42,
|
||||
includePerPage: false);
|
||||
string playlistId = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
GetPlaylistQuery query = request.ToQuery(playlistId);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(query.PaginationData);
|
||||
Assert.Equal(42, query.PaginationData.CurrentPage);
|
||||
Assert.Equal(200, query.PaginationData.PerPage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenOnlyPerPageIsSupplied_ShouldPreserveItAndDefaultCurrentPageToOne()
|
||||
{
|
||||
// Arrange
|
||||
GetPlaylistRequest request = _getPlaylistRequestFixture.Create(
|
||||
perPage: 7,
|
||||
includeCurrentPage: false);
|
||||
string playlistId = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
GetPlaylistQuery query = request.ToQuery(playlistId);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(query.PaginationData);
|
||||
Assert.Equal(1, query.PaginationData.CurrentPage);
|
||||
Assert.Equal(7, query.PaginationData.PerPage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenBothPaginationValuesAreSupplied_ShouldPreserveThem()
|
||||
{
|
||||
// Arrange
|
||||
GetPlaylistRequest request = _getPlaylistRequestFixture.Create(currentPage: 3, perPage: 25);
|
||||
string playlistId = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
GetPlaylistQuery query = request.ToQuery(playlistId);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(query.PaginationData);
|
||||
Assert.Equal(3, query.PaginationData.CurrentPage);
|
||||
Assert.Equal(25, query.PaginationData.PerPage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenPaginationValuesAreBelowOne_ShouldClampThemToOne()
|
||||
{
|
||||
// Arrange
|
||||
GetPlaylistRequest request = _getPlaylistRequestFixture.Create(currentPage: 0, perPage: -5);
|
||||
string playlistId = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
GetPlaylistQuery query = request.ToQuery(playlistId);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(query.PaginationData);
|
||||
Assert.Equal(1, query.PaginationData.CurrentPage);
|
||||
Assert.Equal(1, query.PaginationData.PerPage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenPlaylistIdIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Arrange
|
||||
GetPlaylistRequest request = _getPlaylistRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
GetPlaylistQuery query = request.ToQuery(null);
|
||||
|
||||
// Assert
|
||||
Assert.Null(query.PlaylistId);
|
||||
Assert.NotNull(query.PaginationData);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenPlaylistIdIsEmpty_ShouldPreserveEmpty()
|
||||
{
|
||||
// Arrange
|
||||
GetPlaylistRequest request = _getPlaylistRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
GetPlaylistQuery query = request.ToQuery(string.Empty);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(string.Empty, query.PlaylistId);
|
||||
}
|
||||
}
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Playlists;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Common.DTO.Playlists;
|
||||
using Lumina.Application.Common.Mapping.Playlists;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Playlists;
|
||||
using Lumina.Application.Fixtures.Common.DTO.Pagination;
|
||||
using Lumina.Application.Fixtures.Common.DTO.Playlists;
|
||||
using Lumina.Contracts.Responses.Playlists;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="PlaylistDetailsDtoMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PlaylistDetailsDtoMappingTests
|
||||
{
|
||||
private readonly PlaylistEntityFixture _playlistEntityFixture = new();
|
||||
private readonly PlaylistEntryDtoFixture _playlistEntryDtoFixture = new();
|
||||
private readonly PlaylistDetailsDtoFixture _playlistDetailsDtoFixture = new();
|
||||
private readonly PaginatedResultDtoFixture<PlaylistEntryDto> _paginatedResultDtoFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenMappingPlaylistDetails_ShouldMapThePlaylistFieldsAndThePaginatedEntries()
|
||||
{
|
||||
// Arrange
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
DateTime createdOnUtc = new(2024, 4, 5, 6, 7, 8, DateTimeKind.Utc);
|
||||
DateTime updatedOnUtc = new(2024, 4, 6, 7, 8, 9, DateTimeKind.Utc);
|
||||
PlaylistEntity playlist = _playlistEntityFixture.Create(
|
||||
id: playlistId,
|
||||
name: "Evening",
|
||||
description: "Wind down",
|
||||
type: PlaylistType.Music,
|
||||
createdOnUtc: createdOnUtc,
|
||||
includeUpdatedOnUtc: true,
|
||||
updatedOnUtc: updatedOnUtc);
|
||||
PlaylistEntryDto entry = _playlistEntryDtoFixture.Create(displayPosition: 0);
|
||||
List<PlaylistEntryDto> entries = [entry];
|
||||
PaginatedResultDto<PlaylistEntryDto> entryPage = _paginatedResultDtoFixture.Create(
|
||||
data: entries,
|
||||
currentPage: 2,
|
||||
perPage: 50,
|
||||
count: 51,
|
||||
numberOfPages: 2);
|
||||
PlaylistDetailsDto details = _playlistDetailsDtoFixture.Create(playlist: playlist, entries: entryPage);
|
||||
|
||||
// Act
|
||||
PlaylistResponse response = details.ToResponse();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(playlistId, response.Id);
|
||||
Assert.Equal("Evening", response.Name);
|
||||
Assert.Equal("Wind down", response.Description);
|
||||
Assert.Equal(PlaylistType.Music, response.Type);
|
||||
Assert.Equal(createdOnUtc, response.CreatedOnUtc);
|
||||
Assert.True(response.UpdatedOnUtc.HasValue);
|
||||
Assert.Equal(updatedOnUtc, response.UpdatedOnUtc.Value);
|
||||
PlaylistEntryResponse entryResponse = Assert.Single(response.Entries.Data);
|
||||
Assert.Equal(entry.Entry.Id, entryResponse.Id);
|
||||
Assert.Equal(2, response.Entries.CurrentPage);
|
||||
Assert.Equal(50, response.Entries.PerPage);
|
||||
Assert.Equal(51, response.Entries.Count);
|
||||
Assert.Equal(2, response.Entries.NumberOfPages);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenDescriptionAndUpdatedOnUtcAreMissing_ShouldMapNulls()
|
||||
{
|
||||
// Arrange
|
||||
PlaylistEntity playlist = _playlistEntityFixture.Create(
|
||||
includeDescription: false,
|
||||
includeUpdatedOnUtc: false);
|
||||
PlaylistDetailsDto details = _playlistDetailsDtoFixture.Create(
|
||||
playlist: playlist,
|
||||
entries: _paginatedResultDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
PlaylistResponse response = details.ToResponse();
|
||||
|
||||
// Assert
|
||||
Assert.Null(response.Description);
|
||||
Assert.Null(response.UpdatedOnUtc);
|
||||
}
|
||||
}
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Playlists;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Common.DTO.Playlists;
|
||||
using Lumina.Application.Common.Mapping.Playlists;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Playlists;
|
||||
using Lumina.Application.Fixtures.Common.DTO.Pagination;
|
||||
using Lumina.Application.Fixtures.Common.DTO.Playlists;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
using Lumina.Contracts.Responses.Playlists;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="PlaylistEntryDtoMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PlaylistEntryDtoMappingTests
|
||||
{
|
||||
private readonly PlaylistEntryEntityFixture _playlistEntryEntityFixture = new();
|
||||
private readonly PlaylistEntryDtoFixture _playlistEntryDtoFixture = new();
|
||||
private readonly PlaylistEntryDisplayDtoFixture _playlistEntryDisplayDtoFixture = new();
|
||||
private readonly PaginatedResultDtoFixture<PlaylistEntryDto> _paginatedResultDtoFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenDisplayIsMissing_ShouldReturnTheStoredEntryWithEmptyDisplayFields()
|
||||
{
|
||||
// Arrange
|
||||
PlaylistEntryEntity entity = _playlistEntryEntityFixture.Create();
|
||||
PlaylistEntryDto entry = _playlistEntryDtoFixture.Create(entry: entity, displayPosition: 3, includeDisplay: false);
|
||||
|
||||
// Act
|
||||
PlaylistEntryResponse response = entry.ToResponse();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(entity.Id, response.Id);
|
||||
Assert.Equal(entity.MediaItemId, response.MediaItemId);
|
||||
Assert.Equal(entity.MediaItemType, response.MediaItemType);
|
||||
Assert.Equal(3, response.Position);
|
||||
Assert.Equal(Guid.Empty, response.LibraryId);
|
||||
Assert.Equal(Guid.Empty, response.CollectionId);
|
||||
Assert.Equal(Guid.Empty, response.CreatorId);
|
||||
Assert.Equal(string.Empty, response.MediaItemTitle);
|
||||
Assert.Equal(string.Empty, response.CollectionTitle);
|
||||
Assert.Equal(string.Empty, response.CreatorName);
|
||||
Assert.Equal(0, response.DurationInSeconds);
|
||||
Assert.Null(response.CoverPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenDisplayIsPresent_ShouldMapEveryDisplayField()
|
||||
{
|
||||
// Arrange
|
||||
PlaylistEntryEntity entity = _playlistEntryEntityFixture.Create();
|
||||
PlaylistEntryDisplayDto display = _playlistEntryDisplayDtoFixture.Create();
|
||||
PlaylistEntryDto entry = _playlistEntryDtoFixture.Create(entry: entity, display: display, displayPosition: 6);
|
||||
|
||||
// Act
|
||||
PlaylistEntryResponse response = entry.ToResponse();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(entity.Id, response.Id);
|
||||
Assert.Equal(entity.MediaItemId, response.MediaItemId);
|
||||
Assert.Equal(entity.MediaItemType, response.MediaItemType);
|
||||
Assert.Equal(6, response.Position);
|
||||
Assert.Equal(display.LibraryId, response.LibraryId);
|
||||
Assert.Equal(display.AlbumId, response.CollectionId);
|
||||
Assert.Equal(display.ArtistId, response.CreatorId);
|
||||
Assert.Equal(display.TrackTitle, response.MediaItemTitle);
|
||||
Assert.Equal(display.AlbumTitle, response.CollectionTitle);
|
||||
Assert.Equal(display.ArtistName, response.CreatorName);
|
||||
Assert.Equal(display.DurationInSeconds, response.DurationInSeconds);
|
||||
Assert.Equal(display.CoverPath, response.CoverPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenDisplayHasNoCoverPath_ShouldMapNullCoverPath()
|
||||
{
|
||||
// Arrange
|
||||
PlaylistEntryDisplayDto display = _playlistEntryDisplayDtoFixture.Create(includeCoverPath: false);
|
||||
PlaylistEntryDto entry = _playlistEntryDtoFixture.Create(display: display);
|
||||
|
||||
// Act
|
||||
PlaylistEntryResponse response = entry.ToResponse();
|
||||
|
||||
// Assert
|
||||
Assert.Null(response.CoverPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponses_WhenMappingAPage_ShouldPreserveTheOrderOfTheEntriesAndThePaginationMetadata()
|
||||
{
|
||||
// Arrange
|
||||
PlaylistEntryDto firstEntry = _playlistEntryDtoFixture.Create(displayPosition: 0);
|
||||
PlaylistEntryDto secondEntry = _playlistEntryDtoFixture.Create(displayPosition: 1);
|
||||
PlaylistEntryDto thirdEntry = _playlistEntryDtoFixture.Create(displayPosition: 2, includeDisplay: false);
|
||||
List<PlaylistEntryDto> entries = [firstEntry, secondEntry, thirdEntry];
|
||||
PaginatedResultDto<PlaylistEntryDto> page = _paginatedResultDtoFixture.Create(
|
||||
data: entries,
|
||||
currentPage: 2,
|
||||
perPage: 3,
|
||||
count: 7,
|
||||
numberOfPages: 3);
|
||||
|
||||
// Act
|
||||
PaginatedResponse<PlaylistEntryResponse> response = page.ToResponses();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(3, response.Data.Count);
|
||||
Assert.Equal<Guid>(
|
||||
entries.Select(entry => entry.Entry.Id),
|
||||
response.Data.Select(entry => entry.Id));
|
||||
Assert.Equal<int>([0, 1, 2], response.Data.Select(entry => entry.Position));
|
||||
Assert.Equal(2, response.CurrentPage);
|
||||
Assert.Equal(3, response.PerPage);
|
||||
Assert.Equal(7, response.Count);
|
||||
Assert.Equal(3, response.NumberOfPages);
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Utilities;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Utilities;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="FavoriteMediaKindExtensions"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FavoriteMediaKindExtensionsTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData(FavoriteMediaKind.MusicArtist, nameof(DomainErrors.Music.ArtistNotFound))] // an artist has no library of its own
|
||||
[InlineData(FavoriteMediaKind.MusicAlbum, nameof(DomainErrors.Music.AlbumNotFound))] // an album is not a media item that can be favorited
|
||||
[InlineData(FavoriteMediaKind.MusicTrack, nameof(DomainErrors.Music.TrackNotFound))] // a track is resolved through the music catalogue
|
||||
[InlineData(FavoriteMediaKind.Book, nameof(DomainErrors.WrittenContent.BookNotFound))] // a book is resolved through the written content catalogue
|
||||
public void ToMediaItemNotFoundError_WhenTheMediaKindIsCatalogued_ShouldReturnTheMediaSpecificNotFoundError(FavoriteMediaKind mediaKind, string expectedDescription)
|
||||
{
|
||||
// Act
|
||||
Error error = mediaKind.ToMediaItemNotFoundError();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(expectedDescription, error.Description);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(FavoriteMediaKind.None)] // the default value, which is not a kind that can be favorited
|
||||
[InlineData(FavoriteMediaKind.Video)] // video libraries are not catalogued yet
|
||||
[InlineData(FavoriteMediaKind.Photo)] // photo libraries are not catalogued yet
|
||||
public void ToMediaItemNotFoundError_WhenTheMediaKindIsNotCatalogued_ShouldReturnTheNotSupportedError(FavoriteMediaKind mediaKind)
|
||||
{
|
||||
// Act
|
||||
Error error = mediaKind.ToMediaItemNotFoundError();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(DomainErrors.Favorites.FavoriteMediaKindIsNotSupported, error);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToMediaItemNotFoundError_WhenTheMediaKindIsUndefined_ShouldReturnTheNotSupportedError()
|
||||
{
|
||||
// Arrange
|
||||
FavoriteMediaKind mediaKind = (FavoriteMediaKind)int.MaxValue;
|
||||
|
||||
// Act
|
||||
Error error = mediaKind.ToMediaItemNotFoundError();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(DomainErrors.Favorites.FavoriteMediaKindIsNotSupported, error);
|
||||
}
|
||||
}
|
||||
+451
@@ -0,0 +1,451 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Favorites;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.DomainEvents;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.Common.Base;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Core.Favorites.Commands.AddFavorite;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Fixtures.Core.Favorites.Commands.AddFavorite;
|
||||
using Lumina.Contracts.Responses.Favorites;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.Events;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.Favorites.Commands.AddFavorite;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="AddFavoriteCommandHandler"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddFavoriteCommandHandlerTests
|
||||
{
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly ICurrentUserService _mockCurrentUserService;
|
||||
private readonly IAuthorizationService _mockAuthorizationService;
|
||||
private readonly IDomainEventsQueue _mockDomainEventsQueue;
|
||||
private readonly IFavoriteRepository _mockFavoriteRepository;
|
||||
private readonly IValidator<AddFavoriteCommand> _mockValidator;
|
||||
private readonly AddFavoriteCommandHandler _sut;
|
||||
private readonly AddFavoriteCommandFixture _addFavoriteCommandFixture = new();
|
||||
private readonly FavoriteEntityFixture _favoriteEntityFixture = new();
|
||||
private readonly Guid _userId = Guid.NewGuid();
|
||||
private readonly Guid _libraryId = Guid.NewGuid();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddFavoriteCommandHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public AddFavoriteCommandHandlerTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
|
||||
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
|
||||
_mockDomainEventsQueue = Substitute.For<IDomainEventsQueue>();
|
||||
_mockFavoriteRepository = Substitute.For<IFavoriteRepository>();
|
||||
|
||||
_mockUnitOfWork.FavoriteRepository.Returns(_mockFavoriteRepository);
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_mockCurrentUserService.UserId.Returns(_userId);
|
||||
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<PolicyContext>(), Arg.Any<CancellationToken>())
|
||||
.Returns(true);
|
||||
_mockFavoriteRepository.GetMediaItemLibraryIdAsync(Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<Guid?>(_libraryId));
|
||||
_mockFavoriteRepository.GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<FavoriteEntity?>(null));
|
||||
_mockFavoriteRepository.InsertAsync(Arg.Any<FavoriteEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
|
||||
_mockValidator = Substitute.For<IValidator<AddFavoriteCommand>>();
|
||||
_mockValidator.Validate(Arg.Any<AddFavoriteCommand>()).Returns([]);
|
||||
|
||||
_sut = new AddFavoriteCommandHandler(_mockUnitOfWork, _mockCurrentUserService, _mockAuthorizationService, _mockDomainEventsQueue, _mockValidator);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenValidatorReturnsError_ShouldReturnValidationErrorAndNotTouchTheRepositories()
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteCommand command = _addFavoriteCommandFixture.Create();
|
||||
Error error = DomainErrors.Favorites.FavoriteMediaKindIsInvalid;
|
||||
_mockValidator.Validate(Arg.Any<AddFavoriteCommand>()).Returns([error]);
|
||||
|
||||
// Act
|
||||
Result<FavoriteResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
_ = _mockCurrentUserService.DidNotReceive().UserId;
|
||||
await _mockFavoriteRepository.DidNotReceive().GetMediaItemLibraryIdAsync(Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockFavoriteRepository.DidNotReceive().GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
await _mockFavoriteRepository.DidNotReceive().InsertAsync(Arg.Any<FavoriteEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorizedAndNotReadTheRepositories()
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteCommand command = _addFavoriteCommandFixture.Create();
|
||||
_mockCurrentUserService.UserId.Returns((Guid?)null);
|
||||
|
||||
// Act
|
||||
Result<FavoriteResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
||||
await _mockFavoriteRepository.DidNotReceive().GetMediaItemLibraryIdAsync(Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockFavoriteRepository.DidNotReceive().GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
await _mockFavoriteRepository.DidNotReceive().InsertAsync(Arg.Any<FavoriteEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(FavoriteMediaKind.None)] // the default value, which is not a kind that can be favorited
|
||||
[InlineData(FavoriteMediaKind.Video)] // video libraries are not catalogued yet
|
||||
[InlineData(FavoriteMediaKind.Photo)] // photo libraries are not catalogued yet
|
||||
public async Task HandleAsync_WhenMediaKindIsNotSupported_ShouldReturnNotSupportedAndNotResolveTheLibrary(FavoriteMediaKind mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteCommand command = _addFavoriteCommandFixture.Create(mediaKind: mediaKind);
|
||||
|
||||
// Act
|
||||
Result<FavoriteResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(DomainErrors.Favorites.FavoriteMediaKindIsNotSupported, result.FirstError);
|
||||
await _mockFavoriteRepository.DidNotReceive().GetMediaItemLibraryIdAsync(Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockFavoriteRepository.DidNotReceive().GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTheMediaItemLibraryLookupFails_ShouldReturnThatErrorAndNotAuthorizeOrReadTheFavorite()
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteCommand command = _addFavoriteCommandFixture.Create();
|
||||
Error error = Error.Failure("Persistence.Failure", "The media item library could not be read.");
|
||||
_mockFavoriteRepository.GetMediaItemLibraryIdAsync(Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(error);
|
||||
|
||||
// Act
|
||||
Result<FavoriteResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<PolicyContext>(), Arg.Any<CancellationToken>());
|
||||
await _mockFavoriteRepository.DidNotReceive().GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
await _mockFavoriteRepository.DidNotReceive().InsertAsync(Arg.Any<FavoriteEntity>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(FavoriteMediaKind.MusicArtist, nameof(DomainErrors.Music.ArtistNotFound))] // the artist does not exist
|
||||
[InlineData(FavoriteMediaKind.MusicAlbum, nameof(DomainErrors.Music.AlbumNotFound))] // the album does not exist
|
||||
[InlineData(FavoriteMediaKind.MusicTrack, nameof(DomainErrors.Music.TrackNotFound))] // the track does not exist
|
||||
[InlineData(FavoriteMediaKind.Book, nameof(DomainErrors.WrittenContent.BookNotFound))] // the book does not exist
|
||||
public async Task HandleAsync_WhenTheMediaItemHasNoLibrary_ShouldReturnTheMediaKindSpecificNotFoundError(FavoriteMediaKind mediaKind, string expectedErrorDescription)
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteCommand command = _addFavoriteCommandFixture.Create(mediaKind: mediaKind);
|
||||
_mockFavoriteRepository.GetMediaItemLibraryIdAsync(Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<Guid?>(null));
|
||||
|
||||
// Act
|
||||
Result<FavoriteResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(expectedErrorDescription, result.FirstError.Description);
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<PolicyContext>(), Arg.Any<CancellationToken>());
|
||||
await _mockFavoriteRepository.DidNotReceive().GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenLibraryAccessIsDenied_ShouldReturnTheMediaKindSpecificNotFoundErrorAndNotReadTheFavorite()
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteCommand command = _addFavoriteCommandFixture.Create(mediaKind: FavoriteMediaKind.MusicTrack);
|
||||
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<PolicyContext>(), Arg.Any<CancellationToken>())
|
||||
.Returns(false);
|
||||
|
||||
// Act
|
||||
Result<FavoriteResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(nameof(DomainErrors.Music.TrackNotFound), result.FirstError.Description);
|
||||
await _mockFavoriteRepository.DidNotReceive().GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
await _mockFavoriteRepository.DidNotReceive().InsertAsync(Arg.Any<FavoriteEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTheExistingFavoriteReadFails_ShouldReturnThatErrorAndNotInsert()
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteCommand command = _addFavoriteCommandFixture.Create();
|
||||
Error error = Error.Failure("Persistence.Failure", "The existing favorite could not be read.");
|
||||
_mockFavoriteRepository.GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(error);
|
||||
|
||||
// Act
|
||||
Result<FavoriteResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
await _mockFavoriteRepository.DidNotReceive().InsertAsync(Arg.Any<FavoriteEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTheItemIsAlreadyAFavorite_ShouldReturnTheStoredFavoriteWithoutInsertingOrRaisingAnEvent()
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteCommand command = _addFavoriteCommandFixture.Create();
|
||||
DateTime createdOnUtc = new(2024, 5, 6, 7, 8, 9, DateTimeKind.Utc);
|
||||
FavoriteEntity existingFavorite = _favoriteEntityFixture.Create(
|
||||
userId: _userId,
|
||||
mediaKind: command.MediaKind!.Value,
|
||||
mediaItemId: command.MediaItemId!.Value,
|
||||
createdOnUtc: createdOnUtc);
|
||||
_mockFavoriteRepository.GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<FavoriteEntity?>(existingFavorite));
|
||||
|
||||
// Act
|
||||
Result<FavoriteResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(existingFavorite.Id, result.Value.Id);
|
||||
Assert.Equal(createdOnUtc, result.Value.FavoritedOnUtc);
|
||||
await _mockFavoriteRepository.DidNotReceive().InsertAsync(Arg.Any<FavoriteEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenInsertFails_ShouldReturnThatErrorAndNotSaveChanges()
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteCommand command = _addFavoriteCommandFixture.Create();
|
||||
Error error = Error.Failure("Persistence.Failure", "The favorite could not be inserted.");
|
||||
_mockFavoriteRepository.InsertAsync(Arg.Any<FavoriteEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(error);
|
||||
|
||||
// Act
|
||||
Result<FavoriteResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenSaveFailsWithANonUniqueConstraintError_ShouldReturnThatErrorAndNotRaiseAnEvent()
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteCommand command = _addFavoriteCommandFixture.Create();
|
||||
Error error = Error.Failure("Persistence.Failure", "The changes could not be saved.");
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(error);
|
||||
|
||||
// Act
|
||||
Result<FavoriteResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
_mockUnitOfWork.DidNotReceive().ClearTrackedEntities();
|
||||
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenSaveFailsWithAUniqueConstraintViolationAndAConcurrentFavoriteExists_ShouldReturnTheConcurrentFavoriteWithoutRaisingAnEvent()
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteCommand command = _addFavoriteCommandFixture.Create();
|
||||
DateTime createdOnUtc = new(2024, 7, 8, 9, 10, 11, DateTimeKind.Utc);
|
||||
FavoriteEntity concurrentFavorite = _favoriteEntityFixture.Create(
|
||||
userId: _userId,
|
||||
mediaKind: command.MediaKind!.Value,
|
||||
mediaItemId: command.MediaItemId!.Value,
|
||||
createdOnUtc: createdOnUtc);
|
||||
_mockFavoriteRepository.GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<FavoriteEntity?>(null), Result.From<FavoriteEntity?>(concurrentFavorite));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
|
||||
|
||||
// Act
|
||||
Result<FavoriteResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(concurrentFavorite.Id, result.Value.Id);
|
||||
Assert.Equal(createdOnUtc, result.Value.FavoritedOnUtc);
|
||||
_mockUnitOfWork.Received(1).ClearTrackedEntities();
|
||||
await _mockFavoriteRepository.Received(2).GetByMediaItemIdForUserAsync(_userId, command.MediaKind!.Value, command.MediaItemId!.Value, Arg.Is<bool>(shouldTrackEntities => !shouldTrackEntities), Arg.Any<CancellationToken>());
|
||||
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenSaveFailsWithAUniqueConstraintViolationAndTheConcurrentFavoriteIsMissing_ShouldReturnTheSaveError()
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteCommand command = _addFavoriteCommandFixture.Create();
|
||||
_mockFavoriteRepository.GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<FavoriteEntity?>(null), Result.From<FavoriteEntity?>(null));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
|
||||
|
||||
// Act
|
||||
Result<FavoriteResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
|
||||
_mockUnitOfWork.Received(1).ClearTrackedEntities();
|
||||
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenSaveFailsWithAUniqueConstraintViolationAndTheReReadFails_ShouldReturnTheReReadError()
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteCommand command = _addFavoriteCommandFixture.Create();
|
||||
Error error = Error.Failure("Persistence.Failure", "The concurrent favorite could not be read.");
|
||||
_mockFavoriteRepository.GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<FavoriteEntity?>(null), error);
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
|
||||
|
||||
// Act
|
||||
Result<FavoriteResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
_mockUnitOfWork.Received(1).ClearTrackedEntities();
|
||||
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenSuccessful_ShouldInsertSaveEnqueueOnceAndReturnThePersistedFavorite()
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteCommand command = _addFavoriteCommandFixture.Create(mediaKind: FavoriteMediaKind.MusicAlbum);
|
||||
DateTime createdOnUtc = new(2024, 9, 10, 11, 12, 13, DateTimeKind.Utc);
|
||||
FavoriteEntity persistedFavorite = _favoriteEntityFixture.Create(
|
||||
userId: _userId,
|
||||
mediaKind: command.MediaKind!.Value,
|
||||
mediaItemId: command.MediaItemId!.Value,
|
||||
createdOnUtc: createdOnUtc);
|
||||
_mockFavoriteRepository.GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<FavoriteEntity?>(null), Result.From<FavoriteEntity?>(persistedFavorite));
|
||||
FavoriteEntity? insertedEntity = null;
|
||||
_mockFavoriteRepository.InsertAsync(Arg.Do<FavoriteEntity>(favorite => insertedEntity = favorite), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
|
||||
// Act
|
||||
Result<FavoriteResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(persistedFavorite.Id, result.Value.Id);
|
||||
Assert.Equal(persistedFavorite.MediaKind, result.Value.MediaKind);
|
||||
Assert.Equal(persistedFavorite.MediaItemId, result.Value.MediaItemId);
|
||||
Assert.Equal(createdOnUtc, result.Value.FavoritedOnUtc);
|
||||
Assert.NotNull(insertedEntity);
|
||||
Assert.NotEqual(Guid.Empty, insertedEntity!.Id);
|
||||
Assert.Equal(_userId, insertedEntity.UserId);
|
||||
Assert.Equal(command.MediaKind!.Value, insertedEntity.MediaKind);
|
||||
Assert.Equal(command.MediaItemId!.Value, insertedEntity.MediaItemId);
|
||||
Assert.Equal(Guid.Empty, insertedEntity.CreatedBy);
|
||||
Assert.Null(insertedEntity.UpdatedOnUtc);
|
||||
Assert.Null(insertedEntity.UpdatedBy);
|
||||
await _mockFavoriteRepository.Received(1).InsertAsync(Arg.Any<FavoriteEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
_mockDomainEventsQueue.Received(1).Enqueue(Arg.Is<IDomainEvent>(domainEvent => domainEvent is FavoriteAddedDomainEvent));
|
||||
await _mockFavoriteRepository.Received(2).GetByMediaItemIdForUserAsync(_userId, command.MediaKind!.Value, command.MediaItemId!.Value, Arg.Is<bool>(shouldTrackEntities => !shouldTrackEntities), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenThePersistedFavoriteReadFails_ShouldReturnThatErrorAndNotEnqueueTheAddedEvent()
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteCommand command = _addFavoriteCommandFixture.Create();
|
||||
Error error = Error.Failure("Persistence.Failure", "The persisted favorite could not be read.");
|
||||
_mockFavoriteRepository.GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<FavoriteEntity?>(null), error);
|
||||
|
||||
// Act
|
||||
Result<FavoriteResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenThePersistedFavoriteIsMissing_ShouldReturnFavoriteNotFoundWithoutEnqueuingTheAddedEvent()
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteCommand command = _addFavoriteCommandFixture.Create();
|
||||
_mockFavoriteRepository.GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<FavoriteEntity?>(null), Result.From<FavoriteEntity?>(null));
|
||||
|
||||
// Act
|
||||
Result<FavoriteResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(DomainErrors.Favorites.FavoriteNotFound, result.FirstError);
|
||||
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenCalled_ShouldScopeEveryRepositoryCallToTheCurrentUserTheMediaKindAndTheMediaItemAndForwardTheCancellationToken()
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteCommand command = _addFavoriteCommandFixture.Create(mediaKind: FavoriteMediaKind.Book);
|
||||
using CancellationTokenSource cancellationTokenSource = new();
|
||||
CancellationToken cancellationToken = cancellationTokenSource.Token;
|
||||
FavoriteEntity persistedFavorite = _favoriteEntityFixture.Create(
|
||||
userId: _userId,
|
||||
mediaKind: command.MediaKind!.Value,
|
||||
mediaItemId: command.MediaItemId!.Value);
|
||||
_mockFavoriteRepository.GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<FavoriteEntity?>(null), Result.From<FavoriteEntity?>(persistedFavorite));
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(command, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockFavoriteRepository.Received(1).GetMediaItemLibraryIdAsync(command.MediaKind!.Value, command.MediaItemId!.Value, Arg.Is(cancellationToken));
|
||||
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
_userId,
|
||||
Arg.Is<PolicyContext>(context => context is LibraryOwnershipPolicyContext && ((LibraryOwnershipPolicyContext)context).LibraryId == _libraryId),
|
||||
Arg.Is(cancellationToken));
|
||||
await _mockFavoriteRepository.Received(2).GetByMediaItemIdForUserAsync(_userId, command.MediaKind!.Value, command.MediaItemId!.Value, Arg.Is<bool>(shouldTrackEntities => !shouldTrackEntities), Arg.Is(cancellationToken));
|
||||
await _mockFavoriteRepository.Received(1).InsertAsync(Arg.Any<FavoriteEntity>(), Arg.Is(cancellationToken));
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Is(cancellationToken));
|
||||
}
|
||||
}
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.Favorites.Commands.AddFavorite;
|
||||
using Lumina.Application.Fixtures.Core.Favorites.Commands.AddFavorite;
|
||||
using Lumina.Application.UnitTests.Common.Setup;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.Favorites.Commands.AddFavorite;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="AddFavoriteCommandValidator"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddFavoriteCommandValidatorTests
|
||||
{
|
||||
private readonly AddFavoriteCommandValidator _validator = new();
|
||||
private readonly AddFavoriteCommandFixture _addFavoriteCommandFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenMediaKindIsNotSupplied_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteCommand command = _addFavoriteCommandFixture.Create(includeMediaKind: false);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Favorites.FavoriteMediaKindIsInvalid);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenMediaKindIsUndefined_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteCommand command = _addFavoriteCommandFixture.Create(mediaKind: (FavoriteMediaKind)int.MaxValue);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Favorites.FavoriteMediaKindIsInvalid);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenMediaKindIsNone_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteCommand command = _addFavoriteCommandFixture.Create(mediaKind: FavoriteMediaKind.None);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Favorites.FavoriteMediaKindIsInvalid);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(FavoriteMediaKind.MusicArtist)] // a catalogued music kind
|
||||
[InlineData(FavoriteMediaKind.MusicAlbum)] // a catalogued music kind
|
||||
[InlineData(FavoriteMediaKind.MusicTrack)] // a catalogued music kind
|
||||
[InlineData(FavoriteMediaKind.Book)] // a catalogued written content kind
|
||||
[InlineData(FavoriteMediaKind.Video)] // a planned kind is still a defined enumeration member
|
||||
[InlineData(FavoriteMediaKind.Photo)] // a planned kind is still a defined enumeration member
|
||||
public void Validate_WhenMediaKindIsDefined_ShouldNotHaveValidationError(FavoriteMediaKind mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteCommand command = _addFavoriteCommandFixture.Create(mediaKind: mediaKind);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationError(Errors.Favorites.FavoriteMediaKindIsInvalid);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenMediaItemIdIsNotSupplied_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteCommand command = _addFavoriteCommandFixture.Create(includeMediaItemId: false);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Favorites.FavoriteMediaItemIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenMediaItemIdIsTheEmptyGuid_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteCommand command = _addFavoriteCommandFixture.Create(mediaItemId: Guid.Empty);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Favorites.FavoriteMediaItemIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationError()
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteCommand command = _addFavoriteCommandFixture.Create();
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveAnyValidationErrors();
|
||||
}
|
||||
}
|
||||
+298
@@ -0,0 +1,298 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Favorites;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.DomainEvents;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Core.Favorites.Commands.RemoveFavorite;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Fixtures.Core.Favorites.Commands.RemoveFavorite;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.Events;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.Favorites.Commands.RemoveFavorite;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="RemoveFavoriteCommandHandler"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RemoveFavoriteCommandHandlerTests
|
||||
{
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly ICurrentUserService _mockCurrentUserService;
|
||||
private readonly IDomainEventsQueue _mockDomainEventsQueue;
|
||||
private readonly IFavoriteRepository _mockFavoriteRepository;
|
||||
private readonly IValidator<RemoveFavoriteCommand> _mockValidator;
|
||||
private readonly RemoveFavoriteCommandHandler _sut;
|
||||
private readonly RemoveFavoriteCommandFixture _removeFavoriteCommandFixture = new();
|
||||
private readonly FavoriteEntityFixture _favoriteEntityFixture = new();
|
||||
private readonly Guid _userId = Guid.NewGuid();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RemoveFavoriteCommandHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public RemoveFavoriteCommandHandlerTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
|
||||
_mockDomainEventsQueue = Substitute.For<IDomainEventsQueue>();
|
||||
_mockFavoriteRepository = Substitute.For<IFavoriteRepository>();
|
||||
|
||||
_mockUnitOfWork.FavoriteRepository.Returns(_mockFavoriteRepository);
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_mockCurrentUserService.UserId.Returns(_userId);
|
||||
_mockFavoriteRepository.GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<FavoriteEntity?>(null));
|
||||
_mockFavoriteRepository.DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Deleted);
|
||||
|
||||
_mockValidator = Substitute.For<IValidator<RemoveFavoriteCommand>>();
|
||||
_mockValidator.Validate(Arg.Any<RemoveFavoriteCommand>()).Returns([]);
|
||||
|
||||
_sut = new RemoveFavoriteCommandHandler(_mockUnitOfWork, _mockCurrentUserService, _mockDomainEventsQueue, _mockValidator);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenValidatorReturnsError_ShouldReturnValidationErrorAndNotTouchTheRepositories()
|
||||
{
|
||||
// Arrange
|
||||
RemoveFavoriteCommand command = _removeFavoriteCommandFixture.Create();
|
||||
Error error = DomainErrors.Favorites.FavoriteMediaKindIsInvalid;
|
||||
_mockValidator.Validate(Arg.Any<RemoveFavoriteCommand>()).Returns([error]);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
_ = _mockCurrentUserService.DidNotReceive().UserId;
|
||||
await _mockFavoriteRepository.DidNotReceive().GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
await _mockFavoriteRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorizedAndNotReadTheFavorite()
|
||||
{
|
||||
// Arrange
|
||||
RemoveFavoriteCommand command = _removeFavoriteCommandFixture.Create();
|
||||
_mockCurrentUserService.UserId.Returns((Guid?)null);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
||||
await _mockFavoriteRepository.DidNotReceive().GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTheFavoriteReadFails_ShouldReturnThatError()
|
||||
{
|
||||
// Arrange
|
||||
RemoveFavoriteCommand command = _removeFavoriteCommandFixture.Create();
|
||||
Error error = Error.Failure("Persistence.Failure", "The favorite could not be read.");
|
||||
_mockFavoriteRepository.GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(error);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
await _mockFavoriteRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTheFavoriteIsAbsent_ShouldReturnDeletedWithoutDeletingOrRaisingAnEvent()
|
||||
{
|
||||
// Arrange
|
||||
RemoveFavoriteCommand command = _removeFavoriteCommandFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Deleted, result.Value);
|
||||
await _mockFavoriteRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenDeleteFails_ShouldReturnThatErrorAndNotSaveChanges()
|
||||
{
|
||||
// Arrange
|
||||
RemoveFavoriteCommand command = _removeFavoriteCommandFixture.Create();
|
||||
FavoriteEntity favorite = CreateFavoriteFrom(command);
|
||||
Error error = Error.Failure("Persistence.Failure", "The favorite could not be deleted.");
|
||||
_mockFavoriteRepository.GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<FavoriteEntity?>(favorite));
|
||||
_mockFavoriteRepository.DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(error);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenSaveFailsWithANonConcurrencyError_ShouldReturnThatErrorAndNotRaiseAnEvent()
|
||||
{
|
||||
// Arrange
|
||||
RemoveFavoriteCommand command = _removeFavoriteCommandFixture.Create();
|
||||
FavoriteEntity favorite = CreateFavoriteFrom(command);
|
||||
Error error = Error.Failure("Persistence.Failure", "The changes could not be saved.");
|
||||
_mockFavoriteRepository.GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<FavoriteEntity?>(favorite));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(error);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
_mockUnitOfWork.DidNotReceive().ClearTrackedEntities();
|
||||
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenSaveFailsWithAConcurrencyConflictAndTheFavoriteStillExists_ShouldReturnTheSaveError()
|
||||
{
|
||||
// Arrange
|
||||
RemoveFavoriteCommand command = _removeFavoriteCommandFixture.Create();
|
||||
FavoriteEntity favorite = CreateFavoriteFrom(command);
|
||||
_mockFavoriteRepository.GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<FavoriteEntity?>(favorite), Result.From<FavoriteEntity?>(favorite));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(ApplicationErrors.Persistence.ConcurrencyConflict);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Persistence.ConcurrencyConflict, result.FirstError);
|
||||
_mockUnitOfWork.Received(1).ClearTrackedEntities();
|
||||
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenSaveFailsWithAConcurrencyConflictAndTheFavoriteIsGone_ShouldReturnDeletedWithoutRaisingAnEvent()
|
||||
{
|
||||
// Arrange
|
||||
RemoveFavoriteCommand command = _removeFavoriteCommandFixture.Create();
|
||||
FavoriteEntity favorite = CreateFavoriteFrom(command);
|
||||
_mockFavoriteRepository.GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<FavoriteEntity?>(favorite), Result.From<FavoriteEntity?>(null));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(ApplicationErrors.Persistence.ConcurrencyConflict);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Deleted, result.Value);
|
||||
_mockUnitOfWork.Received(1).ClearTrackedEntities();
|
||||
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenSaveFailsWithAConcurrencyConflictAndTheReReadFails_ShouldReturnThatError()
|
||||
{
|
||||
// Arrange
|
||||
RemoveFavoriteCommand command = _removeFavoriteCommandFixture.Create();
|
||||
FavoriteEntity favorite = CreateFavoriteFrom(command);
|
||||
Error error = Error.Failure("Persistence.Failure", "The remaining favorite could not be read.");
|
||||
_mockFavoriteRepository.GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<FavoriteEntity?>(favorite), error);
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(ApplicationErrors.Persistence.ConcurrencyConflict);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
_mockUnitOfWork.Received(1).ClearTrackedEntities();
|
||||
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenSuccessful_ShouldDeleteTheFavoriteSaveOnceAndRaiseExactlyOneRemovedEvent()
|
||||
{
|
||||
// Arrange
|
||||
RemoveFavoriteCommand command = _removeFavoriteCommandFixture.Create(mediaKind: nameof(FavoriteMediaKind.Book));
|
||||
FavoriteEntity favorite = CreateFavoriteFrom(command);
|
||||
_mockFavoriteRepository.GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<FavoriteEntity?>(favorite));
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Deleted, result.Value);
|
||||
await _mockFavoriteRepository.Received(1).GetByMediaItemIdForUserAsync(_userId, FavoriteMediaKind.Book, favorite.MediaItemId, Arg.Is<bool>(shouldTrackEntities => shouldTrackEntities), Arg.Any<CancellationToken>());
|
||||
await _mockFavoriteRepository.Received(1).DeleteByIdAsync(favorite.Id, Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
_mockDomainEventsQueue.Received(1).Enqueue(Arg.Is<IDomainEvent>(domainEvent => domainEvent is FavoriteRemovedDomainEvent));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenCalled_ShouldScopeEveryCallToTheStoredFavoriteAndForwardTheCancellationToken()
|
||||
{
|
||||
// Arrange
|
||||
RemoveFavoriteCommand command = _removeFavoriteCommandFixture.Create();
|
||||
FavoriteEntity favorite = CreateFavoriteFrom(command);
|
||||
using CancellationTokenSource cancellationTokenSource = new();
|
||||
CancellationToken cancellationToken = cancellationTokenSource.Token;
|
||||
_mockFavoriteRepository.GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<FavoriteEntity?>(favorite));
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(command, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockFavoriteRepository.Received(1).GetByMediaItemIdForUserAsync(_userId, favorite.MediaKind, favorite.MediaItemId, Arg.Is<bool>(shouldTrackEntities => shouldTrackEntities), Arg.Is(cancellationToken));
|
||||
await _mockFavoriteRepository.Received(1).DeleteByIdAsync(favorite.Id, Arg.Is(cancellationToken));
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a stored favorite entity that matches the media kind and media item of <paramref name="command"/>.
|
||||
/// </summary>
|
||||
/// <param name="command">The command whose route values describe the favorite.</param>
|
||||
/// <returns>The created <see cref="FavoriteEntity"/>.</returns>
|
||||
private FavoriteEntity CreateFavoriteFrom(RemoveFavoriteCommand command)
|
||||
{
|
||||
return _favoriteEntityFixture.Create(
|
||||
userId: _userId,
|
||||
mediaKind: Enum.Parse<FavoriteMediaKind>(command.MediaKind!, ignoreCase: true),
|
||||
mediaItemId: Guid.Parse(command.MediaItemId!));
|
||||
}
|
||||
}
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.Favorites.Commands.RemoveFavorite;
|
||||
using Lumina.Application.Fixtures.Core.Favorites.Commands.RemoveFavorite;
|
||||
using Lumina.Application.UnitTests.Common.Setup;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.Favorites.Commands.RemoveFavorite;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="RemoveFavoriteCommandValidator"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RemoveFavoriteCommandValidatorTests
|
||||
{
|
||||
private readonly RemoveFavoriteCommandValidator _validator = new();
|
||||
private readonly RemoveFavoriteCommandFixture _removeFavoriteCommandFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenMediaKindIsNotSupplied_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
RemoveFavoriteCommand command = _removeFavoriteCommandFixture.Create(includeMediaKind: false);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Favorites.FavoriteMediaKindIsInvalid);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")] // the media kind is empty
|
||||
[InlineData(" ")] // the media kind is whitespace only
|
||||
[InlineData("Hologram")] // the media kind is not a member of the enumeration
|
||||
[InlineData("None")] // the default value is not a kind that can be favorited
|
||||
[InlineData("none")] // the default value, matched case insensitively
|
||||
[InlineData("0")] // the media kind is a numeric route value, which the validator rejects by name
|
||||
[InlineData("1")] // a numeric route value that parses to a defined member, which the name check rejects
|
||||
[InlineData("MusicTrack,Book")] // a comma separated list is not a single member name
|
||||
[InlineData("../MusicTrack")] // a path-like value is not a member name
|
||||
public void Validate_WhenMediaKindIsEmptyOrNotAMemberName_ShouldHaveValidationError(string mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
RemoveFavoriteCommand command = _removeFavoriteCommandFixture.Create(mediaKind: mediaKind);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Favorites.FavoriteMediaKindIsInvalid);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("musictrack")] // the member name is lower case
|
||||
[InlineData("BoOk")] // the member name is mixed case
|
||||
public void Validate_WhenMediaKindUsesDifferentCasing_ShouldNotHaveValidationError(string mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
RemoveFavoriteCommand command = _removeFavoriteCommandFixture.Create(mediaKind: mediaKind);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationError(Errors.Favorites.FavoriteMediaKindIsInvalid);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenMediaItemIdIsNotSupplied_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
RemoveFavoriteCommand command = _removeFavoriteCommandFixture.Create(includeMediaItemId: false);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Favorites.FavoriteMediaItemIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")] // the media item Id is empty
|
||||
[InlineData(" ")] // the media item Id is whitespace only
|
||||
[InlineData("not-a-guid")] // the media item Id is not a Guid
|
||||
[InlineData("00000000-0000-0000-0000-000000000000")] // the media item Id is the empty Guid
|
||||
public void Validate_WhenMediaItemIdIsEmptyOrInvalid_ShouldHaveValidationError(string mediaItemId)
|
||||
{
|
||||
// Arrange
|
||||
RemoveFavoriteCommand command = _removeFavoriteCommandFixture.Create(mediaItemId: mediaItemId);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Favorites.FavoriteMediaItemIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationError()
|
||||
{
|
||||
// Arrange
|
||||
RemoveFavoriteCommand command = _removeFavoriteCommandFixture.Create();
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveAnyValidationErrors();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenBothValuesAreInvalid_ShouldHaveBothValidationErrors()
|
||||
{
|
||||
// Arrange
|
||||
RemoveFavoriteCommand command = _removeFavoriteCommandFixture.Create(
|
||||
mediaKind: "Hologram",
|
||||
mediaItemId: "not-a-guid");
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Favorites.FavoriteMediaKindIsInvalid);
|
||||
result.ShouldHaveValidationError(Errors.Favorites.FavoriteMediaItemIdCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
Loaded 100 of 135 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user