Files
SIG-CM2.0/tests/SIGCM2.Application.Tests/Usuarios/UpdateUsuarioCommandHandlerTests.cs

142 lines
6.1 KiB
C#
Raw Normal View History

using FluentValidation;
using NSubstitute;
using NSubstitute.ExceptionExtensions;
using SIGCM2.Application.Abstractions.Persistence;
feat(audit): enchufar audit en handlers de Usuario — Closes #6 7 command handlers del módulo Usuarios ahora auditan via IAuditLogger: | Handler | Action | |-----------------------------------------|-------------------------| | CreateUsuarioCommandHandler | usuario.create | | UpdateUsuarioCommandHandler | usuario.update | | DeactivateUsuarioCommandHandler | usuario.deactivate | | ReactivateUsuarioCommandHandler | usuario.reactivate | | ChangeMyPasswordCommandHandler | usuario.password_change | | ResetUsuarioPasswordCommandHandler | usuario.password_reset | | UpdateUsuarioPermisosOverridesHandler | usuario.permisos_update | Patrón por handler (per design #D-1): using (var tx = new TransactionScope(Required, ReadCommitted, AsyncFlowEnabled)) { await repo.UpdateAsync(...); await audit.LogAsync(...); tx.Complete(); } // post-commit reads OUTSIDE the using block var updated = await repo.GetDetailAsync(...); Metadata captured: - usuario.create: after={username, nombre, apellido, email, rol} — NO password. - usuario.update: {before, after} diff of editable fields. - usuario.password_reset: {targetId} only — tempPassword is NEVER persisted to audit (returned to caller once, never stored). - usuario.permisos_update: {before, after} of grant/deny override lists. Key fix during implementation: initially used 'using var tx = ...' (bare declaration). This kept the TransactionScope active for the rest of the method, causing 'The current TransactionScope is already complete' when post-commit reads (GetDetailAsync) tried to enlist. Solution: explicit 'using (var tx = ...) { ... }' block that disposes the scope before post-commit reads. AuditContextMissingException surfaces from AuditLogger when IAuditContext lacks ActorUserId — fail-closed per #REQ-AUD-4. In integration tests, the middleware populates ActorUserId from the JWT sub of the authenticated admin. Test updates: 6 existing unit test classes now inject IAuditLogger mock: - CreateUsuarioCommandHandlerTests - UpdateUsuarioCommandHandlerTests - DeactivateUsuarioCommandHandlerTests - ReactivateUsuarioCommandHandlerTests - ChangeMyPasswordCommandHandlerTests - ResetUsuarioPasswordCommandHandlerTests Follow-up #6 ([Auditoría] Registrar admin creador en alta de usuarios) is closed: CreateUsuarioCommandHandler now records ActorUserId = admin JWT sub on every user creation. TODO comment removed. Suite: 378/378 Application.Tests + 141/141 Api.Tests = 519/519 passing. Closes #6 Refs: sdd/udt-010-auditoria-trazabilidad/{spec#REQ-UM-AUD, design, tasks#B7}
2026-04-16 13:49:44 -03:00
using SIGCM2.Application.Audit;
using SIGCM2.Application.Common;
using SIGCM2.Application.Usuarios.Update;
using SIGCM2.Domain.Entities;
using SIGCM2.Domain.Exceptions;
namespace SIGCM2.Application.Tests.Usuarios;
public class UpdateUsuarioCommandHandlerTests
{
private readonly IUsuarioRepository _repo = Substitute.For<IUsuarioRepository>();
private readonly IRolRepository _rolRepo = Substitute.For<IRolRepository>();
private readonly IRefreshTokenRepository _refreshRepo = Substitute.For<IRefreshTokenRepository>();
feat(audit): enchufar audit en handlers de Usuario — Closes #6 7 command handlers del módulo Usuarios ahora auditan via IAuditLogger: | Handler | Action | |-----------------------------------------|-------------------------| | CreateUsuarioCommandHandler | usuario.create | | UpdateUsuarioCommandHandler | usuario.update | | DeactivateUsuarioCommandHandler | usuario.deactivate | | ReactivateUsuarioCommandHandler | usuario.reactivate | | ChangeMyPasswordCommandHandler | usuario.password_change | | ResetUsuarioPasswordCommandHandler | usuario.password_reset | | UpdateUsuarioPermisosOverridesHandler | usuario.permisos_update | Patrón por handler (per design #D-1): using (var tx = new TransactionScope(Required, ReadCommitted, AsyncFlowEnabled)) { await repo.UpdateAsync(...); await audit.LogAsync(...); tx.Complete(); } // post-commit reads OUTSIDE the using block var updated = await repo.GetDetailAsync(...); Metadata captured: - usuario.create: after={username, nombre, apellido, email, rol} — NO password. - usuario.update: {before, after} diff of editable fields. - usuario.password_reset: {targetId} only — tempPassword is NEVER persisted to audit (returned to caller once, never stored). - usuario.permisos_update: {before, after} of grant/deny override lists. Key fix during implementation: initially used 'using var tx = ...' (bare declaration). This kept the TransactionScope active for the rest of the method, causing 'The current TransactionScope is already complete' when post-commit reads (GetDetailAsync) tried to enlist. Solution: explicit 'using (var tx = ...) { ... }' block that disposes the scope before post-commit reads. AuditContextMissingException surfaces from AuditLogger when IAuditContext lacks ActorUserId — fail-closed per #REQ-AUD-4. In integration tests, the middleware populates ActorUserId from the JWT sub of the authenticated admin. Test updates: 6 existing unit test classes now inject IAuditLogger mock: - CreateUsuarioCommandHandlerTests - UpdateUsuarioCommandHandlerTests - DeactivateUsuarioCommandHandlerTests - ReactivateUsuarioCommandHandlerTests - ChangeMyPasswordCommandHandlerTests - ResetUsuarioPasswordCommandHandlerTests Follow-up #6 ([Auditoría] Registrar admin creador en alta de usuarios) is closed: CreateUsuarioCommandHandler now records ActorUserId = admin JWT sub on every user creation. TODO comment removed. Suite: 378/378 Application.Tests + 141/141 Api.Tests = 519/519 passing. Closes #6 Refs: sdd/udt-010-auditoria-trazabilidad/{spec#REQ-UM-AUD, design, tasks#B7}
2026-04-16 13:49:44 -03:00
private readonly IAuditLogger _audit = Substitute.For<IAuditLogger>();
private readonly UpdateUsuarioCommandHandler _handler;
public UpdateUsuarioCommandHandlerTests()
{
feat(audit): enchufar audit en handlers de Usuario — Closes #6 7 command handlers del módulo Usuarios ahora auditan via IAuditLogger: | Handler | Action | |-----------------------------------------|-------------------------| | CreateUsuarioCommandHandler | usuario.create | | UpdateUsuarioCommandHandler | usuario.update | | DeactivateUsuarioCommandHandler | usuario.deactivate | | ReactivateUsuarioCommandHandler | usuario.reactivate | | ChangeMyPasswordCommandHandler | usuario.password_change | | ResetUsuarioPasswordCommandHandler | usuario.password_reset | | UpdateUsuarioPermisosOverridesHandler | usuario.permisos_update | Patrón por handler (per design #D-1): using (var tx = new TransactionScope(Required, ReadCommitted, AsyncFlowEnabled)) { await repo.UpdateAsync(...); await audit.LogAsync(...); tx.Complete(); } // post-commit reads OUTSIDE the using block var updated = await repo.GetDetailAsync(...); Metadata captured: - usuario.create: after={username, nombre, apellido, email, rol} — NO password. - usuario.update: {before, after} diff of editable fields. - usuario.password_reset: {targetId} only — tempPassword is NEVER persisted to audit (returned to caller once, never stored). - usuario.permisos_update: {before, after} of grant/deny override lists. Key fix during implementation: initially used 'using var tx = ...' (bare declaration). This kept the TransactionScope active for the rest of the method, causing 'The current TransactionScope is already complete' when post-commit reads (GetDetailAsync) tried to enlist. Solution: explicit 'using (var tx = ...) { ... }' block that disposes the scope before post-commit reads. AuditContextMissingException surfaces from AuditLogger when IAuditContext lacks ActorUserId — fail-closed per #REQ-AUD-4. In integration tests, the middleware populates ActorUserId from the JWT sub of the authenticated admin. Test updates: 6 existing unit test classes now inject IAuditLogger mock: - CreateUsuarioCommandHandlerTests - UpdateUsuarioCommandHandlerTests - DeactivateUsuarioCommandHandlerTests - ReactivateUsuarioCommandHandlerTests - ChangeMyPasswordCommandHandlerTests - ResetUsuarioPasswordCommandHandlerTests Follow-up #6 ([Auditoría] Registrar admin creador en alta de usuarios) is closed: CreateUsuarioCommandHandler now records ActorUserId = admin JWT sub on every user creation. TODO comment removed. Suite: 378/378 Application.Tests + 141/141 Api.Tests = 519/519 passing. Closes #6 Refs: sdd/udt-010-auditoria-trazabilidad/{spec#REQ-UM-AUD, design, tasks#B7}
2026-04-16 13:49:44 -03:00
_handler = new UpdateUsuarioCommandHandler(_repo, _rolRepo, _refreshRepo, _audit);
// Default: rol exists and is active
_rolRepo.ExistsActiveByCodigoAsync(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(true);
// Default: 2 active admins (no lockout)
_repo.CountActiveAdminsAsync(Arg.Any<CancellationToken>()).Returns(2);
}
private static Usuario MakeUser(int id = 5, string rol = "cajero", bool activo = true)
=> new(id, "user" + id, "$2a$12$hash", "Test", "User", null, rol, "[]", activo);
[Fact]
public async Task Handle_Happy_Path_Updates_And_Returns_Detail()
{
var target = MakeUser(5);
var updated = new Usuario(5, "user5", "$2a$12$hash", "Pedro", "Gómez", "p@g.com", "cajero", "[]", true);
_repo.GetByIdAsync(5, Arg.Any<CancellationToken>()).Returns(target);
_repo.GetDetailAsync(5, Arg.Any<CancellationToken>()).Returns(updated);
var cmd = new UpdateUsuarioCommand(5, "Pedro", "Gómez", "p@g.com", "cajero", true);
var result = await _handler.Handle(cmd);
Assert.Equal("Pedro", result.Nombre);
await _repo.Received(1).UpdateAsync(5, Arg.Any<UpdateUsuarioFields>(), Arg.Any<DateTime>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task Handle_Throws_UsuarioNotFoundException_When_Target_Not_Found()
{
_repo.GetByIdAsync(9999, Arg.Any<CancellationToken>()).Returns((Usuario?)null);
var cmd = new UpdateUsuarioCommand(9999, "A", "B", null, "cajero", true);
await Assert.ThrowsAsync<UsuarioNotFoundException>(() => _handler.Handle(cmd));
}
[Fact]
public async Task Handle_Throws_LastAdminLockoutException_When_Changing_Role_Of_Last_Admin()
{
var lastAdmin = MakeUser(1, "admin", true);
_repo.GetByIdAsync(1, Arg.Any<CancellationToken>()).Returns(lastAdmin);
_repo.CountActiveAdminsAsync(Arg.Any<CancellationToken>()).Returns(1);
var cmd = new UpdateUsuarioCommand(1, "Admin", "Sys", null, "cajero", true); // changing rol
await Assert.ThrowsAsync<LastAdminLockoutException>(() => _handler.Handle(cmd));
}
[Fact]
public async Task Handle_Throws_LastAdminLockoutException_When_Deactivating_Last_Admin()
{
var lastAdmin = MakeUser(1, "admin", true);
_repo.GetByIdAsync(1, Arg.Any<CancellationToken>()).Returns(lastAdmin);
_repo.CountActiveAdminsAsync(Arg.Any<CancellationToken>()).Returns(1);
var cmd = new UpdateUsuarioCommand(1, "Admin", "Sys", null, "admin", false); // activo=false
await Assert.ThrowsAsync<LastAdminLockoutException>(() => _handler.Handle(cmd));
}
[Fact]
public async Task Handle_Allows_Same_Rol_On_Last_Admin()
{
var lastAdmin = MakeUser(1, "admin", true);
var updatedAdmin = new Usuario(1, "user1", "$2a$12$hash", "Admin", "Sys", null, "admin", "[]", true);
_repo.GetByIdAsync(1, Arg.Any<CancellationToken>()).Returns(lastAdmin);
_repo.GetDetailAsync(1, Arg.Any<CancellationToken>()).Returns(updatedAdmin);
_repo.CountActiveAdminsAsync(Arg.Any<CancellationToken>()).Returns(1);
var cmd = new UpdateUsuarioCommand(1, "Admin", "Sys", null, "admin", true); // same rol, same activo
var result = await _handler.Handle(cmd); // should NOT throw
Assert.NotNull(result);
}
[Fact]
public async Task Handle_Revokes_Refresh_Tokens_On_Role_Change()
{
var target = MakeUser(5, "cajero", true);
var updated = new Usuario(5, "user5", "$2a$12$hash", "Test", "User", null, "admin", "[]", true);
_repo.GetByIdAsync(5, Arg.Any<CancellationToken>()).Returns(target);
_repo.GetDetailAsync(5, Arg.Any<CancellationToken>()).Returns(updated);
var cmd = new UpdateUsuarioCommand(5, "Test", "User", null, "admin", true); // rol changed
await _handler.Handle(cmd);
await _refreshRepo.Received(1).RevokeAllActiveForUserAsync(5, Arg.Any<DateTime>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task Handle_Revokes_Refresh_Tokens_When_Deactivating()
{
var target = MakeUser(5, "cajero", true);
var updated = new Usuario(5, "user5", "$2a$12$hash", "Test", "User", null, "cajero", "[]", false);
_repo.GetByIdAsync(5, Arg.Any<CancellationToken>()).Returns(target);
_repo.GetDetailAsync(5, Arg.Any<CancellationToken>()).Returns(updated);
var cmd = new UpdateUsuarioCommand(5, "Test", "User", null, "cajero", false); // activo=false
await _handler.Handle(cmd);
await _refreshRepo.Received(1).RevokeAllActiveForUserAsync(5, Arg.Any<DateTime>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task Handle_Does_NOT_Revoke_Tokens_On_Name_Only_Change()
{
var target = MakeUser(5, "cajero", true);
var updated = new Usuario(5, "user5", "$2a$12$hash", "Nuevo", "User", null, "cajero", "[]", true);
_repo.GetByIdAsync(5, Arg.Any<CancellationToken>()).Returns(target);
_repo.GetDetailAsync(5, Arg.Any<CancellationToken>()).Returns(updated);
var cmd = new UpdateUsuarioCommand(5, "Nuevo", "User", null, "cajero", true); // only name changed
await _handler.Handle(cmd);
await _refreshRepo.DidNotReceive().RevokeAllActiveForUserAsync(Arg.Any<int>(), Arg.Any<DateTime>(), Arg.Any<CancellationToken>());
}
}