2026-04-13 21:36:09 -03:00
|
|
|
using Microsoft.Data.SqlClient;
|
|
|
|
|
using Respawn;
|
|
|
|
|
using SIGCM2.Infrastructure.Persistence;
|
|
|
|
|
|
|
|
|
|
namespace SIGCM2.Application.Tests.Integration;
|
|
|
|
|
|
|
|
|
|
[Collection("Database")]
|
|
|
|
|
public class UsuarioRepositoryTests : IAsyncLifetime
|
|
|
|
|
{
|
|
|
|
|
private const string ConnectionString =
|
|
|
|
|
"Server=TECNICA3;Database=SIGCM2_Test;User Id=desarrollo;Password=desarrollo2026;TrustServerCertificate=True;";
|
|
|
|
|
|
|
|
|
|
private SqlConnection _connection = null!;
|
|
|
|
|
private Respawner _respawner = null!;
|
|
|
|
|
private UsuarioRepository _repository = null!;
|
|
|
|
|
|
|
|
|
|
public async Task InitializeAsync()
|
|
|
|
|
{
|
|
|
|
|
_connection = new SqlConnection(ConnectionString);
|
|
|
|
|
await _connection.OpenAsync();
|
|
|
|
|
|
|
|
|
|
_respawner = await Respawner.CreateAsync(_connection, new RespawnerOptions
|
|
|
|
|
{
|
2026-04-15 12:31:29 -03:00
|
|
|
DbAdapter = DbAdapter.SqlServer,
|
|
|
|
|
// Rol is a lookup table seeded by migration V003 — never wipe or Usuario FK breaks.
|
2026-04-15 15:39:25 -03:00
|
|
|
TablesToIgnore =
|
|
|
|
|
[
|
|
|
|
|
new Respawn.Graph.Table("dbo", "Rol"),
|
|
|
|
|
new Respawn.Graph.Table("dbo", "Permiso"),
|
|
|
|
|
new Respawn.Graph.Table("dbo", "RolPermiso"),
|
2026-04-16 13:22:56 -03:00
|
|
|
// UDT-010: *_History tables are system-versioned — engine rejects direct DELETE.
|
|
|
|
|
new Respawn.Graph.Table("dbo", "Usuario_History"),
|
|
|
|
|
new Respawn.Graph.Table("dbo", "Rol_History"),
|
|
|
|
|
new Respawn.Graph.Table("dbo", "Permiso_History"),
|
|
|
|
|
new Respawn.Graph.Table("dbo", "RolPermiso_History"),
|
2026-04-16 19:04:06 -03:00
|
|
|
// ADM-001 (V011): Medio + Seccion are temporal — history tables cannot be directly deleted.
|
|
|
|
|
new Respawn.Graph.Table("dbo", "Medio_History"),
|
|
|
|
|
new Respawn.Graph.Table("dbo", "Seccion_History"),
|
fix(adm-008): correcciones del verify loop
Seis ajustes post-verify detectados durante la corrida full de tests:
1. PuntoDeVentaRepository: UQ_PuntoDeVenta_Medio_AFIP (no _MedioId_NumeroAFIP)
— el catch de unique violation no disparaba → 500 en race duplicado.
2. Application.DependencyInjection: registro de 8 handlers PuntosDeVenta
— sin esto, dispatcher arrojaba "No service registered" → 500.
3. ReservarNumeroCommandHandler: backoff ampliado a 5 retries
[25, 75, 200, 500, 1200]ms para soportar 50 threads concurrentes.
4. SecuenciaComprobante: SYSTEM_VERSIONING = OFF (AD8 revisitado).
Under UPDATE concurrente sobre misma fila, el engine arroja
"transaction time earlier than period start time" — limitación
conocida de Temporal Tables con alta contención de UPDATEs.
Decisión: secuencia es operacional, no configuración → sin history.
V013 y SqlTestFixture actualizados para ser idempotentes.
5. SqlTestFixture: EnsureV013SchemaAsync idempotente + PuntoDeVenta_History
en TablesToIgnore + permiso administracion:puntos_de_venta:gestionar
en seed canónico + asignación a rol admin.
6. Tests: conteos 22→23 permisos (V013 agrega uno); repository fixtures
ignoran PuntoDeVenta_History; test UpdatePdv_WhenPdvInactive eliminado
(over-specified — spec no bloquea update en PdV inactivo, solo en Medio
padre inactivo; alineado con frontend que permite editar PdV inactivo).
Resultado: 190/190 Api.Tests y tests específicos ADM-008 verdes
(Domain 13, Application 42, Api 21 = 76 tests nuevos). El único failure
residual (AuditEventRepositoryTests.QueryAsync_Limit_EmitsCursor) es
pre-existente y no relacionado a ADM-008.
Covers: verify report CRITICAL (UQ name mismatch) + WARNINGs descubiertos
durante la ejecución (DI registro, temporal tables concurrency, permiso
fixture, counts de tests pre-existentes).
2026-04-17 13:02:35 -03:00
|
|
|
// ADM-008 (V013): PuntoDeVenta is temporal; SecuenciaComprobante is NOT temporal (AD8 revisitado).
|
|
|
|
|
new Respawn.Graph.Table("dbo", "PuntoDeVenta_History"),
|
2026-04-17 17:41:30 -03:00
|
|
|
// ADM-009 (V014): TipoDeIva + IngresosBrutos son temporales.
|
|
|
|
|
new Respawn.Graph.Table("dbo", "TipoDeIva_History"),
|
|
|
|
|
new Respawn.Graph.Table("dbo", "IngresosBrutos_History"),
|
|
|
|
|
new Respawn.Graph.Table("dbo", "TipoDeIva"),
|
|
|
|
|
new Respawn.Graph.Table("dbo", "IngresosBrutos"),
|
2026-04-18 19:48:33 -03:00
|
|
|
// CAT-001 (V016): Rubro es temporal — history no puede deletearse directo.
|
|
|
|
|
new Respawn.Graph.Table("dbo", "Rubro_History"),
|
2026-04-15 15:39:25 -03:00
|
|
|
]
|
2026-04-13 21:36:09 -03:00
|
|
|
});
|
|
|
|
|
|
2026-04-15 12:31:29 -03:00
|
|
|
// Reset DB, re-seed Rol canonical table (lookup) and admin user for each test class run.
|
2026-04-13 21:36:09 -03:00
|
|
|
await _respawner.ResetAsync(_connection);
|
2026-04-15 12:31:29 -03:00
|
|
|
await SeedRolCanonicalAsync();
|
2026-04-13 21:36:09 -03:00
|
|
|
await SeedAdminAsync();
|
|
|
|
|
|
|
|
|
|
var factory = new SqlConnectionFactory(ConnectionString);
|
|
|
|
|
_repository = new UsuarioRepository(factory);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async Task DisposeAsync()
|
|
|
|
|
{
|
|
|
|
|
await _respawner.ResetAsync(_connection);
|
|
|
|
|
await _connection.CloseAsync();
|
|
|
|
|
await _connection.DisposeAsync();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Scenario: GetByUsername returns correct entity when user exists
|
|
|
|
|
[Fact]
|
|
|
|
|
public async Task GetByUsernameAsync_ExistingUser_ReturnsUsuario()
|
|
|
|
|
{
|
|
|
|
|
var usuario = await _repository.GetByUsernameAsync("admin");
|
|
|
|
|
|
|
|
|
|
Assert.NotNull(usuario);
|
|
|
|
|
Assert.Equal("admin", usuario.Username);
|
|
|
|
|
Assert.Equal("admin", usuario.Rol);
|
|
|
|
|
Assert.True(usuario.Activo);
|
|
|
|
|
Assert.False(string.IsNullOrWhiteSpace(usuario.PasswordHash));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Triangulation: GetByUsername returns null when user does not exist
|
|
|
|
|
[Fact]
|
|
|
|
|
public async Task GetByUsernameAsync_NonExistentUser_ReturnsNull()
|
|
|
|
|
{
|
|
|
|
|
var usuario = await _repository.GetByUsernameAsync("noexiste");
|
|
|
|
|
Assert.Null(usuario);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Triangulation: case-sensitive username lookup (SQL Server UNIQUE constraint is case-insensitive by default)
|
|
|
|
|
[Fact]
|
2026-04-15 12:31:29 -03:00
|
|
|
public async Task GetByUsernameAsync_DifferentUser_ReturnsCorrectUser_Cajero()
|
2026-04-13 21:36:09 -03:00
|
|
|
{
|
2026-04-15 12:31:29 -03:00
|
|
|
// Insert a second user with canonical rol 'cajero' (post-UDT-004 FK requires Rol.Codigo to exist).
|
2026-04-13 21:36:09 -03:00
|
|
|
await _connection.ExecuteAsync(
|
|
|
|
|
"INSERT INTO dbo.Usuario (Username, PasswordHash, Nombre, Apellido, Rol, PermisosJson) " +
|
2026-04-15 12:31:29 -03:00
|
|
|
"VALUES ('cajero1', '$2a$12$hash2', 'Juan', 'Pérez', 'cajero', '[]')");
|
2026-04-13 21:36:09 -03:00
|
|
|
|
|
|
|
|
var admin = await _repository.GetByUsernameAsync("admin");
|
2026-04-15 12:31:29 -03:00
|
|
|
var cajero = await _repository.GetByUsernameAsync("cajero1");
|
2026-04-13 21:36:09 -03:00
|
|
|
|
|
|
|
|
Assert.NotNull(admin);
|
2026-04-15 12:31:29 -03:00
|
|
|
Assert.NotNull(cajero);
|
|
|
|
|
Assert.NotEqual(admin.Id, cajero.Id);
|
2026-04-13 21:36:09 -03:00
|
|
|
Assert.Equal("admin", admin.Rol);
|
2026-04-15 12:31:29 -03:00
|
|
|
Assert.Equal("cajero", cajero.Rol);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async Task SeedRolCanonicalAsync()
|
|
|
|
|
{
|
|
|
|
|
const string sql = """
|
|
|
|
|
SET QUOTED_IDENTIFIER ON;
|
|
|
|
|
MERGE dbo.Rol AS t
|
|
|
|
|
USING (VALUES
|
|
|
|
|
('admin', N'Administrador', N'Supervisor total'),
|
|
|
|
|
('cajero', N'Cajero', N'Mostrador contado'),
|
|
|
|
|
('operador_ctacte', N'Operador Cta Cte', N'Cuenta corriente'),
|
|
|
|
|
('picadora', N'Picadora/Correctora', N'Edición de textos'),
|
|
|
|
|
('jefe_publicidad', N'Jefe de Publicidad', N'Supervisión de pauta'),
|
|
|
|
|
('productor', N'Productor', N'Carga restringida'),
|
|
|
|
|
('diagramacion', N'Diagramación/Taller', N'Solo lectura pauta'),
|
|
|
|
|
('reportes', N'Reportes', N'Solo lectura reportes')
|
|
|
|
|
) AS s (Codigo, Nombre, Descripcion)
|
|
|
|
|
ON t.Codigo = s.Codigo
|
|
|
|
|
WHEN NOT MATCHED BY TARGET THEN
|
|
|
|
|
INSERT (Codigo, Nombre, Descripcion, Activo)
|
|
|
|
|
VALUES (s.Codigo, s.Nombre, s.Descripcion, 1);
|
|
|
|
|
""";
|
|
|
|
|
await _connection.ExecuteAsync(sql);
|
2026-04-13 21:36:09 -03:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async Task SeedAdminAsync()
|
|
|
|
|
{
|
|
|
|
|
await _connection.ExecuteAsync(
|
|
|
|
|
"SET QUOTED_IDENTIFIER ON; " +
|
|
|
|
|
"IF NOT EXISTS (SELECT 1 FROM dbo.Usuario WHERE Username = 'admin') " +
|
|
|
|
|
"INSERT INTO dbo.Usuario (Username, PasswordHash, Nombre, Apellido, Rol, PermisosJson, Activo) " +
|
|
|
|
|
"VALUES ('admin', '$2a$12$rmq6tlSAQ8WXhR2CwLCSeuwCJKz/.8Eab95UQCUNfwe4dokeOqMcW', " +
|
|
|
|
|
"'Administrador', 'Sistema', 'admin', '[\"*\"]', 1)");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Dapper extension helper for IDbConnection
|
|
|
|
|
file static class DapperHelper
|
|
|
|
|
{
|
|
|
|
|
public static async Task ExecuteAsync(this SqlConnection conn, string sql)
|
|
|
|
|
{
|
|
|
|
|
using var cmd = conn.CreateCommand();
|
|
|
|
|
cmd.CommandText = sql;
|
|
|
|
|
await cmd.ExecuteNonQueryAsync();
|
|
|
|
|
}
|
|
|
|
|
}
|