Formats code comments as sentences in the tests.

Capitalizes the first word and adds the terminal period in the unit, integration and security tests. The AAA markers stay bare, the TODO bodies stay lowercase, and no assertion, payload, expected status code or test signature changes.
This commit is contained in:
BinaryAlley committed 2026-11-16 18:17:29 +02:00
1 parent 727aa33318
commit 057f557791
540 files changed
+3888 -3888

No files matched your search

@@ -316,10 +316,10 @@ public class FavoriteRepositoryTests
}
[Theory]
[InlineData(FavoriteMediaKind.MusicArtist)] // the artist catalogue serves the library Id of an artist
[InlineData(FavoriteMediaKind.MusicAlbum)] // the album catalogue serves the library Id of an album
[InlineData(FavoriteMediaKind.MusicTrack)] // the track catalogue serves the library Id of a track
[InlineData(FavoriteMediaKind.Book)] // the book catalogue serves the library Id of a book
[InlineData(FavoriteMediaKind.MusicArtist)] // The artist catalogue serves the library Id of an artist.
[InlineData(FavoriteMediaKind.MusicAlbum)] // The album catalogue serves the library Id of an album.
[InlineData(FavoriteMediaKind.MusicTrack)] // The track catalogue serves the library Id of a track.
[InlineData(FavoriteMediaKind.Book)] // The book catalogue serves the library Id of a book.
public async Task GetMediaItemLibraryIdAsync_WhenTheMediaItemExists_ShouldReturnTheLibraryIdOfItsCatalogue(FavoriteMediaKind mediaKind)
{
// Arrange
@@ -390,9 +390,9 @@ public class FavoriteRepositoryTests
}
[Theory]
[InlineData(FavoriteMediaKind.Video)] // planned kind, no video catalogue exists
[InlineData(FavoriteMediaKind.Photo)] // planned kind, no photo catalogue exists
[InlineData((FavoriteMediaKind)999)] // an undefined value that is neither catalogued nor planned
[InlineData(FavoriteMediaKind.Video)] // Planned kind, no video catalogue exists.
[InlineData(FavoriteMediaKind.Photo)] // Planned kind, no photo catalogue exists.
[InlineData((FavoriteMediaKind)999)] // An undefined value that is neither catalogued nor planned.
public async Task GetMediaItemLibraryIdAsync_WhenTheKindHasNoCatalogue_ShouldReturnSuccessWithNullWithoutReadingTheCatalogue(FavoriteMediaKind mediaKind)
{
// Arrange
@@ -911,8 +911,8 @@ public class FavoriteRepositoryTests
}
[Theory]
[InlineData(FavoriteMediaKind.Video)] // planned kind, so no display data can be resolved yet
[InlineData(FavoriteMediaKind.Photo)] // planned kind, so no display data can be resolved yet
[InlineData(FavoriteMediaKind.Video)] // Planned kind, so no display data can be resolved yet.
[InlineData(FavoriteMediaKind.Photo)] // Planned kind, so no display data can be resolved yet.
public async Task GetAllForUserAsync_WhenTheFavoriteIsOfAPlannedKind_ShouldReturnItWithoutDisplayData(FavoriteMediaKind mediaKind)
{
// Arrange
@@ -1121,11 +1121,11 @@ public class FavoriteRepositoryTests
}
[Theory]
[InlineData(FavoriteMediaKind.MusicArtist, false)] // the artist itself is soft deleted
[InlineData(FavoriteMediaKind.MusicAlbum, false)] // the album itself is soft deleted
[InlineData(FavoriteMediaKind.MusicAlbum, true)] // the album's artist is soft deleted
[InlineData(FavoriteMediaKind.MusicTrack, false)] // the track itself is soft deleted
[InlineData(FavoriteMediaKind.MusicTrack, true)] // the track's album is soft deleted
[InlineData(FavoriteMediaKind.MusicArtist, false)] // The artist itself is soft deleted.
[InlineData(FavoriteMediaKind.MusicAlbum, false)] // The album itself is soft deleted.
[InlineData(FavoriteMediaKind.MusicAlbum, true)] // The album's artist is soft deleted.
[InlineData(FavoriteMediaKind.MusicTrack, false)] // The track itself is soft deleted.
[InlineData(FavoriteMediaKind.MusicTrack, true)] // The track's album is soft deleted.
public async Task GetMediaItemLibraryIdAsync_WhenTheMusicItemIsSoftDeleted_ShouldReturnSuccessWithNull(FavoriteMediaKind mediaKind, bool isAncestorDeleted)
{
// Arrange
@@ -1144,11 +1144,11 @@ public class FavoriteRepositoryTests
}
[Theory]
[InlineData(FavoriteMediaKind.MusicArtist, false)] // the artist itself is soft deleted
[InlineData(FavoriteMediaKind.MusicAlbum, false)] // the album itself is soft deleted
[InlineData(FavoriteMediaKind.MusicAlbum, true)] // the album's artist is soft deleted
[InlineData(FavoriteMediaKind.MusicTrack, false)] // the track itself is soft deleted
[InlineData(FavoriteMediaKind.MusicTrack, true)] // the track's album is soft deleted
[InlineData(FavoriteMediaKind.MusicArtist, false)] // The artist itself is soft deleted.
[InlineData(FavoriteMediaKind.MusicAlbum, false)] // The album itself is soft deleted.
[InlineData(FavoriteMediaKind.MusicAlbum, true)] // The album's artist is soft deleted.
[InlineData(FavoriteMediaKind.MusicTrack, false)] // The track itself is soft deleted.
[InlineData(FavoriteMediaKind.MusicTrack, true)] // The track's album is soft deleted.
public async Task GetAllForUserAsync_WhenTheFavoritedMusicItemIsSoftDeleted_ShouldKeepTheFavoriteWithoutDisplayData(FavoriteMediaKind mediaKind, bool isAncestorDeleted)
{
// Arrange
@@ -193,9 +193,9 @@ public class ArtistAlphaFilterSpecificationTests : IDisposable
}
[Theory]
[InlineData("a", "Alpha")] // the first letter of the alphabet
[InlineData("b", "Bravo")] // a letter in the middle of the alphabet
[InlineData("c", "Charlie")] // another letter in the middle of the alphabet
[InlineData("a", "Alpha")] // The first letter of the alphabet.
[InlineData("b", "Bravo")] // A letter in the middle of the alphabet.
[InlineData("c", "Charlie")] // Another letter in the middle of the alphabet.
public void ToExpression_WhenAlphaKeyIsALetter_ShouldMatchOnlyTheNamesStartingWithIt(string alphaKey, string matchingName)
{
// Arrange
@@ -212,7 +212,7 @@ public class UnitOfWorkTests
Result<Success> firstSaveResult = await sut.SaveChangesAsync(CancellationToken.None);
Assert.False(firstSaveResult.IsFailure);
// stage a second book with the same library and path directly, bypassing the application level pre-check, so that the unique index of the storage medium is the one that rejects it
// Stage a second book with the same library and path directly, bypassing the application level pre-check, so that the unique index of the storage medium is the one that rejects it.
BookEntity secondBook = _bookEntityFixture.Create();
secondBook.LibraryId = libraryId;
secondBook.Path = "/books/duplicate.epub";
@@ -275,7 +275,7 @@ public class UnitOfWorkTests
Result<Success> firstSaveResult = await sut.SaveChangesAsync(CancellationToken.None);
Assert.False(firstSaveResult.IsFailure);
// stage a duplicate directly through the repository, bypassing the application level existence check, so that the unique index of the storage medium is the one that rejects it
// Stage a duplicate directly through the repository, bypassing the application level existence check, so that the unique index of the storage medium is the one that rejects it.
FavoriteEntity duplicateFavorite = _favoriteEntityFixture.Create(
userId: userId,
mediaKind: FavoriteMediaKind.MusicArtist,
@@ -27,9 +27,9 @@ public class TranscodingCachePathsTests : IDisposable
}
[Theory]
[InlineData(null)] // no cache directory is configured
[InlineData("")] // an empty cache directory is configured
[InlineData(" ")] // a white space cache directory is configured
[InlineData(null)] // No cache directory is configured.
[InlineData("")] // An empty cache directory is configured.
[InlineData(" ")] // A white space cache directory is configured.
public void GetRootDirectory_WhenNoDirectoryIsConfigured_ShouldReturnTheDefaultDirectoryUnderTheTemporaryDirectory(string? configuredDirectory)
{
// Act
@@ -128,13 +128,13 @@ public class TranscodingCachePathsTests : IDisposable
}
[Theory]
[InlineData(null)] // no identifier
[InlineData("")] // an empty identifier
[InlineData("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcde")] // 63 characters
[InlineData("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0")] // 65 characters
[InlineData("0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF")] // uppercase hexadecimal characters
[InlineData("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdeg")] // a character that is not hexadecimal
[InlineData("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcde/")] // a directory separator
[InlineData(null)] // No identifier.
[InlineData("")] // An empty identifier.
[InlineData("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcde")] // 63 characters.
[InlineData("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0")] // 65 characters.
[InlineData("0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF")] // Uppercase hexadecimal characters.
[InlineData("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdeg")] // A character that is not hexadecimal.
[InlineData("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcde/")] // A directory separator.
public void IsValidCacheId_WhenTheValueIsNotAWellFormedIdentifier_ShouldReturnFalse(string? cacheId)
{
// Act
@@ -158,10 +158,10 @@ public class TranscodingCachePathsTests : IDisposable
}
[Theory]
[InlineData(null)] // no name
[InlineData("")] // an empty name
[InlineData("segment.m4s")] // an ordinary file name
[InlineData("not-a-cache-entry")] // an ordinary directory name
[InlineData(null)] // No name.
[InlineData("")] // An empty name.
[InlineData("segment.m4s")] // An ordinary file name.
[InlineData("not-a-cache-entry")] // An ordinary directory name.
public void IsCacheEntryName_WhenTheNameIsNotInTheCacheNamespace_ShouldReturnFalse(string? entryName)
{
// Act
@@ -172,9 +172,9 @@ public class TranscodingCachePathsTests : IDisposable
}
[Theory]
[InlineData("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef")] // a cache identifier
[InlineData("tmp-0123456789abcdef")] // a temporary directory
[InlineData("del-0123456789abcdef")] // a deletion tombstone
[InlineData("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef")] // A cache identifier.
[InlineData("tmp-0123456789abcdef")] // A temporary directory.
[InlineData("del-0123456789abcdef")] // A deletion tombstone.
public void IsCacheEntryName_WhenTheNameIsInTheCacheNamespace_ShouldReturnTrue(string entryName)
{
// Act
@@ -119,13 +119,13 @@ public class MusicArtworkServiceTests
}
[Theory]
[InlineData(ArtworkType.Cover, 0, "cover.jpg")] // the front cover uses the bare type name
[InlineData(ArtworkType.Back, 0, "back.jpg")] // the back cover uses the bare type name
[InlineData(ArtworkType.Medium, 0, "medium.jpg")] // a single medium uses the bare type name
[InlineData(ArtworkType.Booklet, 0, "booklet.jpg")] // the first booklet page uses the bare type name
[InlineData(ArtworkType.Booklet, 2, "booklet-2.jpg")] // a further booklet page is suffixed with its ordinal
[InlineData(ArtworkType.Liner, 1, "liner-1.jpg")] // a liner note page is suffixed with its ordinal
[InlineData(ArtworkType.Other, 0, "other.jpg")] // any other type falls back to the generic name
[InlineData(ArtworkType.Cover, 0, "cover.jpg")] // The front cover uses the bare type name.
[InlineData(ArtworkType.Back, 0, "back.jpg")] // The back cover uses the bare type name.
[InlineData(ArtworkType.Medium, 0, "medium.jpg")] // A single medium uses the bare type name.
[InlineData(ArtworkType.Booklet, 0, "booklet.jpg")] // The first booklet page uses the bare type name.
[InlineData(ArtworkType.Booklet, 2, "booklet-2.jpg")] // A further booklet page is suffixed with its ordinal.
[InlineData(ArtworkType.Liner, 1, "liner-1.jpg")] // A liner note page is suffixed with its ordinal.
[InlineData(ArtworkType.Other, 0, "other.jpg")] // Any other type falls back to the generic name.
public async Task SaveAlbumArtworkAsync_WhenTheArtworkHasAType_ShouldNameTheFileAfterTheTypeAndOrdinal(ArtworkType artworkType, int ordinal, string expectedFileName)
{
// Arrange
@@ -833,9 +833,9 @@ public class MusicArtworkServiceTests
}
[Theory]
[InlineData(null)] // a null path is a no-op
[InlineData("")] // an empty path is a no-op
[InlineData(" ")] // a whitespace path is a no-op
[InlineData(null)] // A null path is a no-op.
[InlineData("")] // An empty path is a no-op.
[InlineData(" ")] // A whitespace path is a no-op.
public void DeleteStoredArtwork_WhenThePathIsMissing_ShouldReturnDeletedWithoutTouchingTheFileSystem(string? artworkRelativePath)
{
// Act
@@ -111,8 +111,8 @@ public class TranscodingCacheCoordinatorTests : IDisposable
}
[Theory]
[InlineData(0)] // a zero sized output
[InlineData(-1)] // a negative sized output
[InlineData(0)] // A zero sized output.
[InlineData(-1)] // A negative sized output.
public void TryReserve_WhenTheRequestedSizeIsNotPositive_ShouldReturnFalse(int requestedBytes)
{
// Act
@@ -124,8 +124,8 @@ public class TranscodingCacheCoordinatorTests : IDisposable
}
[Theory]
[InlineData(0)] // a zero maximum cache size
[InlineData(-1)] // a negative maximum cache size
[InlineData(0)] // A zero maximum cache size.
[InlineData(-1)] // A negative maximum cache size.
public void TryReserve_WhenTheMaximumCacheSizeIsNotPositive_ShouldReturnFalse(int maxCacheBytes)
{
// Act
@@ -107,7 +107,7 @@ public class ThemeServiceTests : IDisposable
public void HasThemePack_WhenThemeIsNotInstalled_ShouldReturnFalse()
{
// Arrange
// nothing is installed
// Nothing is installed.
// Act
bool result = _sut.HasThemePack("test-theme");
@@ -878,9 +878,9 @@ public class ThemeServiceTests : IDisposable
}
[Theory]
[InlineData("../secret")] // parent scope traversal attempt
[InlineData("/etc/passwd")] // rooted path attempt
[InlineData("templates//nested")] // empty segment attempt
[InlineData("../secret")] // Parent scope traversal attempt.
[InlineData("/etc/passwd")] // Rooted path attempt.
[InlineData("templates//nested")] // Empty segment attempt.
public async Task GetTemplateAsync_WhenPageKeyAttemptsToEscapeTheThemePack_ShouldReturnThemeTemplateNotFound(string pageKey)
{
// Arrange
@@ -72,9 +72,9 @@ public class CalibreArtworkProviderTests
}
[Theory]
[InlineData("../cover.jpg")] // parent directory escape
[InlineData("sub/cover.jpg")] // path with a separator
[InlineData("sub\\cover.jpg")] // path with a backslash separator
[InlineData("../cover.jpg")] // Parent directory escape.
[InlineData("sub/cover.jpg")] // Path with a separator.
[InlineData("sub\\cover.jpg")] // Path with a backslash separator.
public async Task GetArtworkAsync_WhenCoverHrefContainsPathTraversalOrSeparators_ShouldReturnNull(string coverHref)
{
// Arrange
@@ -255,9 +255,9 @@ public class Id3TagReaderTests : IDisposable
}
[Theory]
[InlineData("2011-03-14", 2011)] // a full date yields its year
[InlineData("2011", 2011)] // a bare year is matched by the year pattern
[InlineData("released in 1999 remastered", 1999)] // a year embedded in free form text is still matched
[InlineData("2011-03-14", 2011)] // A full date yields its year.
[InlineData("2011", 2011)] // A bare year is matched by the year pattern.
[InlineData("released in 1999 remastered", 1999)] // A year embedded in free form text is still matched.
public void Read_WhenTheReleaseDateIsPresent_ShouldParseTheYear(string releaseDate, int expectedYear)
{
// Arrange
@@ -217,10 +217,10 @@ public class LocalMusicAlbumArtworkProviderTests : IDisposable
}
[Theory]
[InlineData(null)] // a null path contributes no artwork
[InlineData("")] // an empty path contributes no artwork
[InlineData(" ")] // a white space path contributes no artwork
[InlineData("track.flac")] // a path without a directory part contributes no artwork
[InlineData(null)] // A null path contributes no artwork.
[InlineData("")] // An empty path contributes no artwork.
[InlineData(" ")] // A white space path contributes no artwork.
[InlineData("track.flac")] // A path without a directory part contributes no artwork.
public async Task GetArtworkAsync_WhenTheTrackPathDoesNotPointToADirectory_ShouldReturnEmpty(string? trackPath)
{
// Arrange
@@ -106,10 +106,10 @@ public class LocalMusicArtistArtworkProviderTests : IDisposable
}
[Theory]
[InlineData(null)] // a null path contributes no artwork
[InlineData("")] // an empty path contributes no artwork
[InlineData(" ")] // a white space path contributes no artwork
[InlineData("track.flac")] // a path without a directory part contributes no artwork
[InlineData(null)] // A null path contributes no artwork.
[InlineData("")] // An empty path contributes no artwork.
[InlineData(" ")] // A white space path contributes no artwork.
[InlineData("track.flac")] // A path without a directory part contributes no artwork.
public async Task GetArtworkAsync_WhenTheTrackPathDoesNotPointToADirectory_ShouldReturnEmpty(string? trackPath)
{
// Arrange
@@ -68,9 +68,9 @@ public class LocalMusicArtworkEmbeddedCoverExtractorTests : IDisposable
}
[Theory]
[InlineData(null)] // a null path contributes no cover
[InlineData("")] // an empty path contributes no cover
[InlineData(" ")] // a white space path contributes no cover
[InlineData(null)] // A null path contributes no cover.
[InlineData("")] // An empty path contributes no cover.
[InlineData(" ")] // A white space path contributes no cover.
public void Extract_WhenTheTrackPathIsNullOrEmpty_ShouldReturnNull(string? trackPath)
{
// Act
@@ -101,11 +101,11 @@ public class LocalMusicArtworkEmbeddedCoverExtractorTests : IDisposable
[InlineData("image/x-ms-bmp", ".bmp")]
[InlineData("image/gif", ".gif")]
[InlineData("image/tiff", ".tiff")]
[InlineData("IMAGE/PNG", ".png")] // the MIME type is matched without regard to casing
[InlineData(" image/png ", ".png")] // the MIME type is trimmed before it is matched
[InlineData("application/octet-stream", ".jpg")] // an unknown MIME type falls back to the JPEG extension
[InlineData("", ".jpg")] // an empty MIME type falls back to the JPEG extension
[InlineData(null, ".jpg")] // a missing MIME type falls back to the JPEG extension
[InlineData("IMAGE/PNG", ".png")] // The MIME type is matched without regard to casing.
[InlineData(" image/png ", ".png")] // The MIME type is trimmed before it is matched.
[InlineData("application/octet-stream", ".jpg")] // An unknown MIME type falls back to the JPEG extension.
[InlineData("", ".jpg")] // An empty MIME type falls back to the JPEG extension.
[InlineData(null, ".jpg")] // A missing MIME type falls back to the JPEG extension.
public void Extract_WhenTheMimeTypeIsProvided_ShouldUseTheMatchingFileExtension(string? mimeType, string expectedExtension)
{
// Arrange
@@ -308,10 +308,10 @@ public class LocalMusicArtworkScannerTests : IDisposable
}
[Theory]
[InlineData(null)] // a null path contributes no artwork
[InlineData("")] // an empty path contributes no artwork
[InlineData(" ")] // a white space path contributes no artwork
[InlineData("track.flac")] // a path without a directory part contributes no artwork
[InlineData(null)] // A null path contributes no artwork.
[InlineData("")] // An empty path contributes no artwork.
[InlineData(" ")] // A white space path contributes no artwork.
[InlineData("track.flac")] // A path without a directory part contributes no artwork.
public void ScanAlbumArtwork_WhenTheTrackPathDoesNotPointToADirectory_ShouldReturnEmpty(string? trackPath)
{
// Act
@@ -449,10 +449,10 @@ public class LocalMusicArtworkScannerTests : IDisposable
}
[Theory]
[InlineData(null)] // a null path contributes no artwork
[InlineData("")] // an empty path contributes no artwork
[InlineData(" ")] // a white space path contributes no artwork
[InlineData("track.flac")] // a path without a directory part contributes no artwork
[InlineData(null)] // A null path contributes no artwork.
[InlineData("")] // An empty path contributes no artwork.
[InlineData(" ")] // A white space path contributes no artwork.
[InlineData("track.flac")] // A path without a directory part contributes no artwork.
public void ScanArtistArtwork_WhenTheTrackPathDoesNotPointToADirectory_ShouldReturnEmpty(string? trackPath)
{
// Act
@@ -45,10 +45,10 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable
public string? TestUsername { get; private set; }
/// <summary>
/// Creates an HTTP client with authentication headers and a test user
/// Creates an HTTP client with authentication headers and a test user.
/// </summary>
/// <param name="permissions">The permissions granted directly to the test user, if any.</param>
/// <returns>An HTTP client configured with auth headers</returns>
/// <returns>An HTTP client configured with auth headers.</returns>
public async Task<HttpClient> CreateAuthenticatedClientAsync(params AuthorizationPermission[] permissions)
{
HttpClient client = CreateClient();
@@ -101,9 +101,9 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable
}
/// <summary>
/// Creates an HTTP client with authentication headers and an admin test user with all permissions
/// Creates an HTTP client with authentication headers and an admin test user with all permissions.
/// </summary>
/// <returns>An HTTP client configured with admin auth headers</returns>
/// <returns>An HTTP client configured with admin auth headers.</returns>
public async Task<HttpClient> CreateAuthenticatedAdminClientAsync()
{
HttpClient client = CreateClient();
@@ -38,11 +38,11 @@ public class LuminaApiFactory : WebApplicationFactory<Program>, IDisposable
/// </summary>
public LuminaApiFactory()
{
// each factory gets its own uniquely named shared in-memory database, so that parallel test classes remain isolated from one another;
// Each factory gets its own uniquely named shared in-memory database, so that parallel test classes remain isolated from one another;
// the shared cache allows each DbContext to open its own pooled connection to the same database, instead of sharing a single connection,
// which would otherwise serialize every request on one connection and cause nested transaction errors between requests
// which would otherwise serialize every request on one connection and cause nested transaction errors between requests.
_sharedInMemoryConnectionString = string.Format(SHARED_IN_MEMORY_CONNECTION_STRING_PREFIX, Guid.NewGuid());
// keep a single anchor connection open, so that the shared in-memory database it refers to is not dropped
// Keep a single anchor connection open, so that the shared in-memory database it refers to is not dropped.
_connection = new SqliteConnection(_sharedInMemoryConnectionString);
_connection.Open();
}
@@ -55,14 +55,14 @@ public class LuminaApiFactory : WebApplicationFactory<Program>, IDisposable
{
builder.ConfigureAppConfiguration((context, config) =>
{
// clear all existing configuration sources
// Clear all existing configuration sources.
config.Sources.Clear();
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
config.AddJsonFile($"appsettings.test.json", optional: true, reloadOnChange: true);
config.AddJsonFile("appsettings.shared.json", optional: true, reloadOnChange: true);
config.AddJsonFile($"appsettings.shared.test.json", optional: true, reloadOnChange: true);
// First add the test values directly
// First add the test values directly.
config.AddInMemoryCollection(initialData: new Dictionary<string, string?>
{
["JwtSettings:SecretKey"] = "test-key-thats-at-least-32-chars-long-for-jwt",
@@ -70,22 +70,22 @@ public class LuminaApiFactory : WebApplicationFactory<Program>, IDisposable
["JwtSettings:Issuer"] = "test-issuer",
["JwtSettings:Audience"] = "test-audience",
["CorsSettings:AllowedOrigins:0"] = "http://localhost:5012",
["EncryptionSettings:SecretKey"] = TEST_ENCRYPTION_KEY // base64 encoded test key
["EncryptionSettings:SecretKey"] = TEST_ENCRYPTION_KEY // Base64 encoded test key.
});
});
builder.ConfigureServices(services =>
{
// remove existing DbContext configuration
// Remove existing DbContext configuration.
ServiceDescriptor? descriptor = services.SingleOrDefault(serviceDescriptor => serviceDescriptor.ServiceType == typeof(DbContextOptions<LuminaDbContext>));
if (descriptor is not null)
services.Remove(descriptor);
// add SQLite DbContext configuration
// Add SQLite DbContext configuration.
services.AddDbContext<LuminaDbContext>((serviceProvider, options) =>
{
options.UseSqlite(_sharedInMemoryConnectionString);
options.AddInterceptors(serviceProvider.GetRequiredService<UpdateAuditableEntitiesInterceptor>());
});
// configure JWT authentication for testing
// Configure JWT authentication for testing.
services.PostConfigure<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme, options =>
{
options.TokenValidationParameters = new TokenValidationParameters
@@ -99,7 +99,7 @@ public class LuminaApiFactory : WebApplicationFactory<Program>, IDisposable
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("test-key-thats-at-least-32-chars-long-for-jwt"))
};
});
// build service provider and ensure database is created
// Build service provider and ensure database is created.
ServiceProvider servicePreovider = services.BuildServiceProvider();
using (IServiceScope scope = servicePreovider.CreateScope())
{
@@ -79,7 +79,7 @@ public class GetPermissionsEndpointTests : IClassFixture<AuthenticatedLuminaApiF
public async Task GetPermissions_WhenCalledWithNonAdminAccount_ShouldReturnForbiddenResult()
{
// Act
_client = await _apiFactory.CreateAuthenticatedClientAsync(); // authenticated user, but not admin
_client = await _apiFactory.CreateAuthenticatedClientAsync(); // Authenticated user, but not admin.
HttpResponseMessage response = await _client.GetAsync("/api/v1/auth/permissions");
// Assert
@@ -122,11 +122,11 @@ public class GetPermissionsEndpointTests : IClassFixture<AuthenticatedLuminaApiF
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
// clear junction tables first
// Clear junction tables first.
await dbContext.Set<RolePermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserPermissionEntity>().ExecuteDeleteAsync();
// then clear main tables
// Then clear main tables.
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
await dbContext.Set<RoleEntity>().ExecuteDeleteAsync();
await dbContext.Set<PermissionEntity>().ExecuteDeleteAsync();
@@ -173,11 +173,11 @@ public class AddRoleEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
// clear junction tables first
// Clear junction tables first.
await dbContext.Set<RolePermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserPermissionEntity>().ExecuteDeleteAsync();
// then clear main tables
// Then clear main tables.
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
await dbContext.Set<RoleEntity>().ExecuteDeleteAsync();
await dbContext.Set<PermissionEntity>().ExecuteDeleteAsync();
@@ -61,7 +61,7 @@ public class DeleteRoleEndpointTests : IClassFixture<AuthenticatedLuminaApiFacto
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
// Create a test role first
// Create a test role first.
RoleEntity role = _roleEntityFixture.Create(roleName: "TestRole");
dbContext.Roles.Add(role);
await dbContext.SaveChangesAsync();
@@ -72,7 +72,7 @@ public class DeleteRoleEndpointTests : IClassFixture<AuthenticatedLuminaApiFacto
// Assert
Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);
// verify role was deleted
// Verify role was deleted.
RoleEntity? deletedRole = await dbContext.Roles.FirstOrDefaultAsync(r => r.Id == role.Id);
Assert.Null(deletedRole);
}
@@ -177,11 +177,11 @@ public class DeleteRoleEndpointTests : IClassFixture<AuthenticatedLuminaApiFacto
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
// clear junction tables first
// Clear junction tables first.
await dbContext.Set<RolePermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserPermissionEntity>().ExecuteDeleteAsync();
// then clear main tables
// Then clear main tables.
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
await dbContext.Set<RoleEntity>().ExecuteDeleteAsync();
await dbContext.Set<PermissionEntity>().ExecuteDeleteAsync();
@@ -89,7 +89,7 @@ public class GetRolePermissionsEndpointTests : IClassFixture<AuthenticatedLumina
public async Task GetRolePermissions_WhenCalledWithNonAdminAccount_ShouldReturnForbiddenResult()
{
// Arrange
_client = await _apiFactory.CreateAuthenticatedClientAsync(); // authenticated user, but not admin
_client = await _apiFactory.CreateAuthenticatedClientAsync(); // Authenticated user, but not admin.
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
RoleEntity? role = dbContext.Roles.FirstOrDefault();
@@ -161,11 +161,11 @@ public class GetRolePermissionsEndpointTests : IClassFixture<AuthenticatedLumina
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
// clear junction tables first
// Clear junction tables first.
await dbContext.Set<RolePermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserPermissionEntity>().ExecuteDeleteAsync();
// then clear main tables
// Then clear main tables.
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
await dbContext.Set<RoleEntity>().ExecuteDeleteAsync();
await dbContext.Set<PermissionEntity>().ExecuteDeleteAsync();
@@ -119,11 +119,11 @@ public class GetRolesEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
// clear junction tables first
// Clear junction tables first.
await dbContext.Set<RolePermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserPermissionEntity>().ExecuteDeleteAsync();
// then clear main tables
// Then clear main tables.
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
await dbContext.Set<RoleEntity>().ExecuteDeleteAsync();
await dbContext.Set<PermissionEntity>().ExecuteDeleteAsync();
@@ -185,11 +185,11 @@ public class UpdateRoleEndpointTests : IClassFixture<AuthenticatedLuminaApiFacto
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
// clear junction tables first
// Clear junction tables first.
await dbContext.Set<RolePermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserPermissionEntity>().ExecuteDeleteAsync();
// then clear main tables
// Then clear main tables.
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
await dbContext.Set<RoleEntity>().ExecuteDeleteAsync();
await dbContext.Set<PermissionEntity>().ExecuteDeleteAsync();
@@ -78,10 +78,10 @@ public class AddFavoriteEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
}
[Theory]
[InlineData(FavoriteMediaKind.MusicArtist)] // a favorite of an artist of a music library
[InlineData(FavoriteMediaKind.MusicAlbum)] // a favorite of an album of a music library
[InlineData(FavoriteMediaKind.MusicTrack)] // a favorite of a track of a music library
[InlineData(FavoriteMediaKind.Book)] // a favorite of a book of a book library
[InlineData(FavoriteMediaKind.MusicArtist)] // A favorite of an artist of a music library.
[InlineData(FavoriteMediaKind.MusicAlbum)] // A favorite of an album of a music library.
[InlineData(FavoriteMediaKind.MusicTrack)] // A favorite of a track of a music library.
[InlineData(FavoriteMediaKind.Book)] // A favorite of a book of a book library.
public async Task AddFavorite_WhenMediaItemExists_ShouldReturnTheFavoriteAndStoreOneRowForTheCaller(FavoriteMediaKind mediaKind)
{
// Arrange
@@ -138,10 +138,10 @@ public class AddFavoriteEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
}
[Theory]
[InlineData(FavoriteMediaKind.MusicArtist, "ArtistNotFound")] // a missing artist is reported with the artist detail
[InlineData(FavoriteMediaKind.MusicAlbum, "AlbumNotFound")] // a missing album is reported with the album detail
[InlineData(FavoriteMediaKind.MusicTrack, "TrackNotFound")] // a missing track is reported with the track detail
[InlineData(FavoriteMediaKind.Book, "BookNotFound")] // a missing book is reported with the book detail
[InlineData(FavoriteMediaKind.MusicArtist, "ArtistNotFound")] // A missing artist is reported with the artist detail.
[InlineData(FavoriteMediaKind.MusicAlbum, "AlbumNotFound")] // A missing album is reported with the album detail.
[InlineData(FavoriteMediaKind.MusicTrack, "TrackNotFound")] // A missing track is reported with the track detail.
[InlineData(FavoriteMediaKind.Book, "BookNotFound")] // A missing book is reported with the book detail.
public async Task AddFavorite_WhenMediaItemDoesNotExist_ShouldReturnNotFoundWithTheKindSpecificDetail(FavoriteMediaKind mediaKind, string expectedDetail)
{
// Arrange
@@ -161,8 +161,8 @@ public class AddFavoriteEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
}
[Theory]
[InlineData(FavoriteMediaKind.Video)] // video libraries are not catalogued yet
[InlineData(FavoriteMediaKind.Photo)] // photo libraries are not catalogued yet
[InlineData(FavoriteMediaKind.Video)] // Video libraries are not catalogued yet.
[InlineData(FavoriteMediaKind.Photo)] // Photo libraries are not catalogued yet.
public async Task AddFavorite_WhenMediaKindIsPlanned_ShouldReturnValidationProblem(FavoriteMediaKind mediaKind)
{
// Arrange
@@ -166,7 +166,7 @@ public class AddArtistEndpointTests : IClassFixture<AuthenticatedLuminaApiFactor
public async Task AddArtist_WhenLibraryDoesNotExist_ShouldReturnNotFound()
{
// Arrange
// only an admin reaches the library lookup of a library that does not exist, because a regular user is rejected by the ownership policy before it
// Only an admin reaches the library lookup of a library that does not exist, because a regular user is rejected by the ownership policy before it.
HttpClient adminClient = await _apiFactory.CreateAuthenticatedAdminClientAsync();
Guid missingLibraryId = Guid.NewGuid();
AddAlbumRequest album = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
@@ -1068,7 +1068,7 @@ public class AddTrackEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
public async Task AddTrack_WhenTheLibraryDoesNotExist_ShouldReturnNotFound()
{
// Arrange
// only an admin reaches the library lookup of a library that does not exist, because a regular user is rejected by the ownership policy before it
// Only an admin reaches the library lookup of a library that does not exist, because a regular user is rejected by the ownership policy before it.
HttpClient adminClient = await _apiFactory.CreateAuthenticatedAdminClientAsync();
Guid missingLibraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
@@ -93,8 +93,8 @@ public class GetTrackSegmentEndpointTests : IClassFixture<AuthenticatedLuminaApi
}
[Theory]
[InlineData("uppercase")] // the handle format only accepts lowercase hexadecimal characters
[InlineData("dashed")] // the handle format is the N format of a GUID, without dashes
[InlineData("uppercase")] // The handle format only accepts lowercase hexadecimal characters.
[InlineData("dashed")] // The handle format is the N format of a GUID, without dashes.
public async Task GetTrackSegment_WhenDeliveryIdFormatIsInvalid_ShouldReturnValidationProblem(string malformedHandleKind)
{
// Arrange
@@ -144,9 +144,9 @@ public class GetTrackSegmentEndpointTests : IClassFixture<AuthenticatedLuminaApi
}
[Theory]
[InlineData("library")] // the handle was issued for the library of another delivery
[InlineData("artist")] // the handle was issued for the artist of another delivery
[InlineData("album")] // the handle was issued for the album of another delivery
[InlineData("library")] // The handle was issued for the library of another delivery.
[InlineData("artist")] // The handle was issued for the artist of another delivery.
[InlineData("album")] // The handle was issued for the album of another delivery.
public async Task GetTrackSegment_WhenDeliveryWasIssuedForAnotherScope_ShouldReturnPlaybackDeliveryNotFound(string mismatchedScope)
{
// Arrange
@@ -236,9 +236,9 @@ public class ShuffleTracksEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
}
[Theory]
[InlineData(0, "ShuffleTrackCountMustBeGreaterThanZero")] // no track is requested
[InlineData(-1, "ShuffleTrackCountMustBeGreaterThanZero")] // a negative selection size
[InlineData(501, "ShuffleTrackCountMustBeAtMost500")] // one more than the documented maximum
[InlineData(0, "ShuffleTrackCountMustBeGreaterThanZero")] // No track is requested.
[InlineData(-1, "ShuffleTrackCountMustBeGreaterThanZero")] // A negative selection size.
[InlineData(501, "ShuffleTrackCountMustBeAtMost500")] // One more than the documented maximum.
public async Task ShuffleTracks_WhenCountIsInvalid_ShouldReturnUnprocessableEntityWithTheValidationError(int count, string expectedError)
{
// Arrange
@@ -142,7 +142,7 @@ public class UpdateTrackEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
Assert.NotNull(trackResponse);
Assert.Equal(trackId, trackResponse!.Id);
Assert.Equal(libraryId, trackResponse.LibraryId);
// the file system path is preserved by the update, it is set only when the track is created
// The file system path is preserved by the update, it is set only when the track is created.
Assert.Equal(originalPath, trackResponse.Path);
Assert.Equal("Somebody to Love", trackResponse.Metadata!.Title);
@@ -191,7 +191,7 @@ public class UpdateTrackEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
string content = await response.Content.ReadAsStringAsync();
TrackResponse? trackResponse = JsonSerializer.Deserialize<TrackResponse>(content, _jsonOptions);
Assert.NotNull(trackResponse);
// the posted file system path is ignored, because a track path is set only when the track is created by the scanner
// The posted file system path is ignored, because a track path is set only when the track is created by the scanner.
Assert.Equal(originalPath, trackResponse!.Path);
Assert.NotEqual(attemptedPath, trackResponse.Path);
Assert.Equal("Somebody to Love", trackResponse.Metadata!.Title);
@@ -272,9 +272,9 @@ public class GetAllUsersConsumptionStatisticsEndpointTests : IClassFixture<Authe
}
[Theory]
[InlineData("999")] // a number that is not a member name
[InlineData("1")] // a number that is a defined enumeration value, which must still be rejected
[InlineData("not-a-media-kind")] // a name that is not a member of the enumeration
[InlineData("999")] // A number that is not a member name.
[InlineData("1")] // A number that is a defined enumeration value, which must still be rejected.
[InlineData("not-a-media-kind")] // A name that is not a member of the enumeration.
public async Task GetAllUsersConsumptionStatistics_WhenMediaKindIsNotAMemberName_ShouldReturnValidationProblem(string mediaKind)
{
// Arrange
@@ -303,9 +303,9 @@ public class GetConsumptionStatisticsEndpointTests : IClassFixture<Authenticated
}
[Theory]
[InlineData("999")] // a number that is not a member name
[InlineData("1")] // a number that is a defined enumeration value, which must still be rejected
[InlineData("not-a-media-kind")] // a name that is not a member of the enumeration
[InlineData("999")] // A number that is not a member name.
[InlineData("1")] // A number that is a defined enumeration value, which must still be rejected.
[InlineData("not-a-media-kind")] // A name that is not a member of the enumeration.
public async Task GetConsumptionStatistics_WhenMediaKindIsNotAMemberName_ShouldReturnValidationProblem(string mediaKind)
{
// Arrange
@@ -337,8 +337,8 @@ public class GetConsumptionStatisticsEndpointTests : IClassFixture<Authenticated
}
[Theory]
[InlineData("not-a-date")] // a textual value that is not a date
[InlineData("2026-13-45T99:99:99")] // a value with out of range components
[InlineData("not-a-date")] // A textual value that is not a date.
[InlineData("2026-13-45T99:99:99")] // A value with out of range components.
public async Task GetConsumptionStatistics_WhenADateBoundIsNotAValidDate_ShouldReturnValidationProblem(string invalidDate)
{
// Arrange
@@ -262,8 +262,8 @@ public class GetGenreConsumptionEndpointTests : IClassFixture<AuthenticatedLumin
}
[Theory]
[InlineData("999")] // a number that is not a member name
[InlineData("not-a-media-kind")] // a name that is not a member of the enumeration
[InlineData("999")] // A number that is not a member name.
[InlineData("not-a-media-kind")] // A name that is not a member of the enumeration.
public async Task GetGenreConsumption_WhenMediaKindIsNotAMemberName_ShouldReturnValidationProblem(string mediaKind)
{
// Arrange
@@ -283,9 +283,9 @@ public class GetMostConsumedEndpointTests : IClassFixture<AuthenticatedLuminaApi
}
[Theory]
[InlineData("999")] // a number that is not a member name
[InlineData("1")] // a number that is a defined enumeration value, which must still be rejected
[InlineData("not-a-media-kind")] // a name that is not a member of the enumeration
[InlineData("999")] // A number that is not a member name.
[InlineData("1")] // A number that is a defined enumeration value, which must still be rejected.
[InlineData("not-a-media-kind")] // A name that is not a member of the enumeration.
public async Task GetMostConsumed_WhenMediaKindIsNotAMemberName_ShouldReturnValidationProblem(string mediaKind)
{
// Arrange
@@ -349,9 +349,9 @@ public class GetRecentlyConsumedEndpointTests : IClassFixture<AuthenticatedLumin
}
[Theory]
[InlineData("999")] // a number that is not a member name
[InlineData("1")] // a number that is a defined enumeration value, which must still be rejected
[InlineData("not-a-media-kind")] // a name that is not a member of the enumeration
[InlineData("999")] // A number that is not a member name.
[InlineData("1")] // A number that is a defined enumeration value, which must still be rejected.
[InlineData("not-a-media-kind")] // A name that is not a member of the enumeration.
public async Task GetRecentlyConsumed_WhenMediaKindIsNotAMemberName_ShouldReturnValidationProblem(string mediaKind)
{
// Arrange
@@ -250,9 +250,9 @@ public class GetTagConsumptionEndpointTests : IClassFixture<AuthenticatedLuminaA
}
[Theory]
[InlineData("999")] // a number that is not a member name
[InlineData("1")] // a number that is a defined enumeration value, which must still be rejected
[InlineData("not-a-media-kind")] // a name that is not a member of the enumeration
[InlineData("999")] // A number that is not a member name.
[InlineData("1")] // A number that is a defined enumeration value, which must still be rejected.
[InlineData("not-a-media-kind")] // A name that is not a member of the enumeration.
public async Task GetTagConsumption_WhenMediaKindIsNotAMemberName_ShouldReturnValidationProblem(string mediaKind)
{
// Arrange
@@ -107,7 +107,7 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
Assert.NotNull(bookResponse);
// metadata checks
// Metadata checks.
Assert.Equal(bookRequest.Metadata!.Title, bookResponse!.Metadata.Title);
Assert.Equal(bookRequest.Metadata.OriginalTitle, bookResponse.Metadata.OriginalTitle);
Assert.Equal(bookRequest.Metadata.Description, bookResponse.Metadata.Description);
@@ -121,29 +121,29 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
Assert.Equal(bookRequest.Metadata.ReleaseInfo.ReleaseCountry, bookResponse.Metadata.ReleaseInfo.ReleaseCountry);
Assert.Equal(bookRequest.Metadata.ReleaseInfo.ReleaseVersion, bookResponse.Metadata.ReleaseInfo.ReleaseVersion);
// language checks
// Language checks.
Assert.Equal(bookRequest.Metadata.Language!.LanguageCode, bookResponse.Metadata.Language!.LanguageCode);
Assert.Equal(bookRequest.Metadata.Language.LanguageName, bookResponse.Metadata.Language.LanguageName);
Assert.Equal(bookRequest.Metadata.Language.NativeName, bookResponse.Metadata.Language.NativeName);
// original language checks
// Original language checks.
Assert.Equal(bookRequest.Metadata.OriginalLanguage!.LanguageCode, bookResponse.Metadata.OriginalLanguage!.LanguageCode);
Assert.Equal(bookRequest.Metadata.OriginalLanguage.LanguageName, bookResponse.Metadata.OriginalLanguage.LanguageName);
Assert.Equal(bookRequest.Metadata.OriginalLanguage.NativeName, bookResponse.Metadata.OriginalLanguage.NativeName);
// genres checks
// Genres checks.
Assert.Equal(bookRequest.Metadata.Genres!.Count, bookResponse.Metadata.Genres!.Count);
Assert.Equal(
bookRequest.Metadata.Genres.Select(genre => genre.Name!.ToLowerInvariant()).OrderBy(name => name),
bookResponse.Metadata.Genres.Select(genre => genre.Name).OrderBy(name => name));
// tags checks
// Tags checks.
Assert.Equal(bookRequest.Metadata.Tags!.Count, bookResponse.Metadata.Tags!.Count);
Assert.Equal(
bookRequest.Metadata.Tags.Select(tag => tag.Name!.ToLowerInvariant()).OrderBy(name => name),
bookResponse.Metadata.Tags.Select(tag => tag.Name).OrderBy(name => name));
// book specific properties
// Book specific properties.
Assert.Equal(bookRequest.Format, bookResponse.Format);
Assert.Equal(bookRequest.Edition, bookResponse.Edition);
Assert.Equal(bookRequest.VolumeNumber, bookResponse.VolumeNumber);
@@ -157,7 +157,7 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
Assert.Equal(bookRequest.BarnesAndNobleId, bookResponse.BarnesAndNobleId);
Assert.Equal(bookRequest.AppleBooksId, bookResponse.AppleBooksId);
// ISBNs checks
// ISBNs checks.
Assert.Equal(bookRequest.ISBNs!.Count, bookResponse.ISBNs!.Count);
var requestIsbnData = bookRequest.ISBNs.Select(isbn => new { isbn.Value, isbn.Format }).OrderBy(x => x.Value).ToList();
var responseIsbnData = bookResponse.ISBNs.Select(isbn => new { isbn.Value, isbn.Format }).OrderBy(x => x.Value).ToList();
@@ -168,7 +168,7 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
Assert.Equal(requestIsbnData[i].Format, responseIsbnData[i].Format);
}
// ratings checks
// Ratings checks.
Assert.Equal(bookRequest.Ratings!.Count, bookResponse.Ratings!.Count);
var requestRatingData = bookRequest.Ratings.Select(r => new { r.Source, r.Value, r.MaxValue, r.VoteCount }).OrderBy(x => x.Source).ToList();
var responseRatingData = bookResponse.Ratings.Select(r => new { r.Source, r.Value, r.MaxValue, r.VoteCount }).OrderBy(x => x.Source).ToList();
@@ -181,18 +181,18 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
Assert.Equal(requestRatingData[i].VoteCount, responseRatingData[i].VoteCount);
}
// series checks
// Series checks.
if (bookRequest.Series is not null)
Assert.Equal(bookRequest.Series.Title, bookResponse.Series!.Title);
else
Assert.Null(bookResponse.Series);
// check Location header
// Check Location header.
Assert.NotNull(response.Headers.Location);
string locationUri = response.Headers.Location!.ToString();
Assert.EndsWith($"/api/v1/libraries/{_libraryId}/books/{bookResponse.Id}", locationUri);
// extract ID from Location header and compare
// Extract ID from Location header and compare.
string idFromHeader = locationUri.Split('/').Last();
Assert.Equal(idFromHeader, bookResponse.Id.ToString());
}
@@ -1320,7 +1320,7 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
public async Task AddBook_WhenTheLibraryDoesNotExist_ShouldReturnNotFound()
{
// Arrange
// only an admin reaches the library lookup of a library that does not exist, because a regular user is rejected by the ownership policy before it
// Only an admin reaches the library lookup of a library that does not exist, because a regular user is rejected by the ownership policy before it.
HttpClient adminClient = await _apiFactory.CreateAuthenticatedAdminClientAsync();
Guid missingLibraryId = Guid.NewGuid();
AddBookRequest bookRequest = _addBookRequestFixture.Create(contributors: []);
@@ -93,7 +93,7 @@ public class SetupApplicationEndpointTests : IClassFixture<AuthenticatedLuminaAp
Assert.NotNull(response.Headers.Location);
Assert.Equal($"http://localhost/api/v1/users/{result.Id}", response.Headers.Location.ToString());
// verify default permissions, roles, and role permissions are set
// Verify default permissions, roles, and role permissions are set.
await VerifyDefaultSetup(result.Id);
}
@@ -125,7 +125,7 @@ public class SetupApplicationEndpointTests : IClassFixture<AuthenticatedLuminaAp
Assert.NotNull(response.Headers.Location);
Assert.Equal($"http://localhost/api/v1/users/{result.Id}", response.Headers.Location.ToString());
// verify default permissions, roles, and role permissions are set
// Verify default permissions, roles, and role permissions are set.
await VerifyDefaultSetup(result.Id);
}
@@ -187,26 +187,26 @@ public class SetupApplicationEndpointTests : IClassFixture<AuthenticatedLuminaAp
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
// TODO: update list when defaults change
// verify default permissions
// TODO: update list when defaults change.
// Verify default permissions.
List<PermissionEntity> permissions = await dbContext.Permissions.ToListAsync();
Assert.Contains(permissions, p => p.PermissionName == AuthorizationPermission.CanViewUsers);
Assert.Contains(permissions, p => p.PermissionName == AuthorizationPermission.CanDeleteUsers);
Assert.Contains(permissions, p => p.PermissionName == AuthorizationPermission.CanRegisterUsers);
// verify default roles
// Verify default roles.
List<RoleEntity> roles = await dbContext.Roles.ToListAsync();
RoleEntity? adminRole = roles.FirstOrDefault(r => r.RoleName == "Admin");
Assert.NotNull(adminRole);
// verify admin role permissions
// Verify admin role permissions.
List<RolePermissionEntity> rolePermissions = await dbContext.RolePermissions
.Where(rp => rp.RoleId == adminRole!.Id)
.ToListAsync();
Assert.NotEmpty(rolePermissions);
Assert.Contains(rolePermissions, rp => permissions.Any(p => p.Id == rp.PermissionId));
// verify user has admin role
// Verify user has admin role.
UserRoleEntity? userRole = await dbContext.UserRoles.FirstOrDefaultAsync(ur => ur.UserId == userId && ur.RoleId == adminRole!.Id);
Assert.NotNull(userRole);
}
@@ -176,7 +176,7 @@ public class InstallPluginEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
public async Task InstallPlugin_WhenCalledWithoutArchive_ShouldReturnValidationProblem()
{
// Arrange
// a multipart form without any file part, only a regular form field, so the archive is missing
// A multipart form without any file part, only a regular form field, so the archive is missing.
using MultipartFormDataContent multipartContent = [];
multipartContent.Add(new StringContent("value"), "field");
@@ -275,7 +275,7 @@ public class InstallPluginEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
// the admin seeding performed by the factory is not idempotent, so the seed data must be cleared between tests
// The admin seeding performed by the factory is not idempotent, so the seed data must be cleared between tests.
await dbContext.Set<RolePermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserPermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserRoleEntity>().ExecuteDeleteAsync();
@@ -72,12 +72,12 @@ public class DeleteThemeEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
// Assert
Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);
// the theme row is removed from the database
// The theme row is removed from the database.
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.Null(await dbContext.Themes.FirstOrDefaultAsync(theme => theme.ThemeId == themeId));
// the theme no longer appears in GET /themes
// The theme no longer appears in GET /themes.
HttpResponseMessage listResponse = await _client.GetAsync("/api/v1/themes");
List<ThemeResponse>? themes = await listResponse.Content.ReadFromJsonAsync<List<ThemeResponse>>(_jsonOptions);
Assert.NotNull(themes);
@@ -114,11 +114,11 @@ public class DeleteThemeEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
// Arrange
await ThemeTestHelpers.WaitForBundledThemeAsync(_apiFactory);
// deleting a bundled theme that is not the last remaining one is allowed, so only the last one is protected
// Deleting a bundled theme that is not the last remaining one is allowed, so only the last one is protected.
HttpResponseMessage firstDeletionResponse = await _client.DeleteAsync("/api/v1/themes/editorial-paper");
Assert.Equal(HttpStatusCode.NoContent, firstDeletionResponse.StatusCode);
// Act: the last remaining bundled theme cannot be deleted
// Act: the last remaining bundled theme cannot be deleted.
HttpResponseMessage response = await _client.DeleteAsync("/api/v1/themes/lumina-default");
// Assert
@@ -135,7 +135,7 @@ public class DeleteThemeEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
// restore the soft-deleted bundled theme, so the following tests start from a clean state
// Restore the soft-deleted bundled theme, so the following tests start from a clean state.
HttpResponseMessage restoreResponse = await _client.PostAsJsonAsync("/api/v1/themes/editorial-paper/restore", new { });
Assert.Equal(HttpStatusCode.NoContent, restoreResponse.StatusCode);
}
@@ -218,7 +218,7 @@ public class DeleteThemeEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
foreach (string themeId in _installedThemeIds)
await themeService.DeleteAsync(themeId, CancellationToken.None);
// the admin seeding performed by the factory is not idempotent, so the seed data must be cleared between tests
// The admin seeding performed by the factory is not idempotent, so the seed data must be cleared between tests.
await dbContext.Set<RolePermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserPermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserRoleEntity>().ExecuteDeleteAsync();
@@ -86,13 +86,13 @@ public class InstallThemeEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
Assert.Equal(ThemeInstallSource.Uploaded, result.InstallSource);
Assert.Null(result.IsCurrent);
// the installed theme is listed by GET /themes
// The installed theme is listed by GET /themes.
HttpResponseMessage listResponse = await _client.GetAsync("/api/v1/themes");
List<ThemeResponse>? themes = await listResponse.Content.ReadFromJsonAsync<List<ThemeResponse>>(_jsonOptions);
Assert.NotNull(themes);
Assert.Contains(themes!, theme => theme.ThemeId == themeId);
// the installed theme is persisted in the database
// The installed theme is persisted in the database.
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.NotNull(await dbContext.Themes.FirstOrDefaultAsync(theme => theme.ThemeId == themeId));
@@ -131,7 +131,7 @@ public class InstallThemeEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
public async Task InstallTheme_WhenCalledWithoutArchive_ShouldReturnValidationProblem()
{
// Arrange
// a multipart form without any file part, only a regular form field, so the archive is missing
// A multipart form without any file part, only a regular form field, so the archive is missing.
using MultipartFormDataContent multipartContent = [];
multipartContent.Add(new StringContent("value"), "field");
@@ -224,7 +224,7 @@ public class InstallThemeEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
foreach (string themeId in _installedThemeIds)
await themeService.DeleteAsync(themeId, CancellationToken.None);
// the admin seeding performed by the factory is not idempotent, so the seed data must be cleared between tests
// The admin seeding performed by the factory is not idempotent, so the seed data must be cleared between tests.
await dbContext.Set<RolePermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserPermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserRoleEntity>().ExecuteDeleteAsync();
@@ -79,7 +79,7 @@ public class RestoreThemeEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
// Assert
Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);
// the theme is available again and appears in the list
// The theme is available again and appears in the list.
using IServiceScope verificationScope = _apiFactory.Services.CreateScope();
LuminaDbContext verificationContext = verificationScope.ServiceProvider.GetRequiredService<LuminaDbContext>();
ThemeEntity? restoredTheme = await verificationContext.Themes.FirstOrDefaultAsync(candidate => candidate.ThemeId == "editorial-paper");
@@ -218,7 +218,7 @@ public class RestoreThemeEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
foreach (string themeId in _installedThemeIds)
await themeService.DeleteAsync(themeId, CancellationToken.None);
// the admin seeding performed by the factory is not idempotent, so the seed data must be cleared between tests
// The admin seeding performed by the factory is not idempotent, so the seed data must be cleared between tests.
await dbContext.Set<RolePermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserPermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserRoleEntity>().ExecuteDeleteAsync();
@@ -82,7 +82,7 @@ public class SetCurrentThemeEndpointTests : IClassFixture<AuthenticatedLuminaApi
Assert.Equal(themeId, result!.ThemeId);
Assert.True(result.IsCurrent);
// the newly active theme is returned by GET /themes/current
// The newly active theme is returned by GET /themes/current.
HttpResponseMessage currentResponse = await _client.GetAsync("/api/v1/themes/current");
ThemeResponse? current = await currentResponse.Content.ReadFromJsonAsync<ThemeResponse>(_jsonOptions);
Assert.NotNull(current);
@@ -222,7 +222,7 @@ public class SetCurrentThemeEndpointTests : IClassFixture<AuthenticatedLuminaApi
}
}
// restore the bundled default theme as the active one, so the following tests start from a clean state
// Restore the bundled default theme as the active one, so the following tests start from a clean state.
ThemeEntity? bundledTheme = await dbContext.Themes.FirstOrDefaultAsync(t => t.ThemeId == "lumina-default");
if (bundledTheme is not null)
bundledTheme.IsCurrent = true;
@@ -233,7 +233,7 @@ public class SetCurrentThemeEndpointTests : IClassFixture<AuthenticatedLuminaApi
foreach (string themeId in _installedThemeIds)
await themeService.DeleteAsync(themeId, CancellationToken.None);
// the admin seeding performed by the factory is not idempotent, so the seed data must be cleared between tests
// The admin seeding performed by the factory is not idempotent, so the seed data must be cleared between tests.
await dbContext.Set<RolePermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserPermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserRoleEntity>().ExecuteDeleteAsync();
@@ -52,7 +52,7 @@ public class GetThemeAssetEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
HttpClient anonymousClient = _apiFactory.CreateClient();
// Act
// the asset path is relative to the theme pack root and includes the assets/ prefix, so the URL is
// The asset path is relative to the theme pack root and includes the assets/ prefix, so the URL is
// /themes/{themeId}/assets/assets/{assetPath} (the first assets/ segment is the route prefix)
HttpResponseMessage response = await anonymousClient.GetAsync("/api/v1/themes/editorial-paper/assets/assets/theme.css");
@@ -123,11 +123,11 @@ public class GetUsersEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
// clear junction tables first
// Clear junction tables first.
await dbContext.Set<RolePermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserPermissionEntity>().ExecuteDeleteAsync();
// then clear main tables
// Then clear main tables.
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
await dbContext.Set<RoleEntity>().ExecuteDeleteAsync();
await dbContext.Set<PermissionEntity>().ExecuteDeleteAsync();
@@ -310,7 +310,7 @@ public class LoginEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>,
UserEntity user = _userEntityFixture.Create(username: _testUsername, password: _hashService.HashString("TestPass123!"));
user.TotpSecret = null;
user.TempPassword = Uri.EscapeDataString(_hashService.HashString("TempPass123!"));
user.TempPasswordCreated = DateTime.UtcNow.AddMinutes(-16); // expired (> 15 minutes old)
user.TempPasswordCreated = DateTime.UtcNow.AddMinutes(-16); // Expired (> 15 minutes old).
dbContext.Users.Add(user);
await dbContext.SaveChangesAsync();
@@ -58,7 +58,7 @@ public class RecoverPasswordEndpointTests : IClassFixture<AuthenticatedLuminaApi
_apiFactory = apiFactory;
_testUsername = $"testuser_{Guid.NewGuid()}";
// get the encryption service with the test key from factory
// Get the encryption service with the test key from factory.
using IServiceScope scope = apiFactory.Services.CreateScope();
_cryptographyService = scope.ServiceProvider.GetRequiredService<ICryptographyService>();
}
@@ -78,7 +78,7 @@ public class RecoverPasswordEndpointTests : IClassFixture<AuthenticatedLuminaApi
// Arrange
UserEntity user = await CreateUserWithTotp();
// decrypt the TOTP secret and generate a valid code
// Decrypt the TOTP secret and generate a valid code.
byte[] totpSecret = Convert.FromBase64String(_cryptographyService.Decrypt(user.TotpSecret!));
Totp totp = new(totpSecret);
string validTotpCode = totp.ComputeTotp(DateTime.UtcNow);
@@ -101,11 +101,11 @@ public class RecoverPasswordEndpointTests : IClassFixture<AuthenticatedLuminaApi
Assert.NotNull(result);
Assert.True(result!.IsPasswordReset);
// Create a new context to get fresh data
// Create a new context to get fresh data.
using IServiceScope verificationScope = _apiFactory.Services.CreateScope();
LuminaDbContext verificationContext = verificationScope.ServiceProvider.GetRequiredService<LuminaDbContext>();
// Ensure we get fresh data from the database
// Ensure we get fresh data from the database.
verificationContext.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
UserEntity? updatedUser = await verificationContext.Users
.AsNoTracking()
@@ -244,12 +244,12 @@ public class RecoverPasswordEndpointTests : IClassFixture<AuthenticatedLuminaApi
public async Task RecoverPassword_WhenUserDoesNotUseTotpAndTriesToRecoverWithoutCode_ShouldReturnForbiddenResult()
{
// Arrange
// Setup user without TOTP
// Setup user without TOTP.
using (IServiceScope scope = _apiFactory.Services.CreateScope())
{
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity userWithoutTotp = _userEntityFixture.Create(username: "userwithoutotp2", password: _hashService.HashString("OldPass123!"));
userWithoutTotp.TotpSecret = null; // No TOTP configured
userWithoutTotp.TotpSecret = null; // No TOTP configured.
dbContext.Users.Add(userWithoutTotp);
await dbContext.SaveChangesAsync();
}
@@ -174,7 +174,7 @@ public class GetAuthorizationEndpointTests : IClassFixture<AuthenticatedLuminaAp
private async Task<UserEntity> AddRolesAndPermissionsToUser(UserEntity existingUser, LuminaDbContext dbContext)
{
// create and save role and permission first
// Create and save role and permission first.
RoleEntity adminRole = _roleEntityFixture.Create(roleName: "Admin");
PermissionEntity viewUsersPermission = _permissionEntityFixture.Create(permissionName: AuthorizationPermission.CanViewUsers);
@@ -182,21 +182,21 @@ public class GetAuthorizationEndpointTests : IClassFixture<AuthenticatedLuminaAp
await dbContext.Permissions.AddAsync(viewUsersPermission);
await dbContext.SaveChangesAsync();
// create role permission
// Create role permission.
RolePermissionEntity rolePermission = _rolePermissionEntityFixture.Create(role: adminRole, permission: viewUsersPermission);
await dbContext.RolePermissions.AddAsync(rolePermission);
await dbContext.SaveChangesAsync();
// remove existing user role if any
// Remove existing user role if any.
if (existingUser.UserRole != null)
dbContext.UserRoles.Remove(existingUser.UserRole);
// add new user role
// Add new user role.
UserRoleEntity userRole = _userRoleEntityFixture.Create(user: existingUser, role: adminRole);
await dbContext.UserRoles.AddAsync(userRole);
await dbContext.SaveChangesAsync();
// refresh the user entity
// Refresh the user entity.
await dbContext.Entry(existingUser).ReloadAsync();
return existingUser;
@@ -65,7 +65,7 @@ public class GetUserPermissionsEndpointTests : IClassFixture<AuthenticatedLumina
UserEntity? user = dbContext.Users.FirstOrDefault();
Assert.NotNull(user);
// Add a direct user permission
// Add a direct user permission.
PermissionEntity permission = dbContext.Permissions.First();
UserPermissionEntity userPermission = _userPermissionEntityFixture.Create(user, permission);
dbContext.UserPermissions.Add(userPermission);
@@ -169,11 +169,11 @@ public class GetUserPermissionsEndpointTests : IClassFixture<AuthenticatedLumina
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
// clear junction tables first
// Clear junction tables first.
await dbContext.Set<RolePermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserPermissionEntity>().ExecuteDeleteAsync();
// then clear main tables
// Then clear main tables.
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
await dbContext.Set<RoleEntity>().ExecuteDeleteAsync();
await dbContext.Set<PermissionEntity>().ExecuteDeleteAsync();
@@ -156,11 +156,11 @@ public class GetUserRoleEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
// clear junction tables first
// Clear junction tables first.
await dbContext.Set<RolePermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserPermissionEntity>().ExecuteDeleteAsync();
// then clear main tables
// Then clear main tables.
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
await dbContext.Set<RoleEntity>().ExecuteDeleteAsync();
await dbContext.Set<PermissionEntity>().ExecuteDeleteAsync();
@@ -68,12 +68,12 @@ public class UpdateUserRoleAndPermissionsEndpointTests : IClassFixture<Authentic
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
// create a non-admin role first
// Create a non-admin role first.
RoleEntity editorRole = _roleEntityFixture.Create(roleName: "Editor");
dbContext.Roles.Add(editorRole);
await dbContext.SaveChangesAsync();
// create test user
// Create test user.
UserEntity user = _userEntityFixture.Create(username: "TestUser", password: "HashedPassword");
user.TotpSecret = null;
dbContext.Users.Add(user);
@@ -140,12 +140,12 @@ public class UpdateUserRoleAndPermissionsEndpointTests : IClassFixture<Authentic
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
// create Editor role
// Create Editor role.
RoleEntity editorRole = _roleEntityFixture.Create(roleName: "Editor");
dbContext.Roles.Add(editorRole);
await dbContext.SaveChangesAsync();
// get the admin user that was created by CreateAuthenticatedAdminClientAsync
// Get the admin user that was created by CreateAuthenticatedAdminClientAsync.
UserEntity? adminUser = dbContext.Users.FirstOrDefault(u => u.UserRole!.Role.RoleName == "Admin");
Assert.NotNull(adminUser);
UpdateUserRoleAndPermissionsRequest request = _updateUserRoleAndPermissionsRequestFixture.Create(
@@ -229,11 +229,11 @@ public class UpdateUserRoleAndPermissionsEndpointTests : IClassFixture<Authentic
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
// clear junction tables first
// Clear junction tables first.
await dbContext.Set<RolePermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserPermissionEntity>().ExecuteDeleteAsync();
// then clear main tables
// Then clear main tables.
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
await dbContext.Set<RoleEntity>().ExecuteDeleteAsync();
await dbContext.Set<PermissionEntity>().ExecuteDeleteAsync();
@@ -155,8 +155,8 @@ public class UpdatePlaybackStateEndpointTests : IClassFixture<AuthenticatedLumin
}
[Theory]
[InlineData(-0.01)] // just below the minimum
[InlineData(1.01)] // just above the maximum
[InlineData(-0.01)] // Just below the minimum.
[InlineData(1.01)] // Just above the maximum.
public async Task UpdatePlaybackState_WhenVolumeIsOutOfRange_ShouldReturnValidationError(double volume)
{
// Arrange
@@ -273,8 +273,8 @@ public class UpdateUserSettingsEndpointTests : IClassFixture<AuthenticatedLumina
}
[Theory]
[InlineData(0)] // below the minimum
[InlineData(129)] // above the maximum
[InlineData(0)] // Below the minimum.
[InlineData(129)] // Above the maximum.
public async Task UpdateUserSettings_WhenVuMeterSegmentCountIsOutOfRange_ShouldReturnValidationError(int vuMeterSegmentCount)
{
// Arrange
@@ -288,8 +288,8 @@ public class UpdateUserSettingsEndpointTests : IClassFixture<AuthenticatedLumina
}
[Theory]
[InlineData(-1)] // below the minimum
[InlineData(33)] // above the maximum
[InlineData(-1)] // Below the minimum.
[InlineData(33)] // Above the maximum.
public async Task UpdateUserSettings_WhenVuMeterSegmentGapIsOutOfRange_ShouldReturnValidationError(int vuMeterSegmentGap)
{
// Arrange
@@ -303,8 +303,8 @@ public class UpdateUserSettingsEndpointTests : IClassFixture<AuthenticatedLumina
}
[Theory]
[InlineData(-0.01)] // just below the minimum
[InlineData(1.01)] // just above the maximum
[InlineData(-0.01)] // Just below the minimum.
[InlineData(1.01)] // Just above the maximum.
public async Task UpdateUserSettings_WhenVuMeterMediumThresholdIsOutOfRange_ShouldReturnValidationError(double vuMeterMediumThreshold)
{
// Arrange
@@ -320,8 +320,8 @@ public class UpdateUserSettingsEndpointTests : IClassFixture<AuthenticatedLumina
}
[Theory]
[InlineData(-0.01)] // just below the minimum
[InlineData(1.01)] // just above the maximum
[InlineData(-0.01)] // Just below the minimum.
[InlineData(1.01)] // Just above the maximum.
public async Task UpdateUserSettings_WhenVuMeterHighThresholdIsOutOfRange_ShouldReturnValidationError(double vuMeterHighThreshold)
{
// Arrange
@@ -352,8 +352,8 @@ public class UpdateUserSettingsEndpointTests : IClassFixture<AuthenticatedLumina
}
[Theory]
[InlineData(0.5, 0.5)] // the thresholds are equal
[InlineData(0.4, 0.9)] // the high threshold is greater than the medium one
[InlineData(0.5, 0.5)] // The thresholds are equal.
[InlineData(0.4, 0.9)] // The high threshold is greater than the medium one.
public async Task UpdateUserSettings_WhenVuMeterHighThresholdIsGreaterThanOrEqualToMediumThreshold_ShouldUpdateSettings(
double vuMeterMediumThreshold,
double vuMeterHighThreshold)
@@ -372,8 +372,8 @@ public class UpdateUserSettingsEndpointTests : IClassFixture<AuthenticatedLumina
}
[Theory]
[InlineData(-1)] // below the minimum
[InlineData(10001)] // above the maximum
[InlineData(-1)] // Below the minimum.
[InlineData(10001)] // Above the maximum.
public async Task UpdateUserSettings_WhenVuMeterPeakHoldDurationIsOutOfRange_ShouldReturnValidationError(int vuMeterPeakHoldDurationInMilliseconds)
{
// Arrange
@@ -388,8 +388,8 @@ public class UpdateUserSettingsEndpointTests : IClassFixture<AuthenticatedLumina
}
[Theory]
[InlineData(-0.01)] // just below the minimum
[InlineData(100.01)] // just above the maximum
[InlineData(-0.01)] // Just below the minimum.
[InlineData(100.01)] // Just above the maximum.
public async Task UpdateUserSettings_WhenVuMeterReleasePerSecondIsOutOfRange_ShouldReturnValidationError(double vuMeterReleasePerSecond)
{
// Arrange
@@ -403,8 +403,8 @@ public class UpdateUserSettingsEndpointTests : IClassFixture<AuthenticatedLumina
}
[Theory]
[InlineData(-0.01)] // just below the minimum
[InlineData(100.01)] // just above the maximum
[InlineData(-0.01)] // Just below the minimum.
[InlineData(100.01)] // Just above the maximum.
public async Task UpdateUserSettings_WhenVuMeterPeakReleasePerSecondIsOutOfRange_ShouldReturnValidationError(double vuMeterPeakReleasePerSecond)
{
// Arrange
@@ -24,7 +24,7 @@ public class FailingDatabaseApiFactory : LuminaApiFactory
base.ConfigureWebHost(builder);
builder.ConfigureServices(services =>
{
// the health check resolves DatabaseHealthCheck from DI when it runs, so replacing its registration with a failing subclass makes /health/ready report Unhealthy
// The health check resolves DatabaseHealthCheck from DI when it runs, so replacing its registration with a failing subclass makes /health/ready report Unhealthy.
services.RemoveAll<DatabaseHealthCheck>();
services.AddScoped<DatabaseHealthCheck, FailingDatabaseHealthCheck>();
});
@@ -90,10 +90,10 @@ public class GetFavoritesEndpointTests : IClassFixture<LuminaWebFactory>, IDispo
}
[Theory]
[InlineData("", "users/me/favorites?currentPage=1&perPage=200")] // neither the page nor the size is supplied
[InlineData("?currentPage=3", "users/me/favorites?currentPage=3&perPage=200")] // only the page is supplied
[InlineData("?perPage=25", "users/me/favorites?currentPage=1&perPage=25")] // only the size is supplied
[InlineData("?currentPage=2&perPage=50", "users/me/favorites?currentPage=2&perPage=50")] // both the page and the size are supplied
[InlineData("", "users/me/favorites?currentPage=1&perPage=200")] // Neither the page nor the size is supplied.
[InlineData("?currentPage=3", "users/me/favorites?currentPage=3&perPage=200")] // Only the page is supplied.
[InlineData("?perPage=25", "users/me/favorites?currentPage=1&perPage=25")] // Only the size is supplied.
[InlineData("?currentPage=2&perPage=50", "users/me/favorites?currentPage=2&perPage=50")] // Both the page and the size are supplied.
public async Task GetFavorites_WhenCalledWithPagination_ShouldForwardTheDocumentedUpstreamUrl(string queryString, string expectedUpstreamEndpoint)
{
// Arrange
@@ -73,9 +73,9 @@ public class HomeIndexEndpointTests : IClassFixture<LuminaWebFactory>
}
[Theory]
[InlineData("/de-de")] // German culture
[InlineData("/fr-fr")] // French culture
[InlineData("/ja-jp")] // Japanese culture
[InlineData("/de-de")] // German culture.
[InlineData("/fr-fr")] // French culture.
[InlineData("/ja-jp")] // Japanese culture.
public async Task Home_WhenCalledByAuthenticatedUserWithLocalizedCulture_ShouldReturnHomePage(string culturePath)
{
// Arrange
@@ -150,8 +150,8 @@ public class GetPlaybackManifestEndpointTests : IClassFixture<LuminaWebFactory>
}
[Theory]
[InlineData("'; DROP TABLE Tracks; --")] // destructive injection
[InlineData("' OR '1'='1")] // boolean-based injection
[InlineData("'; DROP TABLE Tracks; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
public async Task GetPlaybackManifest_WithSQLInjectionInRouteId_ShouldNormalizeTheIdWithoutLeakingData(string maliciousId)
{
// Arrange
@@ -100,8 +100,8 @@ public class StreamMusicTrackEndpointTests : IClassFixture<LuminaWebFactory>
}
[Theory]
[InlineData(HttpStatusCode.ServiceUnavailable)] // a busy normalization pipeline is a transient condition
[InlineData(HttpStatusCode.TooManyRequests)] // the stream concurrency limit was reached
[InlineData(HttpStatusCode.ServiceUnavailable)] // A busy normalization pipeline is a transient condition.
[InlineData(HttpStatusCode.TooManyRequests)] // The stream concurrency limit was reached.
public async Task StreamMusicTrack_WhenApiReportsATransientCondition_ShouldReturnABareStatus(HttpStatusCode statusCode)
{
// Arrange
@@ -131,8 +131,8 @@ public class StreamMusicTrackEndpointTests : IClassFixture<LuminaWebFactory>
}
[Theory]
[InlineData(HttpStatusCode.ServiceUnavailable)] // a busy normalization pipeline is a transient condition
[InlineData(HttpStatusCode.TooManyRequests)] // the stream concurrency limit was reached
[InlineData(HttpStatusCode.ServiceUnavailable)] // A busy normalization pipeline is a transient condition.
[InlineData(HttpStatusCode.TooManyRequests)] // The stream concurrency limit was reached.
public async Task StreamMusicTrack_WhenApiReportsATransientConditionForANonMediaCaller_ShouldStillReturnABareStatus(HttpStatusCode statusCode)
{
// Arrange
@@ -91,8 +91,8 @@ public class StreamMusicTrackSegmentEndpointTests : IClassFixture<LuminaWebFacto
}
[Theory]
[InlineData(HttpStatusCode.ServiceUnavailable)] // a busy normalization pipeline is a transient condition
[InlineData(HttpStatusCode.TooManyRequests)] // the stream concurrency limit was reached
[InlineData(HttpStatusCode.ServiceUnavailable)] // A busy normalization pipeline is a transient condition.
[InlineData(HttpStatusCode.TooManyRequests)] // The stream concurrency limit was reached.
public async Task StreamMusicTrackSegment_WhenApiReportsATransientCondition_ShouldReturnABareStatus(HttpStatusCode statusCode)
{
// Arrange
@@ -92,7 +92,7 @@ public class LibrariesIndexViewEndpointTests : IClassFixture<LuminaWebFactory>
public async Task LibrariesIndexView_WhenRenderedInACultureWithNonAsciiLabels_ShouldInjectTheScriptLabelsAsJson()
{
// Arrange
// Razor would encode the non-ASCII letters of a raw label as HTML entities, which the browser shows literally inside a script, while JSON escapes them
// Razor would encode the non-ASCII letters of a raw label as HTML entities, which the browser shows literally inside a script, while JSON escapes them.
_apiFactory.ApiClientStub.Reset();
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
@@ -205,9 +205,9 @@ public class GetResumePointEndpointTests : IClassFixture<LuminaWebFactory>
}
[Theory]
[InlineData("MediaResumePointNotFound")] // the user has no resume point for the media item
[InlineData("BookNotFound")] // the book of the resume point no longer exists
[InlineData("TrackNotFound")] // the track of the resume point no longer exists
[InlineData("MediaResumePointNotFound")] // The user has no resume point for the media item.
[InlineData("BookNotFound")] // The book of the resume point no longer exists.
[InlineData("TrackNotFound")] // The track of the resume point no longer exists.
public async Task GetResumePoint_WhenApiReportsAnAbsentResumePoint_ShouldReturnSuccessWithNullData(string detail)
{
// Arrange
@@ -44,9 +44,9 @@ public class LoginViewEndpointTests : IClassFixture<LuminaWebFactory>
}
[Theory]
[InlineData("/de-de/auth/login")] // German culture
[InlineData("/fr-fr/auth/login")] // French culture
[InlineData("/zh-cn/auth/login")] // Chinese culture
[InlineData("/de-de/auth/login")] // German culture.
[InlineData("/fr-fr/auth/login")] // French culture.
[InlineData("/zh-cn/auth/login")] // Chinese culture.
public async Task LoginView_WhenCalledWithLocalizedCulture_ShouldRenderLoginPage(string culturePath)
{
// Arrange