Adds authentication unit tests

This commit is contained in:
BinaryAlley committed 2024-11-12 15:45:26 +02:00
1 parent a6dcf65d1c
commit 4f91f29b62
101 files changed
+5549 -135

No files matched your search

@@ -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
BookEntity bookModel = _bookModelFixture.CreateBookModel();
BookEntity bookModel = _bookEntityFixture.CreateBookModel();
// Act
ErrorOr<Created> result = await _sut.InsertAsync(bookModel, CancellationToken.None);
@@ -63,7 +63,7 @@ public class BookRepositoryTests
public async Task InsertAsync_WhenBookAlreadyExists_ShouldReturnError()
{
// Arrange
BookEntity bookModel = _bookModelFixture.CreateBookModel();
BookEntity bookModel = _bookEntityFixture.CreateBookModel();
_mockContext.Books.Add(bookModel);
await _mockContext.SaveChangesAsync();
@@ -85,7 +85,7 @@ public class BookRepositoryTests
_mockContext.Set<TagEntity>().Add(existingTag);
await _mockContext.SaveChangesAsync();
BookEntity bookModel = _bookModelFixture.CreateBookModel();
BookEntity bookModel = _bookEntityFixture.CreateBookModel();
bookModel.Tags = [new("Existing"), new("New")];
// Act
@@ -112,7 +112,7 @@ public class BookRepositoryTests
_mockContext.Set<GenreEntity>().Add(existingGenre);
await _mockContext.SaveChangesAsync();
BookEntity bookModel = _bookModelFixture.CreateBookModel();
BookEntity bookModel = _bookEntityFixture.CreateBookModel();
bookModel.Genres = [new("Existing"), new("New")];
// Act
@@ -137,9 +137,9 @@ public class BookRepositoryTests
// Arrange
List<BookEntity> books =
[
_bookModelFixture.CreateBookModel(),
_bookModelFixture.CreateBookModel(),
_bookModelFixture.CreateBookModel()
_bookEntityFixture.CreateBookModel(),
_bookEntityFixture.CreateBookModel(),
_bookEntityFixture.CreateBookModel()
];
_mockContext.Books.AddRange(books);
await _mockContext.SaveChangesAsync();
@@ -170,7 +170,7 @@ public class BookRepositoryTests
public async Task GetAllAsync_WhenCalled_ShouldIncludeRelatedEntities()
{
// Arrange
BookEntity book = _bookModelFixture.CreateBookModel();
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)];
@@ -19,16 +19,16 @@ namespace Lumina.DataAccess.UnitTests.Core.Repositories.Books.Fixtures;
/// 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());
@@ -38,9 +38,9 @@ public class BookModelFixture
}
/// <summary>
/// Creates a random valid BookModel.
/// Creates a random valid <see cref="BookEntity"/>.
/// </summary>
/// <returns>The created BookModel.</returns>
/// <returns>The created <see cref="BookEntity"/>.</returns>
public BookEntity CreateBookModel()
{
int releaseYear = _random.Next(2000, 2010);
@@ -86,6 +86,11 @@ public class BookModelFixture
.Generate();
}
/// <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<TagEntity>()
@@ -93,6 +98,11 @@ public class BookModelFixture
.Generate(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<GenreEntity>()
@@ -100,6 +110,11 @@ public class BookModelFixture
.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))
@@ -109,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)"];
@@ -124,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);
@@ -132,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-_";
@@ -140,6 +170,11 @@ public class BookModelFixture
.ToArray());
}
/// <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<IsbnEntity>()
@@ -147,6 +182,11 @@ public class BookModelFixture
.Generate(count);
}
/// <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();
@@ -177,6 +217,11 @@ public class BookModelFixture
}
}
// <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<BookRatingEntity>()
@@ -189,6 +234,9 @@ public class BookModelFixture
.Generate(count);
}
/// <summary>
/// Configures custom type generation rules for the AutoFixture instance.
/// </summary>
private void ConfigureCustomTypes()
{
_fixture.Register(() => new TagEntity(_fixture.Create<string>()));
@@ -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);
}
}