using Heimdall.Application.Common; using Heimdall.Application.Common.Persistence; using Heimdall.Application.Users.Commands.UnlockUser; using Heimdall.Domain.Entities; using Microsoft.AspNetCore.Identity; using NSubstitute; namespace Heimdall.Application.Tests.Handlers.Users; public class UnlockUserHandlerTests { private readonly AppUser _user = new() { Id = Guid.NewGuid(), UserName = "locked@test.com", Email = "locked@test.com", LockoutEnd = DateTimeOffset.UtcNow.AddHours(1) }; private readonly UserManager _userManager; private readonly IUserRepository _repository; private readonly UnlockUserHandler _handler; public UnlockUserHandlerTests() { var store = Substitute.For>(); _userManager = Substitute.For>(store, null!, null!, null!, null!, null!, null!, null!, null!); _repository = Substitute.For(); _handler = new UnlockUserHandler(_userManager, _repository); } [Fact] public async Task Unlock_user_should_return_success() { _userManager.FindByIdAsync(_user.Id.ToString()).Returns(_user); _userManager.SetLockoutEndDateAsync(_user, null).Returns(IdentityResult.Success); _userManager.ResetAccessFailedCountAsync(_user).Returns(IdentityResult.Success); 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()).Returns((AppUser?)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 AppUser { Id = Guid.NewGuid(), UserName = "unlocked@test.com", Email = "unlocked@test.com", LockoutEnd = null }; _userManager.FindByIdAsync(unlockedUser.Id.ToString()).Returns(unlockedUser); _userManager.SetLockoutEndDateAsync(unlockedUser, null).Returns(IdentityResult.Success); _userManager.ResetAccessFailedCountAsync(unlockedUser).Returns(IdentityResult.Success); var result = await _handler.Handle(new UnlockUserCommand(unlockedUser.Id), CancellationToken.None); result.IsSuccess.ShouldBeTrue(); } }