mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 11:11:10 +00:00
Adds library ownership authorization policy
This commit is contained in:
1 parent
65a630155d
commit
a7dfcbe926
23 files changed
+645
-202
No files matched your search
+1
-1
@@ -14,7 +14,7 @@ namespace Lumina.Infrastructure.Fixtures.Core.Authorization;
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class TestAuthorizationPolicy : IAuthorizationPolicy
|
||||
{
|
||||
public Task<bool> EvaluateAsync(Guid userId, CancellationToken cancellationToken)
|
||||
public Task<bool> EvaluateAsync(Guid userId, PolicyContext? context, CancellationToken cancellationToken)
|
||||
{
|
||||
return Task.FromResult(true);
|
||||
}
|
||||
|
||||
+173
@@ -0,0 +1,173 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibrary;
|
||||
using Lumina.Application.Fixtures.Core.MediaLibrary.Management.Queries.GetLibrary;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.Management;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
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;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.MediaLibrary.Management.Queries.GetLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetLibraryQueryHandler"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetLibraryQueryHandlerTests
|
||||
{
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly ILibraryRepository _mockLibraryRepository;
|
||||
private readonly IAuthorizationService _mockAuthorizationService;
|
||||
private readonly ICurrentUserService _mockCurrentUserService;
|
||||
private readonly IValidator<GetLibraryQuery> _mockValidator;
|
||||
private readonly GetLibraryQueryHandler _sut;
|
||||
private readonly Guid _userId;
|
||||
private readonly GetLibraryQueryFixture _getLibraryQueryFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibraryQueryHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public GetLibraryQueryHandlerTests()
|
||||
{
|
||||
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
|
||||
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
|
||||
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
|
||||
_mockValidator = Substitute.For<IValidator<GetLibraryQuery>>();
|
||||
_userId = Guid.NewGuid();
|
||||
|
||||
// default stubs: the current user is authenticated and the library ownership policy allows access
|
||||
_mockCurrentUserService.UserId.Returns(_userId);
|
||||
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
|
||||
.Returns(true);
|
||||
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From((LibraryEntity?)new LibraryEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = _userId,
|
||||
Title = "Test Library",
|
||||
LibraryType = LibraryType.EBook,
|
||||
ContentLocations = [],
|
||||
CreatedBy = _userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
}));
|
||||
_mockValidator.Validate(Arg.Any<GetLibraryQuery>()).Returns([]);
|
||||
|
||||
_sut = new GetLibraryQueryHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork, _mockValidator);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenPolicyAllowsAccess_ShouldReturnLibraryResponse()
|
||||
{
|
||||
// Arrange
|
||||
GetLibraryQuery query = _getLibraryQueryFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<LibraryResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedError()
|
||||
{
|
||||
// Arrange
|
||||
GetLibraryQuery query = _getLibraryQueryFixture.Create();
|
||||
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
|
||||
.Returns(false);
|
||||
|
||||
// Act
|
||||
Result<LibraryResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
||||
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == query.Id), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
|
||||
{
|
||||
// Arrange
|
||||
GetLibraryQuery query = _getLibraryQueryFixture.Create();
|
||||
_mockCurrentUserService.UserId.Returns((Guid?)null);
|
||||
|
||||
// Act
|
||||
Result<LibraryResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
|
||||
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
GetLibraryQuery query = _getLibraryQueryFixture.Create();
|
||||
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result<LibraryEntity?>.Success(null));
|
||||
|
||||
// Act
|
||||
Result<LibraryResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(DomainErrors.Library.LibraryNotFound, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenRepositoryFails_ShouldReturnRepositoryError()
|
||||
{
|
||||
// Arrange
|
||||
GetLibraryQuery query = _getLibraryQueryFixture.Create();
|
||||
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Errors.Library.LibraryNotFound);
|
||||
|
||||
// Act
|
||||
Result<LibraryResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Library.LibraryNotFound, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutQuerying()
|
||||
{
|
||||
// Arrange
|
||||
GetLibraryQuery query = _getLibraryQueryFixture.Create();
|
||||
_mockValidator.Validate(Arg.Any<GetLibraryQuery>()).Returns([Errors.Library.LibraryIdCannotBeEmpty]);
|
||||
|
||||
// Act
|
||||
Result<LibraryResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
|
||||
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+14
-69
@@ -1,11 +1,10 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Books;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
@@ -15,7 +14,6 @@ using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Common;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
@@ -38,7 +36,6 @@ public class GetBooksQueryHandlerTests
|
||||
{
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly IBookRepository _mockBookRepository;
|
||||
private readonly ILibraryRepository _mockLibraryRepository;
|
||||
private readonly IAuthorizationService _mockAuthorizationService;
|
||||
private readonly ICurrentUserService _mockCurrentUserService;
|
||||
private readonly IValidator<GetBooksQuery> _mockValidator;
|
||||
@@ -55,35 +52,22 @@ public class GetBooksQueryHandlerTests
|
||||
_mockBookRepository = Substitute.For<IBookRepository>();
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
|
||||
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
|
||||
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
|
||||
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
|
||||
_mockValidator = Substitute.For<IValidator<GetBooksQuery>>();
|
||||
_userId = Guid.NewGuid();
|
||||
|
||||
// default stubs: the current user is not an admin, but owns the requested library
|
||||
// default stubs: the current user is authenticated and the library ownership policy allows access
|
||||
_mockCurrentUserService.UserId.Returns(_userId);
|
||||
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(false);
|
||||
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From((LibraryEntity?)new LibraryEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = _userId,
|
||||
Title = "Test Library",
|
||||
LibraryType = LibraryType.EBook,
|
||||
ContentLocations = [],
|
||||
CreatedBy = _userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
}));
|
||||
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
|
||||
.Returns(true);
|
||||
_mockValidator.Validate(Arg.Any<GetBooksQuery>()).Returns([]);
|
||||
|
||||
_sut = new GetBooksQueryHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenRepositoryReturnsPaginatedBooks_ShouldReturnMappedPaginatedResponses()
|
||||
public async Task HandleAsync_WhenPolicyAllowsAccess_ShouldReturnMappedPaginatedResponses()
|
||||
{
|
||||
// Arrange
|
||||
GetBooksQuery query = _getBooksQueryFixture.Create();
|
||||
@@ -241,53 +225,12 @@ public class GetBooksQueryHandlerTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenUserIsAdmin_ShouldBypassLibraryOwnershipCheck()
|
||||
public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedError()
|
||||
{
|
||||
// Arrange
|
||||
GetBooksQuery query = _getBooksQueryFixture.Create();
|
||||
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(true);
|
||||
PaginatedResultDto<BookEntity> paginatedBooks = new()
|
||||
{
|
||||
Data = [],
|
||||
CurrentPage = 1,
|
||||
PerPage = 10,
|
||||
Count = 0,
|
||||
NumberOfPages = 0
|
||||
};
|
||||
_mockBookRepository.GetPaginatedAsync(
|
||||
Arg.Any<PaginationDataDto?>(),
|
||||
Arg.Any<string?>(),
|
||||
Arg.Any<SortOrder?>(),
|
||||
Arg.Any<LibraryFilterDto>(),
|
||||
Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(paginatedBooks));
|
||||
|
||||
// Act
|
||||
Result<PaginatedResponse<BookResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
await _mockUnitOfWork.LibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenUserDoesNotOwnLibrary_ShouldReturnNotAuthorizedError()
|
||||
{
|
||||
// Arrange
|
||||
GetBooksQuery query = _getBooksQueryFixture.Create();
|
||||
Guid otherUserId = Guid.NewGuid();
|
||||
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From((LibraryEntity?)new LibraryEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = otherUserId,
|
||||
Title = "Someone else's library",
|
||||
LibraryType = LibraryType.EBook,
|
||||
ContentLocations = [],
|
||||
CreatedBy = otherUserId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
}));
|
||||
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
|
||||
.Returns(false);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResponse<BookResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
@@ -295,16 +238,17 @@ public class GetBooksQueryHandlerTests
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
||||
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == query.Filter.LibraryId), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().GetPaginatedAsync(Arg.Any<PaginationDataDto?>(), Arg.Any<string?>(), Arg.Any<SortOrder?>(), Arg.Any<LibraryFilterDto>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnNotAuthorizedError()
|
||||
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
|
||||
{
|
||||
// Arrange
|
||||
GetBooksQuery query = _getBooksQueryFixture.Create();
|
||||
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result<LibraryEntity?>.Success(null));
|
||||
_mockCurrentUserService.UserId.Returns((Guid?)null);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResponse<BookResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
@@ -312,6 +256,7 @@ public class GetBooksQueryHandlerTests
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().GetPaginatedAsync(Arg.Any<PaginationDataDto?>(), Arg.Any<string?>(), Arg.Any<SortOrder?>(), Arg.Any<LibraryFilterDto>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
@@ -328,7 +273,7 @@ public class GetBooksQueryHandlerTests
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
|
||||
await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().GetPaginatedAsync(Arg.Any<PaginationDataDto?>(), Arg.Any<string?>(), Arg.Any<SortOrder?>(), Arg.Any<LibraryFilterDto>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+14
-69
@@ -1,11 +1,10 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Books;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
@@ -15,7 +14,6 @@ using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Common;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
@@ -38,7 +36,6 @@ public class GetBooksLiteQueryHandlerTests
|
||||
{
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly IBookRepository _mockBookRepository;
|
||||
private readonly ILibraryRepository _mockLibraryRepository;
|
||||
private readonly IAuthorizationService _mockAuthorizationService;
|
||||
private readonly ICurrentUserService _mockCurrentUserService;
|
||||
private readonly IValidator<GetBooksLiteQuery> _mockValidator;
|
||||
@@ -55,35 +52,22 @@ public class GetBooksLiteQueryHandlerTests
|
||||
_mockBookRepository = Substitute.For<IBookRepository>();
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
|
||||
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
|
||||
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
|
||||
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
|
||||
_mockValidator = Substitute.For<IValidator<GetBooksLiteQuery>>();
|
||||
_userId = Guid.NewGuid();
|
||||
|
||||
// default stubs: the current user is not an admin, but owns the requested library
|
||||
// default stubs: the current user is authenticated and the library ownership policy allows access
|
||||
_mockCurrentUserService.UserId.Returns(_userId);
|
||||
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(false);
|
||||
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From((LibraryEntity?)new LibraryEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = _userId,
|
||||
Title = "Test Library",
|
||||
LibraryType = LibraryType.EBook,
|
||||
ContentLocations = [],
|
||||
CreatedBy = _userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
}));
|
||||
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
|
||||
.Returns(true);
|
||||
_mockValidator.Validate(Arg.Any<GetBooksLiteQuery>()).Returns([]);
|
||||
|
||||
_sut = new GetBooksLiteQueryHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenRepositoryReturnsPaginatedBooks_ShouldReturnMappedPaginatedResponses()
|
||||
public async Task HandleAsync_WhenPolicyAllowsAccess_ShouldReturnMappedPaginatedResponses()
|
||||
{
|
||||
// Arrange
|
||||
GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create();
|
||||
@@ -241,53 +225,12 @@ public class GetBooksLiteQueryHandlerTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenUserIsAdmin_ShouldBypassLibraryOwnershipCheck()
|
||||
public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedError()
|
||||
{
|
||||
// Arrange
|
||||
GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create();
|
||||
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(true);
|
||||
PaginatedResultDto<BookEntity> paginatedBooks = new()
|
||||
{
|
||||
Data = [],
|
||||
CurrentPage = 1,
|
||||
PerPage = 10,
|
||||
Count = 0,
|
||||
NumberOfPages = 0
|
||||
};
|
||||
_mockBookRepository.GetPaginatedAsync(
|
||||
Arg.Any<PaginationDataDto?>(),
|
||||
Arg.Any<string?>(),
|
||||
Arg.Any<SortOrder?>(),
|
||||
Arg.Any<LibraryFilterDto>(),
|
||||
Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(paginatedBooks));
|
||||
|
||||
// Act
|
||||
Result<PaginatedResponse<BookLiteResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
await _mockUnitOfWork.LibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenUserDoesNotOwnLibrary_ShouldReturnNotAuthorizedError()
|
||||
{
|
||||
// Arrange
|
||||
GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create();
|
||||
Guid otherUserId = Guid.NewGuid();
|
||||
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From((LibraryEntity?)new LibraryEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = otherUserId,
|
||||
Title = "Someone else's library",
|
||||
LibraryType = LibraryType.EBook,
|
||||
ContentLocations = [],
|
||||
CreatedBy = otherUserId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
}));
|
||||
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
|
||||
.Returns(false);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResponse<BookLiteResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
@@ -295,16 +238,17 @@ public class GetBooksLiteQueryHandlerTests
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
||||
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == query.Filter.LibraryId), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().GetPaginatedAsync(Arg.Any<PaginationDataDto?>(), Arg.Any<string?>(), Arg.Any<SortOrder?>(), Arg.Any<LibraryFilterDto>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnNotAuthorizedError()
|
||||
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
|
||||
{
|
||||
// Arrange
|
||||
GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create();
|
||||
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result<LibraryEntity?>.Success(null));
|
||||
_mockCurrentUserService.UserId.Returns((Guid?)null);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResponse<BookLiteResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
@@ -312,6 +256,7 @@ public class GetBooksLiteQueryHandlerTests
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().GetPaginatedAsync(Arg.Any<PaginationDataDto?>(), Arg.Any<string?>(), Arg.Any<SortOrder?>(), Arg.Any<LibraryFilterDto>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
@@ -328,7 +273,7 @@ public class GetBooksLiteQueryHandlerTests
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
|
||||
await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().GetPaginatedAsync(Arg.Any<PaginationDataDto?>(), Arg.Any<string?>(), Arg.Any<SortOrder?>(), Arg.Any<LibraryFilterDto>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+22
-15
@@ -4,6 +4,7 @@ using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Users;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.Common.Base;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
|
||||
@@ -280,19 +281,20 @@ public class AuthorizationServiceTests
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
PolicyContext context = new LibraryOwnershipPolicyContext(Guid.NewGuid());
|
||||
IAuthorizationPolicy mockPolicy = Substitute.For<IAuthorizationPolicy>();
|
||||
mockPolicy.EvaluateAsync(userId, Arg.Any<CancellationToken>())
|
||||
mockPolicy.EvaluateAsync(userId, context, Arg.Any<CancellationToken>())
|
||||
.Returns(true);
|
||||
|
||||
_mockAuthorizationPolicyFactory.CreatePolicy<IAuthorizationPolicy>()
|
||||
.Returns(mockPolicy);
|
||||
|
||||
// Act
|
||||
bool result = await _sut.EvaluatePolicyAsync<IAuthorizationPolicy>(userId, CancellationToken.None);
|
||||
bool result = await _sut.EvaluatePolicyAsync<IAuthorizationPolicy>(userId, context, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
await mockPolicy.Received(1).EvaluateAsync(userId, Arg.Any<CancellationToken>());
|
||||
await mockPolicy.Received(1).EvaluateAsync(userId, context, Arg.Any<CancellationToken>());
|
||||
_mockAuthorizationPolicyFactory.Received(1).CreatePolicy<IAuthorizationPolicy>();
|
||||
}
|
||||
|
||||
@@ -301,19 +303,20 @@ public class AuthorizationServiceTests
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
PolicyContext context = new LibraryOwnershipPolicyContext(Guid.NewGuid());
|
||||
IAuthorizationPolicy mockPolicy = Substitute.For<IAuthorizationPolicy>();
|
||||
mockPolicy.EvaluateAsync(userId, Arg.Any<CancellationToken>())
|
||||
mockPolicy.EvaluateAsync(userId, context, Arg.Any<CancellationToken>())
|
||||
.Returns(false);
|
||||
|
||||
_mockAuthorizationPolicyFactory.CreatePolicy<IAuthorizationPolicy>()
|
||||
.Returns(mockPolicy);
|
||||
|
||||
// Act
|
||||
bool result = await _sut.EvaluatePolicyAsync<IAuthorizationPolicy>(userId, CancellationToken.None);
|
||||
bool result = await _sut.EvaluatePolicyAsync<IAuthorizationPolicy>(userId, context, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
await mockPolicy.Received(1).EvaluateAsync(userId, Arg.Any<CancellationToken>());
|
||||
await mockPolicy.Received(1).EvaluateAsync(userId, context, Arg.Any<CancellationToken>());
|
||||
_mockAuthorizationPolicyFactory.Received(1).CreatePolicy<IAuthorizationPolicy>();
|
||||
}
|
||||
|
||||
@@ -322,20 +325,21 @@ public class AuthorizationServiceTests
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
PolicyContext context = new LibraryOwnershipPolicyContext(Guid.NewGuid());
|
||||
IAuthorizationPolicy mockPolicy = Substitute.For<IAuthorizationPolicy>();
|
||||
mockPolicy.EvaluateAsync(userId, Arg.Any<CancellationToken>())
|
||||
mockPolicy.EvaluateAsync(userId, context, Arg.Any<CancellationToken>())
|
||||
.Throws(new InvalidOperationException("Policy evaluation failed"));
|
||||
|
||||
_mockAuthorizationPolicyFactory.CreatePolicy<IAuthorizationPolicy>()
|
||||
.Returns(mockPolicy);
|
||||
|
||||
// Act
|
||||
Func<Task> act = async () => await _sut.EvaluatePolicyAsync<IAuthorizationPolicy>(userId, CancellationToken.None);
|
||||
Func<Task> act = async () => await _sut.EvaluatePolicyAsync<IAuthorizationPolicy>(userId, context, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
InvalidOperationException exception = await Assert.ThrowsAsync<InvalidOperationException>(act);
|
||||
Assert.Equal("Policy evaluation failed", exception.Message);
|
||||
await mockPolicy.Received(1).EvaluateAsync(userId, Arg.Any<CancellationToken>());
|
||||
await mockPolicy.Received(1).EvaluateAsync(userId, context, Arg.Any<CancellationToken>());
|
||||
_mockAuthorizationPolicyFactory.Received(1).CreatePolicy<IAuthorizationPolicy>();
|
||||
}
|
||||
|
||||
@@ -344,11 +348,12 @@ public class AuthorizationServiceTests
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
PolicyContext context = new LibraryOwnershipPolicyContext(Guid.NewGuid());
|
||||
_mockAuthorizationPolicyFactory.CreatePolicy<IAuthorizationPolicy>()
|
||||
.Throws(new InvalidOperationException("Policy creation failed"));
|
||||
|
||||
// Act
|
||||
Func<Task> act = async () => await _sut.EvaluatePolicyAsync<IAuthorizationPolicy>(userId, CancellationToken.None);
|
||||
Func<Task> act = async () => await _sut.EvaluatePolicyAsync<IAuthorizationPolicy>(userId, context, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
InvalidOperationException exception = await Assert.ThrowsAsync<InvalidOperationException>(act);
|
||||
@@ -361,6 +366,7 @@ public class AuthorizationServiceTests
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
PolicyContext context = new LibraryOwnershipPolicyContext(Guid.NewGuid());
|
||||
IAuthorizationPolicy mockPolicy = Substitute.For<IAuthorizationPolicy>();
|
||||
CancellationToken cancellationToken = new(true);
|
||||
|
||||
@@ -368,10 +374,10 @@ public class AuthorizationServiceTests
|
||||
.Returns(mockPolicy);
|
||||
|
||||
// Act
|
||||
await _sut.EvaluatePolicyAsync<IAuthorizationPolicy>(userId, cancellationToken);
|
||||
await _sut.EvaluatePolicyAsync<IAuthorizationPolicy>(userId, context, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await mockPolicy.Received(1).EvaluateAsync(userId, cancellationToken);
|
||||
await mockPolicy.Received(1).EvaluateAsync(userId, context, cancellationToken);
|
||||
_mockAuthorizationPolicyFactory.Received(1).CreatePolicy<IAuthorizationPolicy>();
|
||||
}
|
||||
|
||||
@@ -380,19 +386,20 @@ public class AuthorizationServiceTests
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
PolicyContext context = new LibraryOwnershipPolicyContext(Guid.NewGuid());
|
||||
IAuthorizationPolicy mockPolicy = Substitute.For<ITestAuthorizationPolicy>();
|
||||
mockPolicy.EvaluateAsync(userId, Arg.Any<CancellationToken>())
|
||||
mockPolicy.EvaluateAsync(userId, context, Arg.Any<CancellationToken>())
|
||||
.Returns(true);
|
||||
|
||||
_mockAuthorizationPolicyFactory.CreatePolicy<ITestAuthorizationPolicy>()
|
||||
.Returns(mockPolicy);
|
||||
|
||||
// Act
|
||||
bool result = await _sut.EvaluatePolicyAsync<ITestAuthorizationPolicy>(userId, CancellationToken.None);
|
||||
bool result = await _sut.EvaluatePolicyAsync<ITestAuthorizationPolicy>(userId, context, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
await mockPolicy.Received(1).EvaluateAsync(userId, Arg.Any<CancellationToken>());
|
||||
await mockPolicy.Received(1).EvaluateAsync(userId, context, Arg.Any<CancellationToken>());
|
||||
_mockAuthorizationPolicyFactory.Received(1).CreatePolicy<ITestAuthorizationPolicy>();
|
||||
}
|
||||
|
||||
|
||||
+216
@@ -0,0 +1,216 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Users;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.Common.Base;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Infrastructure.Core.Authorization.Policies.LibraryOwnership;
|
||||
using Lumina.Infrastructure.Fixtures.Core.Authorization;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.Authorization.Policies.LibraryOwnership;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="LibraryOwnershipPolicy"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LibraryOwnershipPolicyTests
|
||||
{
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly IUserRepository _mockUserRepository;
|
||||
private readonly ILibraryRepository _mockLibraryRepository;
|
||||
private readonly LibraryOwnershipPolicy _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LibraryOwnershipPolicyTests"/> class.
|
||||
/// </summary>
|
||||
public LibraryOwnershipPolicyTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockUserRepository = Substitute.For<IUserRepository>();
|
||||
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
_mockUnitOfWork.UserRepository.Returns(_mockUserRepository);
|
||||
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
|
||||
|
||||
_sut = new LibraryOwnershipPolicy(_mockUnitOfWork);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EvaluateAsync_WhenContextIsNotLibraryOwnershipContext_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
bool result = await _sut.EvaluateAsync(userId, null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
await _mockUserRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EvaluateAsync_WhenUserDoesNotExist_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
LibraryOwnershipPolicyContext context = new(Guid.NewGuid());
|
||||
_mockUserRepository.GetByIdAsync(userId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<UserEntity?>(null));
|
||||
|
||||
// Act
|
||||
bool result = await _sut.EvaluateAsync(userId, context, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EvaluateAsync_WhenGetUserFails_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
LibraryOwnershipPolicyContext context = new(Guid.NewGuid());
|
||||
_mockUserRepository.GetByIdAsync(userId, Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Database.Error", "Failed to retrieve user"));
|
||||
|
||||
// Act
|
||||
bool result = await _sut.EvaluateAsync(userId, context, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EvaluateAsync_WhenUserIsAdmin_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
UserEntity adminUser = AuthorizationServiceFixture.CreateUserWithPermissions(
|
||||
rolePermissions: new Dictionary<string, IEnumerable<AuthorizationPermission>>
|
||||
{
|
||||
{ "Admin", [] }
|
||||
});
|
||||
LibraryOwnershipPolicyContext context = new(Guid.NewGuid());
|
||||
_mockUserRepository.GetByIdAsync(adminUser.Id, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<UserEntity?>(adminUser));
|
||||
|
||||
// Act
|
||||
bool result = await _sut.EvaluateAsync(adminUser.Id, context, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EvaluateAsync_WhenLibraryDoesNotExist_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
UserEntity regularUser = AuthorizationServiceFixture.CreateUserWithPermissions();
|
||||
LibraryOwnershipPolicyContext context = new(Guid.NewGuid());
|
||||
_mockUserRepository.GetByIdAsync(userId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<UserEntity?>(regularUser));
|
||||
_mockLibraryRepository.GetByIdAsync(context.LibraryId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result<LibraryEntity?>.Success(null));
|
||||
|
||||
// Act
|
||||
bool result = await _sut.EvaluateAsync(userId, context, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EvaluateAsync_WhenGetLibraryFails_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
UserEntity regularUser = AuthorizationServiceFixture.CreateUserWithPermissions();
|
||||
LibraryOwnershipPolicyContext context = new(Guid.NewGuid());
|
||||
_mockUserRepository.GetByIdAsync(userId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<UserEntity?>(regularUser));
|
||||
_mockLibraryRepository.GetByIdAsync(context.LibraryId, Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Database.Error", "Failed to retrieve library"));
|
||||
|
||||
// Act
|
||||
bool result = await _sut.EvaluateAsync(userId, context, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EvaluateAsync_WhenUserOwnsLibrary_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
UserEntity regularUser = AuthorizationServiceFixture.CreateUserWithPermissions();
|
||||
LibraryEntity library = CreateLibrary(userId);
|
||||
LibraryOwnershipPolicyContext context = new(library.Id);
|
||||
_mockUserRepository.GetByIdAsync(userId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<UserEntity?>(regularUser));
|
||||
_mockLibraryRepository.GetByIdAsync(context.LibraryId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(library));
|
||||
|
||||
// Act
|
||||
bool result = await _sut.EvaluateAsync(userId, context, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EvaluateAsync_WhenUserDoesNotOwnLibrary_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
UserEntity regularUser = AuthorizationServiceFixture.CreateUserWithPermissions();
|
||||
LibraryEntity library = CreateLibrary(Guid.NewGuid());
|
||||
LibraryOwnershipPolicyContext context = new(library.Id);
|
||||
_mockUserRepository.GetByIdAsync(userId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<UserEntity?>(regularUser));
|
||||
_mockLibraryRepository.GetByIdAsync(context.LibraryId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(library));
|
||||
|
||||
// Act
|
||||
bool result = await _sut.EvaluateAsync(userId, context, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a library entity owned by <paramref name="ownerId"/>.
|
||||
/// </summary>
|
||||
/// <param name="ownerId">The Id of the user owning the library.</param>
|
||||
/// <returns>The created library entity.</returns>
|
||||
private static LibraryEntity CreateLibrary(Guid ownerId)
|
||||
{
|
||||
return new LibraryEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = ownerId,
|
||||
Title = "Test Library",
|
||||
LibraryType = LibraryType.Book,
|
||||
ContentLocations = [],
|
||||
CreatedBy = ownerId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user