mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 10:11:10 +00:00
Extends the data access repository and persistence tests
This commit is contained in:
1 parent
e73b3997bc
commit
3d089b063f
17 files changed
+1401
-44
No files matched your search
+98
@@ -0,0 +1,98 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.DataAccess.Core.Repositories.Authorization;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.IntegrationTests.Core.Repositories.Authorization;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="RoleRepository"/> class, exercising it against a real SQLite database.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RoleRepositoryTests
|
||||
{
|
||||
private readonly RoleEntityFixture _roleEntityFixture = new();
|
||||
private readonly RolePermissionEntityFixture _rolePermissionEntityFixture = new();
|
||||
private readonly PermissionEntityFixture _permissionEntityFixture = new();
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenAnEditableValueChanges_ShouldPreserveTheStoredAuditColumns()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-rolerepo-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
RoleRepository sut = new(context);
|
||||
|
||||
DateTime storedCreatedOnUtc = new(2020, 3, 4, 5, 6, 7, DateTimeKind.Utc);
|
||||
Guid storedCreatedBy = Guid.NewGuid();
|
||||
RoleEntity storedRole = _roleEntityFixture.Create(roleName: "Admin", createdOnUtc: storedCreatedOnUtc, createdBy: storedCreatedBy);
|
||||
context.Roles.Add(storedRole);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
RoleEntity updatedRole = _roleEntityFixture.Create(id: storedRole.Id, roleName: "SuperAdmin", createdOnUtc: DateTime.UtcNow.AddYears(-10), createdBy: Guid.NewGuid());
|
||||
updatedRole.UpdatedOnUtc = DateTime.UtcNow.AddYears(-5);
|
||||
updatedRole.UpdatedBy = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await sut.UpdateAsync(updatedRole, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
|
||||
await context.SaveChangesAsync();
|
||||
context.ChangeTracker.Clear();
|
||||
RoleEntity reloadedRole = await context.Roles.AsNoTracking().FirstAsync(role => role.Id == storedRole.Id);
|
||||
Assert.Equal("SuperAdmin", reloadedRole.RoleName);
|
||||
Assert.Equal(storedCreatedOnUtc, reloadedRole.CreatedOnUtc);
|
||||
Assert.Equal(storedCreatedBy, reloadedRole.CreatedBy);
|
||||
Assert.Null(reloadedRole.UpdatedOnUtc);
|
||||
Assert.Null(reloadedRole.UpdatedBy);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenNothingChanged_ShouldNotDuplicateThePermissions()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-rolerepo-permissions-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
RoleRepository sut = new(context);
|
||||
|
||||
PermissionEntity firstPermission = _permissionEntityFixture.Create();
|
||||
PermissionEntity secondPermission = _permissionEntityFixture.Create();
|
||||
RoleEntity storedRole = _roleEntityFixture.Create(roleName: $"perm-role-{Guid.NewGuid():N}");
|
||||
context.Permissions.AddRange(firstPermission, secondPermission);
|
||||
context.Roles.Add(storedRole);
|
||||
await context.SaveChangesAsync();
|
||||
storedRole.RolePermissions.Add(_rolePermissionEntityFixture.Create(role: storedRole, permission: firstPermission));
|
||||
storedRole.RolePermissions.Add(_rolePermissionEntityFixture.Create(role: storedRole, permission: secondPermission));
|
||||
await context.SaveChangesAsync();
|
||||
// Detach the seeded role, so that the update must load it through its include chain instead of returning the already populated seeded instance.
|
||||
context.ChangeTracker.Clear();
|
||||
|
||||
RoleEntity incoming = await context.Roles.AsNoTracking().Include(candidate => candidate.RolePermissions).FirstAsync(candidate => candidate.Id == storedRole.Id);
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await sut.UpdateAsync(incoming, CancellationToken.None);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
RoleEntity? reloadedRole = await context.Roles.AsNoTracking().Include(candidate => candidate.RolePermissions).FirstOrDefaultAsync(candidate => candidate.Id == storedRole.Id);
|
||||
Assert.NotNull(reloadedRole);
|
||||
Assert.Equal(2, reloadedRole!.RolePermissions.Count);
|
||||
}
|
||||
}
|
||||
+111
-5
@@ -1,7 +1,9 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Time;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.DataAccess.Common.Interceptors;
|
||||
using Lumina.DataAccess.Core.Repositories.BookLibrary;
|
||||
@@ -34,6 +36,8 @@ public class BookRepositoryTests
|
||||
private readonly BookContributorEntityFixture _bookContributorEntityFixture = new();
|
||||
private readonly BookRatingEntityFixture _bookRatingEntityFixture = new();
|
||||
private readonly IsbnEntityFixture _isbnEntityFixture = new();
|
||||
private readonly TagEntityFixture _tagEntityFixture = new();
|
||||
private readonly GenreEntityFixture _genreEntityFixture = new();
|
||||
|
||||
[Fact]
|
||||
public async Task ResetEnrichmentStateForPathsAsync_WhenCalled_ShouldResetTheMetadataAndArtworkStatusesForThePaths()
|
||||
@@ -42,7 +46,7 @@ public class BookRepositoryTests
|
||||
// The reset methods use ExecuteUpdateAsync, which is not supported by the in-memory provider, so a real SQLite database is used.
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-reset-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
BookRepository sut = new(context);
|
||||
|
||||
@@ -82,7 +86,7 @@ public class BookRepositoryTests
|
||||
// The reset methods use ExecuteUpdateAsync, which is not supported by the in-memory provider, so a real SQLite database is used.
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-reset-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
BookRepository sut = new(context);
|
||||
|
||||
@@ -117,7 +121,7 @@ public class BookRepositoryTests
|
||||
// The reset methods use ExecuteUpdateAsync, which is not supported by the in-memory provider, so a real SQLite database is used.
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-reset-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
BookRepository sut = new(context);
|
||||
|
||||
@@ -151,7 +155,7 @@ public class BookRepositoryTests
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-insert-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
BookRepository sut = new(context);
|
||||
|
||||
@@ -176,7 +180,7 @@ public class BookRepositoryTests
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-insert-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
BookRepository sut = new(context);
|
||||
|
||||
@@ -336,6 +340,108 @@ public class BookRepositoryTests
|
||||
Assert.Contains(storedContributors, contributor => contributor.MediaContributorId == addedMediaContributorId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenNothingChanged_ShouldNotDuplicateAnyReconciledChildCollection()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-update-noop-collections-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
BookRepository sut = new(context);
|
||||
|
||||
BookEntity book = _bookEntityFixture.Create(includeMetadata: false);
|
||||
book.Tags = [_tagEntityFixture.Create(name: $"noop-book-tag-{Guid.NewGuid():N}"), _tagEntityFixture.Create(name: $"noop-book-tag-two-{Guid.NewGuid():N}")];
|
||||
book.Genres = [_genreEntityFixture.Create(name: $"noop-book-genre-{Guid.NewGuid():N}"), _genreEntityFixture.Create(name: $"noop-book-genre-two-{Guid.NewGuid():N}")];
|
||||
book.ISBNs = [_isbnEntityFixture.Create(value: "9783161484100", format: IsbnFormat.Isbn13), _isbnEntityFixture.Create(value: "9780261102693", format: IsbnFormat.Isbn13)];
|
||||
book.Ratings = [_bookRatingEntityFixture.Create(source: BookRatingSource.GoogleBooks), _bookRatingEntityFixture.Create(source: BookRatingSource.Goodreads)];
|
||||
book.Contributors =
|
||||
[
|
||||
_bookContributorEntityFixture.Create(bookId: book.Id, mediaContributorId: Guid.NewGuid()),
|
||||
_bookContributorEntityFixture.Create(bookId: book.Id, mediaContributorId: Guid.NewGuid())
|
||||
];
|
||||
context.Books.Add(book);
|
||||
await context.SaveChangesAsync();
|
||||
// Detach the seeded graph, so that the update must load the tracked book through its include chain instead of returning the already populated seeded instance.
|
||||
context.ChangeTracker.Clear();
|
||||
|
||||
BookEntity incoming = await LoadDetachedBookAsync(context, book.Id);
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await sut.UpdateAsync(incoming, CancellationToken.None);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
BookEntity? storedBook = await context.Books
|
||||
.AsNoTracking()
|
||||
.Include(candidate => candidate.Tags)
|
||||
.Include(candidate => candidate.Genres)
|
||||
.Include(candidate => candidate.ISBNs)
|
||||
.Include(candidate => candidate.Ratings)
|
||||
.Include(candidate => candidate.Contributors)
|
||||
.FirstOrDefaultAsync(candidate => candidate.Id == book.Id);
|
||||
Assert.NotNull(storedBook);
|
||||
Assert.Equal(2, storedBook!.Tags.Count);
|
||||
Assert.Equal(2, storedBook.Genres.Count);
|
||||
Assert.Equal(2, storedBook.ISBNs.Count);
|
||||
Assert.Equal(2, storedBook.Ratings.Count);
|
||||
Assert.Equal(2, storedBook.Contributors.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenOneItemIsRemovedFromEachReconciledChildCollection_ShouldRemoveOnlyThoseItems()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-update-remove-collections-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
BookRepository sut = new(context);
|
||||
|
||||
string keptTagName = $"remove-book-tag-{Guid.NewGuid():N}";
|
||||
string keptGenreName = $"remove-book-genre-{Guid.NewGuid():N}";
|
||||
BookEntity book = _bookEntityFixture.Create(includeMetadata: false);
|
||||
book.Tags = [_tagEntityFixture.Create(name: keptTagName), _tagEntityFixture.Create(name: $"remove-book-tag-two-{Guid.NewGuid():N}")];
|
||||
book.Genres = [_genreEntityFixture.Create(name: keptGenreName), _genreEntityFixture.Create(name: $"remove-book-genre-two-{Guid.NewGuid():N}")];
|
||||
book.ISBNs = [_isbnEntityFixture.Create(value: "9783161484100", format: IsbnFormat.Isbn13), _isbnEntityFixture.Create(value: "9780261102693", format: IsbnFormat.Isbn13)];
|
||||
book.Ratings = [_bookRatingEntityFixture.Create(source: BookRatingSource.GoogleBooks), _bookRatingEntityFixture.Create(source: BookRatingSource.Goodreads)];
|
||||
BookContributorEntity keptContributor = _bookContributorEntityFixture.Create(bookId: book.Id, mediaContributorId: Guid.NewGuid());
|
||||
book.Contributors = [keptContributor, _bookContributorEntityFixture.Create(bookId: book.Id, mediaContributorId: Guid.NewGuid())];
|
||||
context.Books.Add(book);
|
||||
await context.SaveChangesAsync();
|
||||
// Detach the seeded graph, so that the update must load the tracked book through its include chain instead of returning the already populated seeded instance.
|
||||
context.ChangeTracker.Clear();
|
||||
|
||||
BookEntity incoming = await LoadDetachedBookAsync(context, book.Id);
|
||||
incoming.Tags = [incoming.Tags.Single(tag => tag.Name == keptTagName)];
|
||||
incoming.Genres = [incoming.Genres.Single(genre => genre.Name == keptGenreName)];
|
||||
incoming.ISBNs = [incoming.ISBNs.Single(isbn => isbn.Value == "9783161484100")];
|
||||
incoming.Ratings = [incoming.Ratings.Single(rating => rating.Source == BookRatingSource.GoogleBooks)];
|
||||
incoming.Contributors = [incoming.Contributors.Single(contributor => contributor.Id == keptContributor.Id)];
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await sut.UpdateAsync(incoming, CancellationToken.None);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
BookEntity? storedBook = await context.Books
|
||||
.AsNoTracking()
|
||||
.Include(candidate => candidate.Tags)
|
||||
.Include(candidate => candidate.Genres)
|
||||
.Include(candidate => candidate.ISBNs)
|
||||
.Include(candidate => candidate.Ratings)
|
||||
.Include(candidate => candidate.Contributors)
|
||||
.FirstOrDefaultAsync(candidate => candidate.Id == book.Id);
|
||||
Assert.NotNull(storedBook);
|
||||
Assert.Equal(keptTagName, Assert.Single(storedBook!.Tags).Name);
|
||||
Assert.Equal(keptGenreName, Assert.Single(storedBook.Genres).Name);
|
||||
Assert.Equal("9783161484100", Assert.Single(storedBook.ISBNs).Value);
|
||||
Assert.Equal(BookRatingSource.GoogleBooks, Assert.Single(storedBook.Ratings).Source);
|
||||
Assert.Equal(keptContributor.Id, Assert.Single(storedBook.Contributors).Id);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a real SQLite backed context with the auditing interceptor attached, so that audit columns behave exactly like in production.
|
||||
/// </summary>
|
||||
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.DataAccess.Core.Repositories.Libraries;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.IntegrationTests.Core.Repositories.Libraries;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="LibraryScanRepository"/> class, exercising it against a real SQLite database.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LibraryScanRepositoryTests
|
||||
{
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new();
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenAnEditableValueChanges_ShouldPreserveTheStoredAuditColumns()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-libraryscanrepo-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
LibraryScanRepository sut = new(context);
|
||||
|
||||
UserEntity storedUser = _userEntityFixture.Create(username: "scan-user", password: "Password123");
|
||||
context.Users.Add(storedUser);
|
||||
LibraryEntity storedLibrary = _libraryEntityFixture.Create(userId: storedUser.Id);
|
||||
context.Libraries.Add(storedLibrary);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
DateTime storedCreatedOnUtc = new(2020, 3, 4, 5, 6, 7, DateTimeKind.Utc);
|
||||
Guid storedCreatedBy = Guid.NewGuid();
|
||||
LibraryScanEntity storedScan = _libraryScanEntityFixture.Create(libraryId: storedLibrary.Id, userId: storedUser.Id, status: LibraryScanJobStatus.Running, libraryEntity: storedLibrary);
|
||||
storedScan.CreatedOnUtc = storedCreatedOnUtc;
|
||||
storedScan.CreatedBy = storedCreatedBy;
|
||||
context.LibraryScans.Add(storedScan);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
LibraryScanEntity updatedScan = _libraryScanEntityFixture.Create(id: storedScan.Id, libraryId: storedLibrary.Id, userId: storedUser.Id, status: LibraryScanJobStatus.Completed, libraryEntity: storedLibrary);
|
||||
updatedScan.CreatedOnUtc = DateTime.UtcNow.AddYears(-10);
|
||||
updatedScan.CreatedBy = Guid.NewGuid();
|
||||
updatedScan.UpdatedOnUtc = DateTime.UtcNow.AddYears(-5);
|
||||
updatedScan.UpdatedBy = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await sut.UpdateAsync(updatedScan, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
|
||||
await context.SaveChangesAsync();
|
||||
context.ChangeTracker.Clear();
|
||||
LibraryScanEntity reloadedScan = await context.LibraryScans.AsNoTracking().FirstAsync(scan => scan.Id == storedScan.Id);
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, reloadedScan.Status);
|
||||
Assert.Equal(storedCreatedOnUtc, reloadedScan.CreatedOnUtc);
|
||||
Assert.Equal(storedCreatedBy, reloadedScan.CreatedBy);
|
||||
Assert.Null(reloadedScan.UpdatedOnUtc);
|
||||
Assert.Null(reloadedScan.UpdatedBy);
|
||||
}
|
||||
}
|
||||
+2
@@ -214,6 +214,8 @@ public class TrackRepositoryTests
|
||||
[_trackContributorEntityFixture.Create(trackId: track.Id, mediaContributorId: performer.Id, role: MediaContributorRole.Vocals)];
|
||||
context.Tracks.Add(track);
|
||||
await context.SaveChangesAsync();
|
||||
// Detach the seeded graph, so that the update must load the tracked track through its include chain instead of returning the already populated seeded instance.
|
||||
context.ChangeTracker.Clear();
|
||||
Guid contributorId = track.Contributors[0].Id;
|
||||
DateTime contributorCreatedOnUtc = track.Contributors[0].CreatedOnUtc;
|
||||
TrackEntity incoming = await LoadDetachedTrackAsync(context, track.Id);
|
||||
|
||||
+70
-2
@@ -1,11 +1,15 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Time;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
|
||||
using Lumina.DataAccess.Common.Interceptors;
|
||||
using Lumina.DataAccess.Core.Repositories.Scheduling;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
@@ -30,7 +34,7 @@ public class ScheduledJobExecutionRepositoryTests
|
||||
// The deletion uses ExecuteDeleteAsync, which is not supported by the in-memory provider, so a real SQLite database is used.
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-scheduledjobexecutionrepo-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
ScheduledJobExecutionRepository sut = new(context);
|
||||
|
||||
@@ -57,7 +61,7 @@ public class ScheduledJobExecutionRepositoryTests
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-scheduledjobexecutionrepo-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
ScheduledJobExecutionRepository sut = new(context);
|
||||
|
||||
@@ -73,4 +77,68 @@ public class ScheduledJobExecutionRepositoryTests
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(1, await context.ScheduledJobExecutions.CountAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenAnEditableValueChanges_ShouldPreserveTheCreationColumnsAndStampTheModificationColumns()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-scheduledjobexecutionrepo-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
ICurrentUserService currentUserService = Substitute.For<ICurrentUserService>();
|
||||
Guid actingUserId = Guid.NewGuid();
|
||||
currentUserService.UserId.Returns(actingUserId);
|
||||
IDateTimeProvider dateTimeProvider = Substitute.For<IDateTimeProvider>();
|
||||
DateTime insertTimeUtc = new(2020, 3, 4, 5, 6, 7, DateTimeKind.Utc);
|
||||
dateTimeProvider.UtcNow.Returns(insertTimeUtc);
|
||||
// The context is built with the auditing interceptor attached, so an interceptor regression is caught instead of being masked by its absence.
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>()
|
||||
.UseSqlite(anchorConnection.ConnectionString)
|
||||
.AddInterceptors(new UpdateAuditableEntitiesInterceptor(currentUserService, dateTimeProvider))
|
||||
.Options);
|
||||
context.Database.EnsureCreated();
|
||||
ScheduledJobExecutionRepository sut = new(context);
|
||||
|
||||
ScheduledJobExecutionEntity storedExecution = _scheduledJobExecutionEntityFixture.Create(isCycleRun: false);
|
||||
context.ScheduledJobExecutions.Add(storedExecution);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// The interceptor stamps the creation columns on insert.
|
||||
Assert.Equal(insertTimeUtc, storedExecution.CreatedOnUtc);
|
||||
Assert.Equal(actingUserId, storedExecution.CreatedBy);
|
||||
|
||||
DateTime updateTimeUtc = insertTimeUtc.AddDays(1);
|
||||
dateTimeProvider.UtcNow.Returns(updateTimeUtc);
|
||||
|
||||
ScheduledJobExecutionEntity updatedExecution = _scheduledJobExecutionEntityFixture.Create(
|
||||
id: storedExecution.Id,
|
||||
scheduledJobId: storedExecution.ScheduledJobId,
|
||||
taskType: storedExecution.TaskType,
|
||||
isCycleRun: true,
|
||||
wasCycleActive: storedExecution.WasCycleActive,
|
||||
startedOnUtc: storedExecution.StartedOnUtc,
|
||||
completedOnUtc: DateTime.UtcNow);
|
||||
// The incoming entity carries hostile audit values that must never win over the ones owned by the persistence medium.
|
||||
updatedExecution.CreatedOnUtc = insertTimeUtc.AddYears(-10);
|
||||
updatedExecution.CreatedBy = Guid.NewGuid();
|
||||
updatedExecution.UpdatedOnUtc = insertTimeUtc.AddYears(-5);
|
||||
updatedExecution.UpdatedBy = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await sut.UpdateAsync(updatedExecution, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
|
||||
await context.SaveChangesAsync();
|
||||
context.ChangeTracker.Clear();
|
||||
ScheduledJobExecutionEntity reloadedExecution = await context.ScheduledJobExecutions.AsNoTracking().FirstAsync(execution => execution.Id == storedExecution.Id);
|
||||
Assert.True(reloadedExecution.IsCycleRun);
|
||||
// The interceptor owns the modification columns and stamped them with the acting user and time, not with the incoming values.
|
||||
Assert.Equal(updateTimeUtc, reloadedExecution.UpdatedOnUtc);
|
||||
Assert.Equal(actingUserId, reloadedExecution.UpdatedBy);
|
||||
// The creation columns are still the ones stamped on insert.
|
||||
Assert.Equal(insertTimeUtc, reloadedExecution.CreatedOnUtc);
|
||||
Assert.Equal(actingUserId, reloadedExecution.CreatedBy);
|
||||
}
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling;
|
||||
using Lumina.DataAccess.Core.Repositories.Scheduling;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.IntegrationTests.Core.Repositories.Scheduling;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="ScheduledJobRepository"/> class, exercising it against a real SQLite database.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ScheduledJobRepositoryTests
|
||||
{
|
||||
private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new();
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenAnEditableValueChanges_ShouldPreserveTheStoredAuditColumns()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-scheduledjobrepo-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
ScheduledJobRepository sut = new(context);
|
||||
|
||||
DateTime storedCreatedOnUtc = new(2020, 3, 4, 5, 6, 7, DateTimeKind.Utc);
|
||||
Guid storedCreatedBy = Guid.NewGuid();
|
||||
ScheduledJobEntity storedJob = _scheduledJobEntityFixture.Create(name: "Original Job");
|
||||
storedJob.CreatedOnUtc = storedCreatedOnUtc;
|
||||
storedJob.CreatedBy = storedCreatedBy;
|
||||
context.ScheduledJobs.Add(storedJob);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
ScheduledJobEntity updatedJob = _scheduledJobEntityFixture.Create(
|
||||
id: storedJob.Id,
|
||||
name: "Updated Job",
|
||||
taskType: storedJob.TaskType,
|
||||
scheduleType: storedJob.ScheduleType,
|
||||
intervalMinutes: storedJob.IntervalMinutes,
|
||||
hour: storedJob.Hour,
|
||||
minute: storedJob.Minute,
|
||||
status: storedJob.Status,
|
||||
ownerUserId: storedJob.OwnerUserId,
|
||||
lastStartedOnUtc: storedJob.LastStartedOnUtc,
|
||||
lastCompletedOnUtc: storedJob.LastCompletedOnUtc);
|
||||
updatedJob.CreatedOnUtc = DateTime.UtcNow.AddYears(-10);
|
||||
updatedJob.CreatedBy = Guid.NewGuid();
|
||||
updatedJob.UpdatedOnUtc = DateTime.UtcNow.AddYears(-5);
|
||||
updatedJob.UpdatedBy = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await sut.UpdateAsync(updatedJob, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
|
||||
await context.SaveChangesAsync();
|
||||
context.ChangeTracker.Clear();
|
||||
ScheduledJobEntity reloadedJob = await context.ScheduledJobs.AsNoTracking().FirstAsync(job => job.Id == storedJob.Id);
|
||||
Assert.Equal("Updated Job", reloadedJob.Name);
|
||||
Assert.Equal(storedCreatedOnUtc, reloadedJob.CreatedOnUtc);
|
||||
Assert.Equal(storedCreatedBy, reloadedJob.CreatedBy);
|
||||
Assert.Null(reloadedJob.UpdatedOnUtc);
|
||||
Assert.Null(reloadedJob.UpdatedBy);
|
||||
}
|
||||
}
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Themes;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes;
|
||||
using Lumina.DataAccess.Core.Repositories.Themes;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.IntegrationTests.Core.Repositories.Themes;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="ThemeRepository"/> class, exercising it against a real SQLite database.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ThemeRepositoryTests
|
||||
{
|
||||
private readonly ThemeEntityFixture _themeEntityFixture = new();
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenAnEditableValueChanges_ShouldPreserveTheStoredAuditColumns()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-themerepo-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
ThemeRepository sut = new(context);
|
||||
|
||||
DateTime storedCreatedOnUtc = new(2020, 3, 4, 5, 6, 7, DateTimeKind.Utc);
|
||||
Guid storedCreatedBy = Guid.NewGuid();
|
||||
ThemeEntity storedTheme = _themeEntityFixture.Create(createdOnUtc: storedCreatedOnUtc, createdBy: storedCreatedBy);
|
||||
context.Themes.Add(storedTheme);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
ThemeEntity updatedTheme = _themeEntityFixture.Create(
|
||||
id: storedTheme.Id,
|
||||
themeId: storedTheme.ThemeId,
|
||||
name: "Updated Theme",
|
||||
description: storedTheme.Description,
|
||||
author: storedTheme.Author,
|
||||
version: storedTheme.Version,
|
||||
installSource: storedTheme.InstallSource,
|
||||
createdOnUtc: DateTime.UtcNow.AddYears(-10),
|
||||
createdBy: Guid.NewGuid(),
|
||||
includeUpdatedOnUtc: true,
|
||||
updatedOnUtc: DateTime.UtcNow.AddYears(-5),
|
||||
includeUpdatedBy: true,
|
||||
updatedBy: Guid.NewGuid());
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await sut.UpdateAsync(updatedTheme, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
|
||||
await context.SaveChangesAsync();
|
||||
context.ChangeTracker.Clear();
|
||||
ThemeEntity reloadedTheme = await context.Themes.AsNoTracking().FirstAsync(theme => theme.Id == storedTheme.Id);
|
||||
Assert.Equal("Updated Theme", reloadedTheme.Name);
|
||||
Assert.Equal(storedCreatedOnUtc, reloadedTheme.CreatedOnUtc);
|
||||
Assert.Equal(storedCreatedBy, reloadedTheme.CreatedBy);
|
||||
Assert.Null(reloadedTheme.UpdatedOnUtc);
|
||||
Assert.Null(reloadedTheme.UpdatedBy);
|
||||
}
|
||||
}
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.DataAccess.Core.Repositories.Users;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.IntegrationTests.Core.Repositories.Users;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="UserRepository"/> class, exercising it against a real SQLite database.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UserRepositoryTests
|
||||
{
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly PermissionEntityFixture _permissionEntityFixture = new();
|
||||
private readonly UserPermissionEntityFixture _userPermissionEntityFixture = new();
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenAnEditableValueChanges_ShouldPreserveTheStoredAuditColumns()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-userrepo-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
UserRepository sut = new(context);
|
||||
|
||||
DateTime storedCreatedOnUtc = new(2020, 3, 4, 5, 6, 7, DateTimeKind.Utc);
|
||||
Guid storedCreatedBy = Guid.NewGuid();
|
||||
UserEntity storedUser = _userEntityFixture.Create(username: "audit-user", password: "Password123");
|
||||
storedUser.CreatedOnUtc = storedCreatedOnUtc;
|
||||
storedUser.CreatedBy = storedCreatedBy;
|
||||
context.Users.Add(storedUser);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
UserEntity updatedUser = _userEntityFixture.Create(id: storedUser.Id, username: "audit-user", password: "NewPassword123");
|
||||
updatedUser.CreatedOnUtc = DateTime.UtcNow.AddYears(-10);
|
||||
updatedUser.CreatedBy = Guid.NewGuid();
|
||||
updatedUser.UpdatedOnUtc = DateTime.UtcNow.AddYears(-5);
|
||||
updatedUser.UpdatedBy = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await sut.UpdateAsync(updatedUser, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
|
||||
await context.SaveChangesAsync();
|
||||
context.ChangeTracker.Clear();
|
||||
UserEntity reloadedUser = await context.Users.AsNoTracking().FirstAsync(user => user.Id == storedUser.Id);
|
||||
Assert.Equal("NewPassword123", reloadedUser.Password);
|
||||
Assert.Equal(storedCreatedOnUtc, reloadedUser.CreatedOnUtc);
|
||||
Assert.Equal(storedCreatedBy, reloadedUser.CreatedBy);
|
||||
Assert.Null(reloadedUser.UpdatedOnUtc);
|
||||
Assert.Null(reloadedUser.UpdatedBy);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenNothingChanged_ShouldNotDuplicateThePermissions()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-userrepo-permissions-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
UserRepository sut = new(context);
|
||||
|
||||
PermissionEntity firstPermission = _permissionEntityFixture.Create();
|
||||
PermissionEntity secondPermission = _permissionEntityFixture.Create();
|
||||
UserEntity storedUser = _userEntityFixture.Create(username: $"perm-user-{Guid.NewGuid():N}", password: "Password123");
|
||||
context.Permissions.AddRange(firstPermission, secondPermission);
|
||||
context.Users.Add(storedUser);
|
||||
await context.SaveChangesAsync();
|
||||
storedUser.UserPermissions.Add(_userPermissionEntityFixture.Create(storedUser, firstPermission));
|
||||
storedUser.UserPermissions.Add(_userPermissionEntityFixture.Create(storedUser, secondPermission));
|
||||
await context.SaveChangesAsync();
|
||||
// Detach the seeded user, so that the update must load it through its include chain instead of returning the already populated seeded instance.
|
||||
context.ChangeTracker.Clear();
|
||||
|
||||
UserEntity incoming = await context.Users.AsNoTracking().Include(candidate => candidate.UserPermissions).FirstAsync(candidate => candidate.Id == storedUser.Id);
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await sut.UpdateAsync(incoming, CancellationToken.None);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
UserEntity? reloadedUser = await context.Users.AsNoTracking().Include(candidate => candidate.UserPermissions).FirstOrDefaultAsync(candidate => candidate.Id == storedUser.Id);
|
||||
Assert.NotNull(reloadedUser);
|
||||
Assert.Equal(2, reloadedUser!.UserPermissions.Count);
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.DataAccess.Core.Repositories.Users;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.IntegrationTests.Core.Repositories.Users;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="UserSettingsRepository"/> class, exercising it against a real SQLite database.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UserSettingsRepositoryTests
|
||||
{
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new();
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenAnEditableValueChanges_ShouldPreserveTheStoredAuditColumns()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-usersettingsrepo-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
UserSettingsRepository sut = new(context);
|
||||
|
||||
UserEntity storedUser = _userEntityFixture.Create(username: "settings-user", password: "Password123");
|
||||
context.Users.Add(storedUser);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
DateTime storedCreatedOnUtc = new(2020, 3, 4, 5, 6, 7, DateTimeKind.Utc);
|
||||
Guid storedCreatedBy = Guid.NewGuid();
|
||||
UserSettingsEntity storedSettings = _userSettingsEntityFixture.Create(userId: storedUser.Id, itemsPerPage: 10);
|
||||
storedSettings.CreatedOnUtc = storedCreatedOnUtc;
|
||||
storedSettings.CreatedBy = storedCreatedBy;
|
||||
context.UserSettings.Add(storedSettings);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
UserSettingsEntity updatedSettings = _userSettingsEntityFixture.Create(id: storedSettings.Id, userId: storedUser.Id, itemsPerPage: 25);
|
||||
updatedSettings.CreatedOnUtc = DateTime.UtcNow.AddYears(-10);
|
||||
updatedSettings.CreatedBy = Guid.NewGuid();
|
||||
updatedSettings.UpdatedOnUtc = DateTime.UtcNow.AddYears(-5);
|
||||
updatedSettings.UpdatedBy = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await sut.UpdateAsync(updatedSettings, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
|
||||
await context.SaveChangesAsync();
|
||||
context.ChangeTracker.Clear();
|
||||
UserSettingsEntity reloadedSettings = await context.UserSettings.AsNoTracking().FirstAsync(settings => settings.Id == storedSettings.Id);
|
||||
Assert.Equal(25, reloadedSettings.ItemsPerPage);
|
||||
Assert.Equal(storedCreatedOnUtc, reloadedSettings.CreatedOnUtc);
|
||||
Assert.Equal(storedCreatedBy, reloadedSettings.CreatedBy);
|
||||
Assert.Null(reloadedSettings.UpdatedOnUtc);
|
||||
Assert.Null(reloadedSettings.UpdatedBy);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user