feat(application): Rubros commands/queries + RubroTreeBuilder + audit (CAT-001)
This commit is contained in:
@@ -0,0 +1,176 @@
|
||||
using FluentAssertions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.Extensions.Time.Testing;
|
||||
using NSubstitute;
|
||||
using NSubstitute.ExceptionExtensions;
|
||||
using SIGCM2.Application.Abstractions.Persistence;
|
||||
using SIGCM2.Application.Audit;
|
||||
using SIGCM2.Application.Rubros;
|
||||
using SIGCM2.Application.Rubros.Create;
|
||||
using SIGCM2.Domain.Entities;
|
||||
using SIGCM2.Domain.Exceptions;
|
||||
|
||||
namespace SIGCM2.Application.Tests.Rubros.Create;
|
||||
|
||||
public class CreateRubroCommandHandlerTests
|
||||
{
|
||||
private readonly IRubroRepository _repo = Substitute.For<IRubroRepository>();
|
||||
private readonly IAuditLogger _audit = Substitute.For<IAuditLogger>();
|
||||
private readonly FakeTimeProvider _timeProvider = new(new DateTimeOffset(2026, 4, 18, 12, 0, 0, TimeSpan.Zero));
|
||||
private readonly IOptions<RubrosOptions> _options = Options.Create(new RubrosOptions { MaxDepth = 10 });
|
||||
private readonly CreateRubroCommandHandler _handler;
|
||||
|
||||
public CreateRubroCommandHandlerTests()
|
||||
{
|
||||
_repo.ExistsByNombreUnderParentAsync(Arg.Any<int?>(), Arg.Any<string>(), Arg.Any<int?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(false);
|
||||
_repo.GetMaxOrdenAsync(Arg.Any<int?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(0);
|
||||
_repo.AddAsync(Arg.Any<Rubro>(), Arg.Any<CancellationToken>())
|
||||
.Returns(1);
|
||||
_repo.GetDepthAsync(Arg.Any<int?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(0);
|
||||
|
||||
_handler = new CreateRubroCommandHandler(_repo, _audit, _timeProvider, _options);
|
||||
}
|
||||
|
||||
private static CreateRubroCommand RootCommand() => new("Autos", ParentId: null, TarifarioBaseId: null);
|
||||
private static CreateRubroCommand ChildCommand(int parentId) => new("Sedanes", ParentId: parentId, TarifarioBaseId: null);
|
||||
|
||||
// ── Happy path: root ─────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_HappyPath_Root_ReturnsIdFromRepository()
|
||||
{
|
||||
_repo.AddAsync(Arg.Any<Rubro>(), Arg.Any<CancellationToken>()).Returns(42);
|
||||
|
||||
var result = await _handler.Handle(RootCommand());
|
||||
|
||||
result.Id.Should().Be(42);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_HappyPath_Root_CallsAddAsync()
|
||||
{
|
||||
await _handler.Handle(RootCommand());
|
||||
|
||||
await _repo.Received(1).AddAsync(
|
||||
Arg.Is<Rubro>(r => r.Nombre == "Autos" && r.ParentId == null),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_HappyPath_Root_CallsAuditLog()
|
||||
{
|
||||
_repo.AddAsync(Arg.Any<Rubro>(), Arg.Any<CancellationToken>()).Returns(7);
|
||||
|
||||
await _handler.Handle(RootCommand());
|
||||
|
||||
await _audit.Received(1).LogAsync(
|
||||
action: "rubro.created",
|
||||
targetType: "Rubro",
|
||||
targetId: "7",
|
||||
metadata: Arg.Any<object?>(),
|
||||
ct: Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
// ── Happy path: child — uses GetMaxOrdenAsync ────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_HappyPath_Child_UsesMaxOrdenForOrden()
|
||||
{
|
||||
// GetMaxOrdenAsync returns the next available slot (MAX+1 semantics in the repo)
|
||||
_repo.GetMaxOrdenAsync((int?)5, Arg.Any<CancellationToken>()).Returns(3);
|
||||
var parent = new Rubro(5, null, "ParentRubro", 0, activo: true, tarifarioBaseId: null,
|
||||
fechaCreacion: DateTime.UtcNow, fechaModificacion: null);
|
||||
_repo.GetByIdAsync(5, Arg.Any<CancellationToken>()).Returns(parent);
|
||||
|
||||
await _handler.Handle(ChildCommand(parentId: 5));
|
||||
|
||||
await _repo.Received(1).AddAsync(
|
||||
Arg.Is<Rubro>(r => r.Orden == 3),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
// ── Parent not found → RubroNotFoundException ────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_ParentNotFound_ThrowsRubroNotFoundException()
|
||||
{
|
||||
_repo.GetByIdAsync(999, Arg.Any<CancellationToken>()).Returns((Rubro?)null);
|
||||
|
||||
var act = () => _handler.Handle(ChildCommand(parentId: 999));
|
||||
|
||||
await act.Should().ThrowAsync<RubroNotFoundException>()
|
||||
.Where(ex => ex.Id == 999);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_ParentNotFound_DoesNotCallAddAsync()
|
||||
{
|
||||
_repo.GetByIdAsync(999, Arg.Any<CancellationToken>()).Returns((Rubro?)null);
|
||||
|
||||
try { await _handler.Handle(ChildCommand(parentId: 999)); } catch { }
|
||||
|
||||
await _repo.DidNotReceive().AddAsync(Arg.Any<Rubro>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
// ── Parent inactive → RubroPadreInactivoException ───────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_ParentInactive_ThrowsRubroPadreInactivoException()
|
||||
{
|
||||
var inactiveParent = new Rubro(7, null, "InactivoParent", 0, activo: false, tarifarioBaseId: null,
|
||||
fechaCreacion: DateTime.UtcNow, fechaModificacion: null);
|
||||
_repo.GetByIdAsync(7, Arg.Any<CancellationToken>()).Returns(inactiveParent);
|
||||
|
||||
var act = () => _handler.Handle(ChildCommand(parentId: 7));
|
||||
|
||||
await act.Should().ThrowAsync<RubroPadreInactivoException>()
|
||||
.Where(ex => ex.ParentId == 7);
|
||||
}
|
||||
|
||||
// ── Duplicate name (CI) → RubroNombreDuplicadoEnPadreException ──────────
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_DuplicateName_ThrowsRubroNombreDuplicadoEnPadreException()
|
||||
{
|
||||
_repo.ExistsByNombreUnderParentAsync(null, "Autos", null, Arg.Any<CancellationToken>())
|
||||
.Returns(true);
|
||||
|
||||
var act = () => _handler.Handle(RootCommand());
|
||||
|
||||
await act.Should().ThrowAsync<RubroNombreDuplicadoEnPadreException>();
|
||||
}
|
||||
|
||||
// ── Depth exceeded → RubroMaxDepthExceededException ─────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_DepthExceeded_ThrowsRubroMaxDepthExceededException()
|
||||
{
|
||||
// MaxDepth=10, parent is at depth 10 → creating child would be depth 11
|
||||
_repo.GetDepthAsync(5, Arg.Any<CancellationToken>()).Returns(10);
|
||||
var parent = new Rubro(5, null, "DeepParent", 0, activo: true, tarifarioBaseId: null,
|
||||
fechaCreacion: DateTime.UtcNow, fechaModificacion: null);
|
||||
_repo.GetByIdAsync(5, Arg.Any<CancellationToken>()).Returns(parent);
|
||||
|
||||
var act = () => _handler.Handle(ChildCommand(parentId: 5));
|
||||
|
||||
await act.Should().ThrowAsync<RubroMaxDepthExceededException>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_DepthAtMaxAllowed_Succeeds()
|
||||
{
|
||||
// MaxDepth=10, parent at depth 9 → child at depth 10 is allowed
|
||||
_repo.GetDepthAsync(5, Arg.Any<CancellationToken>()).Returns(9);
|
||||
var parent = new Rubro(5, null, "DeepParent", 0, activo: true, tarifarioBaseId: null,
|
||||
fechaCreacion: DateTime.UtcNow, fechaModificacion: null);
|
||||
_repo.GetByIdAsync(5, Arg.Any<CancellationToken>()).Returns(parent);
|
||||
_repo.AddAsync(Arg.Any<Rubro>(), Arg.Any<CancellationToken>()).Returns(99);
|
||||
|
||||
var result = await _handler.Handle(ChildCommand(parentId: 5));
|
||||
|
||||
result.Id.Should().Be(99);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
using FluentAssertions;
|
||||
using Microsoft.Extensions.Time.Testing;
|
||||
using NSubstitute;
|
||||
using SIGCM2.Application.Abstractions.Persistence;
|
||||
using SIGCM2.Application.Audit;
|
||||
using SIGCM2.Application.Rubros.Deactivate;
|
||||
using SIGCM2.Domain.Entities;
|
||||
using SIGCM2.Domain.Exceptions;
|
||||
|
||||
namespace SIGCM2.Application.Tests.Rubros.Deactivate;
|
||||
|
||||
public class DeactivateRubroCommandHandlerTests
|
||||
{
|
||||
private readonly IRubroRepository _repo = Substitute.For<IRubroRepository>();
|
||||
private readonly IAuditLogger _audit = Substitute.For<IAuditLogger>();
|
||||
private readonly FakeTimeProvider _timeProvider = new(new DateTimeOffset(2026, 4, 18, 12, 0, 0, TimeSpan.Zero));
|
||||
private readonly DeactivateRubroCommandHandler _handler;
|
||||
|
||||
private static Rubro LeafRubro(int id = 10) => new(id, null, "Autos", 0, activo: true,
|
||||
tarifarioBaseId: null, fechaCreacion: DateTime.UtcNow, fechaModificacion: null);
|
||||
|
||||
public DeactivateRubroCommandHandlerTests()
|
||||
{
|
||||
_repo.CountActiveChildrenAsync(Arg.Any<int>(), Arg.Any<CancellationToken>()).Returns(0);
|
||||
_handler = new DeactivateRubroCommandHandler(_repo, _audit, _timeProvider);
|
||||
}
|
||||
|
||||
// ── Happy path: leaf soft-delete ─────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_LeafRubro_SoftDeletes()
|
||||
{
|
||||
_repo.GetByIdAsync(10, Arg.Any<CancellationToken>()).Returns(LeafRubro());
|
||||
|
||||
var result = await _handler.Handle(new DeactivateRubroCommand(Id: 10));
|
||||
|
||||
result.Id.Should().Be(10);
|
||||
result.Activo.Should().BeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_LeafRubro_CallsUpdateAsync()
|
||||
{
|
||||
_repo.GetByIdAsync(10, Arg.Any<CancellationToken>()).Returns(LeafRubro());
|
||||
|
||||
await _handler.Handle(new DeactivateRubroCommand(Id: 10));
|
||||
|
||||
await _repo.Received(1).UpdateAsync(
|
||||
Arg.Is<Rubro>(r => r.Id == 10 && !r.Activo),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_LeafRubro_CallsAuditLog()
|
||||
{
|
||||
_repo.GetByIdAsync(10, Arg.Any<CancellationToken>()).Returns(LeafRubro());
|
||||
|
||||
await _handler.Handle(new DeactivateRubroCommand(Id: 10));
|
||||
|
||||
await _audit.Received(1).LogAsync(
|
||||
action: "rubro.deleted",
|
||||
targetType: "Rubro",
|
||||
targetId: "10",
|
||||
metadata: Arg.Any<object?>(),
|
||||
ct: Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
// ── Has active children → RubroTieneHijosActivosException ───────────────
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_HasActiveChildren_ThrowsRubroTieneHijosActivosException()
|
||||
{
|
||||
_repo.GetByIdAsync(5, Arg.Any<CancellationToken>()).Returns(LeafRubro(5));
|
||||
_repo.CountActiveChildrenAsync(5, Arg.Any<CancellationToken>()).Returns(3);
|
||||
|
||||
var act = () => _handler.Handle(new DeactivateRubroCommand(Id: 5));
|
||||
|
||||
await act.Should().ThrowAsync<RubroTieneHijosActivosException>()
|
||||
.Where(ex => ex.Id == 5 && ex.Count == 3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_HasActiveChildren_DoesNotCallAuditLog()
|
||||
{
|
||||
_repo.GetByIdAsync(5, Arg.Any<CancellationToken>()).Returns(LeafRubro(5));
|
||||
_repo.CountActiveChildrenAsync(5, Arg.Any<CancellationToken>()).Returns(1);
|
||||
|
||||
try { await _handler.Handle(new DeactivateRubroCommand(Id: 5)); } catch { }
|
||||
|
||||
await _audit.DidNotReceive().LogAsync(
|
||||
Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(),
|
||||
Arg.Any<object?>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
// ── Not found → RubroNotFoundException ──────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_NotFound_ThrowsRubroNotFoundException()
|
||||
{
|
||||
_repo.GetByIdAsync(99, Arg.Any<CancellationToken>()).Returns((Rubro?)null);
|
||||
|
||||
var act = () => _handler.Handle(new DeactivateRubroCommand(Id: 99));
|
||||
|
||||
await act.Should().ThrowAsync<RubroNotFoundException>();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
using FluentAssertions;
|
||||
using Microsoft.Extensions.Time.Testing;
|
||||
using NSubstitute;
|
||||
using SIGCM2.Application.Abstractions.Persistence;
|
||||
using SIGCM2.Application.Rubros.GetById;
|
||||
using SIGCM2.Application.Rubros.GetTree;
|
||||
using SIGCM2.Domain.Entities;
|
||||
using SIGCM2.Domain.Exceptions;
|
||||
|
||||
namespace SIGCM2.Application.Tests.Rubros.GetTree;
|
||||
|
||||
public class GetRubroTreeQueryHandlerTests
|
||||
{
|
||||
private static readonly FakeTimeProvider FakeTime = new(new DateTimeOffset(2026, 4, 18, 12, 0, 0, TimeSpan.Zero));
|
||||
private readonly IRubroRepository _repo = Substitute.For<IRubroRepository>();
|
||||
|
||||
private static Rubro MakeRubro(int id, int? parentId = null, bool activo = true)
|
||||
=> new(id, parentId, $"Rubro{id}", 0, activo, null, FakeTime.GetUtcNow().UtcDateTime, null);
|
||||
|
||||
// ── GetRubroTreeQueryHandler ─────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task GetTree_OnlyActivos_ByDefault_ReturnsActiveTree()
|
||||
{
|
||||
_repo.GetAllAsync(false, Arg.Any<CancellationToken>())
|
||||
.Returns(new[] { MakeRubro(1), MakeRubro(2) });
|
||||
|
||||
var handler = new GetRubroTreeQueryHandler(_repo);
|
||||
var result = await handler.Handle(new GetRubroTreeQuery(IncluirInactivos: false));
|
||||
|
||||
result.Should().HaveCount(2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTree_IncluirInactivos_CallsRepoWithTrue()
|
||||
{
|
||||
_repo.GetAllAsync(true, Arg.Any<CancellationToken>())
|
||||
.Returns(new[] { MakeRubro(1), MakeRubro(2, activo: false) });
|
||||
|
||||
var handler = new GetRubroTreeQueryHandler(_repo);
|
||||
var result = await handler.Handle(new GetRubroTreeQuery(IncluirInactivos: true));
|
||||
|
||||
await _repo.Received(1).GetAllAsync(true, Arg.Any<CancellationToken>());
|
||||
result.Should().HaveCount(2); // both roots
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTree_Empty_ReturnsEmptyList()
|
||||
{
|
||||
_repo.GetAllAsync(Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Array.Empty<Rubro>());
|
||||
|
||||
var handler = new GetRubroTreeQueryHandler(_repo);
|
||||
var result = await handler.Handle(new GetRubroTreeQuery(IncluirInactivos: false));
|
||||
|
||||
result.Should().BeEmpty();
|
||||
}
|
||||
|
||||
// ── GetRubroByIdQueryHandler ─────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task GetById_Found_Active_ReturnsDto()
|
||||
{
|
||||
_repo.GetByIdAsync(5, Arg.Any<CancellationToken>()).Returns(MakeRubro(5));
|
||||
|
||||
var handler = new GetRubroByIdQueryHandler(_repo);
|
||||
var result = await handler.Handle(new GetRubroByIdQuery(Id: 5));
|
||||
|
||||
result.Should().NotBeNull();
|
||||
result!.Id.Should().Be(5);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetById_NotFound_ThrowsRubroNotFoundException()
|
||||
{
|
||||
_repo.GetByIdAsync(99, Arg.Any<CancellationToken>()).Returns((Rubro?)null);
|
||||
|
||||
var handler = new GetRubroByIdQueryHandler(_repo);
|
||||
var act = () => handler.Handle(new GetRubroByIdQuery(Id: 99));
|
||||
|
||||
await act.Should().ThrowAsync<RubroNotFoundException>();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
using FluentAssertions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.Extensions.Time.Testing;
|
||||
using NSubstitute;
|
||||
using SIGCM2.Application.Abstractions.Persistence;
|
||||
using SIGCM2.Application.Audit;
|
||||
using SIGCM2.Application.Rubros;
|
||||
using SIGCM2.Application.Rubros.Move;
|
||||
using SIGCM2.Domain.Entities;
|
||||
using SIGCM2.Domain.Exceptions;
|
||||
|
||||
namespace SIGCM2.Application.Tests.Rubros.Move;
|
||||
|
||||
public class MoveRubroCommandHandlerTests
|
||||
{
|
||||
private readonly IRubroRepository _repo = Substitute.For<IRubroRepository>();
|
||||
private readonly IAuditLogger _audit = Substitute.For<IAuditLogger>();
|
||||
private readonly FakeTimeProvider _timeProvider = new(new DateTimeOffset(2026, 4, 18, 12, 0, 0, TimeSpan.Zero));
|
||||
private readonly IOptions<RubrosOptions> _options = Options.Create(new RubrosOptions { MaxDepth = 10 });
|
||||
private readonly MoveRubroCommandHandler _handler;
|
||||
|
||||
private static Rubro MakeRubro(int id, int? parentId = null, bool activo = true)
|
||||
=> new(id, parentId, $"Rubro{id}", 0, activo, null, DateTime.UtcNow, null);
|
||||
|
||||
public MoveRubroCommandHandlerTests()
|
||||
{
|
||||
_repo.GetDescendantsAsync(Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Array.Empty<Rubro>());
|
||||
_repo.ExistsByNombreUnderParentAsync(Arg.Any<int?>(), Arg.Any<string>(), Arg.Any<int?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(false);
|
||||
_repo.GetDepthAsync(Arg.Any<int?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(0);
|
||||
_repo.GetMaxOrdenAsync(Arg.Any<int?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(0);
|
||||
|
||||
_handler = new MoveRubroCommandHandler(_repo, _audit, _timeProvider, _options);
|
||||
}
|
||||
|
||||
// ── Happy path: move to other parent ────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_HappyPath_Move_ReturnsMovedDto()
|
||||
{
|
||||
var rubro = MakeRubro(8, parentId: 2);
|
||||
var newParent = MakeRubro(20, parentId: 1);
|
||||
_repo.GetByIdAsync(8, Arg.Any<CancellationToken>()).Returns(rubro);
|
||||
_repo.GetByIdAsync(20, Arg.Any<CancellationToken>()).Returns(newParent);
|
||||
|
||||
var result = await _handler.Handle(new MoveRubroCommand(Id: 8, NuevoParentId: 20, NuevoOrden: 0));
|
||||
|
||||
result.Id.Should().Be(8);
|
||||
result.ParentId.Should().Be(20);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_HappyPath_Move_CallsAuditLogWithParentTransition()
|
||||
{
|
||||
var rubro = MakeRubro(8, parentId: 2);
|
||||
var newParent = MakeRubro(20, parentId: 1);
|
||||
_repo.GetByIdAsync(8, Arg.Any<CancellationToken>()).Returns(rubro);
|
||||
_repo.GetByIdAsync(20, Arg.Any<CancellationToken>()).Returns(newParent);
|
||||
|
||||
await _handler.Handle(new MoveRubroCommand(Id: 8, NuevoParentId: 20, NuevoOrden: 0));
|
||||
|
||||
await _audit.Received(1).LogAsync(
|
||||
action: "rubro.moved",
|
||||
targetType: "Rubro",
|
||||
targetId: "8",
|
||||
metadata: Arg.Any<object?>(),
|
||||
ct: Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
// ── Move to root (nuevoParentId null) ─────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_MoveToRoot_SetsParentIdNull()
|
||||
{
|
||||
var rubro = MakeRubro(8, parentId: 3);
|
||||
_repo.GetByIdAsync(8, Arg.Any<CancellationToken>()).Returns(rubro);
|
||||
|
||||
var result = await _handler.Handle(new MoveRubroCommand(Id: 8, NuevoParentId: null, NuevoOrden: 5));
|
||||
|
||||
result.ParentId.Should().BeNull();
|
||||
result.Orden.Should().Be(5);
|
||||
}
|
||||
|
||||
// ── Rubro not found → RubroNotFoundException ─────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_RubroNotFound_ThrowsRubroNotFoundException()
|
||||
{
|
||||
_repo.GetByIdAsync(99, Arg.Any<CancellationToken>()).Returns((Rubro?)null);
|
||||
|
||||
var act = () => _handler.Handle(new MoveRubroCommand(Id: 99, NuevoParentId: 1, NuevoOrden: 0));
|
||||
|
||||
await act.Should().ThrowAsync<RubroNotFoundException>();
|
||||
}
|
||||
|
||||
// ── Cycle detection ───────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_DirectChildAsNewParent_ThrowsRubroCycleDetectedException()
|
||||
{
|
||||
var rubro = MakeRubro(5, parentId: null);
|
||||
_repo.GetByIdAsync(5, Arg.Any<CancellationToken>()).Returns(rubro);
|
||||
// Descendant id=10 would be the new parent
|
||||
_repo.GetDescendantsAsync(5, Arg.Any<CancellationToken>())
|
||||
.Returns(new[] { MakeRubro(10, parentId: 5) });
|
||||
|
||||
var act = () => _handler.Handle(new MoveRubroCommand(Id: 5, NuevoParentId: 10, NuevoOrden: 0));
|
||||
|
||||
await act.Should().ThrowAsync<RubroCycleDetectedException>()
|
||||
.Where(ex => ex.RubroId == 5 && ex.NuevoParentId == 10);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_DeepDescendantAsNewParent_ThrowsRubroCycleDetectedException()
|
||||
{
|
||||
var rubro = MakeRubro(5, parentId: null);
|
||||
_repo.GetByIdAsync(5, Arg.Any<CancellationToken>()).Returns(rubro);
|
||||
_repo.GetDescendantsAsync(5, Arg.Any<CancellationToken>())
|
||||
.Returns(new[] { MakeRubro(10, 5), MakeRubro(15, 10) });
|
||||
|
||||
var act = () => _handler.Handle(new MoveRubroCommand(Id: 5, NuevoParentId: 15, NuevoOrden: 0));
|
||||
|
||||
await act.Should().ThrowAsync<RubroCycleDetectedException>();
|
||||
}
|
||||
|
||||
// ── New parent inactive → RubroPadreInactivoException ─────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_NewParentInactive_ThrowsRubroPadreInactivoException()
|
||||
{
|
||||
var rubro = MakeRubro(8, parentId: 2);
|
||||
var inactiveParent = MakeRubro(20, activo: false);
|
||||
_repo.GetByIdAsync(8, Arg.Any<CancellationToken>()).Returns(rubro);
|
||||
_repo.GetByIdAsync(20, Arg.Any<CancellationToken>()).Returns(inactiveParent);
|
||||
|
||||
var act = () => _handler.Handle(new MoveRubroCommand(Id: 8, NuevoParentId: 20, NuevoOrden: 0));
|
||||
|
||||
await act.Should().ThrowAsync<RubroPadreInactivoException>();
|
||||
}
|
||||
|
||||
// ── Duplicate name under new parent ────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_DuplicateNameUnderNewParent_ThrowsRubroNombreDuplicadoEnPadreException()
|
||||
{
|
||||
var rubro = MakeRubro(8, parentId: 2);
|
||||
var newParent = MakeRubro(20);
|
||||
_repo.GetByIdAsync(8, Arg.Any<CancellationToken>()).Returns(rubro);
|
||||
_repo.GetByIdAsync(20, Arg.Any<CancellationToken>()).Returns(newParent);
|
||||
_repo.ExistsByNombreUnderParentAsync((int?)20, rubro.Nombre, 8, Arg.Any<CancellationToken>())
|
||||
.Returns(true);
|
||||
|
||||
var act = () => _handler.Handle(new MoveRubroCommand(Id: 8, NuevoParentId: 20, NuevoOrden: 0));
|
||||
|
||||
await act.Should().ThrowAsync<RubroNombreDuplicadoEnPadreException>();
|
||||
}
|
||||
|
||||
// ── Depth exceeded ─────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_DepthExceeded_ThrowsRubroMaxDepthExceededException()
|
||||
{
|
||||
var rubro = MakeRubro(8, parentId: 2);
|
||||
var newParent = MakeRubro(20);
|
||||
_repo.GetByIdAsync(8, Arg.Any<CancellationToken>()).Returns(rubro);
|
||||
_repo.GetByIdAsync(20, Arg.Any<CancellationToken>()).Returns(newParent);
|
||||
_repo.GetDepthAsync((int?)20, Arg.Any<CancellationToken>()).Returns(10); // at MaxDepth
|
||||
|
||||
var act = () => _handler.Handle(new MoveRubroCommand(Id: 8, NuevoParentId: 20, NuevoOrden: 0));
|
||||
|
||||
await act.Should().ThrowAsync<RubroMaxDepthExceededException>();
|
||||
}
|
||||
}
|
||||
158
tests/SIGCM2.Application.Tests/Rubros/RubroTreeBuilderTests.cs
Normal file
158
tests/SIGCM2.Application.Tests/Rubros/RubroTreeBuilderTests.cs
Normal file
@@ -0,0 +1,158 @@
|
||||
using FluentAssertions;
|
||||
using Microsoft.Extensions.Time.Testing;
|
||||
using SIGCM2.Application.Rubros.Common;
|
||||
using SIGCM2.Domain.Entities;
|
||||
|
||||
namespace SIGCM2.Application.Tests.Rubros;
|
||||
|
||||
public class RubroTreeBuilderTests
|
||||
{
|
||||
private static readonly FakeTimeProvider FakeTime = new(new DateTimeOffset(2026, 4, 18, 12, 0, 0, TimeSpan.Zero));
|
||||
|
||||
private static Rubro MakeRubro(int id, int? parentId, string nombre, int orden, bool activo = true)
|
||||
=> new(id, parentId, nombre, orden, activo, tarifarioBaseId: null,
|
||||
fechaCreacion: FakeTime.GetUtcNow().UtcDateTime, fechaModificacion: null);
|
||||
|
||||
// ── empty ─────────────────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Build_empty_returns_empty_list()
|
||||
{
|
||||
var result = RubroTreeBuilder.Build([], incluirInactivos: false);
|
||||
|
||||
result.Should().BeEmpty();
|
||||
}
|
||||
|
||||
// ── single root ───────────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Build_single_root_returns_one_node_no_children()
|
||||
{
|
||||
var rubros = new[] { MakeRubro(1, null, "Autos", 0) };
|
||||
|
||||
var result = RubroTreeBuilder.Build(rubros, incluirInactivos: false);
|
||||
|
||||
result.Should().HaveCount(1);
|
||||
result[0].Id.Should().Be(1);
|
||||
result[0].Nombre.Should().Be("Autos");
|
||||
result[0].Hijos.Should().BeEmpty();
|
||||
}
|
||||
|
||||
// ── multiple roots sorted by Orden ───────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Build_flat_list_with_multiple_roots_sorted_by_orden()
|
||||
{
|
||||
var rubros = new[]
|
||||
{
|
||||
MakeRubro(3, null, "Motos", 2),
|
||||
MakeRubro(1, null, "Autos", 0),
|
||||
MakeRubro(2, null, "Camiones", 1)
|
||||
};
|
||||
|
||||
var result = RubroTreeBuilder.Build(rubros, incluirInactivos: false);
|
||||
|
||||
result.Should().HaveCount(3);
|
||||
result[0].Id.Should().Be(1); // Orden=0
|
||||
result[1].Id.Should().Be(2); // Orden=1
|
||||
result[2].Id.Should().Be(3); // Orden=2
|
||||
}
|
||||
|
||||
// ── tree 3 levels deep ────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Build_tree_3_levels_deep_correctly_nests()
|
||||
{
|
||||
var rubros = new[]
|
||||
{
|
||||
MakeRubro(1, null, "Autos", 0),
|
||||
MakeRubro(2, 1, "Sedanes", 0),
|
||||
MakeRubro(3, 2, "Compactos", 0),
|
||||
};
|
||||
|
||||
var result = RubroTreeBuilder.Build(rubros, incluirInactivos: false);
|
||||
|
||||
result.Should().HaveCount(1);
|
||||
result[0].Id.Should().Be(1);
|
||||
result[0].Hijos.Should().HaveCount(1);
|
||||
result[0].Hijos[0].Id.Should().Be(2);
|
||||
result[0].Hijos[0].Hijos.Should().HaveCount(1);
|
||||
result[0].Hijos[0].Hijos[0].Id.Should().Be(3);
|
||||
}
|
||||
|
||||
// ── filter inactivos ──────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Build_filters_inactivos_by_default()
|
||||
{
|
||||
var rubros = new[]
|
||||
{
|
||||
MakeRubro(1, null, "Autos", 0, activo: true),
|
||||
MakeRubro(2, null, "Motos", 1, activo: false),
|
||||
};
|
||||
|
||||
var result = RubroTreeBuilder.Build(rubros, incluirInactivos: false);
|
||||
|
||||
result.Should().HaveCount(1);
|
||||
result[0].Id.Should().Be(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Build_includes_inactivos_when_incluirInactivos_true()
|
||||
{
|
||||
var rubros = new[]
|
||||
{
|
||||
MakeRubro(1, null, "Autos", 0, activo: true),
|
||||
MakeRubro(2, null, "Motos", 1, activo: false),
|
||||
};
|
||||
|
||||
var result = RubroTreeBuilder.Build(rubros, incluirInactivos: true);
|
||||
|
||||
result.Should().HaveCount(2);
|
||||
}
|
||||
|
||||
// ── siblings sorted by Orden ──────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Build_orders_siblings_by_orden()
|
||||
{
|
||||
var rubros = new[]
|
||||
{
|
||||
MakeRubro(1, null, "Root", 0),
|
||||
MakeRubro(4, 1, "D", 3),
|
||||
MakeRubro(2, 1, "B", 1),
|
||||
MakeRubro(3, 1, "C", 2),
|
||||
MakeRubro(5, 1, "A", 0),
|
||||
};
|
||||
|
||||
var result = RubroTreeBuilder.Build(rubros, incluirInactivos: false);
|
||||
|
||||
var hijos = result[0].Hijos;
|
||||
hijos.Should().HaveCount(4);
|
||||
hijos[0].Nombre.Should().Be("A"); // Orden=0
|
||||
hijos[1].Nombre.Should().Be("B"); // Orden=1
|
||||
hijos[2].Nombre.Should().Be("C"); // Orden=2
|
||||
hijos[3].Nombre.Should().Be("D"); // Orden=3
|
||||
}
|
||||
|
||||
// ── O(n) perf smoke test ──────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Build_is_Olinear_perf_smoke_test_1000_nodes_under_100ms()
|
||||
{
|
||||
var rubros = new List<Rubro>();
|
||||
// root
|
||||
rubros.Add(MakeRubro(1, null, "Root", 0));
|
||||
// 999 children of root
|
||||
for (int i = 2; i <= 1000; i++)
|
||||
rubros.Add(MakeRubro(i, 1, $"Child{i}", i - 2));
|
||||
|
||||
var sw = System.Diagnostics.Stopwatch.StartNew();
|
||||
var result = RubroTreeBuilder.Build(rubros, incluirInactivos: false);
|
||||
sw.Stop();
|
||||
|
||||
result.Should().HaveCount(1);
|
||||
result[0].Hijos.Should().HaveCount(999);
|
||||
sw.ElapsedMilliseconds.Should().BeLessThan(100);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
using FluentAssertions;
|
||||
using Microsoft.Extensions.Time.Testing;
|
||||
using NSubstitute;
|
||||
using SIGCM2.Application.Abstractions.Persistence;
|
||||
using SIGCM2.Application.Audit;
|
||||
using SIGCM2.Application.Rubros.Update;
|
||||
using SIGCM2.Domain.Entities;
|
||||
using SIGCM2.Domain.Exceptions;
|
||||
|
||||
namespace SIGCM2.Application.Tests.Rubros.Update;
|
||||
|
||||
public class UpdateRubroCommandHandlerTests
|
||||
{
|
||||
private readonly IRubroRepository _repo = Substitute.For<IRubroRepository>();
|
||||
private readonly IAuditLogger _audit = Substitute.For<IAuditLogger>();
|
||||
private readonly FakeTimeProvider _timeProvider = new(new DateTimeOffset(2026, 4, 18, 12, 0, 0, TimeSpan.Zero));
|
||||
private readonly UpdateRubroCommandHandler _handler;
|
||||
|
||||
private static Rubro ExistingRubro(int id = 3) => new(id, null, "Autos", 0, activo: true,
|
||||
tarifarioBaseId: null, fechaCreacion: DateTime.UtcNow, fechaModificacion: null);
|
||||
|
||||
public UpdateRubroCommandHandlerTests()
|
||||
{
|
||||
_repo.ExistsByNombreUnderParentAsync(Arg.Any<int?>(), Arg.Any<string>(), Arg.Any<int?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(false);
|
||||
|
||||
_handler = new UpdateRubroCommandHandler(_repo, _audit, _timeProvider);
|
||||
}
|
||||
|
||||
// ── Happy path: rename ───────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_HappyPath_Rename_ReturnsUpdatedDto()
|
||||
{
|
||||
_repo.GetByIdAsync(3, Arg.Any<CancellationToken>()).Returns(ExistingRubro());
|
||||
|
||||
var result = await _handler.Handle(new UpdateRubroCommand(Id: 3, Nombre: "Vehiculos"));
|
||||
|
||||
result.Nombre.Should().Be("Vehiculos");
|
||||
result.Id.Should().Be(3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_HappyPath_Rename_CallsUpdateAsync()
|
||||
{
|
||||
_repo.GetByIdAsync(3, Arg.Any<CancellationToken>()).Returns(ExistingRubro());
|
||||
|
||||
await _handler.Handle(new UpdateRubroCommand(Id: 3, Nombre: "Vehiculos"));
|
||||
|
||||
await _repo.Received(1).UpdateAsync(
|
||||
Arg.Is<Rubro>(r => r.Nombre == "Vehiculos"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_HappyPath_Rename_CallsAuditLog()
|
||||
{
|
||||
_repo.GetByIdAsync(3, Arg.Any<CancellationToken>()).Returns(ExistingRubro());
|
||||
|
||||
await _handler.Handle(new UpdateRubroCommand(Id: 3, Nombre: "Vehiculos"));
|
||||
|
||||
await _audit.Received(1).LogAsync(
|
||||
action: "rubro.updated",
|
||||
targetType: "Rubro",
|
||||
targetId: "3",
|
||||
metadata: Arg.Any<object?>(),
|
||||
ct: Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
// ── Not found → RubroNotFoundException ──────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_NotFound_ThrowsRubroNotFoundException()
|
||||
{
|
||||
_repo.GetByIdAsync(99, Arg.Any<CancellationToken>()).Returns((Rubro?)null);
|
||||
|
||||
var act = () => _handler.Handle(new UpdateRubroCommand(Id: 99, Nombre: "Cualquiera"));
|
||||
|
||||
await act.Should().ThrowAsync<RubroNotFoundException>()
|
||||
.Where(ex => ex.Id == 99);
|
||||
}
|
||||
|
||||
// ── Duplicate name CI under same parent → RubroNombreDuplicadoEnPadreException
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_DuplicateNameUnderParent_ThrowsRubroNombreDuplicadoEnPadreException()
|
||||
{
|
||||
_repo.GetByIdAsync(3, Arg.Any<CancellationToken>()).Returns(ExistingRubro());
|
||||
_repo.ExistsByNombreUnderParentAsync(null, "Motos", 3, Arg.Any<CancellationToken>())
|
||||
.Returns(true);
|
||||
|
||||
var act = () => _handler.Handle(new UpdateRubroCommand(Id: 3, Nombre: "Motos"));
|
||||
|
||||
await act.Should().ThrowAsync<RubroNombreDuplicadoEnPadreException>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_DuplicateName_DoesNotCallAuditLog()
|
||||
{
|
||||
_repo.GetByIdAsync(3, Arg.Any<CancellationToken>()).Returns(ExistingRubro());
|
||||
_repo.ExistsByNombreUnderParentAsync(Arg.Any<int?>(), Arg.Any<string>(), Arg.Any<int?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(true);
|
||||
|
||||
try { await _handler.Handle(new UpdateRubroCommand(Id: 3, Nombre: "Motos")); } catch { }
|
||||
|
||||
await _audit.DidNotReceive().LogAsync(
|
||||
Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(),
|
||||
Arg.Any<object?>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user