mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 07:11:10 +00:00
Renames project paths from Lumina to Nemera
This commit is contained in:
1 parent
ce6fddb4c9
commit
0f659a4877
6450 files changed
No files matched your search
+436
@@ -0,0 +1,436 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Common.ValueObjects.Metadata;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Common.ValueObjects.Metadata;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="AudioMetadata"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
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]
|
||||
public void Create_WhenCalledWithValidValues_ShouldCreateMetadataWithAllPropertiesSet()
|
||||
{
|
||||
// Act
|
||||
Result<AudioMetadata> result = AudioMetadata.Create(
|
||||
"Bohemian Rhapsody",
|
||||
Optional<string>.None(),
|
||||
durationInSeconds: 2826,
|
||||
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>.None(),
|
||||
Optional<LanguageInfo>.None(),
|
||||
Optional<int>.Some(16),
|
||||
Optional<string>.Some("PCM"),
|
||||
Optional<string>.Some("WAV"),
|
||||
Optional<int>.Some(1411),
|
||||
Optional<string>.Some("f0e9c1a2-0000-0000-0000-000000000000"),
|
||||
Optional<decimal>.Some(-6.53m),
|
||||
Optional<decimal>.Some(0.988m),
|
||||
Optional<decimal>.Some(-7.01m),
|
||||
Optional<decimal>.Some(1.001m));
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal("Bohemian Rhapsody", result.Value.Title);
|
||||
Assert.Equal(2826, result.Value.DurationInSeconds);
|
||||
Assert.Equal(44100, result.Value.SampleRate);
|
||||
Assert.Equal(2, result.Value.Channels);
|
||||
Assert.Equal("A song by the British rock band Queen.", result.Value.Description.Value);
|
||||
Assert.Equal(16, result.Value.BitDepth.Value);
|
||||
Assert.Equal("PCM", result.Value.AudioCodec.Value);
|
||||
Assert.Equal("WAV", result.Value.Container.Value);
|
||||
Assert.Equal(1411, result.Value.Bitrate.Value);
|
||||
Assert.Single(result.Value.Genres);
|
||||
Assert.Single(result.Value.Tags);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithOptionalValuesAbsent_ShouldCreateMetadataWithoutThem()
|
||||
{
|
||||
// Act
|
||||
Result<AudioMetadata> result = AudioMetadata.Create(
|
||||
"Bohemian Rhapsody",
|
||||
Optional<string>.None(),
|
||||
durationInSeconds: 2826,
|
||||
sampleRate: 44100,
|
||||
channels: 2,
|
||||
_releaseInfoFixture.Create(),
|
||||
Optional<string>.None(),
|
||||
[],
|
||||
[],
|
||||
Optional<LanguageInfo>.None(),
|
||||
Optional<LanguageInfo>.None(),
|
||||
Optional<int>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<int>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<decimal>.None(),
|
||||
Optional<decimal>.None(),
|
||||
Optional<decimal>.None(),
|
||||
Optional<decimal>.None());
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.False(result.Value.BitDepth.HasValue);
|
||||
Assert.False(result.Value.AudioCodec.HasValue);
|
||||
Assert.False(result.Value.Container.HasValue);
|
||||
Assert.False(result.Value.Bitrate.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithSameValues_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
ReleaseInfo releaseInfo = _releaseInfoFixture.Create();
|
||||
|
||||
// Act
|
||||
AudioMetadata firstResult = _audioMetadataFixture.Create(
|
||||
title: "Bohemian Rhapsody",
|
||||
originalTitle: Optional<string>.None(),
|
||||
durationInSeconds: 2826,
|
||||
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(),
|
||||
container: Optional<string>.None(),
|
||||
bitrate: Optional<int>.None());
|
||||
AudioMetadata secondResult = _audioMetadataFixture.Create(
|
||||
title: "Bohemian Rhapsody",
|
||||
originalTitle: Optional<string>.None(),
|
||||
durationInSeconds: 2826,
|
||||
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(),
|
||||
container: Optional<string>.None(),
|
||||
bitrate: Optional<int>.None());
|
||||
|
||||
// Assert
|
||||
Assert.Equal(firstResult, secondResult);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentSampleRate_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
ReleaseInfo releaseInfo = _releaseInfoFixture.Create();
|
||||
|
||||
// Act
|
||||
AudioMetadata firstResult = _audioMetadataFixture.Create(
|
||||
title: "Bohemian Rhapsody",
|
||||
originalTitle: Optional<string>.None(),
|
||||
durationInSeconds: 2826,
|
||||
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(),
|
||||
container: Optional<string>.None(),
|
||||
bitrate: Optional<int>.None());
|
||||
AudioMetadata secondResult = _audioMetadataFixture.Create(
|
||||
title: "Bohemian Rhapsody",
|
||||
originalTitle: Optional<string>.None(),
|
||||
durationInSeconds: 2826,
|
||||
sampleRate: 48000,
|
||||
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(),
|
||||
container: Optional<string>.None(),
|
||||
bitrate: Optional<int>.None());
|
||||
|
||||
// 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<string>.Some("WAV"),
|
||||
Optional<int>.Some(1411),
|
||||
Optional<string>.Some("f0e9c1a2-0000-0000-0000-000000000000"),
|
||||
Optional<decimal>.Some(-6.53m),
|
||||
Optional<decimal>.Some(0.988m),
|
||||
Optional<decimal>.Some(-7.01m),
|
||||
Optional<decimal>.Some(1.001m));
|
||||
|
||||
// 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<string>.None(),
|
||||
Optional<int>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<decimal>.None(),
|
||||
Optional<decimal>.None(),
|
||||
Optional<decimal>.None(),
|
||||
Optional<decimal>.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(),
|
||||
container: 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(),
|
||||
container: 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_WithDifferentContainer_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(),
|
||||
container: Optional<string>.Some("MP3"),
|
||||
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>.None(),
|
||||
container: 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(),
|
||||
container: 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(),
|
||||
container: Optional<string>.None(),
|
||||
bitrate: Optional<int>.None());
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstResult, secondResult);
|
||||
}
|
||||
}
|
||||
+212
@@ -0,0 +1,212 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="AudioRating"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AudioRatingTests
|
||||
{
|
||||
private readonly AudioRatingFixture _audioRatingFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithValidValues_ShouldCreateRatingWithAllPropertiesSet()
|
||||
{
|
||||
// Act
|
||||
Result<AudioRating> result = AudioRating.Create(4m, 5m, Optional<AudioRatingSource>.Some(AudioRatingSource.MusicBrainz), Optional<int>.Some(10));
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(4m, result.Value.Value);
|
||||
Assert.Equal(5m, result.Value.MaxValue);
|
||||
Assert.Equal(Optional<AudioRatingSource>.Some(AudioRatingSource.MusicBrainz), result.Value.Source);
|
||||
Assert.Equal(Optional<int>.Some(10), result.Value.VoteCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenOptionalValuesAreAbsent_ShouldCreateRatingWithoutThem()
|
||||
{
|
||||
// Act
|
||||
Result<AudioRating> result = AudioRating.Create(3m, 5m, Optional<AudioRatingSource>.None(), Optional<int>.None());
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.False(result.Value.Source.HasValue);
|
||||
Assert.False(result.Value.VoteCount.HasValue);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(-1)] // Negative value.
|
||||
[InlineData(-0.5)] // Negative fractional value.
|
||||
public void Create_WhenValueIsNegative_ShouldReturnError(double value)
|
||||
{
|
||||
// Act
|
||||
Result<AudioRating> result = AudioRating.Create((decimal)value, maxValue: 5, Optional<AudioRatingSource>.None(), Optional<int>.None());
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(DomainErrors.Metadata.RatingValueMustBePositive, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenMaxValueIsNegative_ShouldReturnError()
|
||||
{
|
||||
// Act
|
||||
Result<AudioRating> result = AudioRating.Create(value: 4m, maxValue: -5, Optional<AudioRatingSource>.None(), Optional<int>.None());
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(DomainErrors.Metadata.RatingValueMustBePositive, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenValueIsGreaterThanMaxValue_ShouldReturnError()
|
||||
{
|
||||
// Act
|
||||
Result<AudioRating> result = AudioRating.Create(6m, 5m, Optional<AudioRatingSource>.None(), Optional<int>.None());
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(DomainErrors.Metadata.RatingValueCannotBeGreaterThanMaxValue, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToString_WhenSourceAndVoteCountArePresent_ShouldIncludeThem()
|
||||
{
|
||||
// Arrange
|
||||
AudioRating rating = _audioRatingFixture.Create(value: 4m, maxValue: 5m, source: Optional<AudioRatingSource>.Some(AudioRatingSource.LastFm), voteCount: Optional<int>.Some(10));
|
||||
|
||||
// Act
|
||||
string result = rating.ToString();
|
||||
|
||||
// Assert
|
||||
Assert.Equal("4/5 (LastFm) [10 votes]", result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToString_WhenSourceAndVoteCountAreAbsent_ShouldReturnValueAndMaxValue()
|
||||
{
|
||||
// Arrange
|
||||
AudioRating rating = _audioRatingFixture.Create(value: 3m, maxValue: 5m, source: Optional<AudioRatingSource>.None(), voteCount: Optional<int>.None());
|
||||
|
||||
// Act
|
||||
string result = rating.ToString();
|
||||
|
||||
// Assert
|
||||
Assert.Equal("3/5", result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithSameValues_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
AudioRating firstRating = _audioRatingFixture.Create(value: 4m, maxValue: 5m, source: Optional<AudioRatingSource>.Some(AudioRatingSource.User), voteCount: Optional<int>.Some(10));
|
||||
AudioRating secondRating = _audioRatingFixture.Create(value: 4m, maxValue: 5m, source: Optional<AudioRatingSource>.Some(AudioRatingSource.User), voteCount: Optional<int>.Some(10));
|
||||
|
||||
// Act
|
||||
bool result = firstRating.Equals(secondRating);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentValue_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
AudioRating firstRating = _audioRatingFixture.Create(value: 1m, maxValue: 5m);
|
||||
AudioRating secondRating = _audioRatingFixture.Create(value: 4m, maxValue: 5m);
|
||||
|
||||
// Act
|
||||
bool result = firstRating.Equals(secondRating);
|
||||
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
+93
@@ -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);
|
||||
}
|
||||
}
|
||||
+93
@@ -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);
|
||||
}
|
||||
}
|
||||
+880
@@ -0,0 +1,880 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Common.ValueObjects.Metadata;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Common.ValueObjects.Metadata;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="Artist"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ArtistTests
|
||||
{
|
||||
private readonly ArtistFixture _artistFixture = new();
|
||||
private readonly AlbumFixture _albumFixture = new();
|
||||
private readonly TrackFixture _trackFixture = new();
|
||||
private readonly ArtistIdFixture _artistIdFixture = new();
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly AlbumMetadataFixture _albumMetadataFixture = new();
|
||||
private readonly BarcodeFixture _barcodeFixture = new();
|
||||
private readonly MusicBrainzIdFixture _musicBrainzIdFixture = new();
|
||||
private readonly MusicMediaContributorFixture _musicMediaContributorFixture = new();
|
||||
private readonly AudioRatingFixture _audioRatingFixture = new();
|
||||
private readonly AudioMetadataFixture _audioMetadataFixture = new();
|
||||
private readonly MoodFixture _moodFixture = new();
|
||||
private readonly IsrcFixture _isrcFixture = new();
|
||||
private readonly MusicWorkFixture _musicWorkFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void AddTrackToAlbum_WhenAlbumIsOwnedByTheArtist_ShouldAddTheTrackAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
Album album = _albumFixture.Create(tracks: []);
|
||||
Artist artist = _artistFixture.Create(albums: [album]);
|
||||
Track track = _trackFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Created> result = artist.AddTrackToAlbum(album, track);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Track storedTrack = Assert.Single(album.Tracks);
|
||||
Assert.Equal(track, storedTrack);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddTrackToAlbum_WhenAlbumIsNotOwnedByTheArtist_ShouldReturnAlbumNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
Album ownedAlbum = _albumFixture.Create(tracks: []);
|
||||
Album foreignAlbum = _albumFixture.Create(tracks: []);
|
||||
Artist artist = _artistFixture.Create(albums: [ownedAlbum]);
|
||||
Track track = _trackFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Created> result = artist.AddTrackToAlbum(foreignAlbum, track);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError);
|
||||
Assert.Empty(foreignAlbum.Tracks);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddTrackToAlbum_WhenTrackIsAlreadyInTheAlbum_ShouldPropagateTheTrackIsAlreadyInTheAlbumError()
|
||||
{
|
||||
// Arrange
|
||||
Album album = _albumFixture.Create(tracks: []);
|
||||
Artist artist = _artistFixture.Create(albums: [album]);
|
||||
Track track = _trackFixture.Create();
|
||||
artist.AddTrackToAlbum(album, track);
|
||||
|
||||
// Act
|
||||
Result<Created> result = artist.AddTrackToAlbum(album, track);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.TheTrackIsAlreadyInTheAlbum, result.FirstError);
|
||||
Assert.Single(album.Tracks);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithValidData_ShouldCreateArtistWithAllProperties()
|
||||
{
|
||||
// Arrange
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
MusicBrainzId musicBrainzArtistId = _musicBrainzIdFixture.Create();
|
||||
List<MusicMediaContributor> contributors = [_musicMediaContributorFixture.Create()];
|
||||
Album album = _albumFixture.Create();
|
||||
DateTime beforeCreate = DateTime.UtcNow;
|
||||
|
||||
// Act
|
||||
Result<Artist> result = Artist.Create(
|
||||
libraryId,
|
||||
"Queen",
|
||||
Optional<string>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<MusicArtistType>.None(),
|
||||
Optional<MusicArtistGender>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<MusicArea>.None(),
|
||||
Optional<MusicArea>.None(),
|
||||
Optional<MusicArea>.None(),
|
||||
Optional<DateOnly>.None(),
|
||||
Optional<DateOnly>.None(),
|
||||
false,
|
||||
Optional<string>.Some("https://www.queenonline.com"),
|
||||
Optional<MusicBrainzId>.Some(musicBrainzArtistId),
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
contributors,
|
||||
[album]);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Artist artist = result.Value;
|
||||
Assert.NotEqual(Guid.Empty, artist.Id.Value);
|
||||
Assert.Equal(libraryId, artist.LibraryId);
|
||||
Assert.Equal("Queen", artist.Name);
|
||||
Assert.Equal(Optional<string>.Some("https://www.queenonline.com"), artist.Website);
|
||||
Assert.Equal(Optional<MusicBrainzId>.Some(musicBrainzArtistId), artist.MusicBrainzArtistId);
|
||||
Assert.Equal(contributors, artist.Contributors);
|
||||
Assert.Single(artist.Albums);
|
||||
Assert.Equal(album, artist.Albums.Single());
|
||||
Assert.InRange(artist.CreatedOnUtc, beforeCreate, DateTime.UtcNow);
|
||||
Assert.False(artist.UpdatedOnUtc.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenOptionalValuesAreAbsent_ShouldCreateArtistWithoutThem()
|
||||
{
|
||||
// Arrange
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
Album album = _albumFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Artist> result = Artist.Create(
|
||||
libraryId,
|
||||
"Queen",
|
||||
Optional<string>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<MusicArtistType>.None(),
|
||||
Optional<MusicArtistGender>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<MusicArea>.None(),
|
||||
Optional<MusicArea>.None(),
|
||||
Optional<MusicArea>.None(),
|
||||
Optional<DateOnly>.None(),
|
||||
Optional<DateOnly>.None(),
|
||||
false,
|
||||
Optional<string>.None(),
|
||||
Optional<MusicBrainzId>.None(),
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
[album]);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Artist artist = result.Value;
|
||||
Assert.False(artist.Website.HasValue);
|
||||
Assert.False(artist.MusicBrainzArtistId.HasValue);
|
||||
Assert.Empty(artist.Contributors);
|
||||
Assert.Single(artist.Albums);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // Null name.
|
||||
[InlineData("")] // Empty name.
|
||||
[InlineData(" ")] // Whitespace name.
|
||||
public void Create_WhenNameIsNullOrWhitespace_ShouldReturnArtistNameCannotBeEmptyError(string? name)
|
||||
{
|
||||
// Act
|
||||
Result<Artist> result = Artist.Create(
|
||||
_libraryIdFixture.Create(),
|
||||
name!,
|
||||
Optional<string>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<MusicArtistType>.None(),
|
||||
Optional<MusicArtistGender>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<MusicArea>.None(),
|
||||
Optional<MusicArea>.None(),
|
||||
Optional<MusicArea>.None(),
|
||||
Optional<DateOnly>.None(),
|
||||
Optional<DateOnly>.None(),
|
||||
false,
|
||||
Optional<string>.None(),
|
||||
Optional<MusicBrainzId>.None(),
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
[_albumFixture.Create()]);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.ArtistNameCannotBeEmpty, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenAlbumsListIsEmpty_ShouldReturnArtistMustHaveAtLeastOneAlbumError()
|
||||
{
|
||||
// Act
|
||||
Result<Artist> result = Artist.Create(
|
||||
_libraryIdFixture.Create(),
|
||||
"Queen",
|
||||
Optional<string>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<MusicArtistType>.None(),
|
||||
Optional<MusicArtistGender>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<MusicArea>.None(),
|
||||
Optional<MusicArea>.None(),
|
||||
Optional<MusicArea>.None(),
|
||||
Optional<DateOnly>.None(),
|
||||
Optional<DateOnly>.None(),
|
||||
false,
|
||||
Optional<string>.None(),
|
||||
Optional<MusicBrainzId>.None(),
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
[]);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.ArtistMustHaveAtLeastOneAlbum, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateWithId_WhenCalledWithValidData_ShouldPreserveIdentityAndTimestamps()
|
||||
{
|
||||
// Arrange
|
||||
ArtistId artistId = _artistIdFixture.Create();
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
Album album = _albumFixture.Create();
|
||||
DateTime createdOnUtc = DateTime.UtcNow.AddDays(-1);
|
||||
DateTime updatedOnUtc = DateTime.UtcNow;
|
||||
|
||||
// Act
|
||||
Result<Artist> result = Artist.Create(
|
||||
artistId,
|
||||
libraryId,
|
||||
"Queen",
|
||||
Optional<string>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<MusicArtistType>.None(),
|
||||
Optional<MusicArtistGender>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<MusicArea>.None(),
|
||||
Optional<MusicArea>.None(),
|
||||
Optional<MusicArea>.None(),
|
||||
Optional<DateOnly>.None(),
|
||||
Optional<DateOnly>.None(),
|
||||
false,
|
||||
Optional<string>.Some("https://www.queenonline.com"),
|
||||
Optional<MusicBrainzId>.None(),
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
[album],
|
||||
createdOnUtc,
|
||||
Optional<DateTime>.Some(updatedOnUtc));
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Artist artist = result.Value;
|
||||
Assert.Equal(artistId, artist.Id);
|
||||
Assert.Equal(libraryId, artist.LibraryId);
|
||||
Assert.Equal("Queen", artist.Name);
|
||||
Assert.Equal(Optional<string>.Some("https://www.queenonline.com"), artist.Website);
|
||||
Assert.Equal(createdOnUtc, artist.CreatedOnUtc);
|
||||
Assert.Equal(Optional<DateTime>.Some(updatedOnUtc), artist.UpdatedOnUtc);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // Null name.
|
||||
[InlineData("")] // Empty name.
|
||||
[InlineData(" ")] // Whitespace name.
|
||||
public void CreateWithId_WhenNameIsNullOrWhitespace_ShouldReturnArtistNameCannotBeEmptyError(string? name)
|
||||
{
|
||||
// Act
|
||||
Result<Artist> result = Artist.Create(
|
||||
_artistIdFixture.Create(),
|
||||
_libraryIdFixture.Create(),
|
||||
name!,
|
||||
Optional<string>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<MusicArtistType>.None(),
|
||||
Optional<MusicArtistGender>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<MusicArea>.None(),
|
||||
Optional<MusicArea>.None(),
|
||||
Optional<MusicArea>.None(),
|
||||
Optional<DateOnly>.None(),
|
||||
Optional<DateOnly>.None(),
|
||||
false,
|
||||
Optional<string>.None(),
|
||||
Optional<MusicBrainzId>.None(),
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
[_albumFixture.Create()],
|
||||
DateTime.UtcNow,
|
||||
Optional<DateTime>.None());
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.ArtistNameCannotBeEmpty, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateWithId_WhenAlbumsListIsEmpty_ShouldReturnArtistMustHaveAtLeastOneAlbumError()
|
||||
{
|
||||
// Act
|
||||
Result<Artist> result = Artist.Create(
|
||||
_artistIdFixture.Create(),
|
||||
_libraryIdFixture.Create(),
|
||||
"Queen",
|
||||
Optional<string>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<MusicArtistType>.None(),
|
||||
Optional<MusicArtistGender>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<MusicArea>.None(),
|
||||
Optional<MusicArea>.None(),
|
||||
Optional<MusicArea>.None(),
|
||||
Optional<DateOnly>.None(),
|
||||
Optional<DateOnly>.None(),
|
||||
false,
|
||||
Optional<string>.None(),
|
||||
Optional<MusicBrainzId>.None(),
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
DateTime.UtcNow,
|
||||
Optional<DateTime>.None());
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.ArtistMustHaveAtLeastOneAlbum, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddAlbum_WhenAlbumIsNotOwnedByTheArtist_ShouldAddTheAlbumAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
Album firstAlbum = _albumFixture.Create();
|
||||
Album secondAlbum = _albumFixture.Create();
|
||||
Artist artist = _artistFixture.Create(albums: [firstAlbum]);
|
||||
|
||||
// Act
|
||||
Result<Created> result = artist.AddAlbum(secondAlbum);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(2, artist.Albums.Count);
|
||||
Assert.Contains(secondAlbum, artist.Albums);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddAlbum_WhenAlbumIsAlreadyOwnedByTheArtist_ShouldReturnTheArtistAlreadyHasTheAlbumError()
|
||||
{
|
||||
// Arrange
|
||||
Album album = _albumFixture.Create();
|
||||
Artist artist = _artistFixture.Create(albums: [album]);
|
||||
|
||||
// Act
|
||||
Result<Created> result = artist.AddAlbum(album);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.TheArtistAlreadyHasTheAlbum, result.FirstError);
|
||||
Assert.Single(artist.Albums);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RemoveAlbum_WhenAlbumIsOwnedAndMoreThanOneAlbumExists_ShouldRemoveItAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
Album firstAlbum = _albumFixture.Create();
|
||||
Album secondAlbum = _albumFixture.Create();
|
||||
Artist artist = _artistFixture.Create(albums: [firstAlbum, secondAlbum]);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = artist.RemoveAlbum(firstAlbum);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Single(artist.Albums);
|
||||
Assert.DoesNotContain(firstAlbum, artist.Albums);
|
||||
Assert.Contains(secondAlbum, artist.Albums);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RemoveAlbum_WhenAlbumIsNotOwnedByTheArtist_ShouldReturnTheArtistDoesNotHaveTheAlbumError()
|
||||
{
|
||||
// Arrange
|
||||
Album ownedAlbum = _albumFixture.Create();
|
||||
Album foreignAlbum = _albumFixture.Create();
|
||||
Artist artist = _artistFixture.Create(albums: [ownedAlbum]);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = artist.RemoveAlbum(foreignAlbum);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.TheArtistDoesNotHaveTheAlbum, result.FirstError);
|
||||
Assert.Single(artist.Albums);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RemoveAlbum_WhenAlbumIsTheOnlyAlbumOfTheArtist_ShouldReturnArtistMustHaveAtLeastOneAlbumError()
|
||||
{
|
||||
// Arrange
|
||||
Album onlyAlbum = _albumFixture.Create();
|
||||
Artist artist = _artistFixture.Create(albums: [onlyAlbum]);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = artist.RemoveAlbum(onlyAlbum);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.ArtistMustHaveAtLeastOneAlbum, result.FirstError);
|
||||
Assert.Single(artist.Albums);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EnsureCanRemoveAlbum_WhenTheArtistHasAnotherAlbum_ShouldReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
Album firstAlbum = _albumFixture.Create();
|
||||
Album secondAlbum = _albumFixture.Create();
|
||||
Artist artist = _artistFixture.Create(albums: [firstAlbum, secondAlbum]);
|
||||
|
||||
// Act
|
||||
Result<bool> result = artist.CanRemoveAlbum(firstAlbum);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(2, artist.Albums.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EnsureCanRemoveAlbum_WhenAlbumIsTheOnlyAlbumOfTheArtist_ShouldReturnArtistMustHaveAtLeastOneAlbumError()
|
||||
{
|
||||
// Arrange
|
||||
Album onlyAlbum = _albumFixture.Create();
|
||||
Artist artist = _artistFixture.Create(albums: [onlyAlbum]);
|
||||
|
||||
// Act
|
||||
Result<bool> result = artist.CanRemoveAlbum(onlyAlbum);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.ArtistMustHaveAtLeastOneAlbum, result.FirstError);
|
||||
Assert.Single(artist.Albums);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateContributors_WhenCalledWithNewContributors_ShouldReplaceThemInPlace()
|
||||
{
|
||||
// Arrange
|
||||
MusicMediaContributor firstContributor = _musicMediaContributorFixture.Create();
|
||||
MusicMediaContributor secondContributor = _musicMediaContributorFixture.Create();
|
||||
Artist artist = _artistFixture.Create(contributors: [firstContributor]);
|
||||
|
||||
// Act
|
||||
artist.UpdateContributors([secondContributor]);
|
||||
|
||||
// Assert
|
||||
MusicMediaContributor storedContributor = Assert.Single(artist.Contributors);
|
||||
Assert.Equal(secondContributor, storedContributor);
|
||||
Assert.DoesNotContain(firstContributor, artist.Contributors);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateContributors_WhenCalledWithDuplicateContributors_ShouldKeepOnlyDistinctOnes()
|
||||
{
|
||||
// Arrange
|
||||
MusicMediaContributor contributor = _musicMediaContributorFixture.Create();
|
||||
Artist artist = _artistFixture.Create(contributors: []);
|
||||
|
||||
// Act
|
||||
artist.UpdateContributors([contributor, contributor]);
|
||||
|
||||
// Assert
|
||||
MusicMediaContributor storedContributor = Assert.Single(artist.Contributors);
|
||||
Assert.Equal(contributor, storedContributor);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateDetails_WhenCalledWithValidData_ShouldUpdateDetailsAndSetUpdatedOnUtc()
|
||||
{
|
||||
// Arrange
|
||||
Artist artist = _artistFixture.Create();
|
||||
MusicBrainzId musicBrainzArtistId = _musicBrainzIdFixture.Create();
|
||||
DateTime beforeUpdate = DateTime.UtcNow;
|
||||
|
||||
// Act
|
||||
Result<Updated> result = artist.UpdateDetails(
|
||||
"Queen",
|
||||
Optional<string>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<MusicArtistType>.None(),
|
||||
Optional<MusicArtistGender>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<MusicArea>.None(),
|
||||
Optional<MusicArea>.None(),
|
||||
Optional<MusicArea>.None(),
|
||||
Optional<DateOnly>.None(),
|
||||
Optional<DateOnly>.None(),
|
||||
false,
|
||||
Optional<string>.Some("https://www.queenonline.com"),
|
||||
Optional<MusicBrainzId>.Some(musicBrainzArtistId));
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal("Queen", artist.Name);
|
||||
Assert.Equal(Optional<string>.Some("https://www.queenonline.com"), artist.Website);
|
||||
Assert.Equal(Optional<MusicBrainzId>.Some(musicBrainzArtistId), artist.MusicBrainzArtistId);
|
||||
Assert.True(artist.UpdatedOnUtc.HasValue);
|
||||
Assert.True(artist.UpdatedOnUtc.Value >= beforeUpdate);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateDetails_WhenNameIsNullOrWhitespace_ShouldReturnArtistNameCannotBeEmptyErrorAndNotMutate()
|
||||
{
|
||||
// Arrange
|
||||
Artist artist = _artistFixture.Create(name: "Queen");
|
||||
string originalName = artist.Name;
|
||||
Optional<DateTime> originalUpdatedOnUtc = artist.UpdatedOnUtc;
|
||||
|
||||
// Act
|
||||
Result<Updated> result = artist.UpdateDetails(
|
||||
" ",
|
||||
Optional<string>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<MusicArtistType>.None(),
|
||||
Optional<MusicArtistGender>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<MusicArea>.None(),
|
||||
Optional<MusicArea>.None(),
|
||||
Optional<MusicArea>.None(),
|
||||
Optional<DateOnly>.None(),
|
||||
Optional<DateOnly>.None(),
|
||||
false,
|
||||
Optional<string>.None(),
|
||||
Optional<MusicBrainzId>.None());
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.ArtistNameCannotBeEmpty, result.FirstError);
|
||||
Assert.Equal(originalName, artist.Name);
|
||||
Assert.Equal(originalUpdatedOnUtc, artist.UpdatedOnUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateAlbum_WhenAlbumIsOwnedByTheArtist_ShouldUpdateItAndSetUpdatedOnUtc()
|
||||
{
|
||||
// Arrange
|
||||
Album album = _albumFixture.Create();
|
||||
Artist artist = _artistFixture.Create(albums: [album]);
|
||||
AlbumMetadata metadata = _albumMetadataFixture.Create(title: "A Night at the Opera");
|
||||
Optional<MusicMediaFormat> mediaFormat = Optional<MusicMediaFormat>.Some(MusicMediaFormat.CD);
|
||||
Optional<Barcode> barcode = Optional<Barcode>.Some(_barcodeFixture.Create());
|
||||
List<string> catalogNumbers = ["CAT-123456"];
|
||||
Optional<MusicBrainzId> releaseId = Optional<MusicBrainzId>.Some(_musicBrainzIdFixture.Create());
|
||||
Optional<MusicBrainzId> releaseGroupId = Optional<MusicBrainzId>.Some(_musicBrainzIdFixture.Create());
|
||||
Optional<MusicBrainzId> releaseArtistId = Optional<MusicBrainzId>.Some(_musicBrainzIdFixture.Create());
|
||||
List<MusicMediaContributor> contributors = [_musicMediaContributorFixture.Create()];
|
||||
List<AudioRating> ratings = [_audioRatingFixture.Create()];
|
||||
DateTime beforeUpdate = DateTime.UtcNow;
|
||||
|
||||
// Act
|
||||
Result<Updated> result = artist.UpdateAlbum(
|
||||
album,
|
||||
metadata,
|
||||
Optional<string>.None(),
|
||||
mediaFormat,
|
||||
Optional<MusicReleasePackaging>.None(),
|
||||
Optional<string>.None(),
|
||||
barcode,
|
||||
catalogNumbers,
|
||||
Optional<string>.None(),
|
||||
Optional<string>.None(),
|
||||
releaseId,
|
||||
releaseGroupId,
|
||||
releaseArtistId,
|
||||
contributors,
|
||||
ratings);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(metadata, album.Metadata);
|
||||
Assert.Equal(mediaFormat, album.MediaFormat);
|
||||
Assert.Equal(barcode, album.Barcode);
|
||||
Assert.Equal(catalogNumbers, album.CatalogNumbers);
|
||||
Assert.Equal(releaseId, album.MusicBrainzReleaseId);
|
||||
Assert.Equal(releaseGroupId, album.MusicBrainzReleaseGroupId);
|
||||
Assert.Equal(releaseArtistId, album.MusicBrainzReleaseArtistId);
|
||||
Assert.Equal(contributors, album.Contributors);
|
||||
Assert.Equal(ratings, album.Ratings);
|
||||
Assert.True(artist.UpdatedOnUtc.HasValue);
|
||||
Assert.True(artist.UpdatedOnUtc.Value >= beforeUpdate);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateAlbum_WhenAlbumIsNotOwnedByTheArtist_ShouldReturnAlbumNotFoundErrorAndNotMutate()
|
||||
{
|
||||
// Arrange
|
||||
Album ownedAlbum = _albumFixture.Create();
|
||||
Album foreignAlbum = _albumFixture.Create();
|
||||
AlbumMetadata originalMetadata = foreignAlbum.Metadata;
|
||||
Artist artist = _artistFixture.Create(albums: [ownedAlbum]);
|
||||
Optional<DateTime> originalUpdatedOnUtc = artist.UpdatedOnUtc;
|
||||
|
||||
// Act
|
||||
Result<Updated> result = artist.UpdateAlbum(
|
||||
foreignAlbum,
|
||||
_albumMetadataFixture.Create(),
|
||||
Optional<string>.None(),
|
||||
Optional<MusicMediaFormat>.None(),
|
||||
Optional<MusicReleasePackaging>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<Barcode>.None(),
|
||||
[],
|
||||
Optional<string>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<MusicBrainzId>.None(),
|
||||
Optional<MusicBrainzId>.None(),
|
||||
Optional<MusicBrainzId>.None(),
|
||||
[],
|
||||
[]);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError);
|
||||
Assert.Equal(originalMetadata, foreignAlbum.Metadata);
|
||||
Assert.Equal(originalUpdatedOnUtc, artist.UpdatedOnUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateTrackInAlbum_WhenAlbumAndTrackBelongToTheArtist_ShouldUpdateTheTrackAndSetUpdatedOnUtc()
|
||||
{
|
||||
// Arrange
|
||||
Track track = _trackFixture.Create();
|
||||
Album album = _albumFixture.Create(tracks: [track]);
|
||||
Artist artist = _artistFixture.Create(albums: [album]);
|
||||
string originalPath = track.Path;
|
||||
AudioMetadata metadata = _audioMetadataFixture.Create();
|
||||
Optional<string> disambiguation = Optional<string>.Some("remastered");
|
||||
Optional<int> discNumber = Optional<int>.Some(1);
|
||||
Optional<string> script = Optional<string>.Some("Latin");
|
||||
Optional<MusicKey> key = Optional<MusicKey>.Some(MusicKey.BMajor);
|
||||
Optional<int> bpm = Optional<int>.Some(72);
|
||||
Optional<MusicWork> work = Optional<MusicWork>.Some(_musicWorkFixture.Create(title: "Bohemian Rhapsody"));
|
||||
Optional<MusicBrainzId> recordingId = Optional<MusicBrainzId>.Some(_musicBrainzIdFixture.Create());
|
||||
Optional<MusicBrainzId> musicBrainzTrackId = Optional<MusicBrainzId>.Some(_musicBrainzIdFixture.Create());
|
||||
List<Mood> moods = [_moodFixture.Create(name: "epic")];
|
||||
List<Isrc> isrcs = [_isrcFixture.Create(value: "GBUM71029604")];
|
||||
List<MusicMediaContributor> contributors = [_musicMediaContributorFixture.Create()];
|
||||
List<AudioRating> ratings = [_audioRatingFixture.Create()];
|
||||
DateTime beforeUpdate = DateTime.UtcNow;
|
||||
|
||||
// Act
|
||||
Result<Updated> result = artist.UpdateTrackInAlbum(
|
||||
album,
|
||||
track,
|
||||
metadata,
|
||||
disambiguation,
|
||||
11,
|
||||
discNumber,
|
||||
script,
|
||||
key,
|
||||
bpm,
|
||||
true,
|
||||
work,
|
||||
recordingId,
|
||||
musicBrainzTrackId,
|
||||
moods,
|
||||
isrcs,
|
||||
contributors,
|
||||
ratings);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
// The file system path is not part of the track update, it is set only when the track is created.
|
||||
Assert.Equal(originalPath, track.Path);
|
||||
Assert.Equal(metadata, track.Metadata);
|
||||
Assert.Equal(disambiguation, track.Disambiguation);
|
||||
Assert.Equal(11, track.TrackNumber);
|
||||
Assert.Equal(discNumber, track.DiscNumber);
|
||||
Assert.Equal(script, track.Script);
|
||||
Assert.Equal(key, track.Key);
|
||||
Assert.Equal(bpm, track.Bpm);
|
||||
Assert.True(track.IsVideo);
|
||||
Assert.Equal(work, track.Work);
|
||||
Assert.Equal(recordingId, track.MusicBrainzRecordingId);
|
||||
Assert.Equal(musicBrainzTrackId, track.MusicBrainzTrackId);
|
||||
Assert.Equal(moods, track.Moods);
|
||||
Assert.Equal(isrcs, track.Isrcs);
|
||||
Assert.Equal(contributors, track.Contributors);
|
||||
Assert.Equal(ratings, track.Ratings);
|
||||
Assert.True(artist.UpdatedOnUtc.HasValue);
|
||||
Assert.True(artist.UpdatedOnUtc.Value >= beforeUpdate);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateTrackInAlbum_WhenAlbumIsNotOwnedByTheArtist_ShouldReturnAlbumNotFoundErrorAndNotMutate()
|
||||
{
|
||||
// Arrange
|
||||
Album ownedAlbum = _albumFixture.Create();
|
||||
Track track = _trackFixture.Create();
|
||||
Album foreignAlbum = _albumFixture.Create(tracks: [track]);
|
||||
Artist artist = _artistFixture.Create(albums: [ownedAlbum]);
|
||||
string originalPath = track.Path;
|
||||
Optional<DateTime> originalUpdatedOnUtc = artist.UpdatedOnUtc;
|
||||
|
||||
// Act
|
||||
Result<Updated> result = artist.UpdateTrackInAlbum(
|
||||
foreignAlbum,
|
||||
track,
|
||||
_audioMetadataFixture.Create(),
|
||||
Optional<string>.None(),
|
||||
11,
|
||||
Optional<int>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<MusicKey>.None(),
|
||||
Optional<int>.None(),
|
||||
false,
|
||||
Optional<MusicWork>.None(),
|
||||
Optional<MusicBrainzId>.None(),
|
||||
Optional<MusicBrainzId>.None(),
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
[]);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError);
|
||||
Assert.Equal(originalPath, track.Path);
|
||||
Assert.Equal(originalUpdatedOnUtc, artist.UpdatedOnUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateTrackInAlbum_WhenTrackIsNotInTheAlbum_ShouldReturnTrackNotFoundErrorAndNotMutate()
|
||||
{
|
||||
// Arrange
|
||||
Track track = _trackFixture.Create();
|
||||
Album album = _albumFixture.Create(tracks: []);
|
||||
Artist artist = _artistFixture.Create(albums: [album]);
|
||||
string originalPath = track.Path;
|
||||
Optional<DateTime> originalUpdatedOnUtc = artist.UpdatedOnUtc;
|
||||
|
||||
// Act
|
||||
Result<Updated> result = artist.UpdateTrackInAlbum(
|
||||
album,
|
||||
track,
|
||||
_audioMetadataFixture.Create(),
|
||||
Optional<string>.None(),
|
||||
11,
|
||||
Optional<int>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<MusicKey>.None(),
|
||||
Optional<int>.None(),
|
||||
false,
|
||||
Optional<MusicWork>.None(),
|
||||
Optional<MusicBrainzId>.None(),
|
||||
Optional<MusicBrainzId>.None(),
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
[]);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.TrackNotFound, result.FirstError);
|
||||
Assert.Equal(originalPath, track.Path);
|
||||
Assert.Equal(originalUpdatedOnUtc, artist.UpdatedOnUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RemoveTrackFromAlbum_WhenAlbumAndTrackBelongToTheArtist_ShouldRemoveTheTrackAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
Track track = _trackFixture.Create();
|
||||
Album album = _albumFixture.Create(tracks: [track]);
|
||||
Artist artist = _artistFixture.Create(albums: [album]);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = artist.RemoveTrackFromAlbum(album, track);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Empty(album.Tracks);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RemoveTrackFromAlbum_WhenAlbumIsNotOwnedByTheArtist_ShouldReturnAlbumNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
Album ownedAlbum = _albumFixture.Create();
|
||||
Track track = _trackFixture.Create();
|
||||
Album foreignAlbum = _albumFixture.Create(tracks: [track]);
|
||||
Artist artist = _artistFixture.Create(albums: [ownedAlbum]);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = artist.RemoveTrackFromAlbum(foreignAlbum, track);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError);
|
||||
Assert.Single(foreignAlbum.Tracks);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RemoveTrackFromAlbum_WhenTrackIsNotInTheAlbum_ShouldReturnTrackNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
Track track = _trackFixture.Create();
|
||||
Album album = _albumFixture.Create(tracks: []);
|
||||
Artist artist = _artistFixture.Create(albums: [album]);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = artist.RemoveTrackFromAlbum(album, track);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.TrackNotFound, result.FirstError);
|
||||
Assert.Empty(album.Tracks);
|
||||
}
|
||||
}
|
||||
+388
@@ -0,0 +1,388 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="Album"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AlbumTests
|
||||
{
|
||||
private readonly AlbumFixture _albumFixture = new();
|
||||
private readonly TrackFixture _trackFixture = new();
|
||||
private readonly AlbumIdFixture _albumIdFixture = new();
|
||||
private readonly AlbumMetadataFixture _albumMetadataFixture = new();
|
||||
private readonly BarcodeFixture _barcodeFixture = new();
|
||||
private readonly MusicBrainzIdFixture _musicBrainzIdFixture = new();
|
||||
private readonly MusicMediaContributorFixture _musicMediaContributorFixture = new();
|
||||
private readonly AudioRatingFixture _audioRatingFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void AddTrack_WhenTrackIsNotInTheAlbum_ShouldAddTheTrackAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
Album album = _albumFixture.Create(tracks: []);
|
||||
Track track = _trackFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Created> result = album.AddTrack(track);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Track storedTrack = Assert.Single(album.Tracks);
|
||||
Assert.Equal(track, storedTrack);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddTrack_WhenTrackIsAlreadyInTheAlbum_ShouldReturnTheTrackIsAlreadyInTheAlbumErrorAndNotAddDuplicate()
|
||||
{
|
||||
// Arrange
|
||||
Album album = _albumFixture.Create(tracks: []);
|
||||
Track track = _trackFixture.Create();
|
||||
album.AddTrack(track);
|
||||
|
||||
// Act
|
||||
Result<Created> result = album.AddTrack(track);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.TheTrackIsAlreadyInTheAlbum, result.FirstError);
|
||||
Assert.Single(album.Tracks);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithAllProperties_ShouldCreateAlbumWithAllProperties()
|
||||
{
|
||||
// Arrange
|
||||
AlbumMetadata metadata = _albumMetadataFixture.Create(title: "A Night at the Opera");
|
||||
Optional<MusicMediaFormat> mediaFormat = Optional<MusicMediaFormat>.Some(MusicMediaFormat.Vinyl);
|
||||
Optional<Barcode> barcode = Optional<Barcode>.Some(_barcodeFixture.Create());
|
||||
List<string> catalogNumbers = ["CAT-001"];
|
||||
Optional<MusicBrainzId> releaseId = Optional<MusicBrainzId>.Some(_musicBrainzIdFixture.Create());
|
||||
Optional<MusicBrainzId> releaseGroupId = Optional<MusicBrainzId>.Some(_musicBrainzIdFixture.Create());
|
||||
Optional<MusicBrainzId> releaseArtistId = Optional<MusicBrainzId>.Some(_musicBrainzIdFixture.Create());
|
||||
List<MusicMediaContributor> contributors = [_musicMediaContributorFixture.Create()];
|
||||
List<AudioRating> ratings = [_audioRatingFixture.Create()];
|
||||
List<Track> tracks = [_trackFixture.Create()];
|
||||
DateTime beforeCreate = DateTime.UtcNow;
|
||||
|
||||
// Act
|
||||
Result<Album> result = Album.Create(
|
||||
metadata,
|
||||
Optional<string>.None(),
|
||||
mediaFormat,
|
||||
Optional<MusicReleasePackaging>.Some(MusicReleasePackaging.Digipak),
|
||||
Optional<string>.None(),
|
||||
barcode,
|
||||
catalogNumbers,
|
||||
Optional<string>.Some("Label"),
|
||||
Optional<string>.Some("ASIN"),
|
||||
releaseId,
|
||||
releaseGroupId,
|
||||
releaseArtistId,
|
||||
contributors,
|
||||
ratings,
|
||||
tracks);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Album album = result.Value;
|
||||
Assert.NotEqual(Guid.Empty, album.Id.Value);
|
||||
Assert.Equal(metadata, album.Metadata);
|
||||
Assert.Equal(mediaFormat, album.MediaFormat);
|
||||
Assert.Equal(barcode, album.Barcode);
|
||||
Assert.Equal(catalogNumbers, album.CatalogNumbers);
|
||||
Assert.Equal(releaseId, album.MusicBrainzReleaseId);
|
||||
Assert.Equal(releaseGroupId, album.MusicBrainzReleaseGroupId);
|
||||
Assert.Equal(releaseArtistId, album.MusicBrainzReleaseArtistId);
|
||||
Assert.Equal(contributors, album.Contributors);
|
||||
Assert.Equal(ratings, album.Ratings);
|
||||
Assert.Equal(tracks, album.Tracks);
|
||||
Assert.InRange(album.CreatedOnUtc, beforeCreate, DateTime.UtcNow);
|
||||
Assert.False(album.UpdatedOnUtc.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenOptionalValuesAreAbsent_ShouldCreateAlbumWithoutThem()
|
||||
{
|
||||
// Act
|
||||
Result<Album> result = Album.Create(
|
||||
_albumMetadataFixture.Create(),
|
||||
Optional<string>.None(),
|
||||
Optional<MusicMediaFormat>.None(),
|
||||
Optional<MusicReleasePackaging>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<Barcode>.None(),
|
||||
[],
|
||||
Optional<string>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<MusicBrainzId>.None(),
|
||||
Optional<MusicBrainzId>.None(),
|
||||
Optional<MusicBrainzId>.None(),
|
||||
[],
|
||||
[],
|
||||
[]);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Album album = result.Value;
|
||||
Assert.False(album.MediaFormat.HasValue);
|
||||
Assert.False(album.Barcode.HasValue);
|
||||
Assert.Empty(album.CatalogNumbers);
|
||||
Assert.False(album.MusicBrainzReleaseId.HasValue);
|
||||
Assert.False(album.MusicBrainzReleaseGroupId.HasValue);
|
||||
Assert.False(album.MusicBrainzReleaseArtistId.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCollectionsAreEmpty_ShouldCreateAlbumWithEmptyCollections()
|
||||
{
|
||||
// Act
|
||||
Result<Album> result = Album.Create(
|
||||
_albumMetadataFixture.Create(),
|
||||
Optional<string>.None(),
|
||||
Optional<MusicMediaFormat>.None(),
|
||||
Optional<MusicReleasePackaging>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<Barcode>.None(),
|
||||
[],
|
||||
Optional<string>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<MusicBrainzId>.None(),
|
||||
Optional<MusicBrainzId>.None(),
|
||||
Optional<MusicBrainzId>.None(),
|
||||
[],
|
||||
[],
|
||||
[]);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Empty(result.Value.Contributors);
|
||||
Assert.Empty(result.Value.Ratings);
|
||||
Assert.Empty(result.Value.Tracks);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateWithId_WhenCalledWithPreExistingIdAndTimestamps_ShouldPreserveIdentityAndTimestamps()
|
||||
{
|
||||
// Arrange
|
||||
AlbumId albumId = _albumIdFixture.Create();
|
||||
AlbumMetadata metadata = _albumMetadataFixture.Create();
|
||||
DateTime createdOnUtc = DateTime.UtcNow.AddDays(-1);
|
||||
DateTime updatedOnUtc = DateTime.UtcNow;
|
||||
|
||||
// Act
|
||||
Result<Album> result = Album.Create(
|
||||
albumId,
|
||||
metadata,
|
||||
Optional<string>.None(),
|
||||
Optional<MusicMediaFormat>.Some(MusicMediaFormat.CD),
|
||||
Optional<MusicReleasePackaging>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<Barcode>.Some(_barcodeFixture.Create()),
|
||||
["CAT-002"],
|
||||
Optional<string>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<MusicBrainzId>.None(),
|
||||
Optional<MusicBrainzId>.None(),
|
||||
Optional<MusicBrainzId>.None(),
|
||||
[],
|
||||
[],
|
||||
[],
|
||||
createdOnUtc,
|
||||
Optional<DateTime>.Some(updatedOnUtc));
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Album album = result.Value;
|
||||
Assert.Equal(albumId, album.Id);
|
||||
Assert.Equal(metadata, album.Metadata);
|
||||
Assert.Equal(createdOnUtc, album.CreatedOnUtc);
|
||||
Assert.Equal(Optional<DateTime>.Some(updatedOnUtc), album.UpdatedOnUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RemoveTrack_WhenTrackIsInTheAlbum_ShouldRemoveTrackAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
Track track = _trackFixture.Create();
|
||||
Album album = _albumFixture.Create(tracks: [track]);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = album.RemoveTrack(track);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Empty(album.Tracks);
|
||||
Assert.DoesNotContain(track, album.Tracks);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RemoveTrack_WhenTrackIsNotInTheAlbum_ShouldReturnTheTrackIsNotInTheAlbumError()
|
||||
{
|
||||
// Arrange
|
||||
Track storedTrack = _trackFixture.Create();
|
||||
Track foreignTrack = _trackFixture.Create();
|
||||
Album album = _albumFixture.Create(tracks: [storedTrack]);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = album.RemoveTrack(foreignTrack);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.TheTrackIsNotInTheAlbum, result.FirstError);
|
||||
Assert.Single(album.Tracks);
|
||||
Assert.Equal(storedTrack, album.Tracks.Single());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateContributors_WhenCalledTwice_ShouldReplaceTheContributorsInsteadOfAppending()
|
||||
{
|
||||
// Arrange
|
||||
Album album = _albumFixture.Create(contributors: []);
|
||||
MusicMediaContributor firstContributor = _musicMediaContributorFixture.Create();
|
||||
MusicMediaContributor secondContributor = _musicMediaContributorFixture.Create();
|
||||
album.UpdateContributors([firstContributor, _musicMediaContributorFixture.Create()]);
|
||||
|
||||
// Act
|
||||
album.UpdateContributors([secondContributor]);
|
||||
|
||||
// Assert
|
||||
MusicMediaContributor storedContributor = Assert.Single(album.Contributors);
|
||||
Assert.Equal(secondContributor, storedContributor);
|
||||
Assert.DoesNotContain(firstContributor, album.Contributors);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateContributors_WhenCalledWithEmptyCollection_ShouldClearTheContributors()
|
||||
{
|
||||
// Arrange
|
||||
Album album = _albumFixture.Create(contributors: [_musicMediaContributorFixture.Create()]);
|
||||
|
||||
// Act
|
||||
album.UpdateContributors([]);
|
||||
|
||||
// Assert
|
||||
Assert.Empty(album.Contributors);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateRatings_WhenCalledTwice_ShouldReplaceTheRatingsInsteadOfAppending()
|
||||
{
|
||||
// Arrange
|
||||
Album album = _albumFixture.Create(ratings: []);
|
||||
AudioRating firstRating = _audioRatingFixture.Create(value: 1m, maxValue: 5m);
|
||||
AudioRating secondRating = _audioRatingFixture.Create(value: 4m, maxValue: 5m);
|
||||
album.UpdateRatings([firstRating, _audioRatingFixture.Create(value: 2m, maxValue: 5m)]);
|
||||
|
||||
// Act
|
||||
album.UpdateRatings([secondRating]);
|
||||
|
||||
// Assert
|
||||
AudioRating storedRating = Assert.Single(album.Ratings);
|
||||
Assert.Equal(secondRating, storedRating);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateRatings_WhenCalledWithEmptyCollection_ShouldClearTheRatings()
|
||||
{
|
||||
// Arrange
|
||||
Album album = _albumFixture.Create(ratings: [_audioRatingFixture.Create()]);
|
||||
|
||||
// Act
|
||||
album.UpdateRatings([]);
|
||||
|
||||
// Assert
|
||||
Assert.Empty(album.Ratings);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateDetails_WhenCalled_ShouldUpdateAllDetailPropertiesAndSetUpdatedOnUtc()
|
||||
{
|
||||
// Arrange
|
||||
Album album = _albumFixture.Create();
|
||||
List<Track> originalTracks = [.. album.Tracks];
|
||||
AlbumMetadata metadata = _albumMetadataFixture.Create(title: "A Day at the Races");
|
||||
Optional<MusicMediaFormat> mediaFormat = Optional<MusicMediaFormat>.Some(MusicMediaFormat.Cassette);
|
||||
Optional<Barcode> barcode = Optional<Barcode>.Some(_barcodeFixture.Create());
|
||||
List<string> catalogNumbers = ["CAT-003"];
|
||||
Optional<MusicBrainzId> releaseId = Optional<MusicBrainzId>.Some(_musicBrainzIdFixture.Create());
|
||||
Optional<MusicBrainzId> releaseGroupId = Optional<MusicBrainzId>.Some(_musicBrainzIdFixture.Create());
|
||||
Optional<MusicBrainzId> releaseArtistId = Optional<MusicBrainzId>.Some(_musicBrainzIdFixture.Create());
|
||||
DateTime beforeUpdate = DateTime.UtcNow;
|
||||
|
||||
// Act
|
||||
Result<Updated> result = album.UpdateDetails(
|
||||
metadata,
|
||||
Optional<string>.None(),
|
||||
mediaFormat,
|
||||
Optional<MusicReleasePackaging>.None(),
|
||||
Optional<string>.None(),
|
||||
barcode,
|
||||
catalogNumbers,
|
||||
Optional<string>.None(),
|
||||
Optional<string>.None(),
|
||||
releaseId,
|
||||
releaseGroupId,
|
||||
releaseArtistId);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(metadata, album.Metadata);
|
||||
Assert.Equal(mediaFormat, album.MediaFormat);
|
||||
Assert.Equal(barcode, album.Barcode);
|
||||
Assert.Equal(catalogNumbers, album.CatalogNumbers);
|
||||
Assert.Equal(releaseId, album.MusicBrainzReleaseId);
|
||||
Assert.Equal(releaseGroupId, album.MusicBrainzReleaseGroupId);
|
||||
Assert.Equal(releaseArtistId, album.MusicBrainzReleaseArtistId);
|
||||
Assert.True(album.UpdatedOnUtc.HasValue);
|
||||
Assert.True(album.UpdatedOnUtc.Value >= beforeUpdate);
|
||||
// The tracks are not part of the details update.
|
||||
Assert.Equal(originalTracks, album.Tracks);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateDetails_WhenOptionalValuesAreAbsent_ShouldClearTheOptionalProperties()
|
||||
{
|
||||
// Arrange
|
||||
Album album = _albumFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = album.UpdateDetails(
|
||||
_albumMetadataFixture.Create(),
|
||||
Optional<string>.None(),
|
||||
Optional<MusicMediaFormat>.None(),
|
||||
Optional<MusicReleasePackaging>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<Barcode>.None(),
|
||||
[],
|
||||
Optional<string>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<MusicBrainzId>.None(),
|
||||
Optional<MusicBrainzId>.None(),
|
||||
Optional<MusicBrainzId>.None());
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.False(album.MediaFormat.HasValue);
|
||||
Assert.False(album.Barcode.HasValue);
|
||||
Assert.Empty(album.CatalogNumbers);
|
||||
Assert.False(album.MusicBrainzReleaseId.HasValue);
|
||||
Assert.False(album.MusicBrainzReleaseGroupId.HasValue);
|
||||
Assert.False(album.MusicBrainzReleaseArtistId.HasValue);
|
||||
}
|
||||
}
|
||||
+459
@@ -0,0 +1,459 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Common.ValueObjects.Metadata;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Common.ValueObjects.Metadata;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="Track"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class TrackTests
|
||||
{
|
||||
private readonly TrackFixture _trackFixture = new();
|
||||
private readonly MoodFixture _moodFixture = new();
|
||||
private readonly IsrcFixture _isrcFixture = new();
|
||||
private readonly MusicMediaContributorFixture _musicMediaContributorFixture = new();
|
||||
private readonly AudioRatingFixture _audioRatingFixture = new();
|
||||
private readonly AudioMetadataFixture _audioMetadataFixture = new();
|
||||
private readonly MusicBrainzIdFixture _musicBrainzIdFixture = new();
|
||||
private readonly MusicWorkFixture _musicWorkFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithValidData_ShouldCreateTrackWithAllPropertiesPopulated()
|
||||
{
|
||||
// Arrange
|
||||
DateTime beforeCreate = DateTime.UtcNow;
|
||||
|
||||
// Act
|
||||
Track track = _trackFixture.Create();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(track);
|
||||
Assert.NotNull(track.Id);
|
||||
Assert.NotEqual(Guid.Empty, track.Id.Value);
|
||||
Assert.False(string.IsNullOrWhiteSpace(track.Path));
|
||||
Assert.NotNull(track.Metadata);
|
||||
Assert.True(track.TrackNumber > 0);
|
||||
Assert.True(track.DiscNumber.HasValue);
|
||||
Assert.NotEmpty(track.Moods);
|
||||
Assert.True(track.Script.HasValue);
|
||||
Assert.True(track.Key.HasValue);
|
||||
Assert.True(track.Bpm.HasValue);
|
||||
Assert.NotEmpty(track.Isrcs);
|
||||
Assert.True(track.Work.HasValue);
|
||||
Assert.NotEqual(Guid.Empty, track.Work.Value.MusicBrainzWorkId.Value);
|
||||
Assert.True(track.MusicBrainzRecordingId.HasValue);
|
||||
Assert.True(track.MusicBrainzTrackId.HasValue);
|
||||
Assert.NotEmpty(track.Contributors);
|
||||
Assert.NotEmpty(track.Ratings);
|
||||
Assert.InRange(track.CreatedOnUtc, beforeCreate, DateTime.UtcNow);
|
||||
Assert.False(track.UpdatedOnUtc.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithPreExistingIdAndTimestamps_ShouldPreserveIdentityAndTimestamps()
|
||||
{
|
||||
// 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.Disambiguation,
|
||||
sourceTrack.TrackNumber,
|
||||
sourceTrack.DiscNumber,
|
||||
[.. sourceTrack.Moods],
|
||||
sourceTrack.Script,
|
||||
sourceTrack.Key,
|
||||
sourceTrack.Bpm,
|
||||
sourceTrack.IsVideo,
|
||||
[.. sourceTrack.Isrcs],
|
||||
sourceTrack.Work,
|
||||
sourceTrack.MusicBrainzRecordingId,
|
||||
sourceTrack.MusicBrainzTrackId,
|
||||
[.. sourceTrack.Contributors],
|
||||
[.. sourceTrack.Ratings],
|
||||
createdOnUtc,
|
||||
Optional<DateTime>.Some(updatedOnUtc));
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Track track = result.Value;
|
||||
Assert.Equal(sourceTrack.Id, track.Id);
|
||||
Assert.Equal(sourceTrack.Path, track.Path);
|
||||
Assert.Equal(sourceTrack.Metadata, track.Metadata);
|
||||
Assert.Equal(sourceTrack.TrackNumber, track.TrackNumber);
|
||||
Assert.Equal(sourceTrack.DiscNumber, track.DiscNumber);
|
||||
Assert.Equal(sourceTrack.Moods, track.Moods);
|
||||
Assert.Equal(sourceTrack.Isrcs, track.Isrcs);
|
||||
Assert.Equal(sourceTrack.Contributors, track.Contributors);
|
||||
Assert.Equal(sourceTrack.Ratings, track.Ratings);
|
||||
Assert.Equal(createdOnUtc, track.CreatedOnUtc);
|
||||
Assert.Equal(Optional<DateTime>.Some(updatedOnUtc), track.UpdatedOnUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateMoods_WhenCalledTwice_ShouldReplaceTheMoodsInsteadOfAppending()
|
||||
{
|
||||
// Arrange
|
||||
Track track = _trackFixture.Create(moods: []);
|
||||
Mood firstMood = _moodFixture.Create(name: "calm");
|
||||
Mood secondMood = _moodFixture.Create(name: "energetic");
|
||||
track.UpdateMoods([firstMood, _moodFixture.Create(name: "melancholic")]);
|
||||
|
||||
// Act
|
||||
track.UpdateMoods([secondMood]);
|
||||
|
||||
// Assert
|
||||
// The second call replaces the first set, it is not appended to it.
|
||||
Mood storedMood = Assert.Single(track.Moods);
|
||||
Assert.Equal(secondMood, storedMood);
|
||||
Assert.DoesNotContain(firstMood, track.Moods);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateIsrcs_WhenCalledTwice_ShouldReplaceTheIsrcsInsteadOfAppending()
|
||||
{
|
||||
// Arrange
|
||||
Track track = _trackFixture.Create(isrcs: []);
|
||||
Isrc firstIsrc = _isrcFixture.Create(value: "USRC17607839");
|
||||
Isrc secondIsrc = _isrcFixture.Create(value: "GBAYE0000001");
|
||||
track.UpdateIsrcs([firstIsrc, _isrcFixture.Create(value: "FRUM71400001")]);
|
||||
|
||||
// Act
|
||||
track.UpdateIsrcs([secondIsrc]);
|
||||
|
||||
// Assert
|
||||
// The second call replaces the first set, it is not appended to it.
|
||||
Isrc storedIsrc = Assert.Single(track.Isrcs);
|
||||
Assert.Equal(secondIsrc, storedIsrc);
|
||||
Assert.DoesNotContain(firstIsrc, track.Isrcs);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateContributors_WhenCalledTwice_ShouldReplaceTheContributorsInsteadOfAppending()
|
||||
{
|
||||
// Arrange
|
||||
Track track = _trackFixture.Create(contributors: []);
|
||||
MusicMediaContributor firstContributor = _musicMediaContributorFixture.Create();
|
||||
MusicMediaContributor secondContributor = _musicMediaContributorFixture.Create();
|
||||
track.UpdateContributors([firstContributor]);
|
||||
|
||||
// Act
|
||||
track.UpdateContributors([secondContributor]);
|
||||
|
||||
// Assert
|
||||
// The second call replaces the first set, it is not appended to it.
|
||||
MusicMediaContributor storedContributor = Assert.Single(track.Contributors);
|
||||
Assert.Equal(secondContributor, storedContributor);
|
||||
Assert.DoesNotContain(firstContributor, track.Contributors);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateRatings_WhenCalledTwice_ShouldReplaceTheRatingsInsteadOfAppending()
|
||||
{
|
||||
// Arrange
|
||||
Track track = _trackFixture.Create(ratings: []);
|
||||
AudioRating firstRating = _audioRatingFixture.Create(value: 1m, maxValue: 5m);
|
||||
AudioRating secondRating = _audioRatingFixture.Create(value: 4m, maxValue: 5m);
|
||||
track.UpdateRatings([firstRating]);
|
||||
|
||||
// Act
|
||||
track.UpdateRatings([secondRating]);
|
||||
|
||||
// Assert
|
||||
// The second call replaces the first set, it is not appended to it.
|
||||
AudioRating storedRating = Assert.Single(track.Ratings);
|
||||
Assert.Equal(secondRating, storedRating);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateDetails_WhenCalled_ShouldUpdateAllDetailPropertiesAndSetUpdatedOnUtc()
|
||||
{
|
||||
// Arrange
|
||||
Track track = _trackFixture.Create();
|
||||
string originalPath = track.Path;
|
||||
List<Mood> originalMoods = [.. track.Moods];
|
||||
AudioMetadata metadata = _audioMetadataFixture.Create();
|
||||
Optional<string> disambiguation = Optional<string>.Some("remastered");
|
||||
Optional<int> discNumber = Optional<int>.Some(2);
|
||||
Optional<string> script = Optional<string>.Some("Latin");
|
||||
Optional<MusicKey> key = Optional<MusicKey>.Some(MusicKey.DMajor);
|
||||
Optional<int> bpm = Optional<int>.Some(128);
|
||||
bool isVideo = true;
|
||||
Optional<MusicWork> work = Optional<MusicWork>.Some(_musicWorkFixture.Create(title: "Symphony No. 5"));
|
||||
Optional<MusicBrainzId> recordingId = Optional<MusicBrainzId>.Some(_musicBrainzIdFixture.Create());
|
||||
Optional<MusicBrainzId> trackId = Optional<MusicBrainzId>.Some(_musicBrainzIdFixture.Create());
|
||||
DateTime beforeUpdate = DateTime.UtcNow;
|
||||
|
||||
// Act
|
||||
Result<Updated> result = track.UpdateDetails(
|
||||
metadata,
|
||||
disambiguation,
|
||||
7,
|
||||
discNumber,
|
||||
script,
|
||||
key,
|
||||
bpm,
|
||||
isVideo,
|
||||
work,
|
||||
recordingId,
|
||||
trackId);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(metadata, track.Metadata);
|
||||
Assert.Equal(disambiguation, track.Disambiguation);
|
||||
Assert.Equal(7, track.TrackNumber);
|
||||
Assert.Equal(discNumber, track.DiscNumber);
|
||||
Assert.Equal(script, track.Script);
|
||||
Assert.Equal(key, track.Key);
|
||||
Assert.Equal(bpm, track.Bpm);
|
||||
Assert.True(track.IsVideo);
|
||||
Assert.Equal(work, track.Work);
|
||||
Assert.Equal(recordingId, track.MusicBrainzRecordingId);
|
||||
Assert.Equal(trackId, track.MusicBrainzTrackId);
|
||||
Assert.True(track.UpdatedOnUtc.HasValue);
|
||||
Assert.True(track.UpdatedOnUtc.Value >= beforeUpdate);
|
||||
// The file system path is not part of the details update, it is set only when the track is created.
|
||||
Assert.Equal(originalPath, track.Path);
|
||||
// The collections are not part of the details update.
|
||||
Assert.Equal(originalMoods, track.Moods);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateDetails_WhenTheMetadataCarriesNoContainer_ShouldKeepTheStoredContainer()
|
||||
{
|
||||
// Arrange
|
||||
Track track = _trackFixture.Create();
|
||||
Optional<string> storedContainer = track.Metadata.Container;
|
||||
AudioMetadata metadata = _audioMetadataFixture.Create(container: Optional<string>.None());
|
||||
|
||||
// Act
|
||||
Result<Updated> result = track.UpdateDetails(
|
||||
metadata,
|
||||
track.Disambiguation,
|
||||
track.TrackNumber,
|
||||
track.DiscNumber,
|
||||
track.Script,
|
||||
track.Key,
|
||||
track.Bpm,
|
||||
track.IsVideo,
|
||||
track.Work,
|
||||
track.MusicBrainzRecordingId,
|
||||
track.MusicBrainzTrackId);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
// The container is captured from the file itself and is never part of an edit, so an update that does not carry one keeps the stored container.
|
||||
Assert.Equal(storedContainer, track.Metadata.Container);
|
||||
// The rest of the metadata still comes from the update.
|
||||
Assert.Equal(metadata.Title, track.Metadata.Title);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateDetails_WhenTheMetadataCarriesAContainer_ShouldReplaceTheStoredContainer()
|
||||
{
|
||||
// Arrange
|
||||
Track track = _trackFixture.Create();
|
||||
AudioMetadata metadata = _audioMetadataFixture.Create(container: Optional<string>.Some("OGG"));
|
||||
|
||||
// Act
|
||||
Result<Updated> result = track.UpdateDetails(
|
||||
metadata,
|
||||
track.Disambiguation,
|
||||
track.TrackNumber,
|
||||
track.DiscNumber,
|
||||
track.Script,
|
||||
track.Key,
|
||||
track.Bpm,
|
||||
track.IsVideo,
|
||||
track.Work,
|
||||
track.MusicBrainzRecordingId,
|
||||
track.MusicBrainzTrackId);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal("OGG", track.Metadata.Container.Value);
|
||||
}
|
||||
|
||||
[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<MusicWork>.None(),
|
||||
musicBrainzRecordingId: Optional<MusicBrainzId>.None(),
|
||||
musicBrainzTrackId: 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.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.Disambiguation,
|
||||
sourceTrack.TrackNumber,
|
||||
sourceTrack.DiscNumber,
|
||||
[.. sourceTrack.Moods],
|
||||
sourceTrack.Script,
|
||||
sourceTrack.Key,
|
||||
sourceTrack.Bpm,
|
||||
sourceTrack.IsVideo,
|
||||
[.. sourceTrack.Isrcs],
|
||||
sourceTrack.Work,
|
||||
sourceTrack.MusicBrainzRecordingId,
|
||||
sourceTrack.MusicBrainzTrackId,
|
||||
[.. 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);
|
||||
// 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(
|
||||
_audioMetadataFixture.Create(),
|
||||
Optional<string>.None(),
|
||||
11,
|
||||
Optional<int>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<MusicKey>.None(),
|
||||
Optional<int>.None(),
|
||||
false,
|
||||
Optional<MusicWork>.None(),
|
||||
Optional<MusicBrainzId>.None(),
|
||||
Optional<MusicBrainzId>.None());
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.False(track.DiscNumber.HasValue);
|
||||
Assert.False(track.Disambiguation.HasValue);
|
||||
Assert.False(track.Script.HasValue);
|
||||
Assert.False(track.Key.HasValue);
|
||||
Assert.False(track.Bpm.HasValue);
|
||||
Assert.False(track.IsVideo);
|
||||
Assert.False(track.Work.HasValue);
|
||||
Assert.False(track.MusicBrainzRecordingId.HasValue);
|
||||
Assert.False(track.MusicBrainzTrackId.HasValue);
|
||||
}
|
||||
}
|
||||
+163
@@ -0,0 +1,163 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.PathTemplate;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.PathTemplate;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicLibraryPathPartCatalog"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicLibraryPathPartCatalogTests
|
||||
{
|
||||
private readonly MusicLibraryPathPartCatalog _sut = new();
|
||||
|
||||
[Fact]
|
||||
public void SupportedLibraryType_WhenCalled_ShouldReturnMusic()
|
||||
{
|
||||
// Act
|
||||
LibraryType result = _sut.SupportedLibraryType;
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryType.Music, result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetPartDefinitions_WhenCalled_ShouldReturnTheExpectedDefinitions()
|
||||
{
|
||||
// Act
|
||||
IReadOnlyList<LibraryPathPartDefinition> result = _sut.GetPartDefinitions();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(10, result.Count);
|
||||
|
||||
Assert.Equal(LibraryPathPartKind.Literal, result[0].Kind);
|
||||
Assert.Equal(LibraryPathValueType.None, result[0].ValueType);
|
||||
Assert.Equal(string.Empty, result[0].DefaultRepresentation);
|
||||
Assert.False(result[0].IsOptionalByDefault);
|
||||
|
||||
Assert.Equal(LibraryPathPartKind.Separator, result[1].Kind);
|
||||
Assert.Equal(LibraryPathValueType.None, result[1].ValueType);
|
||||
Assert.Equal(string.Empty, result[1].DefaultRepresentation);
|
||||
Assert.False(result[1].IsOptionalByDefault);
|
||||
|
||||
Assert.Equal(LibraryPathPartKind.Artist, result[2].Kind);
|
||||
Assert.Equal(LibraryPathValueType.Text, result[2].ValueType);
|
||||
Assert.Equal("{0}", result[2].DefaultRepresentation);
|
||||
Assert.False(result[2].IsOptionalByDefault);
|
||||
|
||||
Assert.Equal(LibraryPathPartKind.ReleaseType, result[3].Kind);
|
||||
Assert.Equal(LibraryPathValueType.Enum, result[3].ValueType);
|
||||
Assert.Equal("{0}", result[3].DefaultRepresentation);
|
||||
Assert.False(result[3].IsOptionalByDefault);
|
||||
|
||||
Assert.Equal(LibraryPathPartKind.ReleaseYear, result[4].Kind);
|
||||
Assert.Equal(LibraryPathValueType.Year, result[4].ValueType);
|
||||
Assert.Equal("{0}", result[4].DefaultRepresentation);
|
||||
Assert.False(result[4].IsOptionalByDefault);
|
||||
|
||||
Assert.Equal(LibraryPathPartKind.ReleaseName, result[5].Kind);
|
||||
Assert.Equal(LibraryPathValueType.Text, result[5].ValueType);
|
||||
Assert.Equal("{0}", result[5].DefaultRepresentation);
|
||||
Assert.False(result[5].IsOptionalByDefault);
|
||||
|
||||
Assert.Equal(LibraryPathPartKind.TrackNumber, result[6].Kind);
|
||||
Assert.Equal(LibraryPathValueType.Integer, result[6].ValueType);
|
||||
Assert.Equal("{0:00}", result[6].DefaultRepresentation);
|
||||
Assert.False(result[6].IsOptionalByDefault);
|
||||
|
||||
Assert.Equal(LibraryPathPartKind.TrackName, result[7].Kind);
|
||||
Assert.Equal(LibraryPathValueType.Text, result[7].ValueType);
|
||||
Assert.Equal("{0}", result[7].DefaultRepresentation);
|
||||
Assert.False(result[7].IsOptionalByDefault);
|
||||
|
||||
Assert.Equal(LibraryPathPartKind.Extension, result[8].Kind);
|
||||
Assert.Equal(LibraryPathValueType.Text, result[8].ValueType);
|
||||
Assert.Equal("{0}", result[8].DefaultRepresentation);
|
||||
Assert.False(result[8].IsOptionalByDefault);
|
||||
|
||||
Assert.Equal(LibraryPathPartKind.DiscNumber, result[9].Kind);
|
||||
Assert.Equal(LibraryPathValueType.Integer, result[9].ValueType);
|
||||
Assert.Equal("{0:00}", result[9].DefaultRepresentation);
|
||||
Assert.True(result[9].IsOptionalByDefault);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetDefaultTemplate_WhenCalled_ShouldReturnTheExpectedParts()
|
||||
{
|
||||
// Act
|
||||
IReadOnlyList<LibraryPathPart> result = _sut.GetDefaultTemplate().Parts;
|
||||
|
||||
// Assert
|
||||
Assert.Equal(16, result.Count);
|
||||
|
||||
Assert.Equal(LibraryPathPartKind.Artist, result[0].Kind);
|
||||
Assert.Equal("{0}", result[0].Representation);
|
||||
Assert.False(result[0].IsOptional);
|
||||
|
||||
Assert.Equal(LibraryPathPartKind.Separator, result[1].Kind);
|
||||
Assert.Equal(string.Empty, result[1].Representation);
|
||||
Assert.False(result[1].IsOptional);
|
||||
|
||||
Assert.Equal(LibraryPathPartKind.ReleaseType, result[2].Kind);
|
||||
Assert.Equal("{0}", result[2].Representation);
|
||||
Assert.False(result[2].IsOptional);
|
||||
|
||||
Assert.Equal(LibraryPathPartKind.Separator, result[3].Kind);
|
||||
Assert.Equal(string.Empty, result[3].Representation);
|
||||
Assert.False(result[3].IsOptional);
|
||||
|
||||
Assert.Equal(LibraryPathPartKind.ReleaseYear, result[4].Kind);
|
||||
Assert.Equal("{0}", result[4].Representation);
|
||||
Assert.False(result[4].IsOptional);
|
||||
|
||||
Assert.Equal(LibraryPathPartKind.Literal, result[5].Kind);
|
||||
Assert.Equal(" - ", result[5].Representation);
|
||||
Assert.False(result[5].IsOptional);
|
||||
|
||||
Assert.Equal(LibraryPathPartKind.ReleaseName, result[6].Kind);
|
||||
Assert.Equal("{0}", result[6].Representation);
|
||||
Assert.False(result[6].IsOptional);
|
||||
|
||||
Assert.Equal(LibraryPathPartKind.Separator, result[7].Kind);
|
||||
Assert.Equal(string.Empty, result[7].Representation);
|
||||
Assert.True(result[7].IsOptional);
|
||||
|
||||
Assert.Equal(LibraryPathPartKind.Literal, result[8].Kind);
|
||||
Assert.Equal("Disk ", result[8].Representation);
|
||||
Assert.True(result[8].IsOptional);
|
||||
|
||||
Assert.Equal(LibraryPathPartKind.DiscNumber, result[9].Kind);
|
||||
Assert.Equal("{0:00}", result[9].Representation);
|
||||
Assert.True(result[9].IsOptional);
|
||||
|
||||
Assert.Equal(LibraryPathPartKind.Separator, result[10].Kind);
|
||||
Assert.Equal(string.Empty, result[10].Representation);
|
||||
Assert.False(result[10].IsOptional);
|
||||
|
||||
Assert.Equal(LibraryPathPartKind.TrackNumber, result[11].Kind);
|
||||
Assert.Equal("{0:00}", result[11].Representation);
|
||||
Assert.False(result[11].IsOptional);
|
||||
|
||||
Assert.Equal(LibraryPathPartKind.Literal, result[12].Kind);
|
||||
Assert.Equal(" - ", result[12].Representation);
|
||||
Assert.False(result[12].IsOptional);
|
||||
|
||||
Assert.Equal(LibraryPathPartKind.TrackName, result[13].Kind);
|
||||
Assert.Equal("{0}", result[13].Representation);
|
||||
Assert.False(result[13].IsOptional);
|
||||
|
||||
Assert.Equal(LibraryPathPartKind.Literal, result[14].Kind);
|
||||
Assert.Equal(".", result[14].Representation);
|
||||
Assert.False(result[14].IsOptional);
|
||||
|
||||
Assert.Equal(LibraryPathPartKind.Extension, result[15].Kind);
|
||||
Assert.Equal("{0}", result[15].Representation);
|
||||
Assert.False(result[15].IsOptional);
|
||||
}
|
||||
}
|
||||
+224
@@ -0,0 +1,224 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.Jobs;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.Scanners;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.Scanners;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicLibraryTypeScanner"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicLibraryTypeScannerTests
|
||||
{
|
||||
private readonly IMediaLibraryScanJobFactory _mockJobFactory = Substitute.For<IMediaLibraryScanJobFactory>();
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly ScanIdFixture _scanIdFixture = new();
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void SupportedLibraryType_ShouldBeMusic()
|
||||
{
|
||||
// Arrange
|
||||
MusicLibraryTypeScanner sut = new(_mockJobFactory);
|
||||
|
||||
// Act & Assert
|
||||
Assert.Equal(LibraryType.Music, sut.SupportedLibraryType);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateScanJobsForLibrary_WhenCalled_ShouldCreateJobChainWithEnrichmentJobs()
|
||||
{
|
||||
// Arrange
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
TestScanJob discoveryJob = CreateJob<IMusicFileSystemDiscoveryJob>();
|
||||
TestScanJob diffJob = CreateJob<IMediaLibraryScanDiffJob>();
|
||||
TestScanJob hashJob = CreateJob<IMediaLibraryScanHashJob>();
|
||||
TestScanJob metadataExtractionJob = CreateJob<IMusicMetadataExtractionJob>();
|
||||
TestScanJob saveJob = CreateJob<IMediaLibraryScanResultsSaveJob>();
|
||||
TestScanJob invalidationJob = CreateJob<IMediaLibraryScanProviderConfigurationInvalidationJob>();
|
||||
TestScanJob enrichmentJob = CreateJob<IMediaLibraryScanMetadataEnrichmentJob>();
|
||||
TestScanJob artworkEnrichmentJob = CreateJob<IMediaLibraryScanArtworkEnrichmentJob>();
|
||||
MusicLibraryTypeScanner sut = new(_mockJobFactory);
|
||||
|
||||
// Act
|
||||
IMediaLibraryScanDiscoveryJob rootJob = sut.CreateScanJobsForLibrary(libraryId);
|
||||
|
||||
// Assert
|
||||
Assert.Same(discoveryJob, rootJob);
|
||||
Assert.IsAssignableFrom<IMusicFileSystemDiscoveryJob>(rootJob);
|
||||
Assert.Contains(diffJob, discoveryJob.Children);
|
||||
Assert.Contains(discoveryJob, diffJob.Parents);
|
||||
Assert.Contains(hashJob, diffJob.Children);
|
||||
Assert.Contains(diffJob, hashJob.Parents);
|
||||
Assert.Contains(metadataExtractionJob, hashJob.Children);
|
||||
Assert.Contains(hashJob, metadataExtractionJob.Parents);
|
||||
Assert.Contains(saveJob, metadataExtractionJob.Children);
|
||||
Assert.Contains(metadataExtractionJob, saveJob.Parents);
|
||||
Assert.Contains(invalidationJob, saveJob.Children);
|
||||
Assert.Contains(saveJob, invalidationJob.Parents);
|
||||
Assert.Contains(enrichmentJob, invalidationJob.Children);
|
||||
Assert.Contains(invalidationJob, enrichmentJob.Parents);
|
||||
Assert.Contains(artworkEnrichmentJob, enrichmentJob.Children);
|
||||
Assert.Contains(enrichmentJob, artworkEnrichmentJob.Parents);
|
||||
_mockJobFactory.Received(1).CreateJob<IMusicMetadataExtractionJob>(libraryId);
|
||||
_mockJobFactory.Received(1).CreateJob<IMediaLibraryScanMetadataEnrichmentJob>(libraryId);
|
||||
_mockJobFactory.Received(1).CreateJob<IMediaLibraryScanArtworkEnrichmentJob>(libraryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateScanJobsForLibrary_WhenCalled_ShouldReturnTheFileSystemDiscoveryJobAsTheOnlyRoot()
|
||||
{
|
||||
// Arrange
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
TestScanJob discoveryJob = CreateJob<IMusicFileSystemDiscoveryJob>();
|
||||
CreateJob<IMediaLibraryScanDiffJob>();
|
||||
CreateJob<IMediaLibraryScanHashJob>();
|
||||
CreateJob<IMusicMetadataExtractionJob>();
|
||||
CreateJob<IMediaLibraryScanResultsSaveJob>();
|
||||
CreateJob<IMediaLibraryScanProviderConfigurationInvalidationJob>();
|
||||
CreateJob<IMediaLibraryScanMetadataEnrichmentJob>();
|
||||
CreateJob<IMediaLibraryScanArtworkEnrichmentJob>();
|
||||
MusicLibraryTypeScanner sut = new(_mockJobFactory);
|
||||
|
||||
// Act
|
||||
IMediaLibraryScanDiscoveryJob rootJob = sut.CreateScanJobsForLibrary(libraryId);
|
||||
|
||||
// Assert
|
||||
Assert.Same(discoveryJob, rootJob);
|
||||
// The file system discovery job is the only top level job, so nothing else is reachable without it.
|
||||
Assert.Empty(discoveryJob.Parents);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateScanJobsForLibrary_WhenCalled_ShouldMakeTheWholeChainReachableFromTheRoot()
|
||||
{
|
||||
// Arrange
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
TestScanJob discoveryJob = CreateJob<IMusicFileSystemDiscoveryJob>();
|
||||
TestScanJob diffJob = CreateJob<IMediaLibraryScanDiffJob>();
|
||||
TestScanJob hashJob = CreateJob<IMediaLibraryScanHashJob>();
|
||||
TestScanJob metadataExtractionJob = CreateJob<IMusicMetadataExtractionJob>();
|
||||
TestScanJob saveJob = CreateJob<IMediaLibraryScanResultsSaveJob>();
|
||||
TestScanJob invalidationJob = CreateJob<IMediaLibraryScanProviderConfigurationInvalidationJob>();
|
||||
TestScanJob enrichmentJob = CreateJob<IMediaLibraryScanMetadataEnrichmentJob>();
|
||||
TestScanJob artworkEnrichmentJob = CreateJob<IMediaLibraryScanArtworkEnrichmentJob>();
|
||||
MusicLibraryTypeScanner sut = new(_mockJobFactory);
|
||||
|
||||
// Act
|
||||
IMediaLibraryScanDiscoveryJob rootJob = sut.CreateScanJobsForLibrary(libraryId);
|
||||
HashSet<IMediaLibraryScanJob> reachableJobs = GetReachableJobs(rootJob);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(8, reachableJobs.Count);
|
||||
Assert.Contains(discoveryJob, reachableJobs);
|
||||
Assert.Contains(diffJob, reachableJobs);
|
||||
Assert.Contains(hashJob, reachableJobs);
|
||||
Assert.Contains(metadataExtractionJob, reachableJobs);
|
||||
Assert.Contains(saveJob, reachableJobs);
|
||||
Assert.Contains(invalidationJob, reachableJobs);
|
||||
Assert.Contains(enrichmentJob, reachableJobs);
|
||||
Assert.Contains(artworkEnrichmentJob, reachableJobs);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateScanJobsForLibrary_WhenCalled_ShouldCreateJobsForTheLibrary()
|
||||
{
|
||||
// Arrange
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
CreateJob<IMusicFileSystemDiscoveryJob>();
|
||||
CreateJob<IMediaLibraryScanDiffJob>();
|
||||
CreateJob<IMediaLibraryScanHashJob>();
|
||||
CreateJob<IMusicMetadataExtractionJob>();
|
||||
CreateJob<IMediaLibraryScanResultsSaveJob>();
|
||||
CreateJob<IMediaLibraryScanProviderConfigurationInvalidationJob>();
|
||||
CreateJob<IMediaLibraryScanMetadataEnrichmentJob>();
|
||||
CreateJob<IMediaLibraryScanArtworkEnrichmentJob>();
|
||||
MusicLibraryTypeScanner sut = new(_mockJobFactory);
|
||||
|
||||
// Act
|
||||
_ = sut.CreateScanJobsForLibrary(libraryId);
|
||||
|
||||
// Assert
|
||||
_mockJobFactory.Received(1).CreateJob<IMusicFileSystemDiscoveryJob>(libraryId);
|
||||
_mockJobFactory.Received(1).CreateJob<IMediaLibraryScanDiffJob>(libraryId);
|
||||
_mockJobFactory.Received(1).CreateJob<IMediaLibraryScanHashJob>(libraryId);
|
||||
_mockJobFactory.Received(1).CreateJob<IMusicMetadataExtractionJob>(libraryId);
|
||||
_mockJobFactory.Received(1).CreateJob<IMediaLibraryScanResultsSaveJob>(libraryId);
|
||||
_mockJobFactory.Received(1).CreateJob<IMediaLibraryScanProviderConfigurationInvalidationJob>(libraryId);
|
||||
_mockJobFactory.Received(1).CreateJob<IMediaLibraryScanMetadataEnrichmentJob>(libraryId);
|
||||
_mockJobFactory.Received(1).CreateJob<IMediaLibraryScanArtworkEnrichmentJob>(libraryId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Collects every job that is reachable from <paramref name="rootJob"/> through the child relationships.
|
||||
/// </summary>
|
||||
/// <param name="rootJob">The root job of the job graph.</param>
|
||||
/// <returns>The set of reachable jobs.</returns>
|
||||
private static HashSet<IMediaLibraryScanJob> GetReachableJobs(IMediaLibraryScanJob rootJob)
|
||||
{
|
||||
HashSet<IMediaLibraryScanJob> reachableJobs = [];
|
||||
Queue<IMediaLibraryScanJob> jobsToVisit = new();
|
||||
jobsToVisit.Enqueue(rootJob);
|
||||
while (jobsToVisit.Count > 0)
|
||||
{
|
||||
IMediaLibraryScanJob currentJob = jobsToVisit.Dequeue();
|
||||
if (!reachableJobs.Add(currentJob))
|
||||
continue;
|
||||
foreach (IMediaLibraryScanJob childJob in currentJob.Children)
|
||||
jobsToVisit.Enqueue(childJob);
|
||||
}
|
||||
return reachableJobs;
|
||||
}
|
||||
|
||||
private TestScanJob CreateJob<TJob>() where TJob : class, IMediaLibraryScanJob
|
||||
{
|
||||
TestScanJob job = new()
|
||||
{
|
||||
ScanId = _scanIdFixture.Create(),
|
||||
UserId = _userIdFixture.Create(),
|
||||
LibraryId = _libraryIdFixture.Create()
|
||||
};
|
||||
_mockJobFactory.CreateJob<TJob>(Arg.Any<LibraryId>()).Returns((TJob)(object)job);
|
||||
return job;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Concrete test implementation of the abstract <see cref="MediaLibraryScanJob"/> class that satisfies all job interfaces.
|
||||
/// </summary>
|
||||
private sealed class TestScanJob : MediaLibraryScanJob,
|
||||
IMusicFileSystemDiscoveryJob,
|
||||
IMediaLibraryScanDiffJob,
|
||||
IMediaLibraryScanHashJob,
|
||||
IMusicMetadataExtractionJob,
|
||||
IMediaLibraryScanResultsSaveJob,
|
||||
IMediaLibraryScanProviderConfigurationInvalidationJob,
|
||||
IMediaLibraryScanMetadataEnrichmentJob,
|
||||
IMediaLibraryScanArtworkEnrichmentJob
|
||||
{
|
||||
/// <summary>
|
||||
/// Executes the payload of the media library scan job.
|
||||
/// </summary>
|
||||
/// <typeparam name="TInput">The type of the input parameter.</typeparam>
|
||||
/// <param name="id">The unique identifier of the media library scan job.</param>
|
||||
/// <param name="input">The input data to be processed.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
public override Task ExecuteAsync<TInput>(Guid id, TInput input, CancellationToken cancellationToken)
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="AlbumId"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AlbumIdTests
|
||||
{
|
||||
private readonly AlbumIdFixture _albumIdFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void CreateUnique_WhenCalled_ShouldReturnIdWithNonEmptyValue()
|
||||
{
|
||||
// Act
|
||||
AlbumId albumId = AlbumId.CreateUnique();
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(Guid.Empty, albumId.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithValue_ShouldReturnIdWithThatValue()
|
||||
{
|
||||
// Arrange
|
||||
Guid value = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
AlbumId albumId = AlbumId.Create(value);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(value, albumId.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithEmptyGuid_ShouldReturnIdWithEmptyValue()
|
||||
{
|
||||
// Act
|
||||
AlbumId albumId = AlbumId.Create(Guid.Empty);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(Guid.Empty, albumId.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToString_WhenCalled_ShouldReturnTheStringRepresentationOfTheValue()
|
||||
{
|
||||
// Arrange
|
||||
Guid value = Guid.NewGuid();
|
||||
AlbumId albumId = _albumIdFixture.Create(value);
|
||||
|
||||
// Act
|
||||
string? result = albumId.ToString();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(value.ToString(), result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithSameValue_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
Guid value = Guid.NewGuid();
|
||||
AlbumId firstId = _albumIdFixture.Create(value);
|
||||
AlbumId secondId = _albumIdFixture.Create(value);
|
||||
|
||||
// Act
|
||||
bool result = firstId.Equals(secondId);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentValue_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
AlbumId firstId = _albumIdFixture.Create();
|
||||
AlbumId secondId = _albumIdFixture.Create();
|
||||
|
||||
// Act
|
||||
bool result = firstId.Equals(secondId);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
}
|
||||
+230
@@ -0,0 +1,230 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Common.ValueObjects.Metadata;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Common.ValueObjects.Metadata;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="AlbumMetadata"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AlbumMetadataTests
|
||||
{
|
||||
private readonly AlbumMetadataFixture _albumMetadataFixture = new();
|
||||
private readonly GenreFixture _genreFixture = new();
|
||||
private readonly TagFixture _tagFixture = new();
|
||||
private readonly ReleaseInfoFixture _releaseInfoFixture = new();
|
||||
private readonly LanguageInfoFixture _languageInfoFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithValidValues_ShouldCreateMetadataWithAllPropertiesSet()
|
||||
{
|
||||
// Arrange
|
||||
ReleaseInfo releaseInfo = _releaseInfoFixture.Create();
|
||||
Genre genre = _genreFixture.Create(name: "Rock");
|
||||
Tag tag = _tagFixture.Create(name: "classic");
|
||||
LanguageInfo language = _languageInfoFixture.Create(languageCode: "en", languageName: "English");
|
||||
LanguageInfo originalLanguage = _languageInfoFixture.Create(languageCode: "fr", languageName: "French");
|
||||
|
||||
// Act
|
||||
Result<AlbumMetadata> result = AlbumMetadata.Create(
|
||||
"A Night at the Opera",
|
||||
Optional<string>.Some("A Night at the Opera (original)"),
|
||||
Optional<string>.Some("A Night at the Opera (2011 remaster)"),
|
||||
Optional<string>.Some("The fourth studio album by the British rock band Queen."),
|
||||
releaseInfo,
|
||||
[genre],
|
||||
[tag],
|
||||
Optional<LanguageInfo>.Some(language),
|
||||
Optional<LanguageInfo>.Some(originalLanguage),
|
||||
[MusicReleaseType.Album],
|
||||
Optional<MusicReleaseStatus>.Some(MusicReleaseStatus.Official),
|
||||
Optional<int>.Some(2),
|
||||
12);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
AlbumMetadata metadata = result.Value;
|
||||
Assert.Equal("A Night at the Opera", metadata.Title);
|
||||
Assert.Equal(Optional<string>.Some("A Night at the Opera (original)"), metadata.OriginalTitle);
|
||||
Assert.Equal(Optional<string>.Some("A Night at the Opera (2011 remaster)"), metadata.ReleaseTitle);
|
||||
Assert.Equal(Optional<string>.Some("The fourth studio album by the British rock band Queen."), metadata.Description);
|
||||
Assert.Equal(releaseInfo, metadata.ReleaseInfo);
|
||||
Assert.Equal(genre, Assert.Single(metadata.Genres));
|
||||
Assert.Equal(tag, Assert.Single(metadata.Tags));
|
||||
Assert.Equal(Optional<LanguageInfo>.Some(language), metadata.Language);
|
||||
Assert.Equal(Optional<LanguageInfo>.Some(originalLanguage), metadata.OriginalLanguage);
|
||||
Assert.Equal(new[] { MusicReleaseType.Album }, metadata.ReleaseTypes);
|
||||
Assert.Equal(Optional<MusicReleaseStatus>.Some(MusicReleaseStatus.Official), metadata.ReleaseStatus);
|
||||
Assert.Equal(Optional<int>.Some(2), metadata.TotalDiscs);
|
||||
Assert.Equal(12, metadata.TotalTracks);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenOptionalValuesAreAbsent_ShouldCreateMetadataWithoutThem()
|
||||
{
|
||||
// Act
|
||||
Result<AlbumMetadata> result = AlbumMetadata.Create(
|
||||
"A Night at the Opera",
|
||||
Optional<string>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<string>.None(),
|
||||
_releaseInfoFixture.Create(),
|
||||
[],
|
||||
[],
|
||||
Optional<LanguageInfo>.None(),
|
||||
Optional<LanguageInfo>.None(),
|
||||
[],
|
||||
Optional<MusicReleaseStatus>.None(),
|
||||
Optional<int>.None(),
|
||||
12);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
AlbumMetadata metadata = result.Value;
|
||||
Assert.False(metadata.OriginalTitle.HasValue);
|
||||
Assert.False(metadata.ReleaseTitle.HasValue);
|
||||
Assert.False(metadata.Description.HasValue);
|
||||
Assert.False(metadata.Language.HasValue);
|
||||
Assert.False(metadata.OriginalLanguage.HasValue);
|
||||
Assert.Empty(metadata.ReleaseTypes);
|
||||
Assert.False(metadata.ReleaseStatus.HasValue);
|
||||
Assert.False(metadata.TotalDiscs.HasValue);
|
||||
Assert.Empty(metadata.Genres);
|
||||
Assert.Empty(metadata.Tags);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCollectionsArePopulated_ShouldPreserveTheGenresAndTags()
|
||||
{
|
||||
// Arrange
|
||||
Genre firstGenre = _genreFixture.Create(name: "Rock");
|
||||
Genre secondGenre = _genreFixture.Create(name: "Progressive Rock");
|
||||
Tag firstTag = _tagFixture.Create(name: "classic");
|
||||
Tag secondTag = _tagFixture.Create(name: "70s");
|
||||
List<Genre> expectedGenres = [firstGenre, secondGenre];
|
||||
List<Tag> expectedTags = [firstTag, secondTag];
|
||||
|
||||
// Act
|
||||
Result<AlbumMetadata> result = AlbumMetadata.Create(
|
||||
"A Night at the Opera",
|
||||
Optional<string>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<string>.None(),
|
||||
_releaseInfoFixture.Create(),
|
||||
expectedGenres,
|
||||
expectedTags,
|
||||
Optional<LanguageInfo>.None(),
|
||||
Optional<LanguageInfo>.None(),
|
||||
[],
|
||||
Optional<MusicReleaseStatus>.None(),
|
||||
Optional<int>.None(),
|
||||
12);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(expectedGenres, result.Value.Genres);
|
||||
Assert.Equal(expectedTags, result.Value.Tags);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithSameValues_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
ReleaseInfo releaseInfo = _releaseInfoFixture.Create();
|
||||
|
||||
// Act
|
||||
AlbumMetadata firstMetadata = _albumMetadataFixture.Create(
|
||||
title: "A Night at the Opera",
|
||||
originalTitle: Optional<string>.None(),
|
||||
releaseTitle: Optional<string>.Some("A Night at the Opera (2011 remaster)"),
|
||||
description: Optional<string>.None(),
|
||||
releaseInfo: releaseInfo,
|
||||
genres: [_genreFixture.Create(name: "Rock")],
|
||||
tags: [_tagFixture.Create(name: "classic")],
|
||||
language: Optional<LanguageInfo>.None(),
|
||||
originalLanguage: Optional<LanguageInfo>.None(),
|
||||
releaseTypes: [MusicReleaseType.Album],
|
||||
releaseStatus: Optional<MusicReleaseStatus>.Some(MusicReleaseStatus.Official),
|
||||
totalDiscs: Optional<int>.Some(2),
|
||||
totalTracks: 12);
|
||||
AlbumMetadata secondMetadata = _albumMetadataFixture.Create(
|
||||
title: "A Night at the Opera",
|
||||
originalTitle: Optional<string>.None(),
|
||||
releaseTitle: Optional<string>.Some("A Night at the Opera (2011 remaster)"),
|
||||
description: Optional<string>.None(),
|
||||
releaseInfo: releaseInfo,
|
||||
genres: [_genreFixture.Create(name: "Rock")],
|
||||
tags: [_tagFixture.Create(name: "classic")],
|
||||
language: Optional<LanguageInfo>.None(),
|
||||
originalLanguage: Optional<LanguageInfo>.None(),
|
||||
releaseTypes: [MusicReleaseType.Album],
|
||||
releaseStatus: Optional<MusicReleaseStatus>.Some(MusicReleaseStatus.Official),
|
||||
totalDiscs: Optional<int>.Some(2),
|
||||
totalTracks: 12);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(firstMetadata, secondMetadata);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentTitle_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
ReleaseInfo releaseInfo = _releaseInfoFixture.Create();
|
||||
|
||||
// Act
|
||||
AlbumMetadata firstMetadata = _albumMetadataFixture.Create(title: "A Night at the Opera", releaseInfo: releaseInfo);
|
||||
AlbumMetadata secondMetadata = _albumMetadataFixture.Create(title: "A Day at the Races", releaseInfo: releaseInfo);
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstMetadata, secondMetadata);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentReleaseType_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
ReleaseInfo releaseInfo = _releaseInfoFixture.Create();
|
||||
|
||||
// Act
|
||||
AlbumMetadata firstMetadata = _albumMetadataFixture.Create(
|
||||
title: "A Night at the Opera",
|
||||
releaseInfo: releaseInfo,
|
||||
releaseTypes: [MusicReleaseType.Album]);
|
||||
AlbumMetadata secondMetadata = _albumMetadataFixture.Create(
|
||||
title: "A Night at the Opera",
|
||||
releaseInfo: releaseInfo,
|
||||
releaseTypes: [MusicReleaseType.Single]);
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstMetadata, secondMetadata);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentTotalTracks_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
ReleaseInfo releaseInfo = _releaseInfoFixture.Create();
|
||||
|
||||
// Act
|
||||
AlbumMetadata firstMetadata = _albumMetadataFixture.Create(
|
||||
title: "A Night at the Opera",
|
||||
releaseInfo: releaseInfo,
|
||||
totalTracks: 12);
|
||||
AlbumMetadata secondMetadata = _albumMetadataFixture.Create(
|
||||
title: "A Night at the Opera",
|
||||
releaseInfo: releaseInfo,
|
||||
totalTracks: 11);
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstMetadata, secondMetadata);
|
||||
}
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ArtistId"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ArtistIdTests
|
||||
{
|
||||
private readonly ArtistIdFixture _artistIdFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void CreateUnique_WhenCalled_ShouldReturnIdWithNonEmptyValue()
|
||||
{
|
||||
// Act
|
||||
ArtistId artistId = ArtistId.CreateUnique();
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(Guid.Empty, artistId.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithValue_ShouldReturnIdWithThatValue()
|
||||
{
|
||||
// Arrange
|
||||
Guid value = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
ArtistId artistId = ArtistId.Create(value);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(value, artistId.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithEmptyGuid_ShouldReturnIdWithEmptyValue()
|
||||
{
|
||||
// Act
|
||||
ArtistId artistId = ArtistId.Create(Guid.Empty);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(Guid.Empty, artistId.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToString_WhenCalled_ShouldReturnTheStringRepresentationOfTheValue()
|
||||
{
|
||||
// Arrange
|
||||
Guid value = Guid.NewGuid();
|
||||
ArtistId artistId = _artistIdFixture.Create(value);
|
||||
|
||||
// Act
|
||||
string? result = artistId.ToString();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(value.ToString(), result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithSameValue_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
Guid value = Guid.NewGuid();
|
||||
ArtistId firstId = _artistIdFixture.Create(value);
|
||||
ArtistId secondId = _artistIdFixture.Create(value);
|
||||
|
||||
// Act
|
||||
bool result = firstId.Equals(secondId);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentValue_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
ArtistId firstId = _artistIdFixture.Create();
|
||||
ArtistId secondId = _artistIdFixture.Create();
|
||||
|
||||
// Act
|
||||
bool result = firstId.Equals(secondId);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
}
|
||||
+109
@@ -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);
|
||||
}
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
#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="Isrc"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class IsrcTests
|
||||
{
|
||||
private readonly IsrcFixture _isrcFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithValidIsrc_ShouldCreateIsrc()
|
||||
{
|
||||
// Act
|
||||
Result<Isrc> result = Isrc.Create("USRC17607839");
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal("USRC17607839", result.Value.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenValueHasLowercaseAndWhitespace_ShouldNormalizeToUppercaseTrimmed()
|
||||
{
|
||||
// Act
|
||||
Result<Isrc> result = Isrc.Create(" usrc17607839 ");
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal("USRC17607839", result.Value.Value);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // Null ISRC value.
|
||||
[InlineData("")] // Empty ISRC value.
|
||||
[InlineData(" ")] // Whitespace ISRC value.
|
||||
public void Create_WhenValueIsNullOrWhitespace_ShouldReturnError(string? value)
|
||||
{
|
||||
// Act
|
||||
Result<Isrc> result = Isrc.Create(value!);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(DomainErrors.Music.IsrcValueCannotBeEmpty, result.FirstError);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("USRC1760783")] // Too short.
|
||||
[InlineData("USRC176078399")] // Too long.
|
||||
[InlineData("1SRC17607839")] // Country code does not start with two letters.
|
||||
[InlineData("USRC1760783X")] // Designation segment is not purely numeric.
|
||||
[InlineData("USRC-7607839")] // Contains an invalid character.
|
||||
public void Create_WhenValueHasInvalidFormat_ShouldReturnError(string value)
|
||||
{
|
||||
// Act
|
||||
Result<Isrc> result = Isrc.Create(value);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(DomainErrors.Music.IsrcInvalidFormat, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithSameValue_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
Isrc firstIsrc = _isrcFixture.Create(value: "USRC17607839");
|
||||
Isrc secondIsrc = _isrcFixture.Create(value: "USRC17607839");
|
||||
|
||||
// Act
|
||||
bool result = firstIsrc.Equals(secondIsrc);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentValue_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
Isrc firstIsrc = _isrcFixture.Create(value: "USRC17607839");
|
||||
Isrc secondIsrc = _isrcFixture.Create(value: "GBAYE0000001");
|
||||
|
||||
// Act
|
||||
bool result = firstIsrc.Equals(secondIsrc);
|
||||
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
#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;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicArea"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicAreaTests
|
||||
{
|
||||
private readonly MusicAreaFixture _musicAreaFixture = new();
|
||||
private readonly MusicBrainzIdFixture _musicBrainzIdFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithValidValues_ShouldCreateMusicAreaWithAllPropertiesSet()
|
||||
{
|
||||
// Arrange
|
||||
MusicBrainzId areaId = _musicBrainzIdFixture.Create(value: Guid.Parse("f0e9c1a2-0000-0000-0000-000000000000"));
|
||||
|
||||
// Act
|
||||
Result<MusicArea> result = MusicArea.Create(
|
||||
areaId,
|
||||
"United Kingdom",
|
||||
Optional<string>.Some("UK"),
|
||||
Optional<string>.Some("The United Kingdom of Great Britain and Northern Ireland"),
|
||||
Optional<string>.Some("Country"),
|
||||
Optional<string>.Some("GB"));
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(areaId, result.Value.MusicBrainzAreaId);
|
||||
Assert.Equal("United Kingdom", result.Value.Name);
|
||||
Assert.Equal(Optional<string>.Some("UK"), result.Value.SortName);
|
||||
Assert.Equal(Optional<string>.Some("The United Kingdom of Great Britain and Northern Ireland"), result.Value.Disambiguation);
|
||||
Assert.Equal(Optional<string>.Some("Country"), result.Value.Type);
|
||||
Assert.Equal(Optional<string>.Some("GB"), result.Value.Iso3166Code);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenNameHasSurroundingWhitespace_ShouldTrimIt()
|
||||
{
|
||||
// Act
|
||||
Result<MusicArea> result = MusicArea.Create(
|
||||
_musicBrainzIdFixture.Create(),
|
||||
" United Kingdom ",
|
||||
Optional<string>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<string>.None());
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal("United Kingdom", result.Value.Name);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // Null area name.
|
||||
[InlineData("")] // Empty area name.
|
||||
[InlineData(" ")] // Whitespace area name.
|
||||
public void Create_WhenNameIsNullOrWhitespace_ShouldReturnError(string? name)
|
||||
{
|
||||
// Act
|
||||
Result<MusicArea> result = MusicArea.Create(
|
||||
_musicBrainzIdFixture.Create(),
|
||||
name!,
|
||||
Optional<string>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<string>.None());
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(DomainErrors.Music.AreaNameCannotBeEmpty, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenOptionalValuesAreAbsent_ShouldCreateMusicAreaWithoutThem()
|
||||
{
|
||||
// Act
|
||||
Result<MusicArea> result = MusicArea.Create(
|
||||
_musicBrainzIdFixture.Create(),
|
||||
"United Kingdom",
|
||||
Optional<string>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<string>.None());
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.False(result.Value.SortName.HasValue);
|
||||
Assert.False(result.Value.Disambiguation.HasValue);
|
||||
Assert.False(result.Value.Type.HasValue);
|
||||
Assert.False(result.Value.Iso3166Code.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithSameValues_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
MusicArea firstArea = _musicAreaFixture.Create();
|
||||
|
||||
// Act
|
||||
MusicArea secondArea = _musicAreaFixture.Create(
|
||||
musicBrainzAreaId: firstArea.MusicBrainzAreaId,
|
||||
name: firstArea.Name,
|
||||
sortName: firstArea.SortName,
|
||||
disambiguation: firstArea.Disambiguation,
|
||||
type: firstArea.Type,
|
||||
iso3166Code: firstArea.Iso3166Code);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(firstArea, secondArea);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentMusicBrainzAreaId_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
MusicArea firstArea = _musicAreaFixture.Create(musicBrainzAreaId: _musicBrainzIdFixture.Create(value: Guid.Parse("11111111-1111-1111-1111-111111111111")));
|
||||
|
||||
// Act
|
||||
MusicArea secondArea = _musicAreaFixture.Create(musicBrainzAreaId: _musicBrainzIdFixture.Create(value: Guid.Parse("22222222-2222-2222-2222-222222222222")));
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstArea, secondArea);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentName_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
MusicArea firstArea = _musicAreaFixture.Create(name: "United Kingdom");
|
||||
|
||||
// Act
|
||||
MusicArea secondArea = _musicAreaFixture.Create(name: "France");
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstArea, secondArea);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentSortName_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
MusicArea firstArea = _musicAreaFixture.Create(sortName: Optional<string>.Some("UK"));
|
||||
|
||||
// Act
|
||||
MusicArea secondArea = _musicAreaFixture.Create(sortName: Optional<string>.Some("GB"));
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstArea, secondArea);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentDisambiguation_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
MusicArea firstArea = _musicAreaFixture.Create(disambiguation: Optional<string>.Some("The country"));
|
||||
|
||||
// Act
|
||||
MusicArea secondArea = _musicAreaFixture.Create(disambiguation: Optional<string>.Some("The region"));
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstArea, secondArea);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentType_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
MusicArea firstArea = _musicAreaFixture.Create(type: Optional<string>.Some("Country"));
|
||||
|
||||
// Act
|
||||
MusicArea secondArea = _musicAreaFixture.Create(type: Optional<string>.Some("City"));
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstArea, secondArea);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentIso3166Code_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
MusicArea firstArea = _musicAreaFixture.Create(iso3166Code: Optional<string>.Some("GB"));
|
||||
|
||||
// Act
|
||||
MusicArea secondArea = _musicAreaFixture.Create(iso3166Code: Optional<string>.Some("FR"));
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstArea, secondArea);
|
||||
}
|
||||
}
|
||||
+238
@@ -0,0 +1,238 @@
|
||||
#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;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicArtistAlias"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicArtistAliasTests
|
||||
{
|
||||
private readonly MusicArtistAliasFixture _musicArtistAliasFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithValidValues_ShouldCreateAliasWithAllPropertiesSet()
|
||||
{
|
||||
// Arrange
|
||||
DateOnly beginDate = new(1970, 1, 1);
|
||||
DateOnly endDate = new(1991, 1, 1);
|
||||
|
||||
// Act
|
||||
Result<MusicArtistAlias> result = MusicArtistAlias.Create(
|
||||
"Freddie Mercury",
|
||||
Optional<string>.Some("Mercury, Freddie"),
|
||||
Optional<string>.Some("Artist name"),
|
||||
Optional<string>.Some("en"),
|
||||
isPrimary: true,
|
||||
Optional<DateOnly>.Some(beginDate),
|
||||
Optional<DateOnly>.Some(endDate),
|
||||
isEnded: true);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal("Freddie Mercury", result.Value.Name);
|
||||
Assert.Equal(Optional<string>.Some("Mercury, Freddie"), result.Value.SortName);
|
||||
Assert.Equal(Optional<string>.Some("Artist name"), result.Value.Type);
|
||||
Assert.Equal(Optional<string>.Some("en"), result.Value.Locale);
|
||||
Assert.True(result.Value.IsPrimary);
|
||||
Assert.Equal(Optional<DateOnly>.Some(beginDate), result.Value.BeginDate);
|
||||
Assert.Equal(Optional<DateOnly>.Some(endDate), result.Value.EndDate);
|
||||
Assert.True(result.Value.IsEnded);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenNameHasSurroundingWhitespace_ShouldTrimIt()
|
||||
{
|
||||
// Act
|
||||
Result<MusicArtistAlias> result = MusicArtistAlias.Create(
|
||||
" Freddie Mercury ",
|
||||
Optional<string>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<string>.None(),
|
||||
isPrimary: false,
|
||||
Optional<DateOnly>.None(),
|
||||
Optional<DateOnly>.None(),
|
||||
isEnded: false);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal("Freddie Mercury", result.Value.Name);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // Null alias name.
|
||||
[InlineData("")] // Empty alias name.
|
||||
[InlineData(" ")] // Whitespace alias name.
|
||||
public void Create_WhenNameIsNullOrWhitespace_ShouldReturnError(string? name)
|
||||
{
|
||||
// Act
|
||||
Result<MusicArtistAlias> result = MusicArtistAlias.Create(
|
||||
name!,
|
||||
Optional<string>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<string>.None(),
|
||||
isPrimary: false,
|
||||
Optional<DateOnly>.None(),
|
||||
Optional<DateOnly>.None(),
|
||||
isEnded: false);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(DomainErrors.Music.ArtistAliasNameCannotBeEmpty, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenOptionalValuesAreAbsent_ShouldCreateAliasWithoutThem()
|
||||
{
|
||||
// Act
|
||||
Result<MusicArtistAlias> result = MusicArtistAlias.Create(
|
||||
"Freddie Mercury",
|
||||
Optional<string>.None(),
|
||||
Optional<string>.None(),
|
||||
Optional<string>.None(),
|
||||
isPrimary: false,
|
||||
Optional<DateOnly>.None(),
|
||||
Optional<DateOnly>.None(),
|
||||
isEnded: false);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.False(result.Value.SortName.HasValue);
|
||||
Assert.False(result.Value.Type.HasValue);
|
||||
Assert.False(result.Value.Locale.HasValue);
|
||||
Assert.False(result.Value.BeginDate.HasValue);
|
||||
Assert.False(result.Value.EndDate.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithSameValues_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
MusicArtistAlias firstAlias = _musicArtistAliasFixture.Create();
|
||||
|
||||
// Act
|
||||
MusicArtistAlias secondAlias = _musicArtistAliasFixture.Create(
|
||||
name: firstAlias.Name,
|
||||
sortName: firstAlias.SortName,
|
||||
type: firstAlias.Type,
|
||||
locale: firstAlias.Locale,
|
||||
isPrimary: firstAlias.IsPrimary,
|
||||
beginDate: firstAlias.BeginDate,
|
||||
endDate: firstAlias.EndDate,
|
||||
isEnded: firstAlias.IsEnded);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(firstAlias, secondAlias);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentName_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
MusicArtistAlias firstAlias = _musicArtistAliasFixture.Create(name: "Freddie Mercury");
|
||||
|
||||
// Act
|
||||
MusicArtistAlias secondAlias = _musicArtistAliasFixture.Create(name: "Farrokh Bulsara");
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstAlias, secondAlias);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentSortName_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
MusicArtistAlias firstAlias = _musicArtistAliasFixture.Create(sortName: Optional<string>.Some("Mercury, Freddie"));
|
||||
|
||||
// Act
|
||||
MusicArtistAlias secondAlias = _musicArtistAliasFixture.Create(sortName: Optional<string>.Some("Bulsara, Farrokh"));
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstAlias, secondAlias);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentType_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
MusicArtistAlias firstAlias = _musicArtistAliasFixture.Create(type: Optional<string>.Some("Artist name"));
|
||||
|
||||
// Act
|
||||
MusicArtistAlias secondAlias = _musicArtistAliasFixture.Create(type: Optional<string>.Some("Search hint"));
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstAlias, secondAlias);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentLocale_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
MusicArtistAlias firstAlias = _musicArtistAliasFixture.Create(locale: Optional<string>.Some("en"));
|
||||
|
||||
// Act
|
||||
MusicArtistAlias secondAlias = _musicArtistAliasFixture.Create(locale: Optional<string>.Some("fr"));
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstAlias, secondAlias);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentIsPrimary_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
MusicArtistAlias firstAlias = _musicArtistAliasFixture.Create(isPrimary: true);
|
||||
|
||||
// Act
|
||||
MusicArtistAlias secondAlias = _musicArtistAliasFixture.Create(isPrimary: false);
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstAlias, secondAlias);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentBeginDate_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
MusicArtistAlias firstAlias = _musicArtistAliasFixture.Create(beginDate: Optional<DateOnly>.Some(new DateOnly(1970, 1, 1)));
|
||||
|
||||
// Act
|
||||
MusicArtistAlias secondAlias = _musicArtistAliasFixture.Create(beginDate: Optional<DateOnly>.Some(new DateOnly(1980, 1, 1)));
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstAlias, secondAlias);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentEndDate_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
MusicArtistAlias firstAlias = _musicArtistAliasFixture.Create(endDate: Optional<DateOnly>.Some(new DateOnly(1991, 1, 1)));
|
||||
|
||||
// Act
|
||||
MusicArtistAlias secondAlias = _musicArtistAliasFixture.Create(endDate: Optional<DateOnly>.Some(new DateOnly(2000, 1, 1)));
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstAlias, secondAlias);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentIsEnded_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
MusicArtistAlias firstAlias = _musicArtistAliasFixture.Create(isEnded: true);
|
||||
|
||||
// Act
|
||||
MusicArtistAlias secondAlias = _musicArtistAliasFixture.Create(isEnded: false);
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstAlias, secondAlias);
|
||||
}
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicBrainzId"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicBrainzIdTests
|
||||
{
|
||||
private readonly MusicBrainzIdFixture _musicBrainzIdFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithValue_ShouldReturnIdWithThatValue()
|
||||
{
|
||||
// Arrange
|
||||
Guid value = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
MusicBrainzId musicBrainzId = MusicBrainzId.Create(value);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(value, musicBrainzId.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithSameValue_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
Guid value = Guid.NewGuid();
|
||||
MusicBrainzId firstId = _musicBrainzIdFixture.Create(value);
|
||||
MusicBrainzId secondId = _musicBrainzIdFixture.Create(value);
|
||||
|
||||
// Act
|
||||
bool result = firstId.Equals(secondId);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentValue_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
MusicBrainzId firstId = _musicBrainzIdFixture.Create();
|
||||
MusicBrainzId secondId = _musicBrainzIdFixture.Create();
|
||||
|
||||
// Act
|
||||
bool result = firstId.Equals(secondId);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
}
|
||||
+230
@@ -0,0 +1,230 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicLibraryPathMetadata"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicLibraryPathMetadataTests
|
||||
{
|
||||
private readonly MusicLibraryPathMetadataFixture _musicLibraryPathMetadataFixture = new();
|
||||
private readonly ParsedLibraryPathFixture _parsedLibraryPathFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void FromParsedLibraryPath_WhenAllValuesAreCaptured_ShouldMapAllFields()
|
||||
{
|
||||
// Arrange
|
||||
ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
|
||||
{
|
||||
[LibraryPathPartKind.Artist] = "Queen",
|
||||
[LibraryPathPartKind.ReleaseType] = "Album",
|
||||
[LibraryPathPartKind.ReleaseYear] = "1975",
|
||||
[LibraryPathPartKind.ReleaseName] = "A Night at the Opera",
|
||||
[LibraryPathPartKind.TrackNumber] = "11",
|
||||
[LibraryPathPartKind.DiscNumber] = "1",
|
||||
[LibraryPathPartKind.TrackName] = "Bohemian Rhapsody"
|
||||
});
|
||||
|
||||
// Act
|
||||
MusicLibraryPathMetadata result = MusicLibraryPathMetadata.FromParsedLibraryPath(parsedPath);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Queen", result.ArtistName.Value);
|
||||
Assert.Equal(MusicReleaseType.Album, result.ReleaseType.Value);
|
||||
Assert.Equal(1975, result.ReleaseYear.Value);
|
||||
Assert.Equal("A Night at the Opera", result.ReleaseName.Value);
|
||||
Assert.Equal(11, result.TrackNumber.Value);
|
||||
Assert.Equal(1, result.DiscNumber.Value);
|
||||
Assert.Equal("Bohemian Rhapsody", result.TrackTitle.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FromParsedLibraryPath_WhenReleaseTypeIsRecognized_ShouldParseItCaseInsensitively()
|
||||
{
|
||||
// Arrange
|
||||
ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
|
||||
{
|
||||
[LibraryPathPartKind.ReleaseType] = "album"
|
||||
});
|
||||
|
||||
// Act
|
||||
MusicLibraryPathMetadata result = MusicLibraryPathMetadata.FromParsedLibraryPath(parsedPath);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.ReleaseType.HasValue);
|
||||
Assert.Equal(MusicReleaseType.Album, result.ReleaseType.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FromParsedLibraryPath_WhenReleaseTypeIsNotRecognized_ShouldFallBackToOther()
|
||||
{
|
||||
// Arrange
|
||||
ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
|
||||
{
|
||||
[LibraryPathPartKind.ReleaseType] = "not a release type"
|
||||
});
|
||||
|
||||
// Act
|
||||
MusicLibraryPathMetadata result = MusicLibraryPathMetadata.FromParsedLibraryPath(parsedPath);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.ReleaseType.HasValue);
|
||||
Assert.Equal(MusicReleaseType.Other, result.ReleaseType.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FromParsedLibraryPath_WhenReleaseTypeIsAbsent_ShouldLeaveItUnset()
|
||||
{
|
||||
// Arrange
|
||||
ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
|
||||
{
|
||||
[LibraryPathPartKind.Artist] = "Queen"
|
||||
});
|
||||
|
||||
// Act
|
||||
MusicLibraryPathMetadata result = MusicLibraryPathMetadata.FromParsedLibraryPath(parsedPath);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.ReleaseType.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FromParsedLibraryPath_WhenValuesAreAbsent_ShouldLeaveThemUnset()
|
||||
{
|
||||
// Arrange
|
||||
ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(includeValues: false);
|
||||
|
||||
// Act
|
||||
MusicLibraryPathMetadata result = MusicLibraryPathMetadata.FromParsedLibraryPath(parsedPath);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.ArtistName.HasValue);
|
||||
Assert.False(result.ReleaseType.HasValue);
|
||||
Assert.False(result.ReleaseYear.HasValue);
|
||||
Assert.False(result.ReleaseName.HasValue);
|
||||
Assert.False(result.TrackNumber.HasValue);
|
||||
Assert.False(result.DiscNumber.HasValue);
|
||||
Assert.False(result.TrackTitle.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithSameValues_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
MusicLibraryPathMetadata firstMetadata = _musicLibraryPathMetadataFixture.Create();
|
||||
|
||||
// Act
|
||||
MusicLibraryPathMetadata secondMetadata = _musicLibraryPathMetadataFixture.Create(
|
||||
artistName: firstMetadata.ArtistName.Value,
|
||||
releaseType: firstMetadata.ReleaseType.Value,
|
||||
releaseYear: firstMetadata.ReleaseYear.Value,
|
||||
releaseName: firstMetadata.ReleaseName.Value,
|
||||
trackNumber: firstMetadata.TrackNumber.Value,
|
||||
discNumber: firstMetadata.DiscNumber.Value,
|
||||
trackTitle: firstMetadata.TrackTitle.Value);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(firstMetadata, secondMetadata);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentArtistName_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
MusicLibraryPathMetadata firstMetadata = _musicLibraryPathMetadataFixture.Create(artistName: "Queen");
|
||||
|
||||
// Act
|
||||
MusicLibraryPathMetadata secondMetadata = _musicLibraryPathMetadataFixture.Create(artistName: "Pink Floyd");
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstMetadata, secondMetadata);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentReleaseType_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
MusicLibraryPathMetadata firstMetadata = _musicLibraryPathMetadataFixture.Create(releaseType: MusicReleaseType.Album);
|
||||
|
||||
// Act
|
||||
MusicLibraryPathMetadata secondMetadata = _musicLibraryPathMetadataFixture.Create(releaseType: MusicReleaseType.Single);
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstMetadata, secondMetadata);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentReleaseYear_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
MusicLibraryPathMetadata firstMetadata = _musicLibraryPathMetadataFixture.Create(releaseYear: 1975);
|
||||
|
||||
// Act
|
||||
MusicLibraryPathMetadata secondMetadata = _musicLibraryPathMetadataFixture.Create(releaseYear: 1980);
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstMetadata, secondMetadata);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentReleaseName_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
MusicLibraryPathMetadata firstMetadata = _musicLibraryPathMetadataFixture.Create(releaseName: "A Night at the Opera");
|
||||
|
||||
// Act
|
||||
MusicLibraryPathMetadata secondMetadata = _musicLibraryPathMetadataFixture.Create(releaseName: "The Game");
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstMetadata, secondMetadata);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentTrackNumber_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
MusicLibraryPathMetadata firstMetadata = _musicLibraryPathMetadataFixture.Create(trackNumber: 11);
|
||||
|
||||
// Act
|
||||
MusicLibraryPathMetadata secondMetadata = _musicLibraryPathMetadataFixture.Create(trackNumber: 12);
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstMetadata, secondMetadata);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentDiscNumber_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
MusicLibraryPathMetadata firstMetadata = _musicLibraryPathMetadataFixture.Create(discNumber: 1);
|
||||
|
||||
// Act
|
||||
MusicLibraryPathMetadata secondMetadata = _musicLibraryPathMetadataFixture.Create(discNumber: 2);
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstMetadata, secondMetadata);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentTrackTitle_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
MusicLibraryPathMetadata firstMetadata = _musicLibraryPathMetadataFixture.Create(trackTitle: "Bohemian Rhapsody");
|
||||
|
||||
// Act
|
||||
MusicLibraryPathMetadata secondMetadata = _musicLibraryPathMetadataFixture.Create(trackTitle: "Love of My Life");
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstMetadata, secondMetadata);
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicMediaContributor"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicMediaContributorTests
|
||||
{
|
||||
private readonly MusicMediaContributorFixture _musicMediaContributorFixture = new();
|
||||
private readonly MediaContributorIdFixture _mediaContributorIdFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalled_ShouldReturnContributorWithContributorIdAndRole()
|
||||
{
|
||||
// Arrange
|
||||
MediaContributorId contributorId = _mediaContributorIdFixture.Create();
|
||||
|
||||
// Act
|
||||
MusicMediaContributor contributor = _musicMediaContributorFixture.Create(contributorId: contributorId, role: MediaContributorRole.Composer);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(contributorId, contributor.ContributorId);
|
||||
Assert.Equal(MediaContributorRole.Composer, contributor.Role);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithSameContributorIdAndRole_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
MediaContributorId contributorId = _mediaContributorIdFixture.Create();
|
||||
MusicMediaContributor firstContributor = _musicMediaContributorFixture.Create(contributorId: contributorId, role: MediaContributorRole.Composer);
|
||||
MusicMediaContributor secondContributor = _musicMediaContributorFixture.Create(contributorId: contributorId, role: MediaContributorRole.Composer);
|
||||
|
||||
// Act
|
||||
bool result = firstContributor.Equals(secondContributor);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentRole_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
MediaContributorId contributorId = _mediaContributorIdFixture.Create();
|
||||
MusicMediaContributor firstContributor = _musicMediaContributorFixture.Create(contributorId: contributorId, role: MediaContributorRole.Composer);
|
||||
MusicMediaContributor secondContributor = _musicMediaContributorFixture.Create(contributorId: contributorId, role: MediaContributorRole.Producer);
|
||||
|
||||
// Act
|
||||
bool result = firstContributor.Equals(secondContributor);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentContributorId_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
MusicMediaContributor firstContributor = _musicMediaContributorFixture.Create(contributorId: _mediaContributorIdFixture.Create(), role: MediaContributorRole.Composer);
|
||||
MusicMediaContributor secondContributor = _musicMediaContributorFixture.Create(contributorId: _mediaContributorIdFixture.Create(), role: MediaContributorRole.Composer);
|
||||
|
||||
// Act
|
||||
bool result = firstContributor.Equals(secondContributor);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
}
|
||||
+201
@@ -0,0 +1,201 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Common.ValueObjects.Metadata;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Common.ValueObjects.Metadata;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicWork"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicWorkTests
|
||||
{
|
||||
private readonly MusicWorkFixture _musicWorkFixture = new();
|
||||
private readonly MusicBrainzIdFixture _musicBrainzIdFixture = new();
|
||||
private readonly LanguageInfoFixture _languageInfoFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithValidValues_ShouldCreateWorkWithAllPropertiesSet()
|
||||
{
|
||||
// Arrange
|
||||
MusicBrainzId workId = _musicBrainzIdFixture.Create(value: Guid.Parse("f0e9c1a2-0000-0000-0000-000000000000"));
|
||||
LanguageInfo language = _languageInfoFixture.Create(languageCode: "en", languageName: "English");
|
||||
|
||||
// Act
|
||||
Result<MusicWork> result = MusicWork.Create(
|
||||
workId,
|
||||
"Bohemian Rhapsody",
|
||||
Optional<string>.Some("Song"),
|
||||
[language],
|
||||
["T1234567890"]);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(workId, result.Value.MusicBrainzWorkId);
|
||||
Assert.Equal("Bohemian Rhapsody", result.Value.Title);
|
||||
Assert.Equal(Optional<string>.Some("Song"), result.Value.Type);
|
||||
Assert.Equal([language], result.Value.Languages);
|
||||
Assert.Equal(["T1234567890"], result.Value.Iswcs);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenTitleHasSurroundingWhitespace_ShouldTrimIt()
|
||||
{
|
||||
// Act
|
||||
Result<MusicWork> result = MusicWork.Create(
|
||||
_musicBrainzIdFixture.Create(),
|
||||
" Bohemian Rhapsody ",
|
||||
Optional<string>.None(),
|
||||
[],
|
||||
[]);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal("Bohemian Rhapsody", result.Value.Title);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // Null work title.
|
||||
[InlineData("")] // Empty work title.
|
||||
[InlineData(" ")] // Whitespace work title.
|
||||
public void Create_WhenTitleIsNullOrWhitespace_ShouldReturnError(string? title)
|
||||
{
|
||||
// Act
|
||||
Result<MusicWork> result = MusicWork.Create(
|
||||
_musicBrainzIdFixture.Create(),
|
||||
title!,
|
||||
Optional<string>.None(),
|
||||
[],
|
||||
[]);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(DomainErrors.Music.WorkTitleCannotBeEmpty, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenOptionalAndCollectionValuesAreAbsent_ShouldCreateWorkWithoutThem()
|
||||
{
|
||||
// Act
|
||||
Result<MusicWork> result = MusicWork.Create(
|
||||
_musicBrainzIdFixture.Create(),
|
||||
"Bohemian Rhapsody",
|
||||
Optional<string>.None(),
|
||||
[],
|
||||
[]);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.False(result.Value.Type.HasValue);
|
||||
Assert.Empty(result.Value.Languages);
|
||||
Assert.Empty(result.Value.Iswcs);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithSameValues_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
MusicWork firstWork = _musicWorkFixture.Create();
|
||||
|
||||
// Act
|
||||
MusicWork secondWork = _musicWorkFixture.Create(
|
||||
musicBrainzWorkId: firstWork.MusicBrainzWorkId,
|
||||
title: firstWork.Title,
|
||||
type: firstWork.Type,
|
||||
languages: [.. firstWork.Languages],
|
||||
iswcs: [.. firstWork.Iswcs]);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(firstWork, secondWork);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentMusicBrainzWorkId_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
MusicWork firstWork = _musicWorkFixture.Create(musicBrainzWorkId: _musicBrainzIdFixture.Create(value: Guid.Parse("11111111-1111-1111-1111-111111111111")));
|
||||
|
||||
// Act
|
||||
MusicWork secondWork = _musicWorkFixture.Create(musicBrainzWorkId: _musicBrainzIdFixture.Create(value: Guid.Parse("22222222-2222-2222-2222-222222222222")));
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstWork, secondWork);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentTitle_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
MusicWork firstWork = _musicWorkFixture.Create(title: "Bohemian Rhapsody");
|
||||
|
||||
// Act
|
||||
MusicWork secondWork = _musicWorkFixture.Create(title: "Love of My Life");
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstWork, secondWork);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentType_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
MusicWork firstWork = _musicWorkFixture.Create(type: Optional<string>.Some("Song"));
|
||||
|
||||
// Act
|
||||
MusicWork secondWork = _musicWorkFixture.Create(type: Optional<string>.Some("Instrumental"));
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstWork, secondWork);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentLanguages_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
LanguageInfo english = _languageInfoFixture.Create(languageCode: "en", languageName: "English");
|
||||
LanguageInfo french = _languageInfoFixture.Create(languageCode: "fr", languageName: "French");
|
||||
MusicWork firstWork = _musicWorkFixture.Create(languages: [english]);
|
||||
|
||||
// Act
|
||||
MusicWork secondWork = _musicWorkFixture.Create(languages: [french]);
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstWork, secondWork);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentIswcs_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
MusicWork firstWork = _musicWorkFixture.Create(iswcs: ["T1234567890"]);
|
||||
|
||||
// Act
|
||||
MusicWork secondWork = _musicWorkFixture.Create(iswcs: ["T0987654321"]);
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstWork, secondWork);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentLanguageOrder_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
LanguageInfo english = _languageInfoFixture.Create(languageCode: "en", languageName: "English");
|
||||
LanguageInfo french = _languageInfoFixture.Create(languageCode: "fr", languageName: "French");
|
||||
MusicWork firstWork = _musicWorkFixture.Create(languages: [english, french]);
|
||||
|
||||
// Act
|
||||
MusicWork secondWork = _musicWorkFixture.Create(languages: [french, english]);
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstWork, secondWork);
|
||||
}
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="TrackId"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class TrackIdTests
|
||||
{
|
||||
private readonly TrackIdFixture _trackIdFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void CreateUnique_WhenCalled_ShouldReturnIdWithNonEmptyValue()
|
||||
{
|
||||
// Act
|
||||
TrackId trackId = TrackId.CreateUnique();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(trackId);
|
||||
Assert.NotEqual(default, trackId.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithValue_ShouldReturnIdWithThatValue()
|
||||
{
|
||||
// Arrange
|
||||
Guid value = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
TrackId trackId = TrackId.Create(value);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(value, trackId.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithSameValue_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
Guid value = Guid.NewGuid();
|
||||
TrackId firstId = _trackIdFixture.Create(value);
|
||||
TrackId secondId = _trackIdFixture.Create(value);
|
||||
|
||||
// Act
|
||||
bool result = firstId.Equals(secondId);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentValue_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
TrackId firstId = _trackIdFixture.Create();
|
||||
TrackId secondId = _trackIdFixture.Create();
|
||||
|
||||
// Act
|
||||
bool result = firstId.Equals(secondId);
|
||||
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaItemId"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaItemIdTests
|
||||
{
|
||||
private readonly MediaItemIdFixture _mediaItemIdFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void CreateUnique_WhenCalled_ShouldReturnIdWithNonEmptyValue()
|
||||
{
|
||||
// Act
|
||||
MediaItemId mediaItemId = MediaItemId.CreateUnique();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(mediaItemId);
|
||||
Assert.NotEqual(Guid.Empty, mediaItemId.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithValue_ShouldReturnIdWithThatValue()
|
||||
{
|
||||
// Arrange
|
||||
Guid value = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
MediaItemId mediaItemId = MediaItemId.Create(value);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(value, mediaItemId.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithSameValue_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
Guid value = Guid.NewGuid();
|
||||
MediaItemId firstId = _mediaItemIdFixture.Create(value);
|
||||
MediaItemId secondId = _mediaItemIdFixture.Create(value);
|
||||
|
||||
// Act
|
||||
bool result = firstId.Equals(secondId);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentValue_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
MediaItemId firstId = _mediaItemIdFixture.Create();
|
||||
MediaItemId secondId = _mediaItemIdFixture.Create();
|
||||
|
||||
// Act
|
||||
bool result = firstId.Equals(secondId);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetEqualityComponents_WhenCalled_ShouldReturnOnlyTheValue()
|
||||
{
|
||||
// Arrange
|
||||
MediaItemId mediaItemId = _mediaItemIdFixture.Create();
|
||||
|
||||
// Act
|
||||
List<object?> components = [.. mediaItemId.GetEqualityComponents()];
|
||||
|
||||
// Assert
|
||||
object? component = Assert.Single(components);
|
||||
Assert.Equal(mediaItemId.Value, component);
|
||||
}
|
||||
}
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="UserId"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UserIdTests
|
||||
{
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void CreateUnique_WhenCalled_ShouldReturnIdWithNonEmptyValue()
|
||||
{
|
||||
// Act
|
||||
UserId userId = UserId.CreateUnique();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(userId);
|
||||
Assert.NotEqual(Guid.Empty, userId.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithValue_ShouldReturnIdWithThatValue()
|
||||
{
|
||||
// Arrange
|
||||
Guid value = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
UserId userId = UserId.Create(value);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(value, userId.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithSameValue_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
Guid value = Guid.NewGuid();
|
||||
UserId firstId = _userIdFixture.Create(value);
|
||||
UserId secondId = _userIdFixture.Create(value);
|
||||
|
||||
// Act
|
||||
bool result = firstId.Equals(secondId);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentValue_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
UserId firstId = _userIdFixture.Create();
|
||||
UserId secondId = _userIdFixture.Create();
|
||||
|
||||
// Act
|
||||
bool result = firstId.Equals(secondId);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetEqualityComponents_WhenCalled_ShouldReturnOnlyTheValue()
|
||||
{
|
||||
// Arrange
|
||||
UserId userId = _userIdFixture.Create();
|
||||
|
||||
// Act
|
||||
List<object?> components = [.. userId.GetEqualityComponents()];
|
||||
|
||||
// Assert
|
||||
object? component = Assert.Single(components);
|
||||
Assert.Equal(userId.Value, component);
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.Events;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.Events;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="FavoriteAddedDomainEvent"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FavoriteAddedDomainEventTests
|
||||
{
|
||||
private readonly FavoriteIdFixture _favoriteIdFixture = new();
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
private readonly MediaItemIdFixture _mediaItemIdFixture = new();
|
||||
private readonly FavoriteAddedDomainEventFixture _favoriteAddedDomainEventFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenCalled_ShouldSetAllProperties()
|
||||
{
|
||||
// Arrange
|
||||
Guid id = Guid.NewGuid();
|
||||
FavoriteId favoriteId = _favoriteIdFixture.Create();
|
||||
UserId userId = _userIdFixture.Create();
|
||||
MediaItemId mediaItemId = _mediaItemIdFixture.Create();
|
||||
FavoriteMediaKind mediaKind = FavoriteMediaKind.MusicAlbum;
|
||||
DateTime occurredOnUtc = DateTime.UtcNow;
|
||||
|
||||
// Act
|
||||
FavoriteAddedDomainEvent domainEvent = _favoriteAddedDomainEventFixture.Create(
|
||||
id,
|
||||
favoriteId,
|
||||
userId,
|
||||
mediaItemId,
|
||||
mediaKind,
|
||||
occurredOnUtc);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(id, domainEvent.Id);
|
||||
Assert.Equal(favoriteId, domainEvent.FavoriteId);
|
||||
Assert.Equal(userId, domainEvent.UserId);
|
||||
Assert.Equal(mediaItemId, domainEvent.MediaItemId);
|
||||
Assert.Equal(mediaKind, domainEvent.MediaKind);
|
||||
Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc);
|
||||
Assert.IsType<IDomainEvent>(domainEvent, exactMatch: false);
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.Events;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.Events;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="FavoriteRemovedDomainEvent"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FavoriteRemovedDomainEventTests
|
||||
{
|
||||
private readonly FavoriteIdFixture _favoriteIdFixture = new();
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
private readonly MediaItemIdFixture _mediaItemIdFixture = new();
|
||||
private readonly FavoriteRemovedDomainEventFixture _favoriteRemovedDomainEventFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenCalled_ShouldSetAllProperties()
|
||||
{
|
||||
// Arrange
|
||||
Guid id = Guid.NewGuid();
|
||||
FavoriteId favoriteId = _favoriteIdFixture.Create();
|
||||
UserId userId = _userIdFixture.Create();
|
||||
MediaItemId mediaItemId = _mediaItemIdFixture.Create();
|
||||
FavoriteMediaKind mediaKind = FavoriteMediaKind.Book;
|
||||
DateTime occurredOnUtc = DateTime.UtcNow;
|
||||
|
||||
// Act
|
||||
FavoriteRemovedDomainEvent domainEvent = _favoriteRemovedDomainEventFixture.Create(
|
||||
id,
|
||||
favoriteId,
|
||||
userId,
|
||||
mediaItemId,
|
||||
mediaKind,
|
||||
occurredOnUtc);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(id, domainEvent.Id);
|
||||
Assert.Equal(favoriteId, domainEvent.FavoriteId);
|
||||
Assert.Equal(userId, domainEvent.UserId);
|
||||
Assert.Equal(mediaItemId, domainEvent.MediaItemId);
|
||||
Assert.Equal(mediaKind, domainEvent.MediaKind);
|
||||
Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc);
|
||||
Assert.IsType<IDomainEvent>(domainEvent, exactMatch: false);
|
||||
}
|
||||
}
|
||||
+236
@@ -0,0 +1,236 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="Favorite"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FavoriteTests
|
||||
{
|
||||
private readonly FavoriteFixture _favoriteFixture = new();
|
||||
private readonly FavoriteIdFixture _favoriteIdFixture = new();
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
private readonly MediaItemIdFixture _mediaItemIdFixture = new();
|
||||
|
||||
[Theory]
|
||||
[InlineData(FavoriteMediaKind.MusicArtist)] // An artist of a music library.
|
||||
[InlineData(FavoriteMediaKind.MusicAlbum)] // An album of a music library.
|
||||
[InlineData(FavoriteMediaKind.MusicTrack)] // A track of a music library.
|
||||
[InlineData(FavoriteMediaKind.Book)] // A book of a book library.
|
||||
public void Create_WhenMediaKindIsSupported_ShouldCreateFavoriteAndRaiseSingleAddedEvent(FavoriteMediaKind mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
UserId userId = _userIdFixture.Create();
|
||||
MediaItemId mediaItemId = _mediaItemIdFixture.Create();
|
||||
DateTime beforeUtc = DateTime.UtcNow;
|
||||
|
||||
// Act
|
||||
Result<Favorite> result = Favorite.Create(userId, mediaItemId, mediaKind);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Favorite favorite = result.Value;
|
||||
Assert.NotEqual(Guid.Empty, favorite.Id.Value);
|
||||
Assert.Equal(userId, favorite.UserId);
|
||||
Assert.Equal(mediaItemId, favorite.MediaItemId);
|
||||
Assert.Equal(mediaKind, favorite.MediaKind);
|
||||
Assert.InRange(favorite.CreatedOnUtc, beforeUtc, DateTime.UtcNow);
|
||||
Assert.False(favorite.UpdatedOnUtc.HasValue);
|
||||
Assert.False(favorite.IsRemoved);
|
||||
FavoriteAddedDomainEvent addedEvent = Assert.IsType<FavoriteAddedDomainEvent>(Assert.Single(favorite.GetDomainEvents()));
|
||||
Assert.NotEqual(Guid.Empty, addedEvent.Id);
|
||||
Assert.Equal(favorite.Id, addedEvent.FavoriteId);
|
||||
Assert.Equal(userId, addedEvent.UserId);
|
||||
Assert.Equal(mediaItemId, addedEvent.MediaItemId);
|
||||
Assert.Equal(mediaKind, addedEvent.MediaKind);
|
||||
Assert.Equal(favorite.CreatedOnUtc, addedEvent.OccurredOnUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledTwice_ShouldGenerateDistinctIds()
|
||||
{
|
||||
// Arrange
|
||||
UserId userId = _userIdFixture.Create();
|
||||
MediaItemId mediaItemId = _mediaItemIdFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Favorite> firstResult = Favorite.Create(userId, mediaItemId, FavoriteMediaKind.MusicTrack);
|
||||
Result<Favorite> secondResult = Favorite.Create(userId, mediaItemId, FavoriteMediaKind.MusicTrack);
|
||||
|
||||
// Assert
|
||||
Assert.False(firstResult.IsFailure);
|
||||
Assert.False(secondResult.IsFailure);
|
||||
Assert.NotEqual(firstResult.Value.Id, secondResult.Value.Id);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(FavoriteMediaKind.None)] // The default value, which is not a kind that can be favorited.
|
||||
[InlineData(FavoriteMediaKind.Video)] // A planned kind: video libraries are not catalogued yet.
|
||||
[InlineData(FavoriteMediaKind.Photo)] // A planned kind: photo libraries are not catalogued yet.
|
||||
[InlineData((FavoriteMediaKind)999)] // A value outside the declared enumeration members.
|
||||
public void Create_WhenMediaKindIsNotSupported_ShouldReturnErrorAndProduceNoFavorite(FavoriteMediaKind mediaKind)
|
||||
{
|
||||
// Act
|
||||
Result<Favorite> result = Favorite.Create(_userIdFixture.Create(), _mediaItemIdFixture.Create(), mediaKind);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Favorites.FavoriteMediaKindIsNotSupported, result.FirstError);
|
||||
// A failed result carries no favorite, so no FavoriteAddedDomainEvent can have been raised for one.
|
||||
Assert.Throws<InvalidOperationException>(() => result.Value);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(FavoriteMediaKind.MusicAlbum)] // A supported kind that was stored with an update.
|
||||
[InlineData(FavoriteMediaKind.None)] // The default value, preserved as it was recorded.
|
||||
[InlineData(FavoriteMediaKind.Video)] // A planned kind, stored as it was recorded, whatever its support today.
|
||||
public void Create_WhenRehydratingWithUpdatedOnUtc_ShouldPreserveAllDataAndRaiseNoEvents(FavoriteMediaKind mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
FavoriteId id = _favoriteIdFixture.Create();
|
||||
UserId userId = _userIdFixture.Create();
|
||||
MediaItemId mediaItemId = _mediaItemIdFixture.Create();
|
||||
DateTime createdOnUtc = DateTime.UtcNow.AddDays(-10);
|
||||
DateTime updatedOnUtc = createdOnUtc.AddDays(2);
|
||||
|
||||
// Act
|
||||
Result<Favorite> result = Favorite.Create(id, userId, mediaItemId, mediaKind, createdOnUtc, Optional<DateTime>.Some(updatedOnUtc));
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Favorite favorite = result.Value;
|
||||
Assert.Equal(id, favorite.Id);
|
||||
Assert.Equal(userId, favorite.UserId);
|
||||
Assert.Equal(mediaItemId, favorite.MediaItemId);
|
||||
Assert.Equal(mediaKind, favorite.MediaKind);
|
||||
Assert.Equal(createdOnUtc, favorite.CreatedOnUtc);
|
||||
Assert.Equal(Optional<DateTime>.Some(updatedOnUtc), favorite.UpdatedOnUtc);
|
||||
Assert.False(favorite.IsRemoved);
|
||||
Assert.Empty(favorite.GetDomainEvents());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenRehydratingWithoutUpdatedOnUtc_ShouldPreserveAllDataAndRaiseNoEvents()
|
||||
{
|
||||
// Arrange
|
||||
FavoriteId id = _favoriteIdFixture.Create();
|
||||
UserId userId = _userIdFixture.Create();
|
||||
MediaItemId mediaItemId = _mediaItemIdFixture.Create();
|
||||
DateTime createdOnUtc = DateTime.UtcNow.AddDays(-10);
|
||||
|
||||
// Act
|
||||
Result<Favorite> result = Favorite.Create(id, userId, mediaItemId, FavoriteMediaKind.Book, createdOnUtc, Optional<DateTime>.None());
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Favorite favorite = result.Value;
|
||||
Assert.Equal(id, favorite.Id);
|
||||
Assert.Equal(userId, favorite.UserId);
|
||||
Assert.Equal(mediaItemId, favorite.MediaItemId);
|
||||
Assert.Equal(FavoriteMediaKind.Book, favorite.MediaKind);
|
||||
Assert.Equal(createdOnUtc, favorite.CreatedOnUtc);
|
||||
Assert.False(favorite.UpdatedOnUtc.HasValue);
|
||||
Assert.False(favorite.IsRemoved);
|
||||
Assert.Empty(favorite.GetDomainEvents());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Remove_WhenFavoriteIsNotRemoved_ShouldMarkItRemovedAndRaiseOnlyRemovedEvent()
|
||||
{
|
||||
// Arrange
|
||||
UserId userId = _userIdFixture.Create();
|
||||
MediaItemId mediaItemId = _mediaItemIdFixture.Create();
|
||||
Favorite favorite = Favorite.Create(userId, mediaItemId, FavoriteMediaKind.MusicTrack).Value;
|
||||
FavoriteId favoriteId = favorite.Id;
|
||||
DateTime beforeUtc = DateTime.UtcNow;
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = favorite.Remove();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Deleted, result.Value);
|
||||
Assert.True(favorite.IsRemoved);
|
||||
// The favorite was created with an added event, so a single remaining removal event also proves it was cleared.
|
||||
FavoriteRemovedDomainEvent removedEvent = Assert.IsType<FavoriteRemovedDomainEvent>(Assert.Single(favorite.GetDomainEvents()));
|
||||
Assert.NotEqual(Guid.Empty, removedEvent.Id);
|
||||
Assert.Equal(favoriteId, removedEvent.FavoriteId);
|
||||
Assert.Equal(userId, removedEvent.UserId);
|
||||
Assert.Equal(mediaItemId, removedEvent.MediaItemId);
|
||||
Assert.Equal(FavoriteMediaKind.MusicTrack, removedEvent.MediaKind);
|
||||
Assert.InRange(removedEvent.OccurredOnUtc, beforeUtc, DateTime.UtcNow);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Remove_WhenCalledTwice_ShouldReturnDeletedWithoutRaisingAnotherEvent()
|
||||
{
|
||||
// Arrange
|
||||
Favorite favorite = Favorite.Create(_userIdFixture.Create(), _mediaItemIdFixture.Create(), FavoriteMediaKind.MusicAlbum).Value;
|
||||
Result<Deleted> firstResult = favorite.Remove();
|
||||
Assert.False(firstResult.IsFailure);
|
||||
Assert.Single(favorite.GetDomainEvents());
|
||||
|
||||
// Act
|
||||
Result<Deleted> secondResult = favorite.Remove();
|
||||
|
||||
// Assert
|
||||
Assert.False(secondResult.IsFailure);
|
||||
Assert.Equal(Result.Deleted, secondResult.Value);
|
||||
Assert.True(favorite.IsRemoved);
|
||||
Assert.Empty(favorite.GetDomainEvents());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Remove_WhenRehydratedFavoriteIsAlreadyRemoved_ShouldReturnDeletedWithoutRaisingAnotherEvent()
|
||||
{
|
||||
// Arrange
|
||||
Favorite favorite = _favoriteFixture.Create(mediaKind: FavoriteMediaKind.Book);
|
||||
Result<Deleted> firstResult = favorite.Remove();
|
||||
Assert.False(firstResult.IsFailure);
|
||||
Assert.Single(favorite.GetDomainEvents());
|
||||
|
||||
// Act
|
||||
Result<Deleted> secondResult = favorite.Remove();
|
||||
|
||||
// Assert
|
||||
Assert.False(secondResult.IsFailure);
|
||||
Assert.Equal(Result.Deleted, secondResult.Value);
|
||||
Assert.True(favorite.IsRemoved);
|
||||
Assert.Empty(favorite.GetDomainEvents());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(FavoriteMediaKind.None, false)] // The default value, which is not a kind that can be favorited.
|
||||
[InlineData(FavoriteMediaKind.MusicArtist, true)] // An artist of a music library can be favorited.
|
||||
[InlineData(FavoriteMediaKind.MusicAlbum, true)] // An album of a music library can be favorited.
|
||||
[InlineData(FavoriteMediaKind.MusicTrack, true)] // A track of a music library can be favorited.
|
||||
[InlineData(FavoriteMediaKind.Book, true)] // A book of a book library can be favorited.
|
||||
[InlineData(FavoriteMediaKind.Video, false)] // A planned kind: video libraries are not catalogued yet.
|
||||
[InlineData(FavoriteMediaKind.Photo, false)] // A planned kind: photo libraries are not catalogued yet.
|
||||
[InlineData((FavoriteMediaKind)999, false)] // A value outside the declared enumeration members.
|
||||
[InlineData((FavoriteMediaKind)(-1), false)] // A value below the declared enumeration members.
|
||||
public void IsSupported_WhenCalled_ShouldOnlySupportCataloguedMediaKinds(FavoriteMediaKind mediaKind, bool expectedIsSupported)
|
||||
{
|
||||
// Act
|
||||
bool isSupported = Favorite.IsSupported(mediaKind);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(expectedIsSupported, isSupported);
|
||||
}
|
||||
}
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.ValueObjects;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="FavoriteId"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FavoriteIdTests
|
||||
{
|
||||
private readonly FavoriteIdFixture _favoriteIdFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void CreateUnique_WhenCalled_ShouldReturnIdWithNonEmptyValue()
|
||||
{
|
||||
// Act
|
||||
FavoriteId favoriteId = FavoriteId.CreateUnique();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(favoriteId);
|
||||
Assert.NotEqual(Guid.Empty, favoriteId.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithValue_ShouldReturnIdWithThatValue()
|
||||
{
|
||||
// Arrange
|
||||
Guid value = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
FavoriteId favoriteId = FavoriteId.Create(value);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(value, favoriteId.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithSameValue_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
Guid value = Guid.NewGuid();
|
||||
FavoriteId firstId = _favoriteIdFixture.Create(value);
|
||||
FavoriteId secondId = _favoriteIdFixture.Create(value);
|
||||
|
||||
// Act
|
||||
bool result = firstId.Equals(secondId);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentValue_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
FavoriteId firstId = _favoriteIdFixture.Create();
|
||||
FavoriteId secondId = _favoriteIdFixture.Create();
|
||||
|
||||
// Act
|
||||
bool result = firstId.Equals(secondId);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetEqualityComponents_WhenCalled_ShouldReturnOnlyTheValue()
|
||||
{
|
||||
// Arrange
|
||||
FavoriteId favoriteId = _favoriteIdFixture.Create();
|
||||
|
||||
// Act
|
||||
List<object?> components = [.. favoriteId.GetEqualityComponents()];
|
||||
|
||||
// Assert
|
||||
object? component = Assert.Single(components);
|
||||
Assert.Equal(favoriteId.Value, component);
|
||||
}
|
||||
}
|
||||
+160
@@ -0,0 +1,160 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.FileSystem;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="Directory"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DirectoryTests
|
||||
{
|
||||
private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new();
|
||||
private readonly DirectoryFixture _directoryFixture = new();
|
||||
private readonly FileFixture _fileFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithValidParameters_ShouldReturnSuccessfulResult()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/valid/path";
|
||||
string name = "TestDirectory";
|
||||
Optional<DateTime> dateCreated = DateTime.Now;
|
||||
Optional<DateTime> dateModified = DateTime.Now;
|
||||
|
||||
// Act
|
||||
Result<Directory> result = Directory.Create(path, name, dateCreated, dateModified);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(name, result.Value.Name);
|
||||
Assert.Equal(dateCreated, result.Value.DateCreated);
|
||||
Assert.Equal(dateModified, result.Value.DateModified);
|
||||
Assert.Equal(FileSystemItemStatus.Accessible, result.Value.Status);
|
||||
Assert.False(result.Value.IsHidden);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithHiddenDirectory_ShouldSetHiddenState()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/valid/path";
|
||||
string name = "TestDirectory";
|
||||
Optional<DateTime> dateCreated = DateTime.Now;
|
||||
Optional<DateTime> dateModified = DateTime.Now;
|
||||
|
||||
// Act
|
||||
Result<Directory> result = Directory.Create(path, name, dateCreated, dateModified, isHidden: true);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.True(result.Value.IsHidden);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithInvalidPath_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
string invalidPath = "";
|
||||
string name = "TestDirectory";
|
||||
Optional<DateTime> dateCreated = DateTime.Now;
|
||||
Optional<DateTime> dateModified = DateTime.Now;
|
||||
|
||||
// Act
|
||||
Result<Directory> result = Directory.Create(invalidPath, name, dateCreated, dateModified);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithFileSystemPathId_ShouldReturnSuccessfulResult()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path: "/valid/path");
|
||||
string name = "TestDirectory";
|
||||
Optional<DateTime> dateCreated = DateTime.Now;
|
||||
Optional<DateTime> dateModified = DateTime.Now;
|
||||
|
||||
// Act
|
||||
Result<Directory> result = Directory.Create(pathId, name, dateCreated, dateModified);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(pathId, result.Value.Id);
|
||||
Assert.Equal(name, result.Value.Name);
|
||||
Assert.Equal(dateCreated, result.Value.DateCreated);
|
||||
Assert.Equal(dateModified, result.Value.DateModified);
|
||||
Assert.Equal(FileSystemItemStatus.Accessible, result.Value.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateLastModified_WhenCalled_ShouldUpdateDateModified()
|
||||
{
|
||||
// Arrange
|
||||
Directory directory = _directoryFixture.Create(
|
||||
path: "/valid/path",
|
||||
name: "TestDirectory",
|
||||
dateCreated: Optional<DateTime>.None(),
|
||||
dateModified: Optional<DateTime>.None());
|
||||
DateTime newDate = DateTime.Now;
|
||||
|
||||
// Act
|
||||
Result<Updated> result = directory.UpdateLastModified(newDate);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(newDate, directory.DateModified.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddItem_WhenCalled_ShouldAddItemToCollection()
|
||||
{
|
||||
// Arrange
|
||||
Directory directory = _directoryFixture.Create(
|
||||
path: "/valid/path",
|
||||
name: "TestDirectory",
|
||||
dateCreated: Optional<DateTime>.None(),
|
||||
dateModified: Optional<DateTime>.None());
|
||||
File item = _fileFixture.Create(path: "/mock/path", name: "MockItem");
|
||||
|
||||
// Act
|
||||
Result<Updated> result = directory.AddItem(item);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Contains(item, directory.Items);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RemoveItem_WhenCalledWithExistingItem_ShouldRemoveItemFromCollection()
|
||||
{
|
||||
// Arrange
|
||||
Directory directory = _directoryFixture.Create(
|
||||
path: "/valid/path",
|
||||
name: "TestDirectory",
|
||||
dateCreated: Optional<DateTime>.None(),
|
||||
dateModified: Optional<DateTime>.None());
|
||||
File item = _fileFixture.Create(path: "/mock/path", name: "MockItem");
|
||||
directory.AddItem(item);
|
||||
|
||||
// Act
|
||||
Result<Updated> result = directory.RemoveItem(item);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.DoesNotContain(item, directory.Items);
|
||||
}
|
||||
}
|
||||
+188
@@ -0,0 +1,188 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.FileSystem;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="File"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FileTests
|
||||
{
|
||||
private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new();
|
||||
private readonly FileFixture _fileFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithValidParameters_ShouldReturnSuccessfulResult()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/valid/path/file.txt";
|
||||
string name = "file.txt";
|
||||
Optional<DateTime> dateCreated = DateTime.Now;
|
||||
Optional<DateTime> dateModified = DateTime.Now;
|
||||
long size = 1024;
|
||||
|
||||
// Act
|
||||
Result<File> result = File.Create(path, name, dateCreated, dateModified, size);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(name, result.Value.Name);
|
||||
Assert.Equal(dateCreated, result.Value.DateCreated);
|
||||
Assert.Equal(dateModified, result.Value.DateModified);
|
||||
Assert.Equal(size, result.Value.Size);
|
||||
Assert.Equal(FileSystemItemStatus.Accessible, result.Value.Status);
|
||||
Assert.False(result.Value.IsHidden);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithHiddenFile_ShouldSetHiddenState()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/valid/path/file.txt";
|
||||
string name = "file.txt";
|
||||
Optional<DateTime> dateCreated = DateTime.Now;
|
||||
Optional<DateTime> dateModified = DateTime.Now;
|
||||
long size = 1024;
|
||||
|
||||
// Act
|
||||
Result<File> result = File.Create(path, name, dateCreated, dateModified, size, isHidden: true);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.True(result.Value.IsHidden);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithInvalidPath_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
string invalidPath = "";
|
||||
string name = "file.txt";
|
||||
Optional<DateTime> dateCreated = DateTime.Now;
|
||||
Optional<DateTime> dateModified = DateTime.Now;
|
||||
long size = 1024;
|
||||
|
||||
// Act
|
||||
Result<File> result = File.Create(invalidPath, name, dateCreated, dateModified, size);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithFileSystemPathId_ShouldReturnSuccessfulResult()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path: "/valid/path/file.txt");
|
||||
string name = "file.txt";
|
||||
Optional<DateTime> dateCreated = DateTime.Now;
|
||||
Optional<DateTime> dateModified = DateTime.Now;
|
||||
long size = 1024;
|
||||
|
||||
// Act
|
||||
Result<File> result = File.Create(pathId, name, dateCreated, dateModified, size);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(pathId, result.Value.Id);
|
||||
Assert.Equal(name, result.Value.Name);
|
||||
Assert.Equal(dateCreated, result.Value.DateCreated);
|
||||
Assert.Equal(dateModified, result.Value.DateModified);
|
||||
Assert.Equal(size, result.Value.Size);
|
||||
Assert.Equal(FileSystemItemStatus.Accessible, result.Value.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateLastModified_WhenCalled_ShouldUpdateDateModified()
|
||||
{
|
||||
// Arrange
|
||||
File file = _fileFixture.Create(
|
||||
path: "/valid/path/file.txt",
|
||||
name: "file.txt",
|
||||
dateCreated: Optional<DateTime>.None(),
|
||||
dateModified: Optional<DateTime>.None(),
|
||||
size: 1024);
|
||||
DateTime newDate = DateTime.Now;
|
||||
|
||||
// Act
|
||||
Result<Updated> result = file.UpdateLastModified(newDate);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(newDate, file.DateModified.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateSize_WhenCalled_ShouldUpdateFileSize()
|
||||
{
|
||||
// Arrange
|
||||
File file = _fileFixture.Create(
|
||||
path: "/valid/path/file.txt",
|
||||
name: "file.txt",
|
||||
dateCreated: Optional<DateTime>.None(),
|
||||
dateModified: Optional<DateTime>.None(),
|
||||
size: 1024);
|
||||
long newSize = 2048;
|
||||
|
||||
// Act
|
||||
Result<Updated> result = file.UpdateSize(newSize);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(newSize, file.Size);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Rename_WhenCalledWithValidName_ShouldUpdateFileName()
|
||||
{
|
||||
// Arrange
|
||||
File file = _fileFixture.Create(
|
||||
path: "/valid/path/file.txt",
|
||||
name: "file.txt",
|
||||
dateCreated: Optional<DateTime>.None(),
|
||||
dateModified: Optional<DateTime>.None(),
|
||||
size: 1024);
|
||||
string newName = "newfile.txt";
|
||||
|
||||
// Act
|
||||
Result<Updated> result = file.Rename(newName);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(newName, file.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Rename_WhenCalledWithEmptyName_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
File file = _fileFixture.Create(
|
||||
path: "/valid/path/file.txt",
|
||||
name: "file.txt",
|
||||
dateCreated: Optional<DateTime>.None(),
|
||||
dateModified: Optional<DateTime>.None(),
|
||||
size: 1024);
|
||||
string emptyName = "";
|
||||
|
||||
// Act
|
||||
Result<Updated> result = file.Rename(emptyName);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.NameCannotBeEmpty, result.FirstError);
|
||||
Assert.Equal("file.txt", file.Name);
|
||||
}
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.FileSystem;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="UnixRootItem"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UnixRootItemTests
|
||||
{
|
||||
private readonly UnixRootItemFixture _unixRootItemFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithDefaultStatus_ShouldReturnSuccessfulResult()
|
||||
{
|
||||
// Arrange & Act
|
||||
Result<UnixRootItem> result = UnixRootItem.Create();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal("/", result.Value.Name);
|
||||
Assert.Equal("/", result.Value.Id.Path);
|
||||
Assert.Equal(FileSystemItemType.Root, result.Value.Type);
|
||||
Assert.Equal(FileSystemItemStatus.Accessible, result.Value.Status);
|
||||
Assert.Empty(result.Value.Items);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithCustomStatus_ShouldReturnSuccessfulResultWithSpecifiedStatus()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemItemStatus customStatus = FileSystemItemStatus.Accessible;
|
||||
|
||||
// Act
|
||||
Result<UnixRootItem> result = UnixRootItem.Create(customStatus);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal("/", result.Value.Name);
|
||||
Assert.Equal("/", result.Value.Id.Path);
|
||||
Assert.Equal(FileSystemItemType.Root, result.Value.Type);
|
||||
Assert.Equal(customStatus, result.Value.Status);
|
||||
Assert.Empty(result.Value.Items);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Items_WhenAccessed_ShouldReturnEmptyReadOnlyCollection()
|
||||
{
|
||||
// Arrange
|
||||
UnixRootItem unixRootItem = _unixRootItemFixture.Create();
|
||||
|
||||
// Act
|
||||
IReadOnlyCollection<FileSystemItem> items = unixRootItem.Items;
|
||||
|
||||
// Assert
|
||||
Assert.Empty(items);
|
||||
Assert.IsAssignableFrom<IReadOnlyCollection<FileSystemItem>>(items);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SetStatus_WhenCalledWithNewStatus_ShouldUpdateStatus()
|
||||
{
|
||||
// Arrange
|
||||
UnixRootItem unixRootItem = _unixRootItemFixture.Create();
|
||||
FileSystemItemStatus newStatus = FileSystemItemStatus.Accessible;
|
||||
|
||||
// Act
|
||||
Result<Updated> result = unixRootItem.SetStatus(newStatus);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(newStatus, unixRootItem.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SetParent_WhenCalledWithNullParent_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
UnixRootItem unixRootItem = _unixRootItemFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = unixRootItem.SetParent(null!);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.ParentNodeCannotBeNull, result.FirstError);
|
||||
Assert.False(unixRootItem.Parent.HasValue);
|
||||
}
|
||||
}
|
||||
+142
@@ -0,0 +1,142 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.FileSystem;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="WindowsRootItem"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class WindowsRootItemTests
|
||||
{
|
||||
private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new();
|
||||
private readonly WindowsRootItemFixture _windowsRootItemFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithValidParameters_ShouldReturnSuccessfulResult()
|
||||
{
|
||||
// Arrange
|
||||
string path = "C:\\";
|
||||
string name = "C:";
|
||||
|
||||
// Act
|
||||
Result<WindowsRootItem> result = WindowsRootItem.Create(path, name);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(name, result.Value.Name);
|
||||
Assert.Equal(path, result.Value.Id.Path);
|
||||
Assert.Equal(FileSystemItemType.Root, result.Value.Type);
|
||||
Assert.Equal(FileSystemItemStatus.Accessible, result.Value.Status);
|
||||
Assert.Empty(result.Value.Items);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithInvalidPath_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
string invalidPath = "";
|
||||
string name = "Invalid";
|
||||
|
||||
// Act
|
||||
Result<WindowsRootItem> result = WindowsRootItem.Create(invalidPath, name);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithCustomStatus_ShouldReturnSuccessfulResultWithSpecifiedStatus()
|
||||
{
|
||||
// Arrange
|
||||
string path = "D:\\";
|
||||
string name = "D:";
|
||||
FileSystemItemStatus customStatus = FileSystemItemStatus.Accessible;
|
||||
|
||||
// Act
|
||||
Result<WindowsRootItem> result = WindowsRootItem.Create(path, name, customStatus);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(name, result.Value.Name);
|
||||
Assert.Equal(path, result.Value.Id.Path);
|
||||
Assert.Equal(FileSystemItemType.Root, result.Value.Type);
|
||||
Assert.Equal(customStatus, result.Value.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithFileSystemPathId_ShouldReturnSuccessfulResult()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path: "E:\\");
|
||||
string name = "E:";
|
||||
|
||||
// Act
|
||||
Result<WindowsRootItem> result = WindowsRootItem.Create(pathId, name);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(pathId, result.Value.Id);
|
||||
Assert.Equal(name, result.Value.Name);
|
||||
Assert.Equal(FileSystemItemType.Root, result.Value.Type);
|
||||
Assert.Equal(FileSystemItemStatus.Accessible, result.Value.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Items_WhenAccessed_ShouldReturnEmptyReadOnlyCollection()
|
||||
{
|
||||
// Arrange
|
||||
WindowsRootItem windowsRootItem = _windowsRootItemFixture.Create();
|
||||
|
||||
// Act
|
||||
IReadOnlyCollection<FileSystemItem> items = windowsRootItem.Items;
|
||||
|
||||
// Assert
|
||||
Assert.Empty(items);
|
||||
Assert.IsAssignableFrom<IReadOnlyCollection<FileSystemItem>>(items);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SetStatus_WhenCalledWithNewStatus_ShouldUpdateStatus()
|
||||
{
|
||||
// Arrange
|
||||
WindowsRootItem windowsRootItem = _windowsRootItemFixture.Create();
|
||||
FileSystemItemStatus newStatus = FileSystemItemStatus.Accessible;
|
||||
|
||||
// Act
|
||||
Result<Updated> result = windowsRootItem.SetStatus(newStatus);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(newStatus, windowsRootItem.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SetParent_WhenCalledWithNullParent_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
WindowsRootItem windowsRootItem = _windowsRootItemFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = windowsRootItem.SetParent(null!);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.ParentNodeCannotBeNull, result.FirstError);
|
||||
Assert.False(windowsRootItem.Parent.HasValue);
|
||||
}
|
||||
}
|
||||
+182
@@ -0,0 +1,182 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using AutoFixture;
|
||||
using AutoFixture.AutoNSubstitute;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.FileSystem;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="FileSystemItem"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FileSystemItemTests
|
||||
{
|
||||
private readonly IFixture _fixture;
|
||||
private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="FileSystemItemTests"/> class.
|
||||
/// </summary>
|
||||
public FileSystemItemTests()
|
||||
{
|
||||
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenCalled_ShouldSetPropertiesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId id = _fileSystemPathIdFixture.Create();
|
||||
string name = "TestItem";
|
||||
FileSystemItemType type = FileSystemItemType.File;
|
||||
|
||||
// Act
|
||||
FileSystemItemFixture item = new(id, name, type);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(id, item.Id);
|
||||
Assert.Equal(name, item.Name);
|
||||
Assert.Equal(type, item.Type);
|
||||
Assert.Equal(FileSystemItemStatus.Accessible, item.Status);
|
||||
Assert.False(item.IsHidden);
|
||||
Assert.Equal(Optional<FileSystemItem>.None(), item.Parent);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SetStatus_WhenCalled_ShouldUpdateStatusAndReturnUpdated()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemItemFixture item = CreateFileSystemItemFixture();
|
||||
FileSystemItemStatus newStatus = FileSystemItemStatus.Inaccessible;
|
||||
|
||||
// Act
|
||||
Result<Updated> result = item.SetStatus(newStatus);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
Assert.Equal(newStatus, item.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SetHiddenState_WhenCalled_ShouldUpdateHiddenStateAndReturnUpdated()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemItemFixture item = CreateFileSystemItemFixture();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = item.SetHiddenState(true);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
Assert.True(item.IsHidden);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SetParent_WithValidParent_ShouldUpdateParentAndReturnUpdated()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemItemFixture item = CreateFileSystemItemFixture();
|
||||
FileSystemItemFixture parent = CreateFileSystemItemFixture();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = item.SetParent(parent);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
Assert.Equal(Optional<FileSystemItem>.Some(parent), item.Parent);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SetParent_WithNullParent_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemItemFixture item = CreateFileSystemItemFixture();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = item.SetParent(null!);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.ParentNodeCannotBeNull, result.FirstError);
|
||||
Assert.Equal(Optional<FileSystemItem>.None(), item.Parent);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithSameId_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId id = _fileSystemPathIdFixture.Create();
|
||||
FileSystemItemFixture item1 = CreateFileSystemItemFixture(id);
|
||||
FileSystemItemFixture item2 = CreateFileSystemItemFixture(id);
|
||||
|
||||
// Act
|
||||
bool result = item1.Equals(item2);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentId_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemItemFixture item1 = CreateFileSystemItemFixture();
|
||||
FileSystemItemFixture item2 = CreateFileSystemItemFixture();
|
||||
|
||||
// Act
|
||||
bool result = item1.Equals(item2);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetHashCode_WithSameId_ShouldReturnSameHashCode()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId id = _fileSystemPathIdFixture.Create();
|
||||
FileSystemItemFixture item1 = CreateFileSystemItemFixture(id);
|
||||
FileSystemItemFixture item2 = CreateFileSystemItemFixture(id);
|
||||
|
||||
// Act
|
||||
int hashCode1 = item1.GetHashCode();
|
||||
int hashCode2 = item2.GetHashCode();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(hashCode1, hashCode2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetHashCode_WithDifferentId_ShouldReturnDifferentHashCode()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemItemFixture item1 = CreateFileSystemItemFixture();
|
||||
FileSystemItemFixture item2 = CreateFileSystemItemFixture();
|
||||
|
||||
// Act
|
||||
int hashCode1 = item1.GetHashCode();
|
||||
int hashCode2 = item2.GetHashCode();
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(hashCode1, hashCode2);
|
||||
}
|
||||
|
||||
private FileSystemItemFixture CreateFileSystemItemFixture(FileSystemPathId? id = null)
|
||||
{
|
||||
id ??= _fileSystemPathIdFixture.Create();
|
||||
string name = _fixture.Create<string>();
|
||||
FileSystemItemType type = _fixture.Create<FileSystemItemType>();
|
||||
return new FileSystemItemFixture(id, name, type);
|
||||
}
|
||||
}
|
||||
+1215
File diff suppressed because it is too large.
Load diff
+993
@@ -0,0 +1,993 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.FileSystem;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="DirectoryService"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DirectoryServiceTests
|
||||
{
|
||||
private readonly IEnvironmentContext _mockEnvironmentContext;
|
||||
private readonly IPlatformContextManager _mockPlatformContextManager;
|
||||
private readonly IPlatformContext _mockPlatformContext;
|
||||
private readonly DirectoryService _sut;
|
||||
private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new();
|
||||
private readonly DirectoryFixture _directoryFixture = new();
|
||||
private static readonly bool s_isUnix = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
|
||||
private readonly string _pathDirTest = s_isUnix ? "/TestDir" : @"C:\TestDir";
|
||||
private readonly string _pathDirTestSubDir1 = s_isUnix ? "/TestDir/Sub1" : @"C:\TestDir\Sub1";
|
||||
private readonly string _pathDirTestSubDir2 = s_isUnix ? "/TestDir/Sub2" : @"C:\TestDir\Sub2";
|
||||
private readonly char _dirSeparator = s_isUnix ? '/' : '\\';
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DirectoryServiceTests"/> class.
|
||||
/// </summary>
|
||||
public DirectoryServiceTests()
|
||||
{
|
||||
_mockEnvironmentContext = Substitute.For<IEnvironmentContext>();
|
||||
_mockPlatformContextManager = Substitute.For<IPlatformContextManager>();
|
||||
_mockPlatformContext = Substitute.For<IPlatformContext>();
|
||||
_mockPlatformContextManager.GetCurrentContext().Returns(_mockPlatformContext);
|
||||
_sut = new DirectoryService(_mockEnvironmentContext, _mockPlatformContextManager);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetSubdirectories_WithValidPath_ShouldReturnListOfDirectories()
|
||||
{
|
||||
// Arrange
|
||||
string path = _pathDirTest;
|
||||
bool shouldIncludeHiddenElements = false;
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path);
|
||||
FileSystemPathId[] subPaths =
|
||||
[
|
||||
_fileSystemPathIdFixture.Create(_pathDirTestSubDir1),
|
||||
_fileSystemPathIdFixture.Create(_pathDirTestSubDir2)
|
||||
];
|
||||
|
||||
_mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(pathId, shouldIncludeHiddenElements)
|
||||
.Returns(Result.From(subPaths.AsEnumerable()));
|
||||
|
||||
foreach (FileSystemPathId subPath in subPaths)
|
||||
{
|
||||
_mockEnvironmentContext.DirectoryProviderService.GetFileName(subPath)
|
||||
.Returns(Result.From(System.IO.Path.GetFileName(subPath.Path)));
|
||||
_mockEnvironmentContext.DirectoryProviderService.GetLastWriteTime(subPath)
|
||||
.Returns(Result.From(Optional<DateTime>.FromNullable(DateTime.Now)));
|
||||
_mockEnvironmentContext.DirectoryProviderService.GetCreationTime(subPath)
|
||||
.Returns(Result.From(Optional<DateTime>.FromNullable(DateTime.Now.AddDays(-1))));
|
||||
}
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<Directory>> result = _sut.GetSubdirectories(path, shouldIncludeHiddenElements);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(2, result.Value.Count());
|
||||
Assert.Equal(["Sub1", "Sub2"], result.Value.Select(d => d.Name));
|
||||
_mockEnvironmentContext.DirectoryProviderService.DidNotReceive().IsHidden(Arg.Any<FileSystemPathId>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetSubdirectories_WhenDirectoryIsHidden_ShouldReturnDirectoryWithHiddenState()
|
||||
{
|
||||
// Arrange
|
||||
string path = _pathDirTest;
|
||||
bool shouldIncludeHiddenElements = true;
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path);
|
||||
FileSystemPathId subPath = _fileSystemPathIdFixture.Create(_pathDirTestSubDir1);
|
||||
|
||||
_mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(pathId, shouldIncludeHiddenElements)
|
||||
.Returns(Result.From(new[] { subPath }.AsEnumerable()));
|
||||
_mockEnvironmentContext.DirectoryProviderService.GetFileName(subPath)
|
||||
.Returns(Result.From(System.IO.Path.GetFileName(subPath.Path)));
|
||||
_mockEnvironmentContext.DirectoryProviderService.GetLastWriteTime(subPath)
|
||||
.Returns(Result.From(Optional<DateTime>.FromNullable(DateTime.Now)));
|
||||
_mockEnvironmentContext.DirectoryProviderService.GetCreationTime(subPath)
|
||||
.Returns(Result.From(Optional<DateTime>.FromNullable(DateTime.Now.AddDays(-1))));
|
||||
_mockEnvironmentContext.DirectoryProviderService.IsHidden(subPath)
|
||||
.Returns(true);
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<Directory>> result = _sut.GetSubdirectories(path, shouldIncludeHiddenElements);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Directory directory = Assert.Single(result.Value);
|
||||
Assert.True(directory.IsHidden);
|
||||
_mockEnvironmentContext.DirectoryProviderService.Received(1).IsHidden(subPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetSubdirectories_WithInvalidPath_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
string invalidPath = string.Empty;
|
||||
bool shouldIncludeHiddenElements = false;
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<Directory>> result = _sut.GetSubdirectories(invalidPath, shouldIncludeHiddenElements);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetSubdirectories_WhenDirectoryProviderServiceReturnsError_ShouldPropagateError()
|
||||
{
|
||||
// Arrange
|
||||
string path = _pathDirTest;
|
||||
bool shouldIncludeHiddenElements = false;
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path);
|
||||
|
||||
_mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(pathId, shouldIncludeHiddenElements)
|
||||
.Returns(Errors.Permission.UnauthorizedAccess);
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<Directory>> result = _sut.GetSubdirectories(path, shouldIncludeHiddenElements);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetSubdirectories_WhenSubdirectoryDetailsAreInaccessible_ShouldReturnInaccessibleDirectory()
|
||||
{
|
||||
// Arrange
|
||||
string path = _pathDirTest;
|
||||
bool shouldIncludeHiddenElements = true;
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path);
|
||||
FileSystemPathId subPath = _fileSystemPathIdFixture.Create(
|
||||
s_isUnix ? "/TestDir/InaccessibleSub" : @"C:\TestDir\InaccessibleSub"
|
||||
);
|
||||
|
||||
_mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(pathId, shouldIncludeHiddenElements)
|
||||
.Returns(Result.From(new[] { subPath }.AsEnumerable()));
|
||||
|
||||
_mockEnvironmentContext.DirectoryProviderService.GetFileName(subPath)
|
||||
.Returns(Errors.Permission.UnauthorizedAccess);
|
||||
_mockEnvironmentContext.DirectoryProviderService.GetLastWriteTime(subPath)
|
||||
.Returns(Errors.Permission.UnauthorizedAccess);
|
||||
_mockEnvironmentContext.DirectoryProviderService.GetCreationTime(subPath)
|
||||
.Returns(Errors.Permission.UnauthorizedAccess);
|
||||
_mockEnvironmentContext.DirectoryProviderService.IsHidden(subPath).Returns(true);
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<Directory>> result = _sut.GetSubdirectories(path, shouldIncludeHiddenElements);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Single(result.Value);
|
||||
Assert.Equal(FileSystemItemStatus.Inaccessible, result.Value.First().Status);
|
||||
Assert.True(result.Value.First().IsHidden);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetSubdirectoriesOverload_WithValidDirectory_ShouldReturnListOfDirectories()
|
||||
{
|
||||
// Arrange
|
||||
Directory parentDirectory = _directoryFixture.Create();
|
||||
bool shouldIncludeHiddenElements = false;
|
||||
FileSystemPathId[] subPaths =
|
||||
[
|
||||
_fileSystemPathIdFixture.Create(_pathDirTestSubDir1),
|
||||
_fileSystemPathIdFixture.Create(_pathDirTestSubDir2)
|
||||
];
|
||||
|
||||
_mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(parentDirectory.Id, shouldIncludeHiddenElements)
|
||||
.Returns(Result.From(subPaths.AsEnumerable()));
|
||||
|
||||
foreach (FileSystemPathId subPath in subPaths)
|
||||
{
|
||||
_mockEnvironmentContext.DirectoryProviderService.GetFileName(subPath)
|
||||
.Returns(Result.From(System.IO.Path.GetFileName(subPath.Path)));
|
||||
_mockEnvironmentContext.DirectoryProviderService.GetLastWriteTime(subPath)
|
||||
.Returns(Result.From(Optional<DateTime>.FromNullable(DateTime.Now)));
|
||||
_mockEnvironmentContext.DirectoryProviderService.GetCreationTime(subPath)
|
||||
.Returns(Result.From(Optional<DateTime>.FromNullable(DateTime.Now.AddDays(-1))));
|
||||
}
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<Directory>> result = _sut.GetSubdirectories(parentDirectory, shouldIncludeHiddenElements);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(2, result.Value.Count());
|
||||
Assert.Equal(["Sub1", "Sub2"], result.Value.Select(d => d.Name));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetSubdirectoriesOverload_WhenDirectoryProviderServiceReturnsError_ShouldPropagateError()
|
||||
{
|
||||
// Arrange
|
||||
Directory parentDirectory = _directoryFixture.Create();
|
||||
bool shouldIncludeHiddenElements = false;
|
||||
|
||||
_mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(parentDirectory.Id, shouldIncludeHiddenElements)
|
||||
.Returns(Errors.Permission.UnauthorizedAccess);
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<Directory>> result = _sut.GetSubdirectories(parentDirectory, shouldIncludeHiddenElements);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetSubdirectoriesOverload_WhenSubdirectoryDetailsAreInaccessible_ShouldReturnInaccessibleDirectory()
|
||||
{
|
||||
// Arrange
|
||||
Directory parentDirectory = _directoryFixture.Create();
|
||||
bool shouldIncludeHiddenElements = false;
|
||||
FileSystemPathId subPath = _fileSystemPathIdFixture.Create(
|
||||
s_isUnix ? "/TestDir/InaccessibleSub" : @"C:\TestDir\InaccessibleSub"
|
||||
);
|
||||
|
||||
_mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(parentDirectory.Id, shouldIncludeHiddenElements)
|
||||
.Returns(Result.From(new[] { subPath }.AsEnumerable()));
|
||||
|
||||
_mockEnvironmentContext.DirectoryProviderService.GetFileName(subPath)
|
||||
.Returns(Errors.Permission.UnauthorizedAccess);
|
||||
_mockEnvironmentContext.DirectoryProviderService.GetLastWriteTime(subPath)
|
||||
.Returns(Errors.Permission.UnauthorizedAccess);
|
||||
_mockEnvironmentContext.DirectoryProviderService.GetCreationTime(subPath)
|
||||
.Returns(Errors.Permission.UnauthorizedAccess);
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<Directory>> result = _sut.GetSubdirectories(parentDirectory, shouldIncludeHiddenElements);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Single(result.Value);
|
||||
Assert.Equal(FileSystemItemStatus.Inaccessible, result.Value.First().Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetSubdirectories_WithValidFileSystemPathId_ShouldReturnListOfDirectories()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(_pathDirTest);
|
||||
bool shouldIncludeHiddenElements = false;
|
||||
FileSystemPathId[] subPaths =
|
||||
[
|
||||
_fileSystemPathIdFixture.Create(_pathDirTestSubDir1),
|
||||
_fileSystemPathIdFixture.Create(_pathDirTestSubDir2)
|
||||
];
|
||||
|
||||
_mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(pathId, shouldIncludeHiddenElements)
|
||||
.Returns(Result.From(subPaths.AsEnumerable()));
|
||||
|
||||
foreach (FileSystemPathId subPath in subPaths)
|
||||
{
|
||||
_mockEnvironmentContext.DirectoryProviderService.GetFileName(subPath)
|
||||
.Returns(Result.From(System.IO.Path.GetFileName(subPath.Path)));
|
||||
_mockEnvironmentContext.DirectoryProviderService.GetLastWriteTime(subPath)
|
||||
.Returns(Result.From(Optional<DateTime>.FromNullable(DateTime.Now)));
|
||||
_mockEnvironmentContext.DirectoryProviderService.GetCreationTime(subPath)
|
||||
.Returns(Result.From(Optional<DateTime>.FromNullable(DateTime.Now.AddDays(-1))));
|
||||
}
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<Directory>> result = _sut.GetSubdirectories(pathId, shouldIncludeHiddenElements);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(2, result.Value.Count());
|
||||
Assert.Equal(["Sub1", "Sub2"], result.Value.Select(d => d.Name));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetSubdirectoriesWithFileSystemPathId_WhenDirectoryProviderServiceReturnsError_ShouldPropagateError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(_pathDirTest);
|
||||
bool shouldIncludeHiddenElements = false;
|
||||
|
||||
_mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(pathId, shouldIncludeHiddenElements)
|
||||
.Returns(Errors.Permission.UnauthorizedAccess);
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<Directory>> result = _sut.GetSubdirectories(pathId, shouldIncludeHiddenElements);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetSubdirectoriesWithFileSystemPathId_WhenSubdirectoryDetailsAreInaccessible_ShouldReturnInaccessibleDirectory()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(_pathDirTest);
|
||||
bool shouldIncludeHiddenElements = false;
|
||||
FileSystemPathId subPath = _fileSystemPathIdFixture.Create(
|
||||
s_isUnix ? "/TestDir/InaccessibleSub" : @"C:\TestDir\InaccessibleSub"
|
||||
);
|
||||
|
||||
_mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(pathId, shouldIncludeHiddenElements)
|
||||
.Returns(Result.From(new[] { subPath }.AsEnumerable()));
|
||||
|
||||
_mockEnvironmentContext.DirectoryProviderService.GetFileName(subPath)
|
||||
.Returns(Errors.Permission.UnauthorizedAccess);
|
||||
_mockEnvironmentContext.DirectoryProviderService.GetLastWriteTime(subPath)
|
||||
.Returns(Errors.Permission.UnauthorizedAccess);
|
||||
_mockEnvironmentContext.DirectoryProviderService.GetCreationTime(subPath)
|
||||
.Returns(Errors.Permission.UnauthorizedAccess);
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<Directory>> result = _sut.GetSubdirectories(pathId, shouldIncludeHiddenElements);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Single(result.Value);
|
||||
Assert.Equal(FileSystemItemStatus.Inaccessible, result.Value.First().Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateDirectory_WithValidStringPath_ShouldReturnNewDirectory()
|
||||
{
|
||||
// Arrange
|
||||
string parentPath = _pathDirTest;
|
||||
string newDirName = "NewDirectory";
|
||||
FileSystemPathId parentPathId = _fileSystemPathIdFixture.Create(parentPath);
|
||||
FileSystemPathId newDirPathId = _fileSystemPathIdFixture.Create(System.IO.Path.Combine(parentPath, newDirName));
|
||||
|
||||
_mockPlatformContext.PathStrategy.CombinePath(parentPathId, newDirName).Returns(Result.From(newDirPathId));
|
||||
_mockEnvironmentContext.DirectoryProviderService.DirectoryExists(newDirPathId).Returns(Result.From(false));
|
||||
|
||||
_mockEnvironmentContext.DirectoryProviderService.CreateDirectory(parentPathId, newDirName)
|
||||
.Returns(Result.From(newDirPathId));
|
||||
_mockEnvironmentContext.DirectoryProviderService.GetFileName(newDirPathId)
|
||||
.Returns(Result.From(newDirName));
|
||||
_mockEnvironmentContext.DirectoryProviderService.GetLastWriteTime(newDirPathId)
|
||||
.Returns(Result.From(Optional<DateTime>.FromNullable(DateTime.Now)));
|
||||
_mockEnvironmentContext.DirectoryProviderService.GetCreationTime(newDirPathId)
|
||||
.Returns(Result.From(Optional<DateTime>.FromNullable(DateTime.Now)));
|
||||
_mockEnvironmentContext.DirectoryProviderService.IsHidden(newDirPathId).Returns(true);
|
||||
|
||||
// Act
|
||||
Result<Directory> result = _sut.CreateDirectory(parentPath, newDirName);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(newDirPathId, result.Value.Id);
|
||||
Assert.True(result.Value.IsHidden);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateDirectory_WithInvalidStringPath_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
string invalidPath = string.Empty;
|
||||
string newDirName = "NewDirectory";
|
||||
|
||||
// Act
|
||||
Result<Directory> result = _sut.CreateDirectory(invalidPath, newDirName);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateDirectory_WithFileSystemPathId_ShouldReturnNewDirectory()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId parentPathId = _fileSystemPathIdFixture.Create(_pathDirTest);
|
||||
string newDirName = "NewDirectory";
|
||||
FileSystemPathId newDirPathId = _fileSystemPathIdFixture.Create(System.IO.Path.Combine(parentPathId.Path, newDirName));
|
||||
|
||||
_mockPlatformContext.PathStrategy.CombinePath(parentPathId, newDirName).Returns(Result.From(newDirPathId));
|
||||
_mockEnvironmentContext.DirectoryProviderService.DirectoryExists(newDirPathId).Returns(Result.From(false));
|
||||
|
||||
_mockEnvironmentContext.DirectoryProviderService.CreateDirectory(parentPathId, newDirName)
|
||||
.Returns(Result.From(newDirPathId));
|
||||
_mockEnvironmentContext.DirectoryProviderService.GetFileName(newDirPathId)
|
||||
.Returns(Result.From(newDirName));
|
||||
_mockEnvironmentContext.DirectoryProviderService.GetLastWriteTime(newDirPathId)
|
||||
.Returns(Result.From(Optional<DateTime>.FromNullable(DateTime.Now)));
|
||||
_mockEnvironmentContext.DirectoryProviderService.GetCreationTime(newDirPathId)
|
||||
.Returns(Result.From(Optional<DateTime>.FromNullable(DateTime.Now)));
|
||||
|
||||
// Act
|
||||
Result<Directory> result = _sut.CreateDirectory(parentPathId, newDirName);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(newDirPathId, result.Value.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateDirectory_WhenDirectoryProviderServiceReturnsError_ShouldPropagateError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId parentPathId = _fileSystemPathIdFixture.Create(_pathDirTest);
|
||||
string newDirName = "NewDirectory";
|
||||
FileSystemPathId newDirPathId = _fileSystemPathIdFixture.Create(System.IO.Path.Combine(parentPathId.Path, newDirName));
|
||||
|
||||
_mockPlatformContext.PathStrategy.CombinePath(parentPathId, newDirName).Returns(Result.From(newDirPathId));
|
||||
_mockEnvironmentContext.DirectoryProviderService.DirectoryExists(newDirPathId).Returns(Result.From(false));
|
||||
|
||||
_mockEnvironmentContext.DirectoryProviderService.CreateDirectory(parentPathId, newDirName)
|
||||
.Returns(Errors.Permission.UnauthorizedAccess);
|
||||
|
||||
// Act
|
||||
Result<Directory> result = _sut.CreateDirectory(parentPathId, newDirName);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateDirectory_WhenDirectoryDetailsAreInaccessible_ShouldReturnInaccessibleDirectory()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId parentPathId = _fileSystemPathIdFixture.Create(_pathDirTest);
|
||||
string newDirName = "NewDirectory";
|
||||
FileSystemPathId newDirPathId = _fileSystemPathIdFixture.Create(System.IO.Path.Combine(parentPathId.Path, newDirName));
|
||||
|
||||
_mockPlatformContext.PathStrategy.CombinePath(parentPathId, newDirName).Returns(Result.From(newDirPathId));
|
||||
_mockEnvironmentContext.DirectoryProviderService.DirectoryExists(newDirPathId).Returns(Result.From(false));
|
||||
|
||||
_mockEnvironmentContext.DirectoryProviderService.CreateDirectory(parentPathId, newDirName)
|
||||
.Returns(Result.From(newDirPathId));
|
||||
|
||||
_mockEnvironmentContext.DirectoryProviderService.GetFileName(newDirPathId)
|
||||
.Returns(Errors.Permission.UnauthorizedAccess);
|
||||
_mockEnvironmentContext.DirectoryProviderService.GetLastWriteTime(newDirPathId)
|
||||
.Returns(Errors.Permission.UnauthorizedAccess);
|
||||
_mockEnvironmentContext.DirectoryProviderService.GetCreationTime(newDirPathId)
|
||||
.Returns(Errors.Permission.UnauthorizedAccess);
|
||||
_mockEnvironmentContext.DirectoryProviderService.IsHidden(newDirPathId).Returns(true);
|
||||
|
||||
// Act
|
||||
Result<Directory> result = _sut.CreateDirectory(parentPathId, newDirName);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(FileSystemItemStatus.Inaccessible, result.Value.Status);
|
||||
Assert.Equal(newDirPathId, result.Value.Id);
|
||||
Assert.False(result.Value.DateCreated.HasValue);
|
||||
Assert.False(result.Value.DateModified.HasValue);
|
||||
Assert.True(result.Value.IsHidden);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateDirectory_WhenDirectoryExistsReturnsError_ShouldPropagateError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId parentPathId = _fileSystemPathIdFixture.Create(_pathDirTest);
|
||||
string newDirName = "NewDirectory";
|
||||
FileSystemPathId newDirPathId = _fileSystemPathIdFixture.Create(System.IO.Path.Combine(parentPathId.Path, newDirName));
|
||||
|
||||
_mockPlatformContext.PathStrategy.CombinePath(parentPathId, newDirName).Returns(Result.From(newDirPathId));
|
||||
_mockEnvironmentContext.DirectoryProviderService.DirectoryExists(newDirPathId)
|
||||
.Returns(Errors.Permission.UnauthorizedAccess);
|
||||
|
||||
// Act
|
||||
Result<Directory> result = _sut.CreateDirectory(parentPathId, newDirName);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateDirectory_WhenDirectoryAlreadyExists_ShouldReturnDirectoryAlreadyExistsError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId parentPathId = _fileSystemPathIdFixture.Create(_pathDirTest);
|
||||
string newDirName = "ExistingDirectory";
|
||||
FileSystemPathId newDirPathId = _fileSystemPathIdFixture.Create(System.IO.Path.Combine(parentPathId.Path, newDirName));
|
||||
_mockPlatformContext.PathStrategy.CombinePath(parentPathId, newDirName).Returns(Result.From(newDirPathId));
|
||||
|
||||
_mockEnvironmentContext.DirectoryProviderService.DirectoryExists(newDirPathId).Returns(true);
|
||||
|
||||
// Act
|
||||
Result<Directory> result = _sut.CreateDirectory(parentPathId, newDirName);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.DirectoryAlreadyExists, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateDirectory_WhenCombinePathReturnsError_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId parentPathId = _fileSystemPathIdFixture.Create(_pathDirTest);
|
||||
string newDirName = "NewDirectory";
|
||||
|
||||
_mockPlatformContext.PathStrategy.CombinePath(parentPathId, newDirName)
|
||||
.Returns(Errors.FileSystemManagement.InvalidPath);
|
||||
|
||||
// Act
|
||||
Result<Directory> result = _sut.CreateDirectory(parentPathId, newDirName);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
|
||||
// Verify that DirectoryExists was not called.
|
||||
_mockEnvironmentContext.DirectoryProviderService.DidNotReceive().DirectoryExists(Arg.Any<FileSystemPathId>());
|
||||
_mockEnvironmentContext.DirectoryProviderService.DidNotReceive().CreateDirectory(Arg.Any<FileSystemPathId>(), Arg.Any<string>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CopyDirectory_WhenSourceAndDestinationDoNotEndWithSeparator_ShouldAppendSeparatorAndReturnDirectoryNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
string sourcePath = s_isUnix ? "/TestDir/Source" : @"C:\TestDir\Source";
|
||||
string destinationPath = s_isUnix ? "/TestDir/Destination" : @"C:\TestDir\Destination";
|
||||
bool overrideExisting = true;
|
||||
_mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator);
|
||||
_mockEnvironmentContext.DirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>())
|
||||
.Returns(Result.From(false));
|
||||
|
||||
// Act
|
||||
Result<Directory> result = _sut.CopyDirectory(sourcePath, destinationPath, overrideExisting);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.DirectoryNotFound, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CopyDirectory_WhenSourceAndDestinationEndWithSeparator_ShouldReturnDirectoryNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
string sourcePath = s_isUnix ? "/TestDir/Source/" : @"C:\TestDir\Source\";
|
||||
string destinationPath = s_isUnix ? "/TestDir/Destination/" : @"C:\TestDir\Destination\";
|
||||
bool overrideExisting = true;
|
||||
_mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator);
|
||||
_mockEnvironmentContext.DirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>())
|
||||
.Returns(Result.From(false));
|
||||
|
||||
// Act
|
||||
Result<Directory> result = _sut.CopyDirectory(sourcePath, destinationPath, overrideExisting);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.DirectoryNotFound, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CopyDirectory_WhenDirectoryExistsReturnsError_ShouldPropagateError()
|
||||
{
|
||||
// Arrange
|
||||
string sourcePath = s_isUnix ? "/TestDir/Source" : @"C:\TestDir\Source";
|
||||
string destinationPath = s_isUnix ? "/TestDir/Destination" : @"C:\TestDir\Destination";
|
||||
bool overrideExisting = true;
|
||||
_mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator);
|
||||
_mockEnvironmentContext.DirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>())
|
||||
.Returns(Errors.Permission.UnauthorizedAccess);
|
||||
|
||||
// Act
|
||||
Result<Directory> result = _sut.CopyDirectory(sourcePath, destinationPath, overrideExisting);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CopyDirectory_WhenSourceDirectoryExists_ShouldThrowNotImplementedException()
|
||||
{
|
||||
// Arrange
|
||||
string sourcePath = s_isUnix ? "/TestDir/Source" : @"C:\TestDir\Source";
|
||||
string destinationPath = s_isUnix ? "/TestDir/Destination" : @"C:\TestDir\Destination";
|
||||
bool overrideExisting = true;
|
||||
_mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator);
|
||||
_mockEnvironmentContext.DirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>())
|
||||
.Returns(Result.From(true));
|
||||
|
||||
// Act & Assert
|
||||
Assert.Throws<NotImplementedException>(() => _sut.CopyDirectory(sourcePath, destinationPath, overrideExisting));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MoveDirectory_WhenSourceAndDestinationDoNotEndWithSeparator_ShouldAppendSeparatorAndReturnDirectoryNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
string sourcePath = s_isUnix ? "/TestDir/Source" : @"C:\TestDir\Source";
|
||||
string destinationPath = s_isUnix ? "/TestDir/Destination" : @"C:\TestDir\Destination";
|
||||
bool overrideExisting = true;
|
||||
_mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator);
|
||||
_mockEnvironmentContext.DirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>())
|
||||
.Returns(Result.From(false));
|
||||
|
||||
// Act
|
||||
Result<Directory> result = _sut.MoveDirectory(sourcePath, destinationPath, overrideExisting);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.DirectoryNotFound, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MoveDirectory_WhenSourceAndDestinationEndWithSeparator_ShouldReturnDirectoryNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
string sourcePath = s_isUnix ? "/TestDir/Source/" : @"C:\TestDir\Source\";
|
||||
string destinationPath = s_isUnix ? "/TestDir/Destination/" : @"C:\TestDir\Destination\";
|
||||
bool overrideExisting = true;
|
||||
_mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator);
|
||||
_mockEnvironmentContext.DirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>())
|
||||
.Returns(Result.From(false));
|
||||
|
||||
// Act
|
||||
Result<Directory> result = _sut.MoveDirectory(sourcePath, destinationPath, overrideExisting);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.DirectoryNotFound, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MoveDirectory_WhenDirectoryExistsReturnsError_ShouldPropagateError()
|
||||
{
|
||||
// Arrange
|
||||
string sourcePath = s_isUnix ? "/TestDir/Source" : @"C:\TestDir\Source";
|
||||
string destinationPath = s_isUnix ? "/TestDir/Destination" : @"C:\TestDir\Destination";
|
||||
bool overrideExisting = true;
|
||||
_mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator);
|
||||
_mockEnvironmentContext.DirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>())
|
||||
.Returns(Errors.Permission.UnauthorizedAccess);
|
||||
|
||||
// Act
|
||||
Result<Directory> result = _sut.MoveDirectory(sourcePath, destinationPath, overrideExisting);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MoveDirectory_WhenSourceDirectoryExists_ShouldThrowNotImplementedException()
|
||||
{
|
||||
// Arrange
|
||||
string sourcePath = s_isUnix ? "/TestDir/Source" : @"C:\TestDir\Source";
|
||||
string destinationPath = s_isUnix ? "/TestDir/Destination" : @"C:\TestDir\Destination";
|
||||
bool overrideExisting = true;
|
||||
_mockPlatformContext.PathStrategy.PathSeparator.Returns(_dirSeparator);
|
||||
_mockEnvironmentContext.DirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>())
|
||||
.Returns(Result.From(true));
|
||||
|
||||
// Act & Assert
|
||||
Assert.Throws<NotImplementedException>(() => _sut.MoveDirectory(sourcePath, destinationPath, overrideExisting));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenameDirectory_WithValidStringPath_ShouldReturnRenamedDirectory()
|
||||
{
|
||||
// Arrange
|
||||
string oldPath = s_isUnix ? "/TestDir/OldName" : @"C:\TestDir\OldName";
|
||||
string newName = "NewName";
|
||||
FileSystemPathId oldPathId = _fileSystemPathIdFixture.Create(oldPath);
|
||||
FileSystemPathId newPathId = _fileSystemPathIdFixture.Create(
|
||||
s_isUnix ? "/TestDir/NewName" : @"C:\TestDir\NewName"
|
||||
);
|
||||
|
||||
_mockPlatformContext.PathStrategy.CombinePath(oldPathId, newName).Returns(Result.From(newPathId));
|
||||
_mockEnvironmentContext.DirectoryProviderService.DirectoryExists(newPathId).Returns(Result.From(false));
|
||||
|
||||
_mockEnvironmentContext.DirectoryProviderService.RenameDirectory(oldPathId, newName)
|
||||
.Returns(Result.From(newPathId));
|
||||
_mockEnvironmentContext.DirectoryProviderService.GetFileName(newPathId)
|
||||
.Returns(Result.From(newName));
|
||||
_mockEnvironmentContext.DirectoryProviderService.GetLastWriteTime(newPathId)
|
||||
.Returns(Result.From(Optional<DateTime>.FromNullable(DateTime.Now)));
|
||||
_mockEnvironmentContext.DirectoryProviderService.GetCreationTime(newPathId)
|
||||
.Returns(Result.From(Optional<DateTime>.FromNullable(DateTime.Now)));
|
||||
_mockEnvironmentContext.DirectoryProviderService.IsHidden(newPathId).Returns(true);
|
||||
|
||||
// Act
|
||||
Result<Directory> result = _sut.RenameDirectory(oldPath, newName);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(newPathId, result.Value.Id);
|
||||
Assert.Equal(newName, result.Value.Name);
|
||||
Assert.True(result.Value.IsHidden);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenameDirectory_WithInvalidStringPath_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
string invalidPath = string.Empty;
|
||||
string newName = "NewName";
|
||||
|
||||
// Act
|
||||
Result<Directory> result = _sut.RenameDirectory(invalidPath, newName);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenameDirectory_WithFileSystemPathId_ShouldReturnRenamedDirectory()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId oldPathId = _fileSystemPathIdFixture.Create(
|
||||
s_isUnix ? "/TestDir/OldName" : @"C:\TestDir\OldName"
|
||||
);
|
||||
string newName = "NewName";
|
||||
FileSystemPathId newPathId = _fileSystemPathIdFixture.Create(
|
||||
s_isUnix ? "/TestDir/NewName" : @"C:\TestDir\NewName"
|
||||
);
|
||||
|
||||
_mockPlatformContext.PathStrategy.CombinePath(oldPathId, newName).Returns(Result.From(newPathId));
|
||||
_mockEnvironmentContext.DirectoryProviderService.DirectoryExists(newPathId).Returns(Result.From(false));
|
||||
|
||||
_mockEnvironmentContext.DirectoryProviderService.RenameDirectory(oldPathId, newName)
|
||||
.Returns(Result.From(newPathId));
|
||||
_mockEnvironmentContext.DirectoryProviderService.GetFileName(newPathId)
|
||||
.Returns(Result.From(newName));
|
||||
_mockEnvironmentContext.DirectoryProviderService.GetLastWriteTime(newPathId)
|
||||
.Returns(Result.From(Optional<DateTime>.FromNullable(DateTime.Now)));
|
||||
_mockEnvironmentContext.DirectoryProviderService.GetCreationTime(newPathId)
|
||||
.Returns(Result.From(Optional<DateTime>.FromNullable(DateTime.Now)));
|
||||
|
||||
// Act
|
||||
Result<Directory> result = _sut.RenameDirectory(oldPathId, newName);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(newPathId, result.Value.Id);
|
||||
Assert.Equal(newName, result.Value.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenameDirectory_WhenDirectoryProviderServiceReturnsError_ShouldPropagateError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId oldPathId = _fileSystemPathIdFixture.Create(
|
||||
s_isUnix ? "/TestDir/OldName" : @"C:\TestDir\OldName"
|
||||
);
|
||||
string newName = "NewName";
|
||||
FileSystemPathId newPathId = _fileSystemPathIdFixture.Create(
|
||||
s_isUnix ? "/TestDir/NewName" : @"C:\TestDir\NewName"
|
||||
);
|
||||
|
||||
_mockPlatformContext.PathStrategy.CombinePath(oldPathId, newName).Returns(Result.From(newPathId));
|
||||
_mockEnvironmentContext.DirectoryProviderService.DirectoryExists(newPathId).Returns(Result.From(false));
|
||||
|
||||
_mockEnvironmentContext.DirectoryProviderService.RenameDirectory(oldPathId, newName)
|
||||
.Returns(Errors.Permission.UnauthorizedAccess);
|
||||
|
||||
// Act
|
||||
Result<Directory> result = _sut.RenameDirectory(oldPathId, newName);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenameDirectory_WhenDirectoryDetailsAreInaccessible_ShouldReturnInaccessibleDirectory()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId oldPathId = _fileSystemPathIdFixture.Create(
|
||||
s_isUnix ? "/TestDir/OldName" : @"C:\TestDir\OldName"
|
||||
);
|
||||
string newName = "NewName";
|
||||
FileSystemPathId newPathId = _fileSystemPathIdFixture.Create(
|
||||
s_isUnix ? "/TestDir/NewName" : @"C:\TestDir\NewName"
|
||||
);
|
||||
|
||||
_mockPlatformContext.PathStrategy.CombinePath(oldPathId, newName).Returns(Result.From(newPathId));
|
||||
_mockEnvironmentContext.DirectoryProviderService.DirectoryExists(newPathId).Returns(Result.From(false));
|
||||
|
||||
_mockEnvironmentContext.DirectoryProviderService.RenameDirectory(oldPathId, newName)
|
||||
.Returns(Result.From(newPathId));
|
||||
|
||||
_mockEnvironmentContext.DirectoryProviderService.GetFileName(newPathId)
|
||||
.Returns(Errors.Permission.UnauthorizedAccess);
|
||||
_mockEnvironmentContext.DirectoryProviderService.GetLastWriteTime(newPathId)
|
||||
.Returns(Errors.Permission.UnauthorizedAccess);
|
||||
_mockEnvironmentContext.DirectoryProviderService.GetCreationTime(newPathId)
|
||||
.Returns(Errors.Permission.UnauthorizedAccess);
|
||||
_mockEnvironmentContext.DirectoryProviderService.IsHidden(newPathId).Returns(true);
|
||||
|
||||
// Act
|
||||
Result<Directory> result = _sut.RenameDirectory(oldPathId, newName);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(FileSystemItemStatus.Inaccessible, result.Value.Status);
|
||||
Assert.Equal(newPathId, result.Value.Id);
|
||||
Assert.True(result.Value.IsHidden);
|
||||
Assert.False(result.Value.DateCreated.HasValue);
|
||||
Assert.False(result.Value.DateModified.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenameDirectory_WhenDirectoryAlreadyExists_ShouldReturnDirectoryAlreadyExistsError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId oldPathId = _fileSystemPathIdFixture.Create(
|
||||
s_isUnix ? "/TestDir/OldName" : @"C:\TestDir\OldName"
|
||||
);
|
||||
string newName = "ExistingDirectory";
|
||||
FileSystemPathId newPathId = _fileSystemPathIdFixture.Create(
|
||||
s_isUnix ? "/TestDir/ExistingDirectory" : @"C:\TestDir\ExistingDirectory"
|
||||
);
|
||||
|
||||
_mockPlatformContext.PathStrategy.CombinePath(Arg.Any<FileSystemPathId>(), newName)
|
||||
.Returns(Result.From(newPathId));
|
||||
_mockEnvironmentContext.DirectoryProviderService.DirectoryExists(newPathId)
|
||||
.Returns(Result.From(true));
|
||||
|
||||
// Act
|
||||
Result<Directory> result = _sut.RenameDirectory(oldPathId, newName);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.DirectoryAlreadyExists, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenameDirectory_WhenCombinePathReturnsError_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId oldPathId = _fileSystemPathIdFixture.Create(
|
||||
s_isUnix ? "/TestDir/OldName" : @"C:\TestDir\OldName"
|
||||
);
|
||||
string newName = "NewName";
|
||||
|
||||
_mockPlatformContext.PathStrategy.CombinePath(Arg.Any<FileSystemPathId>(), newName)
|
||||
.Returns(Errors.FileSystemManagement.InvalidPath);
|
||||
|
||||
// Act
|
||||
Result<Directory> result = _sut.RenameDirectory(oldPathId, newName);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
|
||||
// Verify that DirectoryExists and RenameDirectory were not called.
|
||||
_mockEnvironmentContext.DirectoryProviderService.DidNotReceive().DirectoryExists(Arg.Any<FileSystemPathId>());
|
||||
_mockEnvironmentContext.DirectoryProviderService.DidNotReceive().RenameDirectory(Arg.Any<FileSystemPathId>(), Arg.Any<string>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenameDirectory_WhenDirectoryExistsReturnsError_ShouldPropagateError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId oldPathId = _fileSystemPathIdFixture.Create(
|
||||
s_isUnix ? "/TestDir/OldName" : @"C:\TestDir\OldName"
|
||||
);
|
||||
string newName = "NewName";
|
||||
FileSystemPathId newPathId = _fileSystemPathIdFixture.Create(
|
||||
s_isUnix ? "/TestDir/NewName" : @"C:\TestDir\NewName"
|
||||
);
|
||||
_mockPlatformContext.PathStrategy.CombinePath(Arg.Any<FileSystemPathId>(), newName)
|
||||
.Returns(Result.From(newPathId));
|
||||
|
||||
_mockEnvironmentContext.DirectoryProviderService.DirectoryExists(newPathId)
|
||||
.Returns(Errors.Permission.UnauthorizedAccess);
|
||||
|
||||
// Act
|
||||
Result<Directory> result = _sut.RenameDirectory(oldPathId, newName);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError);
|
||||
|
||||
// Verify that RenameDirectory was not called.
|
||||
_mockEnvironmentContext.DirectoryProviderService.DidNotReceive().RenameDirectory(Arg.Any<FileSystemPathId>(), Arg.Any<string>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DeleteDirectory_WithValidStringPath_ShouldReturnDeleted()
|
||||
{
|
||||
// Arrange
|
||||
string path = s_isUnix ? "/TestDir/ToDelete" : @"C:\TestDir\ToDelete";
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path);
|
||||
|
||||
_mockEnvironmentContext.DirectoryProviderService.DeleteDirectory(pathId)
|
||||
.Returns(Result.Deleted);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = _sut.DeleteDirectory(path);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Deleted, result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DeleteDirectory_WithInvalidStringPath_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
string invalidPath = string.Empty;
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = _sut.DeleteDirectory(invalidPath);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DeleteDirectory_WithFileSystemPathId_ShouldReturnDeleted()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(
|
||||
s_isUnix ? "/TestDir/ToDelete" : @"C:\TestDir\ToDelete"
|
||||
);
|
||||
|
||||
_mockEnvironmentContext.DirectoryProviderService.DeleteDirectory(pathId)
|
||||
.Returns(Result.Deleted);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = _sut.DeleteDirectory(pathId);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Deleted, result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DeleteDirectory_WhenDirectoryProviderServiceReturnsError_ShouldPropagateError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(
|
||||
s_isUnix ? "/TestDir/ToDelete" : @"C:\TestDir\ToDelete"
|
||||
);
|
||||
|
||||
_mockEnvironmentContext.DirectoryProviderService.DeleteDirectory(pathId)
|
||||
.Returns(Errors.Permission.UnauthorizedAccess);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = _sut.DeleteDirectory(pathId);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DeleteDirectory_WhenDirectoryDoesNotExist_ShouldReturnDirectoryNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(
|
||||
s_isUnix ? "/TestDir/NonExistent" : @"C:\TestDir\NonExistent"
|
||||
);
|
||||
|
||||
_mockEnvironmentContext.DirectoryProviderService.DeleteDirectory(pathId)
|
||||
.Returns(Errors.FileSystemManagement.DirectoryNotFound);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = _sut.DeleteDirectory(pathId);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.DirectoryNotFound, result.FirstError);
|
||||
}
|
||||
}
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.FileSystem;
|
||||
using NSubstitute;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO.Abstractions;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="DriveService"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DriveServiceTests
|
||||
{
|
||||
private readonly IFileSystem _mockFileSystem;
|
||||
private readonly IPlatformContextManager _mockPlatformContextManager;
|
||||
private readonly IPlatformContext _mockPlatformContext;
|
||||
private readonly DriveService _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DriveServiceTests"/> class.
|
||||
/// </summary>
|
||||
public DriveServiceTests()
|
||||
{
|
||||
_mockFileSystem = Substitute.For<IFileSystem>();
|
||||
_mockPlatformContextManager = Substitute.For<IPlatformContextManager>();
|
||||
_mockPlatformContext = Substitute.For<IPlatformContext>();
|
||||
_mockPlatformContextManager.GetCurrentContext().Returns(_mockPlatformContext);
|
||||
_sut = new DriveService(_mockFileSystem, _mockPlatformContextManager);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetDrives_OnUnixPlatform_ShouldReturnSingleUnixRootItem()
|
||||
{
|
||||
// Arrange
|
||||
_mockPlatformContext.Platform.Returns(PlatformType.Unix);
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<FileSystemItem>> result = _sut.GetDrives();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Single(result.Value);
|
||||
Assert.IsType<UnixRootItem>(result.Value.First());
|
||||
Assert.Equal(FileSystemItemStatus.Accessible, result.Value.First().Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetDrives_OnWindowsPlatform_ShouldReturnWindowsRootItems()
|
||||
{
|
||||
// Arrange
|
||||
_mockPlatformContext.Platform.Returns(PlatformType.Windows);
|
||||
IDriveInfo[] mockDrives =
|
||||
[
|
||||
CreateMockDriveInfo("C:\\", true),
|
||||
CreateMockDriveInfo("D:\\", true),
|
||||
CreateMockDriveInfo("E:\\", false) // Not ready.
|
||||
];
|
||||
_mockFileSystem.DriveInfo.GetDrives().Returns(mockDrives);
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<FileSystemItem>> result = _sut.GetDrives();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(2, result.Value.Count()); // Only ready drives.
|
||||
Assert.All(result.Value, item => Assert.IsType<WindowsRootItem>(item));
|
||||
Assert.Equal(["C:\\", "D:\\"], result.Value.Select(d => d.Name));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetDrives_OnWindowsPlatformWithDriveWithInvalidName_ShouldExcludeThatDrive()
|
||||
{
|
||||
// Arrange
|
||||
_mockPlatformContext.Platform.Returns(PlatformType.Windows);
|
||||
IDriveInfo[] mockDrives =
|
||||
[
|
||||
CreateMockDriveInfo("C:\\", true),
|
||||
CreateMockDriveInfo("", true) // Drive whose name cannot be turned into a valid path.
|
||||
];
|
||||
_mockFileSystem.DriveInfo.GetDrives().Returns(mockDrives);
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<FileSystemItem>> result = _sut.GetDrives();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Single(result.Value);
|
||||
Assert.Equal("C:\\", result.Value.First().Name);
|
||||
}
|
||||
|
||||
private static IDriveInfo CreateMockDriveInfo(string name, bool isReady)
|
||||
{
|
||||
IDriveInfo mockDriveInfo = Substitute.For<IDriveInfo>();
|
||||
mockDriveInfo.Name.Returns(name);
|
||||
mockDriveInfo.IsReady.Returns(isReady);
|
||||
return mockDriveInfo;
|
||||
}
|
||||
}
|
||||
+996
@@ -0,0 +1,996 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using AutoFixture;
|
||||
using AutoFixture.AutoNSubstitute;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.FileSystem;
|
||||
using NSubstitute;
|
||||
using NSubstitute.ExceptionExtensions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.IO.Abstractions;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="FileProviderService"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FileProviderServiceTests
|
||||
{
|
||||
private readonly IFixture _fixture;
|
||||
private readonly IFileSystem _mockFileSystem;
|
||||
private readonly IFileSystemPermissionsService _mockFileSystemPermissionsService;
|
||||
private readonly FileProviderService _sut;
|
||||
private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new();
|
||||
private static readonly bool s_isUnix = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
|
||||
private readonly string _pathVisible1 = s_isUnix ? "/Visible.txt" : @"C:\Visible.txt";
|
||||
private readonly string _pathHidden1 = s_isUnix ? "/Hidden.txt" : @"C:\Hidden.txt";
|
||||
private readonly string _pathValid1 = s_isUnix ? "/Valid.txt" : @"C:\Valid.txt";
|
||||
private readonly string _pathInvalid1 = s_isUnix ? "/Invalid.txt" : @"C:\Invalid.txt";
|
||||
private readonly string _pathSourceFile = s_isUnix ? "/Source/file.txt" : @"C:\Source\file.txt";
|
||||
private readonly string _pathDestinationFile = s_isUnix ? "/Destination/file.txt" : @"C:\Destination\file.txt";
|
||||
private readonly string _pathSource = s_isUnix ? "/Source" : @"C:\Source";
|
||||
private readonly string _pathDestination = s_isUnix ? "/Destination" : @"C:\Destination";
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="FileProviderServiceTests"/> class.
|
||||
/// </summary>
|
||||
public FileProviderServiceTests()
|
||||
{
|
||||
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
|
||||
_mockFileSystem = Substitute.For<IFileSystem>();
|
||||
_mockFileSystemPermissionsService = Substitute.For<IFileSystemPermissionsService>();
|
||||
_sut = new FileProviderService(_mockFileSystem, _mockFileSystemPermissionsService);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetFilePaths_WhenUserHasNoAccess_ShouldReturnUnauthorizedAccessError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create();
|
||||
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory).Returns(false);
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<FileSystemPathId>> result = _sut.GetFilePaths(path, false);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetFilePaths_WhenUserHasAccess_ShouldReturnFiles()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create();
|
||||
string[] files = [.. _fixture.CreateMany<string>(3)];
|
||||
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory).Returns(true);
|
||||
_mockFileSystem.Directory.GetFiles(path.Path).Returns(files);
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<FileSystemPathId>> result = _sut.GetFilePaths(path, false);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(3, result.Value.Count());
|
||||
Assert.Equal(
|
||||
files.OrderBy(f => f),
|
||||
result.Value.Select(x => x.Path).OrderBy(f => f)
|
||||
);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetFilePaths_WhenShouldIncludeHiddenElementsIsFalse_ShouldExcludeHiddenFiles()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create();
|
||||
string[] files = [_pathVisible1, _pathHidden1];
|
||||
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory).Returns(true);
|
||||
_mockFileSystem.Directory.GetFiles(path.Path).Returns(files);
|
||||
_mockFileSystem.File.GetAttributes(_pathVisible1).Returns(FileAttributes.Normal);
|
||||
_mockFileSystem.File.GetAttributes(_pathHidden1).Returns(FileAttributes.Hidden);
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<FileSystemPathId>> result = _sut.GetFilePaths(path, false);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Single(result.Value);
|
||||
Assert.Equal(_pathVisible1, result.Value.First().Path);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetFilePaths_WhenShouldIncludeHiddenElementsIsTrue_ShouldIncludeHiddenFiles()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create();
|
||||
string[] files = [_pathVisible1, _pathHidden1];
|
||||
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory).Returns(true);
|
||||
_mockFileSystem.Directory.GetFiles(path.Path).Returns(files);
|
||||
_mockFileSystem.File.GetAttributes(_pathVisible1).Returns(FileAttributes.Normal);
|
||||
_mockFileSystem.File.GetAttributes(_pathHidden1).Returns(FileAttributes.Hidden);
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<FileSystemPathId>> result = _sut.GetFilePaths(path, true);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(2, result.Value.Count());
|
||||
Assert.Equal(
|
||||
new[] { _pathVisible1, _pathHidden1 }.OrderBy(p => p),
|
||||
result.Value.Select(x => x.Path).OrderBy(p => p)
|
||||
);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetFilePaths_WhenGetAttributesThrowsException_ShouldStillAddFile()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create();
|
||||
string[] files = [_pathValid1, _pathInvalid1];
|
||||
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory).Returns(true);
|
||||
_mockFileSystem.Directory.GetFiles(path.Path).Returns(files);
|
||||
_mockFileSystem.File.GetAttributes(_pathValid1).Returns(FileAttributes.Normal);
|
||||
_mockFileSystem.File.GetAttributes(_pathInvalid1).Throws(new Exception("Access denied"));
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<FileSystemPathId>> result = _sut.GetFilePaths(path, false);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(2, result.Value.Count());
|
||||
Assert.Equal([_pathInvalid1, _pathValid1], result.Value.Select(x => x.Path));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetFilePaths_WhenCalled_ShouldOrderFilesAlphabetically()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create();
|
||||
string[] files = s_isUnix
|
||||
? ["/C.txt", "/A.txt", "/B.txt"]
|
||||
: [@"C:\C.txt", @"C:\A.txt", @"C:\B.txt"];
|
||||
string[] expectedFiles = s_isUnix
|
||||
? ["/A.txt", "/B.txt", "/C.txt"]
|
||||
: [@"C:\A.txt", @"C:\B.txt", @"C:\C.txt"];
|
||||
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory).Returns(true);
|
||||
_mockFileSystem.Directory.GetFiles(path.Path).Returns(files);
|
||||
_mockFileSystem.File.GetAttributes(Arg.Any<string>()).Returns(FileAttributes.Normal);
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<FileSystemPathId>> result = _sut.GetFilePaths(path, false);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(expectedFiles, result.Value.Select(x => x.Path));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetFilePaths_WhenDirectoryHasNoFiles_ShouldReturnEmptyList()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create();
|
||||
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ListDirectory).Returns(true);
|
||||
_mockFileSystem.Directory.GetFiles(path.Path).Returns([]);
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<FileSystemPathId>> result = _sut.GetFilePaths(path, false);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Empty(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsHidden_WhenFileHasHiddenAttribute_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create(_pathHidden1);
|
||||
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties).Returns(true);
|
||||
_mockFileSystem.File.GetAttributes(path.Path).Returns(FileAttributes.Hidden);
|
||||
|
||||
// Act
|
||||
bool result = _sut.IsHidden(path);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsHidden_WhenFileDoesNotHaveHiddenAttribute_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create(_pathVisible1);
|
||||
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties).Returns(true);
|
||||
_mockFileSystem.File.GetAttributes(path.Path).Returns(FileAttributes.Normal);
|
||||
|
||||
// Act
|
||||
bool result = _sut.IsHidden(path);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsHidden_WhenGetAttributesThrowsException_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create(_pathInvalid1);
|
||||
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties).Returns(true);
|
||||
_mockFileSystem.File.GetAttributes(path.Path).Throws(new Exception("Access denied"));
|
||||
|
||||
// Act
|
||||
bool result = _sut.IsHidden(path);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsHidden_WhenUserHasNoAccess_ShouldReturnFalseWithoutReadingAttributes()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create(_pathHidden1);
|
||||
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties).Returns(false);
|
||||
|
||||
// Act
|
||||
bool result = _sut.IsHidden(path);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
_mockFileSystem.File.DidNotReceive().GetAttributes(Arg.Any<string>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FileExists_WhenFileExists_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create();
|
||||
_mockFileSystem.File.Exists(path.Path).Returns(true);
|
||||
|
||||
// Act
|
||||
Result<bool> result = _sut.FileExists(path);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.True(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FileExists_WhenFileDoesNotExist_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create();
|
||||
_mockFileSystem.File.Exists(path.Path).Returns(false);
|
||||
|
||||
// Act
|
||||
Result<bool> result = _sut.FileExists(path);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.False(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetFileName_WhenPathIsValid_ShouldReturnFileName()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create();
|
||||
string expectedFileName = "testfile.txt";
|
||||
_mockFileSystem.Path.GetFileName(path.Path).Returns(expectedFileName);
|
||||
|
||||
// Act
|
||||
Result<string> result = _sut.GetFileName(path);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(expectedFileName, result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetFileName_WhenPathIsEmpty_ShouldReturnEmptyString()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create();
|
||||
_mockFileSystem.Path.GetFileName(path.Path).Returns(string.Empty);
|
||||
|
||||
// Act
|
||||
Result<string> result = _sut.GetFileName(path);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Empty(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetFileAsync_WhenUserHasAccess_ShouldReturnFileContents()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create();
|
||||
byte[] expectedContents = [1, 2, 3, 4, 5];
|
||||
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents).Returns(true);
|
||||
_mockFileSystem.File.ReadAllBytes(path.Path).Returns(expectedContents);
|
||||
|
||||
// Act
|
||||
Result<byte[]> result = _sut.GetFileAsync(path);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(expectedContents, result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetFileAsync_WhenUserHasNoAccess_ShouldReturnUnauthorizedAccessError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create();
|
||||
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents).Returns(false);
|
||||
|
||||
// Act
|
||||
Result<byte[]> result = _sut.GetFileAsync(path);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetFileAsync_WhenFileIsEmpty_ShouldReturnEmptyByteArray()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create();
|
||||
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents).Returns(true);
|
||||
_mockFileSystem.File.ReadAllBytes(path.Path).Returns([]);
|
||||
|
||||
// Act
|
||||
Result<byte[]> result = _sut.GetFileAsync(path);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Empty(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetLastWriteTime_WhenUserHasAccess_ShouldReturnLastWriteTime()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create();
|
||||
DateTime expectedDateTime = new(2024, 1, 2, 3, 4, 5);
|
||||
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties).Returns(true);
|
||||
_mockFileSystem.File.GetLastWriteTime(path.Path).Returns(expectedDateTime);
|
||||
|
||||
// Act
|
||||
Result<Optional<DateTime>> result = _sut.GetLastWriteTime(path);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.True(result.Value.HasValue);
|
||||
Assert.Equal(expectedDateTime, result.Value.Value, TimeSpan.FromSeconds(1));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetLastWriteTime_WhenUserHasNoAccess_ShouldReturnUnauthorizedAccessError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create();
|
||||
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties).Returns(false);
|
||||
|
||||
// Act
|
||||
Result<Optional<DateTime>> result = _sut.GetLastWriteTime(path);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetCreationTime_WhenUserHasAccess_ShouldReturnCreationTime()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create();
|
||||
DateTime expectedDateTime = new(2024, 1, 2, 3, 4, 5);
|
||||
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties).Returns(true);
|
||||
_mockFileSystem.File.GetCreationTime(path.Path).Returns(expectedDateTime);
|
||||
|
||||
// Act
|
||||
Result<Optional<DateTime>> result = _sut.GetCreationTime(path);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.True(result.Value.HasValue);
|
||||
Assert.Equal(expectedDateTime, result.Value.Value, TimeSpan.FromSeconds(1));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetCreationTime_WhenUserHasNoAccess_ShouldReturnUnauthorizedAccessError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create();
|
||||
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties).Returns(false);
|
||||
|
||||
// Act
|
||||
Result<Optional<DateTime>> result = _sut.GetCreationTime(path);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetSize_WhenUserHasAccess_ShouldReturnFileSize()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create();
|
||||
long expectedSize = 42;
|
||||
IFileInfo mockFileInfo = Substitute.For<IFileInfo>();
|
||||
mockFileInfo.Length.Returns(expectedSize);
|
||||
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties).Returns(true);
|
||||
_mockFileSystem.FileInfo.New(path.Path).Returns(mockFileInfo);
|
||||
|
||||
// Act
|
||||
Result<long?> result = _sut.GetSize(path);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(expectedSize, result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetSize_WhenUserHasNoAccess_ShouldReturnUnauthorizedAccessError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create();
|
||||
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties).Returns(false);
|
||||
|
||||
// Act
|
||||
Result<long?> result = _sut.GetSize(path);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetSize_WhenFileDoesNotExist_ShouldReturnZero()
|
||||
{
|
||||
// Arrange
|
||||
string nonExistentFilePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create(nonExistentFilePath);
|
||||
|
||||
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties).Returns(true);
|
||||
_mockFileSystem.FileInfo.New(path.Path).Returns((IFileInfo)null!);
|
||||
|
||||
// Act
|
||||
Result<long?> result = _sut.GetSize(path);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(0, result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CopyFile_WhenSourceFileExistsAndUserHasAccess_ShouldCopyFileAndReturnPath()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId sourcePath = _fileSystemPathIdFixture.Create(_pathSourceFile);
|
||||
FileSystemPathId destinationPath = _fileSystemPathIdFixture.Create(_pathDestination);
|
||||
bool overrideExisting = false;
|
||||
|
||||
_mockFileSystem.File.Exists(sourcePath.Path).Returns(true);
|
||||
_mockFileSystem.File.Exists(Path.Combine(destinationPath.Path, "file.txt")).Returns(false);
|
||||
|
||||
_mockFileSystem.Path.GetFileName(sourcePath.Path).Returns("file.txt");
|
||||
_mockFileSystem.Path.Combine(destinationPath.Path, "file.txt").Returns(_pathDestinationFile);
|
||||
|
||||
// Act
|
||||
Result<FileSystemPathId> result = _sut.CopyFile(sourcePath, destinationPath, overrideExisting);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(_pathDestinationFile, result.Value.Path);
|
||||
_mockFileSystem.File.Received(1).Copy(sourcePath.Path, _pathDestinationFile, overrideExisting);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CopyFile_WhenSourceFileDoesNotExist_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId sourcePath = _fileSystemPathIdFixture.Create();
|
||||
FileSystemPathId destinationPath = _fileSystemPathIdFixture.Create();
|
||||
bool overrideExisting = false;
|
||||
|
||||
_mockFileSystem.File.Exists(sourcePath.Path).Returns(false);
|
||||
|
||||
// Act
|
||||
Result<FileSystemPathId> result = _sut.CopyFile(sourcePath, destinationPath, overrideExisting);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CopyFile_WhenDestinationFileExistsAndOverrideIsFalse_ShouldReturnFileAlreadyExistsError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId sourcePath = _fileSystemPathIdFixture.Create(_pathSourceFile);
|
||||
FileSystemPathId destinationPath = _fileSystemPathIdFixture.Create(_pathDestination);
|
||||
string expectedDestinationFilePath = _pathDestinationFile;
|
||||
bool overrideExisting = false;
|
||||
|
||||
_mockFileSystem.File.Exists(sourcePath.Path).Returns(true);
|
||||
_mockFileSystem.File.Exists(expectedDestinationFilePath).Returns(true);
|
||||
|
||||
_mockFileSystem.Path.GetFileName(sourcePath.Path).Returns("file.txt");
|
||||
_mockFileSystem.Path.GetDirectoryName(sourcePath.Path).Returns(_pathSource);
|
||||
|
||||
_mockFileSystem.Path.Combine(Arg.Any<string>(), Arg.Any<string>())
|
||||
.Returns(callInfo => Path.Combine(callInfo.ArgAt<string>(0), callInfo.ArgAt<string>(1)));
|
||||
|
||||
// Act
|
||||
Result<FileSystemPathId> result = _sut.CopyFile(sourcePath, destinationPath, overrideExisting);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.FileAlreadyExists, result.FirstError);
|
||||
_mockFileSystem.File.DidNotReceive().Copy(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CopyFile_WhenOverrideExistingIsTrue_ShouldOverwriteExistingFile()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId sourcePath = _fileSystemPathIdFixture.Create(_pathSourceFile);
|
||||
FileSystemPathId destinationPath = _fileSystemPathIdFixture.Create(_pathDestination);
|
||||
bool overrideExisting = true;
|
||||
|
||||
_mockFileSystem.File.Exists(sourcePath.Path).Returns(true);
|
||||
_mockFileSystem.File.Exists(_pathDestinationFile).Returns(true);
|
||||
|
||||
_mockFileSystem.Path.GetFileName(sourcePath.Path).Returns("file.txt");
|
||||
_mockFileSystem.Path.Combine(destinationPath.Path, "file.txt").Returns(_pathDestinationFile);
|
||||
|
||||
// Act
|
||||
Result<FileSystemPathId> result = _sut.CopyFile(sourcePath, destinationPath, overrideExisting);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(_pathDestinationFile, result.Value.Path);
|
||||
_mockFileSystem.File.Received(1).Copy(sourcePath.Path, _pathDestinationFile, overrideExisting);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CopyFile_WhenExceptionOccurs_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId sourcePath = _fileSystemPathIdFixture.Create();
|
||||
FileSystemPathId destinationPath = _fileSystemPathIdFixture.Create();
|
||||
bool overrideExisting = false;
|
||||
|
||||
_mockFileSystem.File.Exists(sourcePath.Path).Returns(true);
|
||||
_mockFileSystem.File.When(x => x.Copy(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>()))
|
||||
.Do(x => { throw new Exception("Simulated error"); });
|
||||
|
||||
// Act
|
||||
Result<FileSystemPathId> result = _sut.CopyFile(sourcePath, destinationPath, overrideExisting);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.FileCopyError, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CopyFile_WhenCopyingToSameDirectory_ShouldCreateUniqueFileName()
|
||||
{
|
||||
// Arrange
|
||||
string sourceDirectory = _pathSource;
|
||||
FileSystemPathId sourcePath = _fileSystemPathIdFixture.Create(Path.Combine(sourceDirectory, "file.txt"));
|
||||
FileSystemPathId destinationPath = _fileSystemPathIdFixture.Create(sourceDirectory);
|
||||
string expectedNewFilePath = Path.Combine(sourceDirectory, "file - Copy (1).txt");
|
||||
bool overrideExisting = false;
|
||||
|
||||
_mockFileSystem.File.Exists(sourcePath.Path).Returns(true);
|
||||
_mockFileSystem.File.Exists(Path.Combine(sourceDirectory, "file.txt")).Returns(true);
|
||||
_mockFileSystem.File.Exists(expectedNewFilePath).Returns(false);
|
||||
|
||||
_mockFileSystem.Path.GetFileName(sourcePath.Path).Returns("file.txt");
|
||||
_mockFileSystem.Path.GetDirectoryName(sourcePath.Path).Returns(sourceDirectory);
|
||||
_mockFileSystem.Path.GetFileNameWithoutExtension(Arg.Any<string>()).Returns(x => Path.GetFileNameWithoutExtension(x.Arg<string>()));
|
||||
_mockFileSystem.Path.GetExtension(Arg.Any<string>()).Returns(x => Path.GetExtension(x.Arg<string>()));
|
||||
|
||||
_mockFileSystem.Path.Combine(Arg.Any<string>(), Arg.Any<string>())
|
||||
.Returns(callInfo => Path.Combine(callInfo.ArgAt<string>(0), callInfo.ArgAt<string>(1)));
|
||||
|
||||
// Simulate the behavior of CreateUniqueFilePath.
|
||||
int copyNumber = 1;
|
||||
_mockFileSystem.File.Exists(Arg.Any<string>())
|
||||
.Returns(x =>
|
||||
{
|
||||
string path = x.Arg<string>();
|
||||
if (path == expectedNewFilePath)
|
||||
return false;
|
||||
copyNumber++;
|
||||
return true;
|
||||
});
|
||||
|
||||
// Act
|
||||
Result<FileSystemPathId> result = _sut.CopyFile(sourcePath, destinationPath, overrideExisting);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(expectedNewFilePath, result.Value.Path);
|
||||
_mockFileSystem.File.Received(1).Copy(sourcePath.Path, expectedNewFilePath, overrideExisting);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MoveFile_WhenSourceFileDoesNotExist_ShouldReturnFileNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId sourcePath = _fileSystemPathIdFixture.Create(
|
||||
s_isUnix ? "/NonExistentSource.txt" : @"C:\NonExistentSource.txt"
|
||||
);
|
||||
FileSystemPathId destinationPath = _fileSystemPathIdFixture.Create(_pathDestination);
|
||||
bool overrideExisting = false;
|
||||
|
||||
_mockFileSystem.File.Exists(sourcePath.Path).Returns(false);
|
||||
|
||||
// Act
|
||||
Result<FileSystemPathId> result = _sut.MoveFile(sourcePath, destinationPath, overrideExisting);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MoveFile_WhenDestinationFileDoesNotExist_ShouldPerformSimpleMove()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId sourcePath = _fileSystemPathIdFixture.Create(_pathSourceFile);
|
||||
FileSystemPathId destinationPath = _fileSystemPathIdFixture.Create(_pathDestination);
|
||||
string destinationFilePath = _pathDestinationFile;
|
||||
bool overrideExisting = false;
|
||||
|
||||
_mockFileSystem.File.Exists(sourcePath.Path).Returns(true);
|
||||
_mockFileSystem.File.Exists(destinationFilePath).Returns(false);
|
||||
_mockFileSystem.Path.GetFileName(sourcePath.Path).Returns("file.txt");
|
||||
_mockFileSystem.Path.Combine(destinationPath.Path, "file.txt").Returns(destinationFilePath);
|
||||
|
||||
// Act
|
||||
Result<FileSystemPathId> result = _sut.MoveFile(sourcePath, destinationPath, overrideExisting);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(destinationFilePath, result.Value.Path);
|
||||
_mockFileSystem.File.Received(1).Move(sourcePath.Path, destinationFilePath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MoveFile_WhenDestinationFileExistsAndOverrideIsTrue_ShouldOverwriteFile()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId sourcePath = _fileSystemPathIdFixture.Create(_pathSourceFile);
|
||||
FileSystemPathId destinationPath = _fileSystemPathIdFixture.Create(_pathDestination);
|
||||
string destinationFilePath = _pathDestinationFile;
|
||||
bool overrideExisting = true;
|
||||
|
||||
_mockFileSystem.File.Exists(sourcePath.Path).Returns(true);
|
||||
_mockFileSystem.File.Exists(destinationFilePath).Returns(true);
|
||||
_mockFileSystem.Path.GetFileName(sourcePath.Path).Returns("file.txt");
|
||||
_mockFileSystem.Path.Combine(destinationPath.Path, "file.txt").Returns(destinationFilePath);
|
||||
|
||||
// Act
|
||||
Result<FileSystemPathId> result = _sut.MoveFile(sourcePath, destinationPath, overrideExisting);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(destinationFilePath, result.Value.Path);
|
||||
_mockFileSystem.File.Received(1).Move(sourcePath.Path, destinationFilePath, overrideExisting);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MoveFile_WhenDestinationFileExistsAndOverrideIsFalse_ShouldReturnFileAlreadyExistsError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId sourcePath = _fileSystemPathIdFixture.Create(_pathSourceFile);
|
||||
FileSystemPathId destinationPath = _fileSystemPathIdFixture.Create(_pathDestination);
|
||||
string destinationFilePath = _pathDestinationFile;
|
||||
bool overrideExisting = false;
|
||||
|
||||
_mockFileSystem.File.Exists(sourcePath.Path).Returns(true);
|
||||
_mockFileSystem.File.Exists(destinationFilePath).Returns(true);
|
||||
_mockFileSystem.Path.GetFileName(sourcePath.Path).Returns("file.txt");
|
||||
_mockFileSystem.Path.Combine(destinationPath.Path, "file.txt").Returns(destinationFilePath);
|
||||
|
||||
// Act
|
||||
Result<FileSystemPathId> result = _sut.MoveFile(sourcePath, destinationPath, overrideExisting);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.FileAlreadyExists, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MoveFile_WhenExceptionOccurs_ShouldReturnFileMoveError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId sourcePath = _fileSystemPathIdFixture.Create(_pathSourceFile);
|
||||
FileSystemPathId destinationPath = _fileSystemPathIdFixture.Create(_pathDestination);
|
||||
string destinationFilePath = _pathDestinationFile;
|
||||
bool overrideExisting = false;
|
||||
|
||||
_mockFileSystem.File.Exists(sourcePath.Path).Returns(true);
|
||||
_mockFileSystem.File.Exists(destinationFilePath).Returns(false);
|
||||
_mockFileSystem.Path.GetFileName(sourcePath.Path).Returns("file.txt");
|
||||
_mockFileSystem.Path.Combine(destinationPath.Path, "file.txt").Returns(destinationFilePath);
|
||||
_mockFileSystem.File.When(x => x.Move(Arg.Any<string>(), Arg.Any<string>()))
|
||||
.Do(x => throw new IOException("Simulated IO error"));
|
||||
|
||||
// Act
|
||||
Result<FileSystemPathId> result = _sut.MoveFile(sourcePath, destinationPath, overrideExisting);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.FileMoveError, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenameFile_WhenParentDirectoryIsWritable_ShouldRenameSuccessfully()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create(
|
||||
s_isUnix ? "/OldName.txt" : @"C:\OldName.txt"
|
||||
);
|
||||
string newName = "NewName.txt";
|
||||
string parentPath = s_isUnix ? "/" : @"C:\";
|
||||
string newPath = s_isUnix ? "/NewName.txt" : @"C:\NewName.txt";
|
||||
|
||||
IFileInfo fileInfo = Substitute.For<IFileInfo>();
|
||||
fileInfo.DirectoryName.Returns(parentPath);
|
||||
_mockFileSystem.FileInfo.New(path.Path).Returns(fileInfo);
|
||||
_mockFileSystem.Path.Combine(parentPath, newName).Returns(newPath);
|
||||
_mockFileSystemPermissionsService.CanAccessPath(Arg.Any<FileSystemPathId>(), FileAccessMode.Write).Returns(true);
|
||||
|
||||
// Act
|
||||
Result<FileSystemPathId> result = _sut.RenameFile(path, newName);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(newPath, result.Value.Path);
|
||||
_mockFileSystem.File.Received(1).Move(path.Path, newPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenameFile_WhenParentDirectoryIsNotWritable_ShouldReturnUnauthorizedAccessError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create(
|
||||
s_isUnix ? "/OldName.txt" : @"C:\OldName.txt"
|
||||
);
|
||||
string newName = "NewName.txt";
|
||||
string parentPath = s_isUnix ? "/" : @"C:\";
|
||||
string newPath = s_isUnix ? "/NewName.txt" : @"C:\NewName.txt";
|
||||
|
||||
IFileInfo fileInfo = Substitute.For<IFileInfo>();
|
||||
fileInfo.DirectoryName.Returns(parentPath);
|
||||
_mockFileSystem.FileInfo.New(path.Path).Returns(fileInfo);
|
||||
_mockFileSystem.Path.Combine(parentPath, newName).Returns(newPath);
|
||||
_mockFileSystemPermissionsService.CanAccessPath(Arg.Any<FileSystemPathId>(), FileAccessMode.Write).Returns(false);
|
||||
|
||||
// Act
|
||||
Result<FileSystemPathId> result = _sut.RenameFile(path, newName);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError);
|
||||
_mockFileSystem.File.DidNotReceive().Move(Arg.Any<string>(), Arg.Any<string>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenameFile_WhenParentDirectoryIsNull_ShouldReturnInvalidPathError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create(
|
||||
s_isUnix ? "/OldName.txt" : @"C:\OldName.txt"
|
||||
);
|
||||
string newName = "NewName.txt";
|
||||
|
||||
_mockFileSystem.FileInfo.New(path.Path).Returns((IFileInfo)null!);
|
||||
|
||||
// Act
|
||||
Result<FileSystemPathId> result = _sut.RenameFile(path, newName);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.CannotNavigateUp, result.FirstError);
|
||||
_mockFileSystem.File.DidNotReceive().Move(Arg.Any<string>(), Arg.Any<string>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenameFile_WhenNewPathIsInvalid_ShouldReturnInvalidPathError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create(
|
||||
s_isUnix ? "/OldName.txt" : @"C:\OldName.txt"
|
||||
);
|
||||
string newName = "NewName.txt";
|
||||
string parentPath = s_isUnix ? "/" : @"C:\";
|
||||
|
||||
IFileInfo fileInfo = Substitute.For<IFileInfo>();
|
||||
fileInfo.DirectoryName.Returns(parentPath);
|
||||
_mockFileSystem.FileInfo.New(path.Path).Returns(fileInfo);
|
||||
_mockFileSystem.Path.Combine(parentPath, newName).Returns((string)null!);
|
||||
|
||||
// Act
|
||||
Result<FileSystemPathId> result = _sut.RenameFile(path, newName);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
_mockFileSystem.File.DidNotReceive().Move(Arg.Any<string>(), Arg.Any<string>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenameFile_WhenParentDirectoryPathIsWhitespace_ShouldReturnInvalidPathError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create(
|
||||
s_isUnix ? "/OldName.txt" : @"C:\OldName.txt"
|
||||
);
|
||||
string newName = "NewName.txt";
|
||||
|
||||
IFileInfo fileInfo = Substitute.For<IFileInfo>();
|
||||
fileInfo.DirectoryName.Returns(" ");
|
||||
_mockFileSystem.FileInfo.New(path.Path).Returns(fileInfo);
|
||||
|
||||
// Act
|
||||
Result<FileSystemPathId> result = _sut.RenameFile(path, newName);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
_mockFileSystem.File.DidNotReceive().Move(Arg.Any<string>(), Arg.Any<string>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenameFile_WhenNewPathIsWhitespace_ShouldReturnInvalidPathError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create(
|
||||
s_isUnix ? "/OldName.txt" : @"C:\OldName.txt"
|
||||
);
|
||||
string newName = "NewName.txt";
|
||||
string parentPath = s_isUnix ? "/" : @"C:\";
|
||||
|
||||
IFileInfo fileInfo = Substitute.For<IFileInfo>();
|
||||
fileInfo.DirectoryName.Returns(parentPath);
|
||||
_mockFileSystem.FileInfo.New(path.Path).Returns(fileInfo);
|
||||
_mockFileSystem.Path.Combine(parentPath, newName).Returns(" ");
|
||||
|
||||
// Act
|
||||
Result<FileSystemPathId> result = _sut.RenameFile(path, newName);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
_mockFileSystem.File.DidNotReceive().Move(Arg.Any<string>(), Arg.Any<string>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenameFile_WhenParentDirectoryExistsButNotWritable_ShouldReturnUnauthorizedAccessError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create(
|
||||
s_isUnix ? "/OldName.txt" : @"C:\OldName.txt"
|
||||
);
|
||||
string newName = "NewName.txt";
|
||||
string parentPath = s_isUnix ? "/" : @"C:\";
|
||||
string newPath = s_isUnix ? "/NewName.txt" : @"C:\NewName.txt";
|
||||
|
||||
IFileInfo fileInfo = Substitute.For<IFileInfo>();
|
||||
fileInfo.DirectoryName.Returns(parentPath);
|
||||
_mockFileSystem.FileInfo.New(path.Path).Returns(fileInfo);
|
||||
_mockFileSystem.Path.Combine(parentPath, newName).Returns(newPath);
|
||||
|
||||
// Mock successful creation of parent directory FileSystemPathId.
|
||||
FileSystemPathId parentDirectoryPathId = _fileSystemPathIdFixture.Create(parentPath);
|
||||
_mockFileSystem.Path.GetDirectoryName(path.Path).Returns(parentPath);
|
||||
|
||||
// Mock permissions: executable for the file, but not writable for the parent directory.
|
||||
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Execute).Returns(true);
|
||||
_mockFileSystemPermissionsService.CanAccessPath(Arg.Is<FileSystemPathId>(x => x.Path == parentPath), FileAccessMode.Write).Returns(false);
|
||||
|
||||
// Act
|
||||
Result<FileSystemPathId> result = _sut.RenameFile(path, newName);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError);
|
||||
_mockFileSystem.File.DidNotReceive().Move(Arg.Any<string>(), Arg.Any<string>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DeleteFile_WhenFileExistsAndHasDeletePermission_ShouldDeleteSuccessfully()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create(
|
||||
s_isUnix ? "/FileToDelete.txt" : @"C:\FileToDelete.txt"
|
||||
);
|
||||
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Delete).Returns(true);
|
||||
_mockFileSystem.File.Exists(path.Path).Returns(true);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = _sut.DeleteFile(path);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Deleted, result.Value);
|
||||
_mockFileSystem.File.Received(1).Delete(path.Path);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DeleteFile_WhenNoDeletePermission_ShouldReturnUnauthorizedAccessError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create(
|
||||
s_isUnix ? "/FileToDelete.txt" : @"C:\FileToDelete.txt"
|
||||
);
|
||||
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Delete).Returns(false);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = _sut.DeleteFile(path);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError);
|
||||
_mockFileSystem.File.DidNotReceive().Delete(Arg.Any<string>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DeleteFile_WhenTheFileIsLocked_ShouldReturnFileDeleteError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create(
|
||||
s_isUnix ? "/LockedFileToDelete.txt" : @"C:\LockedFileToDelete.txt"
|
||||
);
|
||||
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Delete).Returns(true);
|
||||
_mockFileSystem.File.When(file => file.Delete(path.Path))
|
||||
.Do(_ => throw new IOException("The file is locked by another process"));
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = _sut.DeleteFile(path);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.FileDeleteError, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DeleteFile_WhenTheFileIsReadOnly_ShouldReturnUnauthorizedAccessError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create(
|
||||
s_isUnix ? "/ReadOnlyFileToDelete.txt" : @"C:\ReadOnlyFileToDelete.txt"
|
||||
);
|
||||
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Delete).Returns(true);
|
||||
_mockFileSystem.File.When(file => file.Delete(path.Path))
|
||||
.Do(_ => throw new UnauthorizedAccessException("The file is read-only"));
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = _sut.DeleteFile(path);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError);
|
||||
}
|
||||
}
|
||||
+1432
File diff suppressed because it is too large.
Load diff
+142
@@ -0,0 +1,142 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Runtime.InteropServices;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="FileSystemStructureSeedService"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FileSystemStructureSeedServiceTests
|
||||
{
|
||||
private readonly IEnvironmentContext _mockEnvironmentContext;
|
||||
private readonly IDirectoryProviderService _mockDirectoryProviderService;
|
||||
private readonly IPathService _mockPathService;
|
||||
private readonly FileSystemStructureSeedService _sut;
|
||||
private static readonly bool s_isUnix = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
|
||||
private readonly string _rootPath = s_isUnix ? "/Lumina" : @"C:\Lumina";
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="FileSystemStructureSeedServiceTests"/> class.
|
||||
/// </summary>
|
||||
public FileSystemStructureSeedServiceTests()
|
||||
{
|
||||
_mockEnvironmentContext = Substitute.For<IEnvironmentContext>();
|
||||
_mockDirectoryProviderService = Substitute.For<IDirectoryProviderService>();
|
||||
_mockPathService = Substitute.For<IPathService>();
|
||||
_mockEnvironmentContext.DirectoryProviderService.Returns(_mockDirectoryProviderService);
|
||||
_sut = new FileSystemStructureSeedService(_mockEnvironmentContext, _mockPathService);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SetDefaultDirectories_WhenDirectoriesDoNotExist_ShouldCreateThem()
|
||||
{
|
||||
// Arrange
|
||||
_mockPathService.CombinePath(_rootPath, "libraries").Returns(Path.Combine(_rootPath, "libraries"));
|
||||
_mockPathService.CombinePath(_rootPath, "books").Returns(Path.Combine(_rootPath, "books"));
|
||||
_mockPathService.CombinePath(_rootPath, "music").Returns(Path.Combine(_rootPath, "music"));
|
||||
_mockDirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>()).Returns(false);
|
||||
_mockDirectoryProviderService.CreateDirectory(Arg.Any<FileSystemPathId>(), Arg.Any<string>())
|
||||
.Returns(callInfo => Result<FileSystemPathId>.Success(FileSystemPathId.Create(Path.Combine(_rootPath, callInfo.ArgAt<string>(1))).Value));
|
||||
|
||||
// Act
|
||||
Result<Created> result = _sut.SetDefaultDirectories(_rootPath);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
_mockDirectoryProviderService.Received(3).DirectoryExists(Arg.Any<FileSystemPathId>());
|
||||
_mockDirectoryProviderService.Received(3).CreateDirectory(Arg.Any<FileSystemPathId>(), Arg.Any<string>());
|
||||
_mockDirectoryProviderService.Received(1).CreateDirectory(Arg.Any<FileSystemPathId>(), "libraries");
|
||||
_mockDirectoryProviderService.Received(1).CreateDirectory(Arg.Any<FileSystemPathId>(), "books");
|
||||
_mockDirectoryProviderService.Received(1).CreateDirectory(Arg.Any<FileSystemPathId>(), "music");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SetDefaultDirectories_WhenDirectoriesAlreadyExist_ShouldNotCreateThem()
|
||||
{
|
||||
// Arrange
|
||||
_mockPathService.CombinePath(_rootPath, "libraries").Returns(Path.Combine(_rootPath, "libraries"));
|
||||
_mockPathService.CombinePath(_rootPath, "books").Returns(Path.Combine(_rootPath, "books"));
|
||||
_mockPathService.CombinePath(_rootPath, "music").Returns(Path.Combine(_rootPath, "music"));
|
||||
_mockDirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>()).Returns(true);
|
||||
|
||||
// Act
|
||||
Result<Created> result = _sut.SetDefaultDirectories(_rootPath);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
_mockDirectoryProviderService.Received(3).DirectoryExists(Arg.Any<FileSystemPathId>());
|
||||
_mockDirectoryProviderService.DidNotReceive().CreateDirectory(Arg.Any<FileSystemPathId>(), Arg.Any<string>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SetDefaultDirectories_WhenRootPathIsInvalid_ShouldReturnInvalidPathError()
|
||||
{
|
||||
// Act
|
||||
Result<Created> result = _sut.SetDefaultDirectories(" ");
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
_mockPathService.DidNotReceive().CombinePath(Arg.Any<string>(), Arg.Any<string>());
|
||||
_mockDirectoryProviderService.DidNotReceive().DirectoryExists(Arg.Any<FileSystemPathId>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SetDefaultDirectories_WhenCombiningPathFails_ShouldReturnTheError()
|
||||
{
|
||||
// Arrange
|
||||
_mockPathService.CombinePath(_rootPath, "libraries").Returns(Errors.FileSystemManagement.InvalidPath);
|
||||
|
||||
// Act
|
||||
Result<Created> result = _sut.SetDefaultDirectories(_rootPath);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
_mockDirectoryProviderService.DidNotReceive().DirectoryExists(Arg.Any<FileSystemPathId>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SetDefaultDirectories_WhenCheckingDirectoryExistenceFails_ShouldReturnTheError()
|
||||
{
|
||||
// Arrange
|
||||
_mockPathService.CombinePath(_rootPath, "libraries").Returns(Path.Combine(_rootPath, "libraries"));
|
||||
_mockDirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>()).Returns(Errors.FileSystemManagement.DirectoryNotFound);
|
||||
|
||||
// Act
|
||||
Result<Created> result = _sut.SetDefaultDirectories(_rootPath);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.DirectoryNotFound, result.FirstError);
|
||||
_mockDirectoryProviderService.DidNotReceive().CreateDirectory(Arg.Any<FileSystemPathId>(), Arg.Any<string>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SetDefaultDirectories_WhenCreatingDirectoryFails_ShouldReturnTheError()
|
||||
{
|
||||
// Arrange
|
||||
_mockPathService.CombinePath(_rootPath, "libraries").Returns(Path.Combine(_rootPath, "libraries"));
|
||||
_mockDirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>()).Returns(false);
|
||||
_mockDirectoryProviderService.CreateDirectory(Arg.Any<FileSystemPathId>(), Arg.Any<string>())
|
||||
.Returns(Errors.FileSystemManagement.DirectoryAlreadyExists);
|
||||
|
||||
// Act
|
||||
Result<Created> result = _sut.SetDefaultDirectories(_rootPath);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.DirectoryAlreadyExists, result.FirstError);
|
||||
}
|
||||
}
|
||||
+228
@@ -0,0 +1,228 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.FileSystem;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary;
|
||||
using NSubstitute;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO.Abstractions.TestingHelpers;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="FileTypeService"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FileTypeServiceTests
|
||||
{
|
||||
private MockFileSystem _mockFileSystem = null!;
|
||||
private readonly IFileSystemPermissionsService _mockFileSystemPermissionsService;
|
||||
private FileTypeService? sut;
|
||||
private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new();
|
||||
private readonly FileFixture _fileFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="FileTypeServiceTests"/> class.
|
||||
/// </summary>
|
||||
public FileTypeServiceTests()
|
||||
{
|
||||
_mockFileSystemPermissionsService = Substitute.For<IFileSystemPermissionsService>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetImageTypeAsync_WithValidFile_ShouldReturnCorrectImageType()
|
||||
{
|
||||
// Arrange
|
||||
File file = _fileFixture.Create();
|
||||
byte[] pngHeader = [137, 80, 78, 71, 13, 10, 26, 10];
|
||||
byte[] fileContent = [.. pngHeader, .. Enumerable.Repeat<byte>(0, 100)];
|
||||
|
||||
SetupMockFileSystem(file.Id, fileContent);
|
||||
sut = new FileTypeService(_mockFileSystem, _mockFileSystemPermissionsService);
|
||||
_mockFileSystemPermissionsService.CanAccessPath(file.Id, FileAccessMode.ReadContents).Returns(true);
|
||||
|
||||
// Act
|
||||
Result<ImageType> result = await sut.GetImageTypeAsync(file, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(ImageType.PNG, result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetImageTypeAsync_WithUnauthorizedAccess_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
File file = _fileFixture.Create();
|
||||
|
||||
SetupMockFileSystem(file.Id, []);
|
||||
sut = new FileTypeService(_mockFileSystem, _mockFileSystemPermissionsService);
|
||||
|
||||
_mockFileSystemPermissionsService.CanAccessPath(file.Id, FileAccessMode.ReadContents).Returns(false);
|
||||
|
||||
// Act
|
||||
Result<ImageType> result = await sut.GetImageTypeAsync(file, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetImageTypeAsync_WithSmallFile_ShouldReturnNone()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(@"C:\test.jpg");
|
||||
byte[] fileContent = [1, 2, 3]; // Less than BUFFER_SIZE.
|
||||
|
||||
SetupMockFileSystem(pathId, fileContent);
|
||||
sut = new FileTypeService(_mockFileSystem, _mockFileSystemPermissionsService);
|
||||
_mockFileSystemPermissionsService.CanAccessPath(pathId, FileAccessMode.ReadContents).Returns(true);
|
||||
|
||||
// Act
|
||||
Result<ImageType> result = await sut.GetImageTypeAsync(pathId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(ImageType.None, result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetImageTypeAsync_WithSvgFile_ShouldReturnSvgType()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(@"C:\test.svg");
|
||||
string svgContent = "<svg xmlns=\"http://www.w3.org/2000/svg\"></svg>";
|
||||
byte[] fileContent = Encoding.UTF8.GetBytes(svgContent);
|
||||
|
||||
SetupMockFileSystem(pathId, fileContent);
|
||||
sut = new FileTypeService(_mockFileSystem, _mockFileSystemPermissionsService);
|
||||
_mockFileSystemPermissionsService.CanAccessPath(pathId, FileAccessMode.ReadContents).Returns(true);
|
||||
|
||||
// Act
|
||||
Result<ImageType> result = await sut.GetImageTypeAsync(pathId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(ImageType.SVG, result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetImageTypeAsync_WithTgaFile_ShouldReturnTgaType()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(@"C:\test.tga");
|
||||
byte[] tgaHeader = new byte[18];
|
||||
tgaHeader[2] = 2; // Set image type to 2 (uncompressed true-color image).
|
||||
byte[] fileContent = [.. tgaHeader, .. Enumerable.Repeat<byte>(0, 100)];
|
||||
|
||||
SetupMockFileSystem(pathId, fileContent);
|
||||
sut = new FileTypeService(_mockFileSystem, _mockFileSystemPermissionsService);
|
||||
|
||||
_mockFileSystemPermissionsService.CanAccessPath(pathId, FileAccessMode.ReadContents).Returns(true);
|
||||
|
||||
// Act
|
||||
Result<ImageType> result = await sut.GetImageTypeAsync(pathId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(ImageType.TGA, result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetImageTypeAsync_WithUnknownImageType_ShouldReturnNone()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(@"C:\test.unknown");
|
||||
byte[] fileContent = [.. Enumerable.Repeat<byte>(0, 100)];
|
||||
|
||||
SetupMockFileSystem(pathId, fileContent);
|
||||
sut = new FileTypeService(_mockFileSystem, _mockFileSystemPermissionsService);
|
||||
_mockFileSystemPermissionsService.CanAccessPath(pathId, FileAccessMode.ReadContents).Returns(true);
|
||||
|
||||
// Act
|
||||
Result<ImageType> result = await sut.GetImageTypeAsync(pathId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(ImageType.None, result.Value);
|
||||
}
|
||||
|
||||
private void SetupMockFileSystem(FileSystemPathId pathId, byte[] fileContent)
|
||||
{
|
||||
MockFileSystem mockFileSystem = new(new Dictionary<string, MockFileData>
|
||||
{
|
||||
{ pathId.Path, new MockFileData(fileContent) }
|
||||
});
|
||||
|
||||
_mockFileSystem = mockFileSystem;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetImageTypeAsync_WithSvgFileStartingWithXmlDeclaration_ShouldReturnSvgType()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(@"C:\test.svg");
|
||||
string svgContent = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<svg xmlns=\"http://www.w3.org/2000/svg\"></svg>";
|
||||
byte[] fileContent = Encoding.UTF8.GetBytes(svgContent);
|
||||
|
||||
SetupMockFileSystem(pathId, fileContent);
|
||||
sut = new FileTypeService(_mockFileSystem, _mockFileSystemPermissionsService);
|
||||
|
||||
_mockFileSystemPermissionsService.CanAccessPath(pathId, FileAccessMode.ReadContents).Returns(true);
|
||||
|
||||
// Act
|
||||
Result<ImageType> result = await sut.GetImageTypeAsync(pathId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(ImageType.SVG, result.Value);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(new byte[] { 66, 77 }, ImageType.BMP, "BMP")]
|
||||
[InlineData(new byte[] { 71, 73, 70 }, ImageType.GIF, "GIF")]
|
||||
[InlineData(new byte[] { 137, 80, 78, 71 }, ImageType.PNG, "PNG")]
|
||||
[InlineData(new byte[] { 73, 73, 42 }, ImageType.TIFF, "TIFF (Little Endian)")]
|
||||
[InlineData(new byte[] { 77, 77, 42 }, ImageType.TIFF, "TIFF (Big Endian)")]
|
||||
[InlineData(new byte[] { 255, 216, 255, 224 }, ImageType.JPEG, "JPEG")]
|
||||
[InlineData(new byte[] { 255, 216, 255, 225 }, ImageType.JPEG_CANON, "JPEG (Canon)")]
|
||||
[InlineData(new byte[] { 255, 216, 255, 226 }, ImageType.JPEG_UNKNOWN, "JPEG (Unknown)")]
|
||||
[InlineData(new byte[] { 0x00, 0x11, 0x02, 0xFF }, ImageType.PICT, "PICT")]
|
||||
[InlineData(new byte[] { 0x00, 0x00, 0x01, 0x00 }, ImageType.ICO, "ICO")]
|
||||
[InlineData(new byte[] { 0x38, 0x42, 0x50, 0x53 }, ImageType.PSD, "PSD")]
|
||||
[InlineData(new byte[] { 0xFF, 0x4F, 0xFF, 0x51 }, ImageType.JPEG2000, "JPEG 2000")]
|
||||
[InlineData(new byte[] { 0x00, 0x00, 0x00, 0x0C, 0x6A, 0x70, 0x20, 0x20 }, ImageType.AVIF, "AVIF")]
|
||||
[InlineData(new byte[] { 0x00, 0x00, 0x00, 0x0C, 0x6A, 0x50, 0x20, 0x20 }, ImageType.JPEG2000, "JPEG 2000 (variant)")]
|
||||
[InlineData(new byte[] { 0x52, 0x49, 0x46, 0x46, 0x00, 0x00, 0x00, 0x00, 0x57, 0x45, 0x42, 0x50 }, ImageType.WEBP, "WEBP")]
|
||||
[InlineData(new byte[] { 0x00, 0x00, 0x00, 0x00 }, ImageType.None, "Unknown")]
|
||||
public async Task GetImageTypeAsync_WithVariousImageTypes_ShouldIdentifyCorrectly(byte[] header, ImageType expectedType, string testName)
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create($@"C:\test.{testName.ToLower()}");
|
||||
byte[] fileContent = [.. header, .. Enumerable.Repeat<byte>(0, 100)];
|
||||
|
||||
SetupMockFileSystem(pathId, fileContent);
|
||||
sut = new FileTypeService(_mockFileSystem, _mockFileSystemPermissionsService);
|
||||
|
||||
_mockFileSystemPermissionsService.CanAccessPath(pathId, FileAccessMode.ReadContents).Returns(true);
|
||||
|
||||
// Act
|
||||
Result<ImageType> result = await sut.GetImageTypeAsync(pathId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(expectedType, result.Value);
|
||||
}
|
||||
}
|
||||
+939
@@ -0,0 +1,939 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Path;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="PathService"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PathServiceTests
|
||||
{
|
||||
private readonly IPlatformContextManager _mockPlatformContextManager;
|
||||
private readonly IPlatformContext _mockPlatformContext;
|
||||
private readonly IPathStrategy _mockPathStrategy;
|
||||
private readonly PathService _sut;
|
||||
private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new();
|
||||
private readonly PathSegmentFixture _pathSegmentFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PathServiceTests"/> class.
|
||||
/// </summary>
|
||||
public PathServiceTests()
|
||||
{
|
||||
_mockPlatformContextManager = Substitute.For<IPlatformContextManager>();
|
||||
_mockPlatformContext = Substitute.For<IPlatformContext>();
|
||||
_mockPathStrategy = Substitute.For<IPathStrategy>();
|
||||
_mockPlatformContext.PathStrategy.Returns(_mockPathStrategy);
|
||||
_mockPlatformContextManager.GetCurrentContext().Returns(_mockPlatformContext);
|
||||
_sut = new PathService(_mockPlatformContextManager);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PathSeparator_WhenAccessed_ShouldReturnPathStrategySeparator()
|
||||
{
|
||||
// Arrange
|
||||
char expectedSeparator = '\\';
|
||||
_mockPathStrategy.PathSeparator.Returns(expectedSeparator);
|
||||
|
||||
// Act
|
||||
char result = _sut.PathSeparator;
|
||||
|
||||
// Assert
|
||||
Assert.Equal(expectedSeparator, result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsValidPath_WithValidPath_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
string validPath = @"C:\ValidPath";
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(validPath);
|
||||
_mockPathStrategy.IsValidPath(pathId).Returns(true);
|
||||
|
||||
// Act
|
||||
bool result = _sut.IsValidPath(validPath);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
_mockPathStrategy.Received(1).IsValidPath(Arg.Is<FileSystemPathId>(id => id.Path == validPath));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsValidPath_WithInvalidPath_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
string invalidPath = @"C:\Invalid\*Path";
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(invalidPath);
|
||||
_mockPathStrategy.IsValidPath(pathId).Returns(false);
|
||||
|
||||
// Act
|
||||
bool result = _sut.IsValidPath(invalidPath);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
_mockPathStrategy.Received(1).IsValidPath(Arg.Is<FileSystemPathId>(id => id.Path == invalidPath));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsValidPath_WithEmptyPath_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
string emptyPath = string.Empty;
|
||||
|
||||
// Act
|
||||
bool result = _sut.IsValidPath(emptyPath);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
_mockPathStrategy.DidNotReceive().IsValidPath(Arg.Any<FileSystemPathId>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsValidPath_WithNullPath_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
string? nullPath = null;
|
||||
|
||||
// Act
|
||||
bool result = _sut.IsValidPath(nullPath!);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
_mockPathStrategy.DidNotReceive().IsValidPath(Arg.Any<FileSystemPathId>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Exists_WithValidExistingPath_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
string existingPath = @"C:\ExistingPath";
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(existingPath);
|
||||
_mockPathStrategy.Exists(pathId).Returns(true);
|
||||
|
||||
// Act
|
||||
bool result = _sut.Exists(existingPath);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
_mockPathStrategy.Received(1).Exists(Arg.Is<FileSystemPathId>(id => id.Path == existingPath));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Exists_WhenPathIsHiddenAndShouldIncludeHiddenElementsIsTrue_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
string existingPath = @"C:\ExistingPath";
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(existingPath);
|
||||
_mockPathStrategy.Exists(pathId, true).Returns(true);
|
||||
|
||||
// Act
|
||||
bool result = _sut.Exists(existingPath, true);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
_mockPathStrategy.Received(1).Exists(Arg.Is<FileSystemPathId>(id => id.Path == existingPath));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Exists_WhenPathIsHiddenAndShouldIncludeHiddenElementsIsFalse_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
string existingPath = @"C:\ExistingPath";
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(existingPath);
|
||||
_mockPathStrategy.Exists(pathId, false).Returns(false);
|
||||
|
||||
// Act
|
||||
bool result = _sut.Exists(existingPath, false);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
_mockPathStrategy.Received(1).Exists(Arg.Is<FileSystemPathId>(id => id.Path == existingPath), false);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Exists_WithValidNonExistingPath_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
string nonExistingPath = @"C:\NonExistingPath";
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(nonExistingPath);
|
||||
_mockPathStrategy.Exists(pathId).Returns(false);
|
||||
|
||||
// Act
|
||||
bool result = _sut.Exists(nonExistingPath);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
_mockPathStrategy.Received(1).Exists(Arg.Is<FileSystemPathId>(id => id.Path == nonExistingPath));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Exists_WithEmptyPath_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
string emptyPath = string.Empty;
|
||||
|
||||
// Act
|
||||
bool result = _sut.Exists(emptyPath);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
_mockPathStrategy.DidNotReceive().Exists(Arg.Any<FileSystemPathId>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Exists_WithNullPath_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
string? nullPath = null;
|
||||
|
||||
// Act
|
||||
bool result = _sut.Exists(nullPath!);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
_mockPathStrategy.DidNotReceive().Exists(Arg.Any<FileSystemPathId>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CombinePath_WithValidPathAndName_ShouldReturnCombinedPath()
|
||||
{
|
||||
// Arrange
|
||||
string path = @"C:\BaseDir";
|
||||
string name = "SubDir";
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path);
|
||||
FileSystemPathId combinedPathId = _fileSystemPathIdFixture.Create(@"C:\BaseDir\SubDir");
|
||||
_mockPathStrategy.CombinePath(pathId, name).Returns(Result.From(combinedPathId));
|
||||
|
||||
// Act
|
||||
Result<string> result = _sut.CombinePath(path, name);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(@"C:\BaseDir\SubDir", result.Value);
|
||||
_mockPathStrategy.Received(1).CombinePath(Arg.Is<FileSystemPathId>(id => id.Path == path), name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CombinePath_WithInvalidPath_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
string invalidPath = string.Empty;
|
||||
string name = "SubDir";
|
||||
|
||||
// Act
|
||||
Result<string> result = _sut.CombinePath(invalidPath, name);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
_mockPathStrategy.DidNotReceive().CombinePath(Arg.Any<FileSystemPathId>(), Arg.Any<string>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CombinePath_WhenPathStrategyReturnsError_ShouldPropagateError()
|
||||
{
|
||||
// Arrange
|
||||
string path = @"C:\BaseDir";
|
||||
string name = "Invalid*Name";
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path);
|
||||
_mockPathStrategy.CombinePath(pathId, name).Returns(Errors.FileSystemManagement.InvalidPath);
|
||||
|
||||
// Act
|
||||
Result<string> result = _sut.CombinePath(path, name);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
_mockPathStrategy.Received(1).CombinePath(Arg.Is<FileSystemPathId>(id => id.Path == path), name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CombinePath_WithNullName_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
string path = @"C:\BaseDir";
|
||||
string? name = null;
|
||||
|
||||
// Act
|
||||
Result<string> result = _sut.CombinePath(path, name!);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
_mockPathStrategy.DidNotReceive().CombinePath(Arg.Any<FileSystemPathId>(), Arg.Any<string>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ParsePath_WithValidPath_ShouldReturnPathSegments()
|
||||
{
|
||||
// Arrange
|
||||
string validPath = @"C:\ValidPath\SubDir";
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(validPath);
|
||||
List<PathSegment> expectedSegments = _pathSegmentFixture.CreateMany();
|
||||
_mockPathStrategy.ParsePath(pathId).Returns(Result.From(expectedSegments.AsEnumerable()));
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<PathSegment>> result = _sut.ParsePath(validPath);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(expectedSegments, result.Value);
|
||||
_mockPathStrategy.Received(1).ParsePath(Arg.Is<FileSystemPathId>(id => id.Path == validPath));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ParsePath_WithInvalidPath_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
string invalidPath = string.Empty;
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<PathSegment>> result = _sut.ParsePath(invalidPath);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
_mockPathStrategy.DidNotReceive().ParsePath(Arg.Any<FileSystemPathId>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ParsePath_WhenPathStrategyReturnsError_ShouldPropagateError()
|
||||
{
|
||||
// Arrange
|
||||
string path = @"C:\InvalidPath\*SubDir";
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path);
|
||||
_mockPathStrategy.ParsePath(pathId).Returns(Errors.FileSystemManagement.InvalidPath);
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<PathSegment>> result = _sut.ParsePath(path);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
_mockPathStrategy.Received(1).ParsePath(Arg.Is<FileSystemPathId>(id => id.Path == path));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ParsePath_WithNullPath_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
string? nullPath = null;
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<PathSegment>> result = _sut.ParsePath(nullPath!);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
_mockPathStrategy.DidNotReceive().ParsePath(Arg.Any<FileSystemPathId>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GoUpOneLevel_WithValidPath_ShouldReturnParentPathSegments()
|
||||
{
|
||||
// Arrange
|
||||
string validPath = @"C:\ValidPath\SubDir";
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(validPath);
|
||||
List<PathSegment> expectedSegments = _pathSegmentFixture.CreateMany(2); // Assuming parent path has 2 segments.
|
||||
_mockPathStrategy.GoUpOneLevel(pathId).Returns(Result.From(expectedSegments.AsEnumerable()));
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<PathSegment>> result = _sut.GoUpOneLevel(validPath);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(expectedSegments, result.Value);
|
||||
_mockPathStrategy.Received(1).GoUpOneLevel(Arg.Is<FileSystemPathId>(id => id.Path == validPath));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GoUpOneLevel_WithRootPath_ShouldReturnEmptySegmentList()
|
||||
{
|
||||
// Arrange
|
||||
string rootPath = @"C:\";
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(rootPath);
|
||||
List<PathSegment> emptySegmentList = [];
|
||||
_mockPathStrategy.GoUpOneLevel(pathId).Returns(Result.From(emptySegmentList.AsEnumerable()));
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<PathSegment>> result = _sut.GoUpOneLevel(rootPath);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Empty(result.Value);
|
||||
_mockPathStrategy.Received(1).GoUpOneLevel(Arg.Is<FileSystemPathId>(id => id.Path == rootPath));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GoUpOneLevel_WithInvalidPath_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
string invalidPath = string.Empty;
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<PathSegment>> result = _sut.GoUpOneLevel(invalidPath);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
_mockPathStrategy.DidNotReceive().GoUpOneLevel(Arg.Any<FileSystemPathId>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GoUpOneLevel_WhenPathStrategyReturnsError_ShouldPropagateError()
|
||||
{
|
||||
// Arrange
|
||||
string path = @"C:\InvalidPath\*SubDir";
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path);
|
||||
_mockPathStrategy.GoUpOneLevel(pathId).Returns(Errors.FileSystemManagement.InvalidPath);
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<PathSegment>> result = _sut.GoUpOneLevel(path);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
_mockPathStrategy.Received(1).GoUpOneLevel(Arg.Is<FileSystemPathId>(id => id.Path == path));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GoUpOneLevel_WithNullPath_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
string? nullPath = null;
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<PathSegment>> result = _sut.GoUpOneLevel(nullPath!);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
_mockPathStrategy.DidNotReceive().GoUpOneLevel(Arg.Any<FileSystemPathId>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetInvalidPathCharsForPlatform_WhenCalled_ShouldReturnInvalidCharsFromPathStrategy()
|
||||
{
|
||||
// Arrange
|
||||
char[] expectedInvalidChars = ['<', '>', ':', '"', '|', '?', '*'];
|
||||
_mockPathStrategy.GetInvalidPathCharsForPlatform().Returns(expectedInvalidChars);
|
||||
|
||||
// Act
|
||||
char[] result = _sut.GetInvalidPathCharsForPlatform();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(expectedInvalidChars, result);
|
||||
_mockPathStrategy.Received(1).GetInvalidPathCharsForPlatform();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetInvalidPathCharsForPlatform_WhenPathStrategyReturnsEmptyArray_ShouldReturnEmptyArray()
|
||||
{
|
||||
// Arrange
|
||||
char[] emptyArray = [];
|
||||
_mockPathStrategy.GetInvalidPathCharsForPlatform().Returns(emptyArray);
|
||||
|
||||
// Act
|
||||
char[] result = _sut.GetInvalidPathCharsForPlatform();
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result);
|
||||
_mockPathStrategy.Received(1).GetInvalidPathCharsForPlatform();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetInvalidPathCharsForPlatform_WhenReturnedArrayIsModified_ShouldNotAffectSubsequentCalls()
|
||||
{
|
||||
// Arrange
|
||||
char[] originalInvalidChars = ['<', '>', ':', '"', '|', '?', '*'];
|
||||
_mockPathStrategy.GetInvalidPathCharsForPlatform().Returns(_ => (char[])originalInvalidChars.Clone());
|
||||
|
||||
// Act
|
||||
char[] result = _sut.GetInvalidPathCharsForPlatform();
|
||||
result[0] = 'X'; // Attempt to modify the returned array.
|
||||
|
||||
// Assert
|
||||
char[] secondResult = _sut.GetInvalidPathCharsForPlatform();
|
||||
Assert.Equal(originalInvalidChars, secondResult);
|
||||
_mockPathStrategy.Received(2).GetInvalidPathCharsForPlatform();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetPathRoot_WhenCalledWithValidPath_ShouldReturnRootPathSegment()
|
||||
{
|
||||
// Arrange
|
||||
string validPath = @"C:\ValidPath\SubDir";
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(validPath);
|
||||
PathSegment expectedRootSegment = _pathSegmentFixture.Create(name: "C:", isDirectory: false, isDrive: true);
|
||||
_mockPathStrategy.GetPathRoot(pathId).Returns(Result.From(expectedRootSegment));
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.GetPathRoot(validPath);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(expectedRootSegment, result.Value);
|
||||
_mockPathStrategy.Received(1).GetPathRoot(Arg.Is<FileSystemPathId>(id => id.Path == validPath));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetPathRoot_WhenCalledWithInvalidPath_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
string invalidPath = string.Empty;
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.GetPathRoot(invalidPath);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
_mockPathStrategy.DidNotReceive().GetPathRoot(Arg.Any<FileSystemPathId>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetPathRoot_WhenPathStrategyReturnsError_ShouldPropagateError()
|
||||
{
|
||||
// Arrange
|
||||
string path = @"C:\InvalidPath\*SubDir";
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path);
|
||||
_mockPathStrategy.GetPathRoot(pathId).Returns(Errors.FileSystemManagement.InvalidPath);
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.GetPathRoot(path);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
_mockPathStrategy.Received(1).GetPathRoot(Arg.Is<FileSystemPathId>(id => id.Path == path));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetPathRoot_WhenCalledWithNullPath_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
string? nullPath = null;
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.GetPathRoot(nullPath!);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
_mockPathStrategy.DidNotReceive().GetPathRoot(Arg.Any<FileSystemPathId>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SanitizeSegment_WithValidName_ShouldReturnTheNameAsASegment()
|
||||
{
|
||||
// Arrange
|
||||
char[] invalidChars = ['<', '>', ':', '"', '|', '?', '*'];
|
||||
_mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(invalidChars);
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.SanitizeSegment("Valid Name");
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal("Valid Name", result.Value.Name);
|
||||
_mockPathStrategy.Received(1).GetInvalidPathSegmentCharsForPlatform();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SanitizeSegment_WithLeadingAndTrailingWhitespace_ShouldTrimTheName()
|
||||
{
|
||||
// Arrange
|
||||
_mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['<', '>', ':', '"', '|', '?', '*']);
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.SanitizeSegment(" Valid Name ");
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal("Valid Name", result.Value.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SanitizeSegment_WithInvalidCharacters_ShouldReplaceThemWithSpaces()
|
||||
{
|
||||
// Arrange
|
||||
char[] invalidChars = ['<', '>', ':', '"', '|', '?', '*'];
|
||||
_mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(invalidChars);
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.SanitizeSegment("Bad<Name>");
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal("Bad Name", result.Value.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SanitizeSegment_WithConsecutiveWhitespace_ShouldCollapseItIntoASingleSpace()
|
||||
{
|
||||
// Arrange
|
||||
_mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['<', '>', ':', '"', '|', '?', '*']);
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.SanitizeSegment("Name with spaces");
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal("Name with spaces", result.Value.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SanitizeSegment_WithDotSegment_ShouldReturnInvalidPath()
|
||||
{
|
||||
// Arrange
|
||||
_mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['<', '>', ':', '"', '|', '?', '*']);
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.SanitizeSegment(".");
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SanitizeSegment_WithDotDotSegment_ShouldReturnInvalidPath()
|
||||
{
|
||||
// Arrange
|
||||
_mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['<', '>', ':', '"', '|', '?', '*']);
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.SanitizeSegment("..");
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SanitizeSegment_WithForwardSlash_ShouldReturnInvalidPath()
|
||||
{
|
||||
// Arrange
|
||||
// The forward slash is not an invalid character for a segment on Unix-like platforms, so only the path service can reject it.
|
||||
_mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['\0']);
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.SanitizeSegment("a/b");
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SanitizeSegment_WithBackslash_ShouldReturnInvalidPath()
|
||||
{
|
||||
// Arrange
|
||||
// The backslash is not an invalid character for a segment on Windows platforms, so only the path service can reject it.
|
||||
_mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['<', '>', '"', '|', '?', '*', ':']);
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.SanitizeSegment("a\\b");
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("../..")] // Parent directory escape.
|
||||
[InlineData("a/../b")] // Embedded parent directory escape.
|
||||
[InlineData("..\\..")] // Windows parent directory escape.
|
||||
[InlineData("a\\..\\b")] // Embedded Windows parent directory escape.
|
||||
public void SanitizeSegment_WithPathTraversal_ShouldReturnInvalidPath(string name)
|
||||
{
|
||||
// Arrange
|
||||
_mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['\0']);
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.SanitizeSegment(name);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SanitizeSegment_WithAColon_WhenTheColonIsValidForThePlatform_ShouldKeepTheColon()
|
||||
{
|
||||
// Arrange
|
||||
// The colon is not an invalid character for a segment on Unix-like platforms, so it must be preserved.
|
||||
_mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['\0']);
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.SanitizeSegment("Name:WithColon");
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal("Name:WithColon", result.Value.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SanitizeSegment_WithAColon_WhenTheColonIsInvalidForThePlatform_ShouldReplaceItWithASpace()
|
||||
{
|
||||
// Arrange
|
||||
// The colon is an invalid character for a segment on Windows platforms, so it must be replaced.
|
||||
_mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['<', '>', '"', '|', '?', '*', ':']);
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.SanitizeSegment("Name:WithColon");
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal("Name WithColon", result.Value.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SanitizeSegment_WithEmptyName_ShouldReturnNameCannotBeEmpty()
|
||||
{
|
||||
// Arrange
|
||||
_mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['<', '>', ':', '"', '|', '?', '*']);
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.SanitizeSegment(string.Empty);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.NameCannotBeEmpty, result.FirstError);
|
||||
_mockPathStrategy.DidNotReceive().GetInvalidPathSegmentCharsForPlatform();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SanitizeSegment_WithWhitespaceOnlyName_ShouldReturnNameCannotBeEmpty()
|
||||
{
|
||||
// Arrange
|
||||
_mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['<', '>', ':', '"', '|', '?', '*']);
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.SanitizeSegment(" ");
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.NameCannotBeEmpty, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SanitizeSegment_WithNameMadeOnlyOfInvalidCharacters_ShouldReturnInvalidPath()
|
||||
{
|
||||
// Arrange
|
||||
_mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['<', '>', ':', '"', '|', '?', '*']);
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.SanitizeSegment("***");
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SanitizeSegment_WithNameLongerThanTheMaximumLength_ShouldCapTheSegment()
|
||||
{
|
||||
// Arrange
|
||||
_mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['<', '>', ':', '"', '|', '?', '*']);
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.SanitizeSegment(new string('a', 150));
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(100, result.Value.Name.Length);
|
||||
Assert.Equal(new string('a', 100), result.Value.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SanitizeSegment_WithNameLongerThanTheMaximumLengthAndTrailingWhitespace_ShouldTrimAfterCapping()
|
||||
{
|
||||
// Arrange
|
||||
_mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['<', '>', ':', '"', '|', '?', '*']);
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.SanitizeSegment(new string('a', 110) + new string(' ', 50));
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(100, result.Value.Name.Length);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SanitizeCompositeSegment_WhenTheNameFitsTheBudget_ShouldAppendTheIdentifier()
|
||||
{
|
||||
// Arrange
|
||||
_mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['<', '>', ':', '"', '|', '?', '*']);
|
||||
string identifier = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.SanitizeCompositeSegment("Queen", identifier);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal($"Queen-{identifier}", result.Value.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SanitizeCompositeSegment_WhenTheNameExceedsTheBudget_ShouldTruncateOnlyTheName()
|
||||
{
|
||||
// Arrange
|
||||
_mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['<', '>', ':', '"', '|', '?', '*']);
|
||||
string identifier = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.SanitizeCompositeSegment(new string('a', 99), identifier);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(100, result.Value.Name.Length);
|
||||
Assert.EndsWith($"-{identifier}", result.Value.Name);
|
||||
Assert.Equal(new string('a', 63), result.Value.Name[..^($"-{identifier}".Length)]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SanitizeCompositeSegment_WhenTheIdentifierLeavesNoRoomForTheName_ShouldReturnInvalidPath()
|
||||
{
|
||||
// Arrange
|
||||
_mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['<', '>', ':', '"', '|', '?', '*']);
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.SanitizeCompositeSegment("Queen", new string('a', 99));
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsPathWithin_WhenBothPathsAreValid_ShouldCreatePathIdsAndDelegateToTheStrategy()
|
||||
{
|
||||
// Arrange
|
||||
string path = @"C:\Media\Books\book.epub";
|
||||
string parentPath = @"C:\Media\Books";
|
||||
_mockPathStrategy.IsPathWithin(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>()).Returns(true);
|
||||
|
||||
// Act
|
||||
bool result = _sut.IsPathWithin(path, parentPath);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
_mockPathStrategy.Received(1).IsPathWithin(
|
||||
Arg.Is<FileSystemPathId>(pathId => pathId.Path == path),
|
||||
Arg.Is<FileSystemPathId>(pathId => pathId.Path == parentPath));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
public void IsPathWithin_WhenPathIsNotValid_ShouldReturnFalseWithoutCallingTheStrategy(string? invalidPath)
|
||||
{
|
||||
// Act
|
||||
bool result = _sut.IsPathWithin(invalidPath!, @"C:\Media");
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
_mockPathStrategy.DidNotReceive().IsPathWithin(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
public void IsPathWithin_WhenParentPathIsNotValid_ShouldReturnFalseWithoutCallingTheStrategy(string? invalidParentPath)
|
||||
{
|
||||
// Act
|
||||
bool result = _sut.IsPathWithin(@"C:\Media\Books\book.epub", invalidParentPath!);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
_mockPathStrategy.DidNotReceive().IsPathWithin(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData('\\', @"C:\Music\Queen\Bohemian Rhapsody.mp3", "Bohemian Rhapsody.mp3")] // Windows separated path.
|
||||
[InlineData('/', "/music/queen/bohemian-rhapsody.mp3", "bohemian-rhapsody.mp3")] // Unix separated path.
|
||||
public void GetFileName_WhenPathHasDirectories_ShouldReturnTheLastSegment(char separator, string path, string expectedFileName)
|
||||
{
|
||||
// Arrange
|
||||
_mockPathStrategy.PathSeparator.Returns(separator);
|
||||
|
||||
// Act
|
||||
string result = _sut.GetFileName(path);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(expectedFileName, result);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData('\\')] // Windows separated path.
|
||||
[InlineData('/')] // Unix separated path.
|
||||
public void GetFileName_WhenPathHasNoDirectory_ShouldReturnThePath(char separator)
|
||||
{
|
||||
// Arrange
|
||||
_mockPathStrategy.PathSeparator.Returns(separator);
|
||||
|
||||
// Act
|
||||
string result = _sut.GetFileName("Bohemian Rhapsody.mp3");
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Bohemian Rhapsody.mp3", result);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)]
|
||||
[InlineData("")]
|
||||
public void GetFileName_WhenPathIsNullOrEmpty_ShouldReturnThePath(string? path)
|
||||
{
|
||||
// Act
|
||||
string result = _sut.GetFileName(path!);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(path, result);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData('\\', @"C:\Music\Queen\Bohemian Rhapsody.mp3", "Bohemian Rhapsody")] // Windows separated path.
|
||||
[InlineData('/', "/music/queen/bohemian-rhapsody.mp3", "bohemian-rhapsody")] // Unix separated path.
|
||||
public void GetFileNameWithoutExtension_WhenPathHasDirectories_ShouldReturnTheFileNameWithoutItsExtension(char separator, string path, string expectedFileName)
|
||||
{
|
||||
// Arrange
|
||||
_mockPathStrategy.PathSeparator.Returns(separator);
|
||||
|
||||
// Act
|
||||
string result = _sut.GetFileNameWithoutExtension(path);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(expectedFileName, result);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData('\\')] // Windows separated path.
|
||||
[InlineData('/')] // Unix separated path.
|
||||
public void GetFileNameWithoutExtension_WhenFileNameHasNoExtension_ShouldReturnTheFileName(char separator)
|
||||
{
|
||||
// Arrange
|
||||
_mockPathStrategy.PathSeparator.Returns(separator);
|
||||
|
||||
// Act
|
||||
string result = _sut.GetFileNameWithoutExtension("Bohemian Rhapsody");
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Bohemian Rhapsody", result);
|
||||
}
|
||||
}
|
||||
+262
@@ -0,0 +1,262 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Fixtures.Common.Enums.PhotoLibrary;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary;
|
||||
using NSubstitute;
|
||||
using SixLabors.ImageSharp;
|
||||
using SixLabors.ImageSharp.Formats;
|
||||
using SixLabors.ImageSharp.Formats.Jpeg;
|
||||
using SixLabors.ImageSharp.PixelFormats;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ThumbnailService"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ThumbnailServiceTests
|
||||
{
|
||||
private readonly IEnvironmentContext _mockEnvironmentContext;
|
||||
private readonly ThumbnailService _sut;
|
||||
private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ThumbnailServiceTests"/> class.
|
||||
/// </summary>
|
||||
public ThumbnailServiceTests()
|
||||
{
|
||||
_mockEnvironmentContext = Substitute.For<IEnvironmentContext>();
|
||||
_sut = new ThumbnailService(_mockEnvironmentContext);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetThumbnailAsync_WithValidPath_ShouldReturnThumbnail()
|
||||
{
|
||||
// Arrange
|
||||
string path = @"C:\TestImage.jpg";
|
||||
int quality = 80;
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path);
|
||||
|
||||
// Create a small valid JPEG image.
|
||||
byte[] imageBytes;
|
||||
using (Image<Rgba32> image = new(10, 10))
|
||||
{
|
||||
using MemoryStream ms = new();
|
||||
image.Save(ms, new JpegEncoder());
|
||||
imageBytes = ms.ToArray();
|
||||
}
|
||||
|
||||
_mockEnvironmentContext.FileTypeService.GetImageTypeAsync(pathId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(ImageType.JPEG));
|
||||
_mockEnvironmentContext.FileProviderService.GetFileAsync(pathId)
|
||||
.Returns(Result.From(imageBytes));
|
||||
|
||||
// Act
|
||||
Result<Thumbnail> result = await _sut.GetThumbnailAsync(path, quality, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(ImageType.JPEG, result.Value.Type);
|
||||
Assert.NotEmpty(result.Value.Bytes);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetThumbnailAsync_WithInvalidPath_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
string invalidPath = string.Empty;
|
||||
int quality = 80;
|
||||
|
||||
// Act
|
||||
Result<Thumbnail> result = await _sut.GetThumbnailAsync(invalidPath, quality, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetThumbnailAsync_WhenFileTypeServiceReturnsError_ShouldPropagateError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(@"C:\TestImage.jpg");
|
||||
int quality = 80;
|
||||
|
||||
_mockEnvironmentContext.FileTypeService.GetImageTypeAsync(pathId, Arg.Any<CancellationToken>())
|
||||
.Returns(Errors.Permission.UnauthorizedAccess);
|
||||
|
||||
// Act
|
||||
Result<Thumbnail> result = await _sut.GetThumbnailAsync(pathId, quality, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetThumbnailAsync_WhenImageTypeIsNone_ShouldReturnNoThumbnailError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(@"C:\TestFile.txt");
|
||||
int quality = 80;
|
||||
|
||||
_mockEnvironmentContext.FileTypeService.GetImageTypeAsync(pathId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(ImageType.None));
|
||||
|
||||
// Act
|
||||
Result<Thumbnail> result = await _sut.GetThumbnailAsync(pathId, quality, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Thumbnails.NoThumbnail, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetThumbnailAsync_WhenFileProviderServiceReturnsError_ShouldPropagateError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(@"C:\TestImage.jpg");
|
||||
int quality = 80;
|
||||
|
||||
_mockEnvironmentContext.FileTypeService.GetImageTypeAsync(pathId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(ImageType.JPEG));
|
||||
_mockEnvironmentContext.FileProviderService.GetFileAsync(pathId)
|
||||
.Returns(Errors.Permission.UnauthorizedAccess);
|
||||
|
||||
// Act
|
||||
Result<Thumbnail> result = await _sut.GetThumbnailAsync(pathId, quality, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[ClassData(typeof(ImageTypeFixture))]
|
||||
public async Task GetThumbnailAsync_WithDifferentImageTypes_ShouldReturnThumbnail(ImageType imageType, byte[] imageBytes)
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(@"C:\TestImage");
|
||||
int quality = 80;
|
||||
|
||||
_mockEnvironmentContext.FileTypeService.GetImageTypeAsync(pathId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(imageType));
|
||||
_mockEnvironmentContext.FileProviderService.GetFileAsync(pathId)
|
||||
.Returns(Result.From(imageBytes));
|
||||
|
||||
// Act
|
||||
Result<Thumbnail> result = await _sut.GetThumbnailAsync(pathId, quality, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(imageType, result.Value.Type);
|
||||
Assert.NotEmpty(result.Value.Bytes);
|
||||
|
||||
using (MemoryStream ms = new(result.Value.Bytes))
|
||||
{
|
||||
Image loadedImage = Image.Load(ms);
|
||||
Assert.NotNull(loadedImage);
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(ImageType.JPEG2000)] // Resolution adjustment switch branch for JPEG2000.
|
||||
[InlineData(ImageType.JPEG_CANON)] // Resolution adjustment switch branch for Canon JPEG.
|
||||
[InlineData(ImageType.JPEG_UNKNOWN)] // Resolution adjustment switch branch for unknown JPEG.
|
||||
[InlineData(ImageType.TIFF)] // Resolution adjustment switch branch for TIFF.
|
||||
[InlineData(ImageType.WEBP)] // Resolution adjustment switch branch for WEBP.
|
||||
[InlineData(ImageType.TGA)] // Resolution adjustment switch branch for TGA.
|
||||
public async Task GetThumbnailAsync_WithAdditionalSupportedImageTypes_ShouldReturnAdjustedThumbnail(ImageType imageType)
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(@"C:\TestImage");
|
||||
int quality = 80;
|
||||
byte[] imageBytes = CreateImageBytes(new JpegEncoder());
|
||||
|
||||
_mockEnvironmentContext.FileTypeService.GetImageTypeAsync(pathId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(imageType));
|
||||
_mockEnvironmentContext.FileProviderService.GetFileAsync(pathId)
|
||||
.Returns(Result.From(imageBytes));
|
||||
|
||||
// Act
|
||||
Result<Thumbnail> result = await _sut.GetThumbnailAsync(pathId, quality, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(imageType, result.Value.Type);
|
||||
Assert.NotEmpty(result.Value.Bytes);
|
||||
|
||||
using (MemoryStream ms = new(result.Value.Bytes))
|
||||
{
|
||||
Image loadedImage = Image.Load(ms);
|
||||
Assert.NotNull(loadedImage);
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(ImageType.SVG)] // SVG is not resized, original bytes are returned.
|
||||
[InlineData(ImageType.PICT)] // PICT is not resized, original bytes are returned.
|
||||
[InlineData(ImageType.ICO)] // ICO is not resized, original bytes are returned.
|
||||
[InlineData(ImageType.PSD)] // PSD is not resized, original bytes are returned.
|
||||
[InlineData(ImageType.AVIF)] // AVIF is not resized, original bytes are returned.
|
||||
public async Task GetThumbnailAsync_WithUnsupportedNonNoneImageType_ShouldReturnOriginalBytes(ImageType imageType)
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(@"C:\TestImage");
|
||||
int quality = 80;
|
||||
byte[] imageBytes = CreateImageBytes(new JpegEncoder());
|
||||
|
||||
_mockEnvironmentContext.FileTypeService.GetImageTypeAsync(pathId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(imageType));
|
||||
_mockEnvironmentContext.FileProviderService.GetFileAsync(pathId)
|
||||
.Returns(Result.From(imageBytes));
|
||||
|
||||
// Act
|
||||
Result<Thumbnail> result = await _sut.GetThumbnailAsync(pathId, quality, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(imageType, result.Value.Type);
|
||||
Assert.Equal(imageBytes, result.Value.Bytes);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetThumbnailAsync_WithCancellation_ShouldThrowTaskCanceledException()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(@"C:\TestImage.jpg");
|
||||
int quality = 80;
|
||||
CancellationTokenSource cts = new();
|
||||
cts.Cancel();
|
||||
|
||||
_mockEnvironmentContext.FileTypeService.GetImageTypeAsync(pathId, cts.Token)
|
||||
.Returns(Task.FromCanceled<Result<ImageType>>(cts.Token));
|
||||
|
||||
// Act & Assert
|
||||
await Assert.ThrowsAsync<TaskCanceledException>(() =>
|
||||
_sut.GetThumbnailAsync(pathId, quality, cts.Token));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates the bytes of a small image encoded with the specified encoder.
|
||||
/// </summary>
|
||||
/// <param name="encoder">The encoder used to encode the image.</param>
|
||||
/// <returns>The bytes of the created image.</returns>
|
||||
private static byte[] CreateImageBytes(IImageEncoder encoder)
|
||||
{
|
||||
using Image<Rgba32> image = new(10, 10);
|
||||
using MemoryStream memoryStream = new();
|
||||
image.Save(memoryStream, encoder);
|
||||
return memoryStream.ToArray();
|
||||
}
|
||||
}
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
|
||||
using NSubstitute;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="EnvironmentContext"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class EnvironmentContextTests
|
||||
{
|
||||
private readonly IDirectoryProviderService _mockDirectoryProviderService;
|
||||
private readonly IFileProviderService _mockFileProviderService;
|
||||
private readonly IFileTypeService _mockFileTypeService;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="EnvironmentContextTests"/> class.
|
||||
/// </summary>
|
||||
public EnvironmentContextTests()
|
||||
{
|
||||
_mockDirectoryProviderService = Substitute.For<IDirectoryProviderService>();
|
||||
_mockFileProviderService = Substitute.For<IFileProviderService>();
|
||||
_mockFileTypeService = Substitute.For<IFileTypeService>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenCalledWithValidParameters_ShouldInitializeAllProperties()
|
||||
{
|
||||
// Arrange & Act
|
||||
EnvironmentContext environmentContext = new(
|
||||
_mockDirectoryProviderService,
|
||||
_mockFileProviderService,
|
||||
_mockFileTypeService);
|
||||
|
||||
// Assert
|
||||
Assert.Same(_mockDirectoryProviderService, environmentContext.DirectoryProviderService);
|
||||
Assert.Same(_mockFileProviderService, environmentContext.FileProviderService);
|
||||
Assert.Same(_mockFileTypeService, environmentContext.FileTypeService);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FileTypeService_WhenAccessed_ShouldReturnInjectedService()
|
||||
{
|
||||
// Arrange
|
||||
EnvironmentContext environmentContext = new(
|
||||
_mockDirectoryProviderService,
|
||||
_mockFileProviderService,
|
||||
_mockFileTypeService);
|
||||
|
||||
// Act
|
||||
IFileTypeService result = environmentContext.FileTypeService;
|
||||
|
||||
// Assert
|
||||
Assert.Same(_mockFileTypeService, result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FileProviderService_WhenAccessed_ShouldReturnInjectedService()
|
||||
{
|
||||
// Arrange
|
||||
EnvironmentContext environmentContext = new(
|
||||
_mockDirectoryProviderService,
|
||||
_mockFileProviderService,
|
||||
_mockFileTypeService);
|
||||
|
||||
// Act
|
||||
IFileProviderService result = environmentContext.FileProviderService;
|
||||
|
||||
// Assert
|
||||
Assert.Same(_mockFileProviderService, result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DirectoryProviderService_WhenAccessed_ShouldReturnInjectedService()
|
||||
{
|
||||
// Arrange
|
||||
EnvironmentContext environmentContext = new(
|
||||
_mockDirectoryProviderService,
|
||||
_mockFileProviderService,
|
||||
_mockFileTypeService);
|
||||
|
||||
// Act
|
||||
IDirectoryProviderService result = environmentContext.DirectoryProviderService;
|
||||
|
||||
// Assert
|
||||
Assert.Same(_mockDirectoryProviderService, result);
|
||||
}
|
||||
}
|
||||
+637
@@ -0,0 +1,637 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Path;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using NSubstitute;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO.Abstractions;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Path;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="UnixPathStrategy"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UnixPathStrategyTests
|
||||
{
|
||||
private readonly IFileSystem _mockFileSystem;
|
||||
private readonly UnixPathStrategy _sut;
|
||||
private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new();
|
||||
private readonly PathSegmentFixture _pathSegmentFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UnixPathStrategyTests"/> class.
|
||||
/// </summary>
|
||||
public UnixPathStrategyTests()
|
||||
{
|
||||
_mockFileSystem = Substitute.For<IFileSystem>();
|
||||
_sut = new UnixPathStrategy(_mockFileSystem);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("/home/user")]
|
||||
[InlineData("/var/log/")]
|
||||
[InlineData("/etc/config.conf")]
|
||||
[InlineData("/")]
|
||||
[InlineData("/usr/local/bin")]
|
||||
public void IsValidPath_WithValidUnixPaths_ShouldReturnTrue(string path)
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path);
|
||||
|
||||
// Act
|
||||
bool result = _sut.IsValidPath(pathId);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("C:\\Windows\\System32")]
|
||||
[InlineData("relative/path")]
|
||||
[InlineData("./relative/path")]
|
||||
[InlineData("../parent/path")]
|
||||
public void IsValidPath_WithInvalidUnixPaths_ShouldReturnFalse(string path)
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path);
|
||||
|
||||
// Act
|
||||
bool result = _sut.IsValidPath(pathId);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsValidPath_WithPathContainingInvalidCharacters_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
string invalidPath = "/home/user/file\0name";
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(invalidPath);
|
||||
|
||||
// Act
|
||||
bool result = _sut.IsValidPath(pathId);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("/home/user/file with spaces")]
|
||||
[InlineData("/home/user/file-with-dashes")]
|
||||
[InlineData("/home/user/file_with_underscores")]
|
||||
[InlineData("/home/user/file.with.dots")]
|
||||
[InlineData("/home/user/file~with~tilde")]
|
||||
[InlineData("/home/user/file!with!exclamation")]
|
||||
[InlineData("/home/user/file$with$dollar")]
|
||||
[InlineData("/home/user/file&with&ersand")]
|
||||
[InlineData("/home/user/file'with'singlequote")]
|
||||
[InlineData("/home/user/file(with)parentheses")]
|
||||
public void IsValidPath_WithValidSpecialCharacters_ShouldReturnTrue(string path)
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path);
|
||||
|
||||
// Act
|
||||
bool result = _sut.IsValidPath(pathId);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsValidPath_WithVeryLongPath_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
string longPath = "/" + string.Join("/", Enumerable.Repeat("a", 100));
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(longPath);
|
||||
|
||||
// Act
|
||||
bool result = _sut.IsValidPath(pathId);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Exists_WhenPathExistsAndIsHiddenAndShouldIncludeHiddenElementsIsTrue_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
string existingPath = "/home/user/existing_file.txt";
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(existingPath);
|
||||
|
||||
_mockFileSystem.Path.Exists(existingPath).Returns(true);
|
||||
_mockFileSystem.File.Exists(existingPath).Returns(true);
|
||||
|
||||
// Act
|
||||
bool result = _sut.Exists(pathId, true);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
_mockFileSystem.Path.Received(1).Exists(existingPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Exists_WhenPathExistsAndIsHiddenAndShouldIncludeHiddenElementsIsFalse_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
string existingPath = "/home/user/existing_file.txt";
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(existingPath);
|
||||
_mockFileSystem.Path.Exists(existingPath).Returns(true);
|
||||
_mockFileSystem.File.Exists(existingPath).Returns(true);
|
||||
IFileInfo mockFileInfo = Substitute.For<IFileInfo>();
|
||||
mockFileInfo.Attributes.Returns(System.IO.FileAttributes.Hidden);
|
||||
_mockFileSystem.FileInfo.New(Arg.Any<string>()).Returns(mockFileInfo);
|
||||
|
||||
// Act
|
||||
bool result = _sut.Exists(pathId, false);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
_mockFileSystem.Path.Received(1).Exists(existingPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Exists_WhenPathDoesNotExist_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
string nonExistingPath = "/home/user/non_existing_file.txt";
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(nonExistingPath);
|
||||
_mockFileSystem.Path.Exists(nonExistingPath).Returns(false);
|
||||
|
||||
// Act
|
||||
bool result = _sut.Exists(pathId);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
_mockFileSystem.Path.Received(1).Exists(nonExistingPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Exists_WithRootPath_ShouldCheckExistence()
|
||||
{
|
||||
// Arrange
|
||||
string rootPath = "/";
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(rootPath);
|
||||
_mockFileSystem.Path.Exists(rootPath).Returns(true);
|
||||
|
||||
// Act
|
||||
bool result = _sut.Exists(pathId, true);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
_mockFileSystem.Path.Received(1).Exists(rootPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Exists_WithDirectoryPath_ShouldCheckExistence()
|
||||
{
|
||||
// Arrange
|
||||
string directoryPath = "/home/user/documents/";
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(directoryPath);
|
||||
_mockFileSystem.Path.Exists(directoryPath).Returns(true);
|
||||
_mockFileSystem.Directory.Exists(directoryPath).Returns(true);
|
||||
|
||||
// Act
|
||||
bool result = _sut.Exists(pathId, true);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
_mockFileSystem.Path.Received(1).Exists(directoryPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Exists_WithFilePath_ShouldCheckExistence()
|
||||
{
|
||||
// Arrange
|
||||
string filePath = "/home/user/documents/file.txt";
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(filePath);
|
||||
_mockFileSystem.Path.Exists(filePath).Returns(true);
|
||||
_mockFileSystem.File.Exists(filePath).Returns(true);
|
||||
|
||||
// Act
|
||||
bool result = _sut.Exists(pathId, true);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
_mockFileSystem.Path.Received(1).Exists(filePath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CombinePath_WithValidPathAndName_ShouldReturnCombinedPath()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create("/home/user");
|
||||
string name = "documents";
|
||||
|
||||
// Act
|
||||
Result<FileSystemPathId> result = _sut.CombinePath(path, name);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal("/home/user/documents/", result.Value.Path);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CombinePath_WithTrailingSlashInPath_ShouldReturnCorrectlyCombinedPath()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create("/home/user/");
|
||||
string name = "documents";
|
||||
|
||||
// Act
|
||||
Result<FileSystemPathId> result = _sut.CombinePath(path, name);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal("/home/user/documents/", result.Value.Path);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CombinePath_WithLeadingSlashInName_ShouldReturnCorrectlyCombinedPath()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create("/home/user");
|
||||
string name = "/documents";
|
||||
|
||||
// Act
|
||||
Result<FileSystemPathId> result = _sut.CombinePath(path, name);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal("/home/user/documents/", result.Value.Path);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CombinePath_WithEmptyName_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create("/home/user");
|
||||
string name = "";
|
||||
|
||||
// Act
|
||||
Result<FileSystemPathId> result = _sut.CombinePath(path, name);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.NameCannotBeEmpty, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CombinePath_WithNullName_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create("/home/user");
|
||||
string name = null!;
|
||||
|
||||
// Act
|
||||
Result<FileSystemPathId> result = _sut.CombinePath(path, name);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.NameCannotBeEmpty, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CombinePath_WithRootPath_ShouldReturnCorrectlyCombinedPath()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create("/");
|
||||
string name = "home";
|
||||
|
||||
// Act
|
||||
Result<FileSystemPathId> result = _sut.CombinePath(path, name);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal("/home/", result.Value.Path);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ParsePath_WithValidUnixPath_ShouldReturnCorrectPathSegments()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create("/home/user/documents/file.txt");
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<PathSegment>> result = _sut.ParsePath(path);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(5, result.Value.Count());
|
||||
Assert.Equal(_pathSegmentFixture.Create("/", false, true), result.Value.ElementAt(0));
|
||||
Assert.Equal(_pathSegmentFixture.Create("home", true, false), result.Value.ElementAt(1));
|
||||
Assert.Equal(_pathSegmentFixture.Create("user", true, false), result.Value.ElementAt(2));
|
||||
Assert.Equal(_pathSegmentFixture.Create("documents", true, false), result.Value.ElementAt(3));
|
||||
Assert.Equal(_pathSegmentFixture.Create("file.txt", false, false), result.Value.ElementAt(4));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ParsePath_WithRootPath_ShouldReturnSingleRootSegment()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create("/");
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<PathSegment>> result = _sut.ParsePath(path);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Single(result.Value);
|
||||
Assert.Equal(_pathSegmentFixture.Create("/", false, true), result.Value.Single());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ParsePath_WithTrailingSlash_ShouldTreatLastSegmentAsDirectory()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create("/home/user/documents/");
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<PathSegment>> result = _sut.ParsePath(path);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(4, result.Value.Count());
|
||||
Assert.Equal(_pathSegmentFixture.Create("documents", true, false), result.Value.Last());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ParsePath_WithRelativePath_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create("home/user");
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<PathSegment>> result = _sut.ParsePath(path);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ParsePath_WhenPathContainsWhitespaceSegment_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create("/home/ /user");
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<PathSegment>> result = _sut.ParsePath(path);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.NameCannotBeEmpty, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ParsePath_WithPathContainingDots_ShouldParseCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create("/home/user/file.with.dots.txt");
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<PathSegment>> result = _sut.ParsePath(path);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(4, result.Value.Count());
|
||||
Assert.Equal(_pathSegmentFixture.Create("file.with.dots.txt", false, false), result.Value.Last());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GoUpOneLevel_WithValidPath_ShouldReturnParentPath()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create("/home/user/documents");
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<PathSegment>> result = _sut.GoUpOneLevel(path);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(3, result.Value.Count());
|
||||
Assert.Equal(_pathSegmentFixture.Create("/", false, true), result.Value.ElementAt(0));
|
||||
Assert.Equal(_pathSegmentFixture.Create("home", true, false), result.Value.ElementAt(1));
|
||||
Assert.Equal(_pathSegmentFixture.Create("user", true, false), result.Value.ElementAt(2));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GoUpOneLevel_WithRootPath_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create("/");
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<PathSegment>> result = _sut.GoUpOneLevel(path);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.CannotNavigateUp, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GoUpOneLevel_WithTrailingSlash_ShouldReturnCorrectParentPath()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create("/home/user/");
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<PathSegment>> result = _sut.GoUpOneLevel(path);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(2, result.Value.Count());
|
||||
Assert.Equal(_pathSegmentFixture.Create("/", false, true), result.Value.ElementAt(0));
|
||||
Assert.Equal(_pathSegmentFixture.Create("home", true, false), result.Value.ElementAt(1));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GoUpOneLevel_WithInvalidPath_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create("invalid/path");
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<PathSegment>> result = _sut.GoUpOneLevel(path);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GoUpOneLevel_WithSingleLevelPath_ShouldReturnRootPath()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create("/home");
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<PathSegment>> result = _sut.GoUpOneLevel(path);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Single(result.Value);
|
||||
Assert.Equal(_pathSegmentFixture.Create("/", false, true), result.Value.Single());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetInvalidPathCharsForPlatform_WhenCalled_ShouldReturnOnlyNullCharacter()
|
||||
{
|
||||
// Act
|
||||
char[] result = _sut.GetInvalidPathCharsForPlatform();
|
||||
|
||||
// Assert
|
||||
Assert.Single(result);
|
||||
Assert.Contains('\0', result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetInvalidPathCharsForPlatform_WhenCalled_ShouldNotContainOtherCharacters()
|
||||
{
|
||||
// Act
|
||||
char[] result = _sut.GetInvalidPathCharsForPlatform();
|
||||
|
||||
// Assert
|
||||
Assert.DoesNotContain('/', result);
|
||||
Assert.DoesNotContain('\\', result);
|
||||
Assert.DoesNotContain(':', result);
|
||||
Assert.DoesNotContain('*', result);
|
||||
Assert.DoesNotContain('?', result);
|
||||
Assert.DoesNotContain('"', result);
|
||||
Assert.DoesNotContain('<', result);
|
||||
Assert.DoesNotContain('>', result);
|
||||
Assert.DoesNotContain('|', result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetInvalidPathCharsForPlatform_WhenCalled_ShouldReturnSameResultOnMultipleCalls()
|
||||
{
|
||||
// Act
|
||||
char[] result1 = _sut.GetInvalidPathCharsForPlatform();
|
||||
char[] result2 = _sut.GetInvalidPathCharsForPlatform();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(result1, result2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetInvalidPathSegmentCharsForPlatform_WhenCalled_ShouldReturnOnlyNullCharacter()
|
||||
{
|
||||
// Act
|
||||
char[] result = _sut.GetInvalidPathSegmentCharsForPlatform();
|
||||
|
||||
// Assert
|
||||
Assert.Single(result);
|
||||
Assert.Contains('\0', result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetInvalidPathSegmentCharsForPlatform_WhenCalled_ShouldNotContainTheColon()
|
||||
{
|
||||
// Act
|
||||
char[] result = _sut.GetInvalidPathSegmentCharsForPlatform();
|
||||
|
||||
// Assert
|
||||
Assert.DoesNotContain(':', result);
|
||||
Assert.DoesNotContain('/', result);
|
||||
Assert.DoesNotContain('\\', result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetInvalidPathSegmentCharsForPlatform_WhenCalled_ShouldReturnSameResultOnMultipleCalls()
|
||||
{
|
||||
// Act
|
||||
char[] result1 = _sut.GetInvalidPathSegmentCharsForPlatform();
|
||||
char[] result2 = _sut.GetInvalidPathSegmentCharsForPlatform();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(result1, result2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetPathRoot_WithValidUnixPath_ShouldReturnRootSegment()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create("/home/user/documents");
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.GetPathRoot(path);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(_pathSegmentFixture.Create("/", false, true), result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetPathRoot_WithRootPath_ShouldReturnRootSegment()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create("/");
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.GetPathRoot(path);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(_pathSegmentFixture.Create("/", false, true), result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetPathRoot_WithInvalidPath_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create("home/user");
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.GetPathRoot(path);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("/media/books", "/media/books/book.epub")] // Direct child.
|
||||
[InlineData("/media", "/media/books/book.epub")] // Nested descendant.
|
||||
[InlineData("/media/books/", "/media/books/book.epub")] // Trailing separator on the parent.
|
||||
[InlineData("/media/books", "/media/books/sub/../book.epub")] // Relative segments that stay inside.
|
||||
public void IsPathWithin_WithContainedPaths_ShouldReturnTrue(string parentPath, string path)
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId parentPathId = _fileSystemPathIdFixture.Create(parentPath);
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path);
|
||||
|
||||
// Act
|
||||
bool result = _sut.IsPathWithin(pathId, parentPathId);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("/media/books", "/media/book.epub")] // Sibling directory.
|
||||
[InlineData("/media/books", "/Media/Books/book.epub")] // Unix paths are case-sensitive.
|
||||
[InlineData("/media/books", "/media/other/book.epub")] // Sibling directory.
|
||||
[InlineData("/media/books", "/media/books/../other/book.epub")] // Relative segment that escapes the parent.
|
||||
[InlineData("/media/books", "/etc/passwd")] // Unrelated location.
|
||||
[InlineData("/media", "/media")] // The parent itself is not inside itself.
|
||||
public void IsPathWithin_WithPathsOutsideTheParent_ShouldReturnFalse(string parentPath, string path)
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId parentPathId = _fileSystemPathIdFixture.Create(parentPath);
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path);
|
||||
|
||||
// Act
|
||||
bool result = _sut.IsPathWithin(pathId, parentPathId);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
}
|
||||
+854
@@ -0,0 +1,854 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Path;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using NSubstitute;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO.Abstractions;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Path;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="WindowsPathStrategy"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class WindowsPathStrategyTests
|
||||
{
|
||||
private readonly IFileSystem _mockFileSystem;
|
||||
private readonly WindowsPathStrategy _sut;
|
||||
private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new();
|
||||
private readonly PathSegmentFixture _pathSegmentFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="WindowsPathStrategyTests"/> class.
|
||||
/// </summary>
|
||||
public WindowsPathStrategyTests()
|
||||
{
|
||||
_mockFileSystem = Substitute.For<IFileSystem>();
|
||||
_sut = new WindowsPathStrategy(_mockFileSystem);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(@"C:\Users\User")]
|
||||
[InlineData(@"D:\Program Files\")]
|
||||
[InlineData(@"E:\Documents\file.txt")]
|
||||
[InlineData(@"F:\")]
|
||||
[InlineData(@"G:\Projects\Visual Studio 2022\")]
|
||||
public void IsValidPath_WithValidWindowsPaths_ShouldReturnTrue(string path)
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path);
|
||||
|
||||
// Act
|
||||
bool result = _sut.IsValidPath(pathId);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("/home/user")]
|
||||
[InlineData("relative\\path")]
|
||||
[InlineData(".\\relative\\path")]
|
||||
[InlineData("..\\parent\\path")]
|
||||
[InlineData("C:invalid_path")]
|
||||
public void IsValidPath_WithInvalidWindowsPaths_ShouldReturnFalse(string path)
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path);
|
||||
|
||||
// Act
|
||||
bool result = _sut.IsValidPath(pathId);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsValidPath_WithPathContainingInvalidCharacters_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
string invalidPath = @"C:\Users\User\file<name>";
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(invalidPath);
|
||||
|
||||
// Act
|
||||
bool result = _sut.IsValidPath(pathId);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(@"C:\Users\User\file with spaces")]
|
||||
[InlineData(@"D:\Projects\file-with-dashes")]
|
||||
[InlineData(@"E:\Documents\file_with_underscores")]
|
||||
[InlineData(@"F:\Data\file.with.dots")]
|
||||
[InlineData(@"G:\Backups\file(with)parentheses")]
|
||||
public void IsValidPath_WithValidSpecialCharacters_ShouldReturnTrue(string path)
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path);
|
||||
|
||||
// Act
|
||||
bool result = _sut.IsValidPath(pathId);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsValidPath_WithVeryLongPath_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
string longPath = @"C:\" + string.Join("\\", Enumerable.Repeat("a", 100));
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(longPath);
|
||||
|
||||
// Act
|
||||
bool result = _sut.IsValidPath(pathId);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(@"\\server\share")]
|
||||
[InlineData(@"\\server\share\folder")]
|
||||
[InlineData(@"\\server\share\folder\file.txt")]
|
||||
public void IsValidPath_WithValidUNCPaths_ShouldReturnTrue(string path)
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path);
|
||||
|
||||
// Act
|
||||
bool result = _sut.IsValidPath(pathId);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(@"\\")]
|
||||
[InlineData(@"\\server")]
|
||||
[InlineData(@"\\\server\share")]
|
||||
public void IsValidPath_WithInvalidUNCPaths_ShouldReturnFalse(string path)
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path);
|
||||
|
||||
// Act
|
||||
bool result = _sut.IsValidPath(pathId);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Exists_WhenPathExistsAndIsHiddenAndShouldIncludeHiddenElementsIsTrue_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
string existingPath = @"C:\Users\User\existing_file.txt";
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(existingPath);
|
||||
_mockFileSystem.Path.Exists(existingPath).Returns(true);
|
||||
_mockFileSystem.File.Exists(existingPath).Returns(true);
|
||||
|
||||
// Act
|
||||
bool result = _sut.Exists(pathId, true);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
_mockFileSystem.Path.Received(1).Exists(existingPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Exists_WhenPathExistsAndIsHiddenAndShouldIncludeHiddenElementsIsFalse_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
string existingPath = @"C:\Users\User\existing_file.txt";
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(existingPath);
|
||||
_mockFileSystem.Path.Exists(existingPath).Returns(true);
|
||||
_mockFileSystem.File.Exists(existingPath).Returns(true);
|
||||
IFileInfo mockFileInfo = Substitute.For<IFileInfo>();
|
||||
mockFileInfo.Attributes.Returns(System.IO.FileAttributes.Hidden);
|
||||
_mockFileSystem.FileInfo.New(Arg.Any<string>()).Returns(mockFileInfo);
|
||||
|
||||
// Act
|
||||
bool result = _sut.Exists(pathId, false);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
_mockFileSystem.Path.Received(1).Exists(existingPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Exists_WhenPathDoesNotExist_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
string nonExistingPath = @"C:\Users\User\non_existing_file.txt";
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(nonExistingPath);
|
||||
_mockFileSystem.Path.Exists(nonExistingPath).Returns(false);
|
||||
|
||||
// Act
|
||||
bool result = _sut.Exists(pathId);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
_mockFileSystem.Path.Received(1).Exists(nonExistingPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Exists_WithRootPath_ShouldCheckExistence()
|
||||
{
|
||||
// Arrange
|
||||
string rootPath = @"C:\";
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(rootPath);
|
||||
_mockFileSystem.Path.Exists(rootPath).Returns(true);
|
||||
|
||||
// Act
|
||||
bool result = _sut.Exists(pathId);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
_mockFileSystem.Path.Received(1).Exists(rootPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Exists_WithDirectoryPath_ShouldCheckExistence()
|
||||
{
|
||||
// Arrange
|
||||
string directoryPath = @"C:\Users\User\Documents\";
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(directoryPath);
|
||||
_mockFileSystem.Path.Exists(directoryPath).Returns(true);
|
||||
_mockFileSystem.Directory.Exists(directoryPath).Returns(true);
|
||||
|
||||
// Act
|
||||
bool result = _sut.Exists(pathId, true);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
_mockFileSystem.Path.Received(1).Exists(directoryPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Exists_WithFilePath_ShouldCheckExistence()
|
||||
{
|
||||
// Arrange
|
||||
string filePath = @"C:\Users\User\Documents\file.txt";
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(filePath);
|
||||
_mockFileSystem.Path.Exists(filePath).Returns(true);
|
||||
_mockFileSystem.File.Exists(filePath).Returns(true);
|
||||
|
||||
// Act
|
||||
bool result = _sut.Exists(pathId, true);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
_mockFileSystem.Path.Received(1).Exists(filePath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Exists_WithUNCPath_ShouldCheckExistence()
|
||||
{
|
||||
// Arrange
|
||||
string uncPath = @"\\server\share\folder\file.txt";
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(uncPath);
|
||||
_mockFileSystem.Path.Exists(uncPath).Returns(true);
|
||||
|
||||
// Act
|
||||
bool result = _sut.Exists(pathId, true);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
_mockFileSystem.Path.Received(1).Exists(uncPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CombinePath_WithValidPathAndName_ShouldReturnCombinedPath()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create(@"C:\Users\User");
|
||||
string name = "Documents";
|
||||
|
||||
// Act
|
||||
Result<FileSystemPathId> result = _sut.CombinePath(path, name);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(@"C:\Users\User\Documents\", result.Value.Path);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CombinePath_WithTrailingBackslashInPath_ShouldReturnCorrectlyCombinedPath()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create(@"C:\Users\User\");
|
||||
string name = "Documents";
|
||||
|
||||
// Act
|
||||
Result<FileSystemPathId> result = _sut.CombinePath(path, name);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(@"C:\Users\User\Documents\", result.Value.Path);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CombinePath_WithLeadingBackslashInName_ShouldReturnCorrectlyCombinedPath()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create(@"C:\Users\User");
|
||||
string name = @"\Documents";
|
||||
|
||||
// Act
|
||||
Result<FileSystemPathId> result = _sut.CombinePath(path, name);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(@"C:\Users\User\Documents\", result.Value.Path);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CombinePath_WithNullName_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create(@"C:\Users\User");
|
||||
string name = null!;
|
||||
|
||||
// Act
|
||||
Result<FileSystemPathId> result = _sut.CombinePath(path, name);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.NameCannotBeEmpty, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CombinePath_WithRootPath_ShouldReturnCorrectlyCombinedPath()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create(@"C:\");
|
||||
string name = "Users";
|
||||
|
||||
// Act
|
||||
Result<FileSystemPathId> result = _sut.CombinePath(path, name);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(@"C:\Users\", result.Value.Path);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CombinePath_WithUNCPath_ShouldReturnCorrectlyCombinedPath()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create(@"\\server\share");
|
||||
string name = "folder";
|
||||
|
||||
// Act
|
||||
Result<FileSystemPathId> result = _sut.CombinePath(path, name);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(@"\\server\share\folder\", result.Value.Path);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ParsePath_WithValidWindowsPath_ShouldReturnCorrectPathSegments()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create(@"C:\Users\User\Documents\file.txt");
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<PathSegment>> result = _sut.ParsePath(path);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(5, result.Value.Count());
|
||||
Assert.Equivalent(_pathSegmentFixture.Create("C:", false, true), result.Value.ElementAt(0));
|
||||
Assert.Equivalent(_pathSegmentFixture.Create("Users", true, false), result.Value.ElementAt(1));
|
||||
Assert.Equivalent(_pathSegmentFixture.Create("User", true, false), result.Value.ElementAt(2));
|
||||
Assert.Equivalent(_pathSegmentFixture.Create("Documents", true, false), result.Value.ElementAt(3));
|
||||
Assert.Equivalent(_pathSegmentFixture.Create("file.txt", false, false), result.Value.ElementAt(4));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ParsePath_WithRootPath_ShouldReturnSingleRootSegment()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create(@"C:\");
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<PathSegment>> result = _sut.ParsePath(path);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Single(result.Value);
|
||||
Assert.Equivalent(_pathSegmentFixture.Create("C:", false, true), result.Value.Single());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ParsePath_WithTrailingBackslash_ShouldTreatLastSegmentAsDirectory()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create(@"C:\Users\User\Documents\");
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<PathSegment>> result = _sut.ParsePath(path);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(4, result.Value.Count());
|
||||
Assert.Equivalent(_pathSegmentFixture.Create("Documents", true, false), result.Value.Last());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ParsePath_WithRelativePath_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create(@"Users\User");
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<PathSegment>> result = _sut.ParsePath(path);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ParsePath_WhenPathContainsWhitespaceSegment_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create(@"C:\ \folder");
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<PathSegment>> result = _sut.ParsePath(path);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.NameCannotBeEmpty, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ParsePath_WithPathContainingDots_ShouldParseCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create(@"C:\Users\User\file.with.dots.txt");
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<PathSegment>> result = _sut.ParsePath(path);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(4, result.Value.Count());
|
||||
Assert.Equivalent(_pathSegmentFixture.Create("file.with.dots.txt", false, false), result.Value.Last());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ParsePath_WithUNCPath_ShouldReturnCorrectPathSegments()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create(@"\\server\share\folder\file.txt");
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<PathSegment>> result = _sut.ParsePath(path);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(5, result.Value.Count());
|
||||
Assert.Equivalent(_pathSegmentFixture.Create(@"\\", false, true), result.Value.ElementAt(0));
|
||||
Assert.Equivalent(_pathSegmentFixture.Create("server", true, false), result.Value.ElementAt(1));
|
||||
Assert.Equivalent(_pathSegmentFixture.Create("share", true, false), result.Value.ElementAt(2));
|
||||
Assert.Equivalent(_pathSegmentFixture.Create("folder", true, false), result.Value.ElementAt(3));
|
||||
Assert.Equivalent(_pathSegmentFixture.Create("file.txt", false, false), result.Value.ElementAt(4));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GoUpOneLevel_WithValidPath_ShouldReturnParentPath()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create(@"C:\Users\User\Documents");
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<PathSegment>> result = _sut.GoUpOneLevel(path);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(3, result.Value.Count());
|
||||
Assert.Equivalent(_pathSegmentFixture.Create("C:", false, true), result.Value.ElementAt(0));
|
||||
Assert.Equivalent(_pathSegmentFixture.Create("Users", true, false), result.Value.ElementAt(1));
|
||||
Assert.Equivalent(_pathSegmentFixture.Create("User", true, false), result.Value.ElementAt(2));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GoUpOneLevel_WithRootPath_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create(@"C:\");
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<PathSegment>> result = _sut.GoUpOneLevel(path);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.CannotNavigateUp, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GoUpOneLevel_WithTrailingBackslash_ShouldReturnCorrectParentPath()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create(@"C:\Users\User\");
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<PathSegment>> result = _sut.GoUpOneLevel(path);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(2, result.Value.Count());
|
||||
Assert.Equivalent(_pathSegmentFixture.Create("C:", false, true), result.Value.ElementAt(0));
|
||||
Assert.Equivalent(_pathSegmentFixture.Create("Users", true, false), result.Value.ElementAt(1));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GoUpOneLevel_WithInvalidPath_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create(@"invalid\path");
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<PathSegment>> result = _sut.GoUpOneLevel(path);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GoUpOneLevel_WithSingleLevelPath_ShouldReturnRootPath()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create(@"C:\Users");
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<PathSegment>> result = _sut.GoUpOneLevel(path);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Single(result.Value);
|
||||
Assert.Equivalent(_pathSegmentFixture.Create("C:", false, true), result.Value.Single());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GoUpOneLevel_WithUNCPath_ShouldReturnParentPath()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create(@"\\server\share\folder\subfolder");
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<PathSegment>> result = _sut.GoUpOneLevel(path);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(4, result.Value.Count());
|
||||
Assert.Equivalent(_pathSegmentFixture.Create(@"\\", false, true), result.Value.ElementAt(0));
|
||||
Assert.Equivalent(_pathSegmentFixture.Create("server", true, false), result.Value.ElementAt(1));
|
||||
Assert.Equivalent(_pathSegmentFixture.Create("share", true, false), result.Value.ElementAt(2));
|
||||
Assert.Equivalent(_pathSegmentFixture.Create("folder", true, false), result.Value.ElementAt(3));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GoUpOneLevel_WithUNCRootPath_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create(@"\\server\share");
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<PathSegment>> result = _sut.GoUpOneLevel(path);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.CannotNavigateUp, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GoUpOneLevel_WithUNCPathWithOneFolder_ShouldReturnUNCRoot()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create(@"\\server\share\folder");
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<PathSegment>> result = _sut.GoUpOneLevel(path);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(3, result.Value.Count());
|
||||
Assert.Equivalent(_pathSegmentFixture.Create(@"\\", false, true), result.Value.ElementAt(0));
|
||||
Assert.Equivalent(_pathSegmentFixture.Create("server", true, false), result.Value.ElementAt(1));
|
||||
Assert.Equivalent(_pathSegmentFixture.Create("share", true, false), result.Value.ElementAt(2));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GoUpOneLevel_WithDriveRootAndBackslash_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create(@"C:\");
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<PathSegment>> result = _sut.GoUpOneLevel(path);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.CannotNavigateUp, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetInvalidPathCharsForPlatform_WhenCalled_ShouldReturnExpectedCharacters()
|
||||
{
|
||||
// Act
|
||||
char[] result = _sut.GetInvalidPathCharsForPlatform();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(['<', '>', '"', '/', '|', '?', '*'], result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetInvalidPathCharsForPlatform_WhenCalled_ShouldNotContainCertainCharacters()
|
||||
{
|
||||
// Act
|
||||
char[] result = _sut.GetInvalidPathCharsForPlatform();
|
||||
|
||||
// Assert
|
||||
Assert.DoesNotContain('\\', result);
|
||||
Assert.DoesNotContain(':', result);
|
||||
Assert.DoesNotContain('\0', result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetInvalidPathCharsForPlatform_WhenCalled_ShouldReturnSameResultOnMultipleCalls()
|
||||
{
|
||||
// Act
|
||||
char[] result1 = _sut.GetInvalidPathCharsForPlatform();
|
||||
char[] result2 = _sut.GetInvalidPathCharsForPlatform();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(result1, result2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetInvalidPathSegmentCharsForPlatform_WhenCalled_ShouldReturnExpectedCharacters()
|
||||
{
|
||||
// Act
|
||||
char[] result = _sut.GetInvalidPathSegmentCharsForPlatform();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(['<', '>', '"', '/', '|', '?', '*', ':'], result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetInvalidPathSegmentCharsForPlatform_WhenCalled_ShouldContainTheColon()
|
||||
{
|
||||
// Act
|
||||
char[] result = _sut.GetInvalidPathSegmentCharsForPlatform();
|
||||
|
||||
// Assert
|
||||
Assert.Contains(':', result);
|
||||
Assert.DoesNotContain('\\', result);
|
||||
Assert.DoesNotContain('\0', result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetInvalidPathSegmentCharsForPlatform_WhenCalled_ShouldReturnSameResultOnMultipleCalls()
|
||||
{
|
||||
// Act
|
||||
char[] result1 = _sut.GetInvalidPathSegmentCharsForPlatform();
|
||||
char[] result2 = _sut.GetInvalidPathSegmentCharsForPlatform();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(result1, result2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetPathRoot_WithValidWindowsPath_ShouldReturnRootSegment()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create(@"C:\Users\User\Documents");
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.GetPathRoot(path);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equivalent(_pathSegmentFixture.Create("C:\\", true, true), result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetPathRoot_WithRootPath_ShouldReturnRootSegment()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create(@"C:\");
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.GetPathRoot(path);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equivalent(_pathSegmentFixture.Create("C:\\", true, true), result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetPathRoot_WithInvalidPath_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create(@"InvalidFolder");
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.GetPathRoot(path);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetPathRoot_WithUNCPath_ShouldReturnUNCRootSegment()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create(@"\\server\share\folder");
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.GetPathRoot(path);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equivalent(_pathSegmentFixture.Create(@"\\server\share\", true, false), result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetPathRoot_WithInvalidUNCPath_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create(@"\\");
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.GetPathRoot(path);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetPathRoot_WithUNCPathWithoutShare_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create(@"\\server");
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.GetPathRoot(path);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetPathRoot_WithNonDriveNonUNCPath_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create(@"InvalidPath");
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.GetPathRoot(path);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetPathRoot_WithUNCPathMissingServerName_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create(@"\\");
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.GetPathRoot(path);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetPathRoot_WithUNCPathWithoutThirdBackslash_ShouldReturnServerAndShare()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create(@"\\server\share");
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.GetPathRoot(path);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equivalent(_pathSegmentFixture.Create(@"\\server\share\", true, false), result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetPathRoot_WithNeitherUNCNorDrivePath_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId path = _fileSystemPathIdFixture.Create(@"invalid\path");
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.GetPathRoot(path);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(@"C:\Media\Books", @"C:\Media\Books\book.epub")] // Direct child.
|
||||
[InlineData(@"C:\Media", @"C:\Media\Books\book.epub")] // Nested descendant.
|
||||
[InlineData(@"C:\Media\Books\", @"C:\Media\Books\book.epub")] // Trailing separator on the parent.
|
||||
[InlineData(@"C:\Media\Books", @"c:\media\books\book.epub")] // Windows paths are case-insensitive.
|
||||
[InlineData(@"C:\Media\Books", @"C:\Media\Books\Sub\..\book.epub")] // Relative segments that stay inside.
|
||||
public void IsPathWithin_WithContainedPaths_ShouldReturnTrue(string parentPath, string path)
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId parentPathId = _fileSystemPathIdFixture.Create(parentPath);
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path);
|
||||
|
||||
// Act
|
||||
bool result = _sut.IsPathWithin(pathId, parentPathId);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(@"C:\Media\Books", @"C:\Media\book.epub")] // Sibling directory.
|
||||
[InlineData(@"C:\Media\Books", @"D:\Media\Books\book.epub")] // Different drive.
|
||||
[InlineData(@"C:\Media\Books", @"C:\Media\BookShelf\book.epub")] // A sibling whose name shares the prefix.
|
||||
[InlineData(@"C:\Media\Books", @"C:\Media\Other\book.epub")] // Sibling directory.
|
||||
[InlineData(@"C:\Media\Books", @"C:\Media\Books\..\Other\book.epub")] // Relative segment that escapes the parent.
|
||||
[InlineData(@"C:\Media\Books", @"C:\Windows\System32\config\SAM")] // Unrelated location.
|
||||
[InlineData(@"C:\Media", @"C:\Media")] // The parent itself is not inside itself.
|
||||
public void IsPathWithin_WithPathsOutsideTheParent_ShouldReturnFalse(string parentPath, string path)
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId parentPathId = _fileSystemPathIdFixture.Create(parentPath);
|
||||
FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path);
|
||||
|
||||
// Act
|
||||
bool result = _sut.IsPathWithin(pathId, parentPathId);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Path;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO.Abstractions;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="PlatformContextFactory"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PlatformContextFactoryTests
|
||||
{
|
||||
private readonly IServiceProvider _serviceProvider;
|
||||
private readonly PlatformContextFactory _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PlatformContextFactoryTests"/> class.
|
||||
/// </summary>
|
||||
public PlatformContextFactoryTests()
|
||||
{
|
||||
ServiceCollection services = new();
|
||||
services.AddTransient<IWindowsPlatformContext, WindowsPlatformContext>();
|
||||
services.AddTransient<IUnixPlatformContext, UnixPlatformContext>();
|
||||
services.AddTransient<IUnixPathStrategy, UnixPathStrategy>();
|
||||
services.AddTransient<IWindowsPathStrategy, WindowsPathStrategy>();
|
||||
services.AddTransient<IFileSystem, FileSystem>();
|
||||
_serviceProvider = services.BuildServiceProvider();
|
||||
_sut = new PlatformContextFactory(_serviceProvider);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateStrategy_WhenWindowsServiceExists_ShouldReturnWindowsService()
|
||||
{
|
||||
// Act
|
||||
IWindowsPlatformContext result = _sut.CreateStrategy<IWindowsPlatformContext>();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.IsType<WindowsPlatformContext>(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateStrategy_WhenUnixServiceExists_ShouldReturnUnixService()
|
||||
{
|
||||
// Act
|
||||
IUnixPlatformContext result = _sut.CreateStrategy<IUnixPlatformContext>();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.IsType<UnixPlatformContext>(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateStrategy_WhenServiceDoesNotExist_ShouldThrowInvalidOperationException()
|
||||
{
|
||||
// Act & Assert
|
||||
Assert.Throws<InvalidOperationException>(() => _sut.CreateStrategy<INonExistentPlatformContextFixture>());
|
||||
}
|
||||
}
|
||||
+150
@@ -0,0 +1,150 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.FileSystem;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Runtime.InteropServices;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="PlatformContextManager"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PlatformContextManagerTests
|
||||
{
|
||||
private readonly IPlatformContextFactory _mockPlatformContextFactory;
|
||||
private PlatformContextManager? sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PlatformContextManagerTests"/> class.
|
||||
/// </summary>
|
||||
public PlatformContextManagerTests()
|
||||
{
|
||||
_mockPlatformContextFactory = Substitute.For<IPlatformContextFactory>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetCurrentContext_WhenNoContextSet_ShouldSetDefaultContext()
|
||||
{
|
||||
// Arrange
|
||||
IWindowsPlatformContext mockWindowsContext = Substitute.For<IWindowsPlatformContext>();
|
||||
_mockPlatformContextFactory.CreateStrategy<IWindowsPlatformContext>().Returns(mockWindowsContext);
|
||||
IOperatingSystemInfo mockOsInfo = Substitute.For<IOperatingSystemInfo>();
|
||||
mockOsInfo.IsOSPlatform(OSPlatform.Linux).Returns(false);
|
||||
sut = new(_mockPlatformContextFactory, mockOsInfo);
|
||||
|
||||
// Act
|
||||
IPlatformContext result = sut.GetCurrentContext();
|
||||
|
||||
// Assert
|
||||
Assert.Same(mockWindowsContext, result);
|
||||
_mockPlatformContextFactory.Received(1).CreateStrategy<IWindowsPlatformContext>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetCurrentContext_WhenContextAlreadySet_ShouldReturnExistingContext()
|
||||
{
|
||||
// Arrange
|
||||
IUnixPlatformContext mockUnixContext = Substitute.For<IUnixPlatformContext>();
|
||||
_mockPlatformContextFactory.CreateStrategy<IUnixPlatformContext>().Returns(mockUnixContext);
|
||||
IOperatingSystemInfo mockOsInfo = Substitute.For<IOperatingSystemInfo>();
|
||||
sut = new(_mockPlatformContextFactory, mockOsInfo);
|
||||
sut.SetCurrentPlatform(PlatformType.Unix);
|
||||
|
||||
// Act
|
||||
IPlatformContext result = sut.GetCurrentContext();
|
||||
|
||||
// Assert
|
||||
Assert.Same(mockUnixContext, result);
|
||||
_mockPlatformContextFactory.Received(1).CreateStrategy<IUnixPlatformContext>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SetCurrentPlatform_WhenUnixPlatform_ShouldSetUnixContext()
|
||||
{
|
||||
// Arrange
|
||||
IUnixPlatformContext mockUnixContext = Substitute.For<IUnixPlatformContext>();
|
||||
_mockPlatformContextFactory.CreateStrategy<IUnixPlatformContext>().Returns(mockUnixContext);
|
||||
IOperatingSystemInfo mockOsInfo = Substitute.For<IOperatingSystemInfo>();
|
||||
mockOsInfo.IsOSPlatform(OSPlatform.Linux).Returns(true);
|
||||
sut = new(_mockPlatformContextFactory, mockOsInfo);
|
||||
|
||||
// Act
|
||||
sut.SetCurrentPlatform(PlatformType.Unix);
|
||||
IPlatformContext result = sut.GetCurrentContext();
|
||||
|
||||
// Assert
|
||||
Assert.Same(mockUnixContext, result);
|
||||
_mockPlatformContextFactory.Received(1).CreateStrategy<IUnixPlatformContext>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SetCurrentPlatform_WhenWindowsPlatform_ShouldSetWindowsContext()
|
||||
{
|
||||
// Arrange
|
||||
IWindowsPlatformContext mockWindowsContext = Substitute.For<IWindowsPlatformContext>();
|
||||
_mockPlatformContextFactory.CreateStrategy<IWindowsPlatformContext>().Returns(mockWindowsContext);
|
||||
IOperatingSystemInfo mockOsInfo = Substitute.For<IOperatingSystemInfo>();
|
||||
mockOsInfo.IsOSPlatform(OSPlatform.Linux).Returns(false);
|
||||
sut = new(_mockPlatformContextFactory, mockOsInfo);
|
||||
|
||||
// Act
|
||||
sut.SetCurrentPlatform(PlatformType.Windows);
|
||||
IPlatformContext result = sut.GetCurrentContext();
|
||||
|
||||
// Assert
|
||||
Assert.Same(mockWindowsContext, result);
|
||||
_mockPlatformContextFactory.Received(1).CreateStrategy<IWindowsPlatformContext>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SetCurrentPlatform_WhenUnsupportedPlatform_ShouldThrowArgumentException()
|
||||
{
|
||||
// Arrange
|
||||
PlatformType unsupportedPlatform = (PlatformType)999; // An unsupported platform type.
|
||||
IOperatingSystemInfo mockOsInfo = Substitute.For<IOperatingSystemInfo>();
|
||||
sut = new(_mockPlatformContextFactory, mockOsInfo);
|
||||
|
||||
// Act & Assert
|
||||
Assert.Throws<ArgumentException>(() => sut.SetCurrentPlatform(unsupportedPlatform));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetCurrentContext_WhenRunningOnLinux_ShouldSetUnixContextByDefault()
|
||||
{
|
||||
// Arrange
|
||||
IUnixPlatformContext mockUnixContext = Substitute.For<IUnixPlatformContext>();
|
||||
_mockPlatformContextFactory.CreateStrategy<IUnixPlatformContext>().Returns(mockUnixContext);
|
||||
IOperatingSystemInfo mockOsInfo = Substitute.For<IOperatingSystemInfo>();
|
||||
mockOsInfo.IsOSPlatform(OSPlatform.Linux).Returns(true);
|
||||
sut = new(_mockPlatformContextFactory, mockOsInfo);
|
||||
|
||||
// Act
|
||||
IPlatformContext result = sut.GetCurrentContext();
|
||||
|
||||
// Assert
|
||||
Assert.Same(mockUnixContext, result);
|
||||
_mockPlatformContextFactory.Received(1).CreateStrategy<IUnixPlatformContext>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetCurrentContext_WhenRunningOnWindows_ShouldSetWindowsContextByDefault()
|
||||
{
|
||||
// Arrange
|
||||
IWindowsPlatformContext mockWindowsContext = Substitute.For<IWindowsPlatformContext>();
|
||||
_mockPlatformContextFactory.CreateStrategy<IWindowsPlatformContext>().Returns(mockWindowsContext);
|
||||
IOperatingSystemInfo mockOsInfo = Substitute.For<IOperatingSystemInfo>();
|
||||
mockOsInfo.IsOSPlatform(OSPlatform.Linux).Returns(false);
|
||||
sut = new(_mockPlatformContextFactory, mockOsInfo);
|
||||
|
||||
// Act
|
||||
IPlatformContext result = sut.GetCurrentContext();
|
||||
|
||||
// Assert
|
||||
Assert.Same(mockWindowsContext, result);
|
||||
_mockPlatformContextFactory.Received(1).CreateStrategy<IWindowsPlatformContext>();
|
||||
}
|
||||
}
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.FileSystem;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Path;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform;
|
||||
using NSubstitute;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="WindowsPlatformContext"/> and <see cref="UnixPlatformContext"/> classes.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PlatformContextTests
|
||||
{
|
||||
[Fact]
|
||||
public void WindowsPlatformContext_Constructor_ShouldSetPropertiesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
IWindowsPathStrategy mockWindowsPathStrategy = Substitute.For<IWindowsPathStrategy>();
|
||||
|
||||
// Act
|
||||
WindowsPlatformContext windowsPlatformContext = new(mockWindowsPathStrategy);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(PlatformType.Windows, windowsPlatformContext.Platform);
|
||||
Assert.Equal(mockWindowsPathStrategy, windowsPlatformContext.PathStrategy);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UnixPlatformContext_Constructor_ShouldSetPropertiesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
IUnixPathStrategy mockUnixPathStrategy = Substitute.For<IUnixPathStrategy>();
|
||||
|
||||
// Act
|
||||
UnixPlatformContext unixPlatformContext = new(mockUnixPathStrategy);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(PlatformType.Unix, unixPlatformContext.Platform);
|
||||
Assert.Equal(mockUnixPathStrategy, unixPlatformContext.PathStrategy);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WindowsPlatformContext_ShouldImplementIWindowsPlatformContext()
|
||||
{
|
||||
// Arrange
|
||||
IWindowsPathStrategy mockWindowsPathStrategy = Substitute.For<IWindowsPathStrategy>();
|
||||
|
||||
// Act
|
||||
WindowsPlatformContext windowsPlatformContext = new(mockWindowsPathStrategy);
|
||||
|
||||
// Assert
|
||||
Assert.IsAssignableFrom<IWindowsPlatformContext>(windowsPlatformContext);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UnixPlatformContext_ShouldImplementIUnixPlatformContext()
|
||||
{
|
||||
// Arrange
|
||||
IUnixPathStrategy mockUnixPathStrategy = Substitute.For<IUnixPathStrategy>();
|
||||
|
||||
// Act
|
||||
UnixPlatformContext unixPlatformContext = new(mockUnixPathStrategy);
|
||||
|
||||
// Assert
|
||||
Assert.IsAssignableFrom<IUnixPlatformContext>(unixPlatformContext);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WindowsPlatformContext_PathStrategy_ShouldBeReadOnly()
|
||||
{
|
||||
// Arrange
|
||||
IWindowsPathStrategy mockWindowsPathStrategy = Substitute.For<IWindowsPathStrategy>();
|
||||
WindowsPlatformContext windowsPlatformContext = new(mockWindowsPathStrategy);
|
||||
|
||||
// Act & Assert
|
||||
Assert.Null(windowsPlatformContext.GetType().GetProperty(nameof(WindowsPlatformContext.PathStrategy))!.SetMethod);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UnixPlatformContext_PathStrategy_ShouldBeReadOnly()
|
||||
{
|
||||
// Arrange
|
||||
IUnixPathStrategy mockUnixPathStrategy = Substitute.For<IUnixPathStrategy>();
|
||||
UnixPlatformContext unixPlatformContext = new(mockUnixPathStrategy);
|
||||
|
||||
// Act & Assert
|
||||
Assert.Null(unixPlatformContext.GetType().GetProperty(nameof(UnixPlatformContext.PathStrategy))!.SetMethod);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WindowsPlatformContext_Platform_ShouldBeReadOnly()
|
||||
{
|
||||
// Arrange
|
||||
IWindowsPathStrategy mockWindowsPathStrategy = Substitute.For<IWindowsPathStrategy>();
|
||||
WindowsPlatformContext windowsPlatformContext = new(mockWindowsPathStrategy);
|
||||
|
||||
// Act & Assert
|
||||
Assert.Null(windowsPlatformContext.GetType().GetProperty(nameof(WindowsPlatformContext.Platform))!.SetMethod);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UnixPlatformContext_Platform_ShouldBeReadOnly()
|
||||
{
|
||||
// Arrange
|
||||
IUnixPathStrategy mockUnixPathStrategy = Substitute.For<IUnixPathStrategy>();
|
||||
UnixPlatformContext unixPlatformContext = new(mockUnixPathStrategy);
|
||||
|
||||
// Act & Assert
|
||||
Assert.Null(unixPlatformContext.GetType().GetProperty(nameof(UnixPlatformContext.Platform))!.SetMethod);
|
||||
}
|
||||
}
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="FileSystemPathId"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FileSystemPathIdTests
|
||||
{
|
||||
private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Create_WithValidPath_ShouldReturnFileSystemPathId()
|
||||
{
|
||||
// Arrange
|
||||
string validPath = @"C:\TestDir\file.txt";
|
||||
|
||||
// Act
|
||||
Result<FileSystemPathId> result = FileSystemPathId.Create(validPath);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(validPath, result.Value.Path);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
public void Create_WithInvalidPath_ShouldReturnError(string? invalidPath)
|
||||
{
|
||||
// Act
|
||||
Result<FileSystemPathId> result = FileSystemPathId.Create(invalidPath!);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithSamePath_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
string path = @"C:\TestDir\file.txt";
|
||||
FileSystemPathId id1 = _fileSystemPathIdFixture.Create(path);
|
||||
FileSystemPathId id2 = _fileSystemPathIdFixture.Create(path);
|
||||
|
||||
// Act
|
||||
bool result = id1.Equals(id2);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentPath_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId id1 = _fileSystemPathIdFixture.Create(@"C:\TestDir\file1.txt");
|
||||
FileSystemPathId id2 = _fileSystemPathIdFixture.Create(@"C:\TestDir\file2.txt");
|
||||
|
||||
// Act
|
||||
bool result = id1.Equals(id2);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetHashCode_WithSamePath_ShouldReturnSameHashCode()
|
||||
{
|
||||
// Arrange
|
||||
string path = @"C:\TestDir\file.txt";
|
||||
FileSystemPathId id1 = _fileSystemPathIdFixture.Create(path);
|
||||
FileSystemPathId id2 = _fileSystemPathIdFixture.Create(path);
|
||||
|
||||
// Act
|
||||
int hashCode1 = id1.GetHashCode();
|
||||
int hashCode2 = id2.GetHashCode();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(hashCode1, hashCode2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetHashCode_WithDifferentPath_ShouldReturnDifferentHashCode()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId id1 = _fileSystemPathIdFixture.Create(@"C:\TestDir\file1.txt");
|
||||
FileSystemPathId id2 = _fileSystemPathIdFixture.Create(@"C:\TestDir\file2.txt");
|
||||
|
||||
// Act
|
||||
int hashCode1 = id1.GetHashCode();
|
||||
int hashCode2 = id2.GetHashCode();
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(hashCode1, hashCode2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EqualityOperator_WithSamePath_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
string path = @"C:\TestDir\file.txt";
|
||||
FileSystemPathId id1 = _fileSystemPathIdFixture.Create(path);
|
||||
FileSystemPathId id2 = _fileSystemPathIdFixture.Create(path);
|
||||
|
||||
// Act
|
||||
bool result = id1 == id2;
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InequalityOperator_WithDifferentPath_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId id1 = _fileSystemPathIdFixture.Create(@"C:\TestDir\file1.txt");
|
||||
FileSystemPathId id2 = _fileSystemPathIdFixture.Create(@"C:\TestDir\file2.txt");
|
||||
|
||||
// Act
|
||||
bool result = id1 != id2;
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
}
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="PathSegment"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PathSegmentTests
|
||||
{
|
||||
private readonly PathSegmentFixture _pathSegmentFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Create_WithValidInput_ShouldReturnPathSegment()
|
||||
{
|
||||
// Arrange
|
||||
string name = "testFolder";
|
||||
bool isDirectory = true;
|
||||
bool isDrive = false;
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = PathSegment.Create(name, isDirectory, isDrive);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(name, result.Value.Name);
|
||||
Assert.Equal(isDirectory, result.Value.IsDirectory);
|
||||
Assert.Equal(isDrive, result.Value.IsDrive);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
public void Create_WithInvalidName_ShouldReturnError(string? invalidName)
|
||||
{
|
||||
// Act
|
||||
Result<PathSegment> result = PathSegment.Create(invalidName!, true, false);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.NameCannotBeEmpty, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithSameProperties_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
PathSegment segment1 = _pathSegmentFixture.Create("folder", true, false);
|
||||
PathSegment segment2 = _pathSegmentFixture.Create("folder", true, false);
|
||||
|
||||
// Act
|
||||
bool result = segment1.Equals(segment2);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentProperties_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
PathSegment segment1 = _pathSegmentFixture.Create("folder1", true, false);
|
||||
PathSegment segment2 = _pathSegmentFixture.Create("folder2", true, false);
|
||||
|
||||
// Act
|
||||
bool result = segment1.Equals(segment2);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetHashCode_WithSameProperties_ShouldReturnSameHashCode()
|
||||
{
|
||||
// Arrange
|
||||
PathSegment segment1 = _pathSegmentFixture.Create("folder", true, false);
|
||||
PathSegment segment2 = _pathSegmentFixture.Create("folder", true, false);
|
||||
|
||||
// Act
|
||||
int hashCode1 = segment1.GetHashCode();
|
||||
int hashCode2 = segment2.GetHashCode();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(hashCode1, hashCode2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetHashCode_WithDifferentProperties_ShouldReturnDifferentHashCode()
|
||||
{
|
||||
// Arrange
|
||||
PathSegment segment1 = _pathSegmentFixture.Create("folder1", true, false);
|
||||
PathSegment segment2 = _pathSegmentFixture.Create("folder2", true, false);
|
||||
|
||||
// Act
|
||||
int hashCode1 = segment1.GetHashCode();
|
||||
int hashCode2 = segment2.GetHashCode();
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(hashCode1, hashCode2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EqualityOperator_WithSameProperties_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
PathSegment segment1 = _pathSegmentFixture.Create("folder", true, false);
|
||||
PathSegment segment2 = _pathSegmentFixture.Create("folder", true, false);
|
||||
|
||||
// Act
|
||||
bool result = segment1 == segment2;
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InequalityOperator_WithDifferentProperties_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
PathSegment segment1 = _pathSegmentFixture.Create("folder1", true, false);
|
||||
PathSegment segment2 = _pathSegmentFixture.Create("folder2", true, false);
|
||||
|
||||
// Act
|
||||
bool result = segment1 != segment2;
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
}
|
||||
+160
@@ -0,0 +1,160 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="StreamInfo"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class StreamInfoTests
|
||||
{
|
||||
private readonly StreamInfoFixture _streamInfoFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Create_WithValidInput_ShouldReturnStreamInfo()
|
||||
{
|
||||
// Arrange
|
||||
string streamId = "testStream";
|
||||
string mimeType = "video/mp4";
|
||||
int bitrate = 1000;
|
||||
string codec = "h264";
|
||||
Optional<string> resolution = Optional<string>.Some("1920x1080");
|
||||
Optional<float> frameRate = Optional<float>.Some(30.0f);
|
||||
Optional<int> sampleRate = Optional<int>.Some(44100);
|
||||
Optional<int> channels = Optional<int>.Some(2);
|
||||
|
||||
// Act
|
||||
Result<StreamInfo> result = StreamInfo.Create(streamId, mimeType, bitrate, codec, resolution, frameRate, sampleRate, channels);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(streamId, result.Value.StreamId);
|
||||
Assert.Equal(mimeType, result.Value.MimeType);
|
||||
Assert.Equal(bitrate, result.Value.Bitrate);
|
||||
Assert.Equal(codec, result.Value.Codec);
|
||||
Assert.Equal(resolution, result.Value.Resolution);
|
||||
Assert.Equal(frameRate, result.Value.FrameRate);
|
||||
Assert.Equal(sampleRate, result.Value.SampleRate);
|
||||
Assert.Equal(channels, result.Value.Channels);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WithNullStreamId_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
string? streamId = null;
|
||||
string mimeType = "video/mp4";
|
||||
int bitrate = 1000;
|
||||
string codec = "h264";
|
||||
|
||||
// Act
|
||||
Result<StreamInfo> result = StreamInfo.Create(streamId!, mimeType, bitrate, codec, Optional<string>.None(), Optional<float>.None(), Optional<int>.None(), Optional<int>.None());
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.StreamIdCannotBeEmpty, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WithNullCodec_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
string streamId = "testStream";
|
||||
string mimeType = "video/mp4";
|
||||
int bitrate = 1000;
|
||||
string? codec = null;
|
||||
|
||||
// Act
|
||||
Result<StreamInfo> result = StreamInfo.Create(streamId, mimeType, bitrate, codec!, Optional<string>.None(), Optional<float>.None(), Optional<int>.None(), Optional<int>.None());
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.CodecCannotBeEmpty, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WithNonPositiveBitrate_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
string streamId = "testStream";
|
||||
string mimeType = "video/mp4";
|
||||
int bitrate = 0;
|
||||
string codec = "h264";
|
||||
|
||||
// Act
|
||||
Result<StreamInfo> result = StreamInfo.Create(streamId, mimeType, bitrate, codec, Optional<string>.None(), Optional<float>.None(), Optional<int>.None(), Optional<int>.None());
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.BitrateMustBeAPositiveNumber, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithSameProperties_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
StreamInfo info1 = _streamInfoFixture.Create();
|
||||
StreamInfo info2 = _streamInfoFixture.Create(
|
||||
info1.StreamId, info1.MimeType, info1.Bitrate, info1.Codec,
|
||||
info1.Resolution, info1.FrameRate, info1.SampleRate, info1.Channels);
|
||||
|
||||
// Act
|
||||
bool result = info1.Equals(info2);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentProperties_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
StreamInfo info1 = _streamInfoFixture.Create();
|
||||
StreamInfo info2 = _streamInfoFixture.Create();
|
||||
|
||||
// Act
|
||||
bool result = info1.Equals(info2);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetHashCode_WithSameProperties_ShouldReturnSameHashCode()
|
||||
{
|
||||
// Arrange
|
||||
StreamInfo info1 = _streamInfoFixture.Create();
|
||||
StreamInfo info2 = _streamInfoFixture.Create(
|
||||
info1.StreamId, info1.MimeType, info1.Bitrate, info1.Codec,
|
||||
info1.Resolution, info1.FrameRate, info1.SampleRate, info1.Channels);
|
||||
|
||||
// Act
|
||||
int hashCode1 = info1.GetHashCode();
|
||||
int hashCode2 = info2.GetHashCode();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(hashCode1, hashCode2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetHashCode_WithDifferentProperties_ShouldReturnDifferentHashCode()
|
||||
{
|
||||
// Arrange
|
||||
StreamInfo info1 = _streamInfoFixture.Create();
|
||||
StreamInfo info2 = _streamInfoFixture.Create();
|
||||
|
||||
// Act
|
||||
int hashCode1 = info1.GetHashCode();
|
||||
int hashCode2 = info2.GetHashCode();
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(hashCode1, hashCode2);
|
||||
}
|
||||
}
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="Thumbnail"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ThumbnailTests
|
||||
{
|
||||
private readonly ThumbnailFixture _thumbnailFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenCalled_ShouldSetPropertiesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
ImageType type = ImageType.PNG;
|
||||
byte[] bytes = [1, 2, 3, 4, 5];
|
||||
|
||||
// Act
|
||||
Thumbnail thumbnail = _thumbnailFixture.Create(type, bytes);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(type, thumbnail.Type);
|
||||
Assert.Equal(bytes, thumbnail.Bytes);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithSameProperties_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
Thumbnail thumbnail1 = _thumbnailFixture.Create();
|
||||
Thumbnail thumbnail2 = _thumbnailFixture.Create(thumbnail1.Type, thumbnail1.Bytes);
|
||||
|
||||
// Act
|
||||
bool result = thumbnail1.Equals(thumbnail2);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentType_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
Thumbnail thumbnail1 = _thumbnailFixture.Create(ImageType.PNG);
|
||||
Thumbnail thumbnail2 = _thumbnailFixture.Create(ImageType.JPEG, thumbnail1.Bytes);
|
||||
|
||||
// Act
|
||||
bool result = thumbnail1.Equals(thumbnail2);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentBytes_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
Thumbnail thumbnail1 = _thumbnailFixture.Create();
|
||||
Thumbnail thumbnail2 = _thumbnailFixture.Create(thumbnail1.Type);
|
||||
|
||||
// Act
|
||||
bool result = thumbnail1.Equals(thumbnail2);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetHashCode_WithSameProperties_ShouldReturnSameHashCode()
|
||||
{
|
||||
// Arrange
|
||||
Thumbnail thumbnail1 = _thumbnailFixture.Create();
|
||||
Thumbnail thumbnail2 = _thumbnailFixture.Create(thumbnail1.Type, thumbnail1.Bytes);
|
||||
|
||||
// Act
|
||||
int hashCode1 = thumbnail1.GetHashCode();
|
||||
int hashCode2 = thumbnail2.GetHashCode();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(hashCode1, hashCode2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetHashCode_WithDifferentProperties_ShouldReturnDifferentHashCode()
|
||||
{
|
||||
// Arrange
|
||||
Thumbnail thumbnail1 = _thumbnailFixture.Create();
|
||||
Thumbnail thumbnail2 = _thumbnailFixture.Create();
|
||||
|
||||
// Act
|
||||
int hashCode1 = thumbnail1.GetHashCode();
|
||||
int hashCode2 = thumbnail2.GetHashCode();
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(hashCode1, hashCode2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetEqualityComponents_ShouldReturnTypeAndBytes()
|
||||
{
|
||||
// Arrange
|
||||
Thumbnail thumbnail = _thumbnailFixture.Create();
|
||||
|
||||
// Act
|
||||
List<object> components = [.. thumbnail.GetEqualityComponents()];
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, components.Count);
|
||||
Assert.Equal(thumbnail.Type, components[0]);
|
||||
Assert.Equal(thumbnail.Bytes, components[1]);
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="LibraryDeletedDomainEvent"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LibraryDeletedDomainEventTests
|
||||
{
|
||||
private readonly LibraryFixture _libraryFixture = new();
|
||||
private readonly LibraryDeletedDomainEventFixture _libraryDeletedDomainEventFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenCalled_ShouldSetAllProperties()
|
||||
{
|
||||
// Arrange
|
||||
Guid id = Guid.NewGuid();
|
||||
Library library = _libraryFixture.Create();
|
||||
DateTime occurredOnUtc = DateTime.UtcNow;
|
||||
|
||||
// Act
|
||||
LibraryDeletedDomainEvent domainEvent = _libraryDeletedDomainEventFixture.Create(id, library, occurredOnUtc);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(id, domainEvent.Id);
|
||||
Assert.Equal(library, domainEvent.Library);
|
||||
Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc);
|
||||
Assert.IsType<IDomainEvent>(domainEvent, exactMatch: false);
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="LibrarySavedDomainEvent"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LibrarySavedDomainEventTests
|
||||
{
|
||||
private readonly LibraryFixture _libraryFixture = new();
|
||||
private readonly LibrarySavedDomainEventFixture _librarySavedDomainEventFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenCalled_ShouldSetAllProperties()
|
||||
{
|
||||
// Arrange
|
||||
Guid id = Guid.NewGuid();
|
||||
Library library = _libraryFixture.Create();
|
||||
DateTime occurredOnUtc = DateTime.UtcNow;
|
||||
|
||||
// Act
|
||||
LibrarySavedDomainEvent domainEvent = _librarySavedDomainEventFixture.Create(id, library, occurredOnUtc);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(id, domainEvent.Id);
|
||||
Assert.Equal(library, domainEvent.Library);
|
||||
Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc);
|
||||
Assert.IsType<IDomainEvent>(domainEvent, exactMatch: false);
|
||||
}
|
||||
}
|
||||
+295
@@ -0,0 +1,295 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="Library"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LibraryTests
|
||||
{
|
||||
private readonly LibraryFixture _libraryFixture = new();
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
private readonly ScanIdFixture _scanIdFixture = new();
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly LibraryConsumptionSettingsFixture _libraryConsumptionSettingsFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithValidData_ShouldCreateLibraryWithAllPropertiesSet()
|
||||
{
|
||||
// Arrange
|
||||
UserId userId = _userIdFixture.Create();
|
||||
string title = "My Books";
|
||||
LibraryType libraryType = LibraryType.Book;
|
||||
List<string> contentLocations = ["C:/Media/Books", "D:/Books"];
|
||||
string coverImageSourcePath = "C:/Cover/cover.jpg";
|
||||
List<ScanId> scanIds = [_scanIdFixture.Create(), _scanIdFixture.Create()];
|
||||
LibraryConsumptionSettings consumptionSettings = _libraryConsumptionSettingsFixture.Create(
|
||||
shouldTrackConsumptionProgress: true,
|
||||
completionThresholdPercentage: 75);
|
||||
|
||||
// Act
|
||||
Result<Library> result = Library.Create(
|
||||
userId,
|
||||
title,
|
||||
libraryType,
|
||||
contentLocations,
|
||||
coverImageSourcePath,
|
||||
isEnabled: false,
|
||||
isLocked: true,
|
||||
canDownloadMetadataFromWeb: false,
|
||||
shouldSaveMetadataInMediaDirectories: true,
|
||||
shouldSkipUnchangedDirectoriesDuringScan: true,
|
||||
shouldSkipHiddenFilesAndDirectoriesDuringScan: true,
|
||||
isContentOnSsd: true,
|
||||
consumptionSettings,
|
||||
LibraryPathTemplate.Empty(),
|
||||
scanIds);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(userId, result.Value.UserId);
|
||||
Assert.Equal(title, result.Value.Title);
|
||||
Assert.Equal(libraryType, result.Value.LibraryType);
|
||||
Assert.Equal(2, result.Value.ContentLocations.Count);
|
||||
Assert.True(result.Value.CoverImage.HasValue);
|
||||
Assert.Equal(coverImageSourcePath, result.Value.CoverImage.Value);
|
||||
Assert.False(result.Value.IsEnabled);
|
||||
Assert.True(result.Value.IsLocked);
|
||||
Assert.False(result.Value.CanDownloadMetadataFromWeb);
|
||||
Assert.True(result.Value.ShouldSaveMetadataInMediaDirectories);
|
||||
Assert.True(result.Value.ShouldSkipUnchangedDirectoriesDuringScan);
|
||||
Assert.True(result.Value.ShouldSkipHiddenFilesAndDirectoriesDuringScan);
|
||||
Assert.True(result.Value.IsContentOnSsd);
|
||||
Assert.Equal(consumptionSettings, result.Value.ConsumptionSettings);
|
||||
Assert.Equal(scanIds, result.Value.ScanIds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithPreExistingId_ShouldCreateLibraryWithThatId()
|
||||
{
|
||||
// Arrange
|
||||
Guid id = Guid.NewGuid();
|
||||
List<ScanId> scanIds = [_scanIdFixture.Create()];
|
||||
|
||||
// Act
|
||||
Result<Library> result = Library.Create(
|
||||
_libraryIdFixture.Create(id),
|
||||
_userIdFixture.Create(),
|
||||
"My Library",
|
||||
LibraryType.Movie,
|
||||
["C:/Media"],
|
||||
Optional<string>.None(),
|
||||
isEnabled: true,
|
||||
isLocked: false,
|
||||
canDownloadMetadataFromWeb: true,
|
||||
shouldSaveMetadataInMediaDirectories: false,
|
||||
shouldSkipUnchangedDirectoriesDuringScan: false,
|
||||
shouldSkipHiddenFilesAndDirectoriesDuringScan: false,
|
||||
isContentOnSsd: false,
|
||||
_libraryConsumptionSettingsFixture.Create(),
|
||||
LibraryPathTemplate.Empty(),
|
||||
scanIds);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(id, result.Value.Id.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenGivenPreExistingIdAndInvalidContentLocation_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
Guid id = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
Result<Library> result = Library.Create(
|
||||
_libraryIdFixture.Create(id),
|
||||
_userIdFixture.Create(),
|
||||
"My Library",
|
||||
LibraryType.Book,
|
||||
[""],
|
||||
Optional<string>.None(),
|
||||
isEnabled: true,
|
||||
isLocked: false,
|
||||
canDownloadMetadataFromWeb: true,
|
||||
shouldSaveMetadataInMediaDirectories: false,
|
||||
shouldSkipUnchangedDirectoriesDuringScan: false,
|
||||
shouldSkipHiddenFilesAndDirectoriesDuringScan: false,
|
||||
isContentOnSsd: false,
|
||||
_libraryConsumptionSettingsFixture.Create(),
|
||||
LibraryPathTemplate.Empty(),
|
||||
[]);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Lumina.Domain.Common.Errors.Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithValidData_ShouldLeaveCoverImageSourcePathUnset()
|
||||
{
|
||||
// Arrange
|
||||
Library library = _libraryFixture.Create();
|
||||
|
||||
// Act
|
||||
Optional<string> coverImageSourcePath = library.CoverImageSourcePath;
|
||||
|
||||
// Assert
|
||||
Assert.False(coverImageSourcePath.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithContentLocations_ShouldCreateFileSystemPathIdForEachLocation()
|
||||
{
|
||||
// Act
|
||||
Result<Library> result = Library.Create(
|
||||
_userIdFixture.Create(),
|
||||
"My Library",
|
||||
LibraryType.Book,
|
||||
["C:/Media/Books", "D:/Books"],
|
||||
Optional<string>.None(),
|
||||
isEnabled: true,
|
||||
isLocked: false,
|
||||
canDownloadMetadataFromWeb: true,
|
||||
shouldSaveMetadataInMediaDirectories: false,
|
||||
shouldSkipUnchangedDirectoriesDuringScan: false,
|
||||
shouldSkipHiddenFilesAndDirectoriesDuringScan: false,
|
||||
isContentOnSsd: false,
|
||||
_libraryConsumptionSettingsFixture.Create(),
|
||||
LibraryPathTemplate.Empty(),
|
||||
[]);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(2, result.Value.ContentLocations.Count);
|
||||
Assert.Contains(result.Value.ContentLocations, location => location.Path == "C:/Media/Books");
|
||||
Assert.Contains(result.Value.ContentLocations, location => location.Path == "D:/Books");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // Null content location.
|
||||
[InlineData("")] // Empty content location.
|
||||
[InlineData(" ")] // Whitespace content location.
|
||||
public void Create_WhenContentLocationIsInvalid_ShouldReturnError(string? contentLocation)
|
||||
{
|
||||
// Act
|
||||
Result<Library> result = Library.Create(
|
||||
_userIdFixture.Create(),
|
||||
"My Library",
|
||||
LibraryType.Book,
|
||||
[contentLocation!],
|
||||
Optional<string>.None(),
|
||||
isEnabled: true,
|
||||
isLocked: false,
|
||||
canDownloadMetadataFromWeb: true,
|
||||
shouldSaveMetadataInMediaDirectories: false,
|
||||
shouldSkipUnchangedDirectoriesDuringScan: false,
|
||||
shouldSkipHiddenFilesAndDirectoriesDuringScan: false,
|
||||
isContentOnSsd: false,
|
||||
_libraryConsumptionSettingsFixture.Create(),
|
||||
LibraryPathTemplate.Empty(),
|
||||
[]);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Lumina.Domain.Common.Errors.Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Save_WhenCalled_ShouldRaiseLibrarySavedDomainEvent()
|
||||
{
|
||||
// Arrange
|
||||
Library library = _libraryFixture.Create();
|
||||
|
||||
// Act
|
||||
library.Save();
|
||||
|
||||
// Assert
|
||||
List<IDomainEvent> domainEvents = library.GetDomainEvents();
|
||||
LibrarySavedDomainEvent savedEvent = Assert.IsType<LibrarySavedDomainEvent>(Assert.Single(domainEvents));
|
||||
Assert.Equal(library, savedEvent.Library);
|
||||
Assert.NotEqual(default, savedEvent.Id);
|
||||
Assert.NotEqual(default, savedEvent.OccurredOnUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Delete_WhenCalled_ShouldRaiseLibraryDeletedDomainEvent()
|
||||
{
|
||||
// Arrange
|
||||
Library library = _libraryFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = library.Delete();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Deleted, result.Value);
|
||||
List<IDomainEvent> domainEvents = library.GetDomainEvents();
|
||||
LibraryDeletedDomainEvent deletedEvent = Assert.IsType<LibraryDeletedDomainEvent>(Assert.Single(domainEvents));
|
||||
Assert.Equal(library, deletedEvent.Library);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Delete_WhenCalledAfterSave_ShouldClearPreviousEventsAndRaiseOnlyDeletedEvent()
|
||||
{
|
||||
// Arrange
|
||||
Library library = _libraryFixture.Create();
|
||||
library.Save();
|
||||
|
||||
// Act
|
||||
library.Delete();
|
||||
|
||||
// Assert
|
||||
List<IDomainEvent> domainEvents = library.GetDomainEvents();
|
||||
Assert.Single(domainEvents);
|
||||
Assert.IsType<LibraryDeletedDomainEvent>(domainEvents[0]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Delete_WhenCalledMultipleTimes_ShouldRaiseOnlyOneDeletedEvent()
|
||||
{
|
||||
// Arrange
|
||||
Library library = _libraryFixture.Create();
|
||||
|
||||
// Act
|
||||
library.Delete();
|
||||
library.Delete();
|
||||
|
||||
// Assert
|
||||
List<IDomainEvent> domainEvents = library.GetDomainEvents();
|
||||
Assert.Single(domainEvents);
|
||||
Assert.IsType<LibraryDeletedDomainEvent>(domainEvents[0]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SetInternalLibraryCoverImagePath_WhenCalled_ShouldUpdateCoverImage()
|
||||
{
|
||||
// Arrange
|
||||
Library library = _libraryFixture.Create();
|
||||
string internalPath = "C:/Internal/Covers/cover.jpg";
|
||||
|
||||
// Act
|
||||
library.SetInternalLibraryCoverImagePath(internalPath);
|
||||
|
||||
// Assert
|
||||
Assert.True(library.CoverImage.HasValue);
|
||||
Assert.Equal(internalPath, library.CoverImage.Value);
|
||||
}
|
||||
}
|
||||
+296
@@ -0,0 +1,296 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="LibraryConsumptionSettings"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LibraryConsumptionSettingsTests
|
||||
{
|
||||
private readonly LibraryConsumptionSettingsFixture _libraryConsumptionSettingsFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenProgressTrackingIsEnabledAndThresholdIsSupplied_ShouldRetainThreshold()
|
||||
{
|
||||
// Act
|
||||
LibraryConsumptionSettings settings = _libraryConsumptionSettingsFixture.Create(
|
||||
shouldTrackConsumptionProgress: true,
|
||||
completionThresholdPercentage: 65);
|
||||
|
||||
// Assert
|
||||
Assert.True(settings.ShouldTrackConsumptionProgress);
|
||||
Assert.True(settings.CompletionThresholdPercentage.HasValue);
|
||||
Assert.Equal(65, settings.CompletionThresholdPercentage.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenProgressTrackingIsEnabledAndThresholdIsAbsent_ShouldHaveNoThreshold()
|
||||
{
|
||||
// Act
|
||||
LibraryConsumptionSettings settings = _libraryConsumptionSettingsFixture.Create(
|
||||
shouldTrackConsumptionProgress: true,
|
||||
includeCompletionThreshold: false);
|
||||
|
||||
// Assert
|
||||
Assert.True(settings.ShouldTrackConsumptionProgress);
|
||||
Assert.False(settings.CompletionThresholdPercentage.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenProgressTrackingIsDisabledAndThresholdIsSupplied_ShouldNotRetainThreshold()
|
||||
{
|
||||
// Act
|
||||
LibraryConsumptionSettings settings = _libraryConsumptionSettingsFixture.Create(
|
||||
shouldTrackConsumptionProgress: false,
|
||||
completionThresholdPercentage: 65);
|
||||
|
||||
// Assert
|
||||
Assert.False(settings.ShouldTrackConsumptionProgress);
|
||||
Assert.False(settings.CompletionThresholdPercentage.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenProgressTrackingIsDisabledAndThresholdIsAbsent_ShouldHaveNoThreshold()
|
||||
{
|
||||
// Act
|
||||
LibraryConsumptionSettings settings = _libraryConsumptionSettingsFixture.Create(
|
||||
shouldTrackConsumptionProgress: false,
|
||||
includeCompletionThreshold: false);
|
||||
|
||||
// Assert
|
||||
Assert.False(settings.ShouldTrackConsumptionProgress);
|
||||
Assert.False(settings.CompletionThresholdPercentage.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WhenSettingsHaveSameValues_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
LibraryConsumptionSettings firstSettings = _libraryConsumptionSettingsFixture.Create(
|
||||
shouldTrackConsumptionProgress: true,
|
||||
completionThresholdPercentage: 65);
|
||||
LibraryConsumptionSettings secondSettings = _libraryConsumptionSettingsFixture.Create(
|
||||
shouldTrackConsumptionProgress: true,
|
||||
completionThresholdPercentage: 65);
|
||||
|
||||
// Act
|
||||
bool areEqual = firstSettings.Equals(secondSettings);
|
||||
|
||||
// Assert
|
||||
Assert.True(areEqual);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WhenProgressTrackingDiffers_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
LibraryConsumptionSettings trackingSettings = _libraryConsumptionSettingsFixture.Create(
|
||||
shouldTrackConsumptionProgress: true,
|
||||
completionThresholdPercentage: 65);
|
||||
LibraryConsumptionSettings notTrackingSettings = _libraryConsumptionSettingsFixture.Create(
|
||||
shouldTrackConsumptionProgress: false,
|
||||
completionThresholdPercentage: 65);
|
||||
|
||||
// Act
|
||||
bool areEqual = trackingSettings.Equals(notTrackingSettings);
|
||||
|
||||
// Assert
|
||||
Assert.False(areEqual);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WhenThresholdsDiffer_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
LibraryConsumptionSettings firstSettings = _libraryConsumptionSettingsFixture.Create(
|
||||
shouldTrackConsumptionProgress: true,
|
||||
completionThresholdPercentage: 40);
|
||||
LibraryConsumptionSettings secondSettings = _libraryConsumptionSettingsFixture.Create(
|
||||
shouldTrackConsumptionProgress: true,
|
||||
completionThresholdPercentage: 60);
|
||||
|
||||
// Act
|
||||
bool areEqual = firstSettings.Equals(secondSettings);
|
||||
|
||||
// Assert
|
||||
Assert.False(areEqual);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WhenProgressTrackingIsDisabled_ShouldIgnoreAnySuppliedThreshold()
|
||||
{
|
||||
// Arrange
|
||||
LibraryConsumptionSettings settingsWithThreshold = _libraryConsumptionSettingsFixture.Create(
|
||||
shouldTrackConsumptionProgress: false,
|
||||
completionThresholdPercentage: 40);
|
||||
LibraryConsumptionSettings settingsWithoutThreshold = _libraryConsumptionSettingsFixture.Create(
|
||||
shouldTrackConsumptionProgress: false,
|
||||
includeCompletionThreshold: false);
|
||||
|
||||
// Act
|
||||
bool areEqual = settingsWithThreshold.Equals(settingsWithoutThreshold);
|
||||
|
||||
// Assert
|
||||
Assert.False(settingsWithThreshold.CompletionThresholdPercentage.HasValue);
|
||||
Assert.False(settingsWithoutThreshold.CompletionThresholdPercentage.HasValue);
|
||||
Assert.True(areEqual);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WhenComparedWithNull_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
LibraryConsumptionSettings settings = _libraryConsumptionSettingsFixture.Create(
|
||||
shouldTrackConsumptionProgress: true,
|
||||
completionThresholdPercentage: 65);
|
||||
|
||||
// Act
|
||||
bool areEqual = settings.Equals((object?)null);
|
||||
|
||||
// Assert
|
||||
Assert.False(areEqual);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetHashCode_WhenSettingsAreEqual_ShouldReturnSameHashCode()
|
||||
{
|
||||
// Arrange
|
||||
LibraryConsumptionSettings firstSettings = _libraryConsumptionSettingsFixture.Create(
|
||||
shouldTrackConsumptionProgress: true,
|
||||
completionThresholdPercentage: 65);
|
||||
LibraryConsumptionSettings secondSettings = _libraryConsumptionSettingsFixture.Create(
|
||||
shouldTrackConsumptionProgress: true,
|
||||
completionThresholdPercentage: 65);
|
||||
|
||||
// Act
|
||||
int firstHashCode = firstSettings.GetHashCode();
|
||||
int secondHashCode = secondSettings.GetHashCode();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(firstHashCode, secondHashCode);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(LibraryType.Book, true, 100)] // Written content.
|
||||
[InlineData(LibraryType.EBook, true, 100)] // Written content.
|
||||
[InlineData(LibraryType.ComicBook, true, 100)] // Written content.
|
||||
[InlineData(LibraryType.Magazine, true, 100)] // Written content.
|
||||
[InlineData(LibraryType.Newspaper, true, 100)] // Written content.
|
||||
[InlineData(LibraryType.Manga, true, 100)] // Written content.
|
||||
[InlineData(LibraryType.GraphicNovel, true, 100)] // Written content.
|
||||
[InlineData(LibraryType.AcademicPaper, true, 100)] // Written content.
|
||||
[InlineData(LibraryType.SheetMusic, true, 100)] // Written content.
|
||||
[InlineData(LibraryType.TvShow, true, 90)] // Video.
|
||||
[InlineData(LibraryType.Movie, true, 90)] // Video.
|
||||
[InlineData(LibraryType.Documentary, true, 90)] // Video.
|
||||
[InlineData(LibraryType.Anime, true, 90)] // Video.
|
||||
[InlineData(LibraryType.ConcertVideo, true, 90)] // Video.
|
||||
[InlineData(LibraryType.TutorialVideo, true, 90)] // Video.
|
||||
[InlineData(LibraryType.HomeVideo, true, 90)] // Video.
|
||||
[InlineData(LibraryType.YouTubeVideo, true, 90)] // Video.
|
||||
[InlineData(LibraryType.MusicVideo, true, 90)] // Video.
|
||||
[InlineData(LibraryType.LiveRecordingVideo, true, 90)] // Video.
|
||||
[InlineData(LibraryType.InterviewVideo, true, 90)] // Video.
|
||||
[InlineData(LibraryType.CoverSongVideo, true, 90)] // Video.
|
||||
[InlineData(LibraryType.Audiobook, true, 95)] // Audiobooks and podcasts.
|
||||
[InlineData(LibraryType.PodcastAudio, true, 95)] // Audiobooks and podcasts.
|
||||
[InlineData(LibraryType.PodcastVideo, true, 95)] // Audiobooks and podcasts.
|
||||
[InlineData(LibraryType.Music, false, null)] // Music audio and photos.
|
||||
[InlineData(LibraryType.Remix, false, null)] // Music audio and photos.
|
||||
[InlineData(LibraryType.SoundEffect, false, null)] // Music audio and photos.
|
||||
[InlineData(LibraryType.LiveRecordingAudio, false, null)] // Music audio and photos.
|
||||
[InlineData(LibraryType.InterviewAudio, false, null)] // Music audio and photos.
|
||||
[InlineData(LibraryType.CoverSongAudio, false, null)] // Music audio and photos.
|
||||
[InlineData(LibraryType.Photo, false, null)] // Music audio and photos.
|
||||
[InlineData(LibraryType.Playlist, false, null)] // Library types that are not media libraries.
|
||||
[InlineData(LibraryType.Collection, false, null)] // Library types that are not media libraries.
|
||||
[InlineData(LibraryType.Subtitles, false, null)] // Library types that are not media libraries.
|
||||
[InlineData(LibraryType.Lyrics, false, null)] // Library types that are not media libraries.
|
||||
[InlineData(LibraryType.Other, false, null)] // Library types that are not media libraries.
|
||||
public void CreateDefault_WhenLibraryTypeIsKnown_ShouldReturnTheTypeDefaults(
|
||||
LibraryType libraryType,
|
||||
bool expectedShouldTrackConsumptionProgress,
|
||||
int? expectedCompletionThresholdPercentage)
|
||||
{
|
||||
// Act
|
||||
LibraryConsumptionSettings settings = LibraryConsumptionSettings.CreateDefault(libraryType);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(expectedShouldTrackConsumptionProgress, settings.ShouldTrackConsumptionProgress);
|
||||
if (expectedCompletionThresholdPercentage is null)
|
||||
Assert.False(settings.CompletionThresholdPercentage.HasValue);
|
||||
else
|
||||
{
|
||||
Assert.True(settings.CompletionThresholdPercentage.HasValue);
|
||||
Assert.Equal(expectedCompletionThresholdPercentage.Value, settings.CompletionThresholdPercentage.Value);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateDefault_WhenLibraryTypeIsNotClassified_ShouldReturnTrackingOffWithoutThreshold()
|
||||
{
|
||||
// Act
|
||||
LibraryConsumptionSettings settings = LibraryConsumptionSettings.CreateDefault((LibraryType)999);
|
||||
|
||||
// Assert
|
||||
Assert.False(settings.ShouldTrackConsumptionProgress);
|
||||
Assert.False(settings.CompletionThresholdPercentage.HasValue);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(MediaKind.None, false, null)] // No media kind.
|
||||
[InlineData(MediaKind.MusicTrack, false, null)] // Music tracks.
|
||||
[InlineData(MediaKind.PodcastEpisode, true, 95)] // Audiobooks and podcast episodes.
|
||||
[InlineData(MediaKind.Audiobook, true, 95)] // Audiobooks and podcast episodes.
|
||||
[InlineData(MediaKind.Movie, true, 90)] // Video.
|
||||
[InlineData(MediaKind.TvEpisode, true, 90)] // Video.
|
||||
[InlineData(MediaKind.Book, true, 100)] // Written content.
|
||||
[InlineData(MediaKind.Photo, false, null)] // Photos.
|
||||
[InlineData(MediaKind.Video, true, 90)] // Video.
|
||||
public void CreateDefault_WhenMediaKindIsKnown_ShouldReturnTheKindDefaults(
|
||||
MediaKind mediaKind,
|
||||
bool expectedShouldTrackConsumptionProgress,
|
||||
int? expectedCompletionThresholdPercentage)
|
||||
{
|
||||
// Act
|
||||
LibraryConsumptionSettings settings = LibraryConsumptionSettings.CreateDefault(mediaKind);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(expectedShouldTrackConsumptionProgress, settings.ShouldTrackConsumptionProgress);
|
||||
if (expectedCompletionThresholdPercentage is null)
|
||||
Assert.False(settings.CompletionThresholdPercentage.HasValue);
|
||||
else
|
||||
{
|
||||
Assert.True(settings.CompletionThresholdPercentage.HasValue);
|
||||
Assert.Equal(expectedCompletionThresholdPercentage.Value, settings.CompletionThresholdPercentage.Value);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateDefault_WhenMediaKindIsNotClassified_ShouldReturnTrackingOffWithoutThreshold()
|
||||
{
|
||||
// Act
|
||||
LibraryConsumptionSettings settings = LibraryConsumptionSettings.CreateDefault((MediaKind)999);
|
||||
|
||||
// Assert
|
||||
Assert.False(settings.ShouldTrackConsumptionProgress);
|
||||
Assert.False(settings.CompletionThresholdPercentage.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateDefault_WhenReturnedSettingsAreTrackingOff_ShouldNotRetainAThreshold()
|
||||
{
|
||||
// Act
|
||||
LibraryConsumptionSettings settings = LibraryConsumptionSettings.CreateDefault(LibraryType.Music);
|
||||
|
||||
// Assert
|
||||
Assert.False(settings.ShouldTrackConsumptionProgress);
|
||||
Assert.False(settings.CompletionThresholdPercentage.HasValue);
|
||||
}
|
||||
}
|
||||
+155
@@ -0,0 +1,155 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="LibraryPathPart"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LibraryPathPartTests
|
||||
{
|
||||
private readonly LibraryPathPartFixture _libraryPathPartFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenKindIsSeparator_ShouldCreateSeparatorWithoutRepresentation()
|
||||
{
|
||||
// Act
|
||||
Result<LibraryPathPart> result = LibraryPathPart.Create(LibraryPathPartKind.Separator, "/", isOptional: false);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(LibraryPathPartKind.Separator, result.Value.Kind);
|
||||
Assert.Equal(string.Empty, result.Value.Representation);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenKindIsLiteralWithText_ShouldCreateLiteralWithThatRepresentation()
|
||||
{
|
||||
// Act
|
||||
Result<LibraryPathPart> result = LibraryPathPart.Create(LibraryPathPartKind.Literal, " - ", isOptional: false);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(LibraryPathPartKind.Literal, result.Value.Kind);
|
||||
Assert.Equal(" - ", result.Value.Representation);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // The representation is absent.
|
||||
[InlineData("")] // The representation is empty.
|
||||
[InlineData(" ")] // The representation is whitespace.
|
||||
public void Create_WhenKindIsNotSeparatorAndRepresentationIsEmpty_ShouldReturnLiteralCannotBeEmptyError(string? representation)
|
||||
{
|
||||
// Act
|
||||
Result<LibraryPathPart> result = LibraryPathPart.Create(LibraryPathPartKind.Literal, representation, isOptional: false);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Lumina.Domain.Common.Errors.Errors.Library.PathTemplateLiteralCannotBeEmpty, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenTypedPartContainsSinglePlaceholder_ShouldCreateThePart()
|
||||
{
|
||||
// Act
|
||||
Result<LibraryPathPart> result = LibraryPathPart.Create(LibraryPathPartKind.Artist, "{0}", isOptional: false);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal("{0}", result.Value.Representation);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenTypedPartContainsFixedWidthPlaceholder_ShouldCreateThePart()
|
||||
{
|
||||
// Act
|
||||
Result<LibraryPathPart> result = LibraryPathPart.Create(LibraryPathPartKind.TrackNumber, "Disc {0:00}", isOptional: true);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal("Disc {0:00}", result.Value.Representation);
|
||||
Assert.True(result.Value.IsOptional);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("no placeholder")] // The mask carries no value placeholder.
|
||||
[InlineData("{0} {0}")] // The mask carries more than one value placeholder.
|
||||
public void Create_WhenTypedPartDoesNotContainExactlyOnePlaceholder_ShouldReturnError(string representation)
|
||||
{
|
||||
// Act
|
||||
Result<LibraryPathPart> result = LibraryPathPart.Create(LibraryPathPartKind.Artist, representation, isOptional: false);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Lumina.Domain.Common.Errors.Errors.Library.PathTemplateValuePartMustContainSinglePlaceholder, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenLiteralContainsNoPlaceholder_ShouldCreateThePart()
|
||||
{
|
||||
// Act
|
||||
Result<LibraryPathPart> result = LibraryPathPart.Create(LibraryPathPartKind.Literal, "Disk ", isOptional: false);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal("Disk ", result.Value.Representation);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithSameValues_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
LibraryPathPart firstPart = _libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: true);
|
||||
|
||||
// Act
|
||||
LibraryPathPart secondPart = _libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: true);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(firstPart, secondPart);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentKind_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
LibraryPathPart firstPart = _libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: false);
|
||||
|
||||
// Act
|
||||
LibraryPathPart secondPart = _libraryPathPartFixture.Create(kind: LibraryPathPartKind.ReleaseName, representation: "{0}", isOptional: false);
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstPart, secondPart);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentRepresentation_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
LibraryPathPart firstPart = _libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: false);
|
||||
|
||||
// Act
|
||||
LibraryPathPart secondPart = _libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "Artist: {0}", isOptional: false);
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstPart, secondPart);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentIsOptional_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
LibraryPathPart firstPart = _libraryPathPartFixture.Create(kind: LibraryPathPartKind.DiscNumber, representation: "{0:00}", isOptional: false);
|
||||
|
||||
// Act
|
||||
LibraryPathPart secondPart = _libraryPathPartFixture.Create(kind: LibraryPathPartKind.DiscNumber, representation: "{0:00}", isOptional: true);
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstPart, secondPart);
|
||||
}
|
||||
}
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="LibraryPathTemplate"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LibraryPathTemplateTests
|
||||
{
|
||||
private readonly LibraryPathTemplateFixture _libraryPathTemplateFixture = new();
|
||||
private readonly LibraryPathPartFixture _libraryPathPartFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithParts_ShouldCreateTemplateWithThoseParts()
|
||||
{
|
||||
// Arrange
|
||||
LibraryPathTemplate template = _libraryPathTemplateFixture.Create();
|
||||
|
||||
// Act
|
||||
LibraryPathTemplate result = LibraryPathTemplate.Create(template.Parts);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(template.Parts, result.Parts);
|
||||
Assert.False(result.IsEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Empty_WhenCalled_ShouldCreateTemplateWithoutParts()
|
||||
{
|
||||
// Act
|
||||
LibraryPathTemplate result = LibraryPathTemplate.Empty();
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result.Parts);
|
||||
Assert.True(result.IsEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenSourceCollectionIsLaterModified_ShouldNotAffectTheTemplate()
|
||||
{
|
||||
// Arrange
|
||||
List<LibraryPathPart> sourceParts = [.. _libraryPathTemplateFixture.Create().Parts];
|
||||
int originalCount = sourceParts.Count;
|
||||
|
||||
// Act
|
||||
LibraryPathTemplate template = LibraryPathTemplate.Create(sourceParts);
|
||||
sourceParts.Clear();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(originalCount, template.Parts.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithSameValues_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
LibraryPathTemplate firstTemplate = _libraryPathTemplateFixture.Create();
|
||||
|
||||
// Act
|
||||
LibraryPathTemplate secondTemplate = LibraryPathTemplate.Create(firstTemplate.Parts);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(firstTemplate, secondTemplate);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentParts_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
LibraryPathTemplate firstTemplate = _libraryPathTemplateFixture.Create();
|
||||
|
||||
// Act
|
||||
// The second template extends the first one, because two random templates can be identical (a single typed part of the same kind).
|
||||
LibraryPathTemplate secondTemplate = LibraryPathTemplate.Create([.. firstTemplate.Parts, _libraryPathPartFixture.Create()]);
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstTemplate, secondTemplate);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WhenBothTemplatesAreEmpty_ShouldReturnTrue()
|
||||
{
|
||||
// Act
|
||||
LibraryPathTemplate firstTemplate = LibraryPathTemplate.Empty();
|
||||
LibraryPathTemplate secondTemplate = LibraryPathTemplate.Empty();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(firstTemplate, secondTemplate);
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="LibraryMediaItemDeletedDomainEvent"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LibraryMediaItemDeletedDomainEventTests
|
||||
{
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new();
|
||||
private readonly LibraryMediaItemDeletedDomainEventFixture _libraryMediaItemDeletedDomainEventFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenCalled_ShouldSetAllProperties()
|
||||
{
|
||||
// Arrange
|
||||
Guid id = Guid.NewGuid();
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
string path = "C:/Media/Books/old-book.pdf";
|
||||
DateTime occurredOnUtc = DateTime.UtcNow;
|
||||
|
||||
// Act
|
||||
LibraryMediaItemDeletedDomainEvent domainEvent = _libraryMediaItemDeletedDomainEventFixture.Create(id, libraryId, compositeId, path, occurredOnUtc);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(id, domainEvent.Id);
|
||||
Assert.Equal(libraryId, domainEvent.LibraryId);
|
||||
Assert.Equal(compositeId, domainEvent.MediaLibraryScanCompositeId);
|
||||
Assert.Equal(path, domainEvent.Path);
|
||||
Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc);
|
||||
Assert.IsAssignableFrom<IDomainEvent>(domainEvent);
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="LibraryScanCancelledDomainEvent"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LibraryScanCancelledDomainEventTests
|
||||
{
|
||||
private readonly ScanIdFixture _scanIdFixture = new();
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly LibraryScanCancelledDomainEventFixture _libraryScanCancelledDomainEventFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenCalled_ShouldSetAllProperties()
|
||||
{
|
||||
// Arrange
|
||||
Guid id = Guid.NewGuid();
|
||||
ScanId scanId = _scanIdFixture.Create();
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
DateTime occurredOnUtc = DateTime.UtcNow;
|
||||
|
||||
// Act
|
||||
LibraryScanCancelledDomainEvent domainEvent = _libraryScanCancelledDomainEventFixture.Create(id, scanId, libraryId, occurredOnUtc);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(id, domainEvent.Id);
|
||||
Assert.Equal(scanId, domainEvent.ScanId);
|
||||
Assert.Equal(libraryId, domainEvent.LibraryId);
|
||||
Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc);
|
||||
Assert.IsAssignableFrom<IDomainEvent>(domainEvent);
|
||||
}
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="LibraryScanFailedDomainEvent"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LibraryScanFailedDomainEventTests
|
||||
{
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new();
|
||||
private readonly LibraryScanFailedDomainEventFixture _libraryScanFailedDomainEventFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenCalledWithErrorMessage_ShouldSetAllProperties()
|
||||
{
|
||||
// Arrange
|
||||
Guid id = Guid.NewGuid();
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
DateTime occurredOnUtc = DateTime.UtcNow;
|
||||
string errorMessage = "Scan failed unexpectedly.";
|
||||
|
||||
// Act
|
||||
LibraryScanFailedDomainEvent domainEvent = _libraryScanFailedDomainEventFixture.Create(
|
||||
id: id,
|
||||
libraryId: libraryId,
|
||||
mediaLibraryScanCompositeId: compositeId,
|
||||
occurredOnUtc: occurredOnUtc,
|
||||
errorMessage: errorMessage);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(id, domainEvent.Id);
|
||||
Assert.Equal(libraryId, domainEvent.LibraryId);
|
||||
Assert.Equal(compositeId, domainEvent.MediaLibraryScanCompositeId);
|
||||
Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc);
|
||||
Assert.True(domainEvent.ErrorMessage.HasValue);
|
||||
Assert.Equal(errorMessage, domainEvent.ErrorMessage.Value);
|
||||
Assert.IsType<IDomainEvent>(domainEvent, exactMatch: false);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenCalledWithoutErrorMessage_ShouldLeaveErrorMessageUnset()
|
||||
{
|
||||
// Act
|
||||
LibraryScanFailedDomainEvent domainEvent = _libraryScanFailedDomainEventFixture.Create(includeErrorMessage: false);
|
||||
|
||||
// Assert
|
||||
Assert.False(domainEvent.ErrorMessage.HasValue);
|
||||
Assert.IsType<IDomainEvent>(domainEvent, exactMatch: false);
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="LibraryScanFinishedDomainEvent"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LibraryScanFinishedDomainEventTests
|
||||
{
|
||||
private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new();
|
||||
private readonly LibraryScanFinishedDomainEventFixture _libraryScanFinishedDomainEventFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenCalled_ShouldSetAllProperties()
|
||||
{
|
||||
// Arrange
|
||||
Guid id = Guid.NewGuid();
|
||||
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
DateTime occurredOnUtc = DateTime.UtcNow;
|
||||
|
||||
// Act
|
||||
LibraryScanFinishedDomainEvent domainEvent = _libraryScanFinishedDomainEventFixture.Create(id, compositeId, occurredOnUtc);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(id, domainEvent.Id);
|
||||
Assert.Equal(compositeId, domainEvent.MediaLibraryScanCompositeId);
|
||||
Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc);
|
||||
Assert.IsType<IDomainEvent>(domainEvent, exactMatch: false);
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="LibraryScanJobProgressChangedDomainEvent"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LibraryScanJobProgressChangedDomainEventTests
|
||||
{
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new();
|
||||
private readonly MediaLibraryScanJobProgressFixture _mediaLibraryScanJobProgressFixture = new();
|
||||
private readonly LibraryScanJobProgressChangedDomainEventFixture _libraryScanJobProgressChangedDomainEventFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenCalled_ShouldSetAllProperties()
|
||||
{
|
||||
// Arrange
|
||||
Guid id = Guid.NewGuid();
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
MediaLibraryScanJobProgress progress = _mediaLibraryScanJobProgressFixture.Create();
|
||||
DateTime occurredOnUtc = DateTime.UtcNow;
|
||||
|
||||
// Act
|
||||
LibraryScanJobProgressChangedDomainEvent domainEvent = _libraryScanJobProgressChangedDomainEventFixture.Create(id, libraryId, compositeId, progress, occurredOnUtc);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(id, domainEvent.Id);
|
||||
Assert.Equal(libraryId, domainEvent.LibraryId);
|
||||
Assert.Equal(compositeId, domainEvent.MediaLibraryScanCompositeId);
|
||||
Assert.Equal(progress, domainEvent.Progress);
|
||||
Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc);
|
||||
Assert.IsType<IDomainEvent>(domainEvent, exactMatch: false);
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="LibraryScanProgressChangedDomainEvent"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LibraryScanProgressChangedDomainEventTests
|
||||
{
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new();
|
||||
private readonly LibraryScanProgressChangedDomainEventFixture _libraryScanProgressChangedDomainEventFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenCalled_ShouldSetAllProperties()
|
||||
{
|
||||
// Arrange
|
||||
Guid id = Guid.NewGuid();
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
DateTime occurredOnUtc = DateTime.UtcNow;
|
||||
|
||||
// Act
|
||||
LibraryScanProgressChangedDomainEvent domainEvent = _libraryScanProgressChangedDomainEventFixture.Create(id, libraryId, compositeId, occurredOnUtc);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(id, domainEvent.Id);
|
||||
Assert.Equal(libraryId, domainEvent.LibraryId);
|
||||
Assert.Equal(compositeId, domainEvent.MediaLibraryScanCompositeId);
|
||||
Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc);
|
||||
Assert.IsType<IDomainEvent>(domainEvent, exactMatch: false);
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="LibraryScanQueuedDomainEvent"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LibraryScanQueuedDomainEventTests
|
||||
{
|
||||
private readonly ScanIdFixture _scanIdFixture = new();
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly LibraryScanQueuedDomainEventFixture _libraryScanQueuedDomainEventFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenCalled_ShouldSetAllProperties()
|
||||
{
|
||||
// Arrange
|
||||
Guid id = Guid.NewGuid();
|
||||
ScanId scanId = _scanIdFixture.Create();
|
||||
UserId userId = _userIdFixture.Create();
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
DateTime occurredOnUtc = DateTime.UtcNow;
|
||||
|
||||
// Act
|
||||
LibraryScanQueuedDomainEvent domainEvent = _libraryScanQueuedDomainEventFixture.Create(id, scanId, userId, libraryId, occurredOnUtc);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(id, domainEvent.Id);
|
||||
Assert.Equal(scanId, domainEvent.ScanId);
|
||||
Assert.Equal(userId, domainEvent.UserId);
|
||||
Assert.Equal(libraryId, domainEvent.LibraryId);
|
||||
Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc);
|
||||
Assert.IsType<IDomainEvent>(domainEvent, exactMatch: false);
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="LibraryScanStartedDomainEvent"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LibraryScanStartedDomainEventTests
|
||||
{
|
||||
private readonly LibraryScanFixture _libraryScanFixture = new();
|
||||
private readonly LibraryScanStartedDomainEventFixture _libraryScanStartedDomainEventFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenCalled_ShouldSetAllProperties()
|
||||
{
|
||||
// Arrange
|
||||
Guid id = Guid.NewGuid();
|
||||
LibraryScan scan = _libraryScanFixture.Create();
|
||||
DateTime occurredOnUtc = DateTime.UtcNow;
|
||||
|
||||
// Act
|
||||
LibraryScanStartedDomainEvent domainEvent = _libraryScanStartedDomainEventFixture.Create(id, scan, occurredOnUtc);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(id, domainEvent.Id);
|
||||
Assert.Equal(scan, domainEvent.LibraryScan);
|
||||
Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc);
|
||||
Assert.IsType<IDomainEvent>(domainEvent, exactMatch: false);
|
||||
}
|
||||
}
|
||||
+295
@@ -0,0 +1,295 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="LibraryScan"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LibraryScanTests
|
||||
{
|
||||
private readonly LibraryScanFixture _libraryScanFixture = new();
|
||||
private readonly ScanIdFixture _scanIdFixture = new();
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithValidData_ShouldCreateScanWithPendingStatus()
|
||||
{
|
||||
// Arrange
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
UserId userId = _userIdFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<LibraryScan> result = LibraryScan.Create(libraryId, userId, []);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(libraryId, result.Value.LibraryId);
|
||||
Assert.Equal(userId, result.Value.UserId);
|
||||
Assert.Equal(LibraryScanJobStatus.Pending, result.Value.Status);
|
||||
Assert.NotEqual(default, result.Value.Id.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithPreExistingIdAndStatus_ShouldCreateScanWithThoseValues()
|
||||
{
|
||||
// Arrange
|
||||
Guid id = Guid.NewGuid();
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
UserId userId = _userIdFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<LibraryScan> result = LibraryScan.Create(_scanIdFixture.Create(id), libraryId, userId, LibraryScanJobStatus.Running, []);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(id, result.Value.Id.Value);
|
||||
Assert.Equal(libraryId, result.Value.LibraryId);
|
||||
Assert.Equal(userId, result.Value.UserId);
|
||||
Assert.Equal(LibraryScanJobStatus.Running, result.Value.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledTwice_ShouldGenerateDistinctIds()
|
||||
{
|
||||
// Act
|
||||
Result<LibraryScan> firstResult = LibraryScan.Create(_libraryIdFixture.Create(), _userIdFixture.Create(), []);
|
||||
Result<LibraryScan> secondResult = LibraryScan.Create(_libraryIdFixture.Create(), _userIdFixture.Create(), []);
|
||||
|
||||
// Assert
|
||||
Assert.False(firstResult.IsFailure);
|
||||
Assert.False(secondResult.IsFailure);
|
||||
Assert.NotEqual(firstResult.Value.Id.Value, secondResult.Value.Id.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void QueueScan_WhenNoActivePastScanExists_ShouldSucceedAndRaiseQueuedEvent()
|
||||
{
|
||||
// Arrange
|
||||
LibraryScan scan = _libraryScanFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Success> result = scan.QueueScan();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Success, result.Value);
|
||||
Assert.Equal(LibraryScanJobStatus.Pending, scan.Status);
|
||||
LibraryScanQueuedDomainEvent queuedEvent = Assert.IsType<LibraryScanQueuedDomainEvent>(Assert.Single(scan.GetDomainEvents()));
|
||||
Assert.Equal(scan.Id, queuedEvent.ScanId);
|
||||
Assert.Equal(scan.UserId, queuedEvent.UserId);
|
||||
Assert.Equal(scan.LibraryId, queuedEvent.LibraryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void QueueScan_WhenPastScanIsRunning_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
LibraryScan pastScan = _libraryScanFixture.Create(status: LibraryScanJobStatus.Running);
|
||||
LibraryScan scan = _libraryScanFixture.Create(pastScans: [pastScan]);
|
||||
|
||||
// Act
|
||||
Result<Success> result = scan.QueueScan();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.LibraryScanning.LibraryAlreadyBeingScanned, result.FirstError);
|
||||
Assert.Empty(scan.GetDomainEvents());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void QueueScan_WhenPastScanIsPending_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
LibraryScan pastScan = _libraryScanFixture.Create(status: LibraryScanJobStatus.Pending);
|
||||
LibraryScan scan = _libraryScanFixture.Create(pastScans: [pastScan]);
|
||||
|
||||
// Act
|
||||
Result<Success> result = scan.QueueScan();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.LibraryScanning.LibraryAlreadyBeingScanned, result.FirstError);
|
||||
Assert.Empty(scan.GetDomainEvents());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void StartScan_WhenPending_ShouldTransitionToRunningAndRaiseStartedEvent()
|
||||
{
|
||||
// Arrange
|
||||
LibraryScan scan = _libraryScanFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Success> result = scan.StartScan();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Success, result.Value);
|
||||
Assert.Equal(LibraryScanJobStatus.Running, scan.Status);
|
||||
LibraryScanStartedDomainEvent startedEvent = Assert.IsType<LibraryScanStartedDomainEvent>(Assert.Single(scan.GetDomainEvents()));
|
||||
Assert.Equal(scan, startedEvent.LibraryScan);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(LibraryScanJobStatus.Running)] // Cannot start an already running scan.
|
||||
[InlineData(LibraryScanJobStatus.Completed)] // Cannot start a completed scan.
|
||||
[InlineData(LibraryScanJobStatus.Canceled)] // Cannot start a canceled scan.
|
||||
[InlineData(LibraryScanJobStatus.Failed)] // Cannot start a failed scan.
|
||||
public void StartScan_WhenNotPending_ShouldReturnError(LibraryScanJobStatus status)
|
||||
{
|
||||
// Arrange
|
||||
LibraryScan scan = _libraryScanFixture.Create(status: status);
|
||||
|
||||
// Act
|
||||
Result<Success> result = scan.StartScan();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.LibraryScanning.CanOnlyStartPendingScans, result.FirstError);
|
||||
Assert.Equal(status, scan.Status);
|
||||
Assert.Empty(scan.GetDomainEvents());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void StartScan_WhenPastScanIsActive_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
LibraryScan pastScan = _libraryScanFixture.Create(status: LibraryScanJobStatus.Running);
|
||||
LibraryScan scan = _libraryScanFixture.Create(pastScans: [pastScan]);
|
||||
|
||||
// Act
|
||||
Result<Success> result = scan.StartScan();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.LibraryScanning.LibraryAlreadyBeingScanned, result.FirstError);
|
||||
Assert.Empty(scan.GetDomainEvents());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FinishScan_WhenRunning_ShouldTransitionToCompleted()
|
||||
{
|
||||
// Arrange
|
||||
LibraryScan scan = _libraryScanFixture.Create(status: LibraryScanJobStatus.Running);
|
||||
|
||||
// Act
|
||||
Result<Success> result = scan.FinishScan();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Success, result.Value);
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, scan.Status);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(LibraryScanJobStatus.Pending)] // Cannot complete a pending scan.
|
||||
[InlineData(LibraryScanJobStatus.Completed)] // Cannot complete an already completed scan.
|
||||
[InlineData(LibraryScanJobStatus.Canceled)] // Cannot complete a canceled scan.
|
||||
[InlineData(LibraryScanJobStatus.Failed)] // Cannot complete a failed scan.
|
||||
public void FinishScan_WhenNotRunning_ShouldReturnError(LibraryScanJobStatus status)
|
||||
{
|
||||
// Arrange
|
||||
LibraryScan scan = _libraryScanFixture.Create(status: status);
|
||||
|
||||
// Act
|
||||
Result<Success> result = scan.FinishScan();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.LibraryScanning.CanOnlyCompleteRunningScans, result.FirstError);
|
||||
Assert.Equal(status, scan.Status);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(LibraryScanJobStatus.Pending)] // A scan waiting in the scan queue can be canceled too.
|
||||
[InlineData(LibraryScanJobStatus.Running)] // A scan that is already executing can be canceled.
|
||||
public void CancelScan_WhenPendingOrRunning_ShouldTransitionToCanceledAndRaiseCancelledEvent(LibraryScanJobStatus status)
|
||||
{
|
||||
// Arrange
|
||||
LibraryScan scan = _libraryScanFixture.Create(status: status);
|
||||
|
||||
// Act
|
||||
Result<Success> result = scan.CancelScan();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Success, result.Value);
|
||||
Assert.Equal(LibraryScanJobStatus.Canceled, scan.Status);
|
||||
LibraryScanCancelledDomainEvent cancelledEvent = Assert.IsType<LibraryScanCancelledDomainEvent>(Assert.Single(scan.GetDomainEvents()));
|
||||
Assert.Equal(scan.Id, cancelledEvent.ScanId);
|
||||
Assert.Equal(scan.LibraryId, cancelledEvent.LibraryId);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(LibraryScanJobStatus.Completed)] // Cannot cancel a completed scan.
|
||||
[InlineData(LibraryScanJobStatus.Canceled)] // Cannot cancel an already canceled scan.
|
||||
[InlineData(LibraryScanJobStatus.Failed)] // Cannot cancel a failed scan.
|
||||
public void CancelScan_WhenInATerminalState_ShouldReturnError(LibraryScanJobStatus status)
|
||||
{
|
||||
// Arrange
|
||||
LibraryScan scan = _libraryScanFixture.Create(status: status);
|
||||
|
||||
// Act
|
||||
Result<Success> result = scan.CancelScan();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.LibraryScanning.CanOnlyCancelPendingOrRunningScans, result.FirstError);
|
||||
Assert.Equal(status, scan.Status);
|
||||
Assert.Empty(scan.GetDomainEvents());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(LibraryScanJobStatus.Pending)] // A scan that has no scanner yet fails before it starts executing.
|
||||
[InlineData(LibraryScanJobStatus.Running)] // A scan that is executing can fail too.
|
||||
public void FailScan_WhenPendingOrRunning_ShouldTransitionToFailed(LibraryScanJobStatus status)
|
||||
{
|
||||
// Arrange
|
||||
LibraryScan scan = _libraryScanFixture.Create(status: status);
|
||||
|
||||
// Act
|
||||
Result<Success> result = scan.FailScan();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Success, result.Value);
|
||||
Assert.Equal(LibraryScanJobStatus.Failed, scan.Status);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(LibraryScanJobStatus.Completed)] // Cannot fail a completed scan.
|
||||
[InlineData(LibraryScanJobStatus.Canceled)] // Cannot fail a canceled scan.
|
||||
[InlineData(LibraryScanJobStatus.Failed)] // Cannot fail an already failed scan.
|
||||
public void FailScan_WhenInATerminalState_ShouldReturnError(LibraryScanJobStatus status)
|
||||
{
|
||||
// Arrange
|
||||
LibraryScan scan = _libraryScanFixture.Create(status: status);
|
||||
|
||||
// Act
|
||||
Result<Success> result = scan.FailScan();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.LibraryScanning.CanOnlyFailPendingOrRunningScans, result.FirstError);
|
||||
Assert.Equal(status, scan.Status);
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaLibraryScanJobFactory"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaLibraryScanJobFactoryTests
|
||||
{
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void CreateJob_WhenJobTypeIsRegistered_ShouldResolveJobAndSetLibraryId()
|
||||
{
|
||||
// Arrange
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
IMediaLibraryScanJob expectedJob = Substitute.For<IMediaLibraryScanJob>();
|
||||
ServiceCollection services = new();
|
||||
services.AddSingleton(expectedJob);
|
||||
using ServiceProvider serviceProvider = services.BuildServiceProvider();
|
||||
MediaLibraryScanJobFactory sut = new(serviceProvider);
|
||||
|
||||
// Act
|
||||
IMediaLibraryScanJob job = sut.CreateJob<IMediaLibraryScanJob>(libraryId);
|
||||
|
||||
// Assert
|
||||
Assert.Same(expectedJob, job);
|
||||
Assert.Equal(libraryId, job.LibraryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateJob_WhenJobTypeIsNotRegistered_ShouldThrowInvalidOperationException()
|
||||
{
|
||||
// Arrange
|
||||
ServiceCollection services = new();
|
||||
using ServiceProvider serviceProvider = services.BuildServiceProvider();
|
||||
MediaLibraryScanJobFactory sut = new(serviceProvider);
|
||||
|
||||
// Act & Assert
|
||||
Assert.Throws<InvalidOperationException>(() => sut.CreateJob<IMediaLibraryScanJob>(_libraryIdFixture.Create()));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateJob_WhenServiceProviderReturnsNull_ShouldThrowInvalidOperationException()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibraryScanJobFactory sut = new(new NullServiceProvider());
|
||||
|
||||
// Act & Assert
|
||||
InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() => sut.CreateJob<IMediaLibraryScanJob>(_libraryIdFixture.Create()));
|
||||
Assert.Contains("IMediaLibraryScanJob", exception.Message);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Test service provider that returns <see langword="null"/> for every requested service.
|
||||
/// </summary>
|
||||
private sealed class NullServiceProvider : IServiceProvider
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the service object of the specified type.
|
||||
/// </summary>
|
||||
/// <param name="serviceType">The type of service to get.</param>
|
||||
/// <returns><see langword="null"/>.</returns>
|
||||
public object? GetService(Type serviceType)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
+175
@@ -0,0 +1,175 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaLibraryScanJob"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaLibraryScanJobTests
|
||||
{
|
||||
private readonly ScanIdFixture _scanIdFixture = new();
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Status_WhenCreated_ShouldBePending()
|
||||
{
|
||||
// Act
|
||||
TestMediaLibraryScanJob job = CreateJob();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Pending, job.Status);
|
||||
Assert.Empty(job.Children);
|
||||
Assert.Empty(job.Parents);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddChild_WhenCalledWithNewJob_ShouldAddChild()
|
||||
{
|
||||
// Arrange
|
||||
TestMediaLibraryScanJob job = CreateJob();
|
||||
TestMediaLibraryScanJob child = CreateJob();
|
||||
|
||||
// Act
|
||||
job.AddChild(child);
|
||||
|
||||
// Assert
|
||||
Assert.Single(job.Children);
|
||||
Assert.Contains(child, job.Children);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddChild_WhenJobIsAlreadyChild_ShouldNotAddDuplicate()
|
||||
{
|
||||
// Arrange
|
||||
TestMediaLibraryScanJob job = CreateJob();
|
||||
TestMediaLibraryScanJob child = CreateJob();
|
||||
|
||||
// Act
|
||||
job.AddChild(child);
|
||||
job.AddChild(child);
|
||||
|
||||
// Assert
|
||||
Assert.Single(job.Children);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddChild_WhenJobIsParent_ShouldNotAddChild()
|
||||
{
|
||||
// Arrange
|
||||
TestMediaLibraryScanJob job = CreateJob();
|
||||
TestMediaLibraryScanJob parent = CreateJob();
|
||||
job.AddParent(parent);
|
||||
|
||||
// Act
|
||||
job.AddChild(parent);
|
||||
|
||||
// Assert
|
||||
Assert.Empty(job.Children);
|
||||
Assert.Single(job.Parents);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddParent_WhenCalledWithNewJob_ShouldAddParent()
|
||||
{
|
||||
// Arrange
|
||||
TestMediaLibraryScanJob job = CreateJob();
|
||||
TestMediaLibraryScanJob parent = CreateJob();
|
||||
|
||||
// Act
|
||||
job.AddParent(parent);
|
||||
|
||||
// Assert
|
||||
Assert.Single(job.Parents);
|
||||
Assert.Contains(parent, job.Parents);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddParent_WhenJobIsAlreadyParent_ShouldNotAddDuplicate()
|
||||
{
|
||||
// Arrange
|
||||
TestMediaLibraryScanJob job = CreateJob();
|
||||
TestMediaLibraryScanJob parent = CreateJob();
|
||||
|
||||
// Act
|
||||
job.AddParent(parent);
|
||||
job.AddParent(parent);
|
||||
|
||||
// Assert
|
||||
Assert.Single(job.Parents);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddParent_WhenJobIsChild_ShouldNotAddParent()
|
||||
{
|
||||
// Arrange
|
||||
TestMediaLibraryScanJob job = CreateJob();
|
||||
TestMediaLibraryScanJob child = CreateJob();
|
||||
job.AddChild(child);
|
||||
|
||||
// Act
|
||||
job.AddParent(child);
|
||||
|
||||
// Assert
|
||||
Assert.Single(job.Children);
|
||||
Assert.Empty(job.Parents);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldCompleteWithoutChangingJobState()
|
||||
{
|
||||
// Arrange
|
||||
TestMediaLibraryScanJob job = CreateJob();
|
||||
|
||||
// Act
|
||||
await job.ExecuteAsync(Guid.NewGuid(), "input", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Pending, job.Status);
|
||||
Assert.Empty(job.Children);
|
||||
Assert.Empty(job.Parents);
|
||||
}
|
||||
|
||||
private TestMediaLibraryScanJob CreateJob()
|
||||
{
|
||||
return new TestMediaLibraryScanJob
|
||||
{
|
||||
ScanId = _scanIdFixture.Create(),
|
||||
UserId = _userIdFixture.Create(),
|
||||
LibraryId = _libraryIdFixture.Create()
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Concrete test implementation of the abstract <see cref="MediaLibraryScanJob"/> class.
|
||||
/// </summary>
|
||||
private sealed class TestMediaLibraryScanJob : MediaLibraryScanJob
|
||||
{
|
||||
/// <summary>
|
||||
/// Executes the payload of the media library scan job.
|
||||
/// </summary>
|
||||
/// <typeparam name="TInput">The type of the input parameter.</typeparam>
|
||||
/// <param name="id">The unique identifier of the media library scan job.</param>
|
||||
/// <param name="input">The input data to be processed.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
public override Task ExecuteAsync<TInput>(Guid id, TInput input, CancellationToken cancellationToken)
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
}
|
||||
+299
@@ -0,0 +1,299 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Scanners;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using NSubstitute;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaLibraryScanningService"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaLibraryScanningServiceTests
|
||||
{
|
||||
private readonly IMediaLibraryScannerFactory _mockScannerFactory;
|
||||
private readonly IMediaLibrariesScanCancellationTracker _mockCancellationTracker;
|
||||
private readonly IMediaLibrariesScanProgressTracker _mockProgressTracker;
|
||||
private readonly IDomainEventPublisher _mockDomainEventPublisher;
|
||||
private readonly MediaLibraryScanningService _sut;
|
||||
private readonly LibraryScanFixture _libraryScanFixture = new();
|
||||
private readonly ScanIdFixture _scanIdFixture = new();
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly MediaLibraryScanDiscoveryJobFixture _mediaLibraryScanDiscoveryJobFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaLibraryScanningServiceTests"/> class.
|
||||
/// </summary>
|
||||
public MediaLibraryScanningServiceTests()
|
||||
{
|
||||
_mockScannerFactory = Substitute.For<IMediaLibraryScannerFactory>();
|
||||
_mockCancellationTracker = Substitute.For<IMediaLibrariesScanCancellationTracker>();
|
||||
_mockProgressTracker = Substitute.For<IMediaLibrariesScanProgressTracker>();
|
||||
_mockProgressTracker.InitializeScanProgress(Arg.Any<LibraryId>(), Arg.Any<MediaLibraryScanCompositeId>(), Arg.Any<int>())
|
||||
.Returns(Result.Created);
|
||||
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
|
||||
_sut = new MediaLibraryScanningService(_mockScannerFactory, _mockCancellationTracker, _mockProgressTracker, _mockDomainEventPublisher);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartScanAsync_WhenScanStartsSuccessfully_ShouldReturnTheDiscoveryRootJob()
|
||||
{
|
||||
// Arrange
|
||||
LibraryScan scan = _libraryScanFixture.Create();
|
||||
FakeMediaLibraryScanDiscoveryJob rootJob = _mediaLibraryScanDiscoveryJobFixture.Create();
|
||||
RegisterScanner(LibraryType.Book, rootJob);
|
||||
|
||||
// Act
|
||||
Result<IMediaLibraryScanDiscoveryJob> result = await _sut.StartScanAsync(scan, LibraryType.Book, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Same(rootJob, result.Value);
|
||||
Assert.Equal(LibraryScanJobStatus.Running, scan.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartScanAsync_WhenScanStartsSuccessfully_ShouldPublishTheStartedEvent()
|
||||
{
|
||||
// Arrange
|
||||
LibraryScan scan = _libraryScanFixture.Create();
|
||||
RegisterScanner(LibraryType.Book, _mediaLibraryScanDiscoveryJobFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.StartScanAsync(scan, LibraryType.Book, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(
|
||||
Arg.Is<IDomainEvent>(domainEvent => domainEvent.GetType() == typeof(LibraryScanStartedDomainEvent)
|
||||
&& ((LibraryScanStartedDomainEvent)domainEvent).LibraryScan == scan),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartScanAsync_WhenScanStartsSuccessfully_ShouldRegisterTheScanForCancellation()
|
||||
{
|
||||
// Arrange
|
||||
LibraryScan scan = _libraryScanFixture.Create();
|
||||
RegisterScanner(LibraryType.Book, _mediaLibraryScanDiscoveryJobFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.StartScanAsync(scan, LibraryType.Book, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
_mockCancellationTracker.Received(1).RegisterScan(
|
||||
Arg.Is<MediaLibraryScanCompositeId>(compositeId => compositeId.ScanId == scan.Id && compositeId.UserId == scan.UserId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartScanAsync_WhenScanStartsSuccessfully_ShouldInitializeProgressWithTheRealJobCount()
|
||||
{
|
||||
// Arrange
|
||||
LibraryScan scan = _libraryScanFixture.Create();
|
||||
FakeMediaLibraryScanDiscoveryJob leafJob = _mediaLibraryScanDiscoveryJobFixture.Create();
|
||||
FakeMediaLibraryScanDiscoveryJob middleJob = _mediaLibraryScanDiscoveryJobFixture.Create(children: [leafJob]);
|
||||
FakeMediaLibraryScanDiscoveryJob rootJob = _mediaLibraryScanDiscoveryJobFixture.Create(children: [middleJob]);
|
||||
RegisterScanner(LibraryType.Book, rootJob);
|
||||
|
||||
// Act
|
||||
await _sut.StartScanAsync(scan, LibraryType.Book, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
_mockProgressTracker.Received(1).InitializeScanProgress(
|
||||
scan.LibraryId,
|
||||
Arg.Is<MediaLibraryScanCompositeId>(compositeId => compositeId.ScanId == scan.Id && compositeId.UserId == scan.UserId),
|
||||
totalJobs: 3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartScanAsync_WhenScanStartsSuccessfully_ShouldSetScanPropertiesOnTheWholeJobChain()
|
||||
{
|
||||
// Arrange
|
||||
LibraryScan scan = _libraryScanFixture.Create();
|
||||
FakeMediaLibraryScanDiscoveryJob leafJob = _mediaLibraryScanDiscoveryJobFixture.Create();
|
||||
FakeMediaLibraryScanDiscoveryJob middleJob = _mediaLibraryScanDiscoveryJobFixture.Create(children: [leafJob]);
|
||||
FakeMediaLibraryScanDiscoveryJob rootJob = _mediaLibraryScanDiscoveryJobFixture.Create(children: [middleJob]);
|
||||
RegisterScanner(LibraryType.Book, rootJob);
|
||||
|
||||
// Act
|
||||
await _sut.StartScanAsync(scan, LibraryType.Book, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
AssertScanProperties(rootJob, scan);
|
||||
AssertScanProperties(middleJob, scan);
|
||||
AssertScanProperties(leafJob, scan);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartScanAsync_WhenScannerIsUnavailable_ShouldReturnErrorAndChangeNothing()
|
||||
{
|
||||
// Arrange
|
||||
LibraryScan scan = _libraryScanFixture.Create();
|
||||
_mockScannerFactory.CreateLibraryScanner(LibraryType.Movie).Returns(Errors.LibraryScanning.NoScannerForLibraryType);
|
||||
|
||||
// Act
|
||||
Result<IMediaLibraryScanDiscoveryJob> result = await _sut.StartScanAsync(scan, LibraryType.Movie, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.LibraryScanning.NoScannerForLibraryType, result.FirstError);
|
||||
Assert.Equal(LibraryScanJobStatus.Pending, scan.Status);
|
||||
Assert.Empty(scan.GetDomainEvents());
|
||||
_mockCancellationTracker.DidNotReceive().RegisterScan(Arg.Any<MediaLibraryScanCompositeId>());
|
||||
_mockProgressTracker.DidNotReceive().InitializeScanProgress(Arg.Any<LibraryId>(), Arg.Any<MediaLibraryScanCompositeId>(), Arg.Any<int>());
|
||||
await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartScanAsync_WhenScanIsNotPending_ShouldReturnErrorWithoutRegisteringOrPublishing()
|
||||
{
|
||||
// Arrange
|
||||
LibraryScan scan = _libraryScanFixture.Create(status: LibraryScanJobStatus.Running);
|
||||
RegisterScanner(LibraryType.Book, _mediaLibraryScanDiscoveryJobFixture.Create());
|
||||
|
||||
// Act
|
||||
Result<IMediaLibraryScanDiscoveryJob> result = await _sut.StartScanAsync(scan, LibraryType.Book, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.LibraryScanning.CanOnlyStartPendingScans, result.FirstError);
|
||||
Assert.Equal(LibraryScanJobStatus.Running, scan.Status);
|
||||
Assert.Empty(scan.GetDomainEvents());
|
||||
_mockCancellationTracker.DidNotReceive().RegisterScan(Arg.Any<MediaLibraryScanCompositeId>());
|
||||
_mockProgressTracker.DidNotReceive().InitializeScanProgress(Arg.Any<LibraryId>(), Arg.Any<MediaLibraryScanCompositeId>(), Arg.Any<int>());
|
||||
await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartScanAsync_WhenProgressInitializationFails_ShouldReturnErrorWithoutPublishingEvents()
|
||||
{
|
||||
// Arrange
|
||||
LibraryScan scan = _libraryScanFixture.Create();
|
||||
RegisterScanner(LibraryType.Book, _mediaLibraryScanDiscoveryJobFixture.Create());
|
||||
Error error = Error.Failure(description: "Failed to initialize the media library scan progress");
|
||||
_mockProgressTracker.InitializeScanProgress(Arg.Any<LibraryId>(), Arg.Any<MediaLibraryScanCompositeId>(), Arg.Any<int>())
|
||||
.Returns(error);
|
||||
|
||||
// Act
|
||||
Result<IMediaLibraryScanDiscoveryJob> result = await _sut.StartScanAsync(scan, LibraryType.Book, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartScanAsync_WhenJobGraphHasSharedChild_ShouldCountOnlyUniqueJobs()
|
||||
{
|
||||
// Arrange
|
||||
LibraryScan scan = _libraryScanFixture.Create();
|
||||
IMediaLibraryScanJob sharedChild = CreateJob(children: []);
|
||||
IMediaLibraryScanJob firstChild = CreateJob(children: [sharedChild]);
|
||||
IMediaLibraryScanJob secondChild = CreateJob(children: [sharedChild]);
|
||||
FakeMediaLibraryScanDiscoveryJob rootJob = _mediaLibraryScanDiscoveryJobFixture.Create(children: [firstChild, secondChild]);
|
||||
RegisterScanner(LibraryType.Book, rootJob);
|
||||
|
||||
// Act
|
||||
await _sut.StartScanAsync(scan, LibraryType.Book, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
_mockProgressTracker.Received(1).InitializeScanProgress(scan.LibraryId, Arg.Any<MediaLibraryScanCompositeId>(), totalJobs: 4);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CancelScan_WhenCalled_ShouldCancelScanInTracker()
|
||||
{
|
||||
// Arrange
|
||||
LibraryScan scan = _libraryScanFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Success> result = _sut.CancelScan(scan);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Success, result.Value);
|
||||
_mockCancellationTracker.Received(1).CancelScan(Arg.Is<MediaLibraryScanCompositeId>(compositeId => compositeId.ScanId == scan.Id && compositeId.UserId == scan.UserId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SetScanPropertiesForJobChain_WhenCalled_ShouldSetScanPropertiesRecursively()
|
||||
{
|
||||
// Arrange
|
||||
ScanId scanId = _scanIdFixture.Create();
|
||||
UserId userId = _userIdFixture.Create();
|
||||
IMediaLibraryScanJob leafJob = CreateJob(children: []);
|
||||
IMediaLibraryScanJob middleJob = CreateJob(children: [leafJob]);
|
||||
IMediaLibraryScanJob rootJob = CreateJob(children: [middleJob]);
|
||||
|
||||
// Act
|
||||
MediaLibraryScanningService.SetScanPropertiesForJobChain(rootJob, scanId, userId);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(scanId, rootJob.ScanId);
|
||||
Assert.Equal(userId, rootJob.UserId);
|
||||
Assert.Equal(scanId, middleJob.ScanId);
|
||||
Assert.Equal(userId, middleJob.UserId);
|
||||
Assert.Equal(scanId, leafJob.ScanId);
|
||||
Assert.Equal(userId, leafJob.UserId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers a mocked media library scanner that returns <paramref name="rootJob"/> with the mocked scanner factory.
|
||||
/// </summary>
|
||||
/// <param name="libraryType">The media library type that the scanner is registered for.</param>
|
||||
/// <param name="rootJob">The file system discovery job returned by the scanner.</param>
|
||||
/// <returns>The created mocked scanner.</returns>
|
||||
private IMediaTypeScanner RegisterScanner(LibraryType libraryType, IMediaLibraryScanDiscoveryJob rootJob)
|
||||
{
|
||||
IMediaTypeScanner scanner = Substitute.For<IMediaTypeScanner>();
|
||||
scanner.CreateScanJobsForLibrary(Arg.Any<LibraryId>()).Returns(rootJob);
|
||||
_mockScannerFactory.CreateLibraryScanner(libraryType).Returns(Result.From(scanner));
|
||||
return scanner;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a mocked scan job with the given children.
|
||||
/// </summary>
|
||||
/// <param name="children">The child scan jobs of the created job.</param>
|
||||
/// <returns>The created mocked scan job.</returns>
|
||||
private static IMediaLibraryScanJob CreateJob(List<IMediaLibraryScanJob> children)
|
||||
{
|
||||
IMediaLibraryScanJob job = Substitute.For<IMediaLibraryScanJob>();
|
||||
job.Children.Returns(children);
|
||||
return job;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the scan identity of the scan was propagated to <paramref name="job"/>.
|
||||
/// </summary>
|
||||
/// <param name="job">The job whose scan properties are asserted.</param>
|
||||
/// <param name="scan">The media library scan that owns the job.</param>
|
||||
private static void AssertScanProperties(IMediaLibraryScanJob job, LibraryScan scan)
|
||||
{
|
||||
Assert.Equal(scan.Id, job.ScanId);
|
||||
Assert.Equal(scan.UserId, job.UserId);
|
||||
}
|
||||
}
|
||||
+497
@@ -0,0 +1,497 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using NSubstitute;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="LibraryPathTemplateService"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LibraryPathTemplateServiceTests
|
||||
{
|
||||
private readonly ILibraryPathPartCatalog _mockCatalog = Substitute.For<ILibraryPathPartCatalog>();
|
||||
private readonly LibraryPathTemplateService _sut;
|
||||
private readonly LibraryPathPartFixture _libraryPathPartFixture = new();
|
||||
private readonly LibraryPathTemplateFixture _libraryPathTemplateFixture = new();
|
||||
private readonly LibraryPathPartDefinitionFixture _libraryPathPartDefinitionFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LibraryPathTemplateServiceTests"/> class.
|
||||
/// </summary>
|
||||
public LibraryPathTemplateServiceTests()
|
||||
{
|
||||
_mockCatalog.SupportedLibraryType.Returns(LibraryType.Music);
|
||||
_sut = new LibraryPathTemplateService([_mockCatalog]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetDefaultTemplate_WhenCatalogExists_ShouldReturnTheCatalogDefaultTemplate()
|
||||
{
|
||||
// Arrange
|
||||
LibraryPathTemplate defaultTemplate = _libraryPathTemplateFixture.Create();
|
||||
_mockCatalog.GetDefaultTemplate().Returns(defaultTemplate);
|
||||
|
||||
// Act
|
||||
LibraryPathTemplate result = _sut.GetDefaultTemplate(LibraryType.Music);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(defaultTemplate, result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetDefaultTemplate_WhenNoCatalogExistsForTheLibraryType_ShouldReturnAnEmptyTemplate()
|
||||
{
|
||||
// Act
|
||||
LibraryPathTemplate result = _sut.GetDefaultTemplate(LibraryType.Book);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ResolveTemplate_WhenProvidedPartsAreEmpty_ShouldReturnTheCatalogDefaultTemplate()
|
||||
{
|
||||
// Arrange
|
||||
SetupCatalog();
|
||||
LibraryPathTemplate defaultTemplate = CreateMusicTemplate();
|
||||
_mockCatalog.GetDefaultTemplate().Returns(defaultTemplate);
|
||||
|
||||
// Act
|
||||
Result<LibraryPathTemplate> result = _sut.ResolveTemplate(LibraryType.Music, []);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(defaultTemplate, result.Value);
|
||||
_mockCatalog.Received(1).GetDefaultTemplate();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ResolveTemplate_WhenProvidedPartsAreEmptyAndNoCatalogExists_ShouldReturnAnEmptyTemplate()
|
||||
{
|
||||
// Act
|
||||
Result<LibraryPathTemplate> result = _sut.ResolveTemplate(LibraryType.Book, []);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.True(result.Value.IsEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ResolveTemplate_WhenProvidedPartsAreNotEmpty_ShouldReturnATemplateWithThoseParts()
|
||||
{
|
||||
// Arrange
|
||||
SetupCatalog();
|
||||
LibraryPathPart providedPart = _libraryPathPartFixture.Create(
|
||||
kind: LibraryPathPartKind.Artist,
|
||||
representation: "{0}",
|
||||
isOptional: false);
|
||||
|
||||
// Act
|
||||
Result<LibraryPathTemplate> result = _sut.ResolveTemplate(LibraryType.Music, [providedPart]);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
LibraryPathPart pathPart = Assert.Single(result.Value.Parts);
|
||||
Assert.Equal(LibraryPathPartKind.Artist, pathPart.Kind);
|
||||
Assert.Equal("{0}", pathPart.Representation);
|
||||
Assert.False(pathPart.IsOptional);
|
||||
_mockCatalog.DidNotReceive().GetDefaultTemplate();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ResolveTemplate_WhenProvidedPartsAreNotSupportedByTheCatalog_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
SetupCatalog(
|
||||
[
|
||||
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Artist, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}"),
|
||||
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Separator, valueType: LibraryPathValueType.None, defaultRepresentation: string.Empty)
|
||||
]);
|
||||
LibraryPathPart releaseNamePart = _libraryPathPartFixture.Create(
|
||||
kind: LibraryPathPartKind.ReleaseName,
|
||||
representation: "{0}",
|
||||
isOptional: false);
|
||||
|
||||
// Act
|
||||
Result<LibraryPathTemplate> result = _sut.ResolveTemplate(LibraryType.Music, [releaseNamePart]);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Library.PathTemplatePartKindNotSupportedForLibraryType, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ResolveTemplate_WhenNoCatalogExistsForTheLibraryTypeAndPartsAreProvided_ShouldReturnNotSupportedError()
|
||||
{
|
||||
// Arrange
|
||||
LibraryPathPart artistPart = _libraryPathPartFixture.Create(
|
||||
kind: LibraryPathPartKind.Artist,
|
||||
representation: "{0}",
|
||||
isOptional: false);
|
||||
|
||||
// Act
|
||||
Result<LibraryPathTemplate> result = _sut.ResolveTemplate(LibraryType.Book, [artistPart]);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Library.PathTemplateIsNotSupportedForLibraryType, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenTemplateIsEmpty_ShouldReturnSuccess()
|
||||
{
|
||||
// Act
|
||||
Result<Success> result = _sut.Validate(LibraryType.Music, LibraryPathTemplate.Empty());
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenTemplateIsEmptyAndNoCatalogExists_ShouldReturnSuccess()
|
||||
{
|
||||
// Act
|
||||
Result<Success> result = _sut.Validate(LibraryType.Book, LibraryPathTemplate.Empty());
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenNoCatalogExistsForTheLibraryType_ShouldReturnNotSupportedError()
|
||||
{
|
||||
// Act
|
||||
Result<Success> result = _sut.Validate(LibraryType.Book, CreateMusicTemplate());
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Library.PathTemplateIsNotSupportedForLibraryType, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenPartKindIsNotSupportedByTheCatalog_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
SetupCatalog(definitions:
|
||||
[
|
||||
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Artist, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}"),
|
||||
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Separator, valueType: LibraryPathValueType.None, defaultRepresentation: string.Empty),
|
||||
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.TrackName, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}")
|
||||
]);
|
||||
LibraryPathTemplate template = _libraryPathTemplateFixture.Create(
|
||||
[
|
||||
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "{0}"),
|
||||
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Separator, representation: string.Empty),
|
||||
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.ReleaseName, representation: "{0}")
|
||||
]);
|
||||
|
||||
// Act
|
||||
Result<Success> result = _sut.Validate(LibraryType.Music, template);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Library.PathTemplatePartKindNotSupportedForLibraryType, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenAllPartKindsAreSupportedByTheCatalog_ShouldReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
SetupCatalog();
|
||||
LibraryPathTemplate template = CreateMusicTemplate();
|
||||
|
||||
// Act
|
||||
Result<Success> result = _sut.Validate(LibraryType.Music, template);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")] // The relative path is empty.
|
||||
[InlineData(" ")] // The relative path is whitespace.
|
||||
public void Parse_WhenRelativePathIsEmpty_ShouldReturnNull(string relativePath)
|
||||
{
|
||||
// Act
|
||||
Result<Optional<ParsedLibraryPath>> result = _sut.Parse(LibraryType.Music, CreateMusicTemplate(), relativePath, '/');
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.False(result.Value.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_WhenTemplateIsEmpty_ShouldReturnNull()
|
||||
{
|
||||
// Act
|
||||
Result<Optional<ParsedLibraryPath>> result = _sut.Parse(LibraryType.Music, LibraryPathTemplate.Empty(), "Pink Floyd/1973 - Time.mp3", '/');
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.False(result.Value.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_WhenTemplateIsNotSupportedForTheLibraryType_ShouldReturnError()
|
||||
{
|
||||
// Act
|
||||
Result<Optional<ParsedLibraryPath>> result = _sut.Parse(LibraryType.Book, CreateMusicTemplate(), "Pink Floyd/1973 - Time.mp3", '/');
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Library.PathTemplateIsNotSupportedForLibraryType, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_WhenPathMatchesTheTemplate_ShouldReturnTheCapturedValues()
|
||||
{
|
||||
// Arrange
|
||||
SetupCatalog();
|
||||
LibraryPathTemplate template = CreateMusicTemplate();
|
||||
|
||||
// Act
|
||||
Result<Optional<ParsedLibraryPath>> result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/1973 - Time.mp3", '/');
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
ParsedLibraryPath parsedPath = result.Value.Value;
|
||||
Assert.Equal("Pink Floyd", parsedPath.GetString(LibraryPathPartKind.Artist).Value);
|
||||
Assert.Equal(1973, parsedPath.GetInt(LibraryPathPartKind.ReleaseYear).Value);
|
||||
Assert.Equal("Time", parsedPath.GetString(LibraryPathPartKind.TrackName).Value);
|
||||
Assert.Equal("mp3", parsedPath.GetString(LibraryPathPartKind.Extension).Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_WhenPathDoesNotMatchTheTemplate_ShouldReturnNull()
|
||||
{
|
||||
// Arrange
|
||||
SetupCatalog();
|
||||
LibraryPathTemplate template = CreateMusicTemplate();
|
||||
|
||||
// Act
|
||||
Result<Optional<ParsedLibraryPath>> result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/no year/Time.mp3", '/');
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.False(result.Value.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_WhenIntegerPartHasAFixedWidth_ShouldCaptureIt()
|
||||
{
|
||||
// Arrange
|
||||
SetupCatalog(
|
||||
[
|
||||
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Artist, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}"),
|
||||
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Separator, valueType: LibraryPathValueType.None, defaultRepresentation: string.Empty),
|
||||
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.TrackNumber, valueType: LibraryPathValueType.Integer, defaultRepresentation: "{0:00}")
|
||||
]);
|
||||
LibraryPathTemplate template = _libraryPathTemplateFixture.Create(
|
||||
[
|
||||
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "{0}"),
|
||||
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Separator, representation: string.Empty),
|
||||
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.TrackNumber, representation: "{0:00}")
|
||||
]);
|
||||
|
||||
// Act
|
||||
Result<Optional<ParsedLibraryPath>> result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/07", '/');
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(7, result.Value.Value.GetInt(LibraryPathPartKind.TrackNumber).Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_WhenIntegerPartDoesNotMatchTheFixedWidth_ShouldReturnNull()
|
||||
{
|
||||
// Arrange
|
||||
SetupCatalog(
|
||||
[
|
||||
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Artist, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}"),
|
||||
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Separator, valueType: LibraryPathValueType.None, defaultRepresentation: string.Empty),
|
||||
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.TrackNumber, valueType: LibraryPathValueType.Integer, defaultRepresentation: "{0:00}")
|
||||
]);
|
||||
LibraryPathTemplate template = _libraryPathTemplateFixture.Create(
|
||||
[
|
||||
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "{0}"),
|
||||
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Separator, representation: string.Empty),
|
||||
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.TrackNumber, representation: "{0:00}")
|
||||
]);
|
||||
|
||||
// Act
|
||||
Result<Optional<ParsedLibraryPath>> result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/007", '/');
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.False(result.Value.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_WhenYearPartHasAFourDigitValue_ShouldCaptureIt()
|
||||
{
|
||||
// Arrange
|
||||
SetupCatalog(
|
||||
[
|
||||
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.ReleaseYear, valueType: LibraryPathValueType.Year, defaultRepresentation: "{0}")
|
||||
]);
|
||||
LibraryPathTemplate template = _libraryPathTemplateFixture.Create(
|
||||
[
|
||||
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.ReleaseYear, representation: "{0}")
|
||||
]);
|
||||
|
||||
// Act
|
||||
Result<Optional<ParsedLibraryPath>> result = _sut.Parse(LibraryType.Music, template, "1973", '/');
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(1973, result.Value.Value.GetInt(LibraryPathPartKind.ReleaseYear).Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_WhenYearPartDoesNotHaveAFourDigitValue_ShouldReturnNull()
|
||||
{
|
||||
// Arrange
|
||||
SetupCatalog(
|
||||
[
|
||||
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.ReleaseYear, valueType: LibraryPathValueType.Year, defaultRepresentation: "{0}")
|
||||
]);
|
||||
LibraryPathTemplate template = _libraryPathTemplateFixture.Create(
|
||||
[
|
||||
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.ReleaseYear, representation: "{0}")
|
||||
]);
|
||||
|
||||
// Act
|
||||
Result<Optional<ParsedLibraryPath>> result = _sut.Parse(LibraryType.Music, template, "73", '/');
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.False(result.Value.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_WhenAnOptionalRunIsAbsent_ShouldStillMatchThePath()
|
||||
{
|
||||
// Arrange
|
||||
SetupCatalog(
|
||||
[
|
||||
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Artist, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}"),
|
||||
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Separator, valueType: LibraryPathValueType.None, defaultRepresentation: string.Empty),
|
||||
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.DiscNumber, valueType: LibraryPathValueType.Integer, defaultRepresentation: "{0:00}")
|
||||
]);
|
||||
LibraryPathTemplate template = _libraryPathTemplateFixture.Create(
|
||||
[
|
||||
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "{0}"),
|
||||
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Separator, representation: string.Empty),
|
||||
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.DiscNumber, representation: "{0:00}", isOptional: true)
|
||||
]);
|
||||
|
||||
// Act
|
||||
Result<Optional<ParsedLibraryPath>> result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/", '/');
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal("Pink Floyd", result.Value.Value.GetString(LibraryPathPartKind.Artist).Value);
|
||||
Assert.False(result.Value.Value.GetInt(LibraryPathPartKind.DiscNumber).HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_WhenAnOptionalRunIsPresent_ShouldCaptureIt()
|
||||
{
|
||||
// Arrange
|
||||
SetupCatalog(
|
||||
[
|
||||
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Artist, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}"),
|
||||
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Separator, valueType: LibraryPathValueType.None, defaultRepresentation: string.Empty),
|
||||
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.DiscNumber, valueType: LibraryPathValueType.Integer, defaultRepresentation: "{0:00}")
|
||||
]);
|
||||
LibraryPathTemplate template = _libraryPathTemplateFixture.Create(
|
||||
[
|
||||
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "{0}"),
|
||||
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Separator, representation: string.Empty),
|
||||
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.DiscNumber, representation: "{0:00}", isOptional: true)
|
||||
]);
|
||||
|
||||
// Act
|
||||
Result<Optional<ParsedLibraryPath>> result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/02", '/');
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal("Pink Floyd", result.Value.Value.GetString(LibraryPathPartKind.Artist).Value);
|
||||
Assert.Equal(2, result.Value.Value.GetInt(LibraryPathPartKind.DiscNumber).Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_WhenTheSameKindAppearsMoreThanOnce_ShouldKeepTheFirstCapture()
|
||||
{
|
||||
// Arrange
|
||||
SetupCatalog(
|
||||
[
|
||||
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Author, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}"),
|
||||
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Separator, valueType: LibraryPathValueType.None, defaultRepresentation: string.Empty),
|
||||
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Title, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}"),
|
||||
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Literal, valueType: LibraryPathValueType.None, defaultRepresentation: string.Empty)
|
||||
]);
|
||||
LibraryPathTemplate template = _libraryPathTemplateFixture.Create(
|
||||
[
|
||||
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Author, representation: "{0}"),
|
||||
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Separator, representation: string.Empty),
|
||||
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Title, representation: "{0}"),
|
||||
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Literal, representation: " - "),
|
||||
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Author, representation: "{0}")
|
||||
]);
|
||||
|
||||
// Act
|
||||
Result<Optional<ParsedLibraryPath>> result = _sut.Parse(LibraryType.Music, template, "Tolkien/The Lord of the Rings - J.R.R. Tolkien", '/');
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal("Tolkien", result.Value.Value.GetString(LibraryPathPartKind.Author).Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets up the mock catalog to return a music-like set of part definitions and a default template.
|
||||
/// </summary>
|
||||
/// <param name="definitions">Optional. The part definitions the catalog returns. When omitted, a standard music set is used.</param>
|
||||
private void SetupCatalog(IReadOnlyList<LibraryPathPartDefinition>? definitions = null)
|
||||
{
|
||||
_mockCatalog.GetPartDefinitions().Returns(definitions ??
|
||||
[
|
||||
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Literal, valueType: LibraryPathValueType.None, defaultRepresentation: string.Empty),
|
||||
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Artist, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}"),
|
||||
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Separator, valueType: LibraryPathValueType.None, defaultRepresentation: string.Empty),
|
||||
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.ReleaseYear, valueType: LibraryPathValueType.Year, defaultRepresentation: "{0}"),
|
||||
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.TrackNumber, valueType: LibraryPathValueType.Integer, defaultRepresentation: "{0:00}"),
|
||||
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.TrackName, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}"),
|
||||
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Extension, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}")
|
||||
]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a music-like path template whose parts are all supported by the standard music set of definitions.
|
||||
/// </summary>
|
||||
/// <returns>The created path template.</returns>
|
||||
private LibraryPathTemplate CreateMusicTemplate()
|
||||
{
|
||||
return _libraryPathTemplateFixture.Create(
|
||||
[
|
||||
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "{0}"),
|
||||
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Separator, representation: string.Empty),
|
||||
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.ReleaseYear, representation: "{0}"),
|
||||
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Literal, representation: " - "),
|
||||
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.TrackName, representation: "{0}"),
|
||||
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Literal, representation: "."),
|
||||
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Extension, representation: "{0}")
|
||||
]);
|
||||
}
|
||||
}
|
||||
+259
@@ -0,0 +1,259 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaLibrariesScanProgressTracker"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaLibrariesScanProgressTrackerTests
|
||||
{
|
||||
private readonly MediaLibrariesScanProgressTracker _sut = new();
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new();
|
||||
private readonly MediaLibraryScanJobProgressFixture _mediaLibraryScanJobProgressFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void InitializeQueuedScanProgress_WhenCalled_ShouldCreatePendingProgressWithZeroTotalJobs()
|
||||
{
|
||||
// Arrange
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Created> result = _sut.InitializeQueuedScanProgress(libraryId, compositeId);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Created, result.Value);
|
||||
Result<MediaLibraryScanProgress> progressResult = _sut.GetScanProgress(compositeId);
|
||||
Assert.False(progressResult.IsFailure);
|
||||
Assert.Equal(compositeId.ScanId, progressResult.Value.ScanId);
|
||||
Assert.Equal(compositeId.UserId, progressResult.Value.UserId);
|
||||
Assert.Equal(libraryId, progressResult.Value.LibraryId);
|
||||
Assert.Equal(0, progressResult.Value.CompletedJobs);
|
||||
Assert.Equal(0, progressResult.Value.TotalJobs);
|
||||
Assert.Equal(LibraryScanJobStatus.Pending, progressResult.Value.Status);
|
||||
Assert.True(progressResult.Value.CurrentJobProgress.HasValue);
|
||||
Assert.Equal("Queued", progressResult.Value.CurrentJobProgress.Value.CurrentOperation);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InitializeQueuedScanProgress_WhenCalledTwice_ShouldReplaceThePreviousProgress()
|
||||
{
|
||||
// Arrange
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
|
||||
// Act
|
||||
_sut.InitializeQueuedScanProgress(libraryId, compositeId);
|
||||
Result<Created> result = _sut.InitializeQueuedScanProgress(libraryId, compositeId);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Result<MediaLibraryScanProgress> progressResult = _sut.GetScanProgress(compositeId);
|
||||
Assert.False(progressResult.IsFailure);
|
||||
Assert.Equal(0, progressResult.Value.CompletedJobs);
|
||||
Assert.Equal(0, progressResult.Value.TotalJobs);
|
||||
Assert.Equal("Queued", progressResult.Value.CurrentJobProgress.Value.CurrentOperation);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InitializeScanProgress_WhenCalled_ShouldCreateProgressWithZeroCompletedJobs()
|
||||
{
|
||||
// Arrange
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Created> result = _sut.InitializeScanProgress(libraryId, compositeId, totalJobs: 5);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Created, result.Value);
|
||||
Result<MediaLibraryScanProgress> progressResult = _sut.GetScanProgress(compositeId);
|
||||
Assert.False(progressResult.IsFailure);
|
||||
Assert.Equal(0, progressResult.Value.CompletedJobs);
|
||||
Assert.Equal(5, progressResult.Value.TotalJobs);
|
||||
Assert.Equal(LibraryScanJobStatus.Pending, progressResult.Value.Status);
|
||||
Assert.True(progressResult.Value.CurrentJobProgress.HasValue);
|
||||
Assert.Equal("Initializing", progressResult.Value.CurrentJobProgress.Value.CurrentOperation);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InitializeScanProgress_WhenTotalJobsIsNegative_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Created> result = _sut.InitializeScanProgress(libraryId, compositeId, totalJobs: -1);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.LibraryScanning.TotalScanJobsCountMustBePositive, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateScanProgress_WhenScanExists_ShouldIncrementCompletedJobs()
|
||||
{
|
||||
// Arrange
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
_sut.InitializeScanProgress(libraryId, compositeId, totalJobs: 2);
|
||||
|
||||
// Act
|
||||
Result<Updated> result = _sut.UpdateScanProgress(libraryId, compositeId);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
Result<MediaLibraryScanProgress> progressResult = _sut.GetScanProgress(compositeId);
|
||||
Assert.False(progressResult.IsFailure);
|
||||
Assert.Equal(1, progressResult.Value.CompletedJobs);
|
||||
Assert.Equal(LibraryScanJobStatus.Running, progressResult.Value.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateScanProgress_WhenLastJobIsCompleted_ShouldSetStatusCompleted()
|
||||
{
|
||||
// Arrange
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
_sut.InitializeScanProgress(libraryId, compositeId, totalJobs: 1);
|
||||
|
||||
// Act
|
||||
Result<Updated> result = _sut.UpdateScanProgress(libraryId, compositeId);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Result<MediaLibraryScanProgress> progressResult = _sut.GetScanProgress(compositeId);
|
||||
Assert.False(progressResult.IsFailure);
|
||||
Assert.Equal(1, progressResult.Value.CompletedJobs);
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, progressResult.Value.Status);
|
||||
Assert.Equal(100, progressResult.Value.OverallProgressPercentage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateScanProgress_WhenScanIsAlreadyCompleted_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
_sut.InitializeScanProgress(libraryId, compositeId, totalJobs: 1);
|
||||
_sut.UpdateScanProgress(libraryId, compositeId);
|
||||
|
||||
// Act
|
||||
Result<Updated> result = _sut.UpdateScanProgress(libraryId, compositeId);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.LibraryScanning.CompletedScanJobsCountCantExceedTotalScanJobsCount, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateScanJobProgress_WhenScanExists_ShouldUpdateCurrentJobProgress()
|
||||
{
|
||||
// Arrange
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
_sut.InitializeScanProgress(libraryId, compositeId, totalJobs: 2);
|
||||
MediaLibraryScanJobProgress jobProgress = _mediaLibraryScanJobProgressFixture.Create(completedItems: 3, totalItems: 10, currentOperation: "Hashing files");
|
||||
|
||||
// Act
|
||||
Result<Updated> result = _sut.UpdateScanJobProgress(libraryId, compositeId, jobProgress);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
Result<MediaLibraryScanProgress> progressResult = _sut.GetScanProgress(compositeId);
|
||||
Assert.False(progressResult.IsFailure);
|
||||
Assert.True(progressResult.Value.CurrentJobProgress.HasValue);
|
||||
Assert.Equal(3, progressResult.Value.CurrentJobProgress.Value.CompletedItems);
|
||||
Assert.Equal("Hashing files", progressResult.Value.CurrentJobProgress.Value.CurrentOperation);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateScanJobProgress_WhenScanDoesNotExist_ShouldReturnNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
MediaLibraryScanJobProgress jobProgress = _mediaLibraryScanJobProgressFixture.Create(completedItems: 1, totalItems: 10, currentOperation: "Hashing files");
|
||||
|
||||
// Act
|
||||
Result<Updated> result = _sut.UpdateScanJobProgress(libraryId, compositeId, jobProgress);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.LibraryScanning.LibraryScanNotFound, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetScanProgress_WhenScanExists_ShouldReturnProgress()
|
||||
{
|
||||
// Arrange
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
_sut.InitializeScanProgress(libraryId, compositeId, totalJobs: 3);
|
||||
|
||||
// Act
|
||||
Result<MediaLibraryScanProgress> result = _sut.GetScanProgress(compositeId);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(compositeId.ScanId, result.Value.ScanId);
|
||||
Assert.Equal(compositeId.UserId, result.Value.UserId);
|
||||
Assert.Equal(libraryId, result.Value.LibraryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetScanProgress_WhenScanDoesNotExist_ShouldReturnNotFoundError()
|
||||
{
|
||||
// Act
|
||||
Result<MediaLibraryScanProgress> result = _sut.GetScanProgress(_mediaLibraryScanCompositeIdFixture.Create());
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.LibraryScanning.LibraryScanNotFound, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RemoveScanProgress_WhenScanExists_ShouldRemoveAndReturnProgress()
|
||||
{
|
||||
// Arrange
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
_sut.InitializeScanProgress(libraryId, compositeId, totalJobs: 3);
|
||||
|
||||
// Act
|
||||
Result<MediaLibraryScanProgress> result = _sut.RemoveScanProgress(compositeId);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(compositeId.ScanId, result.Value.ScanId);
|
||||
Assert.True(_sut.GetScanProgress(compositeId).IsFailure);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RemoveScanProgress_WhenScanDoesNotExist_ShouldReturnNotFoundError()
|
||||
{
|
||||
// Act
|
||||
Result<MediaLibraryScanProgress> result = _sut.RemoveScanProgress(_mediaLibraryScanCompositeIdFixture.Create());
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.LibraryScanning.LibraryScanNotFound, result.FirstError);
|
||||
}
|
||||
}
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.Scanners;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Scanners;
|
||||
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Scanners;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Scanners;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaLibraryScannerFactory"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaLibraryScannerFactoryTests : IDisposable
|
||||
{
|
||||
private readonly IBookLibraryTypeScanner _mockBookLibraryTypeScanner;
|
||||
private readonly IMusicLibraryTypeScanner _mockMusicLibraryTypeScanner;
|
||||
private readonly ServiceProvider _serviceProvider;
|
||||
private readonly MediaLibraryScannerFactory _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaLibraryScannerFactoryTests"/> class.
|
||||
/// </summary>
|
||||
public MediaLibraryScannerFactoryTests()
|
||||
{
|
||||
_mockBookLibraryTypeScanner = Substitute.For<IBookLibraryTypeScanner>();
|
||||
_mockMusicLibraryTypeScanner = Substitute.For<IMusicLibraryTypeScanner>();
|
||||
|
||||
ServiceCollection services = new();
|
||||
services.AddSingleton(_mockBookLibraryTypeScanner);
|
||||
services.AddSingleton(_mockMusicLibraryTypeScanner);
|
||||
_serviceProvider = services.BuildServiceProvider();
|
||||
_sut = new MediaLibraryScannerFactory(_serviceProvider);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateLibraryScanner_WhenLibraryTypeIsBook_ShouldReturnBookLibraryTypeScanner()
|
||||
{
|
||||
// Act
|
||||
Result<IMediaTypeScanner> result = _sut.CreateLibraryScanner(LibraryType.Book);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Same(_mockBookLibraryTypeScanner, result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateLibraryScanner_WhenLibraryTypeIsMusic_ShouldReturnMusicLibraryTypeScanner()
|
||||
{
|
||||
// Act
|
||||
Result<IMediaTypeScanner> result = _sut.CreateLibraryScanner(LibraryType.Music);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Same(_mockMusicLibraryTypeScanner, result.Value);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(LibraryType.EBook)] // EBook scanner is not implemented.
|
||||
[InlineData(LibraryType.ComicBook)] // Comic book scanner is not implemented.
|
||||
[InlineData(LibraryType.Magazine)] // Magazine scanner is not implemented.
|
||||
[InlineData(LibraryType.Newspaper)] // Newspaper scanner is not implemented.
|
||||
[InlineData(LibraryType.Manga)] // Manga scanner is not implemented.
|
||||
[InlineData(LibraryType.GraphicNovel)] // Graphic novel scanner is not implemented.
|
||||
[InlineData(LibraryType.AcademicPaper)] // Academic paper scanner is not implemented.
|
||||
[InlineData(LibraryType.SheetMusic)] // Sheet music scanner is not implemented.
|
||||
[InlineData(LibraryType.Movie)] // Movie scanner is not implemented.
|
||||
[InlineData(LibraryType.TvShow)] // TV show scanner is not implemented.
|
||||
[InlineData(LibraryType.Documentary)] // Documentary scanner is not implemented.
|
||||
[InlineData(LibraryType.Anime)] // Anime scanner is not implemented.
|
||||
[InlineData(LibraryType.ConcertVideo)] // Concert video scanner is not implemented.
|
||||
[InlineData(LibraryType.TutorialVideo)] // Tutorial video scanner is not implemented.
|
||||
[InlineData(LibraryType.HomeVideo)] // Home video scanner is not implemented.
|
||||
[InlineData(LibraryType.YouTubeVideo)] // YouTube video scanner is not implemented.
|
||||
[InlineData(LibraryType.MusicVideo)] // Music video scanner is not implemented.
|
||||
[InlineData(LibraryType.LiveRecordingVideo)] // Live recording video scanner is not implemented.
|
||||
[InlineData(LibraryType.InterviewVideo)] // Interview video scanner is not implemented.
|
||||
[InlineData(LibraryType.CoverSongVideo)] // Cover song video scanner is not implemented.
|
||||
[InlineData(LibraryType.PodcastVideo)] // Podcast video scanner is not implemented.
|
||||
[InlineData(LibraryType.Audiobook)] // Audiobook scanner is not implemented.
|
||||
[InlineData(LibraryType.LiveRecordingAudio)] // Live recording audio scanner is not implemented.
|
||||
[InlineData(LibraryType.InterviewAudio)] // Interview audio scanner is not implemented.
|
||||
[InlineData(LibraryType.CoverSongAudio)] // Cover song audio scanner is not implemented.
|
||||
[InlineData(LibraryType.Remix)] // Remix scanner is not implemented.
|
||||
[InlineData(LibraryType.SoundEffect)] // Sound effect scanner is not implemented.
|
||||
[InlineData(LibraryType.PodcastAudio)] // Podcast audio scanner is not implemented.
|
||||
[InlineData(LibraryType.Photo)] // Photo scanner is not implemented.
|
||||
[InlineData(LibraryType.Playlist)] // Playlist scanner is not implemented.
|
||||
[InlineData(LibraryType.Collection)] // Collection scanner is not implemented.
|
||||
[InlineData(LibraryType.Subtitles)] // Subtitles scanner is not implemented.
|
||||
[InlineData(LibraryType.Lyrics)] // Lyrics scanner is not implemented.
|
||||
public void CreateLibraryScanner_WhenLibraryTypeIsNotImplemented_ShouldReturnNoScannerError(LibraryType libraryType)
|
||||
{
|
||||
// Act
|
||||
Result<IMediaTypeScanner> result = _sut.CreateLibraryScanner(libraryType);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.LibraryScanning.NoScannerForLibraryType, result.FirstError);
|
||||
Assert.IsType<NotImplementedError>(result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateLibraryScanner_WhenLibraryTypeIsNotImplemented_ShouldNotThrow()
|
||||
{
|
||||
// Act
|
||||
Exception? exception = Record.Exception(() => _sut.CreateLibraryScanner(LibraryType.Movie));
|
||||
|
||||
// Assert
|
||||
Assert.Null(exception);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateLibraryScanner_WhenLibraryTypeIsUnknown_ShouldReturnNoScannerError()
|
||||
{
|
||||
// Act
|
||||
Result<IMediaTypeScanner> result = _sut.CreateLibraryScanner((LibraryType)999);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.LibraryScanning.NoScannerForLibraryType, result.FirstError);
|
||||
Assert.IsType<NotImplementedError>(result.FirstError);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the test dependencies.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_serviceProvider.Dispose();
|
||||
}
|
||||
}
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="LibraryPathPartDefinition"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LibraryPathPartDefinitionTests
|
||||
{
|
||||
private readonly LibraryPathPartDefinitionFixture _libraryPathPartDefinitionFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenCalled_ShouldSetAllProperties()
|
||||
{
|
||||
// Act
|
||||
LibraryPathPartDefinition definition = new(LibraryPathPartKind.TrackNumber, LibraryPathValueType.Integer, "{0:00}", isOptionalByDefault: true);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryPathPartKind.TrackNumber, definition.Kind);
|
||||
Assert.Equal(LibraryPathValueType.Integer, definition.ValueType);
|
||||
Assert.Equal("{0:00}", definition.DefaultRepresentation);
|
||||
Assert.True(definition.IsOptionalByDefault);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithSameValues_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
LibraryPathPartDefinition firstDefinition = _libraryPathPartDefinitionFixture.Create(
|
||||
kind: LibraryPathPartKind.Artist,
|
||||
valueType: LibraryPathValueType.Text,
|
||||
defaultRepresentation: "{0}",
|
||||
isOptionalByDefault: false);
|
||||
|
||||
// Act
|
||||
LibraryPathPartDefinition secondDefinition = _libraryPathPartDefinitionFixture.Create(
|
||||
kind: LibraryPathPartKind.Artist,
|
||||
valueType: LibraryPathValueType.Text,
|
||||
defaultRepresentation: "{0}",
|
||||
isOptionalByDefault: false);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(firstDefinition, secondDefinition);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentKind_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
LibraryPathPartDefinition firstDefinition = _libraryPathPartDefinitionFixture.Create(
|
||||
kind: LibraryPathPartKind.Artist,
|
||||
valueType: LibraryPathValueType.Text,
|
||||
defaultRepresentation: "{0}");
|
||||
|
||||
// Act
|
||||
LibraryPathPartDefinition secondDefinition = _libraryPathPartDefinitionFixture.Create(
|
||||
kind: LibraryPathPartKind.ReleaseName,
|
||||
valueType: LibraryPathValueType.Text,
|
||||
defaultRepresentation: "{0}");
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstDefinition, secondDefinition);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentValueType_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
LibraryPathPartDefinition firstDefinition = _libraryPathPartDefinitionFixture.Create(
|
||||
kind: LibraryPathPartKind.TrackNumber,
|
||||
valueType: LibraryPathValueType.Integer,
|
||||
defaultRepresentation: "{0}");
|
||||
|
||||
// Act
|
||||
LibraryPathPartDefinition secondDefinition = _libraryPathPartDefinitionFixture.Create(
|
||||
kind: LibraryPathPartKind.TrackNumber,
|
||||
valueType: LibraryPathValueType.Text,
|
||||
defaultRepresentation: "{0}");
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstDefinition, secondDefinition);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentDefaultRepresentation_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
LibraryPathPartDefinition firstDefinition = _libraryPathPartDefinitionFixture.Create(
|
||||
kind: LibraryPathPartKind.ReleaseYear,
|
||||
valueType: LibraryPathValueType.Year,
|
||||
defaultRepresentation: "{0}");
|
||||
|
||||
// Act
|
||||
LibraryPathPartDefinition secondDefinition = _libraryPathPartDefinitionFixture.Create(
|
||||
kind: LibraryPathPartKind.ReleaseYear,
|
||||
valueType: LibraryPathValueType.Year,
|
||||
defaultRepresentation: "Year {0}");
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstDefinition, secondDefinition);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentIsOptionalByDefault_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
LibraryPathPartDefinition firstDefinition = _libraryPathPartDefinitionFixture.Create(
|
||||
kind: LibraryPathPartKind.DiscNumber,
|
||||
valueType: LibraryPathValueType.Integer,
|
||||
defaultRepresentation: "{0:00}",
|
||||
isOptionalByDefault: false);
|
||||
|
||||
// Act
|
||||
LibraryPathPartDefinition secondDefinition = _libraryPathPartDefinitionFixture.Create(
|
||||
kind: LibraryPathPartKind.DiscNumber,
|
||||
valueType: LibraryPathValueType.Integer,
|
||||
defaultRepresentation: "{0:00}",
|
||||
isOptionalByDefault: true);
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstDefinition, secondDefinition);
|
||||
}
|
||||
}
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaLibraryScanCompositeId"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaLibraryScanCompositeIdTests
|
||||
{
|
||||
private readonly ScanIdFixture _scanIdFixture = new();
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithScanIdAndUserId_ShouldCreateCompositeIdWithThoseValues()
|
||||
{
|
||||
// Arrange
|
||||
ScanId scanId = _scanIdFixture.Create();
|
||||
UserId userId = _userIdFixture.Create();
|
||||
|
||||
// Act
|
||||
MediaLibraryScanCompositeId compositeId = MediaLibraryScanCompositeId.Create(scanId, userId);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(scanId, compositeId.ScanId);
|
||||
Assert.Equal(userId, compositeId.UserId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithSameValues_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
ScanId scanId = _scanIdFixture.Create();
|
||||
UserId userId = _userIdFixture.Create();
|
||||
|
||||
// Act
|
||||
MediaLibraryScanCompositeId firstId = _mediaLibraryScanCompositeIdFixture.Create(scanId: scanId, userId: userId);
|
||||
MediaLibraryScanCompositeId secondId = _mediaLibraryScanCompositeIdFixture.Create(scanId: scanId, userId: userId);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(firstId, secondId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentScanId_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
UserId userId = _userIdFixture.Create();
|
||||
|
||||
// Act
|
||||
MediaLibraryScanCompositeId firstId = _mediaLibraryScanCompositeIdFixture.Create(userId: userId);
|
||||
MediaLibraryScanCompositeId secondId = _mediaLibraryScanCompositeIdFixture.Create(userId: userId);
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstId, secondId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetHashCode_WithSameValues_ShouldReturnSameHashCode()
|
||||
{
|
||||
// Arrange
|
||||
ScanId scanId = _scanIdFixture.Create();
|
||||
UserId userId = _userIdFixture.Create();
|
||||
|
||||
// Act
|
||||
MediaLibraryScanCompositeId firstId = _mediaLibraryScanCompositeIdFixture.Create(scanId: scanId, userId: userId);
|
||||
MediaLibraryScanCompositeId secondId = _mediaLibraryScanCompositeIdFixture.Create(scanId: scanId, userId: userId);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(firstId.GetHashCode(), secondId.GetHashCode());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToString_WhenCalled_ShouldReturnFormattedString()
|
||||
{
|
||||
// Arrange
|
||||
ScanId scanId = _scanIdFixture.Create();
|
||||
UserId userId = _userIdFixture.Create();
|
||||
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(scanId: scanId, userId: userId);
|
||||
|
||||
// Act
|
||||
string result = compositeId.ToString();
|
||||
|
||||
// Assert
|
||||
Assert.Equal($"{scanId}-{userId}", result);
|
||||
}
|
||||
}
|
||||
+132
@@ -0,0 +1,132 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaLibraryScanJobProgress"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaLibraryScanJobProgressTests
|
||||
{
|
||||
private readonly MediaLibraryScanJobProgressFixture _mediaLibraryScanJobProgressFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithValidValues_ShouldCreateJobProgressWithExpectedValues()
|
||||
{
|
||||
// Act
|
||||
Result<MediaLibraryScanJobProgress> result = MediaLibraryScanJobProgress.Create(completedItems: 2, totalItems: 10, "Scanning files");
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(2, result.Value.CompletedItems);
|
||||
Assert.Equal(10, result.Value.TotalItems);
|
||||
Assert.Equal("Scanning files", result.Value.CurrentOperation);
|
||||
Assert.Equal(20, result.Value.ProgressPercentage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenTotalItemsIsZero_ShouldCreateJobProgressWithZeroPercentage()
|
||||
{
|
||||
// Act
|
||||
Result<MediaLibraryScanJobProgress> result = MediaLibraryScanJobProgress.Create(completedItems: 0, totalItems: 0, "Scanning files");
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(0, result.Value.ProgressPercentage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenTotalItemsIsNegative_ShouldReturnError()
|
||||
{
|
||||
// Act
|
||||
Result<MediaLibraryScanJobProgress> result = MediaLibraryScanJobProgress.Create(completedItems: 0, totalItems: -1, "Scanning files");
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.LibraryScanning.TotalScanJobItemsCountMustBePositive, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCompletedItemsIsNegative_ShouldReturnError()
|
||||
{
|
||||
// Act
|
||||
Result<MediaLibraryScanJobProgress> result = MediaLibraryScanJobProgress.Create(completedItems: -1, totalItems: 10, "Scanning files");
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.LibraryScanning.CompletedScanJobItemsCountMustBePositive, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCompletedItemsExceedsTotalItems_ShouldReturnError()
|
||||
{
|
||||
// Act
|
||||
Result<MediaLibraryScanJobProgress> result = MediaLibraryScanJobProgress.Create(completedItems: 11, totalItems: 10, "Scanning files");
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.LibraryScanning.CompletedScanJobItemsCountCantExceedTotalScanJobItemsCount, result.FirstError);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // Null current operation.
|
||||
[InlineData("")] // Empty current operation.
|
||||
[InlineData(" ")] // Whitespace current operation.
|
||||
public void Create_WhenCurrentOperationIsEmpty_ShouldReturnError(string? currentOperation)
|
||||
{
|
||||
// Act
|
||||
Result<MediaLibraryScanJobProgress> result = MediaLibraryScanJobProgress.Create(completedItems: 1, totalItems: 10, currentOperation!);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.LibraryScanning.ScanJobCurrentOperationCannotBeEmpty, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithSameValues_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibraryScanJobProgress firstProgress = _mediaLibraryScanJobProgressFixture.Create(completedItems: 2, totalItems: 10, currentOperation: "Scanning files");
|
||||
MediaLibraryScanJobProgress secondProgress = _mediaLibraryScanJobProgressFixture.Create(completedItems: 2, totalItems: 10, currentOperation: "Scanning files");
|
||||
|
||||
// Act
|
||||
bool result = firstProgress.Equals(secondProgress);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentCurrentOperation_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibraryScanJobProgress firstProgress = _mediaLibraryScanJobProgressFixture.Create(completedItems: 2, totalItems: 10, currentOperation: "Scanning files");
|
||||
MediaLibraryScanJobProgress secondProgress = _mediaLibraryScanJobProgressFixture.Create(completedItems: 2, totalItems: 10, currentOperation: "Hashing files");
|
||||
|
||||
// Act
|
||||
bool result = firstProgress.Equals(secondProgress);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToString_WhenCalled_ShouldReturnFormattedString()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibraryScanJobProgress jobProgress = _mediaLibraryScanJobProgressFixture.Create(completedItems: 2, totalItems: 10, currentOperation: "Scanning files");
|
||||
|
||||
// Act
|
||||
string result = jobProgress.ToString();
|
||||
|
||||
// Assert
|
||||
Assert.Equal("CompletedItems: 2; TotalItems: 10; CurrentOperation: Scanning files", result);
|
||||
}
|
||||
}
|
||||
+258
@@ -0,0 +1,258 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaLibraryScanProgress"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaLibraryScanProgressTests
|
||||
{
|
||||
private readonly ScanIdFixture _scanIdFixture = new();
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly MediaLibraryScanJobProgressFixture _mediaLibraryScanJobProgressFixture = new();
|
||||
private readonly MediaLibraryScanProgressFixture _mediaLibraryScanProgressFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithValidValues_ShouldCreateProgressWithExpectedValues()
|
||||
{
|
||||
// Arrange
|
||||
ScanId scanId = _scanIdFixture.Create();
|
||||
UserId userId = _userIdFixture.Create();
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
Optional<MediaLibraryScanJobProgress> currentJobProgress = Optional<MediaLibraryScanJobProgress>.Some(_mediaLibraryScanJobProgressFixture.Create());
|
||||
|
||||
// Act
|
||||
Result<MediaLibraryScanProgress> result = MediaLibraryScanProgress.Create(scanId, userId, libraryId, completedJobs: 2, totalJobs: 5, LibraryScanJobStatus.Running, currentJobProgress);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(scanId, result.Value.ScanId);
|
||||
Assert.Equal(userId, result.Value.UserId);
|
||||
Assert.Equal(libraryId, result.Value.LibraryId);
|
||||
Assert.Equal(2, result.Value.CompletedJobs);
|
||||
Assert.Equal(5, result.Value.TotalJobs);
|
||||
Assert.Equal(LibraryScanJobStatus.Running, result.Value.Status);
|
||||
Assert.True(result.Value.CurrentJobProgress.HasValue);
|
||||
Assert.Equal(40, result.Value.OverallProgressPercentage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithDefaults_ShouldUsePendingStatusAndNoCurrentJobProgress()
|
||||
{
|
||||
// Act
|
||||
Result<MediaLibraryScanProgress> result = MediaLibraryScanProgress.Create(
|
||||
_scanIdFixture.Create(),
|
||||
_userIdFixture.Create(),
|
||||
_libraryIdFixture.Create(),
|
||||
completedJobs: 0,
|
||||
totalJobs: 1,
|
||||
LibraryScanJobStatus.Pending,
|
||||
Optional<MediaLibraryScanJobProgress>.None());
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(LibraryScanJobStatus.Pending, result.Value.Status);
|
||||
Assert.False(result.Value.CurrentJobProgress.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenTotalJobsIsZeroAndStatusIsPending_ShouldCreateQueuedProgress()
|
||||
{
|
||||
// Act
|
||||
Result<MediaLibraryScanProgress> result = MediaLibraryScanProgress.Create(
|
||||
_scanIdFixture.Create(),
|
||||
_userIdFixture.Create(),
|
||||
_libraryIdFixture.Create(),
|
||||
completedJobs: 0,
|
||||
totalJobs: 0,
|
||||
LibraryScanJobStatus.Pending,
|
||||
Optional<MediaLibraryScanJobProgress>.None());
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(0, result.Value.TotalJobs);
|
||||
Assert.Equal(LibraryScanJobStatus.Pending, result.Value.Status);
|
||||
Assert.Equal(0, result.Value.OverallProgressPercentage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenTotalJobsIsNegative_ShouldReturnError()
|
||||
{
|
||||
// Act
|
||||
Result<MediaLibraryScanProgress> result = MediaLibraryScanProgress.Create(
|
||||
_scanIdFixture.Create(),
|
||||
_userIdFixture.Create(),
|
||||
_libraryIdFixture.Create(),
|
||||
completedJobs: 0,
|
||||
totalJobs: -1,
|
||||
LibraryScanJobStatus.Pending,
|
||||
Optional<MediaLibraryScanJobProgress>.None());
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.LibraryScanning.TotalScanJobsCountMustBePositive, result.FirstError);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(LibraryScanJobStatus.Running)] // Only a scan that is still queued may have no jobs yet.
|
||||
[InlineData(LibraryScanJobStatus.Completed)] // A completed scan must have had at least one job.
|
||||
[InlineData(LibraryScanJobStatus.Canceled)] // A canceled scan must have had at least one job.
|
||||
[InlineData(LibraryScanJobStatus.Failed)] // A failed scan must have had at least one job.
|
||||
public void Create_WhenTotalJobsIsZeroAndStatusIsNotPending_ShouldReturnError(LibraryScanJobStatus status)
|
||||
{
|
||||
// Act
|
||||
Result<MediaLibraryScanProgress> result = MediaLibraryScanProgress.Create(
|
||||
_scanIdFixture.Create(),
|
||||
_userIdFixture.Create(),
|
||||
_libraryIdFixture.Create(),
|
||||
completedJobs: 0,
|
||||
totalJobs: 0,
|
||||
status,
|
||||
Optional<MediaLibraryScanJobProgress>.None());
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.LibraryScanning.TotalScanJobsCountMustBePositive, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCompletedJobsIsNegative_ShouldReturnError()
|
||||
{
|
||||
// Act
|
||||
Result<MediaLibraryScanProgress> result = MediaLibraryScanProgress.Create(
|
||||
_scanIdFixture.Create(),
|
||||
_userIdFixture.Create(),
|
||||
_libraryIdFixture.Create(),
|
||||
completedJobs: -1,
|
||||
totalJobs: 5,
|
||||
LibraryScanJobStatus.Pending,
|
||||
Optional<MediaLibraryScanJobProgress>.None());
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.LibraryScanning.CompletedScanJobsCountMustBePositive, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCompletedJobsExceedsTotalJobs_ShouldReturnError()
|
||||
{
|
||||
// Act
|
||||
Result<MediaLibraryScanProgress> result = MediaLibraryScanProgress.Create(
|
||||
_scanIdFixture.Create(),
|
||||
_userIdFixture.Create(),
|
||||
_libraryIdFixture.Create(),
|
||||
completedJobs: 6,
|
||||
totalJobs: 5,
|
||||
LibraryScanJobStatus.Pending,
|
||||
Optional<MediaLibraryScanJobProgress>.None());
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.LibraryScanning.CompletedScanJobsCountCantExceedTotalScanJobsCount, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OverallProgressPercentage_WhenNoJobsCompleted_ShouldReturnZero()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibraryScanProgress scanProgress = _mediaLibraryScanProgressFixture.Create(completedJobs: 0, totalJobs: 5);
|
||||
|
||||
// Act
|
||||
decimal result = scanProgress.OverallProgressPercentage;
|
||||
|
||||
// Assert
|
||||
Assert.Equal(0, result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithSameValues_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
ScanId scanId = _scanIdFixture.Create();
|
||||
UserId userId = _userIdFixture.Create();
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
|
||||
// Act
|
||||
MediaLibraryScanProgress firstResult = _mediaLibraryScanProgressFixture.Create(
|
||||
scanId: scanId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
completedJobs: 2,
|
||||
totalJobs: 5,
|
||||
status: LibraryScanJobStatus.Running,
|
||||
currentJobProgress: Optional<MediaLibraryScanJobProgress>.None());
|
||||
MediaLibraryScanProgress secondResult = _mediaLibraryScanProgressFixture.Create(
|
||||
scanId: scanId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
completedJobs: 2,
|
||||
totalJobs: 5,
|
||||
status: LibraryScanJobStatus.Running,
|
||||
currentJobProgress: Optional<MediaLibraryScanJobProgress>.None());
|
||||
|
||||
// Assert
|
||||
Assert.Equal(firstResult, secondResult);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentCompletedJobs_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
ScanId scanId = _scanIdFixture.Create();
|
||||
UserId userId = _userIdFixture.Create();
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
|
||||
// Act
|
||||
MediaLibraryScanProgress firstResult = _mediaLibraryScanProgressFixture.Create(
|
||||
scanId: scanId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
completedJobs: 2,
|
||||
totalJobs: 5,
|
||||
status: LibraryScanJobStatus.Running,
|
||||
currentJobProgress: Optional<MediaLibraryScanJobProgress>.None());
|
||||
MediaLibraryScanProgress secondResult = _mediaLibraryScanProgressFixture.Create(
|
||||
scanId: scanId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
completedJobs: 3,
|
||||
totalJobs: 5,
|
||||
status: LibraryScanJobStatus.Running,
|
||||
currentJobProgress: Optional<MediaLibraryScanJobProgress>.None());
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstResult, secondResult);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToString_WhenCalled_ShouldReturnFormattedProgressString()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibraryScanJobProgress currentJobProgress = _mediaLibraryScanJobProgressFixture.Create(completedItems: 3, totalItems: 10, currentOperation: "Hashing files");
|
||||
MediaLibraryScanProgress scanProgress = _mediaLibraryScanProgressFixture.Create(
|
||||
completedJobs: 2,
|
||||
totalJobs: 5,
|
||||
status: LibraryScanJobStatus.Running,
|
||||
currentJobProgress: Optional<MediaLibraryScanJobProgress>.Some(currentJobProgress));
|
||||
|
||||
// Act
|
||||
string result = scanProgress.ToString();
|
||||
|
||||
// Assert
|
||||
Assert.Equal("CompletedJobs: 2; TotalJobs: 5; CurrentJobProgress: CompletedItems: 3; TotalItems: 10; CurrentOperation: Hashing files", result);
|
||||
}
|
||||
}
|
||||
+230
@@ -0,0 +1,230 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ParsedLibraryPath"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ParsedLibraryPathTests
|
||||
{
|
||||
private readonly ParsedLibraryPathFixture _parsedLibraryPathFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithValues_ShouldExposeThoseValues()
|
||||
{
|
||||
// Arrange
|
||||
Dictionary<LibraryPathPartKind, string> values = new()
|
||||
{
|
||||
[LibraryPathPartKind.Artist] = "Pink Floyd",
|
||||
[LibraryPathPartKind.TrackName] = "Time"
|
||||
};
|
||||
|
||||
// Act
|
||||
ParsedLibraryPath result = ParsedLibraryPath.Create(values);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, result.Values.Count);
|
||||
Assert.Equal("Pink Floyd", result.Values[LibraryPathPartKind.Artist]);
|
||||
Assert.Equal("Time", result.Values[LibraryPathPartKind.TrackName]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetString_WhenKindIsCaptured_ShouldReturnTheTrimmedValue()
|
||||
{
|
||||
// Arrange
|
||||
ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
|
||||
{
|
||||
[LibraryPathPartKind.Artist] = " Pink Floyd "
|
||||
});
|
||||
|
||||
// Act
|
||||
Optional<string> result = parsedPath.GetString(LibraryPathPartKind.Artist);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.HasValue);
|
||||
Assert.Equal("Pink Floyd", result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetString_WhenKindIsNotCaptured_ShouldReturnNoValue()
|
||||
{
|
||||
// Arrange
|
||||
ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
|
||||
{
|
||||
[LibraryPathPartKind.Artist] = "Pink Floyd"
|
||||
});
|
||||
|
||||
// Act
|
||||
Optional<string> result = parsedPath.GetString(LibraryPathPartKind.TrackName);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetString_WhenCapturedValueIsWhitespace_ShouldReturnNoValue()
|
||||
{
|
||||
// Arrange
|
||||
ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
|
||||
{
|
||||
[LibraryPathPartKind.Artist] = " "
|
||||
});
|
||||
|
||||
// Act
|
||||
Optional<string> result = parsedPath.GetString(LibraryPathPartKind.Artist);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetInt_WhenKindIsCapturedWithAnInteger_ShouldReturnTheValue()
|
||||
{
|
||||
// Arrange
|
||||
ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
|
||||
{
|
||||
[LibraryPathPartKind.ReleaseYear] = "1973"
|
||||
});
|
||||
|
||||
// Act
|
||||
Optional<int> result = parsedPath.GetInt(LibraryPathPartKind.ReleaseYear);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.HasValue);
|
||||
Assert.Equal(1973, result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetInt_WhenKindIsNotCaptured_ShouldReturnNoValue()
|
||||
{
|
||||
// Arrange
|
||||
ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
|
||||
{
|
||||
[LibraryPathPartKind.Artist] = "Pink Floyd"
|
||||
});
|
||||
|
||||
// Act
|
||||
Optional<int> result = parsedPath.GetInt(LibraryPathPartKind.ReleaseYear);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetInt_WhenCapturedValueIsNotAnInteger_ShouldReturnNoValue()
|
||||
{
|
||||
// Arrange
|
||||
ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
|
||||
{
|
||||
[LibraryPathPartKind.ReleaseYear] = "not a year"
|
||||
});
|
||||
|
||||
// Act
|
||||
Optional<int> result = parsedPath.GetInt(LibraryPathPartKind.ReleaseYear);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDictionary_WhenCalled_ShouldReturnAllCapturedValues()
|
||||
{
|
||||
// Arrange
|
||||
Dictionary<LibraryPathPartKind, string> values = new()
|
||||
{
|
||||
[LibraryPathPartKind.Artist] = "Pink Floyd",
|
||||
[LibraryPathPartKind.TrackName] = "Time"
|
||||
};
|
||||
ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(values);
|
||||
|
||||
// Act
|
||||
IReadOnlyDictionary<LibraryPathPartKind, string> result = parsedPath.ToDictionary();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(values, result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDictionary_WhenCalled_ShouldReturnACopy()
|
||||
{
|
||||
// Arrange
|
||||
Dictionary<LibraryPathPartKind, string> values = new()
|
||||
{
|
||||
[LibraryPathPartKind.Artist] = "Pink Floyd"
|
||||
};
|
||||
ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(values);
|
||||
|
||||
// Act
|
||||
IReadOnlyDictionary<LibraryPathPartKind, string> result = parsedPath.ToDictionary();
|
||||
|
||||
// Assert
|
||||
Assert.NotSame(values, result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithSameValuesInDifferentOrder_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
ParsedLibraryPath firstPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
|
||||
{
|
||||
[LibraryPathPartKind.Artist] = "Pink Floyd",
|
||||
[LibraryPathPartKind.TrackName] = "Time"
|
||||
});
|
||||
|
||||
// Act
|
||||
ParsedLibraryPath secondPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
|
||||
{
|
||||
[LibraryPathPartKind.TrackName] = "Time",
|
||||
[LibraryPathPartKind.Artist] = "Pink Floyd"
|
||||
});
|
||||
|
||||
// Assert
|
||||
Assert.Equal(firstPath, secondPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentValues_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
ParsedLibraryPath firstPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
|
||||
{
|
||||
[LibraryPathPartKind.Artist] = "Pink Floyd"
|
||||
});
|
||||
|
||||
// Act
|
||||
ParsedLibraryPath secondPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
|
||||
{
|
||||
[LibraryPathPartKind.Artist] = "Queen"
|
||||
});
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstPath, secondPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentKeys_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
ParsedLibraryPath firstPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
|
||||
{
|
||||
[LibraryPathPartKind.Artist] = "Pink Floyd"
|
||||
});
|
||||
|
||||
// Act
|
||||
ParsedLibraryPath secondPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
|
||||
{
|
||||
[LibraryPathPartKind.Title] = "Pink Floyd"
|
||||
});
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstPath, secondPath);
|
||||
}
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ScanId"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ScanIdTests
|
||||
{
|
||||
private readonly ScanIdFixture _scanIdFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void CreateUnique_WhenCalled_ShouldReturnIdWithNonEmptyValue()
|
||||
{
|
||||
// Act
|
||||
ScanId scanId = ScanId.CreateUnique();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(scanId);
|
||||
Assert.NotEqual(default, scanId.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateUnique_WhenCalledTwice_ShouldReturnDistinctIds()
|
||||
{
|
||||
// Act
|
||||
ScanId firstId = ScanId.CreateUnique();
|
||||
ScanId secondId = ScanId.CreateUnique();
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstId.Value, secondId.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithValue_ShouldReturnIdWithThatValue()
|
||||
{
|
||||
// Arrange
|
||||
Guid value = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
ScanId scanId = ScanId.Create(value);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(value, scanId.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithSameValue_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
Guid value = Guid.NewGuid();
|
||||
ScanId firstId = _scanIdFixture.Create(value);
|
||||
ScanId secondId = _scanIdFixture.Create(value);
|
||||
|
||||
// Act
|
||||
bool result = firstId.Equals(secondId);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentValue_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
ScanId firstId = _scanIdFixture.Create();
|
||||
ScanId secondId = _scanIdFixture.Create();
|
||||
|
||||
// Act
|
||||
bool result = firstId.Equals(secondId);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
}
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="DurationThresholdConsumptionRule"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DurationThresholdConsumptionRuleTests
|
||||
{
|
||||
private readonly MovieConsumptionRuleFixture _movieConsumptionRuleFixture = new();
|
||||
private readonly DurationThresholdConsumptionRule _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DurationThresholdConsumptionRuleTests"/> class.
|
||||
/// </summary>
|
||||
public DurationThresholdConsumptionRuleTests()
|
||||
{
|
||||
_sut = _movieConsumptionRuleFixture.Create();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Counts_WhenCompletedWithZeroDuration_ShouldReturnTrue()
|
||||
{
|
||||
// Act
|
||||
bool result = _sut.Counts(ConsumptionStatus.Completed, TimeSpan.Zero, consecutivePagesRead: 0);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Counts_WhenStoppedWithDurationEqualToMinimum_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
TimeSpan consumedDuration = _sut.MinimumCountedDuration;
|
||||
|
||||
// Act
|
||||
bool result = _sut.Counts(ConsumptionStatus.Stopped, consumedDuration, consecutivePagesRead: 0);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Counts_WhenStoppedWithDurationOneTickAboveMinimum_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
TimeSpan consumedDuration = _sut.MinimumCountedDuration + TimeSpan.FromTicks(1);
|
||||
|
||||
// Act
|
||||
bool result = _sut.Counts(ConsumptionStatus.Stopped, consumedDuration, consecutivePagesRead: 0);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Counts_WhenStoppedWithDurationOneTickBelowMinimum_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
TimeSpan consumedDuration = _sut.MinimumCountedDuration - TimeSpan.FromTicks(1);
|
||||
|
||||
// Act
|
||||
bool result = _sut.Counts(ConsumptionStatus.Stopped, consumedDuration, consecutivePagesRead: 0);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Counts_WhenInProgressWithDurationEqualToMinimum_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
TimeSpan consumedDuration = _sut.MinimumCountedDuration;
|
||||
|
||||
// Act
|
||||
bool result = _sut.Counts(ConsumptionStatus.InProgress, consumedDuration, consecutivePagesRead: 0);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Counts_WhenInProgressWithDurationOneTickBelowMinimum_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
TimeSpan consumedDuration = _sut.MinimumCountedDuration - TimeSpan.FromTicks(1);
|
||||
|
||||
// Act
|
||||
bool result = _sut.Counts(ConsumptionStatus.InProgress, consumedDuration, consecutivePagesRead: 0);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Counts_WhenStoppedBelowMinimumWithLargePageCount_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
TimeSpan consumedDuration = _sut.MinimumCountedDuration - TimeSpan.FromTicks(1);
|
||||
|
||||
// Act
|
||||
bool result = _sut.Counts(ConsumptionStatus.Stopped, consumedDuration, consecutivePagesRead: 1000);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="EverySessionConsumptionRule"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class EverySessionConsumptionRuleTests
|
||||
{
|
||||
private readonly PhotoConsumptionRuleFixture _photoConsumptionRuleFixture = new();
|
||||
private readonly EverySessionConsumptionRule _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="EverySessionConsumptionRuleTests"/> class.
|
||||
/// </summary>
|
||||
public EverySessionConsumptionRuleTests()
|
||||
{
|
||||
_sut = _photoConsumptionRuleFixture.Create();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(ConsumptionStatus.InProgress)] // A session that is still running.
|
||||
[InlineData(ConsumptionStatus.Completed)] // A session that reached its completion.
|
||||
[InlineData(ConsumptionStatus.Stopped)] // A session that ended before completion.
|
||||
public void Counts_WhenSessionHasZeroDurationAndZeroPages_ShouldReturnTrue(ConsumptionStatus status)
|
||||
{
|
||||
// Act
|
||||
bool result = _sut.Counts(status, TimeSpan.Zero, consecutivePagesRead: 0);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(ConsumptionStatus.InProgress)] // A session that is still running.
|
||||
[InlineData(ConsumptionStatus.Completed)] // A session that reached its completion.
|
||||
[InlineData(ConsumptionStatus.Stopped)] // A session that ended before completion.
|
||||
public void Counts_WhenSessionHasLargeDurationAndLargePageCount_ShouldReturnTrue(ConsumptionStatus status)
|
||||
{
|
||||
// Act
|
||||
bool result = _sut.Counts(status, TimeSpan.FromHours(5), consecutivePagesRead: 1000);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
}
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaConsumptionRule"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaConsumptionRuleTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData(MediaKind.MusicTrack, typeof(MusicTrackConsumptionRule))] // Duration based rule of a music track.
|
||||
[InlineData(MediaKind.PodcastEpisode, typeof(PodcastEpisodeConsumptionRule))] // Duration based rule of a podcast episode.
|
||||
[InlineData(MediaKind.Audiobook, typeof(AudiobookConsumptionRule))] // Duration based rule of an audiobook.
|
||||
[InlineData(MediaKind.Movie, typeof(MovieConsumptionRule))] // Duration based rule of a movie.
|
||||
[InlineData(MediaKind.TvEpisode, typeof(TvEpisodeConsumptionRule))] // Duration based rule of a TV episode.
|
||||
[InlineData(MediaKind.Book, typeof(BookConsumptionRule))] // Page based rule of a book.
|
||||
[InlineData(MediaKind.Photo, typeof(PhotoConsumptionRule))] // Every session rule of a photo.
|
||||
[InlineData(MediaKind.Video, typeof(VideoConsumptionRule))] // Duration based rule of a video.
|
||||
public void For_WhenMediaKindHasARule_ShouldReturnTheRuleOfThatKind(MediaKind mediaKind, Type expectedType)
|
||||
{
|
||||
// Act
|
||||
Optional<MediaConsumptionRule> result = MediaConsumptionRule.For(mediaKind);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.HasValue);
|
||||
Assert.IsType(expectedType, result.Value);
|
||||
Assert.Equal(mediaKind, result.Value.MediaKind);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(MediaKind.None)] // The default value, which is not a valid kind for a media item.
|
||||
[InlineData((MediaKind)999)] // A value outside the declared enumeration members.
|
||||
public void For_WhenMediaKindHasNoRule_ShouldReturnNoValue(MediaKind mediaKind)
|
||||
{
|
||||
// Act
|
||||
Optional<MediaConsumptionRule> result = MediaConsumptionRule.For(mediaKind);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void For_WhenEveryDeclaredMediaKindIsNotNone_ShouldReturnTheRuleOfThatKind()
|
||||
{
|
||||
// Arrange
|
||||
MediaKind[] declaredMediaKinds = [.. Enum.GetValues<MediaKind>().Where(mediaKind => mediaKind != MediaKind.None)];
|
||||
|
||||
// Act
|
||||
Optional<MediaConsumptionRule>[] results = [.. declaredMediaKinds.Select(MediaConsumptionRule.For)];
|
||||
|
||||
// Assert
|
||||
Assert.All(results, result => Assert.True(result.HasValue));
|
||||
Assert.Equal(declaredMediaKinds, results.Select(result => result.Value.MediaKind));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(MediaKind.Movie)] // A duration based rule that resumes from a time offset.
|
||||
[InlineData(MediaKind.Book)] // A page based rule that resumes from a location.
|
||||
public void CanResume_WhenRuleHasAPositionKind_ShouldReturnTrue(MediaKind mediaKind)
|
||||
{
|
||||
// Act
|
||||
bool result = MediaConsumptionRule.For(mediaKind).Value.CanResume;
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CanResume_WhenRuleHasNoPositionKind_ShouldReturnFalse()
|
||||
{
|
||||
// Act
|
||||
bool result = MediaConsumptionRule.For(MediaKind.Photo).Value.CanResume;
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WhenRulesHaveTheSameMediaKind_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
MediaConsumptionRule firstRule = MediaConsumptionRule.For(MediaKind.MusicTrack).Value;
|
||||
MediaConsumptionRule secondRule = MediaConsumptionRule.For(MediaKind.MusicTrack).Value;
|
||||
|
||||
// Act
|
||||
bool result = firstRule.Equals(secondRule);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WhenRulesHaveDifferentMediaKinds_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
MediaConsumptionRule firstRule = MediaConsumptionRule.For(MediaKind.MusicTrack).Value;
|
||||
MediaConsumptionRule secondRule = MediaConsumptionRule.For(MediaKind.Movie).Value;
|
||||
|
||||
// Act
|
||||
bool result = firstRule.Equals(secondRule);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetHashCode_WhenRulesHaveTheSameMediaKind_ShouldBeEqual()
|
||||
{
|
||||
// Arrange
|
||||
MediaConsumptionRule firstRule = MediaConsumptionRule.For(MediaKind.MusicTrack).Value;
|
||||
MediaConsumptionRule secondRule = MediaConsumptionRule.For(MediaKind.MusicTrack).Value;
|
||||
|
||||
// Act
|
||||
int firstHashCode = firstRule.GetHashCode();
|
||||
int secondHashCode = secondRule.GetHashCode();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(firstHashCode, secondHashCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetEqualityComponents_WhenCalled_ShouldContainOnlyTheMediaKind()
|
||||
{
|
||||
// Arrange
|
||||
MediaConsumptionRule rule = MediaConsumptionRule.For(MediaKind.Movie).Value;
|
||||
|
||||
// Act
|
||||
object?[] components = [.. rule.GetEqualityComponents()];
|
||||
|
||||
// Assert
|
||||
object? component = Assert.Single(components);
|
||||
Assert.Equal(rule.MediaKind, Assert.IsType<MediaKind>(component));
|
||||
}
|
||||
}
|
||||
+164
@@ -0,0 +1,164 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaPosition"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaPositionTests
|
||||
{
|
||||
private readonly MediaPositionFixture _mediaPositionFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void CreateTimeOffset_WhenCalled_ShouldSetTimeOffsetKindAndTheOffset()
|
||||
{
|
||||
// Arrange
|
||||
TimeSpan timeOffset = TimeSpan.FromMinutes(42);
|
||||
|
||||
// Act
|
||||
MediaPosition position = MediaPosition.CreateTimeOffset(timeOffset);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(MediaPositionKind.TimeOffset, position.Kind);
|
||||
Assert.True(position.TimeOffset.HasValue);
|
||||
Assert.Equal(timeOffset, position.TimeOffset.Value);
|
||||
Assert.False(position.Location.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateLocation_WhenCalled_ShouldSetLocationKindAndTheLocation()
|
||||
{
|
||||
// Arrange
|
||||
string location = "chapter-7/page-12";
|
||||
|
||||
// Act
|
||||
MediaPosition position = MediaPosition.CreateLocation(location);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(MediaPositionKind.Location, position.Kind);
|
||||
Assert.True(position.Location.HasValue);
|
||||
Assert.Equal(location, position.Location.Value);
|
||||
Assert.False(position.TimeOffset.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateTimeOffset_WhenOffsetIsNegative_ShouldStoreTheOffsetAsGiven()
|
||||
{
|
||||
// Arrange
|
||||
TimeSpan negativeTimeOffset = TimeSpan.FromMinutes(-1);
|
||||
|
||||
// Act
|
||||
MediaPosition position = MediaPosition.CreateTimeOffset(negativeTimeOffset);
|
||||
|
||||
// Assert
|
||||
// The value object does not validate the sign of the offset, the reported value is stored as given.
|
||||
Assert.Equal(TimeSpan.FromMinutes(-1), position.TimeOffset.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateLocation_WhenLocationIsEmpty_ShouldStoreTheEmptyLocation()
|
||||
{
|
||||
// Act
|
||||
MediaPosition position = MediaPosition.CreateLocation(string.Empty);
|
||||
|
||||
// Assert
|
||||
// The value object does not validate the content of the location, the reported value is stored as given.
|
||||
Assert.True(position.Location.HasValue);
|
||||
Assert.Equal(string.Empty, position.Location.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WhenKindAndValueAreTheSame_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
MediaPosition firstPosition = _mediaPositionFixture.Create(kind: MediaPositionKind.TimeOffset, timeOffset: TimeSpan.FromMinutes(10));
|
||||
MediaPosition secondPosition = _mediaPositionFixture.Create(kind: MediaPositionKind.TimeOffset, timeOffset: TimeSpan.FromMinutes(10));
|
||||
|
||||
// Act
|
||||
bool result = firstPosition.Equals(secondPosition);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WhenTimeOffsetDiffers_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
MediaPosition firstPosition = _mediaPositionFixture.Create(kind: MediaPositionKind.TimeOffset, timeOffset: TimeSpan.FromMinutes(10));
|
||||
MediaPosition secondPosition = _mediaPositionFixture.Create(kind: MediaPositionKind.TimeOffset, timeOffset: TimeSpan.FromMinutes(11));
|
||||
|
||||
// Act
|
||||
bool result = firstPosition.Equals(secondPosition);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WhenLocationDiffers_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
MediaPosition firstPosition = _mediaPositionFixture.Create(kind: MediaPositionKind.Location, location: "chapter-1");
|
||||
MediaPosition secondPosition = _mediaPositionFixture.Create(kind: MediaPositionKind.Location, location: "chapter-2");
|
||||
|
||||
// Act
|
||||
bool result = firstPosition.Equals(secondPosition);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WhenKindDiffers_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
MediaPosition firstPosition = _mediaPositionFixture.Create(kind: MediaPositionKind.TimeOffset, timeOffset: TimeSpan.FromMinutes(10));
|
||||
MediaPosition secondPosition = _mediaPositionFixture.Create(kind: MediaPositionKind.Location, location: "chapter-1");
|
||||
|
||||
// Act
|
||||
bool result = firstPosition.Equals(secondPosition);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetHashCode_WhenKindAndValueAreTheSame_ShouldReturnSameHashCode()
|
||||
{
|
||||
// Arrange
|
||||
MediaPosition firstPosition = _mediaPositionFixture.Create(kind: MediaPositionKind.Location, location: "chapter-3");
|
||||
MediaPosition secondPosition = _mediaPositionFixture.Create(kind: MediaPositionKind.Location, location: "chapter-3");
|
||||
|
||||
// Act
|
||||
int firstHashCode = firstPosition.GetHashCode();
|
||||
int secondHashCode = secondPosition.GetHashCode();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(firstHashCode, secondHashCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetEqualityComponents_WhenCalled_ShouldYieldKindThenTimeOffsetThenLocation()
|
||||
{
|
||||
// Arrange
|
||||
MediaPosition position = _mediaPositionFixture.Create(kind: MediaPositionKind.TimeOffset);
|
||||
|
||||
// Act
|
||||
object?[] components = [.. position.GetEqualityComponents()];
|
||||
|
||||
// Assert
|
||||
Assert.Equal(3, components.Length);
|
||||
Assert.Equal(MediaPositionKind.TimeOffset, Assert.IsType<MediaPositionKind>(components[0]));
|
||||
Assert.Equal(position.TimeOffset, Assert.IsType<Optional<TimeSpan>>(components[1]));
|
||||
Assert.Equal(position.Location, Assert.IsType<Optional<string>>(components[2]));
|
||||
}
|
||||
}
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="PageThresholdConsumptionRule"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PageThresholdConsumptionRuleTests
|
||||
{
|
||||
private readonly BookConsumptionRuleFixture _bookConsumptionRuleFixture = new();
|
||||
private readonly PageThresholdConsumptionRule _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PageThresholdConsumptionRuleTests"/> class.
|
||||
/// </summary>
|
||||
public PageThresholdConsumptionRuleTests()
|
||||
{
|
||||
_sut = _bookConsumptionRuleFixture.Create();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Counts_WhenCompletedWithZeroPages_ShouldReturnTrue()
|
||||
{
|
||||
// Act
|
||||
bool result = _sut.Counts(ConsumptionStatus.Completed, TimeSpan.Zero, consecutivePagesRead: 0);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Counts_WhenStoppedWithPagesEqualToMinimum_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
int consecutivePagesRead = _sut.MinimumConsecutivePages;
|
||||
|
||||
// Act
|
||||
bool result = _sut.Counts(ConsumptionStatus.Stopped, TimeSpan.Zero, consecutivePagesRead);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Counts_WhenStoppedWithPagesOneAboveMinimum_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
int consecutivePagesRead = _sut.MinimumConsecutivePages + 1;
|
||||
|
||||
// Act
|
||||
bool result = _sut.Counts(ConsumptionStatus.Stopped, TimeSpan.Zero, consecutivePagesRead);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Counts_WhenInProgressWithPagesEqualToMinimum_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
int consecutivePagesRead = _sut.MinimumConsecutivePages;
|
||||
|
||||
// Act
|
||||
bool result = _sut.Counts(ConsumptionStatus.InProgress, TimeSpan.Zero, consecutivePagesRead);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Counts_WhenInProgressWithPagesOneAboveMinimum_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
int consecutivePagesRead = _sut.MinimumConsecutivePages + 1;
|
||||
|
||||
// Act
|
||||
bool result = _sut.Counts(ConsumptionStatus.InProgress, TimeSpan.Zero, consecutivePagesRead);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Counts_WhenStoppedWithLargeDurationAndPagesEqualToMinimum_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
TimeSpan consumedDuration = TimeSpan.FromHours(5);
|
||||
int consecutivePagesRead = _sut.MinimumConsecutivePages;
|
||||
|
||||
// Act
|
||||
bool result = _sut.Counts(ConsumptionStatus.Stopped, consumedDuration, consecutivePagesRead);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.MediaConsumptionBoundedContext.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.NotNull(libraryId);
|
||||
Assert.NotEqual(default, 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 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);
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaItemId"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaItemIdTests
|
||||
{
|
||||
private readonly MediaItemIdFixture _mediaItemIdFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void CreateUnique_WhenCalled_ShouldReturnIdWithNonEmptyValue()
|
||||
{
|
||||
// Act
|
||||
MediaItemId mediaItemId = MediaItemId.CreateUnique();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(mediaItemId);
|
||||
Assert.NotEqual(default, mediaItemId.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithValue_ShouldReturnIdWithThatValue()
|
||||
{
|
||||
// Arrange
|
||||
Guid value = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
MediaItemId mediaItemId = MediaItemId.Create(value);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(value, mediaItemId.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithSameValue_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
Guid value = Guid.NewGuid();
|
||||
MediaItemId firstId = _mediaItemIdFixture.Create(value);
|
||||
MediaItemId secondId = _mediaItemIdFixture.Create(value);
|
||||
|
||||
// Act
|
||||
bool result = firstId.Equals(secondId);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentValue_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
MediaItemId firstId = _mediaItemIdFixture.Create();
|
||||
MediaItemId secondId = _mediaItemIdFixture.Create();
|
||||
|
||||
// Act
|
||||
bool result = firstId.Equals(secondId);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="UserId"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UserIdTests
|
||||
{
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void CreateUnique_WhenCalled_ShouldReturnIdWithNonEmptyValue()
|
||||
{
|
||||
// Act
|
||||
UserId userId = UserId.CreateUnique();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(userId);
|
||||
Assert.NotEqual(default, userId.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithValue_ShouldReturnIdWithThatValue()
|
||||
{
|
||||
// Arrange
|
||||
Guid value = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
UserId userId = UserId.Create(value);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(value, userId.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithSameValue_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
Guid value = Guid.NewGuid();
|
||||
UserId firstId = _userIdFixture.Create(value);
|
||||
UserId secondId = _userIdFixture.Create(value);
|
||||
|
||||
// Act
|
||||
bool result = firstId.Equals(secondId);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentValue_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
UserId firstId = _userIdFixture.Create();
|
||||
UserId secondId = _userIdFixture.Create();
|
||||
|
||||
// Act
|
||||
bool result = firstId.Equals(secondId);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.Events;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.Events;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaConsumptionCompletedDomainEvent"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaConsumptionCompletedDomainEventTests
|
||||
{
|
||||
private readonly MediaConsumptionRecordIdFixture _mediaConsumptionRecordIdFixture = new();
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly MediaItemIdFixture _mediaItemIdFixture = new();
|
||||
private readonly MediaPositionFixture _mediaPositionFixture = new();
|
||||
private readonly MediaConsumptionCompletedDomainEventFixture _mediaConsumptionCompletedDomainEventFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenCalled_ShouldSetAllProperties()
|
||||
{
|
||||
// Arrange
|
||||
Guid id = Guid.NewGuid();
|
||||
MediaConsumptionRecordId mediaConsumptionRecordId = _mediaConsumptionRecordIdFixture.Create();
|
||||
UserId userId = _userIdFixture.Create();
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
MediaItemId mediaItemId = _mediaItemIdFixture.Create();
|
||||
MediaPosition lastPosition = _mediaPositionFixture.Create(kind: MediaPositionKind.Location);
|
||||
double lastProgressFraction = 1.0;
|
||||
TimeSpan consumedDuration = TimeSpan.FromHours(2);
|
||||
int consecutivePagesRead = 12;
|
||||
DateTime occurredOnUtc = DateTime.UtcNow;
|
||||
|
||||
// Act
|
||||
MediaConsumptionCompletedDomainEvent domainEvent = _mediaConsumptionCompletedDomainEventFixture.Create(
|
||||
id,
|
||||
mediaConsumptionRecordId,
|
||||
userId,
|
||||
libraryId,
|
||||
mediaItemId,
|
||||
MediaKind.Book,
|
||||
lastPosition: Optional<MediaPosition>.Some(lastPosition),
|
||||
lastProgressFraction: lastProgressFraction,
|
||||
consumedDuration: consumedDuration,
|
||||
consecutivePagesRead: consecutivePagesRead,
|
||||
occurredOnUtc: occurredOnUtc);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(id, domainEvent.Id);
|
||||
Assert.Equal(mediaConsumptionRecordId, domainEvent.MediaConsumptionRecordId);
|
||||
Assert.Equal(userId, domainEvent.UserId);
|
||||
Assert.Equal(libraryId, domainEvent.LibraryId);
|
||||
Assert.Equal(mediaItemId, domainEvent.MediaItemId);
|
||||
Assert.Equal(MediaKind.Book, domainEvent.MediaKind);
|
||||
Assert.Equal(Optional<MediaPosition>.Some(lastPosition), domainEvent.LastPosition);
|
||||
Assert.Equal(lastProgressFraction, domainEvent.LastProgressFraction);
|
||||
Assert.Equal(consumedDuration, domainEvent.ConsumedDuration);
|
||||
Assert.Equal(consecutivePagesRead, domainEvent.ConsecutivePagesRead);
|
||||
Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc);
|
||||
Assert.IsType<IDomainEvent>(domainEvent, exactMatch: false);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenLastPositionIsAbsent_ShouldSetNoLastPosition()
|
||||
{
|
||||
// Arrange
|
||||
MediaConsumptionCompletedDomainEvent domainEvent = _mediaConsumptionCompletedDomainEventFixture.Create(mediaKind: MediaKind.Photo);
|
||||
|
||||
// Act
|
||||
Optional<MediaPosition> lastPosition = domainEvent.LastPosition;
|
||||
|
||||
// Assert
|
||||
Assert.False(lastPosition.HasValue);
|
||||
}
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.Events;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.Events;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaConsumptionProgressedDomainEvent"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaConsumptionProgressedDomainEventTests
|
||||
{
|
||||
private readonly MediaConsumptionRecordIdFixture _mediaConsumptionRecordIdFixture = new();
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly MediaItemIdFixture _mediaItemIdFixture = new();
|
||||
private readonly MediaPositionFixture _mediaPositionFixture = new();
|
||||
private readonly MediaConsumptionProgressedDomainEventFixture _mediaConsumptionProgressedDomainEventFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenCalled_ShouldSetAllProperties()
|
||||
{
|
||||
// Arrange
|
||||
Guid id = Guid.NewGuid();
|
||||
MediaConsumptionRecordId mediaConsumptionRecordId = _mediaConsumptionRecordIdFixture.Create();
|
||||
UserId userId = _userIdFixture.Create();
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
MediaItemId mediaItemId = _mediaItemIdFixture.Create();
|
||||
MediaPosition lastPosition = _mediaPositionFixture.Create(kind: MediaPositionKind.TimeOffset);
|
||||
double lastProgressFraction = 0.4;
|
||||
TimeSpan consumedDuration = TimeSpan.FromMinutes(25);
|
||||
int consecutivePagesRead = 0;
|
||||
DateTime occurredOnUtc = DateTime.UtcNow;
|
||||
|
||||
// Act
|
||||
MediaConsumptionProgressedDomainEvent domainEvent = _mediaConsumptionProgressedDomainEventFixture.Create(
|
||||
id,
|
||||
mediaConsumptionRecordId,
|
||||
userId,
|
||||
libraryId,
|
||||
mediaItemId,
|
||||
MediaKind.Movie,
|
||||
lastPosition: Optional<MediaPosition>.Some(lastPosition),
|
||||
lastProgressFraction: lastProgressFraction,
|
||||
consumedDuration: consumedDuration,
|
||||
consecutivePagesRead: consecutivePagesRead,
|
||||
occurredOnUtc: occurredOnUtc);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(id, domainEvent.Id);
|
||||
Assert.Equal(mediaConsumptionRecordId, domainEvent.MediaConsumptionRecordId);
|
||||
Assert.Equal(userId, domainEvent.UserId);
|
||||
Assert.Equal(libraryId, domainEvent.LibraryId);
|
||||
Assert.Equal(mediaItemId, domainEvent.MediaItemId);
|
||||
Assert.Equal(MediaKind.Movie, domainEvent.MediaKind);
|
||||
Assert.Equal(Optional<MediaPosition>.Some(lastPosition), domainEvent.LastPosition);
|
||||
Assert.Equal(lastProgressFraction, domainEvent.LastProgressFraction);
|
||||
Assert.Equal(consumedDuration, domainEvent.ConsumedDuration);
|
||||
Assert.Equal(consecutivePagesRead, domainEvent.ConsecutivePagesRead);
|
||||
Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc);
|
||||
Assert.IsType<IDomainEvent>(domainEvent, exactMatch: false);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenLastPositionIsAbsent_ShouldSetNoLastPosition()
|
||||
{
|
||||
// Arrange
|
||||
MediaConsumptionProgressedDomainEvent domainEvent = _mediaConsumptionProgressedDomainEventFixture.Create(mediaKind: MediaKind.Movie);
|
||||
|
||||
// Act
|
||||
Optional<MediaPosition> lastPosition = domainEvent.LastPosition;
|
||||
|
||||
// Assert
|
||||
Assert.False(lastPosition.HasValue);
|
||||
}
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.Events;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.Events;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaConsumptionStartedDomainEvent"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaConsumptionStartedDomainEventTests
|
||||
{
|
||||
private readonly MediaConsumptionRecordIdFixture _mediaConsumptionRecordIdFixture = new();
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly MediaItemIdFixture _mediaItemIdFixture = new();
|
||||
private readonly MediaConsumptionStartedDomainEventFixture _mediaConsumptionStartedDomainEventFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenCalled_ShouldSetAllProperties()
|
||||
{
|
||||
// Arrange
|
||||
Guid id = Guid.NewGuid();
|
||||
MediaConsumptionRecordId mediaConsumptionRecordId = _mediaConsumptionRecordIdFixture.Create();
|
||||
UserId userId = _userIdFixture.Create();
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
MediaItemId mediaItemId = _mediaItemIdFixture.Create();
|
||||
MediaKind mediaKind = MediaKind.Movie;
|
||||
DateTime occurredOnUtc = DateTime.UtcNow;
|
||||
|
||||
// Act
|
||||
MediaConsumptionStartedDomainEvent domainEvent = _mediaConsumptionStartedDomainEventFixture.Create(
|
||||
id,
|
||||
mediaConsumptionRecordId,
|
||||
userId,
|
||||
libraryId,
|
||||
mediaItemId,
|
||||
mediaKind,
|
||||
occurredOnUtc);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(id, domainEvent.Id);
|
||||
Assert.Equal(mediaConsumptionRecordId, domainEvent.MediaConsumptionRecordId);
|
||||
Assert.Equal(userId, domainEvent.UserId);
|
||||
Assert.Equal(libraryId, domainEvent.LibraryId);
|
||||
Assert.Equal(mediaItemId, domainEvent.MediaItemId);
|
||||
Assert.Equal(mediaKind, domainEvent.MediaKind);
|
||||
Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc);
|
||||
Assert.IsType<IDomainEvent>(domainEvent, exactMatch: false);
|
||||
}
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.Events;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.Events;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaConsumptionStoppedDomainEvent"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaConsumptionStoppedDomainEventTests
|
||||
{
|
||||
private readonly MediaConsumptionRecordIdFixture _mediaConsumptionRecordIdFixture = new();
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly MediaItemIdFixture _mediaItemIdFixture = new();
|
||||
private readonly MediaPositionFixture _mediaPositionFixture = new();
|
||||
private readonly MediaConsumptionStoppedDomainEventFixture _mediaConsumptionStoppedDomainEventFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenCalled_ShouldSetAllProperties()
|
||||
{
|
||||
// Arrange
|
||||
Guid id = Guid.NewGuid();
|
||||
MediaConsumptionRecordId mediaConsumptionRecordId = _mediaConsumptionRecordIdFixture.Create();
|
||||
UserId userId = _userIdFixture.Create();
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
MediaItemId mediaItemId = _mediaItemIdFixture.Create();
|
||||
MediaPosition lastPosition = _mediaPositionFixture.Create(kind: MediaPositionKind.TimeOffset);
|
||||
double lastProgressFraction = 0.35;
|
||||
TimeSpan consumedDuration = TimeSpan.FromMinutes(18);
|
||||
int consecutivePagesRead = 0;
|
||||
DateTime occurredOnUtc = DateTime.UtcNow;
|
||||
|
||||
// Act
|
||||
MediaConsumptionStoppedDomainEvent domainEvent = _mediaConsumptionStoppedDomainEventFixture.Create(
|
||||
id,
|
||||
mediaConsumptionRecordId,
|
||||
userId,
|
||||
libraryId,
|
||||
mediaItemId,
|
||||
MediaKind.TvEpisode,
|
||||
lastPosition: Optional<MediaPosition>.Some(lastPosition),
|
||||
lastProgressFraction: lastProgressFraction,
|
||||
consumedDuration: consumedDuration,
|
||||
consecutivePagesRead: consecutivePagesRead,
|
||||
occurredOnUtc: occurredOnUtc);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(id, domainEvent.Id);
|
||||
Assert.Equal(mediaConsumptionRecordId, domainEvent.MediaConsumptionRecordId);
|
||||
Assert.Equal(userId, domainEvent.UserId);
|
||||
Assert.Equal(libraryId, domainEvent.LibraryId);
|
||||
Assert.Equal(mediaItemId, domainEvent.MediaItemId);
|
||||
Assert.Equal(MediaKind.TvEpisode, domainEvent.MediaKind);
|
||||
Assert.Equal(Optional<MediaPosition>.Some(lastPosition), domainEvent.LastPosition);
|
||||
Assert.Equal(lastProgressFraction, domainEvent.LastProgressFraction);
|
||||
Assert.Equal(consumedDuration, domainEvent.ConsumedDuration);
|
||||
Assert.Equal(consecutivePagesRead, domainEvent.ConsecutivePagesRead);
|
||||
Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc);
|
||||
Assert.IsType<IDomainEvent>(domainEvent, exactMatch: false);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenLastPositionIsAbsent_ShouldSetNoLastPosition()
|
||||
{
|
||||
// Arrange
|
||||
MediaConsumptionStoppedDomainEvent domainEvent = _mediaConsumptionStoppedDomainEventFixture.Create(mediaKind: MediaKind.Movie);
|
||||
|
||||
// Act
|
||||
Optional<MediaPosition> lastPosition = domainEvent.LastPosition;
|
||||
|
||||
// Assert
|
||||
Assert.False(lastPosition.HasValue);
|
||||
}
|
||||
}
|
||||
+1676
File diff suppressed because it is too large.
Load diff
+80
@@ -0,0 +1,80 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="AudiobookConsumptionRule"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AudiobookConsumptionRuleTests
|
||||
{
|
||||
private readonly AudiobookConsumptionRuleFixture _audiobookConsumptionRuleFixture = new();
|
||||
private readonly AudiobookConsumptionRule _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AudiobookConsumptionRuleTests"/> class.
|
||||
/// </summary>
|
||||
public AudiobookConsumptionRuleTests()
|
||||
{
|
||||
_sut = _audiobookConsumptionRuleFixture.Create();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MediaKind_WhenRead_ShouldBeAudiobook()
|
||||
{
|
||||
// Act
|
||||
MediaKind result = _sut.MediaKind;
|
||||
|
||||
// Assert
|
||||
Assert.Equal(MediaKind.Audiobook, result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsSupportedByCurrentCatalogues_WhenRead_ShouldBeFalse()
|
||||
{
|
||||
// Act
|
||||
bool result = _sut.IsSupportedByCurrentCatalogues;
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PositionKind_WhenRead_ShouldBeTimeOffset()
|
||||
{
|
||||
// Act
|
||||
Optional<MediaPositionKind> result = _sut.PositionKind;
|
||||
|
||||
// Assert
|
||||
Assert.True(result.HasValue);
|
||||
Assert.Equal(MediaPositionKind.TimeOffset, result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsOneShot_WhenRead_ShouldBeFalse()
|
||||
{
|
||||
// Act
|
||||
bool result = _sut.IsOneShot;
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MinimumCountedDuration_WhenRead_ShouldBeSixtySeconds()
|
||||
{
|
||||
// Act
|
||||
TimeSpan result = _sut.MinimumCountedDuration;
|
||||
|
||||
// Assert
|
||||
Assert.Equal(TimeSpan.FromSeconds(60), result);
|
||||
}
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="BookConsumptionRule"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class BookConsumptionRuleTests
|
||||
{
|
||||
private readonly BookConsumptionRuleFixture _bookConsumptionRuleFixture = new();
|
||||
private readonly BookConsumptionRule _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BookConsumptionRuleTests"/> class.
|
||||
/// </summary>
|
||||
public BookConsumptionRuleTests()
|
||||
{
|
||||
_sut = _bookConsumptionRuleFixture.Create();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MediaKind_WhenRead_ShouldBeBook()
|
||||
{
|
||||
// Act
|
||||
MediaKind result = _sut.MediaKind;
|
||||
|
||||
// Assert
|
||||
Assert.Equal(MediaKind.Book, result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsSupportedByCurrentCatalogues_WhenRead_ShouldBeTrue()
|
||||
{
|
||||
// Act
|
||||
bool result = _sut.IsSupportedByCurrentCatalogues;
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PositionKind_WhenRead_ShouldBeLocation()
|
||||
{
|
||||
// Act
|
||||
Optional<MediaPositionKind> result = _sut.PositionKind;
|
||||
|
||||
// Assert
|
||||
Assert.True(result.HasValue);
|
||||
Assert.Equal(MediaPositionKind.Location, result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsOneShot_WhenRead_ShouldBeFalse()
|
||||
{
|
||||
// Act
|
||||
bool result = _sut.IsOneShot;
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MinimumConsecutivePages_WhenRead_ShouldBeFive()
|
||||
{
|
||||
// Act
|
||||
int result = _sut.MinimumConsecutivePages;
|
||||
|
||||
// Assert
|
||||
Assert.Equal(5, result);
|
||||
}
|
||||
}
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaConsumptionRecordId"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaConsumptionRecordIdTests
|
||||
{
|
||||
private readonly MediaConsumptionRecordIdFixture _mediaConsumptionRecordIdFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void CreateUnique_WhenCalled_ShouldReturnIdWithNonEmptyValue()
|
||||
{
|
||||
// Act
|
||||
MediaConsumptionRecordId mediaConsumptionRecordId = MediaConsumptionRecordId.CreateUnique();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(mediaConsumptionRecordId);
|
||||
Assert.NotEqual(default, mediaConsumptionRecordId.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateUnique_WhenCalledTwice_ShouldReturnDistinctIds()
|
||||
{
|
||||
// Act
|
||||
MediaConsumptionRecordId firstId = MediaConsumptionRecordId.CreateUnique();
|
||||
MediaConsumptionRecordId secondId = MediaConsumptionRecordId.CreateUnique();
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstId.Value, secondId.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithValue_ShouldReturnIdWithThatValue()
|
||||
{
|
||||
// Arrange
|
||||
Guid value = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
MediaConsumptionRecordId mediaConsumptionRecordId = MediaConsumptionRecordId.Create(value);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(value, mediaConsumptionRecordId.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithSameValue_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
Guid value = Guid.NewGuid();
|
||||
MediaConsumptionRecordId firstId = _mediaConsumptionRecordIdFixture.Create(value);
|
||||
MediaConsumptionRecordId secondId = _mediaConsumptionRecordIdFixture.Create(value);
|
||||
|
||||
// Act
|
||||
bool result = firstId.Equals(secondId);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentValue_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
MediaConsumptionRecordId firstId = _mediaConsumptionRecordIdFixture.Create();
|
||||
MediaConsumptionRecordId secondId = _mediaConsumptionRecordIdFixture.Create();
|
||||
|
||||
// Act
|
||||
bool result = firstId.Equals(secondId);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetHashCode_WhenValuesAreEqual_ShouldReturnSameHashCode()
|
||||
{
|
||||
// Arrange
|
||||
Guid value = Guid.NewGuid();
|
||||
MediaConsumptionRecordId firstId = _mediaConsumptionRecordIdFixture.Create(value);
|
||||
MediaConsumptionRecordId secondId = _mediaConsumptionRecordIdFixture.Create(value);
|
||||
|
||||
// Act
|
||||
int firstHashCode = firstId.GetHashCode();
|
||||
int secondHashCode = secondId.GetHashCode();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(firstHashCode, secondHashCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetEqualityComponents_WhenCalled_ShouldYieldTheGuidValue()
|
||||
{
|
||||
// Arrange
|
||||
Guid value = Guid.NewGuid();
|
||||
MediaConsumptionRecordId mediaConsumptionRecordId = _mediaConsumptionRecordIdFixture.Create(value);
|
||||
|
||||
// Act
|
||||
object?[] components = [.. mediaConsumptionRecordId.GetEqualityComponents()];
|
||||
|
||||
// Assert
|
||||
object? component = Assert.Single(components);
|
||||
Assert.Equal(value, Assert.IsType<Guid>(component));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToString_WhenCalled_ShouldReturnTheGuidString()
|
||||
{
|
||||
// Arrange
|
||||
Guid value = Guid.NewGuid();
|
||||
MediaConsumptionRecordId mediaConsumptionRecordId = _mediaConsumptionRecordIdFixture.Create(value);
|
||||
|
||||
// Act
|
||||
string? result = mediaConsumptionRecordId.ToString();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(value.ToString(), result);
|
||||
}
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MovieConsumptionRule"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MovieConsumptionRuleTests
|
||||
{
|
||||
private readonly MovieConsumptionRuleFixture _movieConsumptionRuleFixture = new();
|
||||
private readonly MovieConsumptionRule _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MovieConsumptionRuleTests"/> class.
|
||||
/// </summary>
|
||||
public MovieConsumptionRuleTests()
|
||||
{
|
||||
_sut = _movieConsumptionRuleFixture.Create();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MediaKind_WhenRead_ShouldBeMovie()
|
||||
{
|
||||
// Act
|
||||
MediaKind result = _sut.MediaKind;
|
||||
|
||||
// Assert
|
||||
Assert.Equal(MediaKind.Movie, result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsSupportedByCurrentCatalogues_WhenRead_ShouldBeFalse()
|
||||
{
|
||||
// Act
|
||||
bool result = _sut.IsSupportedByCurrentCatalogues;
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PositionKind_WhenRead_ShouldBeTimeOffset()
|
||||
{
|
||||
// Act
|
||||
Optional<MediaPositionKind> result = _sut.PositionKind;
|
||||
|
||||
// Assert
|
||||
Assert.True(result.HasValue);
|
||||
Assert.Equal(MediaPositionKind.TimeOffset, result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsOneShot_WhenRead_ShouldBeFalse()
|
||||
{
|
||||
// Act
|
||||
bool result = _sut.IsOneShot;
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MinimumCountedDuration_WhenRead_ShouldBeThreeMinutes()
|
||||
{
|
||||
// Act
|
||||
TimeSpan result = _sut.MinimumCountedDuration;
|
||||
|
||||
// Assert
|
||||
Assert.Equal(TimeSpan.FromMinutes(3), result);
|
||||
}
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicTrackConsumptionRule"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicTrackConsumptionRuleTests
|
||||
{
|
||||
private readonly MusicTrackConsumptionRuleFixture _musicTrackConsumptionRuleFixture = new();
|
||||
private readonly MusicTrackConsumptionRule _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MusicTrackConsumptionRuleTests"/> class.
|
||||
/// </summary>
|
||||
public MusicTrackConsumptionRuleTests()
|
||||
{
|
||||
_sut = _musicTrackConsumptionRuleFixture.Create();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MediaKind_WhenRead_ShouldBeMusicTrack()
|
||||
{
|
||||
// Act
|
||||
MediaKind result = _sut.MediaKind;
|
||||
|
||||
// Assert
|
||||
Assert.Equal(MediaKind.MusicTrack, result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsSupportedByCurrentCatalogues_WhenRead_ShouldBeTrue()
|
||||
{
|
||||
// Act
|
||||
bool result = _sut.IsSupportedByCurrentCatalogues;
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PositionKind_WhenRead_ShouldBeTimeOffset()
|
||||
{
|
||||
// Act
|
||||
Optional<MediaPositionKind> result = _sut.PositionKind;
|
||||
|
||||
// Assert
|
||||
Assert.True(result.HasValue);
|
||||
Assert.Equal(MediaPositionKind.TimeOffset, result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsOneShot_WhenRead_ShouldBeFalse()
|
||||
{
|
||||
// Act
|
||||
bool result = _sut.IsOneShot;
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MinimumCountedDuration_WhenRead_ShouldBeThirtySeconds()
|
||||
{
|
||||
// Act
|
||||
TimeSpan result = _sut.MinimumCountedDuration;
|
||||
|
||||
// Assert
|
||||
Assert.Equal(TimeSpan.FromSeconds(30), result);
|
||||
}
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="PhotoConsumptionRule"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PhotoConsumptionRuleTests
|
||||
{
|
||||
private readonly PhotoConsumptionRuleFixture _photoConsumptionRuleFixture = new();
|
||||
private readonly PhotoConsumptionRule _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PhotoConsumptionRuleTests"/> class.
|
||||
/// </summary>
|
||||
public PhotoConsumptionRuleTests()
|
||||
{
|
||||
_sut = _photoConsumptionRuleFixture.Create();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MediaKind_WhenRead_ShouldBePhoto()
|
||||
{
|
||||
// Act
|
||||
MediaKind result = _sut.MediaKind;
|
||||
|
||||
// Assert
|
||||
Assert.Equal(MediaKind.Photo, result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsSupportedByCurrentCatalogues_WhenRead_ShouldBeFalse()
|
||||
{
|
||||
// Act
|
||||
bool result = _sut.IsSupportedByCurrentCatalogues;
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PositionKind_WhenRead_ShouldHaveNoValue()
|
||||
{
|
||||
// Act
|
||||
Optional<MediaPositionKind> result = _sut.PositionKind;
|
||||
|
||||
// Assert
|
||||
Assert.False(result.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsOneShot_WhenRead_ShouldBeTrue()
|
||||
{
|
||||
// Act
|
||||
bool result = _sut.IsOneShot;
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="PodcastEpisodeConsumptionRule"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PodcastEpisodeConsumptionRuleTests
|
||||
{
|
||||
private readonly PodcastEpisodeConsumptionRuleFixture _podcastEpisodeConsumptionRuleFixture = new();
|
||||
private readonly PodcastEpisodeConsumptionRule _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PodcastEpisodeConsumptionRuleTests"/> class.
|
||||
/// </summary>
|
||||
public PodcastEpisodeConsumptionRuleTests()
|
||||
{
|
||||
_sut = _podcastEpisodeConsumptionRuleFixture.Create();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MediaKind_WhenRead_ShouldBePodcastEpisode()
|
||||
{
|
||||
// Act
|
||||
MediaKind result = _sut.MediaKind;
|
||||
|
||||
// Assert
|
||||
Assert.Equal(MediaKind.PodcastEpisode, result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsSupportedByCurrentCatalogues_WhenRead_ShouldBeFalse()
|
||||
{
|
||||
// Act
|
||||
bool result = _sut.IsSupportedByCurrentCatalogues;
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PositionKind_WhenRead_ShouldBeTimeOffset()
|
||||
{
|
||||
// Act
|
||||
Optional<MediaPositionKind> result = _sut.PositionKind;
|
||||
|
||||
// Assert
|
||||
Assert.True(result.HasValue);
|
||||
Assert.Equal(MediaPositionKind.TimeOffset, result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsOneShot_WhenRead_ShouldBeFalse()
|
||||
{
|
||||
// Act
|
||||
bool result = _sut.IsOneShot;
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MinimumCountedDuration_WhenRead_ShouldBeThirtySeconds()
|
||||
{
|
||||
// Act
|
||||
TimeSpan result = _sut.MinimumCountedDuration;
|
||||
|
||||
// Assert
|
||||
Assert.Equal(TimeSpan.FromSeconds(30), result);
|
||||
}
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="TvEpisodeConsumptionRule"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class TvEpisodeConsumptionRuleTests
|
||||
{
|
||||
private readonly TvEpisodeConsumptionRuleFixture _tvEpisodeConsumptionRuleFixture = new();
|
||||
private readonly TvEpisodeConsumptionRule _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="TvEpisodeConsumptionRuleTests"/> class.
|
||||
/// </summary>
|
||||
public TvEpisodeConsumptionRuleTests()
|
||||
{
|
||||
_sut = _tvEpisodeConsumptionRuleFixture.Create();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MediaKind_WhenRead_ShouldBeTvEpisode()
|
||||
{
|
||||
// Act
|
||||
MediaKind result = _sut.MediaKind;
|
||||
|
||||
// Assert
|
||||
Assert.Equal(MediaKind.TvEpisode, result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsSupportedByCurrentCatalogues_WhenRead_ShouldBeFalse()
|
||||
{
|
||||
// Act
|
||||
bool result = _sut.IsSupportedByCurrentCatalogues;
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PositionKind_WhenRead_ShouldBeTimeOffset()
|
||||
{
|
||||
// Act
|
||||
Optional<MediaPositionKind> result = _sut.PositionKind;
|
||||
|
||||
// Assert
|
||||
Assert.True(result.HasValue);
|
||||
Assert.Equal(MediaPositionKind.TimeOffset, result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsOneShot_WhenRead_ShouldBeFalse()
|
||||
{
|
||||
// Act
|
||||
bool result = _sut.IsOneShot;
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MinimumCountedDuration_WhenRead_ShouldBeThreeMinutes()
|
||||
{
|
||||
// Act
|
||||
TimeSpan result = _sut.MinimumCountedDuration;
|
||||
|
||||
// Assert
|
||||
Assert.Equal(TimeSpan.FromMinutes(3), result);
|
||||
}
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="VideoConsumptionRule"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class VideoConsumptionRuleTests
|
||||
{
|
||||
private readonly VideoConsumptionRuleFixture _videoConsumptionRuleFixture = new();
|
||||
private readonly VideoConsumptionRule _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="VideoConsumptionRuleTests"/> class.
|
||||
/// </summary>
|
||||
public VideoConsumptionRuleTests()
|
||||
{
|
||||
_sut = _videoConsumptionRuleFixture.Create();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MediaKind_WhenRead_ShouldBeVideo()
|
||||
{
|
||||
// Act
|
||||
MediaKind result = _sut.MediaKind;
|
||||
|
||||
// Assert
|
||||
Assert.Equal(MediaKind.Video, result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsSupportedByCurrentCatalogues_WhenRead_ShouldBeFalse()
|
||||
{
|
||||
// Act
|
||||
bool result = _sut.IsSupportedByCurrentCatalogues;
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PositionKind_WhenRead_ShouldBeTimeOffset()
|
||||
{
|
||||
// Act
|
||||
Optional<MediaPositionKind> result = _sut.PositionKind;
|
||||
|
||||
// Assert
|
||||
Assert.True(result.HasValue);
|
||||
Assert.Equal(MediaPositionKind.TimeOffset, result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsOneShot_WhenRead_ShouldBeFalse()
|
||||
{
|
||||
// Act
|
||||
bool result = _sut.IsOneShot;
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MinimumCountedDuration_WhenRead_ShouldBeThreeMinutes()
|
||||
{
|
||||
// Act
|
||||
TimeSpan result = _sut.MinimumCountedDuration;
|
||||
|
||||
// Assert
|
||||
Assert.Equal(TimeSpan.FromMinutes(3), result);
|
||||
}
|
||||
}
|
||||
Loaded 100 of 6450 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user