mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 08:11:10 +00:00
Implements tests for commit f777af07cf
This commit is contained in:
1 parent
99fc721d8c
commit
54b468855a
54 files changed
+10681
-17
No files matched your search
+318
-1
@@ -1,9 +1,10 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Time;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.DataAccess.Common.Interceptors;
|
||||
using Lumina.DataAccess.Core.Repositories.BookLibrary;
|
||||
@@ -11,6 +12,7 @@ using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
@@ -38,6 +40,7 @@ public class BookRepositoryTests
|
||||
private readonly IsbnEntityFixture _isbnEntityFixture = new();
|
||||
private readonly TagEntityFixture _tagEntityFixture = new();
|
||||
private readonly GenreEntityFixture _genreEntityFixture = new();
|
||||
private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new();
|
||||
|
||||
[Fact]
|
||||
public async Task ResetEnrichmentStateForPathsAsync_WhenCalled_ShouldResetTheMetadataAndArtworkStatusesForThePaths()
|
||||
@@ -474,6 +477,320 @@ public class BookRepositoryTests
|
||||
Assert.Equal(bookOfAnotherLibrary.Id, survivor.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdsAsync_WhenIdsIsEmpty_ShouldReturnAnEmptyList()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-getbyids-empty-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
BookRepository sut = new(context);
|
||||
context.Books.Add(_bookEntityFixture.Create(includeMetadata: false));
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<BookEntity>> result = await sut.GetByIdsAsync([], false, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Empty(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdsAsync_WhenCalled_ShouldReturnOnlyTheRequestedBooks()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-getbyids-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
BookRepository sut = new(context);
|
||||
BookEntity firstBook = _bookEntityFixture.Create(includeMetadata: false);
|
||||
BookEntity secondBook = _bookEntityFixture.Create(includeMetadata: false);
|
||||
BookEntity thirdBook = _bookEntityFixture.Create(includeMetadata: false);
|
||||
context.Books.AddRange(firstBook, secondBook, thirdBook);
|
||||
await context.SaveChangesAsync();
|
||||
context.ChangeTracker.Clear();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<BookEntity>> result = await sut.GetByIdsAsync([firstBook.Id, thirdBook.Id], false, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(2, result.Value.Count);
|
||||
Assert.Contains(result.Value, book => book.Id == firstBook.Id);
|
||||
Assert.Contains(result.Value, book => book.Id == thirdBook.Id);
|
||||
Assert.DoesNotContain(result.Value, book => book.Id == secondBook.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdsAsync_WhenNavigationPropertiesShouldNotBeIncluded_ShouldNotLoadTheRelatedCollections()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-getbyids-notracking-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
BookRepository sut = new(context);
|
||||
MediaContributorEntity author = _mediaContributorEntityFixture.Create(displayName: "Frank Herbert");
|
||||
BookEntity book = _bookEntityFixture.Create(includeMetadata: false);
|
||||
book.Tags = [_tagEntityFixture.Create(name: "HiddenTag")];
|
||||
book.Genres = [_genreEntityFixture.Create(name: "HiddenGenre")];
|
||||
book.ISBNs = [_isbnEntityFixture.Create(value: "9783161484100", format: IsbnFormat.Isbn13)];
|
||||
book.Ratings = [_bookRatingEntityFixture.Create(value: 4.5M, maxValue: 5, source: BookRatingSource.Goodreads, voteCount: 100)];
|
||||
book.Contributors = [_bookContributorEntityFixture.Create(bookId: book.Id, mediaContributorId: author.Id, role: MediaContributorRole.Author)];
|
||||
book.Artwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)];
|
||||
context.Books.Add(book);
|
||||
context.MediaContributors.Add(author);
|
||||
await context.SaveChangesAsync();
|
||||
context.ChangeTracker.Clear();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<BookEntity>> result = await sut.GetByIdsAsync([book.Id], false, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
BookEntity returnedBook = Assert.Single(result.Value);
|
||||
Assert.Equal(book.Id, returnedBook.Id);
|
||||
Assert.Empty(returnedBook.Tags);
|
||||
Assert.Empty(returnedBook.Genres);
|
||||
Assert.Empty(returnedBook.Contributors);
|
||||
Assert.Empty(returnedBook.Artwork);
|
||||
// ISBNs and Ratings are owned collections, so EF Core materializes them together with the book even when the optional graph is not
|
||||
// included. The flag only controls the non-owned navigation properties, which is why those are asserted empty above.
|
||||
Assert.Single(returnedBook.ISBNs);
|
||||
Assert.Single(returnedBook.Ratings);
|
||||
// The rows are read without tracking, so the read statistics never leak into the unit of work.
|
||||
Assert.Empty(context.ChangeTracker.Entries<BookEntity>());
|
||||
Assert.Equal(EntityState.Detached, context.Entry(returnedBook).State);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdsAsync_WhenNavigationPropertiesShouldBeIncluded_ShouldLoadTheRelatedCollections()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-getbyids-include-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
BookRepository sut = new(context);
|
||||
MediaContributorEntity author = _mediaContributorEntityFixture.Create(displayName: "Frank Herbert");
|
||||
BookEntity book = _bookEntityFixture.Create(includeMetadata: false);
|
||||
book.Tags = [_tagEntityFixture.Create(name: "LoadedTag"), _tagEntityFixture.Create(name: "SecondLoadedTag")];
|
||||
book.Genres = [_genreEntityFixture.Create(name: "LoadedGenre")];
|
||||
book.ISBNs = [_isbnEntityFixture.Create(value: "9783161484100", format: IsbnFormat.Isbn13)];
|
||||
book.Ratings = [_bookRatingEntityFixture.Create(value: 4.5M, maxValue: 5, source: BookRatingSource.Goodreads, voteCount: 100)];
|
||||
book.Contributors = [_bookContributorEntityFixture.Create(bookId: book.Id, mediaContributorId: author.Id, role: MediaContributorRole.Author)];
|
||||
book.Artwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched, fileName: "cover.jpg")];
|
||||
context.Books.Add(book);
|
||||
context.MediaContributors.Add(author);
|
||||
await context.SaveChangesAsync();
|
||||
context.ChangeTracker.Clear();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<BookEntity>> result = await sut.GetByIdsAsync([book.Id], true, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
BookEntity returnedBook = Assert.Single(result.Value);
|
||||
Assert.Equal(2, returnedBook.Tags.Count);
|
||||
Assert.Single(returnedBook.Genres);
|
||||
Assert.Equal("9783161484100", Assert.Single(returnedBook.ISBNs).Value);
|
||||
Assert.Equal(4.5M, Assert.Single(returnedBook.Ratings).Value);
|
||||
Assert.Equal(author.Id, Assert.Single(returnedBook.Contributors).MediaContributorId);
|
||||
Assert.Equal("cover.jpg", Assert.Single(returnedBook.Artwork).FileName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdsAsync_WhenExactlyFiveHundredIdsAreRequested_ShouldReturnEveryBook()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-getbyids-boundary-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
BookRepository sut = new(context);
|
||||
const int BOOK_COUNT = 500;
|
||||
List<BookEntity> books = CreateBooks(BOOK_COUNT);
|
||||
context.Books.AddRange(books);
|
||||
await context.SaveChangesAsync();
|
||||
context.ChangeTracker.Clear();
|
||||
|
||||
// Act
|
||||
// A single full chunk proves the boundary does not drop the last chunk.
|
||||
Result<IReadOnlyList<BookEntity>> result = await sut.GetByIdsAsync([.. books.Select(book => book.Id)], false, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(BOOK_COUNT, result.Value.Count);
|
||||
Assert.Equal(
|
||||
books.Select(book => book.Id).OrderBy(id => id),
|
||||
result.Value.Select(book => book.Id).OrderBy(id => id));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdsAsync_WhenMoreThanFiveHundredIdsAreRequested_ShouldReturnEveryBook()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-getbyids-chunks-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
BookRepository sut = new(context);
|
||||
const int BOOK_COUNT = 501;
|
||||
List<BookEntity> books = CreateBooks(BOOK_COUNT);
|
||||
context.Books.AddRange(books);
|
||||
await context.SaveChangesAsync();
|
||||
context.ChangeTracker.Clear();
|
||||
|
||||
// Act
|
||||
// The lookup is chunked in batches of 500, so the 501st Id proves the second chunk is queried as well.
|
||||
Result<IReadOnlyList<BookEntity>> result = await sut.GetByIdsAsync([.. books.Select(book => book.Id)], false, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(BOOK_COUNT, result.Value.Count);
|
||||
Assert.Equal(
|
||||
books.Select(book => book.Id).OrderBy(id => id),
|
||||
result.Value.Select(book => book.Id).OrderBy(id => id));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAuthorsDisplayNamesByBookIdsAsync_WhenBookHasMultipleAuthors_ShouldReturnTheMinimumAuthorDisplayName()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-authors-min-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
BookRepository sut = new(context);
|
||||
BookEntity book = _bookEntityFixture.Create(includeMetadata: false);
|
||||
MediaContributorEntity firstAuthor = _mediaContributorEntityFixture.Create(displayName: "Zoe Author");
|
||||
MediaContributorEntity secondAuthor = _mediaContributorEntityFixture.Create(displayName: "Alice Author");
|
||||
MediaContributorEntity translator = _mediaContributorEntityFixture.Create(displayName: "Aaron Translator");
|
||||
context.Books.Add(book);
|
||||
context.MediaContributors.AddRange(firstAuthor, secondAuthor, translator);
|
||||
await context.SaveChangesAsync();
|
||||
context.BookContributors.AddRange(
|
||||
_bookContributorEntityFixture.Create(bookId: book.Id, mediaContributorId: firstAuthor.Id, role: MediaContributorRole.Author),
|
||||
_bookContributorEntityFixture.Create(bookId: book.Id, mediaContributorId: secondAuthor.Id, role: MediaContributorRole.Author),
|
||||
// The translator sorts before every author, so the result would change if a non-Author role were included.
|
||||
_bookContributorEntityFixture.Create(bookId: book.Id, mediaContributorId: translator.Id, role: MediaContributorRole.Translator));
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyDictionary<Guid, string?>> result = await sut.GetAuthorsDisplayNamesByBookIdsAsync([book.Id], CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal("Alice Author", result.Value[book.Id]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAuthorsDisplayNamesByBookIdsAsync_WhenABookIsNotRequested_ShouldNotReturnIt()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-authors-requested-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
BookRepository sut = new(context);
|
||||
BookEntity requestedBook = _bookEntityFixture.Create(includeMetadata: false);
|
||||
BookEntity bookNotRequested = _bookEntityFixture.Create(includeMetadata: false);
|
||||
MediaContributorEntity requestedAuthor = _mediaContributorEntityFixture.Create(displayName: "Requested Author");
|
||||
MediaContributorEntity otherAuthor = _mediaContributorEntityFixture.Create(displayName: "Other Author");
|
||||
context.Books.AddRange(requestedBook, bookNotRequested);
|
||||
context.MediaContributors.AddRange(requestedAuthor, otherAuthor);
|
||||
await context.SaveChangesAsync();
|
||||
context.BookContributors.AddRange(
|
||||
_bookContributorEntityFixture.Create(bookId: requestedBook.Id, mediaContributorId: requestedAuthor.Id, role: MediaContributorRole.Author),
|
||||
_bookContributorEntityFixture.Create(bookId: bookNotRequested.Id, mediaContributorId: otherAuthor.Id, role: MediaContributorRole.Author));
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyDictionary<Guid, string?>> result = await sut.GetAuthorsDisplayNamesByBookIdsAsync([requestedBook.Id], CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal("Requested Author", result.Value[requestedBook.Id]);
|
||||
Assert.DoesNotContain(bookNotRequested.Id, result.Value.Keys);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAuthorsDisplayNamesByBookIdsAsync_WhenBookIdsIsEmpty_ShouldReturnAnEmptyDictionary()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-authors-empty-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
BookRepository sut = new(context);
|
||||
BookEntity book = _bookEntityFixture.Create(includeMetadata: false);
|
||||
MediaContributorEntity author = _mediaContributorEntityFixture.Create();
|
||||
context.Books.Add(book);
|
||||
context.MediaContributors.Add(author);
|
||||
await context.SaveChangesAsync();
|
||||
context.BookContributors.Add(
|
||||
_bookContributorEntityFixture.Create(bookId: book.Id, mediaContributorId: author.Id, role: MediaContributorRole.Author));
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyDictionary<Guid, string?>> result = await sut.GetAuthorsDisplayNamesByBookIdsAsync([], CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Empty(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAuthorsDisplayNamesByBookIdsAsync_WhenMoreThanFiveHundredIdsAreRequested_ShouldReturnTheAuthorOfEveryRequestedBook()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-authors-chunks-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
BookRepository sut = new(context);
|
||||
const int BOOK_COUNT = 501;
|
||||
List<BookEntity> books = CreateBooks(BOOK_COUNT);
|
||||
MediaContributorEntity author = _mediaContributorEntityFixture.Create(displayName: "Shared Author");
|
||||
context.Books.AddRange(books);
|
||||
context.MediaContributors.Add(author);
|
||||
await context.SaveChangesAsync();
|
||||
context.BookContributors.AddRange([.. books.Select(book =>
|
||||
_bookContributorEntityFixture.Create(bookId: book.Id, mediaContributorId: author.Id, role: MediaContributorRole.Author))]);
|
||||
await context.SaveChangesAsync();
|
||||
context.ChangeTracker.Clear();
|
||||
|
||||
// Act
|
||||
// The lookup is chunked in batches of 500, so the 501st book proves the second chunk is queried as well.
|
||||
Result<IReadOnlyDictionary<Guid, string?>> result = await sut.GetAuthorsDisplayNamesByBookIdsAsync(
|
||||
[.. books.Select(book => book.Id)], CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(BOOK_COUNT, result.Value.Count);
|
||||
Assert.All(result.Value.Keys, bookId => Assert.Equal("Shared Author", result.Value[bookId]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of books with distinct paths and empty metadata collections, so that the chunked lookups can be exercised without extra graph data.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of books to create.</param>
|
||||
/// <returns>The created books.</returns>
|
||||
private List<BookEntity> CreateBooks(int count)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => _bookEntityFixture.Create(
|
||||
path: $"/books/generated-{Guid.NewGuid():N}.epub", includeMetadata: false))];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a real SQLite backed context, so that the stored values are read exactly as they were written.
|
||||
/// </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>
|
||||
/// Creates a real SQLite backed context with the auditing interceptor attached, so that audit columns behave exactly like in production.
|
||||
/// </summary>
|
||||
|
||||
+408
@@ -0,0 +1,408 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.DataAccess.Core.Repositories.MediaConsumption;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.IntegrationTests.Core.Repositories.MediaConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="ConsumptionStatisticsRepository"/> class, exercising it against a real SQLite database.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ConsumptionStatisticsRepositoryTests
|
||||
{
|
||||
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
[Fact]
|
||||
public async Task GetForUserAsync_WhenTheUserHasRecords_ShouldReturnOnlyTheirRecordsWithEveryPersistedValue()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-consumptionstats-get-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
ConsumptionStatisticsRepository sut = new(context);
|
||||
|
||||
Guid userId = Guid.NewGuid();
|
||||
Guid otherUserId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid movieMediaItemId = Guid.NewGuid();
|
||||
Guid bookMediaItemId = Guid.NewGuid();
|
||||
DateTime movieStartedOnUtc = new(2025, 1, 1, 8, 0, 0, DateTimeKind.Utc);
|
||||
DateTime movieLastActivityOnUtc = new(2025, 1, 1, 8, 45, 0, DateTimeKind.Utc);
|
||||
DateTime movieEndedOnUtc = new(2025, 1, 1, 9, 0, 0, DateTimeKind.Utc);
|
||||
MediaConsumptionRecordEntity movieRecord = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.Movie,
|
||||
mediaItemId: movieMediaItemId,
|
||||
status: ConsumptionStatus.Completed,
|
||||
startedOnUtc: movieStartedOnUtc,
|
||||
lastActivityOnUtc: movieLastActivityOnUtc,
|
||||
endedOnUtc: movieEndedOnUtc,
|
||||
consumedDurationMilliseconds: 1_800_000,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 1_234_567,
|
||||
includeLastPositionLocation: false,
|
||||
lastProgressFraction: 0.42,
|
||||
consecutivePagesRead: 0,
|
||||
version: 7);
|
||||
MediaConsumptionRecordEntity bookRecord = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.Book,
|
||||
mediaItemId: bookMediaItemId,
|
||||
status: ConsumptionStatus.InProgress,
|
||||
startedOnUtc: new DateTime(2025, 1, 1, 10, 0, 0, DateTimeKind.Utc),
|
||||
lastActivityOnUtc: new DateTime(2025, 1, 1, 10, 20, 0, DateTimeKind.Utc),
|
||||
includeEndedOnUtc: false,
|
||||
consumedDurationMilliseconds: 90_000,
|
||||
lastPositionKind: MediaPositionKind.Location,
|
||||
includeLastPositionTimeOffsetMilliseconds: false,
|
||||
lastPositionLocation: "chapter-3:paragraph-14",
|
||||
lastProgressFraction: 0.17,
|
||||
consecutivePagesRead: 12,
|
||||
version: 1);
|
||||
MediaConsumptionRecordEntity otherUserRecord = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: otherUserId, libraryId: libraryId, mediaKind: MediaKind.Movie);
|
||||
context.Users.AddRange(_userEntityFixture.Create(id: userId), _userEntityFixture.Create(id: otherUserId));
|
||||
context.MediaConsumptionRecords.AddRange(movieRecord, bookRecord, otherUserRecord);
|
||||
await context.SaveChangesAsync();
|
||||
context.ChangeTracker.Clear();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<MediaConsumptionRecordEntity>> result = await sut.GetForUserAsync(userId, null, null, null, null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(2, result.Value.Count);
|
||||
Assert.DoesNotContain(result.Value, record => record.Id == otherUserRecord.Id);
|
||||
|
||||
MediaConsumptionRecordEntity storedMovieRecord = result.Value.Single(record => record.Id == movieRecord.Id);
|
||||
Assert.Equal(userId, storedMovieRecord.UserId);
|
||||
Assert.Equal(libraryId, storedMovieRecord.LibraryId);
|
||||
Assert.Equal(MediaKind.Movie, storedMovieRecord.MediaKind);
|
||||
Assert.Equal(movieMediaItemId, storedMovieRecord.MediaItemId);
|
||||
Assert.Equal(ConsumptionStatus.Completed, storedMovieRecord.Status);
|
||||
Assert.Equal(movieStartedOnUtc, storedMovieRecord.StartedOnUtc);
|
||||
Assert.Equal(movieLastActivityOnUtc, storedMovieRecord.LastActivityOnUtc);
|
||||
Assert.Equal(movieEndedOnUtc, storedMovieRecord.EndedOnUtc);
|
||||
Assert.Equal(1_800_000L, storedMovieRecord.ConsumedDurationMilliseconds);
|
||||
Assert.Equal(MediaPositionKind.TimeOffset, storedMovieRecord.LastPositionKind);
|
||||
Assert.Equal(1_234_567L, storedMovieRecord.LastPositionTimeOffsetMilliseconds);
|
||||
Assert.Null(storedMovieRecord.LastPositionLocation);
|
||||
Assert.Equal(0.42, storedMovieRecord.LastProgressFraction);
|
||||
Assert.Equal(0, storedMovieRecord.ConsecutivePagesRead);
|
||||
Assert.Equal(7L, storedMovieRecord.Version);
|
||||
|
||||
MediaConsumptionRecordEntity storedBookRecord = result.Value.Single(record => record.Id == bookRecord.Id);
|
||||
Assert.Equal(MediaKind.Book, storedBookRecord.MediaKind);
|
||||
Assert.Equal(bookMediaItemId, storedBookRecord.MediaItemId);
|
||||
Assert.Equal(ConsumptionStatus.InProgress, storedBookRecord.Status);
|
||||
Assert.Null(storedBookRecord.EndedOnUtc);
|
||||
Assert.Equal(90_000L, storedBookRecord.ConsumedDurationMilliseconds);
|
||||
Assert.Equal(MediaPositionKind.Location, storedBookRecord.LastPositionKind);
|
||||
Assert.Null(storedBookRecord.LastPositionTimeOffsetMilliseconds);
|
||||
Assert.Equal("chapter-3:paragraph-14", storedBookRecord.LastPositionLocation);
|
||||
Assert.Equal(0.17, storedBookRecord.LastProgressFraction);
|
||||
Assert.Equal(12, storedBookRecord.ConsecutivePagesRead);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetForUserAsync_WhenAnotherUserHasAMatchingRecord_ShouldNotReturnIt()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-consumptionstats-otheruser-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
ConsumptionStatisticsRepository sut = new(context);
|
||||
|
||||
Guid userId = Guid.NewGuid();
|
||||
Guid otherUserId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
DateTime startedOnUtc = new(2025, 1, 15, 0, 0, 0, DateTimeKind.Utc);
|
||||
MediaConsumptionRecordEntity userRecord = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: userId, libraryId: libraryId, mediaKind: MediaKind.Movie, startedOnUtc: startedOnUtc);
|
||||
MediaConsumptionRecordEntity otherUserRecord = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: otherUserId, libraryId: libraryId, mediaKind: MediaKind.Movie, startedOnUtc: startedOnUtc);
|
||||
context.Users.AddRange(_userEntityFixture.Create(id: userId), _userEntityFixture.Create(id: otherUserId));
|
||||
context.MediaConsumptionRecords.AddRange(userRecord, otherUserRecord);
|
||||
await context.SaveChangesAsync();
|
||||
context.ChangeTracker.Clear();
|
||||
|
||||
// Act
|
||||
// Every other filter matches the foreign record too, so the user scope has to be the reason it is excluded.
|
||||
Result<IReadOnlyList<MediaConsumptionRecordEntity>> result = await sut.GetForUserAsync(
|
||||
userId, libraryId, MediaKind.Movie, startedOnUtc.AddDays(-1), startedOnUtc.AddDays(1), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
MediaConsumptionRecordEntity returnedRecord = Assert.Single(result.Value);
|
||||
Assert.Equal(userRecord.Id, returnedRecord.Id);
|
||||
Assert.Equal(userId, returnedRecord.UserId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetForUserAsync_WhenTheRangeBoundariesMatchExactly_ShouldIncludeTheBoundaryRecords()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-consumptionstats-boundary-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
ConsumptionStatisticsRepository sut = new(context);
|
||||
|
||||
Guid userId = Guid.NewGuid();
|
||||
DateTime fromUtc = new(2025, 1, 10, 12, 0, 0, DateTimeKind.Utc);
|
||||
DateTime toUtc = new(2025, 1, 20, 12, 0, 0, DateTimeKind.Utc);
|
||||
MediaConsumptionRecordEntity recordBeforeTheRange = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: userId, startedOnUtc: fromUtc.AddMilliseconds(-1));
|
||||
MediaConsumptionRecordEntity recordAtTheStartBoundary = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: userId, startedOnUtc: fromUtc);
|
||||
MediaConsumptionRecordEntity recordInsideTheRange = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: userId, startedOnUtc: fromUtc.AddDays(5));
|
||||
MediaConsumptionRecordEntity recordAtTheEndBoundary = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: userId, startedOnUtc: toUtc);
|
||||
MediaConsumptionRecordEntity recordAfterTheRange = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: userId, startedOnUtc: toUtc.AddMilliseconds(1));
|
||||
context.Users.Add(_userEntityFixture.Create(id: userId));
|
||||
context.MediaConsumptionRecords.AddRange(
|
||||
recordBeforeTheRange, recordAtTheStartBoundary, recordInsideTheRange, recordAtTheEndBoundary, recordAfterTheRange);
|
||||
await context.SaveChangesAsync();
|
||||
context.ChangeTracker.Clear();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<MediaConsumptionRecordEntity>> result = await sut.GetForUserAsync(userId, null, null, fromUtc, toUtc, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(3, result.Value.Count);
|
||||
Assert.Contains(result.Value, record => record.Id == recordAtTheStartBoundary.Id);
|
||||
Assert.Contains(result.Value, record => record.Id == recordInsideTheRange.Id);
|
||||
Assert.Contains(result.Value, record => record.Id == recordAtTheEndBoundary.Id);
|
||||
Assert.DoesNotContain(result.Value, record => record.Id == recordBeforeTheRange.Id);
|
||||
Assert.DoesNotContain(result.Value, record => record.Id == recordAfterTheRange.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetForUserAsync_WhenAllFiltersAreProvided_ShouldApplyEveryFilter()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-consumptionstats-allfilters-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
ConsumptionStatisticsRepository sut = new(context);
|
||||
|
||||
Guid userId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
DateTime fromUtc = new(2025, 1, 10, 0, 0, 0, DateTimeKind.Utc);
|
||||
DateTime toUtc = new(2025, 1, 20, 0, 0, 0, DateTimeKind.Utc);
|
||||
MediaConsumptionRecordEntity matchingRecord = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: userId, libraryId: libraryId, mediaKind: MediaKind.Movie, startedOnUtc: new DateTime(2025, 1, 15, 0, 0, 0, DateTimeKind.Utc));
|
||||
MediaConsumptionRecordEntity recordOfAnotherLibrary = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: userId, libraryId: Guid.NewGuid(), mediaKind: MediaKind.Movie, startedOnUtc: new DateTime(2025, 1, 15, 0, 0, 0, DateTimeKind.Utc));
|
||||
MediaConsumptionRecordEntity recordOfAnotherKind = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: userId, libraryId: libraryId, mediaKind: MediaKind.Book, startedOnUtc: new DateTime(2025, 1, 15, 0, 0, 0, DateTimeKind.Utc));
|
||||
MediaConsumptionRecordEntity recordOutsideTheRange = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: userId, libraryId: libraryId, mediaKind: MediaKind.Movie, startedOnUtc: toUtc.AddDays(1));
|
||||
context.Users.Add(_userEntityFixture.Create(id: userId));
|
||||
context.MediaConsumptionRecords.AddRange(matchingRecord, recordOfAnotherLibrary, recordOfAnotherKind, recordOutsideTheRange);
|
||||
await context.SaveChangesAsync();
|
||||
context.ChangeTracker.Clear();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<MediaConsumptionRecordEntity>> result = await sut.GetForUserAsync(
|
||||
userId, libraryId, MediaKind.Movie, fromUtc, toUtc, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
MediaConsumptionRecordEntity returnedRecord = Assert.Single(result.Value);
|
||||
Assert.Equal(matchingRecord.Id, returnedRecord.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetForUserAsync_WhenNothingMatches_ShouldReturnAnEmptyList()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-consumptionstats-emptymatch-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
ConsumptionStatisticsRepository sut = new(context);
|
||||
|
||||
Guid userId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: userId, libraryId: Guid.NewGuid(), mediaKind: MediaKind.Book, startedOnUtc: new DateTime(2025, 1, 15, 0, 0, 0, DateTimeKind.Utc));
|
||||
context.Users.Add(_userEntityFixture.Create(id: userId));
|
||||
context.MediaConsumptionRecords.Add(record);
|
||||
await context.SaveChangesAsync();
|
||||
context.ChangeTracker.Clear();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<MediaConsumptionRecordEntity>> result = await sut.GetForUserAsync(
|
||||
userId, Guid.NewGuid(), MediaKind.Movie, new DateTime(2025, 1, 1, 0, 0, 0, DateTimeKind.Utc), new DateTime(2025, 1, 31, 0, 0, 0, DateTimeKind.Utc), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Empty(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetForUserAsync_WhenCalled_ShouldReturnDetachedRecordsAndAllowRepeatedReads()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-consumptionstats-notracking-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
ConsumptionStatisticsRepository sut = new(context);
|
||||
|
||||
Guid userId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(userId: userId);
|
||||
context.Users.Add(_userEntityFixture.Create(id: userId));
|
||||
context.MediaConsumptionRecords.Add(record);
|
||||
await context.SaveChangesAsync();
|
||||
context.ChangeTracker.Clear();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<MediaConsumptionRecordEntity>> firstResult = await sut.GetForUserAsync(userId, null, null, null, null, CancellationToken.None);
|
||||
Result<IReadOnlyList<MediaConsumptionRecordEntity>> secondResult = await sut.GetForUserAsync(userId, null, null, null, null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(firstResult.IsFailure);
|
||||
Assert.False(secondResult.IsFailure);
|
||||
// The read is untracked, so the context never holds the returned statistics records, and a second read works the same way.
|
||||
Assert.Empty(context.ChangeTracker.Entries<MediaConsumptionRecordEntity>());
|
||||
Assert.Equal(EntityState.Detached, context.Entry(firstResult.Value.Single()).State);
|
||||
MediaConsumptionRecordEntity firstReturnedRecord = Assert.Single(firstResult.Value);
|
||||
MediaConsumptionRecordEntity secondReturnedRecord = Assert.Single(secondResult.Value);
|
||||
Assert.Equal(record.Id, firstReturnedRecord.Id);
|
||||
Assert.Equal(record.Id, secondReturnedRecord.Id);
|
||||
Assert.Empty(context.ChangeTracker.Entries<MediaConsumptionRecordEntity>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetForAllUsersAsync_WhenCalled_ShouldReturnTheRecordsOfEveryUser()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-consumptionstats-allusers-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
ConsumptionStatisticsRepository sut = new(context);
|
||||
|
||||
Guid firstUserId = Guid.NewGuid();
|
||||
Guid secondUserId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity firstUserRecord = _mediaConsumptionRecordEntityFixture.Create(userId: firstUserId, mediaKind: MediaKind.Movie);
|
||||
MediaConsumptionRecordEntity secondUserMovieRecord = _mediaConsumptionRecordEntityFixture.Create(userId: secondUserId, mediaKind: MediaKind.Movie);
|
||||
MediaConsumptionRecordEntity secondUserBookRecord = _mediaConsumptionRecordEntityFixture.Create(userId: secondUserId, mediaKind: MediaKind.Book);
|
||||
context.Users.AddRange(_userEntityFixture.Create(id: firstUserId), _userEntityFixture.Create(id: secondUserId));
|
||||
context.MediaConsumptionRecords.AddRange(firstUserRecord, secondUserMovieRecord, secondUserBookRecord);
|
||||
await context.SaveChangesAsync();
|
||||
context.ChangeTracker.Clear();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<MediaConsumptionRecordEntity>> result = await sut.GetForAllUsersAsync(null, null, null, null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(3, result.Value.Count);
|
||||
Assert.Contains(result.Value, record => record.Id == firstUserRecord.Id);
|
||||
Assert.Contains(result.Value, record => record.Id == secondUserMovieRecord.Id);
|
||||
Assert.Contains(result.Value, record => record.Id == secondUserBookRecord.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetForAllUsersAsync_WhenAllFiltersAreProvided_ShouldApplyEveryFilterAcrossUsers()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-consumptionstats-allusers-filters-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
ConsumptionStatisticsRepository sut = new(context);
|
||||
|
||||
Guid firstUserId = Guid.NewGuid();
|
||||
Guid secondUserId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
DateTime fromUtc = new(2025, 1, 10, 0, 0, 0, DateTimeKind.Utc);
|
||||
DateTime toUtc = new(2025, 1, 20, 0, 0, 0, DateTimeKind.Utc);
|
||||
MediaConsumptionRecordEntity matchingFirstUserRecord = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: firstUserId, libraryId: libraryId, mediaKind: MediaKind.Movie, startedOnUtc: new DateTime(2025, 1, 15, 0, 0, 0, DateTimeKind.Utc));
|
||||
MediaConsumptionRecordEntity matchingSecondUserRecord = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: secondUserId, libraryId: libraryId, mediaKind: MediaKind.Movie, startedOnUtc: new DateTime(2025, 1, 16, 0, 0, 0, DateTimeKind.Utc));
|
||||
MediaConsumptionRecordEntity recordOfAnotherLibrary = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: firstUserId, libraryId: Guid.NewGuid(), mediaKind: MediaKind.Movie, startedOnUtc: new DateTime(2025, 1, 15, 0, 0, 0, DateTimeKind.Utc));
|
||||
MediaConsumptionRecordEntity recordOfAnotherKind = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: secondUserId, libraryId: libraryId, mediaKind: MediaKind.Book, startedOnUtc: new DateTime(2025, 1, 15, 0, 0, 0, DateTimeKind.Utc));
|
||||
MediaConsumptionRecordEntity recordOutsideTheRange = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: secondUserId, libraryId: libraryId, mediaKind: MediaKind.Movie, startedOnUtc: toUtc.AddDays(1));
|
||||
context.Users.AddRange(_userEntityFixture.Create(id: firstUserId), _userEntityFixture.Create(id: secondUserId));
|
||||
context.MediaConsumptionRecords.AddRange(
|
||||
matchingFirstUserRecord, matchingSecondUserRecord, recordOfAnotherLibrary, recordOfAnotherKind, recordOutsideTheRange);
|
||||
await context.SaveChangesAsync();
|
||||
context.ChangeTracker.Clear();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<MediaConsumptionRecordEntity>> result = await sut.GetForAllUsersAsync(
|
||||
libraryId, MediaKind.Movie, fromUtc, toUtc, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(2, result.Value.Count);
|
||||
// The filters are applied across every user, instead of one user at a time.
|
||||
Assert.Contains(result.Value, record => record.Id == matchingFirstUserRecord.Id);
|
||||
Assert.Contains(result.Value, record => record.Id == matchingSecondUserRecord.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetForAllUsersAsync_WhenNothingMatches_ShouldReturnAnEmptyList()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-consumptionstats-allusers-empty-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
ConsumptionStatisticsRepository sut = new(context);
|
||||
|
||||
Guid userId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: userId, libraryId: Guid.NewGuid(), mediaKind: MediaKind.Book, startedOnUtc: new DateTime(2025, 1, 15, 0, 0, 0, DateTimeKind.Utc));
|
||||
context.Users.Add(_userEntityFixture.Create(id: userId));
|
||||
context.MediaConsumptionRecords.Add(record);
|
||||
await context.SaveChangesAsync();
|
||||
context.ChangeTracker.Clear();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<MediaConsumptionRecordEntity>> result = await sut.GetForAllUsersAsync(
|
||||
Guid.NewGuid(), MediaKind.Movie, new DateTime(2025, 1, 1, 0, 0, 0, DateTimeKind.Utc), new DateTime(2025, 1, 31, 0, 0, 0, DateTimeKind.Utc), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Empty(result.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a real SQLite backed context, so that the stored rows are read exactly as they were written.
|
||||
/// </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;
|
||||
}
|
||||
}
|
||||
+91
@@ -8,7 +8,9 @@ using Lumina.Domain.Common.Primitives;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
@@ -46,4 +48,93 @@ public class MediaContributorRepositoryTests
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.MediaContributor.MediaContributorAlreadyExists, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdsAsync_WhenCalled_ShouldReturnOnlyTheRequestedContributorsAndIgnoreMissingIds()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-mediacontributorrepo-getbyids-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
MediaContributorRepository sut = new(context);
|
||||
MediaContributorEntity firstContributor = _mediaContributorEntityFixture.Create(displayName: "Frank Herbert");
|
||||
MediaContributorEntity secondContributor = _mediaContributorEntityFixture.Create(displayName: "Stephen King");
|
||||
MediaContributorEntity thirdContributor = _mediaContributorEntityFixture.Create(displayName: "Ursula K. Le Guin");
|
||||
context.MediaContributors.AddRange(firstContributor, secondContributor, thirdContributor);
|
||||
await context.SaveChangesAsync();
|
||||
context.ChangeTracker.Clear();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<MediaContributorEntity>> result = await sut.GetByIdsAsync(
|
||||
[firstContributor.Id, thirdContributor.Id, Guid.NewGuid()], CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(2, result.Value.Count);
|
||||
Assert.Contains(result.Value, contributor => contributor.Id == firstContributor.Id);
|
||||
Assert.Contains(result.Value, contributor => contributor.Id == thirdContributor.Id);
|
||||
Assert.DoesNotContain(result.Value, contributor => contributor.Id == secondContributor.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdsAsync_WhenIdsIsEmpty_ShouldReturnAnEmptyList()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-mediacontributorrepo-getbyids-empty-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
MediaContributorRepository sut = new(context);
|
||||
context.MediaContributors.Add(_mediaContributorEntityFixture.Create());
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<MediaContributorEntity>> result = await sut.GetByIdsAsync([], CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Empty(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdsAsync_WhenMoreThanFiveHundredIdsAreRequested_ShouldReturnEveryContributor()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-mediacontributorrepo-getbyids-chunks-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
MediaContributorRepository sut = new(context);
|
||||
const int CONTRIBUTOR_COUNT = 501;
|
||||
List<MediaContributorEntity> contributors = [.. Enumerable.Range(0, CONTRIBUTOR_COUNT).Select(index =>
|
||||
_mediaContributorEntityFixture.Create(displayName: $"Contributor {index}-{Guid.NewGuid():N}"))];
|
||||
context.MediaContributors.AddRange(contributors);
|
||||
await context.SaveChangesAsync();
|
||||
context.ChangeTracker.Clear();
|
||||
|
||||
// Act
|
||||
// The lookup is chunked in batches of 500, so the 501st Id proves the second chunk is queried as well.
|
||||
Result<IReadOnlyList<MediaContributorEntity>> result = await sut.GetByIdsAsync(
|
||||
[.. contributors.Select(contributor => contributor.Id)], CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(CONTRIBUTOR_COUNT, result.Value.Count);
|
||||
Assert.Equal(
|
||||
contributors.Select(contributor => contributor.Id).OrderBy(id => id),
|
||||
result.Value.Select(contributor => contributor.Id).OrderBy(id => id));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a real SQLite backed context, so that the stored values are read exactly as they were written.
|
||||
/// </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;
|
||||
}
|
||||
}
|
||||
+160
@@ -308,6 +308,166 @@ public class MusicArtworkRepositoryTests : IDisposable
|
||||
Assert.Equal(ArtworkStatus.Enriched, cover.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByOwnersAsync_WhenCalled_ShouldReturnOnlyTheArtworkOfTheRequestedOwnerTypeAndOwnerIds()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-musicartworkrepo-getbyowners-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
MusicArtworkRepository sut = new(context);
|
||||
MusicArtworkOwnerType ownerType = MusicArtworkOwnerType.Album;
|
||||
Guid firstOwnerId = Guid.NewGuid();
|
||||
Guid secondOwnerId = Guid.NewGuid();
|
||||
MusicArtworkEntity firstOwnerCover = _musicArtworkEntityFixture.Create(
|
||||
ownerType: ownerType, ownerId: firstOwnerId, artworkType: ArtworkType.Cover, ordinal: 0);
|
||||
MusicArtworkEntity firstOwnerFront = _musicArtworkEntityFixture.Create(
|
||||
ownerType: ownerType, ownerId: firstOwnerId, artworkType: ArtworkType.Front, ordinal: 1);
|
||||
MusicArtworkEntity secondOwnerCover = _musicArtworkEntityFixture.Create(
|
||||
ownerType: ownerType, ownerId: secondOwnerId, artworkType: ArtworkType.Cover, ordinal: 0);
|
||||
MusicArtworkEntity artworkOfAnotherOwner = _musicArtworkEntityFixture.Create(
|
||||
ownerType: ownerType, ownerId: Guid.NewGuid(), artworkType: ArtworkType.Cover, ordinal: 0);
|
||||
MusicArtworkEntity artworkOfAnotherOwnerType = _musicArtworkEntityFixture.Create(
|
||||
ownerType: MusicArtworkOwnerType.Artist, ownerId: firstOwnerId, artworkType: ArtworkType.Cover, ordinal: 0);
|
||||
context.MusicArtwork.AddRange(firstOwnerCover, firstOwnerFront, secondOwnerCover, artworkOfAnotherOwner, artworkOfAnotherOwnerType);
|
||||
await context.SaveChangesAsync();
|
||||
context.ChangeTracker.Clear();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<MusicArtworkEntity>> result = await sut.GetByOwnersAsync(ownerType, [firstOwnerId, secondOwnerId], CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(3, result.Value.Count);
|
||||
Assert.Contains(result.Value, artwork => artwork.Id == firstOwnerCover.Id);
|
||||
Assert.Contains(result.Value, artwork => artwork.Id == firstOwnerFront.Id);
|
||||
Assert.Contains(result.Value, artwork => artwork.Id == secondOwnerCover.Id);
|
||||
Assert.DoesNotContain(result.Value, artwork => artwork.Id == artworkOfAnotherOwner.Id);
|
||||
Assert.DoesNotContain(result.Value, artwork => artwork.Id == artworkOfAnotherOwnerType.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByOwnersAsync_WhenOwnerIdsIsEmpty_ShouldReturnAnEmptyList()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-musicartworkrepo-getbyowners-empty-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
MusicArtworkRepository sut = new(context);
|
||||
context.MusicArtwork.Add(_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album));
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<MusicArtworkEntity>> result = await sut.GetByOwnersAsync(MusicArtworkOwnerType.Album, [], CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Empty(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByOwnersAsync_WhenCalled_ShouldOrderTheArtworkByTypeThenOrdinal()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-musicartworkrepo-getbyowners-order-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
MusicArtworkRepository sut = new(context);
|
||||
MusicArtworkOwnerType ownerType = MusicArtworkOwnerType.Album;
|
||||
Guid ownerId = Guid.NewGuid();
|
||||
MusicArtworkEntity frontSecond = _musicArtworkEntityFixture.Create(
|
||||
ownerType: ownerType, ownerId: ownerId, artworkType: ArtworkType.Front, ordinal: 1);
|
||||
MusicArtworkEntity frontFirst = _musicArtworkEntityFixture.Create(
|
||||
ownerType: ownerType, ownerId: ownerId, artworkType: ArtworkType.Front, ordinal: 0);
|
||||
MusicArtworkEntity cover = _musicArtworkEntityFixture.Create(
|
||||
ownerType: ownerType, ownerId: ownerId, artworkType: ArtworkType.Cover, ordinal: 0);
|
||||
context.MusicArtwork.AddRange(frontSecond, frontFirst, cover);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<MusicArtworkEntity>> result = await sut.GetByOwnersAsync(ownerType, [ownerId], CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal([cover.Id, frontFirst.Id, frontSecond.Id], result.Value.Select(artwork => artwork.Id));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByOwnersAsync_WhenMoreThanFiveHundredOwnerIdsAreRequested_ShouldReturnTheArtworkOfEveryOwner()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-musicartworkrepo-getbyowners-chunks-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
MusicArtworkRepository sut = new(context);
|
||||
const int OWNER_COUNT = 501;
|
||||
List<Guid> ownerIds = [.. Enumerable.Range(0, OWNER_COUNT).Select(_ => Guid.NewGuid())];
|
||||
List<MusicArtworkEntity> artwork = [.. ownerIds.Select(ownerId => _musicArtworkEntityFixture.Create(
|
||||
ownerType: MusicArtworkOwnerType.Album, ownerId: ownerId, artworkType: ArtworkType.Cover, ordinal: 0))];
|
||||
context.MusicArtwork.AddRange(artwork);
|
||||
await context.SaveChangesAsync();
|
||||
context.ChangeTracker.Clear();
|
||||
|
||||
// Act
|
||||
// The lookup is chunked in batches of 500, so the 501st owner proves the second chunk is queried as well.
|
||||
Result<IReadOnlyList<MusicArtworkEntity>> result = await sut.GetByOwnersAsync(MusicArtworkOwnerType.Album, ownerIds, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(OWNER_COUNT, result.Value.Count);
|
||||
Assert.Equal(
|
||||
artwork.Select(candidate => candidate.Id).OrderBy(id => id),
|
||||
result.Value.Select(candidate => candidate.Id).OrderBy(id => id));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByOwnersAsync_WhenCalled_ShouldReturnDetachedArtwork()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-musicartworkrepo-getbyowners-notracking-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
MusicArtworkRepository sut = new(context);
|
||||
MusicArtworkOwnerType ownerType = MusicArtworkOwnerType.Album;
|
||||
Guid ownerId = Guid.NewGuid();
|
||||
MusicArtworkEntity artwork = _musicArtworkEntityFixture.Create(
|
||||
ownerType: ownerType, ownerId: ownerId, artworkType: ArtworkType.Cover, ordinal: 0);
|
||||
context.MusicArtwork.Add(artwork);
|
||||
await context.SaveChangesAsync();
|
||||
context.ChangeTracker.Clear();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<MusicArtworkEntity>> firstResult = await sut.GetByOwnersAsync(ownerType, [ownerId], CancellationToken.None);
|
||||
Result<IReadOnlyList<MusicArtworkEntity>> secondResult = await sut.GetByOwnersAsync(ownerType, [ownerId], CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(firstResult.IsFailure);
|
||||
Assert.False(secondResult.IsFailure);
|
||||
// The read is untracked, so the returned rows never leak into the unit of work, and a second read works the same way.
|
||||
Assert.Empty(context.ChangeTracker.Entries<MusicArtworkEntity>());
|
||||
MusicArtworkEntity firstReturnedArtwork = Assert.Single(firstResult.Value);
|
||||
MusicArtworkEntity secondReturnedArtwork = Assert.Single(secondResult.Value);
|
||||
Assert.Equal(artwork.Id, firstReturnedArtwork.Id);
|
||||
Assert.Equal(artwork.Id, secondReturnedArtwork.Id);
|
||||
Assert.Equal(EntityState.Detached, context.Entry(firstReturnedArtwork).State);
|
||||
Assert.Empty(context.ChangeTracker.Entries<MusicArtworkEntity>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a real SQLite backed context, so that the stored values are read exactly as they were written.
|
||||
/// </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>
|
||||
/// Disposes the database context and its underlying connection.
|
||||
/// </summary>
|
||||
|
||||
+187
@@ -768,6 +768,193 @@ public class TrackRepositoryTests
|
||||
Assert.Equal(367, row.DurationInSeconds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdsAsync_WhenIdsIsEmpty_ShouldReturnAnEmptyList()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-getbyids-empty-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
TrackRepository sut = new(context);
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
|
||||
context.Tracks.Add(_trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false));
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<TrackEntity>> result = await sut.GetByIdsAsync([], false, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Empty(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdsAsync_WhenCalled_ShouldReturnOnlyTheRequestedTracks()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-getbyids-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
TrackRepository sut = new(context);
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
|
||||
TrackEntity firstTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/first.flac", includeMetadata: false);
|
||||
TrackEntity secondTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/second.flac", includeMetadata: false);
|
||||
TrackEntity thirdTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/third.flac", includeMetadata: false);
|
||||
context.Tracks.AddRange(firstTrack, secondTrack, thirdTrack);
|
||||
await context.SaveChangesAsync();
|
||||
context.ChangeTracker.Clear();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<TrackEntity>> result = await sut.GetByIdsAsync([firstTrack.Id, thirdTrack.Id], false, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(2, result.Value.Count);
|
||||
Assert.Contains(result.Value, track => track.Id == firstTrack.Id);
|
||||
Assert.Contains(result.Value, track => track.Id == thirdTrack.Id);
|
||||
Assert.DoesNotContain(result.Value, track => track.Id == secondTrack.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdsAsync_WhenNavigationPropertiesShouldNotBeIncluded_ShouldNotLoadTheNonOwnedNavigationProperties()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-getbyids-notracking-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
TrackRepository sut = new(context);
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
|
||||
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/hidden.flac", includeMetadata: false);
|
||||
track.Tags = [_tagEntityFixture.Create(name: "HiddenTag")];
|
||||
track.Genres = [_genreEntityFixture.Create(name: "HiddenGenre")];
|
||||
track.Moods = [_trackMoodEntityFixture.Create(name: "HiddenMood")];
|
||||
track.Isrcs = [_trackIsrcEntityFixture.Create(value: "USRC12345678")];
|
||||
track.Ratings = [_audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100)];
|
||||
track.Contributors = [_trackContributorEntityFixture.Create(trackId: track.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals)];
|
||||
context.Tracks.Add(track);
|
||||
await context.SaveChangesAsync();
|
||||
context.ChangeTracker.Clear();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<TrackEntity>> result = await sut.GetByIdsAsync([track.Id], false, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
TrackEntity returnedTrack = Assert.Single(result.Value);
|
||||
Assert.Equal(track.Id, returnedTrack.Id);
|
||||
Assert.Null(returnedTrack.Album);
|
||||
Assert.Empty(returnedTrack.Tags);
|
||||
Assert.Empty(returnedTrack.Genres);
|
||||
Assert.Empty(returnedTrack.Contributors);
|
||||
// Moods, ISRCs and Ratings are owned collections, so EF Core materializes them together with the track even when the optional graph
|
||||
// is not included. The flag only controls the non-owned navigation properties, which is why those are asserted unloaded above.
|
||||
Assert.Single(returnedTrack.Moods);
|
||||
Assert.Single(returnedTrack.Isrcs);
|
||||
Assert.Single(returnedTrack.Ratings);
|
||||
// The rows are read without tracking, so the read statistics never leak into the unit of work.
|
||||
Assert.Empty(context.ChangeTracker.Entries<TrackEntity>());
|
||||
Assert.Equal(EntityState.Detached, context.Entry(returnedTrack).State);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdsAsync_WhenNavigationPropertiesShouldBeIncluded_ShouldLoadTheAlbumArtistAndRelatedCollections()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-getbyids-include-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
TrackRepository sut = new(context);
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
|
||||
ArtistEntity artist = await context.Artists.AsNoTracking().FirstAsync(candidate => candidate.Id == album.ArtistId);
|
||||
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/loaded.flac", includeMetadata: false);
|
||||
track.Tags = [_tagEntityFixture.Create(name: "LoadedTag"), _tagEntityFixture.Create(name: "SecondLoadedTag")];
|
||||
track.Genres = [_genreEntityFixture.Create(name: "LoadedGenre")];
|
||||
track.Moods = [_trackMoodEntityFixture.Create(name: "Calm")];
|
||||
track.Isrcs = [_trackIsrcEntityFixture.Create(value: "USRC12345678")];
|
||||
track.Ratings = [_audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100)];
|
||||
track.Contributors = [_trackContributorEntityFixture.Create(trackId: track.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals)];
|
||||
context.Tracks.Add(track);
|
||||
await context.SaveChangesAsync();
|
||||
context.ChangeTracker.Clear();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<TrackEntity>> result = await sut.GetByIdsAsync([track.Id], true, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
TrackEntity returnedTrack = Assert.Single(result.Value);
|
||||
Assert.NotNull(returnedTrack.Album);
|
||||
Assert.Equal(album.Id, returnedTrack.Album!.Id);
|
||||
Assert.NotNull(returnedTrack.Album.Artist);
|
||||
Assert.Equal(artist.Id, returnedTrack.Album.Artist!.Id);
|
||||
Assert.Equal(2, returnedTrack.Tags.Count);
|
||||
Assert.Single(returnedTrack.Genres);
|
||||
Assert.Single(returnedTrack.Moods);
|
||||
Assert.Single(returnedTrack.Isrcs);
|
||||
Assert.Single(returnedTrack.Ratings);
|
||||
Assert.Single(returnedTrack.Contributors);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdsAsync_WhenMoreThanFiveHundredIdsAreRequested_ShouldReturnEveryTrack()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-getbyids-chunks-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = CreateContext(anchorConnection);
|
||||
TrackRepository sut = new(context);
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
|
||||
const int trackCount = 501;
|
||||
List<TrackEntity> tracks = CreateTracks(trackCount, album.Id, libraryId);
|
||||
context.Tracks.AddRange(tracks);
|
||||
await context.SaveChangesAsync();
|
||||
context.ChangeTracker.Clear();
|
||||
|
||||
// Act
|
||||
// The lookup is chunked in batches of 500, so the 501st Id proves the second chunk is queried as well.
|
||||
Result<IReadOnlyList<TrackEntity>> result = await sut.GetByIdsAsync([.. tracks.Select(track => track.Id)], false, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(trackCount, result.Value.Count);
|
||||
Assert.Equal(
|
||||
tracks.Select(track => track.Id).OrderBy(id => id),
|
||||
result.Value.Select(track => track.Id).OrderBy(id => id));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of tracks with distinct paths and empty metadata collections, so that the chunked lookup can be exercised without extra graph data.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of tracks to create.</param>
|
||||
/// <param name="albumId">The Id of the album that owns the tracks.</param>
|
||||
/// <param name="libraryId">The Id of the library that owns the tracks.</param>
|
||||
/// <returns>The created tracks.</returns>
|
||||
private List<TrackEntity> CreateTracks(int count, Guid albumId, Guid libraryId)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => _trackEntityFixture.Create(
|
||||
albumId: albumId, libraryId: libraryId, path: $"/music/generated-{Guid.NewGuid():N}.flac", includeMetadata: false))];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a real SQLite backed context, so that the stored values are read exactly as they were written.
|
||||
/// </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 an artist and the album that owns the tracks of the library identified by <paramref name="libraryId"/>, so that the required foreign keys of a track are satisfied.
|
||||
/// </summary>
|
||||
|
||||
Reference in new issue
Block a user