using Heimdall.Application.Common; using Heimdall.Application.Common.Persistence; using Heimdall.Application.Users.Commands.UnlockUser; using Heimdall.Domain.Entities; using NSubstitute; using Heimdall.Application.Services; namespace Heimdall.Application.Tests.Handlers.Users; public class UnlockUserHandlerTests { private readonly IdentityAccount _user = new() { Id = Guid.NewGuid(), UserName = "locked@test.com", Email = "locked@test.com", LockoutEnd = DateTimeOffset.UtcNow.AddHours(1) }; private readonly IIdentityAccountService _userManager; private readonly IUserRepository _repository; private readonly UnlockUserHandler _handler; public UnlockUserHandlerTests() { _userManager = Substitute.For(); _repository = Substitute.For(); _handler = new UnlockUserHandler(_userManager, _repository); } [Fact] public async Task Unlock_user_should_return_success() { _userManager.FindByIdAsync(_user.Id, Arg.Any()).Returns(_user); _userManager.SetLockoutEndDateAsync(_user, null).Returns(IdentityOperationResult.Success); _userManager.ResetAccessFailedCountAsync(_user).Returns(IdentityOperationResult.Success); _userManager.UpdateSecurityStampAsync(_user).Returns(true); var result = await _handler.Handle(new UnlockUserCommand(_user.Id), CancellationToken.None); result.IsSuccess.ShouldBeTrue(); await _repository.Received(1).AddAuditLogAsync(null, "UserUnlocked", "User", _user.Id.ToString(), null, null, Arg.Any()); } [Fact] public async Task Unlock_nonexistent_user_should_return_not_found() { _userManager.FindByIdAsync(Arg.Any(), Arg.Any()).Returns((IdentityAccount?)null); var result = await _handler.Handle(new UnlockUserCommand(Guid.NewGuid()), CancellationToken.None); result.IsSuccess.ShouldBeFalse(); result.StatusCode.ShouldBe(404); } [Fact] public async Task Unlock_already_unlocked_user_should_return_success() { var unlockedUser = new IdentityAccount { Id = Guid.NewGuid(), UserName = "unlocked@test.com", Email = "unlocked@test.com", LockoutEnd = null }; _userManager.FindByIdAsync(unlockedUser.Id, Arg.Any()).Returns(unlockedUser); _userManager.SetLockoutEndDateAsync(unlockedUser, null).Returns(IdentityOperationResult.Success); _userManager.ResetAccessFailedCountAsync(unlockedUser).Returns(IdentityOperationResult.Success); _userManager.UpdateSecurityStampAsync(unlockedUser).Returns(true); var result = await _handler.Handle(new UnlockUserCommand(unlockedUser.Id), CancellationToken.None); result.IsSuccess.ShouldBeTrue(); } }