67 lines
1.8 KiB
C#
67 lines
1.8 KiB
C#
|
|
using Dapper;
|
||
|
|
using Microsoft.Data.SqlClient;
|
||
|
|
using Respawn;
|
||
|
|
using Xunit;
|
||
|
|
|
||
|
|
namespace SIGCM2.TestSupport;
|
||
|
|
|
||
|
|
/// <summary>
|
||
|
|
/// Manages a real SQL Server test database.
|
||
|
|
/// Resets state between test runs using Respawn.
|
||
|
|
/// Seeds the admin user after each reset.
|
||
|
|
/// </summary>
|
||
|
|
public sealed class SqlTestFixture : IAsyncLifetime
|
||
|
|
{
|
||
|
|
private readonly string _connectionString;
|
||
|
|
private SqlConnection _connection = null!;
|
||
|
|
private Respawner _respawner = null!;
|
||
|
|
|
||
|
|
public SqlTestFixture(string connectionString)
|
||
|
|
{
|
||
|
|
_connectionString = connectionString;
|
||
|
|
}
|
||
|
|
|
||
|
|
public async Task InitializeAsync()
|
||
|
|
{
|
||
|
|
_connection = new SqlConnection(_connectionString);
|
||
|
|
await _connection.OpenAsync();
|
||
|
|
|
||
|
|
_respawner = await Respawner.CreateAsync(_connection, new RespawnerOptions
|
||
|
|
{
|
||
|
|
DbAdapter = DbAdapter.SqlServer
|
||
|
|
});
|
||
|
|
|
||
|
|
await ResetAndSeedAsync();
|
||
|
|
}
|
||
|
|
|
||
|
|
public async Task ResetAndSeedAsync()
|
||
|
|
{
|
||
|
|
await _respawner.ResetAsync(_connection);
|
||
|
|
await SeedAdminAsync();
|
||
|
|
}
|
||
|
|
|
||
|
|
public async Task DisposeAsync()
|
||
|
|
{
|
||
|
|
if (_connection is not null)
|
||
|
|
{
|
||
|
|
await _connection.CloseAsync();
|
||
|
|
await _connection.DisposeAsync();
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
private async Task SeedAdminAsync()
|
||
|
|
{
|
||
|
|
const string sql = """
|
||
|
|
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
|
||
|
|
);
|
||
|
|
""";
|
||
|
|
await _connection.ExecuteAsync(sql);
|
||
|
|
}
|
||
|
|
}
|