mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 05:11:10 +00:00
Adds playlist management and playback
This commit is contained in:
1 parent
009a0c8156
commit
9889c86c76
296 files changed
+18830
-367
No files matched your search
+7
-9
@@ -45,15 +45,13 @@ public class AlbumLiteRowFixture
|
||||
bool includeReleaseYear = true,
|
||||
bool includeReleaseTypes = true)
|
||||
{
|
||||
return new AlbumLiteRow
|
||||
{
|
||||
Id = id ?? _faker.Random.Guid(),
|
||||
Title = title ?? _faker.Music.Genre(),
|
||||
TotalTracks = totalTracks ?? _faker.Random.Int(1, 30),
|
||||
CoverPath = includeCoverPath ? (coverPath ?? _faker.System.FilePath()) : null,
|
||||
ReleaseYear = includeReleaseYear ? (releaseYear ?? _faker.Random.Int(MINIMUM_RELEASE_YEAR, MAXIMUM_RELEASE_YEAR)) : null,
|
||||
ReleaseTypes = includeReleaseTypes ? (releaseTypes ?? [.. Enumerable.Range(0, _faker.Random.Int(1, 3)).Select(index => _faker.PickRandom<MusicReleaseType>())]) : null
|
||||
};
|
||||
return new AlbumLiteRow(
|
||||
id ?? _faker.Random.Guid(),
|
||||
title ?? _faker.Music.Genre(),
|
||||
totalTracks ?? _faker.Random.Int(1, 30),
|
||||
includeCoverPath ? (coverPath ?? _faker.System.FilePath()) : null,
|
||||
includeReleaseYear ? (releaseYear ?? _faker.Random.Int(MINIMUM_RELEASE_YEAR, MAXIMUM_RELEASE_YEAR)) : null,
|
||||
includeReleaseTypes ? (releaseTypes ?? [.. Enumerable.Range(0, _faker.Random.Int(1, 3)).Select(index => _faker.PickRandom<MusicReleaseType>())]) : null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+4
-6
@@ -31,12 +31,10 @@ public class ArtistLiteRowFixture
|
||||
string? coverPath = null,
|
||||
bool includeCoverPath = true)
|
||||
{
|
||||
return new ArtistLiteRow
|
||||
{
|
||||
Id = id ?? _faker.Random.Guid(),
|
||||
Name = name ?? _faker.Name.FullName(),
|
||||
CoverPath = includeCoverPath ? (coverPath ?? _faker.System.FilePath()) : null
|
||||
};
|
||||
return new ArtistLiteRow(
|
||||
id ?? _faker.Random.Guid(),
|
||||
name ?? _faker.Name.FullName(),
|
||||
includeCoverPath ? (coverPath ?? _faker.System.FilePath()) : null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+6
-8
@@ -35,14 +35,12 @@ public class TrackLiteRowFixture
|
||||
bool includeDiscNumber = true,
|
||||
int? durationInSeconds = null)
|
||||
{
|
||||
return new TrackLiteRow
|
||||
{
|
||||
Id = id ?? _faker.Random.Guid(),
|
||||
Title = title ?? _faker.Lorem.Sentence(),
|
||||
TrackNumber = trackNumber ?? _faker.Random.Int(1, 30),
|
||||
DiscNumber = includeDiscNumber ? (discNumber ?? _faker.Random.Int(1, 3)) : null,
|
||||
DurationInSeconds = durationInSeconds ?? _faker.Random.Int(1, 600)
|
||||
};
|
||||
return new TrackLiteRow(
|
||||
id ?? _faker.Random.Guid(),
|
||||
title ?? _faker.Lorem.Sentence(),
|
||||
trackNumber ?? _faker.Random.Int(1, 30),
|
||||
includeDiscNumber ? (discNumber ?? _faker.Random.Int(1, 3)) : null,
|
||||
durationInSeconds ?? _faker.Random.Int(1, 600));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+5
-7
@@ -31,13 +31,11 @@ public class BookLiteRowFixture
|
||||
int? releaseYear = null,
|
||||
string? coverPath = null)
|
||||
{
|
||||
return new BookLiteRow
|
||||
{
|
||||
Id = id ?? _faker.Random.Guid(),
|
||||
Title = title ?? _faker.Lorem.Sentence(),
|
||||
ReleaseYear = releaseYear,
|
||||
CoverPath = coverPath
|
||||
};
|
||||
return new BookLiteRow(
|
||||
id ?? _faker.Random.Guid(),
|
||||
title ?? _faker.Lorem.Sentence(),
|
||||
releaseYear,
|
||||
coverPath);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Playlists;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="PlaylistEntity"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PlaylistEntityFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="PlaylistEntity"/>.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional. The Id of the playlist.</param>
|
||||
/// <param name="userId">Optional. The Id of the user that owns the playlist.</param>
|
||||
/// <param name="name">Optional. The name of the playlist.</param>
|
||||
/// <param name="includeDescription">Whether the description should be populated.</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 ordered entries of the playlist.</param>
|
||||
/// <param name="entryCount">Optional. The number of entries the playlist holds.</param>
|
||||
/// <param name="version">Optional. The concurrency token of the playlist.</param>
|
||||
/// <param name="createdOnUtc">Optional. The time and date when the playlist was created.</param>
|
||||
/// <param name="createdBy">Optional. The Id of the user that created the playlist.</param>
|
||||
/// <param name="includeUpdatedOnUtc">Whether the update time should be populated.</param>
|
||||
/// <param name="updatedOnUtc">Optional. The time and date when the playlist was updated.</param>
|
||||
/// <param name="updatedBy">Optional. The Id of the user that updated the playlist.</param>
|
||||
/// <returns>The created playlist entity.</returns>
|
||||
public PlaylistEntity Create(
|
||||
Guid? id = null,
|
||||
Guid? userId = null,
|
||||
string? name = null,
|
||||
bool includeDescription = true,
|
||||
string? description = null,
|
||||
PlaylistType? type = null,
|
||||
IEnumerable<PlaylistEntryEntity>? entries = null,
|
||||
int? entryCount = null,
|
||||
long? version = null,
|
||||
DateTime? createdOnUtc = null,
|
||||
Guid? createdBy = null,
|
||||
bool includeUpdatedOnUtc = false,
|
||||
DateTime? updatedOnUtc = null,
|
||||
Guid? updatedBy = null)
|
||||
{
|
||||
Guid playlistId = id ?? Guid.NewGuid();
|
||||
List<PlaylistEntryEntity> resolvedEntries = entries is null ? [] : [.. entries];
|
||||
|
||||
return new Faker<PlaylistEntity>()
|
||||
.CustomInstantiator(f => new PlaylistEntity
|
||||
{
|
||||
Id = playlistId,
|
||||
UserId = userId ?? f.Random.Guid(),
|
||||
Name = name ?? f.Lorem.Sentence(3),
|
||||
Description = includeDescription ? (description ?? f.Lorem.Sentence()) : null,
|
||||
Type = type ?? f.PickRandom<PlaylistType>(),
|
||||
Entries = resolvedEntries,
|
||||
EntryCount = entryCount ?? resolvedEntries.Count,
|
||||
Version = version ?? f.Random.Long(0, 1_000L),
|
||||
CreatedOnUtc = createdOnUtc ?? f.Date.Past(),
|
||||
CreatedBy = createdBy ?? f.Random.Guid(),
|
||||
UpdatedOnUtc = includeUpdatedOnUtc ? (updatedOnUtc ?? f.Date.Recent()) : null,
|
||||
UpdatedBy = includeUpdatedOnUtc ? (updatedBy ?? f.Random.Guid()) : null
|
||||
})
|
||||
.Generate();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="PlaylistEntity"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <param name="userId">Optional. The Id of the user that owns the created playlists.</param>
|
||||
/// <returns>List of configured <see cref="PlaylistEntity"/> instances.</returns>
|
||||
public List<PlaylistEntity> CreateMany(int count = 3, Guid? userId = null)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create(userId: userId))];
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Playlists;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="PlaylistEntryEntity"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PlaylistEntryEntityFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="PlaylistEntryEntity"/>.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional. The Id of the entry.</param>
|
||||
/// <param name="playlistId">Optional. The Id of the playlist the entry belongs to.</param>
|
||||
/// <param name="mediaItemId">Optional. The Id of the referenced media item.</param>
|
||||
/// <param name="mediaItemType">Optional. The kind of the referenced media item.</param>
|
||||
/// <param name="position">Optional. The sparse order key of the entry.</param>
|
||||
/// <param name="createdOnUtc">Optional. The time and date when the entry was created.</param>
|
||||
/// <param name="createdBy">Optional. The Id of the user that created the entry.</param>
|
||||
/// <param name="includeUpdatedOnUtc">Whether the update time should be populated.</param>
|
||||
/// <param name="updatedOnUtc">Optional. The time and date when the entry was updated.</param>
|
||||
/// <param name="updatedBy">Optional. The Id of the user that updated the entry.</param>
|
||||
/// <returns>The created playlist entry entity.</returns>
|
||||
public PlaylistEntryEntity Create(
|
||||
Guid? id = null,
|
||||
Guid? playlistId = null,
|
||||
Guid? mediaItemId = null,
|
||||
PlaylistMediaItemType? mediaItemType = null,
|
||||
long? position = null,
|
||||
DateTime? createdOnUtc = null,
|
||||
Guid? createdBy = null,
|
||||
bool includeUpdatedOnUtc = false,
|
||||
DateTime? updatedOnUtc = null,
|
||||
Guid? updatedBy = null)
|
||||
{
|
||||
return new Faker<PlaylistEntryEntity>()
|
||||
.CustomInstantiator(f => new PlaylistEntryEntity
|
||||
{
|
||||
Id = id ?? f.Random.Guid(),
|
||||
PlaylistId = playlistId ?? f.Random.Guid(),
|
||||
MediaItemId = mediaItemId ?? f.Random.Guid(),
|
||||
MediaItemType = mediaItemType ?? f.PickRandom<PlaylistMediaItemType>(),
|
||||
Position = position ?? f.Random.Long(0, 1_000_000_000L),
|
||||
CreatedOnUtc = createdOnUtc ?? f.Date.Past(),
|
||||
CreatedBy = createdBy ?? f.Random.Guid(),
|
||||
UpdatedOnUtc = includeUpdatedOnUtc ? (updatedOnUtc ?? f.Date.Recent()) : null,
|
||||
UpdatedBy = includeUpdatedOnUtc ? (updatedBy ?? f.Random.Guid()) : null
|
||||
})
|
||||
.Generate();
|
||||
}
|
||||
}
|
||||
+3
@@ -3,6 +3,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.DataAccess.Common.Dapper;
|
||||
using Lumina.DataAccess.Core.Repositories.Libraries;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
@@ -49,6 +50,8 @@ public class LibraryScanSnapshotRepositoryTests : IDisposable
|
||||
_anchorConnection.Open();
|
||||
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(_connectionString).Options);
|
||||
_context.Database.EnsureCreated();
|
||||
// The production composition root registers this handler, so the integration tests must exercise the same Guid representation.
|
||||
DapperTypeHandlers.Register();
|
||||
_sut = new LibraryScanSnapshotRepository(_context);
|
||||
}
|
||||
|
||||
|
||||
+485
@@ -0,0 +1,485 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Playlists;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DTO.Playlists;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Time;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Playlists;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
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.Playlists;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Storage;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.IntegrationTests.Core.Repositories.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="PlaylistRepository"/> class, exercising it against a real SQLite database.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PlaylistRepositoryTests
|
||||
{
|
||||
private readonly PlaylistEntityFixture _playlistEntityFixture = new();
|
||||
private readonly PlaylistEntryEntityFixture _playlistEntryEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenNoEditableValueChanged_ShouldNotModifyTheStoredPlaylist()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-playlistrepo-update-noop-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
Guid userId = Guid.NewGuid();
|
||||
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
|
||||
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
|
||||
PlaylistRepository sut = new(context);
|
||||
context.Users.Add(_userEntityFixture.Create(id: userId));
|
||||
PlaylistEntity playlist = _playlistEntityFixture.Create(userId: userId, type: PlaylistType.Music, entryCount: 7);
|
||||
context.Playlists.Add(playlist);
|
||||
await context.SaveChangesAsync();
|
||||
long storedVersion = playlist.Version;
|
||||
// A detached copy is the same shape the command mapping produces for an edit, so this is a real no-op round-trip instead of an object built only to satisfy the repository signature.
|
||||
PlaylistEntity incoming = await context.Playlists
|
||||
.AsNoTracking()
|
||||
.FirstAsync(candidate => candidate.Id == playlist.Id);
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await sut.UpdateAsync(incoming, CancellationToken.None);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
PlaylistEntity storedPlaylist = await context.Playlists
|
||||
.AsNoTracking()
|
||||
.FirstAsync(candidate => candidate.Id == playlist.Id);
|
||||
Assert.Equal(storedVersion, storedPlaylist.Version);
|
||||
Assert.Equal(7, storedPlaylist.EntryCount);
|
||||
Assert.Null(storedPlaylist.UpdatedOnUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenOnlyTheNameChanged_ShouldIncrementTheVersionAndPreserveTheEntryCount()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-playlistrepo-update-name-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
Guid userId = Guid.NewGuid();
|
||||
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
|
||||
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
|
||||
PlaylistRepository sut = new(context);
|
||||
context.Users.Add(_userEntityFixture.Create(id: userId));
|
||||
PlaylistEntity playlist = _playlistEntityFixture.Create(userId: userId, type: PlaylistType.Music, entryCount: 7);
|
||||
context.Playlists.Add(playlist);
|
||||
await context.SaveChangesAsync();
|
||||
long storedVersion = playlist.Version;
|
||||
// The mapped edit path does not load the entries, so its entry count is zero. The test proves the repository preserves the stored count instead of copying that zero onto the playlist.
|
||||
PlaylistEntity incoming = _playlistEntityFixture.Create(
|
||||
id: playlist.Id,
|
||||
userId: userId,
|
||||
name: "Renamed playlist",
|
||||
type: PlaylistType.Music,
|
||||
entryCount: 0);
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await sut.UpdateAsync(incoming, CancellationToken.None);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
PlaylistEntity storedPlaylist = await context.Playlists
|
||||
.AsNoTracking()
|
||||
.FirstAsync(candidate => candidate.Id == playlist.Id);
|
||||
Assert.Equal("Renamed playlist", storedPlaylist.Name);
|
||||
Assert.Equal(storedVersion + 1, storedPlaylist.Version);
|
||||
Assert.Equal(7, storedPlaylist.EntryCount);
|
||||
Assert.Equal(utcNow, storedPlaylist.UpdatedOnUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllForUserAsync_WhenTheUserHasPlaylists_ShouldReturnTheirStoredEntryCounts()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-playlistrepo-list-{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 firstPlaylist = _playlistEntityFixture.Create(userId: userId, type: PlaylistType.Music, entryCount: 7);
|
||||
PlaylistEntity secondPlaylist = _playlistEntityFixture.Create(userId: userId, type: PlaylistType.Music, entryCount: 0);
|
||||
context.Playlists.AddRange(firstPlaylist, secondPlaylist);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<PlaylistSummaryDto>> result = await sut.GetAllForUserAsync(userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(2, result.Value.Count);
|
||||
Assert.Contains(result.Value, playlist => playlist.Id == firstPlaylist.Id && playlist.EntryCount == 7);
|
||||
Assert.Contains(result.Value, playlist => playlist.Id == secondPlaylist.Id && playlist.EntryCount == 0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddScopeEntriesAsync_WhenTheWholeLibraryIsAppended_ShouldInsertCatalogueOrderAndUpdateTheEntryCount()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-playlistrepo-scope-{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));
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
List<TrackEntity> orderedTracks = await SeedCatalogueAsync(context, libraryId);
|
||||
PlaylistEntity playlist = _playlistEntityFixture.Create(userId: userId, type: PlaylistType.Music, entryCount: 0, version: 0);
|
||||
context.Playlists.Add(playlist);
|
||||
await context.SaveChangesAsync();
|
||||
DateTime updatedOnUtc = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
// Act
|
||||
Result<PlaylistBulkAddResultDto> result = await sut.AddScopeEntriesAsync(
|
||||
playlist.Id,
|
||||
userId,
|
||||
libraryId,
|
||||
artistId: null,
|
||||
albumId: null,
|
||||
PlaylistMediaItemType.MusicTrack,
|
||||
updatedOnUtc,
|
||||
CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(orderedTracks.Count, result.Value.AddedCount);
|
||||
List<PlaylistEntryEntity> storedEntries = await context.PlaylistEntries
|
||||
.AsNoTracking()
|
||||
.Where(entry => entry.PlaylistId == playlist.Id)
|
||||
.OrderBy(entry => entry.Position)
|
||||
.ToListAsync();
|
||||
Assert.Equal(orderedTracks.Select(track => track.Id), storedEntries.Select(entry => entry.MediaItemId));
|
||||
Assert.All(storedEntries, entry => Assert.NotEqual(Guid.Empty, entry.Id));
|
||||
// The generated entry Ids must be stored in the same text form the provider uses, so the appended entry can still be read back by
|
||||
// its Id through a normal Entity Framework parameter. It is the last entry, so its display position comes from the stored count.
|
||||
Result<PlaylistEntryDto?> storedEntryResult = await sut.GetAppendedEntryDetailsForUserAsync(playlist.Id, userId, storedEntries[^1].Id, CancellationToken.None);
|
||||
Assert.False(storedEntryResult.IsFailure);
|
||||
Assert.NotNull(storedEntryResult.Value);
|
||||
Assert.Equal(orderedTracks.Count - 1, storedEntryResult.Value!.DisplayPosition);
|
||||
Assert.NotNull(storedEntryResult.Value.Display);
|
||||
PlaylistEntity storedPlaylist = await context.Playlists
|
||||
.AsNoTracking()
|
||||
.FirstAsync(candidate => candidate.Id == playlist.Id);
|
||||
Assert.Equal(orderedTracks.Count, storedPlaylist.EntryCount);
|
||||
Assert.Equal(1L, storedPlaylist.Version);
|
||||
Assert.Equal(updatedOnUtc, storedPlaylist.UpdatedOnUtc);
|
||||
// A window read reports the stored count of the whole playlist while materializing only the requested window.
|
||||
Result<PlaylistDetailsDto?> detailsResult = await sut.GetDetailsForUserAsync(playlist.Id, userId, offset: 0, limit: 2, CancellationToken.None);
|
||||
Assert.False(detailsResult.IsFailure);
|
||||
Assert.NotNull(detailsResult.Value);
|
||||
Assert.Equal(orderedTracks.Count, detailsResult.Value!.Playlist.EntryCount);
|
||||
Assert.Equal(2, detailsResult.Value.Entries.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddScopeEntriesAsync_WhenAnAlbumIsSpecified_ShouldAppendOnlyThatAlbum()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-playlistrepo-scope-album-{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));
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
List<TrackEntity> orderedTracks = await SeedCatalogueAsync(context, libraryId);
|
||||
AlbumEntity album = await context.Albums.FirstAsync(candidate => candidate.Id == orderedTracks[0].AlbumId);
|
||||
PlaylistEntity playlist = _playlistEntityFixture.Create(userId: userId, type: PlaylistType.Music, entryCount: 0, version: 0);
|
||||
context.Playlists.Add(playlist);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<PlaylistBulkAddResultDto> result = await sut.AddScopeEntriesAsync(
|
||||
playlist.Id,
|
||||
userId,
|
||||
libraryId,
|
||||
artistId: album.ArtistId,
|
||||
albumId: album.Id,
|
||||
PlaylistMediaItemType.MusicTrack,
|
||||
DateTime.UtcNow,
|
||||
CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
List<Guid> storedMediaItemIds = await context.PlaylistEntries
|
||||
.AsNoTracking()
|
||||
.Where(entry => entry.PlaylistId == playlist.Id)
|
||||
.OrderBy(entry => entry.Position)
|
||||
.Select(entry => entry.MediaItemId)
|
||||
.ToListAsync();
|
||||
Assert.Equal(
|
||||
orderedTracks.Where(track => track.AlbumId == album.Id).Select(track => track.Id),
|
||||
storedMediaItemIds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddEntriesAsync_WhenALaterBatchFails_ShouldLeaveNoPrefixWhenTheAmbientTransactionIsRolledBack()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-playlistrepo-batch-rollback-{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 = _playlistEntityFixture.Create(userId: userId, type: PlaylistType.Music, entryCount: 0, version: 0);
|
||||
context.Playlists.Add(playlist);
|
||||
await context.SaveChangesAsync();
|
||||
List<Guid> mediaItemIds = [.. Enumerable.Range(0, 501).Select(_ => Guid.NewGuid())];
|
||||
List<Guid> entryIds = [.. mediaItemIds.Select(_ => Guid.NewGuid())];
|
||||
// The duplicate in the second batch violates the primary key after the first batch was already inserted.
|
||||
entryIds[500] = entryIds[0];
|
||||
|
||||
// Act
|
||||
// This is the transaction the request middleware owns in production. The repository must not take a decision about it: the middleware rolls it back once the response is known to be unsuccessful.
|
||||
using IDbContextTransaction ambientTransaction = await context.Database.BeginTransactionAsync();
|
||||
// A primary key violation is not one of the mapped persistence conflicts, so it takes the generic failure path.
|
||||
await Assert.ThrowsAsync<SqliteException>(() => sut.AddEntriesAsync(
|
||||
playlist.Id,
|
||||
userId,
|
||||
mediaItemIds,
|
||||
PlaylistMediaItemType.MusicTrack,
|
||||
entryIds,
|
||||
DateTime.UtcNow,
|
||||
CancellationToken.None));
|
||||
|
||||
// The middleware rolls the request transaction back after a failed response.
|
||||
await ambientTransaction.RollbackAsync();
|
||||
|
||||
// Assert
|
||||
// The ambient transaction has been rolled back, so another connection can read the database and sees no partial prefix.
|
||||
using LuminaDbContext verificationContext = CreateContext(anchorConnection);
|
||||
Assert.Equal(0, await verificationContext.PlaylistEntries.CountAsync(entry => entry.PlaylistId == playlist.Id));
|
||||
PlaylistEntity storedPlaylist = await verificationContext.Playlists
|
||||
.AsNoTracking()
|
||||
.FirstAsync(candidate => candidate.Id == playlist.Id);
|
||||
Assert.Equal(0, storedPlaylist.EntryCount);
|
||||
Assert.Equal(0L, storedPlaylist.Version);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteByIdAsync_WhenThePlaylistExists_ShouldRemoveThePlaylistAndItsEntries()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-playlistrepo-delete-{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));
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
PlaylistEntryEntity firstEntry = _playlistEntryEntityFixture.Create(playlistId: playlistId, position: 1_000_000_000L);
|
||||
PlaylistEntryEntity secondEntry = _playlistEntryEntityFixture.Create(playlistId: playlistId, position: 2_000_000_000L);
|
||||
PlaylistEntity playlist = _playlistEntityFixture.Create(
|
||||
id: playlistId,
|
||||
userId: userId,
|
||||
type: PlaylistType.Music,
|
||||
entries: [firstEntry, secondEntry],
|
||||
entryCount: 2);
|
||||
context.Playlists.Add(playlist);
|
||||
await context.SaveChangesAsync();
|
||||
// A real delete request starts with no tracked entries, so the database cascade is the path that has to remove them.
|
||||
context.ChangeTracker.Clear();
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await sut.DeleteByIdAsync(playlistId, CancellationToken.None);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.False(await context.Playlists.AsNoTracking().AnyAsync(candidate => candidate.Id == playlistId));
|
||||
Assert.False(await context.PlaylistEntries.AsNoTracking().AnyAsync(entry => entry.PlaylistId == playlistId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteByIdAsync_WhenThePlaylistDoesNotExist_ShouldReturnPlaylistNotFound()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-playlistrepo-delete-missing-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
PlaylistRepository sut = new(context);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await sut.DeleteByIdAsync(Guid.NewGuid(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(DomainErrors.Playlists.PlaylistNotFound, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MoveEntryAsync_WhenMovingAnEntry_ShouldUpdateItsPositionWithoutChangingTheEntryCount()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-playlistrepo-move-{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));
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
PlaylistEntryEntity firstEntry = _playlistEntryEntityFixture.Create(playlistId: playlistId, position: 1_000_000_000L);
|
||||
PlaylistEntryEntity secondEntry = _playlistEntryEntityFixture.Create(playlistId: playlistId, position: 2_000_000_000L);
|
||||
PlaylistEntryEntity thirdEntry = _playlistEntryEntityFixture.Create(playlistId: playlistId, position: 3_000_000_000L);
|
||||
PlaylistEntity playlist = _playlistEntityFixture.Create(
|
||||
id: playlistId,
|
||||
userId: userId,
|
||||
type: PlaylistType.Music,
|
||||
entries: [firstEntry, secondEntry, thirdEntry],
|
||||
entryCount: 3,
|
||||
version: 0);
|
||||
context.Playlists.Add(playlist);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await sut.MoveEntryAsync(playlistId, userId, thirdEntry.Id, targetPosition: 0, DateTime.UtcNow, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
List<Guid> orderedMediaItemIds = await context.PlaylistEntries
|
||||
.AsNoTracking()
|
||||
.Where(entry => entry.PlaylistId == playlistId)
|
||||
.OrderBy(entry => entry.Position)
|
||||
.Select(entry => entry.MediaItemId)
|
||||
.ToListAsync();
|
||||
Assert.Equal([thirdEntry.MediaItemId, firstEntry.MediaItemId, secondEntry.MediaItemId], orderedMediaItemIds);
|
||||
PlaylistEntity storedPlaylist = await context.Playlists
|
||||
.AsNoTracking()
|
||||
.FirstAsync(candidate => candidate.Id == playlistId);
|
||||
Assert.Equal(3, storedPlaylist.EntryCount);
|
||||
Assert.Equal(1L, storedPlaylist.Version);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveEntryAsync_WhenTheEntryExists_ShouldDecrementTheStoredEntryCount()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-playlistrepo-remove-{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));
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
PlaylistEntryEntity firstEntry = _playlistEntryEntityFixture.Create(playlistId: playlistId, position: 1_000_000_000L);
|
||||
PlaylistEntryEntity secondEntry = _playlistEntryEntityFixture.Create(playlistId: playlistId, position: 2_000_000_000L);
|
||||
PlaylistEntity playlist = _playlistEntityFixture.Create(
|
||||
id: playlistId,
|
||||
userId: userId,
|
||||
type: PlaylistType.Music,
|
||||
entries: [firstEntry, secondEntry],
|
||||
entryCount: 2,
|
||||
version: 0);
|
||||
context.Playlists.Add(playlist);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<int> result = await sut.RemoveEntryAsync(playlistId, userId, firstEntry.Id, DateTime.UtcNow, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
PlaylistEntity storedPlaylist = await context.Playlists
|
||||
.AsNoTracking()
|
||||
.FirstAsync(candidate => candidate.Id == playlistId);
|
||||
Assert.Equal(1, storedPlaylist.EntryCount);
|
||||
Assert.Equal(1L, storedPlaylist.Version);
|
||||
Assert.False(await context.PlaylistEntries.AsNoTracking().AnyAsync(entry => entry.Id == firstEntry.Id));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a real SQLite backed context with the auditing interceptor attached, so that audit columns behave exactly like in production.
|
||||
/// </summary>
|
||||
/// <param name="anchorConnection">The open in-memory SQLite connection that keeps the database alive for the duration of the test.</param>
|
||||
/// <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>The created context.</returns>
|
||||
private static LuminaDbContext CreateAuditedContext(SqliteConnection anchorConnection, Guid userId, DateTime utcNow)
|
||||
{
|
||||
ICurrentUserService currentUserService = Substitute.For<ICurrentUserService>();
|
||||
currentUserService.UserId.Returns(userId);
|
||||
IDateTimeProvider dateTimeProvider = Substitute.For<IDateTimeProvider>();
|
||||
dateTimeProvider.UtcNow.Returns(utcNow);
|
||||
LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>()
|
||||
.UseSqlite(anchorConnection.ConnectionString)
|
||||
.AddInterceptors(new UpdateAuditableEntitiesInterceptor(currentUserService, dateTimeProvider))
|
||||
.Options);
|
||||
context.Database.EnsureCreated();
|
||||
return context;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a real SQLite backed context without the auditing interceptor.
|
||||
/// </summary>
|
||||
/// <param name="anchorConnection">The open in-memory SQLite connection that keeps the database alive for the duration of the test.</param>
|
||||
/// <returns>The created context.</returns>
|
||||
private static LuminaDbContext CreateContext(SqliteConnection anchorConnection)
|
||||
{
|
||||
LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>()
|
||||
.UseSqlite(anchorConnection.ConnectionString)
|
||||
.Options);
|
||||
context.Database.EnsureCreated();
|
||||
return context;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds two artists and three albums with four tracks in total, and returns the tracks in the order a playlist must receive them.
|
||||
/// </summary>
|
||||
/// <param name="context">The context to seed.</param>
|
||||
/// <param name="libraryId">The Id of the library the catalogue belongs to.</param>
|
||||
/// <returns>The tracks in artist, album, disc and track order.</returns>
|
||||
private async Task<List<TrackEntity>> SeedCatalogueAsync(LuminaDbContext context, Guid libraryId)
|
||||
{
|
||||
ArtistEntity betaArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Beta Artist", includeAlbums: false, includeContributors: false);
|
||||
ArtistEntity alphaArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Alpha Artist", includeAlbums: false, includeContributors: false);
|
||||
context.Artists.AddRange(betaArtist, alphaArtist);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
AlbumEntity betaAlbum = _albumEntityFixture.Create(artistId: betaArtist.Id, libraryId: libraryId, title: "Only Album", includeTracks: false, includeMetadata: false);
|
||||
AlbumEntity alphaZetaAlbum = _albumEntityFixture.Create(artistId: alphaArtist.Id, libraryId: libraryId, title: "Zeta", includeTracks: false, includeMetadata: false);
|
||||
AlbumEntity alphaAlphaAlbum = _albumEntityFixture.Create(artistId: alphaArtist.Id, libraryId: libraryId, title: "Alpha", includeTracks: false, includeMetadata: false);
|
||||
context.Albums.AddRange(betaAlbum, alphaZetaAlbum, alphaAlphaAlbum);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
TrackEntity betaTrack = _trackEntityFixture.Create(albumId: betaAlbum.Id, libraryId: libraryId, title: "Beta One", trackNumber: 1, includeMetadata: false);
|
||||
TrackEntity alphaZetaTrack = _trackEntityFixture.Create(albumId: alphaZetaAlbum.Id, libraryId: libraryId, title: "Alpha Zeta One", trackNumber: 1, includeMetadata: false);
|
||||
TrackEntity alphaAlphaSecondTrack = _trackEntityFixture.Create(albumId: alphaAlphaAlbum.Id, libraryId: libraryId, title: "Alpha Alpha Two", trackNumber: 2, includeMetadata: false);
|
||||
TrackEntity alphaAlphaFirstTrack = _trackEntityFixture.Create(albumId: alphaAlphaAlbum.Id, libraryId: libraryId, title: "Alpha Alpha One", trackNumber: 1, includeMetadata: false);
|
||||
// The fixture randomizes the disc number, so it is pinned here to make the track order of the album deterministic.
|
||||
betaTrack.DiscNumber = 1;
|
||||
alphaZetaTrack.DiscNumber = 1;
|
||||
alphaAlphaSecondTrack.DiscNumber = 1;
|
||||
alphaAlphaFirstTrack.DiscNumber = 1;
|
||||
// The tracks are deliberately inserted out of catalogue order, so the test proves that the database produces the playlist order.
|
||||
context.Tracks.AddRange(betaTrack, alphaZetaTrack, alphaAlphaSecondTrack, alphaAlphaFirstTrack);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
return [alphaAlphaFirstTrack, alphaAlphaSecondTrack, alphaZetaTrack, betaTrack];
|
||||
}
|
||||
}
|
||||
+3
-1
@@ -48,7 +48,7 @@ public class LuminaDbContextTests : IDisposable
|
||||
|
||||
// Assert
|
||||
// The count assertion fails when a table is added or removed, reminding to update the assertions below.
|
||||
Assert.Equal(63, tableNames.Length);
|
||||
Assert.Equal(65, tableNames.Length);
|
||||
Assert.Contains("Books", tableNames);
|
||||
Assert.Contains("Users", tableNames);
|
||||
Assert.Contains("UserSettings", tableNames);
|
||||
@@ -109,6 +109,8 @@ public class LuminaDbContextTests : IDisposable
|
||||
Assert.Contains("MusicArtwork", tableNames);
|
||||
Assert.Contains("MusicLibraryScanItemMetadata", tableNames);
|
||||
Assert.Contains("MusicPlayRecords", tableNames);
|
||||
Assert.Contains("Playlists", tableNames);
|
||||
Assert.Contains("PlaylistEntries", tableNames);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
+2
-2
@@ -25,7 +25,7 @@ public class SqliteGuidTypeHandlerTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SetValue_WhenCalled_ShouldStoreTheGuidAsItsTextRepresentation()
|
||||
public void SetValue_WhenCalled_ShouldStoreTheGuidAsItsUpperCaseTextRepresentation()
|
||||
{
|
||||
// Arrange
|
||||
IDbDataParameter parameter = Substitute.For<IDbDataParameter>();
|
||||
@@ -35,7 +35,7 @@ public class SqliteGuidTypeHandlerTests
|
||||
_sut.SetValue(parameter, guid);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(guid.ToString(), (string?)parameter.Value);
|
||||
Assert.Equal(guid.ToString().ToUpperInvariant(), (string?)parameter.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Events;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="Playlist"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PlaylistTests
|
||||
{
|
||||
[Fact]
|
||||
public void Delete_WhenCalled_ShouldMarkThePlaylistAsDeletedAndRaiseOneEvent()
|
||||
{
|
||||
// Arrange
|
||||
Result<Playlist> createResult = Playlist.Create(
|
||||
UserId.Create(Guid.NewGuid()),
|
||||
"Playlist",
|
||||
Optional<string>.None(),
|
||||
PlaylistType.Music);
|
||||
Assert.False(createResult.IsFailure);
|
||||
Playlist playlist = createResult.Value;
|
||||
Assert.False(playlist.IsDeleted);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = playlist.Delete();
|
||||
List<IDomainEvent> domainEvents = playlist.GetDomainEvents();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.True(playlist.IsDeleted);
|
||||
Assert.Single(domainEvents);
|
||||
Assert.IsType<PlaylistDeletedDomainEvent>(domainEvents[0]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Delete_WhenCalledAgain_ShouldNotRaiseAnotherEvent()
|
||||
{
|
||||
// Arrange
|
||||
Result<Playlist> createResult = Playlist.Create(
|
||||
UserId.Create(Guid.NewGuid()),
|
||||
"Playlist",
|
||||
Optional<string>.None(),
|
||||
PlaylistType.Music);
|
||||
Assert.False(createResult.IsFailure);
|
||||
Playlist playlist = createResult.Value;
|
||||
playlist.Delete();
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = playlist.Delete();
|
||||
List<IDomainEvent> domainEvents = playlist.GetDomainEvents();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.True(playlist.IsDeleted);
|
||||
Assert.Single(domainEvents);
|
||||
}
|
||||
}
|
||||
+23
-50
@@ -1,7 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Users;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.Common.Base;
|
||||
@@ -29,7 +28,6 @@ public class LibraryOwnershipPolicyTests
|
||||
{
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly IUserRepository _mockUserRepository;
|
||||
private readonly ILibraryRepository _mockLibraryRepository;
|
||||
private readonly LibraryOwnershipPolicy _sut;
|
||||
private readonly AuthorizationServiceFixture _authorizationServiceFixture = new();
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
@@ -42,9 +40,7 @@ public class LibraryOwnershipPolicyTests
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_mockUserRepository = Substitute.For<IUserRepository>();
|
||||
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
_mockUnitOfWork.UserRepository.Returns(_mockUserRepository);
|
||||
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
|
||||
|
||||
_sut = new LibraryOwnershipPolicy(_mockUnitOfWork);
|
||||
}
|
||||
@@ -61,7 +57,6 @@ public class LibraryOwnershipPolicyTests
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
await _mockUserRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>());
|
||||
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -78,7 +73,6 @@ public class LibraryOwnershipPolicyTests
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -95,7 +89,6 @@ public class LibraryOwnershipPolicyTests
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -116,45 +109,6 @@ public class LibraryOwnershipPolicyTests
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EvaluateAsync_WhenLibraryDoesNotExist_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
UserEntity regularUser = _authorizationServiceFixture.CreateUserWithPermissions();
|
||||
LibraryOwnershipPolicyContext context = new(Guid.NewGuid());
|
||||
_mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<UserEntity?>(regularUser));
|
||||
_mockLibraryRepository.GetByIdAsync(context.LibraryId, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result<LibraryEntity?>.Success(null));
|
||||
|
||||
// Act
|
||||
bool result = await _sut.EvaluateAsync(userId, context, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EvaluateAsync_WhenGetLibraryFails_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
UserEntity regularUser = _authorizationServiceFixture.CreateUserWithPermissions();
|
||||
LibraryOwnershipPolicyContext context = new(Guid.NewGuid());
|
||||
_mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<UserEntity?>(regularUser));
|
||||
_mockLibraryRepository.GetByIdAsync(context.LibraryId, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Database.Error", "Failed to retrieve library"));
|
||||
|
||||
// Act
|
||||
bool result = await _sut.EvaluateAsync(userId, context, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -164,11 +118,10 @@ public class LibraryOwnershipPolicyTests
|
||||
Guid userId = Guid.NewGuid();
|
||||
UserEntity regularUser = _authorizationServiceFixture.CreateUserWithPermissions();
|
||||
LibraryEntity library = _libraryEntityFixture.Create(userId: userId);
|
||||
regularUser.Libraries.Add(library);
|
||||
LibraryOwnershipPolicyContext context = new(library.Id);
|
||||
_mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<UserEntity?>(regularUser));
|
||||
_mockLibraryRepository.GetByIdAsync(context.LibraryId, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(library));
|
||||
|
||||
// Act
|
||||
bool result = await _sut.EvaluateAsync(userId, context, CancellationToken.None);
|
||||
@@ -187,8 +140,6 @@ public class LibraryOwnershipPolicyTests
|
||||
LibraryOwnershipPolicyContext context = new(library.Id);
|
||||
_mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<UserEntity?>(regularUser));
|
||||
_mockLibraryRepository.GetByIdAsync(context.LibraryId, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(library));
|
||||
|
||||
// Act
|
||||
bool result = await _sut.EvaluateAsync(userId, context, CancellationToken.None);
|
||||
@@ -196,4 +147,26 @@ public class LibraryOwnershipPolicyTests
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EvaluateAsync_WhenMultipleLibrariesAreEvaluated_ShouldReadTheUserOnlyOnce()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
UserEntity regularUser = _authorizationServiceFixture.CreateUserWithPermissions();
|
||||
LibraryEntity ownedLibrary = _libraryEntityFixture.Create(userId: userId);
|
||||
regularUser.Libraries.Add(ownedLibrary);
|
||||
_mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<UserEntity?>(regularUser));
|
||||
|
||||
// Act
|
||||
// The policy is scoped to one request, so both library checks in that scope must share a single user read.
|
||||
bool canAccessOwnedLibrary = await _sut.EvaluateAsync(userId, new LibraryOwnershipPolicyContext(ownedLibrary.Id), CancellationToken.None);
|
||||
bool canAccessOtherLibrary = await _sut.EvaluateAsync(userId, new LibraryOwnershipPolicyContext(Guid.NewGuid()), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(canAccessOwnedLibrary);
|
||||
Assert.False(canAccessOtherLibrary);
|
||||
await _mockUserRepository.Received(1).GetByIdAsync(userId, cancellationToken: Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+194
@@ -1,10 +1,22 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.DomainEvents;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Presentation.Api.Common.Http;
|
||||
using Lumina.Presentation.Api.Common.Middlewares;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.Features;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
@@ -52,4 +64,186 @@ public class EventualConsistencyMiddlewareTests
|
||||
// Assert
|
||||
Assert.True(_nextInvoked);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_WhenTheClientAbortsAfterASuccessfulOperation_ShouldStillCommitTheTransaction()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-eventual-consistency-abort-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext dbContext = CreateContext(anchorConnection);
|
||||
using UnitOfWork unitOfWork = new(dbContext);
|
||||
await dbContext.Database.ExecuteSqlRawAsync("CREATE TABLE CommitProbe (Id INTEGER NOT NULL PRIMARY KEY);");
|
||||
CapturingHttpResponseFeature responseFeature = new();
|
||||
DefaultHttpContext httpContext = new();
|
||||
httpContext.Features.Set<IHttpResponseFeature>(responseFeature);
|
||||
httpContext.Request.Path = "/api/v1/probe";
|
||||
httpContext.Response.StatusCode = StatusCodes.Status200OK;
|
||||
using CancellationTokenSource cancellationTokenSource = new();
|
||||
httpContext.RequestAborted = cancellationTokenSource.Token;
|
||||
ILogger<EventualConsistencyMiddleware> mockLogger = Substitute.For<ILogger<EventualConsistencyMiddleware>>();
|
||||
EventualConsistencyMiddleware sut = new(
|
||||
async requestContext =>
|
||||
{
|
||||
await dbContext.Database.ExecuteSqlRawAsync("INSERT INTO CommitProbe (Id) VALUES (1);");
|
||||
// The abort happens after the operation has completed, which is exactly when the response token can already be cancelled as the completion callback runs.
|
||||
cancellationTokenSource.Cancel();
|
||||
},
|
||||
mockLogger);
|
||||
IDomainEventPublisher mockPublisher = Substitute.For<IDomainEventPublisher>();
|
||||
IDomainEventsQueue mockQueue = Substitute.For<IDomainEventsQueue>();
|
||||
|
||||
// Act
|
||||
await sut.InvokeAsync(httpContext, mockPublisher, unitOfWork, mockQueue);
|
||||
await responseFeature.InvokeCompletedCallbacksAsync();
|
||||
|
||||
// Assert
|
||||
using LuminaDbContext verificationContext = CreateContext(anchorConnection);
|
||||
int committedCount = await verificationContext.Database
|
||||
.SqlQueryRaw<int>("SELECT COUNT(*) AS \"Value\" FROM CommitProbe")
|
||||
.SingleAsync();
|
||||
Assert.Equal(1, committedCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_WhenTheResponseIsNotSuccessful_ShouldRollBackTheTransactionAndTheEvents()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-eventual-consistency-rollback-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext dbContext = CreateContext(anchorConnection);
|
||||
using UnitOfWork unitOfWork = new(dbContext);
|
||||
await dbContext.Database.ExecuteSqlRawAsync("CREATE TABLE CommitProbe (Id INTEGER NOT NULL PRIMARY KEY);");
|
||||
CapturingHttpResponseFeature responseFeature = new();
|
||||
DefaultHttpContext httpContext = new();
|
||||
httpContext.Features.Set<IHttpResponseFeature>(responseFeature);
|
||||
httpContext.Request.Path = "/api/v1/probe";
|
||||
ILogger<EventualConsistencyMiddleware> mockLogger = Substitute.For<ILogger<EventualConsistencyMiddleware>>();
|
||||
EventualConsistencyMiddleware sut = new(
|
||||
async requestContext =>
|
||||
{
|
||||
await dbContext.Database.ExecuteSqlRawAsync("INSERT INTO CommitProbe (Id) VALUES (1);");
|
||||
// A client abort is reported by the exception handling middleware as a non-success status, even though the request reached the database.
|
||||
requestContext.Response.StatusCode = StatusCodes.Status499ClientClosedRequest;
|
||||
},
|
||||
mockLogger);
|
||||
IDomainEventPublisher mockPublisher = Substitute.For<IDomainEventPublisher>();
|
||||
IDomainEventsQueue mockQueue = Substitute.For<IDomainEventsQueue>();
|
||||
|
||||
// Act
|
||||
await sut.InvokeAsync(httpContext, mockPublisher, unitOfWork, mockQueue);
|
||||
await responseFeature.InvokeCompletedCallbacksAsync();
|
||||
|
||||
// Assert
|
||||
using LuminaDbContext verificationContext = CreateContext(anchorConnection);
|
||||
int committedCount = await verificationContext.Database
|
||||
.SqlQueryRaw<int>("SELECT COUNT(*) AS \"Value\" FROM CommitProbe")
|
||||
.SingleAsync();
|
||||
Assert.Equal(0, committedCount);
|
||||
await mockPublisher.DidNotReceive().PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_WhenTheCommitFails_ShouldRollBackTheTransactionAndLogTheFailure()
|
||||
{
|
||||
// Arrange
|
||||
CapturingHttpResponseFeature responseFeature = new();
|
||||
DefaultHttpContext httpContext = new();
|
||||
httpContext.Features.Set<IHttpResponseFeature>(responseFeature);
|
||||
httpContext.Request.Path = "/api/v1/probe";
|
||||
httpContext.Response.StatusCode = StatusCodes.Status200OK;
|
||||
ILogger<EventualConsistencyMiddleware> mockLogger = Substitute.For<ILogger<EventualConsistencyMiddleware>>();
|
||||
EventualConsistencyMiddleware sut = new(_ => Task.CompletedTask, mockLogger);
|
||||
IUnitOfWork mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
mockUnitOfWork
|
||||
.CommitTransactionAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromException(new InvalidOperationException("commit failed")));
|
||||
IDomainEventPublisher mockPublisher = Substitute.For<IDomainEventPublisher>();
|
||||
IDomainEventsQueue mockQueue = Substitute.For<IDomainEventsQueue>();
|
||||
|
||||
// Act
|
||||
await sut.InvokeAsync(httpContext, mockPublisher, mockUnitOfWork, mockQueue);
|
||||
await responseFeature.InvokeCompletedCallbacksAsync();
|
||||
|
||||
// Assert
|
||||
// The completion callback must never leave a transaction open after a failed commit, and it must never publish events that belong to a transaction that did not commit.
|
||||
await mockUnitOfWork.Received(1).RollbackTransactionAsync(Arg.Any<CancellationToken>());
|
||||
await mockPublisher.DidNotReceive().PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a context backed by the provided in-memory SQLite connection.
|
||||
/// </summary>
|
||||
/// <param name="anchorConnection">The open in-memory SQLite connection that keeps the database alive for the duration of the test.</param>
|
||||
/// <returns>The created context.</returns>
|
||||
private static LuminaDbContext CreateContext(SqliteConnection anchorConnection)
|
||||
{
|
||||
LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>()
|
||||
.UseSqlite(anchorConnection.ConnectionString)
|
||||
.Options);
|
||||
context.Database.EnsureCreated();
|
||||
return context;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Response feature that captures the completed callbacks so a test can run them when the response ends.
|
||||
/// </summary>
|
||||
private sealed class CapturingHttpResponseFeature : IHttpResponseFeature
|
||||
{
|
||||
private readonly List<Func<Task>> _completedCallbacks = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the HTTP status code of the response.
|
||||
/// </summary>
|
||||
public int StatusCode { get; set; } = StatusCodes.Status200OK;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the reason phrase of the response.
|
||||
/// </summary>
|
||||
public string? ReasonPhrase { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the response headers.
|
||||
/// </summary>
|
||||
public IHeaderDictionary Headers { get; set; } = new HeaderDictionary();
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the response body stream.
|
||||
/// </summary>
|
||||
public Stream Body { get; set; } = Stream.Null;
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the response has already started.
|
||||
/// </summary>
|
||||
public bool HasStarted => false;
|
||||
|
||||
/// <summary>
|
||||
/// Registers a callback to be invoked when the response is about to start.
|
||||
/// </summary>
|
||||
/// <param name="callback">The callback to invoke.</param>
|
||||
/// <param name="state">The state passed to the callback.</param>
|
||||
public void OnStarting(Func<object, Task> callback, object state)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers a callback to be invoked when the response has completed.
|
||||
/// </summary>
|
||||
/// <param name="callback">The callback to invoke.</param>
|
||||
/// <param name="state">The state passed to the callback.</param>
|
||||
public void OnCompleted(Func<object, Task> callback, object state)
|
||||
{
|
||||
_completedCallbacks.Add(() => callback(state));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Invokes every callback that was registered through <see cref="OnCompleted"/>.
|
||||
/// </summary>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
public async Task InvokeCompletedCallbacksAsync()
|
||||
{
|
||||
foreach (Func<Task> callback in _completedCallbacks)
|
||||
await callback();
|
||||
}
|
||||
}
|
||||
}
|
||||
+3
-2
@@ -112,7 +112,7 @@ public class ExceptionHandlingMiddlewareTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_WhenNextThrowsOperationCanceledException_ShouldRethrow()
|
||||
public async Task InvokeAsync_WhenNextThrowsOperationCanceledException_ShouldRethrowAndReportTheRequestAsAborted()
|
||||
{
|
||||
// Arrange
|
||||
DefaultHttpContext context = new()
|
||||
@@ -125,7 +125,8 @@ public class ExceptionHandlingMiddlewareTests
|
||||
await Assert.ThrowsAsync<OperationCanceledException>(() => _sut.InvokeAsync(context));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(StatusCodes.Status200OK, context.Response.StatusCode);
|
||||
// An aborted request is still reported as a non-success status, so the eventual consistency middleware rolls its writes back.
|
||||
Assert.Equal(StatusCodes.Status499ClientClosedRequest, context.Response.StatusCode);
|
||||
Assert.Equal(0, context.Response.Body.Length);
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user