Hardens test assertions and adds missing test coverage.

This commit is contained in:
BinaryAlley committed 2026-08-18 08:28:16 -07:00
1 parent 6b86fd5805
commit 1189bbaf36
489 files changed
+39982 -512

No files matched your search

@@ -0,0 +1,179 @@
#region ========================================================================= USING =====================================================================================
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Primitives;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Common.Errors;
/// <summary>
/// Contains unit tests for the static <see cref="Errors"/> catalog classes.
/// </summary>
[ExcludeFromCodeCoverage]
public class ErrorsTests
{
[Fact]
public void LibraryScanning_WhenAccessed_ShouldExposeErrorsWithExpectedTypes()
{
// Assert
// The count assertion fails when an error is added or removed, reminding to update the assertions below.
Assert.Equal(16, typeof(DomainErrors.LibraryScanning).GetProperties().Length);
AssertError(DomainErrors.LibraryScanning.LibraryScanIdCannotBeEmpty, ErrorType.Validation);
AssertError(DomainErrors.LibraryScanning.CanOnlyStartPendingScans, ErrorType.Forbidden);
AssertError(DomainErrors.LibraryScanning.CanOnlyCompleteRunningScans, ErrorType.Forbidden);
AssertError(DomainErrors.LibraryScanning.CanOnlyCancelRunningScans, ErrorType.Forbidden);
AssertError(DomainErrors.LibraryScanning.CanOnlyFailRunningScans, ErrorType.Forbidden);
AssertError(DomainErrors.LibraryScanning.ScanIdCannotBeEmpty, ErrorType.Validation);
AssertError(DomainErrors.LibraryScanning.LibraryScanAlreadyExists, ErrorType.Conflict);
AssertError(DomainErrors.LibraryScanning.LibraryAlreadyBeingScanned, ErrorType.Forbidden);
AssertError(DomainErrors.LibraryScanning.LibraryScanNotFound, ErrorType.NotFound);
AssertError(DomainErrors.LibraryScanning.TotalScanJobItemsCountMustBePositive, ErrorType.Validation);
AssertError(DomainErrors.LibraryScanning.TotalScanJobsCountMustBePositive, ErrorType.Validation);
AssertError(DomainErrors.LibraryScanning.CompletedScanJobItemsCountMustBePositive, ErrorType.Validation);
AssertError(DomainErrors.LibraryScanning.CompletedScanJobsCountMustBePositive, ErrorType.Validation);
AssertError(DomainErrors.LibraryScanning.CompletedScanJobItemsCountCantExceedTotalScanJobItemsCount, ErrorType.Validation);
AssertError(DomainErrors.LibraryScanning.CompletedScanJobsCountCantExceedTotalScanJobsCount, ErrorType.Validation);
AssertError(DomainErrors.LibraryScanning.ScanJobCurrentOperationCannotBeEmpty, ErrorType.Validation);
}
[Fact]
public void Library_WhenAccessed_ShouldExposeErrorsWithExpectedTypes()
{
// Assert
// The count assertion fails when an error is added or removed, reminding to update the assertions below.
Assert.Equal(14, typeof(DomainErrors.Library).GetProperties().Length);
AssertError(DomainErrors.Library.CannotScanLockedLibrary, ErrorType.Forbidden);
AssertError(DomainErrors.Library.CannotScanDisabledLibrary, ErrorType.Forbidden);
AssertError(DomainErrors.Library.LibraryIdCannotBeEmpty, ErrorType.Validation);
AssertError(DomainErrors.Library.FilterMustIncludeLibraryId, ErrorType.Validation);
AssertError(DomainErrors.Library.InvalidFilterAlphaKey, ErrorType.Validation);
AssertError(DomainErrors.Library.LibraryAlreadyExists, ErrorType.Conflict);
AssertError(DomainErrors.Library.LibraryNotFound, ErrorType.NotFound);
AssertError(DomainErrors.Library.LibraryTypeCannotBeNull, ErrorType.Validation);
AssertError(DomainErrors.Library.CoverFileMustBeAnImage, ErrorType.Validation);
AssertError(DomainErrors.Library.UnknownLibraryType, ErrorType.Unexpected);
AssertError(DomainErrors.Library.PathsListCannotBeNull, ErrorType.Validation);
AssertError(DomainErrors.Library.PathsListCannotBeEmpty, ErrorType.Validation);
AssertError(DomainErrors.Library.TitleCannotBeEmpty, ErrorType.Validation);
AssertError(DomainErrors.Library.TitleMustBeMaximum255CharactersLong, ErrorType.Validation);
}
[Fact]
public void Users_WhenAccessed_ShouldExposeErrorsWithExpectedTypes()
{
// Assert
// The count assertion fails when an error is added or removed, reminding to update the assertions below.
Assert.Equal(3, typeof(DomainErrors.Users).GetProperties().Length);
AssertError(DomainErrors.Users.UserAlreadyExists, ErrorType.Conflict);
AssertError(DomainErrors.Users.UserDoesNotExist, ErrorType.NotFound);
AssertError(DomainErrors.Users.UserIdCannotBeEmpty, ErrorType.Validation);
}
[Fact]
public void UserSettings_WhenAccessed_ShouldExposeErrorsWithExpectedTypes()
{
// Assert
// The count assertion fails when an error is added or removed, reminding to update the assertions below.
Assert.Equal(3, typeof(DomainErrors.UserSettings).GetProperties().Length);
AssertError(DomainErrors.UserSettings.UserSettingsAlreadyExists, ErrorType.Conflict);
AssertError(DomainErrors.UserSettings.UserSettingsNotFound, ErrorType.NotFound);
AssertError(DomainErrors.UserSettings.ItemsPerPageMustBeGreaterThanZero, ErrorType.Validation);
}
[Fact]
public void Metadata_WhenAccessed_ShouldExposeRepresentativeErrorsWithExpectedTypes()
{
// Assert
AssertError(DomainErrors.Metadata.MetadataCannotBeNull, ErrorType.Validation);
AssertError(DomainErrors.Metadata.TitleCannotBeEmpty, ErrorType.Validation);
AssertError(DomainErrors.Metadata.OriginalReleaseYearMustBeBetween1And9999, ErrorType.Validation);
AssertError(DomainErrors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear, ErrorType.Validation);
AssertError(DomainErrors.Metadata.OriginalReleaseDateAndYearMustMatch, ErrorType.Validation);
AssertError(DomainErrors.Metadata.RatingValueMustBePositive, ErrorType.Validation);
AssertError(DomainErrors.Metadata.RatingValueCannotBeGreaterThanMaxValue, ErrorType.Validation);
AssertError(DomainErrors.Metadata.RatingVoteCountMustBePositive, ErrorType.Validation);
AssertError(DomainErrors.Metadata.InvalidIsoCode, ErrorType.Validation);
AssertError(DomainErrors.Metadata.GenreNameCannotBeEmpty, ErrorType.Validation);
AssertError(DomainErrors.Metadata.TagNameCannotBeEmpty, ErrorType.Validation);
AssertError(DomainErrors.Metadata.LanguageCodeCannotBeEmpty, ErrorType.Validation);
}
[Fact]
public void WrittenContent_WhenAccessed_ShouldExposeRepresentativeErrorsWithExpectedTypes()
{
// Assert
AssertError(DomainErrors.WrittenContent.BookAlreadyExists, ErrorType.Conflict);
AssertError(DomainErrors.WrittenContent.IsbnValueCannotBeEmpty, ErrorType.Validation);
AssertError(DomainErrors.WrittenContent.InvalidIsbn10Format, ErrorType.Validation);
AssertError(DomainErrors.WrittenContent.InvalidIsbn13Format, ErrorType.Validation);
AssertError(DomainErrors.WrittenContent.UnknownIsbnFormat, ErrorType.Unexpected);
AssertError(DomainErrors.WrittenContent.TheBookIsAlreadyInTheSeries, ErrorType.Forbidden);
AssertError(DomainErrors.WrittenContent.TheBookIsNotInTheSeries, ErrorType.Forbidden);
AssertError(DomainErrors.WrittenContent.BookNotFound, ErrorType.NotFound);
AssertError(DomainErrors.WrittenContent.PageCountMustBeGreaterThanZero, ErrorType.Validation);
}
[Fact]
public void MediaContributor_WhenAccessed_ShouldExposeRepresentativeErrorsWithExpectedTypes()
{
// Assert
AssertError(DomainErrors.MediaContributor.ContributorsListCannotBeNull, ErrorType.Validation);
AssertError(DomainErrors.MediaContributor.ContributorNameCannotBeEmpty, ErrorType.Validation);
AssertError(DomainErrors.MediaContributor.ContributorDisplayNameCannotBeEmpty, ErrorType.Validation);
AssertError(DomainErrors.MediaContributor.ContributorDisplayNameMustBeMaximum100CharactersLong, ErrorType.Validation);
AssertError(DomainErrors.MediaContributor.RoleNameCannotBeEmpty, ErrorType.Validation);
AssertError(DomainErrors.MediaContributor.RoleCategoryCannotBeEmpty, ErrorType.Validation);
AssertError(DomainErrors.MediaContributor.ContributorRoleCannotBeNull, ErrorType.Validation);
}
[Fact]
public void FileSystemManagement_WhenAccessed_ShouldExposeRepresentativeErrorsWithExpectedTypes()
{
// Assert
AssertError(DomainErrors.FileSystemManagement.ParentNodeCannotBeNull, ErrorType.Failure);
AssertError(DomainErrors.FileSystemManagement.InvalidPath, ErrorType.Validation);
AssertError(DomainErrors.FileSystemManagement.PathCannotBeEmpty, ErrorType.Validation);
AssertError(DomainErrors.FileSystemManagement.FileNotFound, ErrorType.NotFound);
AssertError(DomainErrors.FileSystemManagement.FileAlreadyExists, ErrorType.Conflict);
AssertError(DomainErrors.FileSystemManagement.DirectoryAlreadyExists, ErrorType.Conflict);
AssertError(DomainErrors.FileSystemManagement.NameCannotBeEmpty, ErrorType.Validation);
}
[Fact]
public void Thumbnails_WhenAccessed_ShouldExposeErrorsWithExpectedTypes()
{
// Assert
// The count assertion fails when an error is added or removed, reminding to update the assertions below.
Assert.Equal(2, typeof(DomainErrors.Thumbnails).GetProperties().Length);
AssertError(DomainErrors.Thumbnails.NoThumbnail, ErrorType.Failure);
AssertError(DomainErrors.Thumbnails.ImageQualityMustBeBetweenZeroAndOneHundred, ErrorType.Validation);
}
[Fact]
public void Permission_WhenAccessed_ShouldExposeErrorsWithExpectedTypes()
{
// Assert
// The count assertion fails when an error is added or removed, reminding to update the assertions below.
Assert.Single(typeof(DomainErrors.Permission).GetProperties());
AssertError(DomainErrors.Permission.UnauthorizedAccess, ErrorType.Failure);
}
[Fact]
public void Plugins_WhenAccessed_ShouldExposeRepresentativeErrorsWithExpectedTypes()
{
// Assert
AssertError(DomainErrors.Plugins.PluginNotFound, ErrorType.NotFound);
AssertError(DomainErrors.Plugins.PluginIdCannotBeEmpty, ErrorType.Validation);
AssertError(DomainErrors.Plugins.PluginIdsListCannotBeNull, ErrorType.Validation);
AssertError(DomainErrors.Plugins.PluginIdsListCannotBeEmpty, ErrorType.Validation);
AssertError(DomainErrors.Plugins.LibraryMetadataProviderConfigurationNotFound, ErrorType.NotFound);
}
private static void AssertError(Error error, ErrorType expectedType)
{
Assert.Equal(expectedType, error.Type);
Assert.False(string.IsNullOrWhiteSpace(error.Code));
Assert.False(string.IsNullOrWhiteSpace(error.Description));
}
}
@@ -0,0 +1,56 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Exceptions;
using Lumina.Domain.Common.Primitives;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Common.Exceptions;
/// <summary>
/// Contains unit tests for the <see cref="EventualConsistencyException"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class EventualConsistencyExceptionTests
{
[Fact]
public void Constructor_WhenCalledWithError_ShouldSetErrorAndMessage()
{
// Arrange
Error error = Error.Validation("Code", "The operation could not be completed.");
// Act
EventualConsistencyException exception = new(error);
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
Assert.Equal(error.Description, exception.Message);
Assert.Empty(exception.UnderlyingErrors);
}
[Fact]
public void Constructor_WhenCalledWithUnderlyingErrors_ShouldSetUnderlyingErrors()
{
// Arrange
Error primaryError = Error.Validation("Primary", "Primary error.");
List<Error> underlyingErrors = [Error.NotFound("Underlying1", "Underlying error 1."), Error.Conflict("Underlying2", "Underlying error 2.")];
// Act
EventualConsistencyException exception = new(primaryError, underlyingErrors);
// Assert
Assert.Equal(primaryError, exception.EventualConsistencyError);
Assert.Equal(underlyingErrors, exception.UnderlyingErrors);
}
[Fact]
public void Constructor_WhenUnderlyingErrorsAreNull_ShouldUseEmptyList()
{
// Act
EventualConsistencyException exception = new(Error.Failure("Code", "Description"), null);
// Assert
Assert.NotNull(exception.UnderlyingErrors);
Assert.Empty(exception.UnderlyingErrors);
}
}
@@ -0,0 +1,87 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Models.Core;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Common.Models.Core;
/// <summary>
/// Contains unit tests for the <see cref="AggregateRoot{TId}"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AggregateRootTests
{
[Fact]
public void GetDomainEvents_WhenNoEventsWereRaised_ShouldReturnEmptyList()
{
// Arrange
TestAggregateRoot aggregateRoot = new(Guid.NewGuid());
// Act
List<IDomainEvent> domainEvents = aggregateRoot.GetDomainEvents();
// Assert
Assert.Empty(domainEvents);
}
[Fact]
public void GetDomainEvents_WhenEventsWereRaised_ShouldReturnAllEvents()
{
// Arrange
TestAggregateRoot aggregateRoot = new(Guid.NewGuid());
aggregateRoot.RaiseTestEvent();
aggregateRoot.RaiseTestEvent();
// Act
List<IDomainEvent> domainEvents = aggregateRoot.GetDomainEvents();
// Assert
Assert.Equal(2, domainEvents.Count);
Assert.All(domainEvents, domainEvent => Assert.IsType<TestDomainEvent>(domainEvent));
}
[Fact]
public void GetDomainEvents_WhenCalled_ShouldClearTheStoredEvents()
{
// Arrange
TestAggregateRoot aggregateRoot = new(Guid.NewGuid());
aggregateRoot.RaiseTestEvent();
// Act
aggregateRoot.GetDomainEvents();
List<IDomainEvent> domainEvents = aggregateRoot.GetDomainEvents();
// Assert
Assert.Empty(domainEvents);
}
/// <summary>
/// Concrete test implementation of the abstract <see cref="AggregateRoot{TId}"/> class.
/// </summary>
private sealed class TestAggregateRoot : AggregateRoot<Guid>
{
/// <summary>
/// Initializes a new instance of the <see cref="TestAggregateRoot"/> class.
/// </summary>
/// <param name="id">The id of the aggregate root.</param>
public TestAggregateRoot(Guid id) : base(id)
{
}
/// <summary>
/// Raises a <see cref="TestDomainEvent"/> on this aggregate root.
/// </summary>
public void RaiseTestEvent()
{
_domainEvents.Add(new TestDomainEvent(Guid.NewGuid(), DateTime.UtcNow));
}
}
/// <summary>
/// Test implementation of the <see cref="IDomainEvent"/> interface.
/// </summary>
private sealed record TestDomainEvent(Guid Id, DateTime OccurredOnUtc) : IDomainEvent;
}
@@ -0,0 +1,110 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Models.Core;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Common.Models.Core;
/// <summary>
/// Contains unit tests for the <see cref="EntityId{TId}"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class EntityIdTests
{
[Fact]
public void Value_WhenConstructed_ShouldBeSet()
{
// Arrange
Guid value = Guid.NewGuid();
// Act
TestEntityId entityId = new(value);
// Assert
Assert.Equal(value, entityId.Value);
}
[Fact]
public void ToString_WhenCalled_ShouldReturnValueAsString()
{
// Arrange
Guid value = Guid.NewGuid();
TestEntityId entityId = new(value);
// Act
string? result = entityId.ToString();
// Assert
Assert.Equal(value.ToString(), result);
}
[Fact]
public void Equals_WithSameValue_ShouldReturnTrue()
{
// Arrange
Guid value = Guid.NewGuid();
TestEntityId firstId = new(value);
TestEntityId secondId = new(value);
// Act
bool result = firstId.Equals(secondId);
// Assert
Assert.True(result);
}
[Fact]
public void Equals_WithDifferentValue_ShouldReturnFalse()
{
// Arrange
TestEntityId firstId = new(Guid.NewGuid());
TestEntityId secondId = new(Guid.NewGuid());
// Act
bool result = firstId.Equals(secondId);
// Assert
Assert.False(result);
}
[Fact]
public void GetHashCode_WithSameValue_ShouldReturnSameHashCode()
{
// Arrange
Guid value = Guid.NewGuid();
TestEntityId firstId = new(value);
TestEntityId secondId = new(value);
// Act
int firstHashCode = firstId.GetHashCode();
int secondHashCode = secondId.GetHashCode();
// Assert
Assert.Equal(firstHashCode, secondHashCode);
}
/// <summary>
/// Concrete test implementation of the abstract <see cref="EntityId{TId}"/> class.
/// </summary>
private sealed class TestEntityId : EntityId<Guid>
{
/// <summary>
/// Initializes a new instance of the <see cref="TestEntityId"/> class.
/// </summary>
/// <param name="value">The value representing this object.</param>
public TestEntityId(Guid value) : base(value)
{
}
/// <summary>
/// Gets the list of items that define equality of the object.
/// </summary>
/// <returns>A list of items defining the equality.</returns>
public override IEnumerable<object> GetEqualityComponents()
{
yield return Value;
}
}
}
@@ -0,0 +1,132 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Models.Core;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Common.Models.Core;
/// <summary>
/// Contains unit tests for the <see cref="Entity{TId}"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class EntityTests
{
[Fact]
public void Id_WhenConstructed_ShouldBeSet()
{
// Arrange
Guid id = Guid.NewGuid();
// Act
TestEntity entity = new(id);
// Assert
Assert.Equal(id, entity.Id);
}
[Fact]
public void Equals_WithSameId_ShouldReturnTrue()
{
// Arrange
Guid id = Guid.NewGuid();
TestEntity firstEntity = new(id);
TestEntity secondEntity = new(id);
// Act
bool result = firstEntity.Equals(secondEntity);
// Assert
Assert.True(result);
}
[Fact]
public void Equals_WithDifferentId_ShouldReturnFalse()
{
// Arrange
TestEntity firstEntity = new(Guid.NewGuid());
TestEntity secondEntity = new(Guid.NewGuid());
// Act
bool result = firstEntity.Equals(secondEntity);
// Assert
Assert.False(result);
}
[Fact]
public void EqualityOperator_WithSameId_ShouldReturnTrue()
{
// Arrange
Guid id = Guid.NewGuid();
TestEntity firstEntity = new(id);
TestEntity secondEntity = new(id);
// Act
bool result = firstEntity == secondEntity;
// Assert
Assert.True(result);
}
[Fact]
public void InequalityOperator_WithDifferentId_ShouldReturnTrue()
{
// Arrange
TestEntity firstEntity = new(Guid.NewGuid());
TestEntity secondEntity = new(Guid.NewGuid());
// Act
bool result = firstEntity != secondEntity;
// Assert
Assert.True(result);
}
[Fact]
public void GetHashCode_WithSameId_ShouldReturnSameHashCode()
{
// Arrange
Guid id = Guid.NewGuid();
TestEntity firstEntity = new(id);
TestEntity secondEntity = new(id);
// Act
int firstHashCode = firstEntity.GetHashCode();
int secondHashCode = secondEntity.GetHashCode();
// Assert
Assert.Equal(firstHashCode, secondHashCode);
}
[Fact]
public void CreatedOnUtc_And_UpdatedOnUtc_WhenSet_ShouldBeStored()
{
// Arrange
TestEntity entity = new(Guid.NewGuid());
DateTime createdOnUtc = new(2024, 1, 1, 12, 0, 0, DateTimeKind.Utc);
DateTime updatedOnUtc = new(2024, 1, 2, 12, 0, 0, DateTimeKind.Utc);
// Act
entity.CreatedOnUtc = createdOnUtc;
entity.UpdatedOnUtc = updatedOnUtc;
// Assert
Assert.Equal(createdOnUtc, entity.CreatedOnUtc);
Assert.Equal(updatedOnUtc, entity.UpdatedOnUtc);
}
/// <summary>
/// Concrete test implementation of the abstract <see cref="Entity{TId}"/> class.
/// </summary>
private sealed class TestEntity : Entity<Guid>
{
/// <summary>
/// Initializes a new instance of the <see cref="TestEntity"/> class.
/// </summary>
/// <param name="id">The id of the entity.</param>
public TestEntity(Guid id) : base(id)
{
}
}
}
@@ -0,0 +1,164 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Models.Core;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Common.Models.Core;
/// <summary>
/// Contains unit tests for the <see cref="ValueObject"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ValueObjectTests
{
[Fact]
public void Equals_WithSameComponents_ShouldReturnTrue()
{
// Arrange
TestValueObject firstValueObject = new("value");
TestValueObject secondValueObject = new("value");
// Act
bool result = firstValueObject.Equals(secondValueObject);
// Assert
Assert.True(result);
}
[Fact]
public void Equals_WithDifferentComponents_ShouldReturnFalse()
{
// Arrange
TestValueObject firstValueObject = new("first");
TestValueObject secondValueObject = new("second");
// Act
bool result = firstValueObject.Equals(secondValueObject);
// Assert
Assert.False(result);
}
[Fact]
public void Equals_WithDifferentType_ShouldReturnFalse()
{
// Arrange
TestValueObject valueObject = new("value");
OtherTestValueObject otherValueObject = new("value");
// Act
bool result = valueObject.Equals(otherValueObject);
// Assert
Assert.False(result);
}
[Fact]
public void Equals_WithNull_ShouldReturnFalse()
{
// Arrange
TestValueObject valueObject = new("value");
// Act
bool result = valueObject.Equals(null);
// Assert
Assert.False(result);
}
[Fact]
public void EqualityOperator_WithSameComponents_ShouldReturnTrue()
{
// Arrange
TestValueObject firstValueObject = new("value");
TestValueObject secondValueObject = new("value");
// Act
bool result = firstValueObject == secondValueObject;
// Assert
Assert.True(result);
}
[Fact]
public void InequalityOperator_WithDifferentComponents_ShouldReturnTrue()
{
// Arrange
TestValueObject firstValueObject = new("first");
TestValueObject secondValueObject = new("second");
// Act
bool result = firstValueObject != secondValueObject;
// Assert
Assert.True(result);
}
[Fact]
public void GetHashCode_WithSameComponents_ShouldReturnSameHashCode()
{
// Arrange
TestValueObject firstValueObject = new("value");
TestValueObject secondValueObject = new("value");
// Act
int firstHashCode = firstValueObject.GetHashCode();
int secondHashCode = secondValueObject.GetHashCode();
// Assert
Assert.Equal(firstHashCode, secondHashCode);
}
/// <summary>
/// Concrete test implementation of the abstract <see cref="ValueObject"/> class.
/// </summary>
private sealed class TestValueObject : ValueObject
{
private readonly string _value;
/// <summary>
/// Initializes a new instance of the <see cref="TestValueObject"/> class.
/// </summary>
/// <param name="value">The value of the value object.</param>
public TestValueObject(string value)
{
_value = value;
}
/// <summary>
/// Gets the list of items that define equality of the object.
/// </summary>
/// <returns>A list of items defining the equality.</returns>
public override IEnumerable<object?> GetEqualityComponents()
{
yield return _value;
}
}
/// <summary>
/// Concrete test implementation of the abstract <see cref="ValueObject"/> class, with a different type.
/// </summary>
private sealed class OtherTestValueObject : ValueObject
{
private readonly string _value;
/// <summary>
/// Initializes a new instance of the <see cref="OtherTestValueObject"/> class.
/// </summary>
/// <param name="value">The value of the value object.</param>
public OtherTestValueObject(string value)
{
_value = value;
}
/// <summary>
/// Gets the list of items that define equality of the object.
/// </summary>
/// <returns>A list of items defining the equality.</returns>
public override IEnumerable<object?> GetEqualityComponents()
{
yield return _value;
}
}
}
@@ -0,0 +1,197 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Primitives;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Common.Primitives;
/// <summary>
/// Contains unit tests for the <see cref="Error"/> class and its derived error records.
/// </summary>
[ExcludeFromCodeCoverage]
public class ErrorTests
{
[Fact]
public void NotFound_WhenCalledWithoutArguments_ShouldUseDefaultCodeAndDescription()
{
// Act
Error error = Error.NotFound();
// Assert
AssertError(error, ErrorType.NotFound, "General.NotFound", "A 'Not Found' error has occurred.");
}
[Fact]
public void NotFound_WhenCalledWithCodeAndDescription_ShouldUseProvidedValues()
{
// Act
Error error = Error.NotFound("Library.NotFound", "The library was not found.");
// Assert
AssertError(error, ErrorType.NotFound, "Library.NotFound", "The library was not found.");
}
[Fact]
public void InvalidOperation_WhenCalledWithoutArguments_ShouldUseDefaultCodeAndDescription()
{
// Act
Error error = Error.InvalidOperation();
// Assert
AssertError(error, ErrorType.Unexpected, "General.InvalidOperation", "An invalid operation error has occurred.");
}
[Fact]
public void Forbidden_WhenCalledWithoutArguments_ShouldUseDefaultCodeAndDescription()
{
// Act
Error error = Error.Forbidden();
// Assert
AssertError(error, ErrorType.Forbidden, "General.Forbidden", "A 'Forbidden' error has occurred.");
}
[Fact]
public void Failure_WhenCalledWithoutArguments_ShouldUseDefaultCodeAndDescription()
{
// Act
Error error = Error.Failure();
// Assert
AssertError(error, ErrorType.Failure, "General.Failure", "A failure has occurred.");
}
[Fact]
public void Validation_WhenCalledWithoutArguments_ShouldUseDefaultCodeAndDescription()
{
// Act
Error error = Error.Validation();
// Assert
AssertError(error, ErrorType.Validation, "General.Validation", "A validation error has occurred.");
}
[Fact]
public void Validation_WhenCalledWithCodeAndDescription_ShouldUseProvidedValues()
{
// Act
Error error = Error.Validation("Title.CannotBeEmpty", "The title cannot be empty.");
// Assert
AssertError(error, ErrorType.Validation, "Title.CannotBeEmpty", "The title cannot be empty.");
}
[Fact]
public void Conflict_WhenCalledWithoutArguments_ShouldUseDefaultCodeAndDescription()
{
// Act
Error error = Error.Conflict();
// Assert
AssertError(error, ErrorType.Conflict, "General.Conflict", "A conflict error has occurred.");
}
[Fact]
public void Timeout_WhenCalledWithoutArguments_ShouldUseDefaultCodeAndDescription()
{
// Act
Error error = Error.Timeout();
// Assert
AssertError(error, ErrorType.Unexpected, "General.Timeout", "The operation timed out.");
}
[Fact]
public void Unauthorized_WhenCalledWithoutArguments_ShouldUseDefaultCodeAndDescription()
{
// Act
Error error = Error.Unauthorized();
// Assert
AssertError(error, ErrorType.Unauthorized, "General.Unauthorized", "An 'Unauthorized' error has occurred.");
}
[Fact]
public void Unexpected_WhenCalledWithoutArguments_ShouldUseDefaultCodeAndDescription()
{
// Act
Error error = Error.Unexpected();
// Assert
AssertError(error, ErrorType.Unexpected, "General.Unexpected", "An unexpected error has occurred.");
}
[Fact]
public void Internal_WhenCalledWithoutArguments_ShouldUseDefaultCodeAndDescription()
{
// Act
Error error = Error.Internal();
// Assert
AssertError(error, ErrorType.Unexpected, "General.Internal", "An internal error has occurred.");
}
[Fact]
public void ResourceUnavailable_WhenCalledWithoutArguments_ShouldUseDefaultCodeAndDescription()
{
// Act
Error error = Error.ResourceUnavailable();
// Assert
AssertError(error, ErrorType.Unexpected, "General.ResourceUnavailable", "The required resource is currently unavailable.");
}
[Fact]
public void NotImplemented_WhenCalledWithoutArguments_ShouldUseDefaultCodeAndDescription()
{
// Act
Error error = Error.NotImplemented();
// Assert
AssertError(error, ErrorType.Unexpected, "General.NotImplemented", "The requested functionality is not implemented.");
}
[Fact]
public void ToString_WhenCalled_ShouldReturnRecordRepresentation()
{
// Arrange
Error error = Error.NotFound("Library.NotFound", "The library was not found.");
// Act
string result = error.ToString();
// Assert
Assert.Equal("NotFoundError { Type = NotFound, Code = Library.NotFound, Description = The library was not found. }", result);
}
[Fact]
public void Equals_WhenSameCodeAndDescription_ShouldReturnTrue()
{
// Act
Error firstError = Error.Validation("Code", "Description");
Error secondError = Error.Validation("Code", "Description");
// Assert
Assert.Equal(firstError, secondError);
Assert.Equal(firstError.GetHashCode(), secondError.GetHashCode());
}
[Fact]
public void Equals_WhenDifferentCode_ShouldReturnFalse()
{
// Act
Error firstError = Error.Validation("Code1", "Description");
Error secondError = Error.Validation("Code2", "Description");
// Assert
Assert.NotEqual(firstError, secondError);
}
private static void AssertError(Error error, ErrorType expectedType, string expectedCode, string expectedDescription)
{
Assert.Equal(expectedType, error.Type);
Assert.Equal(expectedCode, error.Code);
Assert.Equal(expectedDescription, error.Description);
}
}
@@ -0,0 +1,377 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Domain.UnitTests.Common.Primitives;
/// <summary>
/// Contains unit tests for the <see cref="Result{TValue}"/> structure.
/// </summary>
[ExcludeFromCodeCoverage]
public class ResultTests
{
[Fact]
public void Success_WhenCalledWithValue_ShouldCreateSuccessfulResult()
{
// Act
Result<string> result = Result<string>.Success("test");
// Assert
Assert.True(result.IsSuccess);
Assert.False(result.IsFailure);
Assert.Equal("test", result.Value);
}
[Fact]
public void Failure_WhenCalledWithSingleError_ShouldCreateFailedResult()
{
// Arrange
Error error = Error.Validation("Code", "Description");
// Act
Result<string> result = Result<string>.Failure(error);
// Assert
Assert.False(result.IsSuccess);
Assert.True(result.IsFailure);
Assert.Single(result.Errors);
Assert.Equal(error, result.FirstError);
}
[Fact]
public void Failure_WhenCalledWithMultipleErrors_ShouldCreateFailedResultWithAllErrors()
{
// Arrange
Error firstError = Error.Validation("Code1", "Description1");
Error secondError = Error.NotFound("Code2", "Description2");
// Act
Result<string> result = Result<string>.Failure(new List<Error>([firstError, secondError]));
// Assert
Assert.True(result.IsFailure);
Assert.Equal(2, result.Errors.Count);
Assert.Equal(firstError, result.Errors[0]);
Assert.Equal(secondError, result.Errors[1]);
Assert.Equal(firstError, result.FirstError);
}
[Fact]
public void ImplicitConversion_WhenConvertingValue_ShouldCreateSuccessfulResult()
{
// Act
Result<string> result = "test";
// Assert
Assert.True(result.IsSuccess);
Assert.Equal("test", result.Value);
}
[Fact]
public void ImplicitConversion_WhenConvertingError_ShouldCreateFailedResult()
{
// Arrange
Error error = Error.Conflict("Code", "Description");
// Act
Result<string> result = error;
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
}
[Fact]
public void ImplicitConversion_WhenConvertingErrorList_ShouldCreateFailedResult()
{
// Arrange
List<Error> errors = [Error.Validation("Code", "Description")];
// Act
Result<string> result = errors;
// Assert
Assert.True(result.IsFailure);
Assert.Equal(errors, result.Errors);
}
[Fact]
public void Map_WhenResultIsSuccessful_ShouldMapValue()
{
// Arrange
Result<int> result = Result<int>.Success(5);
// Act
Result<string> mappedResult = result.Map(value => value.ToString());
// Assert
Assert.True(mappedResult.IsSuccess);
Assert.Equal("5", mappedResult.Value);
}
[Fact]
public void Map_WhenResultIsFailed_ShouldPreserveErrors()
{
// Arrange
Error error = Error.Validation("Code", "Description");
Result<int> result = Result<int>.Failure(error);
// Act
Result<string> mappedResult = result.Map(value => value.ToString());
// Assert
Assert.True(mappedResult.IsFailure);
Assert.Equal(error, mappedResult.FirstError);
}
[Fact]
public void Bind_WhenResultIsSuccessful_ShouldReturnBinderResult()
{
// Arrange
Result<int> result = Result<int>.Success(5);
// Act
Result<string> boundResult = result.Bind(value => Result<string>.Success(value.ToString()));
// Assert
Assert.True(boundResult.IsSuccess);
Assert.Equal("5", boundResult.Value);
}
[Fact]
public void Bind_WhenResultIsFailed_ShouldPreserveErrors()
{
// Arrange
Error error = Error.Validation("Code", "Description");
Result<int> result = Result<int>.Failure(error);
// Act
Result<string> boundResult = result.Bind(value => Result<string>.Success(value.ToString()));
// Assert
Assert.True(boundResult.IsFailure);
Assert.Equal(error, boundResult.FirstError);
}
[Fact]
public void OnSuccess_WhenResultIsSuccessful_ShouldExecuteAction()
{
// Arrange
Result<int> result = Result<int>.Success(5);
bool actionExecuted = false;
// Act
result.OnSuccess(value => actionExecuted = true);
// Assert
Assert.True(actionExecuted);
}
[Fact]
public void OnSuccess_WhenResultIsFailed_ShouldNotExecuteAction()
{
// Arrange
Result<int> result = Result<int>.Failure(Error.Validation("Code", "Description"));
bool actionExecuted = false;
// Act
result.OnSuccess(value => actionExecuted = true);
// Assert
Assert.False(actionExecuted);
}
[Fact]
public void OnFailure_WhenResultIsFailed_ShouldExecuteAction()
{
// Arrange
Error error = Error.Validation("Code", "Description");
Result<int> result = Result<int>.Failure(error);
List<Error>? receivedErrors = null;
// Act
result.OnFailure(errors => receivedErrors = [.. errors]);
// Assert
Assert.NotNull(receivedErrors);
Assert.Single(receivedErrors);
Assert.Equal(error, receivedErrors[0]);
}
[Fact]
public void OnFailure_WhenResultIsSuccessful_ShouldNotExecuteAction()
{
// Arrange
Result<int> result = Result<int>.Success(5);
bool actionExecuted = false;
// Act
result.OnFailure(errors => actionExecuted = true);
// Assert
Assert.False(actionExecuted);
}
[Fact]
public void Match_WhenResultIsSuccessful_ShouldExecuteOnSuccessFunction()
{
// Arrange
Result<int> result = Result<int>.Success(5);
// Act
string matchedResult = result.Match(value => $"Success: {value}", errors => "Failure");
// Assert
Assert.Equal("Success: 5", matchedResult);
}
[Fact]
public void Match_WhenResultIsFailed_ShouldExecuteOnFailureFunction()
{
// Arrange
Result<int> result = Result<int>.Failure(Error.Validation("Code", "Description"));
// Act
string matchedResult = result.Match(value => "Success", errors => $"Failure: {errors.Count}");
// Assert
Assert.Equal("Failure: 1", matchedResult);
}
[Fact]
public void Value_WhenResultIsFailed_ShouldThrowInvalidOperationException()
{
// Arrange
Result<string> result = Result<string>.Failure(Error.Validation("Code", "Description"));
// Act & Assert
Assert.Throws<InvalidOperationException>(() => result.Value);
}
[Fact]
public void Errors_WhenResultIsSuccessful_ShouldThrowInvalidOperationException()
{
// Arrange
Result<string> result = Result<string>.Success("test");
// Act & Assert
Assert.Throws<InvalidOperationException>(() => result.Errors);
}
[Fact]
public void Equals_WhenBothResultsAreSuccessfulWithSameValue_ShouldReturnTrue()
{
// Act
Result<string> firstResult = Result<string>.Success("test");
Result<string> secondResult = Result<string>.Success("test");
// Assert
Assert.True(firstResult.Equals(secondResult));
}
[Fact]
public void Equals_WhenResultsHaveDifferentSuccessValues_ShouldReturnFalse()
{
// Act
Result<string> firstResult = Result<string>.Success("first");
Result<string> secondResult = Result<string>.Success("second");
// Assert
Assert.False(firstResult.Equals(secondResult));
}
[Fact]
public void Equals_WhenBothResultsAreFailedWithSameErrors_ShouldReturnTrue()
{
// Act
Result<string> firstResult = Result<string>.Failure(Error.Validation("Code", "Description"));
Result<string> secondResult = Result<string>.Failure(Error.Validation("Code", "Description"));
// Assert
Assert.True(firstResult.Equals(secondResult));
}
[Fact]
public void EqualityOperator_WhenResultsAreEqual_ShouldReturnTrue()
{
// Act
Result<int> firstResult = Result<int>.Success(5);
Result<int> secondResult = Result<int>.Success(5);
// Assert
Assert.True(firstResult == secondResult);
}
[Fact]
public void InequalityOperator_WhenResultsAreNotEqual_ShouldReturnTrue()
{
// Act
Result<int> firstResult = Result<int>.Success(5);
Result<int> secondResult = Result<int>.Success(6);
// Assert
Assert.True(firstResult != secondResult);
}
[Fact]
public void GetHashCode_WhenResultsAreEqual_ShouldReturnSameHashCode()
{
// Act
Result<int> firstResult = Result<int>.Success(5);
Result<int> secondResult = Result<int>.Success(5);
// Assert
Assert.Equal(firstResult.GetHashCode(), secondResult.GetHashCode());
}
[Fact]
public void ToString_WhenResultIsSuccessful_ShouldReturnSuccessString()
{
// Arrange
Result<string> result = Result<string>.Success("test");
// Act
string resultString = result.ToString();
// Assert
Assert.Equal("Success: test", resultString);
}
[Fact]
public void ToString_WhenResultIsFailed_ShouldReturnFailureString()
{
// Arrange
Result<string> result = Result<string>.Failure(Error.Validation("Code", "Description"));
// Act
string resultString = result.ToString();
// Assert
Assert.Equal("Failure: [ValidationError { Type = Validation, Code = Code, Description = Description }]", resultString);
}
[Fact]
public void From_WhenCalledWithValue_ShouldCreateSuccessfulResult()
{
// Act
Result<int> result = Result.From(5);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal(5, result.Value);
}
[Fact]
public void Marker_WhenAccessed_ShouldExposePredefinedSuccessResults()
{
// Act & Assert
Assert.Equal(new Success(), Result.Success);
Assert.Equal(new Created(), Result.Created);
Assert.Equal(new Updated(), Result.Updated);
Assert.Equal(new Deleted(), Result.Deleted);
}
}
@@ -0,0 +1,137 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Common.ValueObjects.Metadata;
using Lumina.Domain.Fixtures.Common.ValueObjects.Metadata;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Common.ValueObjects.Metadata;
/// <summary>
/// Contains unit tests for the <see cref="BaseMetadata"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class BaseMetadataTests
{
private readonly GenreFixture _genreFixture = new();
private readonly TagFixture _tagFixture = new();
private readonly ReleaseInfoFixture _releaseInfoFixture = new();
private readonly LanguageInfoFixture _languageInfoFixture = new();
[Fact]
public void Constructor_WhenCalledWithValidData_ShouldSetAllProperties()
{
// Arrange
ReleaseInfo releaseInfo = _releaseInfoFixture.Create();
List<Genre> genres = [_genreFixture.Create(name: "Science Fiction")];
List<Tag> tags = [_tagFixture.Create(name: "bestseller")];
Optional<LanguageInfo> language = Optional<LanguageInfo>.Some(_languageInfoFixture.Create());
// Act
TestMetadata metadata = new(
"Dune",
Optional<string>.Some("Dune (Original)"),
Optional<string>.Some("A classic novel."),
releaseInfo,
genres,
tags,
language,
Optional<LanguageInfo>.None());
// Assert
Assert.Equal("Dune", metadata.Title);
Assert.Equal("Dune (Original)", metadata.OriginalTitle.Value);
Assert.Equal("A classic novel.", metadata.Description.Value);
Assert.Equal(releaseInfo, metadata.ReleaseInfo);
Assert.Single(metadata.Genres);
Assert.Single(metadata.Tags);
Assert.True(metadata.Language.HasValue);
Assert.False(metadata.OriginalLanguage.HasValue);
}
[Fact]
public void Constructor_WhenTitleIsNull_ShouldThrowArgumentNullException()
{
// Act & Assert
Assert.Throws<ArgumentNullException>(() => new TestMetadata(
null!,
Optional<string>.None(),
Optional<string>.None(),
_releaseInfoFixture.Create(),
[],
[],
Optional<LanguageInfo>.None(),
Optional<LanguageInfo>.None()));
}
[Fact]
public void Equals_WithSameData_ShouldReturnTrue()
{
// Arrange
ReleaseInfo releaseInfo = _releaseInfoFixture.Create();
List<Genre> genres = [_genreFixture.Create(name: "Science Fiction")];
List<Tag> tags = [_tagFixture.Create(name: "bestseller")];
// Act
TestMetadata firstMetadata = new("Dune", Optional<string>.None(), Optional<string>.None(), releaseInfo, genres, tags, Optional<LanguageInfo>.None(), Optional<LanguageInfo>.None());
TestMetadata secondMetadata = new("Dune", Optional<string>.None(), Optional<string>.None(), releaseInfo, genres, tags, Optional<LanguageInfo>.None(), Optional<LanguageInfo>.None());
// Assert
Assert.Equal(firstMetadata, secondMetadata);
}
[Fact]
public void Equals_WithDifferentTitle_ShouldReturnFalse()
{
// Arrange
ReleaseInfo releaseInfo = _releaseInfoFixture.Create();
// Act
TestMetadata firstMetadata = new("Dune", Optional<string>.None(), Optional<string>.None(), releaseInfo, [], [], Optional<LanguageInfo>.None(), Optional<LanguageInfo>.None());
TestMetadata secondMetadata = new("Foundation", Optional<string>.None(), Optional<string>.None(), releaseInfo, [], [], Optional<LanguageInfo>.None(), Optional<LanguageInfo>.None());
// Assert
Assert.NotEqual(firstMetadata, secondMetadata);
}
/// <summary>
/// Concrete test implementation of the abstract <see cref="BaseMetadata"/> class.
/// </summary>
private sealed class TestMetadata : BaseMetadata
{
/// <summary>
/// Initializes a new instance of the <see cref="TestMetadata"/> class.
/// </summary>
/// <param name="title">The title of the media item.</param>
/// <param name="originalTitle">The optional original title.</param>
/// <param name="description">The optional description.</param>
/// <param name="releaseInfo">The release information.</param>
/// <param name="genres">The genres.</param>
/// <param name="tags">The tags.</param>
/// <param name="language">The optional language.</param>
/// <param name="originalLanguage">The optional original language.</param>
public TestMetadata(
string title,
Optional<string> originalTitle,
Optional<string> description,
ReleaseInfo releaseInfo,
List<Genre> genres,
List<Tag> tags,
Optional<LanguageInfo> language,
Optional<LanguageInfo> originalLanguage)
: base(title, originalTitle, description, releaseInfo, genres, tags, language, originalLanguage)
{
}
/// <summary>
/// Gets the list of items that define equality of the object.
/// </summary>
/// <returns>A list of items defining the equality.</returns>
public override IEnumerable<object> GetEqualityComponents()
{
return base.GetEqualityComponents();
}
}
}
@@ -0,0 +1,84 @@
#region ========================================================================= USING =====================================================================================
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Common.ValueObjects.Metadata;
using Lumina.Domain.Fixtures.Common.ValueObjects.Metadata;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Common.ValueObjects.Metadata;
/// <summary>
/// Contains unit tests for the <see cref="Genre"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GenreTests
{
private readonly GenreFixture _genreFixture = new();
[Fact]
public void Create_WhenCalledWithValidName_ShouldCreateGenreWithTrimmedName()
{
// Act
Result<Genre> result = Genre.Create(" Science Fiction ");
// Assert
Assert.False(result.IsFailure);
Assert.Equal("Science Fiction", result.Value.Name);
}
[Theory]
[InlineData(null)] // null name
[InlineData("")] // empty name
[InlineData(" ")] // whitespace name
public void Create_WhenNameIsNullOrWhitespace_ShouldReturnError(string? name)
{
// Act
Result<Genre> result = Genre.Create(name);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Metadata.GenreNameCannotBeEmpty, result.FirstError);
}
[Fact]
public void Equals_WithSameName_ShouldReturnTrue()
{
// Arrange
Genre firstGenre = _genreFixture.Create(name: "Science Fiction");
Genre secondGenre = _genreFixture.Create(name: "Science Fiction");
// Act
bool result = firstGenre.Equals(secondGenre);
// Assert
Assert.True(result);
}
[Fact]
public void Equals_WithDifferentName_ShouldReturnFalse()
{
// Arrange
Genre firstGenre = _genreFixture.Create(name: "Science Fiction");
Genre secondGenre = _genreFixture.Create(name: "Fantasy");
// Act
bool result = firstGenre.Equals(secondGenre);
// Assert
Assert.False(result);
}
[Fact]
public void ToString_WhenCalled_ShouldReturnName()
{
// Arrange
Genre genre = _genreFixture.Create(name: "Science Fiction");
// Act
string result = genre.ToString();
// Assert
Assert.Equal("Science Fiction", result);
}
}
@@ -0,0 +1,90 @@
#region ========================================================================= USING =====================================================================================
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Common.ValueObjects.Metadata;
using Lumina.Domain.Fixtures.Common.ValueObjects.Metadata;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Common.ValueObjects.Metadata;
/// <summary>
/// Contains unit tests for the <see cref="LanguageInfo"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LanguageInfoTests
{
private readonly LanguageInfoFixture _languageInfoFixture = new();
[Fact]
public void Create_WhenCalledWithValidValues_ShouldCreateLanguageInfoWithLowercaseCode()
{
// Act
Result<LanguageInfo> result = LanguageInfo.Create("EN", "English", Optional<string>.Some("English"));
// Assert
Assert.False(result.IsFailure);
Assert.Equal("en", result.Value.LanguageCode);
Assert.Equal("English", result.Value.LanguageName);
Assert.True(result.Value.NativeName.HasValue);
Assert.Equal("English", result.Value.NativeName.Value);
}
[Theory]
[InlineData(null)] // null language code
[InlineData("")] // empty language code
[InlineData(" ")] // whitespace language code
public void Create_WhenLanguageCodeIsNullOrWhitespace_ShouldReturnError(string? languageCode)
{
// Act
Result<LanguageInfo> result = LanguageInfo.Create(languageCode, "English", Optional<string>.None());
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Metadata.LanguageCodeCannotBeEmpty, result.FirstError);
}
[Theory]
[InlineData(null)] // null language name
[InlineData("")] // empty language name
[InlineData(" ")] // whitespace language name
public void Create_WhenLanguageNameIsNullOrWhitespace_ShouldReturnError(string? languageName)
{
// Act
Result<LanguageInfo> result = LanguageInfo.Create("en", languageName, Optional<string>.None());
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Metadata.LanguageNameCannotBeEmpty, result.FirstError);
}
[Theory]
[InlineData("e")] // single character code
[InlineData("eng")] // three character code
[InlineData("english")] // long code
public void Create_WhenLanguageCodeIsNotTwoCharactersLong_ShouldReturnError(string languageCode)
{
// Act
Result<LanguageInfo> result = LanguageInfo.Create(languageCode, "English", Optional<string>.None());
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Metadata.InvalidIsoCode, result.FirstError);
}
[Fact]
public void ToString_WhenCalled_ShouldReturnFormattedString()
{
// Arrange
LanguageInfo languageInfo = _languageInfoFixture.Create(
languageCode: "en",
languageName: "English",
nativeName: Optional<string>.None());
// Act
string result = languageInfo.ToString();
// Assert
Assert.Equal("en - English", result);
}
}
@@ -0,0 +1,81 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Common.ValueObjects.Metadata;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Common.ValueObjects.Metadata;
/// <summary>
/// Contains unit tests for the <see cref="Rating"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RatingTests
{
[Fact]
public void Constructor_WhenCalled_ShouldSetValueMaxValueAndVoteCount()
{
// Act
TestRating rating = new(value: 4.5m, maxValue: 5, voteCount: Optional<int>.Some(100));
// Assert
Assert.Equal(4.5m, rating.Value);
Assert.Equal(5, rating.MaxValue);
Assert.True(rating.VoteCount.HasValue);
Assert.Equal(100, rating.VoteCount.Value);
}
[Fact]
public void AsPercentage_WhenCalled_ShouldReturnValueAsPercentageOfMaxValue()
{
// Arrange
TestRating rating = new(value: 4.5m, maxValue: 5, voteCount: Optional<int>.None());
// Act
decimal result = rating.AsPercentage();
// Assert
Assert.Equal(90, result);
}
[Fact]
public void AsPercentage_WhenValueEqualsMaxValue_ShouldReturnOneHundred()
{
// Arrange
TestRating rating = new(value: 5, maxValue: 5, voteCount: Optional<int>.None());
// Act
decimal result = rating.AsPercentage();
// Assert
Assert.Equal(100, result);
}
/// <summary>
/// Concrete test implementation of the abstract <see cref="Rating"/> class.
/// </summary>
private sealed class TestRating : Rating
{
/// <summary>
/// Initializes a new instance of the <see cref="TestRating"/> class.
/// </summary>
/// <param name="value">The numeric value of the rating.</param>
/// <param name="maxValue">The maximum possible rating value.</param>
/// <param name="voteCount">The optional number of votes or reviews.</param>
public TestRating(decimal value, decimal maxValue, Optional<int> voteCount) : base(value, maxValue, voteCount)
{
}
/// <summary>
/// Gets the list of items that define equality of the object.
/// </summary>
/// <returns>A list of items defining the equality.</returns>
public override IEnumerable<object> GetEqualityComponents()
{
yield return Value;
yield return MaxValue;
yield return VoteCount;
}
}
}
@@ -0,0 +1,124 @@
#region ========================================================================= USING =====================================================================================
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Common.ValueObjects.Metadata;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Common.ValueObjects.Metadata;
/// <summary>
/// Contains unit tests for the <see cref="ReleaseInfo"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReleaseInfoTests
{
[Fact]
public void Create_WhenCalledWithValidValues_ShouldCreateReleaseInfo()
{
// Act
Result<ReleaseInfo> result = ReleaseInfo.Create(
Optional<DateOnly>.Some(new DateOnly(2001, 9, 14)),
Optional<int>.Some(2001),
Optional<DateOnly>.Some(new DateOnly(2010, 6, 1)),
Optional<int>.Some(2010),
Optional<string>.Some("US"),
Optional<string>.Some("Director's Cut"));
// Assert
Assert.False(result.IsFailure);
Assert.Equal(new DateOnly(2001, 9, 14), result.Value.OriginalReleaseDate.Value);
Assert.Equal(2001, result.Value.OriginalReleaseYear.Value);
Assert.Equal(new DateOnly(2010, 6, 1), result.Value.ReReleaseDate.Value);
Assert.Equal(2010, result.Value.ReReleaseYear.Value);
Assert.Equal("US", result.Value.ReleaseCountry.Value);
Assert.Equal("Director's Cut", result.Value.ReleaseVersion.Value);
}
[Fact]
public void Create_WhenOnlyOriginalReleaseYearProvided_ShouldCreateReleaseInfo()
{
// Act
Result<ReleaseInfo> result = ReleaseInfo.Create(
Optional<DateOnly>.None(),
Optional<int>.Some(2001),
Optional<DateOnly>.None(),
Optional<int>.None(),
Optional<string>.None(),
Optional<string>.None());
// Assert
Assert.False(result.IsFailure);
Assert.Equal(2001, result.Value.OriginalReleaseYear.Value);
Assert.False(result.Value.OriginalReleaseDate.HasValue);
}
[Fact]
public void Create_WhenOriginalReleaseDateAndYearMismatch_ShouldReturnError()
{
// Act
Result<ReleaseInfo> result = ReleaseInfo.Create(
Optional<DateOnly>.Some(new DateOnly(2001, 9, 14)),
Optional<int>.Some(2002),
Optional<DateOnly>.None(),
Optional<int>.None(),
Optional<string>.None(),
Optional<string>.None());
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Metadata.OriginalReleaseDateAndYearMustMatch, result.FirstError);
}
[Fact]
public void Create_WhenReReleaseDateAndYearMismatch_ShouldReturnError()
{
// Act
Result<ReleaseInfo> result = ReleaseInfo.Create(
Optional<DateOnly>.None(),
Optional<int>.None(),
Optional<DateOnly>.Some(new DateOnly(2010, 6, 1)),
Optional<int>.Some(2011),
Optional<string>.None(),
Optional<string>.None());
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Metadata.ReReleaseDateAndYearMustMatch, result.FirstError);
}
[Fact]
public void Create_WhenReReleaseDateIsEarlierThanOriginalReleaseDate_ShouldReturnError()
{
// Act
Result<ReleaseInfo> result = ReleaseInfo.Create(
Optional<DateOnly>.Some(new DateOnly(2010, 6, 1)),
Optional<int>.Some(2010),
Optional<DateOnly>.Some(new DateOnly(2001, 9, 14)),
Optional<int>.Some(2001),
Optional<string>.None(),
Optional<string>.None());
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate, result.FirstError);
}
[Fact]
public void Create_WhenReReleaseYearIsEarlierThanOriginalReleaseYear_ShouldReturnError()
{
// Act
Result<ReleaseInfo> result = ReleaseInfo.Create(
Optional<DateOnly>.None(),
Optional<int>.Some(2010),
Optional<DateOnly>.None(),
Optional<int>.Some(2001),
Optional<string>.None(),
Optional<string>.None());
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear, result.FirstError);
}
}
@@ -0,0 +1,84 @@
#region ========================================================================= USING =====================================================================================
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Common.ValueObjects.Metadata;
using Lumina.Domain.Fixtures.Common.ValueObjects.Metadata;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Common.ValueObjects.Metadata;
/// <summary>
/// Contains unit tests for the <see cref="Tag"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class TagTests
{
private readonly TagFixture _tagFixture = new();
[Fact]
public void Create_WhenCalledWithValidName_ShouldCreateTagWithTrimmedName()
{
// Act
Result<Tag> result = Tag.Create(" bestseller ");
// Assert
Assert.False(result.IsFailure);
Assert.Equal("bestseller", result.Value.Name);
}
[Theory]
[InlineData(null)] // null name
[InlineData("")] // empty name
[InlineData(" ")] // whitespace name
public void Create_WhenNameIsNullOrWhitespace_ShouldReturnError(string? name)
{
// Act
Result<Tag> result = Tag.Create(name);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Metadata.TagNameCannotBeEmpty, result.FirstError);
}
[Fact]
public void Equals_WithSameName_ShouldReturnTrue()
{
// Arrange
Tag firstTag = _tagFixture.Create(name: "bestseller");
Tag secondTag = _tagFixture.Create(name: "bestseller");
// Act
bool result = firstTag.Equals(secondTag);
// Assert
Assert.True(result);
}
[Fact]
public void Equals_WithDifferentName_ShouldReturnFalse()
{
// Arrange
Tag firstTag = _tagFixture.Create(name: "bestseller");
Tag secondTag = _tagFixture.Create(name: "award-winning");
// Act
bool result = firstTag.Equals(secondTag);
// Assert
Assert.False(result);
}
[Fact]
public void ToString_WhenCalled_ShouldReturnName()
{
// Arrange
Tag tag = _tagFixture.Create(name: "bestseller");
// Act
string result = tag.ToString();
// Assert
Assert.Equal("bestseller", result);
}
}