IdentityShroud/IdentityShroud.Core.Tests/Fixtures/DbFixture.cs

70 lines
2.1 KiB
C#
Raw Normal View History

using DotNet.Testcontainers.Containers;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Npgsql;
using Testcontainers.PostgreSql;
namespace IdentityShroud.Core.Tests.Fixtures;
public class DbFixture : IAsyncLifetime
{
private readonly IContainer _postgresqlServer;
private string ConnectionString =>
$"Host={_postgresqlServer.Hostname};" +
$"Port={DbPort};" +
$"Username={Username};Password={Password}";
private string Username => "postgres";
private string Password => "password";
private string DbHostname => _postgresqlServer.Hostname;
private int DbPort => _postgresqlServer.GetMappedPublicPort(PostgreSqlBuilder.PostgreSqlPort);
public Db CreateDbContext(string dbName)
{
var db = new Db(Options.Create<DbConfiguration>(new()
{
ConnectionString = ConnectionString + ";Database=" + dbName,
LogSensitiveData = false,
}), new NullLoggerFactory());
return db;
}
public DbFixture()
{
_postgresqlServer = new PostgreSqlBuilder("postgres:18.1")
.WithName("KMS-Test-Infra-" + Guid.NewGuid().ToString("D"))
.WithPassword(Password)
.Build();
}
public async ValueTask DisposeAsync()
{
await _postgresqlServer.StopAsync();
}
public async ValueTask InitializeAsync()
{
await _postgresqlServer.StartAsync();
}
public NpgsqlConnection GetConnection(string dbname)
{
string connString = ConnectionString
+ $";Database={dbname}";
var connection = new NpgsqlConnection(connString);
connection.Open();
return connection;
}
}
/*
[CollectionDefinition("PostgresqlFixtureCollection", DisableParallelization = false)]
public class PostgresqlFactoryCollection : ICollectionFixture<PostgresqlFixture>
{
// This class has no code, and is never created. Its purpose is simply
// to be the place to apply [CollectionDefinition] and all the
// ICollectionFixture<> interfaces.
}
*/