Tidies the remaining test assertions and shared fixtures

This commit is contained in:
BinaryAlley committed 2026-09-27 23:05:11 +03:00
1 parent 4d96fe10dd
commit 385e962392
16 files changed
+938 -20

No files matched your search

@@ -18,8 +18,10 @@ namespace Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibr
[ExcludeFromCodeCoverage]
public class AudioMetadataDtoFixture
{
private const int MINIMUM_RELEASE_YEAR = 1900;
private const int MAXIMUM_RELEASE_YEAR = 2026;
private readonly Faker _faker = new();
private readonly Random _random = new();
private readonly GenreDtoFixture _genreDtoFixture = new();
private readonly TagDtoFixture _tagDtoFixture = new();
private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new();
@@ -120,8 +122,8 @@ public class AudioMetadataDtoFixture
/// <returns>The created <see cref="ReleaseInfoDto"/>.</returns>
private ReleaseInfoDto GenerateReleaseInfo()
{
int originalReleaseYear = _random.Next(1900, 2026);
int reReleaseYear = _random.Next(originalReleaseYear, 2026);
int originalReleaseYear = Random.Shared.Next(MINIMUM_RELEASE_YEAR, MAXIMUM_RELEASE_YEAR);
int reReleaseYear = Random.Shared.Next(originalReleaseYear, MAXIMUM_RELEASE_YEAR);
return _releaseInfoDtoFixture.Create(
originalReleaseDate: new DateOnly(originalReleaseYear, 1, 1),
originalReleaseYear: originalReleaseYear,
@@ -18,8 +18,10 @@ namespace Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary;
[ExcludeFromCodeCoverage]
public class WrittenContentMetadataDtoFixture
{
private const int MINIMUM_RELEASE_YEAR = 1900;
private const int MAXIMUM_RELEASE_YEAR = 2026;
private readonly Faker _faker = new();
private readonly Random _random = new();
private readonly GenreDtoFixture _genreDtoFixture = new();
private readonly TagDtoFixture _tagDtoFixture = new();
private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new();
@@ -100,8 +102,8 @@ public class WrittenContentMetadataDtoFixture
/// <returns>The created <see cref="ReleaseInfoDto"/>.</returns>
private ReleaseInfoDto CreateReleaseInfo()
{
int originalReleaseYear = _random.Next(1900, 2026);
int reReleaseYear = _random.Next(originalReleaseYear, 2026);
int originalReleaseYear = Random.Shared.Next(MINIMUM_RELEASE_YEAR, MAXIMUM_RELEASE_YEAR);
int reReleaseYear = Random.Shared.Next(originalReleaseYear, MAXIMUM_RELEASE_YEAR);
return _releaseInfoDtoFixture.Create(
originalReleaseDate: new DateOnly(originalReleaseYear, 1, 1),
originalReleaseYear: originalReleaseYear,
@@ -0,0 +1,52 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
/// <summary>
/// Fixture class for the <see cref="TrackLiteResponse"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class TrackLiteResponseFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="TrackLiteResponse"/>.
/// </summary>
/// <param name="id">Optional. The Id of the track.</param>
/// <param name="title">Optional. The title of the track.</param>
/// <param name="trackNumber">Optional. The number of the track on its disc.</param>
/// <param name="discNumber">Optional. The number of the disc the track belongs to.</param>
/// <param name="includeDiscNumber">Whether the disc number should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="TrackLiteResponse"/>.</returns>
public TrackLiteResponse Create(
Guid? id = null,
string? title = null,
int? trackNumber = null,
int? discNumber = null,
bool includeDiscNumber = true)
{
return new TrackLiteResponse(
id ?? _faker.Random.Guid(),
title ?? _faker.Lorem.Sentence(),
trackNumber ?? _faker.Random.Int(1, 30),
includeDiscNumber ? (discNumber ?? _faker.Random.Int(1, 3)) : null);
}
/// <summary>
/// Creates a list of <see cref="TrackLiteResponse"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<TrackLiteResponse> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -35,7 +35,7 @@ public class DeleteTrackCommandValidatorTests
[Theory]
[InlineData(null)] // missing route value
[InlineData("")] // empty route value
[InlineData(" ")] // whitespace route value, which the format rule skips but the not empty rule rejects
[InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject
[InlineData("not-a-library-guid")] // non-Guid route value
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId)
@@ -53,7 +53,7 @@ public class DeleteTrackCommandValidatorTests
[Theory]
[InlineData(null)] // missing route value
[InlineData("")] // empty route value
[InlineData(" ")] // whitespace route value, which the format rule skips but the not empty rule rejects
[InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject
[InlineData("not-an-artist-guid")] // non-Guid route value
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
public void Validate_WhenArtistIdIsEmptyOrInvalid_ShouldHaveValidationError(string? artistId)
@@ -71,7 +71,7 @@ public class DeleteTrackCommandValidatorTests
[Theory]
[InlineData(null)] // missing route value
[InlineData("")] // empty route value
[InlineData(" ")] // whitespace route value, which the format rule skips but the not empty rule rejects
[InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject
[InlineData("not-an-album-guid")] // non-Guid route value
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
public void Validate_WhenAlbumIdIsEmptyOrInvalid_ShouldHaveValidationError(string? albumId)
@@ -89,7 +89,7 @@ public class DeleteTrackCommandValidatorTests
[Theory]
[InlineData(null)] // missing route value
[InlineData("")] // empty route value
[InlineData(" ")] // whitespace route value, which the format rule skips but the not empty rule rejects
[InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject
[InlineData("not-a-track-guid")] // non-Guid route value
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
public void Validate_WhenTrackIdIsEmptyOrInvalid_ShouldHaveValidationError(string? trackId)
@@ -38,7 +38,7 @@ public class GetTrackQueryValidatorTests
[Theory]
[InlineData(null)] // missing route value
[InlineData("")] // empty route value
[InlineData(" ")] // whitespace route value, which the format rule skips but the not empty rule rejects
[InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject
[InlineData("not-a-library-guid")] // non-Guid route value
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId)
@@ -56,7 +56,7 @@ public class GetTrackQueryValidatorTests
[Theory]
[InlineData(null)] // missing route value
[InlineData("")] // empty route value
[InlineData(" ")] // whitespace route value, which the format rule skips but the not empty rule rejects
[InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject
[InlineData("not-an-artist-guid")] // non-Guid route value
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
public void Validate_WhenArtistIdIsEmptyOrInvalid_ShouldHaveValidationError(string? artistId)
@@ -74,7 +74,7 @@ public class GetTrackQueryValidatorTests
[Theory]
[InlineData(null)] // missing route value
[InlineData("")] // empty route value
[InlineData(" ")] // whitespace route value, which the format rule skips but the not empty rule rejects
[InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject
[InlineData("not-an-album-guid")] // non-Guid route value
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
public void Validate_WhenAlbumIdIsEmptyOrInvalid_ShouldHaveValidationError(string? albumId)
@@ -92,7 +92,7 @@ public class GetTrackQueryValidatorTests
[Theory]
[InlineData(null)] // missing route value
[InlineData("")] // empty route value
[InlineData(" ")] // whitespace route value, which the format rule skips but the not empty rule rejects
[InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject
[InlineData("not-a-track-guid")] // non-Guid route value
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
public void Validate_WhenTrackIdIsEmptyOrInvalid_ShouldHaveValidationError(string? trackId)
@@ -41,6 +41,7 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests
private readonly IUserRepository _mockUserRepository;
private readonly IRoleRepository _mockRoleRepository;
private readonly IPermissionRepository _mockPermissionRepository;
private readonly IValidator<UpdateUserRoleAndPermissionsCommand> _mockValidator;
private readonly UpdateUserRoleAndPermissionsCommandHandler _sut;
private readonly UserEntityFixture _userEntityFixture = new();
private readonly RoleEntityFixture _roleEntityFixture = new();
@@ -69,14 +70,14 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests
_mockUnitOfWork.RoleRepository.Returns(_mockRoleRepository);
_mockUnitOfWork.PermissionRepository.Returns(_mockPermissionRepository);
IValidator<UpdateUserRoleAndPermissionsCommand> mockValidator = Substitute.For<IValidator<UpdateUserRoleAndPermissionsCommand>>();
mockValidator.Validate(Arg.Any<UpdateUserRoleAndPermissionsCommand>())
_mockValidator = Substitute.For<IValidator<UpdateUserRoleAndPermissionsCommand>>();
_mockValidator.Validate(Arg.Any<UpdateUserRoleAndPermissionsCommand>())
.Returns([]);
_sut = new UpdateUserRoleAndPermissionsCommandHandler(
_mockAuthorizationService,
_mockCurrentUserService,
_mockUnitOfWork,
mockValidator);
_mockValidator);
}
[Fact]
@@ -318,4 +319,98 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
}
[Fact]
public async Task HandleAsync_WhenRoleIdIsOmitted_ShouldPreserveTheCurrentRole()
{
// Arrange
UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.Create(roleId: null);
RoleEntity currentRole = _roleEntityFixture.Create(roleName: "Editor");
UserRoleEntity userRole = _userRoleEntityFixture.Create(userId: command.UserId, role: currentRole);
UserEntity user = _userEntityFixture.Create(
id: command.UserId,
username: "testUser",
password: "hashedPassword",
userRole: userRole,
includeUserRole: true);
IEnumerable<PermissionEntity> permissions = command.Permissions.Select(permissionId =>
_permissionEntityFixture.Create(id: permissionId, permissionName: AuthorizationPermission.CanViewUsers));
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>())
.Returns(true);
_mockUserRepository.GetByIdAsync(command.UserId, cancellationToken: Arg.Any<CancellationToken>())
.Returns(user);
_mockPermissionRepository.GetByIdsAsync(command.Permissions, Arg.Any<CancellationToken>())
.Returns(Result.From(permissions));
_mockUserRepository.UpdateAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
// Act
Result<AuthorizationResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(currentRole.RoleName, result.Value.Role);
// The current role is left untouched, so the repository is asked to keep it and no role lookup is made.
await _mockUserRepository.Received(1).UpdateAsync(
Arg.Is<UserEntity>(updatedUser => updatedUser.UserRole != null && updatedUser.UserRole.RoleId == currentRole.Id),
Arg.Any<CancellationToken>());
await _mockRoleRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenPermissionDoesNotExist_ShouldReturnPermissionNotFoundError()
{
// Arrange
UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.Create(roleId: Guid.NewGuid());
UserEntity user = _userEntityFixture.Create(id: command.UserId, username: "testUser", password: "hashedPassword");
RoleEntity role = _roleEntityFixture.Create(roleName: "TestRole");
// Only one of the requested permissions exists, so resolving the rest would throw if it were done with a strict lookup.
IEnumerable<PermissionEntity> existingPermissions =
[
_permissionEntityFixture.Create(id: command.Permissions[0], permissionName: AuthorizationPermission.CanViewUsers)
];
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>())
.Returns(true);
_mockUserRepository.GetByIdAsync(command.UserId, cancellationToken: Arg.Any<CancellationToken>())
.Returns(user);
_mockRoleRepository.GetByIdAsync(command.RoleId!.Value, cancellationToken: Arg.Any<CancellationToken>())
.Returns(role);
_mockPermissionRepository.GetByIdsAsync(command.Permissions, Arg.Any<CancellationToken>())
.Returns(Result.From(existingPermissions));
// Act
Result<AuthorizationResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.PermissionNotFound, result.FirstError);
await _mockUserRepository.DidNotReceive().UpdateAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenValidationFails_ShouldReturnTheValidationErrorsWithoutPersisting()
{
// Arrange
UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.Create();
Error validationError = Error.Validation("General.Validation", "RoleIdCannotBeEmpty");
_mockValidator.Validate(command).Returns([validationError]);
// Act
Result<AuthorizationResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(validationError, result.FirstError);
// The handler short-circuits on validation failure, so no authentication, lookup or persistence work is done.
await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockUserRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>());
await _mockUserRepository.DidNotReceive().UpdateAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
}
@@ -20,6 +20,7 @@ public class AudioMetadataTests
private readonly GenreFixture _genreFixture = new();
private readonly TagFixture _tagFixture = new();
private readonly ReleaseInfoFixture _releaseInfoFixture = new();
private readonly LanguageInfoFixture _languageInfoFixture = new();
private readonly AudioMetadataFixture _audioMetadataFixture = new();
[Fact]
@@ -166,4 +167,192 @@ public class AudioMetadataTests
// Assert
Assert.NotEqual(firstResult, secondResult);
}
[Fact]
public void Create_WhenOptionalBaseValuesArePresent_ShouldSetThem()
{
// Arrange
LanguageInfo language = _languageInfoFixture.Create(languageCode: "en", languageName: "English");
LanguageInfo originalLanguage = _languageInfoFixture.Create(languageCode: "fr", languageName: "French");
// Act
Result<AudioMetadata> result = AudioMetadata.Create(
"Bohemian Rhapsody",
Optional<string>.Some("Bohemian Rhapsody (original)"),
durationInSeconds: 355,
sampleRate: 44100,
channels: 2,
_releaseInfoFixture.Create(),
Optional<string>.Some("A song by the British rock band Queen."),
[_genreFixture.Create(name: "Rock")],
[_tagFixture.Create(name: "classic")],
Optional<LanguageInfo>.Some(language),
Optional<LanguageInfo>.Some(originalLanguage),
Optional<int>.Some(16),
Optional<string>.Some("PCM"),
Optional<int>.Some(1411));
// Assert
Assert.False(result.IsFailure);
AudioMetadata metadata = result.Value;
Assert.Equal("Bohemian Rhapsody", metadata.Title);
Assert.Equal(Optional<string>.Some("Bohemian Rhapsody (original)"), metadata.OriginalTitle);
Assert.Equal(Optional<string>.Some("A song by the British rock band Queen."), metadata.Description);
Assert.Equal(Optional<LanguageInfo>.Some(language), metadata.Language);
Assert.Equal(Optional<LanguageInfo>.Some(originalLanguage), metadata.OriginalLanguage);
Assert.Single(metadata.Genres);
Assert.Single(metadata.Tags);
}
[Fact]
public void Create_WhenCollectionsAreEmpty_ShouldCreateMetadataWithEmptyCollections()
{
// Act
Result<AudioMetadata> result = AudioMetadata.Create(
"Bohemian Rhapsody",
Optional<string>.None(),
durationInSeconds: 355,
sampleRate: 44100,
channels: 2,
_releaseInfoFixture.Create(),
Optional<string>.None(),
[],
[],
Optional<LanguageInfo>.None(),
Optional<LanguageInfo>.None(),
Optional<int>.None(),
Optional<string>.None(),
Optional<int>.None());
// Assert
Assert.False(result.IsFailure);
Assert.Empty(result.Value.Genres);
Assert.Empty(result.Value.Tags);
}
[Fact]
public void Equals_WithDifferentTitle_ShouldReturnFalse()
{
// Arrange
ReleaseInfo releaseInfo = _releaseInfoFixture.Create();
// Act
AudioMetadata firstResult = _audioMetadataFixture.Create(
title: "Bohemian Rhapsody",
originalTitle: Optional<string>.None(),
durationInSeconds: 355,
sampleRate: 44100,
channels: 2,
releaseInfo: releaseInfo,
description: Optional<string>.None(),
genres: [],
tags: [],
language: Optional<LanguageInfo>.None(),
originalLanguage: Optional<LanguageInfo>.None(),
bitDepth: Optional<int>.None(),
audioCodec: Optional<string>.None(),
bitrate: Optional<int>.None());
AudioMetadata secondResult = _audioMetadataFixture.Create(
title: "Love of My Life",
originalTitle: Optional<string>.None(),
durationInSeconds: 355,
sampleRate: 44100,
channels: 2,
releaseInfo: releaseInfo,
description: Optional<string>.None(),
genres: [],
tags: [],
language: Optional<LanguageInfo>.None(),
originalLanguage: Optional<LanguageInfo>.None(),
bitDepth: Optional<int>.None(),
audioCodec: Optional<string>.None(),
bitrate: Optional<int>.None());
// Assert
Assert.NotEqual(firstResult, secondResult);
}
[Fact]
public void Equals_WithDifferentAudioCodec_ShouldReturnFalse()
{
// Arrange
ReleaseInfo releaseInfo = _releaseInfoFixture.Create();
// Act
AudioMetadata firstResult = _audioMetadataFixture.Create(
title: "Bohemian Rhapsody",
originalTitle: Optional<string>.None(),
durationInSeconds: 355,
sampleRate: 44100,
channels: 2,
releaseInfo: releaseInfo,
description: Optional<string>.None(),
genres: [],
tags: [],
language: Optional<LanguageInfo>.None(),
originalLanguage: Optional<LanguageInfo>.None(),
bitDepth: Optional<int>.None(),
audioCodec: Optional<string>.Some("PCM"),
bitrate: Optional<int>.None());
AudioMetadata secondResult = _audioMetadataFixture.Create(
title: "Bohemian Rhapsody",
originalTitle: Optional<string>.None(),
durationInSeconds: 355,
sampleRate: 44100,
channels: 2,
releaseInfo: releaseInfo,
description: Optional<string>.None(),
genres: [],
tags: [],
language: Optional<LanguageInfo>.None(),
originalLanguage: Optional<LanguageInfo>.None(),
bitDepth: Optional<int>.None(),
audioCodec: Optional<string>.Some("FLAC"),
bitrate: Optional<int>.None());
// Assert
Assert.NotEqual(firstResult, secondResult);
}
[Fact]
public void Equals_WithDifferentGenres_ShouldReturnFalse()
{
// Arrange
ReleaseInfo releaseInfo = _releaseInfoFixture.Create();
// Act
AudioMetadata firstResult = _audioMetadataFixture.Create(
title: "Bohemian Rhapsody",
originalTitle: Optional<string>.None(),
durationInSeconds: 355,
sampleRate: 44100,
channels: 2,
releaseInfo: releaseInfo,
description: Optional<string>.None(),
genres: [_genreFixture.Create(name: "Rock")],
tags: [],
language: Optional<LanguageInfo>.None(),
originalLanguage: Optional<LanguageInfo>.None(),
bitDepth: Optional<int>.None(),
audioCodec: Optional<string>.None(),
bitrate: Optional<int>.None());
AudioMetadata secondResult = _audioMetadataFixture.Create(
title: "Bohemian Rhapsody",
originalTitle: Optional<string>.None(),
durationInSeconds: 355,
sampleRate: 44100,
channels: 2,
releaseInfo: releaseInfo,
description: Optional<string>.None(),
genres: [_genreFixture.Create(name: "Jazz")],
tags: [],
language: Optional<LanguageInfo>.None(),
originalLanguage: Optional<LanguageInfo>.None(),
bitDepth: Optional<int>.None(),
audioCodec: Optional<string>.None(),
bitrate: Optional<int>.None());
// Assert
Assert.NotEqual(firstResult, secondResult);
}
}
@@ -131,4 +131,82 @@ public class AudioRatingTests
// Assert
Assert.False(result);
}
[Fact]
public void Create_WhenValueIsZero_ShouldCreateRating()
{
// Act
Result<AudioRating> result = AudioRating.Create(0m, 5m, Optional<AudioRatingSource>.None(), Optional<int>.None());
// Assert
Assert.False(result.IsFailure);
Assert.Equal(0m, result.Value.Value);
}
[Fact]
public void Create_WhenValueEqualsMaxValue_ShouldCreateRating()
{
// Act
Result<AudioRating> result = AudioRating.Create(5m, 5m, Optional<AudioRatingSource>.None(), Optional<int>.None());
// Assert
Assert.False(result.IsFailure);
Assert.Equal(5m, result.Value.Value);
Assert.Equal(5m, result.Value.MaxValue);
}
[Fact]
public void Equals_WithDifferentMaxValue_ShouldReturnFalse()
{
// Arrange
AudioRating firstRating = _audioRatingFixture.Create(value: 4m, maxValue: 5m, source: Optional<AudioRatingSource>.None(), voteCount: Optional<int>.None());
AudioRating secondRating = _audioRatingFixture.Create(value: 4m, maxValue: 10m, source: Optional<AudioRatingSource>.None(), voteCount: Optional<int>.None());
// Act
bool result = firstRating.Equals(secondRating);
// Assert
Assert.False(result);
}
[Fact]
public void Equals_WithDifferentSource_ShouldReturnFalse()
{
// Arrange
AudioRating firstRating = _audioRatingFixture.Create(value: 4m, maxValue: 5m, source: Optional<AudioRatingSource>.Some(AudioRatingSource.User), voteCount: Optional<int>.None());
AudioRating secondRating = _audioRatingFixture.Create(value: 4m, maxValue: 5m, source: Optional<AudioRatingSource>.Some(AudioRatingSource.Discogs), voteCount: Optional<int>.None());
// Act
bool result = firstRating.Equals(secondRating);
// Assert
Assert.False(result);
}
[Fact]
public void Equals_WithDifferentVoteCount_ShouldReturnFalse()
{
// Arrange
AudioRating firstRating = _audioRatingFixture.Create(value: 4m, maxValue: 5m, source: Optional<AudioRatingSource>.None(), voteCount: Optional<int>.Some(10));
AudioRating secondRating = _audioRatingFixture.Create(value: 4m, maxValue: 5m, source: Optional<AudioRatingSource>.None(), voteCount: Optional<int>.Some(20));
// Act
bool result = firstRating.Equals(secondRating);
// Assert
Assert.False(result);
}
[Fact]
public void AsPercentage_WhenCalled_ShouldReturnTheValueAsPercentageOfMaxValue()
{
// Arrange
AudioRating rating = _audioRatingFixture.Create(value: 4m, maxValue: 5m);
// Act
decimal result = rating.AsPercentage();
// Assert
Assert.Equal(80m, result);
}
}
@@ -0,0 +1,93 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate;
/// <summary>
/// Contains unit tests for the <see cref="LibraryId"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryIdTests
{
private readonly LibraryIdFixture _libraryIdFixture = new();
[Fact]
public void CreateUnique_WhenCalled_ShouldReturnIdWithNonEmptyValue()
{
// Act
LibraryId libraryId = LibraryId.CreateUnique();
// Assert
Assert.NotEqual(Guid.Empty, libraryId.Value);
}
[Fact]
public void Create_WhenCalledWithValue_ShouldReturnIdWithThatValue()
{
// Arrange
Guid value = Guid.NewGuid();
// Act
LibraryId libraryId = LibraryId.Create(value);
// Assert
Assert.Equal(value, libraryId.Value);
}
[Fact]
public void Create_WhenCalledWithEmptyGuid_ShouldReturnIdWithEmptyValue()
{
// Act
LibraryId libraryId = LibraryId.Create(Guid.Empty);
// Assert
Assert.Equal(Guid.Empty, libraryId.Value);
}
[Fact]
public void ToString_WhenCalled_ShouldReturnTheStringRepresentationOfTheValue()
{
// Arrange
Guid value = Guid.NewGuid();
LibraryId libraryId = _libraryIdFixture.Create(value);
// Act
string? result = libraryId.ToString();
// Assert
Assert.Equal(value.ToString(), result);
}
[Fact]
public void Equals_WithSameValue_ShouldReturnTrue()
{
// Arrange
Guid value = Guid.NewGuid();
LibraryId firstId = _libraryIdFixture.Create(value);
LibraryId secondId = _libraryIdFixture.Create(value);
// Act
bool result = firstId.Equals(secondId);
// Assert
Assert.True(result);
}
[Fact]
public void Equals_WithDifferentValue_ShouldReturnFalse()
{
// Arrange
LibraryId firstId = _libraryIdFixture.Create();
LibraryId secondId = _libraryIdFixture.Create();
// Act
bool result = firstId.Equals(secondId);
// Assert
Assert.False(result);
}
}
@@ -0,0 +1,93 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate;
using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate;
/// <summary>
/// Contains unit tests for the <see cref="MediaContributorId"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MediaContributorIdTests
{
private readonly MediaContributorIdFixture _mediaContributorIdFixture = new();
[Fact]
public void CreateUnique_WhenCalled_ShouldReturnIdWithNonEmptyValue()
{
// Act
MediaContributorId mediaContributorId = MediaContributorId.CreateUnique();
// Assert
Assert.NotEqual(Guid.Empty, mediaContributorId.Value);
}
[Fact]
public void Create_WhenCalledWithValue_ShouldReturnIdWithThatValue()
{
// Arrange
Guid value = Guid.NewGuid();
// Act
MediaContributorId mediaContributorId = MediaContributorId.Create(value);
// Assert
Assert.Equal(value, mediaContributorId.Value);
}
[Fact]
public void Create_WhenCalledWithEmptyGuid_ShouldReturnIdWithEmptyValue()
{
// Act
MediaContributorId mediaContributorId = MediaContributorId.Create(Guid.Empty);
// Assert
Assert.Equal(Guid.Empty, mediaContributorId.Value);
}
[Fact]
public void ToString_WhenCalled_ShouldReturnTheStringRepresentationOfTheValue()
{
// Arrange
Guid value = Guid.NewGuid();
MediaContributorId mediaContributorId = _mediaContributorIdFixture.Create(value);
// Act
string? result = mediaContributorId.ToString();
// Assert
Assert.Equal(value.ToString(), result);
}
[Fact]
public void Equals_WithSameValue_ShouldReturnTrue()
{
// Arrange
Guid value = Guid.NewGuid();
MediaContributorId firstId = _mediaContributorIdFixture.Create(value);
MediaContributorId secondId = _mediaContributorIdFixture.Create(value);
// Act
bool result = firstId.Equals(secondId);
// Assert
Assert.True(result);
}
[Fact]
public void Equals_WithDifferentValue_ShouldReturnFalse()
{
// Arrange
MediaContributorId firstId = _mediaContributorIdFixture.Create();
MediaContributorId secondId = _mediaContributorIdFixture.Create();
// Act
bool result = firstId.Equals(secondId);
// Assert
Assert.False(result);
}
}
@@ -34,6 +34,9 @@ public class TrackTests
[Fact]
public void Create_WhenCalledWithValidData_ShouldCreateTrackWithAllPropertiesPopulated()
{
// Arrange
DateTime beforeCreate = DateTime.UtcNow;
// Act
Track track = _trackFixture.Create();
@@ -56,7 +59,7 @@ public class TrackTests
Assert.True(track.MusicBrainzWorkId.HasValue);
Assert.NotEmpty(track.Contributors);
Assert.NotEmpty(track.Ratings);
Assert.True(track.CreatedOnUtc > DateTime.MinValue);
Assert.InRange(track.CreatedOnUtc, beforeCreate, DateTime.UtcNow);
Assert.False(track.UpdatedOnUtc.HasValue);
}
@@ -230,4 +233,167 @@ public class TrackTests
// the collections are not part of the details update
Assert.Equal(originalMoods, track.Moods);
}
[Fact]
public void Create_WhenOptionalValuesAndCollectionsAreEmpty_ShouldCreateTrackWithoutThem()
{
// Act
Track track = _trackFixture.Create(
discNumber: Optional<int>.None(),
moods: [],
script: Optional<string>.None(),
key: Optional<MusicKey>.None(),
bpm: Optional<int>.None(),
isrcs: [],
work: Optional<string>.None(),
musicBrainzRecordingId: Optional<MusicBrainzId>.None(),
musicBrainzTrackId: Optional<MusicBrainzId>.None(),
musicBrainzWorkId: Optional<MusicBrainzId>.None(),
contributors: [],
ratings: []);
// Assert
Assert.False(track.DiscNumber.HasValue);
Assert.False(track.Script.HasValue);
Assert.False(track.Key.HasValue);
Assert.False(track.Bpm.HasValue);
Assert.False(track.Work.HasValue);
Assert.False(track.MusicBrainzRecordingId.HasValue);
Assert.False(track.MusicBrainzTrackId.HasValue);
Assert.False(track.MusicBrainzWorkId.HasValue);
Assert.Empty(track.Moods);
Assert.Empty(track.Isrcs);
Assert.Empty(track.Contributors);
Assert.Empty(track.Ratings);
}
[Fact]
public void CreateWithId_WhenCalledWithPreExistingIdAndTimestamps_ShouldPreserveAllOptionalProperties()
{
// Arrange
Track sourceTrack = _trackFixture.Create();
DateTime createdOnUtc = DateTime.UtcNow.AddDays(-1);
DateTime updatedOnUtc = DateTime.UtcNow;
// Act
Result<Track> result = Track.Create(
sourceTrack.Id,
sourceTrack.Path,
sourceTrack.Metadata,
sourceTrack.TrackNumber,
sourceTrack.DiscNumber,
[.. sourceTrack.Moods],
sourceTrack.Script,
sourceTrack.Key,
sourceTrack.Bpm,
[.. sourceTrack.Isrcs],
sourceTrack.Work,
sourceTrack.MusicBrainzRecordingId,
sourceTrack.MusicBrainzTrackId,
sourceTrack.MusicBrainzWorkId,
[.. sourceTrack.Contributors],
[.. sourceTrack.Ratings],
createdOnUtc,
Optional<DateTime>.Some(updatedOnUtc));
// Assert
Assert.False(result.IsFailure);
Track track = result.Value;
Assert.Equal(sourceTrack.Script, track.Script);
Assert.Equal(sourceTrack.Key, track.Key);
Assert.Equal(sourceTrack.Bpm, track.Bpm);
Assert.Equal(sourceTrack.Work, track.Work);
Assert.Equal(sourceTrack.MusicBrainzRecordingId, track.MusicBrainzRecordingId);
Assert.Equal(sourceTrack.MusicBrainzTrackId, track.MusicBrainzTrackId);
Assert.Equal(sourceTrack.MusicBrainzWorkId, track.MusicBrainzWorkId);
// The pre-existing identity and the provided timestamps must survive the rehydration.
Assert.Equal(sourceTrack.Id, track.Id);
Assert.Equal(createdOnUtc, track.CreatedOnUtc);
Assert.True(track.UpdatedOnUtc.HasValue);
Assert.Equal(updatedOnUtc, track.UpdatedOnUtc.Value);
}
[Fact]
public void UpdateMoods_WhenCalledWithEmptyCollection_ShouldClearTheMoods()
{
// Arrange
Track track = _trackFixture.Create(moods: [_moodFixture.Create(name: "calm")]);
// Act
track.UpdateMoods([]);
// Assert
Assert.Empty(track.Moods);
}
[Fact]
public void UpdateIsrcs_WhenCalledWithEmptyCollection_ShouldClearTheIsrcs()
{
// Arrange
Track track = _trackFixture.Create(isrcs: [_isrcFixture.Create(value: "USRC17607839")]);
// Act
track.UpdateIsrcs([]);
// Assert
Assert.Empty(track.Isrcs);
}
[Fact]
public void UpdateContributors_WhenCalledWithEmptyCollection_ShouldClearTheContributors()
{
// Arrange
Track track = _trackFixture.Create(contributors: [.. _musicMediaContributorFixture.CreateMany()]);
// Act
track.UpdateContributors([]);
// Assert
Assert.Empty(track.Contributors);
}
[Fact]
public void UpdateRatings_WhenCalledWithEmptyCollection_ShouldClearTheRatings()
{
// Arrange
Track track = _trackFixture.Create(ratings: [_audioRatingFixture.Create(value: 4m, maxValue: 5m)]);
// Act
track.UpdateRatings([]);
// Assert
Assert.Empty(track.Ratings);
}
[Fact]
public void UpdateDetails_WhenOptionalValuesAreAbsent_ShouldClearTheOptionalProperties()
{
// Arrange
Track track = _trackFixture.Create();
// Act
Result<Updated> result = track.UpdateDetails(
"C:\\Music\\queen\\bohemian-rhapsody.flac",
_audioMetadataFixture.Create(),
11,
Optional<int>.None(),
Optional<string>.None(),
Optional<MusicKey>.None(),
Optional<int>.None(),
Optional<string>.None(),
Optional<MusicBrainzId>.None(),
Optional<MusicBrainzId>.None(),
Optional<MusicBrainzId>.None());
// Assert
Assert.False(result.IsFailure);
Assert.False(track.DiscNumber.HasValue);
Assert.False(track.Script.HasValue);
Assert.False(track.Key.HasValue);
Assert.False(track.Bpm.HasValue);
Assert.False(track.Work.HasValue);
Assert.False(track.MusicBrainzRecordingId.HasValue);
Assert.False(track.MusicBrainzTrackId.HasValue);
Assert.False(track.MusicBrainzWorkId.HasValue);
}
}
@@ -0,0 +1,109 @@
#region ========================================================================= USING =====================================================================================
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
/// <summary>
/// Contains unit tests for the <see cref="Barcode"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class BarcodeTests
{
private readonly BarcodeFixture _barcodeFixture = new();
[Fact]
public void Create_WhenCalledWithValidTwelveDigitBarcode_ShouldCreateBarcode()
{
// Act
Result<Barcode> result = Barcode.Create("123456789012");
// Assert
Assert.False(result.IsFailure);
Assert.Equal("123456789012", result.Value.Value);
}
[Fact]
public void Create_WhenCalledWithValidThirteenDigitBarcode_ShouldCreateBarcode()
{
// Act
Result<Barcode> result = Barcode.Create("1234567890123");
// Assert
Assert.False(result.IsFailure);
Assert.Equal("1234567890123", result.Value.Value);
}
[Fact]
public void Create_WhenValueHasSurroundingWhitespace_ShouldTrimIt()
{
// Act
Result<Barcode> result = Barcode.Create(" 123456789012 ");
// Assert
Assert.False(result.IsFailure);
Assert.Equal("123456789012", result.Value.Value);
}
[Theory]
[InlineData(null)] // null barcode value
[InlineData("")] // empty barcode value
[InlineData(" ")] // whitespace barcode value
public void Create_WhenValueIsNullOrWhitespace_ShouldReturnBarcodeValueCannotBeEmptyError(string? value)
{
// Act
Result<Barcode> result = Barcode.Create(value!);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Music.BarcodeValueCannotBeEmpty, result.FirstError);
}
[Theory]
[InlineData("12345678901")] // eleven digits, one too few
[InlineData("12345678901234")] // fourteen digits, one too many
[InlineData("12345678901A")] // contains a letter
[InlineData("1234-56789012")] // contains a separator
[InlineData("1234567890.2")] // contains a decimal separator
public void Create_WhenValueHasInvalidFormat_ShouldReturnInvalidFormatForBarcodeError(string value)
{
// Act
Result<Barcode> result = Barcode.Create(value);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Music.InvalidFormatForBarcode, result.FirstError);
}
[Fact]
public void Equals_WithSameValue_ShouldReturnTrue()
{
// Arrange
Barcode firstBarcode = _barcodeFixture.Create(value: "123456789012");
Barcode secondBarcode = _barcodeFixture.Create(value: "123456789012");
// Act
bool result = firstBarcode.Equals(secondBarcode);
// Assert
Assert.True(result);
}
[Fact]
public void Equals_WithDifferentValue_ShouldReturnFalse()
{
// Arrange
Barcode firstBarcode = _barcodeFixture.Create(value: "123456789012");
Barcode secondBarcode = _barcodeFixture.Create(value: "1234567890123");
// Act
bool result = firstBarcode.Equals(secondBarcode);
// Assert
Assert.False(result);
}
}
@@ -95,4 +95,29 @@ public class IsrcTests
// Assert
Assert.False(result);
}
[Fact]
public void Create_WhenRegistrantCodeContainsOnlyLetters_ShouldCreateIsrc()
{
// Act
Result<Isrc> result = Isrc.Create("GBAAA0000001");
// Assert
Assert.False(result.IsFailure);
Assert.Equal("GBAAA0000001", result.Value.Value);
}
[Fact]
public void Equals_WhenValuesDifferOnlyByCase_ShouldNormalizeThemBeforeComparing()
{
// Arrange
Isrc firstIsrc = _isrcFixture.Create(value: "USRC17607839");
Isrc secondIsrc = _isrcFixture.Create(value: "usrc17607839");
// Act
bool result = firstIsrc.Equals(secondIsrc);
// Assert
Assert.True(result);
}
}
@@ -67,4 +67,18 @@ public class TrackIdTests
// Assert
Assert.False(result);
}
[Fact]
public void ToString_WhenCalled_ShouldReturnTheStringRepresentationOfTheValue()
{
// Arrange
Guid value = Guid.NewGuid();
TrackId trackId = _trackIdFixture.Create(value);
// Act
string? result = trackId.ToString();
// Assert
Assert.Equal(value.ToString(), result);
}
}
@@ -107,7 +107,7 @@ public class BaseEndpointTests
// Assert
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(422, problemResult.StatusCode);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemResult.StatusCode);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemResult.ProblemDetails.Status);
Assert.Equal("General.Validation", problemResult.ProblemDetails.Title);
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemResult.ProblemDetails.Detail);
@@ -67,7 +67,7 @@ public class ApiHttpClientTests
Assert.Equal(HttpStatusCode.UnprocessableEntity, exception.HttpStatusCode);
Assert.NotNull(exception.ProblemDetails);
Assert.Equal("General.Validation", exception.ProblemDetails!.Title);
Assert.Equal(422, exception.ProblemDetails.Status);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, exception.ProblemDetails.Status);
Assert.Equal("OneOrMoreValidationErrorsOccurred", exception.ProblemDetails.Detail);
}