Updates to .NET 9.0

This commit is contained in:
BinaryAlley committed 2024-11-13 20:46:54 +02:00
commit acbdb0a5f8
853 files changed
+34993 -10123

No files matched your search

@@ -1,6 +1,4 @@
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using AutoFixture.AutoNSubstitute;
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Application.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.DataAccess.UoW;
@@ -23,16 +21,6 @@ namespace Lumina.DataAccess.UnitTests.Common.DependencyInjection;
[ExcludeFromCodeCoverage]
public class DataAccessLayerServicesTests
{
private readonly IFixture _fixture;
/// <summary>
/// Initializes a new instance of the <see cref="DataAccessLayerServicesTests"/> class.
/// </summary>
public DataAccessLayerServicesTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
}
[Fact]
public void AddDataAccessLayerServices_WhenBasePathExists_ShouldAddServices()
{
@@ -83,4 +71,4 @@ public class DataAccessLayerServicesTests
IBookRepository? repository = serviceProvider.GetService<IBookRepository>();
repository.Should().NotBeNull();
}
}
}
@@ -2,12 +2,12 @@
using EntityFrameworkCore.Testing.NSubstitute;
using ErrorOr;
using FluentAssertions;
using Lumina.Contracts.Enums.BookLibrary;
using Lumina.Contracts.Models.Common;
using Lumina.Contracts.Models.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.DataAccess.Core.Repositories.Books;
using Lumina.DataAccess.Core.UoW;
using Lumina.DataAccess.UnitTests.Core.Repositories.Books.Fixtures;
using Lumina.Domain.Common.Enums.BookLibrary;
using Lumina.Domain.Common.Errors;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
@@ -28,7 +28,7 @@ public class BookRepositoryTests
{
private readonly LuminaDbContext _mockContext;
private readonly BookRepository _sut;
private readonly BookModelFixture _bookModelFixture;
private readonly BookEntityFixture _bookEntityFixture;
/// <summary>
/// Initializes a new instance of the <see cref="BookRepositoryTests"/> class.
@@ -37,14 +37,14 @@ public class BookRepositoryTests
{
_mockContext = Create.MockedDbContextFor<LuminaDbContext>();
_sut = new BookRepository(_mockContext);
_bookModelFixture = new BookModelFixture();
_bookEntityFixture = new BookEntityFixture();
}
[Fact]
public async Task InsertAsync_WhenBookDoesNotExist_ShouldAddBookToContextAndReturnCreated()
{
// Arrange
BookModel bookModel = _bookModelFixture.CreateBookModel();
BookEntity bookModel = _bookEntityFixture.CreateBookModel();
// Act
ErrorOr<Created> result = await _sut.InsertAsync(bookModel, CancellationToken.None);
@@ -54,7 +54,7 @@ public class BookRepositoryTests
result.Value.Should().Be(Result.Created);
// Check if the book was added to the context's ChangeTracker
EntityEntry<BookModel>? addedBook = _mockContext.ChangeTracker.Entries<BookModel>()
EntityEntry<BookEntity>? addedBook = _mockContext.ChangeTracker.Entries<BookEntity>()
.FirstOrDefault(e => e.State == EntityState.Added && e.Entity.Id == bookModel.Id);
addedBook.Should().NotBeNull();
}
@@ -63,7 +63,7 @@ public class BookRepositoryTests
public async Task InsertAsync_WhenBookAlreadyExists_ShouldReturnError()
{
// Arrange
BookModel bookModel = _bookModelFixture.CreateBookModel();
BookEntity bookModel = _bookEntityFixture.CreateBookModel();
_mockContext.Books.Add(bookModel);
await _mockContext.SaveChangesAsync();
@@ -74,18 +74,18 @@ public class BookRepositoryTests
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.WrittenContent.BookAlreadyExists);
_mockContext.ChangeTracker.Entries<BookModel>().Should().HaveCount(1); // Only the existing book should be in the context}
_mockContext.ChangeTracker.Entries<BookEntity>().Should().HaveCount(1); // Only the existing book should be in the context}
}
[Fact]
public async Task InsertAsync_WhenExistingTagsFound_ShouldReplaceTagsWithExistingOnes()
{
// Arrange
TagModel existingTag = new("Existing");
_mockContext.Set<TagModel>().Add(existingTag);
TagEntity existingTag = new("Existing");
_mockContext.Set<TagEntity>().Add(existingTag);
await _mockContext.SaveChangesAsync();
BookModel bookModel = _bookModelFixture.CreateBookModel();
BookEntity bookModel = _bookEntityFixture.CreateBookModel();
bookModel.Tags = [new("Existing"), new("New")];
// Act
@@ -95,10 +95,10 @@ public class BookRepositoryTests
result.IsError.Should().BeFalse();
result.Value.Should().Be(Result.Created);
EntityEntry<BookModel>? addedBook = _mockContext.ChangeTracker.Entries<BookModel>()
EntityEntry<BookEntity>? addedBook = _mockContext.ChangeTracker.Entries<BookEntity>()
.FirstOrDefault(e => e.State == EntityState.Added && e.Entity.Id == bookModel.Id);
addedBook.Should().NotBeNull();
BookModel addedBookEntity = addedBook!.Entity;
BookEntity addedBookEntity = addedBook!.Entity;
addedBookEntity.Tags.Should().HaveCount(2);
addedBookEntity.Tags.Should().Contain(t => t.Name == "Existing" && t == existingTag);
addedBookEntity.Tags.Should().Contain(t => t.Name == "New" && t != existingTag);
@@ -108,11 +108,11 @@ public class BookRepositoryTests
public async Task InsertAsync_WhenExistingGenresFound_ShouldReplaceGenresWithExistingOnes()
{
// Arrange
GenreModel existingGenre = new("Existing");
_mockContext.Set<GenreModel>().Add(existingGenre);
GenreEntity existingGenre = new("Existing");
_mockContext.Set<GenreEntity>().Add(existingGenre);
await _mockContext.SaveChangesAsync();
BookModel bookModel = _bookModelFixture.CreateBookModel();
BookEntity bookModel = _bookEntityFixture.CreateBookModel();
bookModel.Genres = [new("Existing"), new("New")];
// Act
@@ -122,10 +122,10 @@ public class BookRepositoryTests
result.IsError.Should().BeFalse();
result.Value.Should().Be(Result.Created);
EntityEntry<BookModel>? addedBook = _mockContext.ChangeTracker.Entries<BookModel>()
EntityEntry<BookEntity>? addedBook = _mockContext.ChangeTracker.Entries<BookEntity>()
.FirstOrDefault(e => e.State == EntityState.Added && e.Entity.Id == bookModel.Id);
addedBook.Should().NotBeNull();
BookModel addedBookEntity = addedBook!.Entity;
BookEntity addedBookEntity = addedBook!.Entity;
addedBookEntity.Genres.Should().HaveCount(2);
addedBookEntity.Genres.Should().Contain(g => g.Name == "Existing" && g == existingGenre);
addedBookEntity.Genres.Should().Contain(g => g.Name == "New" && g != existingGenre);
@@ -135,17 +135,17 @@ public class BookRepositoryTests
public async Task GetAllAsync_WhenCalled_ShouldReturnAllBooks()
{
// Arrange
List<BookModel> books =
List<BookEntity> books =
[
_bookModelFixture.CreateBookModel(),
_bookModelFixture.CreateBookModel(),
_bookModelFixture.CreateBookModel()
_bookEntityFixture.CreateBookModel(),
_bookEntityFixture.CreateBookModel(),
_bookEntityFixture.CreateBookModel()
];
_mockContext.Books.AddRange(books);
await _mockContext.SaveChangesAsync();
// Act
ErrorOr<IEnumerable<BookModel>> result = await _sut.GetAllAsync(CancellationToken.None);
ErrorOr<IEnumerable<BookEntity>> result = await _sut.GetAllAsync(CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
@@ -158,7 +158,7 @@ public class BookRepositoryTests
public async Task GetAllAsync_WhenNoBooksExist_ShouldReturnEmptyList()
{
// Act
ErrorOr<IEnumerable<BookModel>> result = await _sut.GetAllAsync(CancellationToken.None);
ErrorOr<IEnumerable<BookEntity>> result = await _sut.GetAllAsync(CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
@@ -170,21 +170,21 @@ public class BookRepositoryTests
public async Task GetAllAsync_WhenCalled_ShouldIncludeRelatedEntities()
{
// Arrange
BookModel book = _bookModelFixture.CreateBookModel();
book.Tags = [new TagModel("Tag1"), new TagModel("Tag2")];
book.Genres = [new GenreModel("Genre1"), new GenreModel("Genre2")];
book.ISBNs = [new IsbnModel("1234567890", IsbnFormat.Isbn10), new IsbnModel("1234567890123", IsbnFormat.Isbn13)];
BookEntity book = _bookEntityFixture.CreateBookModel();
book.Tags = [new TagEntity("Tag1"), new TagEntity("Tag2")];
book.Genres = [new GenreEntity("Genre1"), new GenreEntity("Genre2")];
book.ISBNs = [new IsbnEntity("1234567890", IsbnFormat.Isbn10), new IsbnEntity("1234567890123", IsbnFormat.Isbn13)];
_mockContext.Books.Add(book);
await _mockContext.SaveChangesAsync();
// Act
ErrorOr<IEnumerable<BookModel>> result = await _sut.GetAllAsync(CancellationToken.None);
ErrorOr<IEnumerable<BookEntity>> result = await _sut.GetAllAsync(CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().NotBeNull();
result.Value.Should().HaveCount(1);
BookModel retrievedBook = result.Value.First();
BookEntity retrievedBook = result.Value.First();
retrievedBook.Tags.Should().HaveCount(2);
retrievedBook.Genres.Should().HaveCount(2);
retrievedBook.ISBNs.Should().HaveCount(2);
@@ -1,32 +1,34 @@
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using Bogus;
using Lumina.Contracts.Enums.BookLibrary;
using Lumina.Contracts.Models.Common;
using Lumina.Contracts.Models.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Domain.Common.Enums.BookLibrary;
using Lumina.DataAccess.UnitTests.Common.Setup;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
#endregion
namespace Lumina.DataAccess.UnitTests.Core.Repositories.Books.Fixtures;
/// <summary>
/// Fixture class for the <see cref="BookModel"/> class.
/// Fixture class for the <see cref="BookEntity"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class BookModelFixture
public class BookEntityFixture
{
private readonly Fixture _fixture;
private readonly Random _random = new();
private readonly Faker _faker;
/// <summary>
/// Initializes a new instance of the <see cref="BookModelFixture"/> class.
/// Initializes a new instance of the <see cref="BookEntityFixture"/> class.
/// </summary>
public BookModelFixture()
public BookEntityFixture()
{
_fixture = new Fixture();
_fixture.Customizations.Add(new DateOnlySpecimenBuilder());
@@ -36,15 +38,15 @@ public class BookModelFixture
}
/// <summary>
/// Creates a random valid BookModel.
/// Creates a random valid <see cref="BookEntity"/>.
/// </summary>
/// <returns>The created BookModel.</returns>
public BookModel CreateBookModel()
/// <returns>The created <see cref="BookEntity"/>.</returns>
public BookEntity CreateBookModel()
{
int releaseYear = _random.Next(2000, 2010);
int reReleaseYear = _random.Next(2010, 2020);
return new Faker<BookModel>()
return new Faker<BookEntity>()
.RuleFor(x => x.Id, f => f.Random.Guid())
.RuleFor(x => x.Title, f => f.Random.String2(f.Random.Number(1, 255)))
.RuleFor(x => x.OriginalTitle, f => f.Random.String2(f.Random.Number(1, 255)))
@@ -61,11 +63,11 @@ public class BookModelFixture
.RuleFor(x => x.OriginalLanguageCode, f => f.Random.String2(2))
.RuleFor(x => x.OriginalLanguageName, f => f.Random.String2(f.Random.Number(1, 50)))
.RuleFor(x => x.OriginalLanguageNativeName, f => f.Random.String2(f.Random.Number(1, 50)))
.RuleFor(x => x.Tags, f => new HashSet<TagModel>(CreateTags(f.Random.Number(1, 5))))
.RuleFor(x => x.Genres, f => new HashSet<GenreModel>(CreateGenres(f.Random.Number(1, 5))))
.RuleFor(x => x.Tags, f => new HashSet<TagEntity>(CreateTags(f.Random.Number(1, 5))))
.RuleFor(x => x.Genres, f => new HashSet<GenreEntity>(CreateGenres(f.Random.Number(1, 5))))
.RuleFor(x => x.Publisher, f => f.Random.String2(f.Random.Number(1, 100)))
.RuleFor(x => x.PageCount, _random.Next(100, 300))
.RuleFor(x => x.Format, f => f.PickRandom<BookFormat>().ToString())
.RuleFor(x => x.Format, f => f.PickRandom<BookFormat>())
.RuleFor(x => x.Edition, f => f.Random.String2(f.Random.Number(1, 50)))
.RuleFor(x => x.VolumeNumber, _random.Next(1, 3))
.RuleFor(x => x.ASIN, f => f.Random.String2(10))
@@ -84,20 +86,35 @@ public class BookModelFixture
.Generate();
}
private List<TagModel> CreateTags(int count)
/// <summary>
/// Creates a list of tag entities with random data.
/// </summary>
/// <param name="count">The number of tags to create.</param>
/// <returns>A list of randomly generated tag entities.</returns>
private static List<TagEntity> CreateTags(int count)
{
return new Faker<TagModel>()
.CustomInstantiator(f => new TagModel(f.Random.String2(f.Random.Number(1, 50))))
return new Faker<TagEntity>()
.CustomInstantiator(f => new TagEntity(f.Random.String2(f.Random.Number(1, 50))))
.Generate(count);
}
private List<GenreModel> CreateGenres(int count)
/// <summary>
/// Creates a list of genre entities with random data.
/// </summary>
/// <param name="count">The number of genres to create.</param>
/// <returns>A list of randomly generated genre entities.</returns>
private static List<GenreEntity> CreateGenres(int count)
{
return new Faker<GenreModel>()
.CustomInstantiator(f => new GenreModel(f.Random.String2(f.Random.Number(1, 50))))
return new Faker<GenreEntity>()
.CustomInstantiator(f => new GenreEntity(f.Random.String2(f.Random.Number(1, 50))))
.Generate(count);
}
/// <summary>
/// Creates a valid Library of Congress Control Number (LCCN).
/// </summary>
/// <param name="f">The Faker instance used for generating random data.</param>
/// <returns>A properly formatted LCCN string.</returns>
private string CreateLCCN(Faker f)
{
string letters = new(Enumerable.Range(0, f.Random.Number(0, 3))
@@ -107,6 +124,11 @@ public class BookModelFixture
return letters + digits;
}
/// <summary>
/// Creates a valid OCLC (Online Computer Library Center) number.
/// </summary>
/// <param name="f">The Faker instance used for generating random data.</param>
/// <returns>A properly formatted OCLC number string with valid prefix.</returns>
private string CreateOCLCNumber(Faker f)
{
string[] prefixes = ["ocm", "ocn", "on", "(OCoLC)"];
@@ -122,6 +144,11 @@ public class BookModelFixture
return prefix + number;
}
/// <summary>
/// Creates a valid Open Library ID.
/// </summary>
/// <param name="f">The Faker instance used for generating random data.</param>
/// <returns>A properly formatted Open Library ID string.</returns>
private string CreateOpenLibraryId(Faker f)
{
int firstDigit = f.Random.Number(1, 9);
@@ -130,6 +157,11 @@ public class BookModelFixture
return $"OL{firstDigit}{remainingDigits}{suffix}";
}
/// <summary>
/// Creates a valid Google Books ID.
/// </summary>
/// <param name="f">The Faker instance used for generating random data.</param>
/// <returns>A properly formatted Google Books ID string.</returns>
private string CreateGoogleBooksId(Faker f)
{
const string VALID_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
@@ -138,14 +170,24 @@ public class BookModelFixture
.ToArray());
}
private List<IsbnModel> CreateIsbns(int count)
/// <summary>
/// Creates a list of ISBN entities with random data.
/// </summary>
/// <param name="count">The number of ISBNs to create.</param>
/// <returns>A list of randomly generated ISBN entities.</returns>
private static List<IsbnEntity> CreateIsbns(int count)
{
return new Faker<IsbnModel>()
.CustomInstantiator(f => new IsbnModel(CreateIsbn(f), f.PickRandom<IsbnFormat>()))
return new Faker<IsbnEntity>()
.CustomInstantiator(f => new IsbnEntity(CreateIsbn(f), f.PickRandom<IsbnFormat>()))
.Generate(count);
}
private string CreateIsbn(Faker f)
/// <summary>
/// Creates a valid ISBN (International Standard Book Number).
/// </summary>
/// <param name="f">The Faker instance used for generating random data.</param>
/// <returns>A properly formatted ISBN-10 or ISBN-13 string with valid checksum.</returns>
private static string CreateIsbn(Faker f)
{
bool isIsbn13 = f.Random.Bool();
if (isIsbn13)
@@ -175,10 +217,15 @@ public class BookModelFixture
}
}
private List<BookRatingModel> CreateBookRatings(int count)
// <summary>
/// Creates a list of book rating entities with random data.
/// </summary>
/// <param name="count">The number of ratings to create.</param>
/// <returns>A list of randomly generated book rating entities.</returns>
private static List<BookRatingEntity> CreateBookRatings(int count)
{
return new Faker<BookRatingModel>()
.CustomInstantiator(f => new BookRatingModel(
return new Faker<BookRatingEntity>()
.CustomInstantiator(f => new BookRatingEntity(
f.Random.Decimal(1, 5),
5,
f.PickRandom<BookRatingSource>(),
@@ -187,12 +234,15 @@ public class BookModelFixture
.Generate(count);
}
/// <summary>
/// Configures custom type generation rules for the AutoFixture instance.
/// </summary>
private void ConfigureCustomTypes()
{
_fixture.Register(() => new TagModel(_fixture.Create<string>()));
_fixture.Register(() => new GenreModel(_fixture.Create<string>()));
_fixture.Register(() => new IsbnModel(_fixture.Create<string>(), _fixture.Create<IsbnFormat>()));
_fixture.Register(() => new BookRatingModel(
_fixture.Register(() => new TagEntity(_fixture.Create<string>()));
_fixture.Register(() => new GenreEntity(_fixture.Create<string>()));
_fixture.Register(() => new IsbnEntity(_fixture.Create<string>(), _fixture.Create<IsbnFormat>()));
_fixture.Register(() => new BookRatingEntity(
_fixture.Create<decimal>(),
_fixture.Create<decimal>(),
_fixture.Create<BookRatingSource>(),
@@ -0,0 +1,114 @@
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using Bogus;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Domain.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.DataAccess.UnitTests.Core.Repositories.Users.Fixtures;
/// <summary>
/// Fixture class for the <see cref="UserEntity"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UserEntityFixture
{
private readonly Fixture _fixture;
private readonly Faker _faker;
/// <summary>
/// Initializes a new instance of the <see cref="UserEntityFixture"/> class.
/// </summary>
public UserEntityFixture()
{
_fixture = new Fixture();
_faker = new Faker();
ConfigureCustomTypes();
}
/// <summary>
/// Creates a random valid <see cref="UserEntity"/>.
/// </summary>
/// <returns>The created <see cref="UserEntity"/>.</returns>
public UserEntity CreateUserModel()
{
Guid userId = _faker.Random.Guid();
return new Faker<UserEntity>()
.RuleFor(x => x.Id, _ => userId)
.RuleFor(x => x.Username, f => f.Internet.UserName())
.RuleFor(x => x.Password, f => f.Internet.Password(12))
.RuleFor(x => x.TempPassword, f => f.Random.Bool() ? f.Internet.Password(8) : null)
.RuleFor(x => x.TotpSecret, f => f.Random.Bool() ? f.Random.String2(32, "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567") : null)
.RuleFor(x => x.VerificationToken, f => f.Random.Bool() ? f.Random.Guid().ToString() : null)
.RuleFor(x => x.VerificationTokenCreated, (f, u) => u.VerificationToken != null ? f.Date.Past() : null)
.RuleFor(x => x.TempPasswordCreated, (f, u) => u.TempPassword != null ? f.Date.Past() : null)
.RuleFor(x => x.Libraries, _ => CreateLibraries(_faker.Random.Number(1, 3), userId))
.RuleFor(x => x.Created, f => f.Date.Past())
.RuleFor(x => x.Updated, f => f.Random.Bool() ? f.Date.Recent() : null)
.Generate();
}
/// <summary>
/// Creates a valid collection of user libraries.
/// </summary>
/// <param name="count">The number of user libraries to create.</param>
/// <param name="userId">The Id of the user for whom to create the libraries.</param>
/// <returns>A collection of <see cref="LibraryEntity"/>.</returns>
private static List<LibraryEntity> CreateLibraries(int count, Guid userId)
{
return new Faker<LibraryEntity>()
.CustomInstantiator(f => new LibraryEntity
{
Id = f.Random.Guid(),
UserId = userId,
Title = f.Random.String2(f.Random.Number(1, 50)),
LibraryType = f.PickRandom<LibraryType>(),
ContentLocations = CreateContentLocations(f.Random.Number(1, 3)),
Created = f.Date.Past(),
Updated = f.Random.Bool() ? f.Date.Recent() : null
})
.Generate(count);
}
/// <summary>
/// Creates a valid collection of media paths for a library.
/// </summary>
/// <param name="count">The number of media library contents to create.</param>
/// <returns>A collection of <see cref="LibraryContentLocationEntity"/>.</returns>
private static List<LibraryContentLocationEntity> CreateContentLocations(int count)
{
return new Faker<LibraryContentLocationEntity>()
.CustomInstantiator(f => new LibraryContentLocationEntity
{
Path = f.System.FilePath()
})
.Generate(count);
}
/// <summary>
/// Configures custom type generation rules for the AutoFixture instance.
/// </summary>
private void ConfigureCustomTypes()
{
_fixture.Register(() => new LibraryEntity
{
Id = _fixture.Create<Guid>(),
UserId = _fixture.Create<Guid>(),
Title = _fixture.Create<string>(),
LibraryType = _fixture.Create<LibraryType>(),
ContentLocations = new List<LibraryContentLocationEntity>(),
Created = _fixture.Create<DateTime>(),
Updated = _fixture.Create<DateTime>()
});
_fixture.Register(() => new LibraryContentLocationEntity
{
Path = _fixture.Create<string>()
});
}
}
@@ -0,0 +1,189 @@
#region ========================================================================= USING =====================================================================================
using EntityFrameworkCore.Testing.NSubstitute;
using ErrorOr;
using FluentAssertions;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.Repositories.Users;
using Lumina.DataAccess.Core.UoW;
using Lumina.DataAccess.UnitTests.Core.Repositories.Users.Fixtures;
using Lumina.Domain.Common.Errors;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.UnitTests.Core.Repositories.Users;
/// <summary>
/// Contains unit tests for the <see cref="UserRepository"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UserRepositoryTests
{
private readonly LuminaDbContext _mockContext;
private readonly UserRepository _sut;
private readonly UserEntityFixture _userEntityFixture;
/// <summary>
/// Initializes a new instance of the <see cref="UserRepositoryTests"/> class.
/// </summary>
public UserRepositoryTests()
{
_mockContext = Create.MockedDbContextFor<LuminaDbContext>();
_sut = new UserRepository(_mockContext);
_userEntityFixture = new UserEntityFixture();
}
[Fact]
public async Task InsertAsync_WhenUserDoesNotExist_ShouldAddUserToContextAndReturnCreated()
{
// Arrange
UserEntity userModel = _userEntityFixture.CreateUserModel();
// Act
ErrorOr<Created> result = await _sut.InsertAsync(userModel, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().Be(Result.Created);
EntityEntry<UserEntity>? addedUser = _mockContext.ChangeTracker.Entries<UserEntity>()
.FirstOrDefault(e => e.State == EntityState.Added && e.Entity.Id == userModel.Id);
addedUser.Should().NotBeNull();
}
[Fact]
public async Task InsertAsync_WhenUserAlreadyExists_ShouldReturnError()
{
// Arrange
UserEntity userModel = _userEntityFixture.CreateUserModel();
_mockContext.Users.Add(userModel);
await _mockContext.SaveChangesAsync();
// Act
ErrorOr<Created> result = await _sut.InsertAsync(userModel, CancellationToken.None);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.Users.UserAlreadyExists);
_mockContext.ChangeTracker.Entries<UserEntity>().Should().HaveCount(1);
}
[Fact]
public async Task GetAllAsync_WhenCalled_ShouldReturnAllUsers()
{
// Arrange
List<UserEntity> users =
[
_userEntityFixture.CreateUserModel(),
_userEntityFixture.CreateUserModel(),
_userEntityFixture.CreateUserModel()
];
_mockContext.Users.AddRange(users);
await _mockContext.SaveChangesAsync();
// Act
ErrorOr<IEnumerable<UserEntity>> result = await _sut.GetAllAsync(CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().NotBeNull();
result.Value.Should().HaveCount(3);
result.Value.Should().BeEquivalentTo(users);
}
[Fact]
public async Task GetAllAsync_WhenNoUsersExist_ShouldReturnEmptyList()
{
// Act
ErrorOr<IEnumerable<UserEntity>> result = await _sut.GetAllAsync(CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().NotBeNull();
result.Value.Should().BeEmpty();
}
[Fact]
public async Task GetByUsernameAsync_WhenUserExists_ShouldReturnUser()
{
// Arrange
UserEntity userModel = _userEntityFixture.CreateUserModel();
_mockContext.Users.Add(userModel);
await _mockContext.SaveChangesAsync();
// Act
ErrorOr<UserEntity?> result = await _sut.GetByUsernameAsync(userModel.Username, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().NotBeNull();
result.Value.Should().BeEquivalentTo(userModel);
}
[Fact]
public async Task GetByUsernameAsync_WhenUserDoesNotExist_ShouldReturnNull()
{
// Act
ErrorOr<UserEntity?> result = await _sut.GetByUsernameAsync("nonexistent", CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().BeNull();
}
[Fact]
public async Task UpdateAsync_WhenUserExists_ShouldUpdateUserAndReturnUpdated()
{
// Arrange
UserEntity existingUser = _userEntityFixture.CreateUserModel();
_mockContext.Users.Add(existingUser);
await _mockContext.SaveChangesAsync();
// Create updated user with same Id but different properties
UserEntity updatedUser = new()
{
Id = existingUser.Id,
Username = existingUser.Username, // Keep username as it's used for lookup
Password = "NewPassword123",
TempPassword = "TempPass456",
TotpSecret = "NewSecret",
Libraries = [],
Created = existingUser.Created,
Updated = DateTime.UtcNow
};
// Act
ErrorOr<Updated> result = await _sut.UpdateAsync(updatedUser, CancellationToken.None);
// Assert
result.IsError.Should().BeFalse();
result.Value.Should().Be(Result.Updated);
UserEntity? modifiedUser = await _mockContext.Users.FirstOrDefaultAsync(u => u.Username == existingUser.Username);
modifiedUser.Should().NotBeNull();
modifiedUser!.Password.Should().Be(updatedUser.Password);
modifiedUser.TempPassword.Should().Be(updatedUser.TempPassword);
modifiedUser.TotpSecret.Should().Be(updatedUser.TotpSecret);
}
[Fact]
public async Task UpdateAsync_WhenUserDoesNotExist_ShouldReturnError()
{
// Arrange
UserEntity userModel = _userEntityFixture.CreateUserModel();
// Act
ErrorOr<Updated> result = await _sut.UpdateAsync(userModel, CancellationToken.None);
// Assert
result.IsError.Should().BeTrue();
result.FirstError.Should().Be(Errors.Users.UserDoesNotExist);
}
}
@@ -9,22 +9,29 @@
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<AssemblyAttribute Include="Xunit.CollectionBehaviorAttribute">
<_Parameter1>DisableTestParallelization = true</_Parameter1>
<_Parameter1_IsLiteral>true</_Parameter1_IsLiteral>
</AssemblyAttribute>
</ItemGroup>
<ItemGroup>
<PackageReference Include="AutoFixture.AutoNSubstitute" Version="5.0.0-preview0011" />
<PackageReference Include="AutoFixture.Xunit2" Version="5.0.0-preview0011" />
<PackageReference Include="Bogus" Version="35.6.0" />
<PackageReference Include="Bogus" Version="35.6.1" />
<PackageReference Include="coverlet.collector" Version="6.0.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="FluentAssertions" Version="7.0.0-alpha.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="9.0.0-rc.2.24474.1" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="9.0.0-rc.2.24473.5" />
<PackageReference Include="FluentAssertions" Version="7.0.0-alpha.5" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="9.0.0" />
<PackageReference Include="EntityFrameworkCore.Testing.NSubstitute" Version="8.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" />
<PackageReference Include="NSubstitute" Version="5.1.0" />
<PackageReference Include="NSubstitute" Version="5.3.0" />
<PackageReference Include="xunit" Version="2.9.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.0.0-pre.35">
<PackageReference Include="xunit.runner.visualstudio" Version="3.0.0-pre.49">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>